HttpRequest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. #include <emscripten/bind.h>
  29. #else
  30. #include <Civetweb/civetweb.h>
  31. #endif
  32. #include "../DebugNew.h"
  33. namespace Urho3D
  34. {
  35. static const unsigned ERROR_BUFFER_SIZE = 256;
  36. static const unsigned READ_BUFFER_SIZE = 65536; // Must be a power of two
  37. HttpRequest::HttpRequest(const String& url, const String& verb, const Vector<String>& headers, const String& postData) :
  38. url_(url.Trimmed()),
  39. verb_(!verb.Empty() ? verb : "GET"),
  40. headers_(headers),
  41. postData_(postData),
  42. state_(HTTP_INITIALIZING),
  43. httpReadBuffer_(new unsigned char[READ_BUFFER_SIZE]),
  44. readBuffer_(new unsigned char[READ_BUFFER_SIZE]),
  45. readPosition_(0),
  46. writePosition_(0)
  47. {
  48. // Size of response is unknown, so just set maximum value. The position will also be changed
  49. // to maximum value once the request is done, signaling end for Deserializer::IsEof().
  50. size_ = M_MAX_UNSIGNED;
  51. URHO3D_LOGDEBUG("HTTP " + verb_ + " request to URL " + url_);
  52. #ifdef URHO3D_SSL
  53. static bool sslInitialized = false;
  54. if (!sslInitialized)
  55. {
  56. mg_init_library(MG_FEATURES_TLS);
  57. sslInitialized = true;
  58. }
  59. #endif
  60. #if defined(__EMSCRIPTEN__)
  61. EM_ASM({
  62. let url = UTF8ToString($0);
  63. let handler = $1;
  64. fetch(url)
  65. .then(response => response.arrayBuffer())
  66. .then(data => {
  67. // Copy data to Emscripten heap (directly accessed from Module.HEAPU8)
  68. const nDataBytes = data.byteLength;
  69. const dataPtr = Module._malloc(nDataBytes);
  70. const dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);
  71. dataHeap.set(new Uint8Array(data));
  72. if (Module.JSResponse) {
  73. Module.JSResponse(handler, dataHeap.byteOffset, nDataBytes);
  74. } else {
  75. console.error('Module.JSResponse() methoddoes not exist');
  76. }
  77. Module._free(dataHeap.byteOffset);
  78. });
  79. }, url.CString(), this);
  80. #elif defined(URHO3D_THREADING)
  81. // Start the worker thread to actually create the connection and read the response data.
  82. Run();
  83. #else
  84. URHO3D_LOGERROR("HTTP request will not execute as threading is disabled");
  85. #endif
  86. }
  87. #ifdef __EMSCRIPTEN__
  88. void JSResponse(intptr_t requester, intptr_t data, int length)
  89. {
  90. auto handler = reinterpret_cast<HttpRequest*>(requester);
  91. if (handler) {
  92. MutexLock lock(handler->mutex_);
  93. memcpy(handler->readBuffer_.Get(), reinterpret_cast<void*>(data), (size_t)length);
  94. handler->writePosition_ = length;
  95. handler->writePosition_ &= READ_BUFFER_SIZE - 1;
  96. handler->state_ = HTTP_CLOSED;
  97. }
  98. }
  99. using namespace emscripten;
  100. EMSCRIPTEN_BINDINGS(HttpRequestHandler) {
  101. function("JSResponse", &JSResponse);
  102. }
  103. #endif
  104. HttpRequest::~HttpRequest()
  105. {
  106. Stop();
  107. }
  108. void HttpRequest::ThreadFunction()
  109. {
  110. String protocol = "http";
  111. String host;
  112. String path = "/";
  113. int port = 80;
  114. unsigned protocolEnd = url_.Find("://");
  115. if (protocolEnd != String::NPOS)
  116. {
  117. protocol = url_.Substring(0, protocolEnd);
  118. host = url_.Substring(protocolEnd + 3);
  119. }
  120. else
  121. host = url_;
  122. unsigned pathStart = host.Find('/');
  123. if (pathStart != String::NPOS)
  124. {
  125. path = host.Substring(pathStart);
  126. host = host.Substring(0, pathStart);
  127. }
  128. unsigned portStart = host.Find(':');
  129. if (portStart != String::NPOS)
  130. {
  131. port = ToInt(host.Substring(portStart + 1));
  132. host = host.Substring(0, portStart);
  133. } else if (protocol.Compare("https", false) >= 0)
  134. port = 443;
  135. char errorBuffer[ERROR_BUFFER_SIZE];
  136. memset(errorBuffer, 0, sizeof(errorBuffer));
  137. String headersStr;
  138. for (unsigned i = 0; i < headers_.Size(); ++i)
  139. {
  140. // Trim and only add non-empty header strings
  141. String header = headers_[i].Trimmed();
  142. if (header.Length())
  143. headersStr += header + "\r\n";
  144. }
  145. #ifndef __EMSCRIPTEN__
  146. // Initiate the connection. This may block due to DNS query
  147. mg_connection* connection = nullptr;
  148. if (postData_.Empty())
  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. "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString());
  155. }
  156. else
  157. {
  158. connection = mg_download(host.CString(), port, protocol.Compare("https", false) >= 0 ? 1 : 0, errorBuffer, sizeof(errorBuffer),
  159. "%s %s HTTP/1.0\r\n"
  160. "Host: %s\r\n"
  161. "%s"
  162. "Content-Length: %d\r\n"
  163. "\r\n"
  164. "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString());
  165. }
  166. {
  167. MutexLock lock(mutex_);
  168. state_ = connection ? HTTP_OPEN : HTTP_ERROR;
  169. // If no connection could be made, store the error and exit
  170. if (state_ == HTTP_ERROR)
  171. {
  172. error_ = String(&errorBuffer[0]);
  173. return;
  174. }
  175. }
  176. // Loop while should run, read data from the connection, copy to the main thread buffer if there is space
  177. while (shouldRun_)
  178. {
  179. // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block
  180. int bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4);
  181. if (bytesRead <= 0)
  182. break;
  183. mutex_.Acquire();
  184. // Wait until enough space in the main thread's ring buffer
  185. for (;;)
  186. {
  187. unsigned spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1));
  188. if ((int)spaceInBuffer > bytesRead || !shouldRun_)
  189. break;
  190. mutex_.Release();
  191. Time::Sleep(5);
  192. mutex_.Acquire();
  193. }
  194. if (!shouldRun_)
  195. {
  196. mutex_.Release();
  197. break;
  198. }
  199. if (writePosition_ + bytesRead <= READ_BUFFER_SIZE)
  200. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), (size_t)bytesRead);
  201. else
  202. {
  203. // Handle ring buffer wrap
  204. unsigned part1 = READ_BUFFER_SIZE - writePosition_;
  205. unsigned part2 = bytesRead - part1;
  206. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1);
  207. memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2);
  208. }
  209. writePosition_ += bytesRead;
  210. writePosition_ &= READ_BUFFER_SIZE - 1;
  211. mutex_.Release();
  212. }
  213. // Close the connection
  214. mg_close_connection(connection);
  215. #endif
  216. {
  217. MutexLock lock(mutex_);
  218. state_ = HTTP_CLOSED;
  219. }
  220. }
  221. unsigned HttpRequest::Read(void* dest, unsigned size)
  222. {
  223. #if defined(URHO3D_THREADING) || defined(__EMSCRIPTEN__)
  224. mutex_.Acquire();
  225. auto* destPtr = (unsigned char*)dest;
  226. unsigned sizeLeft = size;
  227. unsigned totalRead = 0;
  228. for (;;)
  229. {
  230. Pair<unsigned, bool> status{};
  231. for (;;)
  232. {
  233. status = CheckAvailableSizeAndEof();
  234. if (status.first_ || status.second_)
  235. break;
  236. // While no bytes and connection is still open, block until has some data
  237. mutex_.Release();
  238. Time::Sleep(5);
  239. mutex_.Acquire();
  240. }
  241. unsigned bytesAvailable = status.first_;
  242. if (bytesAvailable)
  243. {
  244. if (bytesAvailable > sizeLeft)
  245. bytesAvailable = sizeLeft;
  246. if (readPosition_ + bytesAvailable <= READ_BUFFER_SIZE)
  247. memcpy(destPtr, readBuffer_.Get() + readPosition_, bytesAvailable);
  248. else
  249. {
  250. // Handle ring buffer wrap
  251. unsigned part1 = READ_BUFFER_SIZE - readPosition_;
  252. unsigned part2 = bytesAvailable - part1;
  253. memcpy(destPtr, readBuffer_.Get() + readPosition_, part1);
  254. memcpy(destPtr + part1, readBuffer_.Get(), part2);
  255. }
  256. readPosition_ += bytesAvailable;
  257. readPosition_ &= READ_BUFFER_SIZE - 1;
  258. sizeLeft -= bytesAvailable;
  259. totalRead += bytesAvailable;
  260. destPtr += bytesAvailable;
  261. }
  262. if (!sizeLeft || !bytesAvailable)
  263. break;
  264. }
  265. mutex_.Release();
  266. return totalRead;
  267. #else
  268. // Threading disabled, nothing to read
  269. return 0;
  270. #endif
  271. }
  272. unsigned HttpRequest::Seek(unsigned position)
  273. {
  274. return 0;
  275. }
  276. bool HttpRequest::IsEof() const
  277. {
  278. MutexLock lock(mutex_);
  279. return CheckAvailableSizeAndEof().second_;
  280. }
  281. String HttpRequest::GetError() const
  282. {
  283. MutexLock lock(mutex_);
  284. return error_;
  285. }
  286. HttpRequestState HttpRequest::GetState() const
  287. {
  288. MutexLock lock(mutex_);
  289. return state_;
  290. }
  291. unsigned HttpRequest::GetAvailableSize() const
  292. {
  293. MutexLock lock(mutex_);
  294. return CheckAvailableSizeAndEof().first_;
  295. }
  296. Pair<unsigned, bool> HttpRequest::CheckAvailableSizeAndEof() const
  297. {
  298. unsigned size = (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  299. return {size, (state_ == HTTP_ERROR || (state_ == HTTP_CLOSED && !size))};
  300. }
  301. }