HttpRequest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Profiler.h"
  24. #include "../IO/Log.h"
  25. #include "../Network/HttpRequest.h"
  26. #ifdef __EMSCRIPTEN__
  27. #include <emscripten.h>
  28. #else
  29. #include <Civetweb/civetweb.h>
  30. #endif
  31. #include "../DebugNew.h"
  32. namespace Urho3D
  33. {
  34. static const unsigned ERROR_BUFFER_SIZE = 256;
  35. static const unsigned READ_BUFFER_SIZE = 65536; // Must be a power of two
  36. HttpRequest::HttpRequest(const String& url, const String& verb, const Vector<String>& headers, const String& postData) :
  37. url_(url.Trimmed()),
  38. verb_(!verb.Empty() ? verb : "GET"),
  39. headers_(headers),
  40. postData_(postData),
  41. state_(HTTP_INITIALIZING),
  42. httpReadBuffer_(new unsigned char[READ_BUFFER_SIZE]),
  43. readBuffer_(new unsigned char[READ_BUFFER_SIZE]),
  44. readPosition_(0),
  45. writePosition_(0)
  46. {
  47. // Size of response is unknown, so just set maximum value. The position will also be changed
  48. // to maximum value once the request is done, signaling end for Deserializer::IsEof().
  49. size_ = M_MAX_UNSIGNED;
  50. URHO3D_LOGDEBUG("HTTP " + verb_ + " request to URL " + url_);
  51. #ifdef URHO3D_SSL
  52. static bool sslInitialized = false;
  53. if (!sslInitialized)
  54. {
  55. mg_init_library(MG_FEATURES_TLS);
  56. sslInitialized = true;
  57. }
  58. #endif
  59. #ifdef URHO3D_THREADING
  60. // Start the worker thread to actually create the connection and read the response data.
  61. Run();
  62. #else
  63. URHO3D_LOGERROR("HTTP request will not execute as threading is disabled");
  64. #endif
  65. }
  66. HttpRequest::~HttpRequest()
  67. {
  68. Stop();
  69. }
  70. void HttpRequest::ThreadFunction()
  71. {
  72. String protocol = "http";
  73. String host;
  74. String path = "/";
  75. int port = 80;
  76. unsigned protocolEnd = url_.Find("://");
  77. if (protocolEnd != String::NPOS)
  78. {
  79. protocol = url_.Substring(0, protocolEnd);
  80. host = url_.Substring(protocolEnd + 3);
  81. }
  82. else
  83. host = url_;
  84. unsigned pathStart = host.Find('/');
  85. if (pathStart != String::NPOS)
  86. {
  87. path = host.Substring(pathStart);
  88. host = host.Substring(0, pathStart);
  89. }
  90. unsigned portStart = host.Find(':');
  91. if (portStart != String::NPOS)
  92. {
  93. port = ToInt(host.Substring(portStart + 1));
  94. host = host.Substring(0, portStart);
  95. } else if (protocol.Compare("https", false) >= 0)
  96. port = 443;
  97. char errorBuffer[ERROR_BUFFER_SIZE];
  98. memset(errorBuffer, 0, sizeof(errorBuffer));
  99. String headersStr;
  100. for (unsigned i = 0; i < headers_.Size(); ++i)
  101. {
  102. // Trim and only add non-empty header strings
  103. String header = headers_[i].Trimmed();
  104. if (header.Length())
  105. headersStr += header + "\r\n";
  106. }
  107. #ifdef __EMSCRIPTEN__
  108. EM_ASM({
  109. let protocol = UTF8ToString($0);
  110. let host = UTF8ToString($1);
  111. let port = $2;
  112. let path = UTF8ToString($3);
  113. console.log('Http request params:');
  114. console.log('protocol: ', protocol);
  115. console.log('host: ', host);
  116. console.log('port: ', port);
  117. console.log('path: ', path);
  118. let url = protocol + '://' + host + ':' + port + '/' + path;
  119. console.log('result: ', url);
  120. let response = await fetch(url);
  121. fetch(url)
  122. .then(response => response.arrayBuffer())
  123. .then(data => {
  124. // Copy data to Emscripten heap (directly accessed from Module.HEAPU8)
  125. const nDataBytes = data.length * data.BYTES_PER_ELEMENT
  126. const dataPtr = Module._malloc(nDataBytes)
  127. const dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes)
  128. dataHeap.set(new Uint8Array(data.buffer))
  129. // const float_multiply_array = Module.cwrap(
  130. // 'MultiplyArray', 'number', ['number', 'number', 'number']
  131. // );
  132. // Call function and get result
  133. //Module.MultiplyArray(2, dataHeap.byteOffset, data.length)
  134. Module._free(dataHeap.byteOffset)
  135. });
  136. }, protocol.CString(), host.CString(), port, path.CString());
  137. #else
  138. // Initiate the connection. This may block due to DNS query
  139. mg_connection* connection = nullptr;
  140. if (postData_.Empty())
  141. {
  142. connection = mg_download(host.CString(), port, protocol.Compare("https", false) >= 0 ? 1 : 0, errorBuffer, sizeof(errorBuffer),
  143. "%s %s HTTP/1.0\r\n"
  144. "Host: %s\r\n"
  145. "%s"
  146. "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString());
  147. }
  148. else
  149. {
  150. connection = mg_download(host.CString(), port, protocol.Compare("https", false) >= 0 ? 1 : 0, errorBuffer, sizeof(errorBuffer),
  151. "%s %s HTTP/1.0\r\n"
  152. "Host: %s\r\n"
  153. "%s"
  154. "Content-Length: %d\r\n"
  155. "\r\n"
  156. "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString());
  157. }
  158. {
  159. MutexLock lock(mutex_);
  160. state_ = connection ? HTTP_OPEN : HTTP_ERROR;
  161. // If no connection could be made, store the error and exit
  162. if (state_ == HTTP_ERROR)
  163. {
  164. error_ = String(&errorBuffer[0]);
  165. return;
  166. }
  167. }
  168. // Loop while should run, read data from the connection, copy to the main thread buffer if there is space
  169. while (shouldRun_)
  170. {
  171. // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block
  172. int bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4);
  173. if (bytesRead <= 0)
  174. break;
  175. mutex_.Acquire();
  176. // Wait until enough space in the main thread's ring buffer
  177. for (;;)
  178. {
  179. unsigned spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1));
  180. if ((int)spaceInBuffer > bytesRead || !shouldRun_)
  181. break;
  182. mutex_.Release();
  183. Time::Sleep(5);
  184. mutex_.Acquire();
  185. }
  186. if (!shouldRun_)
  187. {
  188. mutex_.Release();
  189. break;
  190. }
  191. if (writePosition_ + bytesRead <= READ_BUFFER_SIZE)
  192. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), (size_t)bytesRead);
  193. else
  194. {
  195. // Handle ring buffer wrap
  196. unsigned part1 = READ_BUFFER_SIZE - writePosition_;
  197. unsigned part2 = bytesRead - part1;
  198. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1);
  199. memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2);
  200. }
  201. writePosition_ += bytesRead;
  202. writePosition_ &= READ_BUFFER_SIZE - 1;
  203. mutex_.Release();
  204. }
  205. // Close the connection
  206. mg_close_connection(connection);
  207. #endif
  208. {
  209. MutexLock lock(mutex_);
  210. state_ = HTTP_CLOSED;
  211. }
  212. }
  213. unsigned HttpRequest::Read(void* dest, unsigned size)
  214. {
  215. #ifdef URHO3D_THREADING
  216. mutex_.Acquire();
  217. auto* destPtr = (unsigned char*)dest;
  218. unsigned sizeLeft = size;
  219. unsigned totalRead = 0;
  220. for (;;)
  221. {
  222. Pair<unsigned, bool> status{};
  223. for (;;)
  224. {
  225. status = CheckAvailableSizeAndEof();
  226. if (status.first_ || status.second_)
  227. break;
  228. // While no bytes and connection is still open, block until has some data
  229. mutex_.Release();
  230. Time::Sleep(5);
  231. mutex_.Acquire();
  232. }
  233. unsigned bytesAvailable = status.first_;
  234. if (bytesAvailable)
  235. {
  236. if (bytesAvailable > sizeLeft)
  237. bytesAvailable = sizeLeft;
  238. if (readPosition_ + bytesAvailable <= READ_BUFFER_SIZE)
  239. memcpy(destPtr, readBuffer_.Get() + readPosition_, bytesAvailable);
  240. else
  241. {
  242. // Handle ring buffer wrap
  243. unsigned part1 = READ_BUFFER_SIZE - readPosition_;
  244. unsigned part2 = bytesAvailable - part1;
  245. memcpy(destPtr, readBuffer_.Get() + readPosition_, part1);
  246. memcpy(destPtr + part1, readBuffer_.Get(), part2);
  247. }
  248. readPosition_ += bytesAvailable;
  249. readPosition_ &= READ_BUFFER_SIZE - 1;
  250. sizeLeft -= bytesAvailable;
  251. totalRead += bytesAvailable;
  252. destPtr += bytesAvailable;
  253. }
  254. if (!sizeLeft || !bytesAvailable)
  255. break;
  256. }
  257. mutex_.Release();
  258. return totalRead;
  259. #else
  260. // Threading disabled, nothing to read
  261. return 0;
  262. #endif
  263. }
  264. unsigned HttpRequest::Seek(unsigned position)
  265. {
  266. return 0;
  267. }
  268. bool HttpRequest::IsEof() const
  269. {
  270. MutexLock lock(mutex_);
  271. return CheckAvailableSizeAndEof().second_;
  272. }
  273. String HttpRequest::GetError() const
  274. {
  275. MutexLock lock(mutex_);
  276. return error_;
  277. }
  278. HttpRequestState HttpRequest::GetState() const
  279. {
  280. MutexLock lock(mutex_);
  281. return state_;
  282. }
  283. unsigned HttpRequest::GetAvailableSize() const
  284. {
  285. MutexLock lock(mutex_);
  286. return CheckAvailableSizeAndEof().first_;
  287. }
  288. Pair<unsigned, bool> HttpRequest::CheckAvailableSizeAndEof() const
  289. {
  290. unsigned size = (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  291. return {size, (state_ == HTTP_ERROR || (state_ == HTTP_CLOSED && !size))};
  292. }
  293. }