HttpRequest.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Profiler.h"
  5. #include "../IO/Log.h"
  6. #include "../Network/HttpRequest.h"
  7. #include <Civetweb/civetweb.h>
  8. #include "../DebugNew.h"
  9. namespace Urho3D
  10. {
  11. static constexpr i32 ERROR_BUFFER_SIZE = 256;
  12. static constexpr i32 READ_BUFFER_SIZE = 65536; // Must be a power of two
  13. HttpRequest::HttpRequest(const String& url, const String& verb, const Vector<String>& headers, const String& postData) :
  14. url_(url.Trimmed()),
  15. verb_(!verb.Empty() ? verb : "GET"),
  16. headers_(headers),
  17. postData_(postData),
  18. state_(HTTP_INITIALIZING),
  19. httpReadBuffer_(new u8[READ_BUFFER_SIZE]),
  20. readBuffer_(new u8[READ_BUFFER_SIZE]),
  21. readPosition_(0),
  22. writePosition_(0)
  23. {
  24. // Size of response is unknown, so just set maximum value. The position will also be changed
  25. // to maximum value once the request is done, signaling end for Deserializer::IsEof().
  26. size_ = M_MAX_UNSIGNED;
  27. URHO3D_LOGDEBUG("HTTP " + verb_ + " request to URL " + url_);
  28. #ifdef URHO3D_SSL
  29. static bool sslInitialized = false;
  30. if (!sslInitialized)
  31. {
  32. mg_init_library(MG_FEATURES_TLS);
  33. sslInitialized = true;
  34. }
  35. #endif
  36. #ifdef URHO3D_THREADING
  37. // Start the worker thread to actually create the connection and read the response data.
  38. Run();
  39. #else
  40. URHO3D_LOGERROR("HTTP request will not execute as threading is disabled");
  41. #endif
  42. }
  43. HttpRequest::~HttpRequest()
  44. {
  45. Stop();
  46. }
  47. void HttpRequest::ThreadFunction()
  48. {
  49. URHO3D_PROFILE_THREAD("HttpRequest Thread");
  50. String protocol = "http";
  51. String host;
  52. String path = "/";
  53. int port = 80;
  54. i32 protocolEnd = url_.Find("://");
  55. if (protocolEnd != String::NPOS)
  56. {
  57. protocol = url_.Substring(0, protocolEnd);
  58. host = url_.Substring(protocolEnd + 3);
  59. }
  60. else
  61. host = url_;
  62. i32 pathStart = host.Find('/');
  63. if (pathStart != String::NPOS)
  64. {
  65. path = host.Substring(pathStart);
  66. host = host.Substring(0, pathStart);
  67. }
  68. i32 portStart = host.Find(':');
  69. if (portStart != String::NPOS)
  70. {
  71. port = ToI32(host.Substring(portStart + 1));
  72. host = host.Substring(0, portStart);
  73. } else if (protocol.Compare("https", false) >= 0)
  74. port = 443;
  75. char errorBuffer[ERROR_BUFFER_SIZE];
  76. memset(errorBuffer, 0, sizeof(errorBuffer));
  77. String headersStr;
  78. for (i32 i = 0; i < headers_.Size(); ++i)
  79. {
  80. // Trim and only add non-empty header strings
  81. String header = headers_[i].Trimmed();
  82. if (header.Length())
  83. headersStr += header + "\r\n";
  84. }
  85. // Initiate the connection. This may block due to DNS query
  86. mg_connection* connection = nullptr;
  87. if (postData_.Empty())
  88. {
  89. connection = mg_download(host.CString(), port, protocol.Compare("https", false) >= 0 ? 1 : 0, errorBuffer, sizeof(errorBuffer),
  90. "%s %s HTTP/1.0\r\n"
  91. "Host: %s\r\n"
  92. "%s"
  93. "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString());
  94. }
  95. else
  96. {
  97. connection = mg_download(host.CString(), port, protocol.Compare("https", false) >= 0 ? 1 : 0, errorBuffer, sizeof(errorBuffer),
  98. "%s %s HTTP/1.0\r\n"
  99. "Host: %s\r\n"
  100. "%s"
  101. "Content-Length: %d\r\n"
  102. "\r\n"
  103. "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString());
  104. }
  105. {
  106. MutexLock lock(mutex_);
  107. state_ = connection ? HTTP_OPEN : HTTP_ERROR;
  108. // If no connection could be made, store the error and exit
  109. if (state_ == HTTP_ERROR)
  110. {
  111. error_ = String(&errorBuffer[0]);
  112. return;
  113. }
  114. }
  115. // Loop while should run, read data from the connection, copy to the main thread buffer if there is space
  116. while (shouldRun_)
  117. {
  118. // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block
  119. i32 bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4);
  120. if (bytesRead <= 0)
  121. break;
  122. mutex_.Acquire();
  123. // Wait until enough space in the main thread's ring buffer
  124. for (;;)
  125. {
  126. i32 spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1));
  127. if (spaceInBuffer > bytesRead || !shouldRun_)
  128. break;
  129. mutex_.Release();
  130. Time::Sleep(5);
  131. mutex_.Acquire();
  132. }
  133. if (!shouldRun_)
  134. {
  135. mutex_.Release();
  136. break;
  137. }
  138. if (writePosition_ + bytesRead <= READ_BUFFER_SIZE)
  139. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), (size_t)bytesRead);
  140. else
  141. {
  142. // Handle ring buffer wrap
  143. i32 part1 = READ_BUFFER_SIZE - writePosition_;
  144. i32 part2 = bytesRead - part1;
  145. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1);
  146. memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2);
  147. }
  148. writePosition_ += bytesRead;
  149. writePosition_ &= READ_BUFFER_SIZE - 1;
  150. mutex_.Release();
  151. }
  152. // Close the connection
  153. mg_close_connection(connection);
  154. {
  155. MutexLock lock(mutex_);
  156. state_ = HTTP_CLOSED;
  157. }
  158. }
  159. i32 HttpRequest::Read(void* dest, i32 size)
  160. {
  161. assert(size >= 0);
  162. #ifdef URHO3D_THREADING
  163. mutex_.Acquire();
  164. u8* destPtr = (u8*)dest;
  165. i32 sizeLeft = size;
  166. i32 totalRead = 0;
  167. for (;;)
  168. {
  169. Pair<i32, bool> status{};
  170. for (;;)
  171. {
  172. status = CheckAvailableSizeAndEof();
  173. if (status.first_ || status.second_)
  174. break;
  175. // While no bytes and connection is still open, block until has some data
  176. mutex_.Release();
  177. Time::Sleep(5);
  178. mutex_.Acquire();
  179. }
  180. i32 bytesAvailable = status.first_;
  181. if (bytesAvailable)
  182. {
  183. if (bytesAvailable > sizeLeft)
  184. bytesAvailable = sizeLeft;
  185. if (readPosition_ + bytesAvailable <= READ_BUFFER_SIZE)
  186. memcpy(destPtr, readBuffer_.Get() + readPosition_, bytesAvailable);
  187. else
  188. {
  189. // Handle ring buffer wrap
  190. i32 part1 = READ_BUFFER_SIZE - readPosition_;
  191. i32 part2 = bytesAvailable - part1;
  192. memcpy(destPtr, readBuffer_.Get() + readPosition_, part1);
  193. memcpy(destPtr + part1, readBuffer_.Get(), part2);
  194. }
  195. readPosition_ += bytesAvailable;
  196. readPosition_ &= READ_BUFFER_SIZE - 1;
  197. sizeLeft -= bytesAvailable;
  198. totalRead += bytesAvailable;
  199. destPtr += bytesAvailable;
  200. }
  201. if (!sizeLeft || !bytesAvailable)
  202. break;
  203. }
  204. mutex_.Release();
  205. return totalRead;
  206. #else
  207. // Threading disabled, nothing to read
  208. return 0;
  209. #endif
  210. }
  211. i64 HttpRequest::Seek(i64 position)
  212. {
  213. return 0;
  214. }
  215. bool HttpRequest::IsEof() const
  216. {
  217. MutexLock lock(mutex_);
  218. return CheckAvailableSizeAndEof().second_;
  219. }
  220. String HttpRequest::GetError() const
  221. {
  222. MutexLock lock(mutex_);
  223. return error_;
  224. }
  225. HttpRequestState HttpRequest::GetState() const
  226. {
  227. MutexLock lock(mutex_);
  228. return state_;
  229. }
  230. i32 HttpRequest::GetAvailableSize() const
  231. {
  232. MutexLock lock(mutex_);
  233. return CheckAvailableSizeAndEof().first_;
  234. }
  235. Pair<i32, bool> HttpRequest::CheckAvailableSizeAndEof() const
  236. {
  237. i32 size = (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  238. return {size, (state_ == HTTP_ERROR || (state_ == HTTP_CLOSED && !size))};
  239. }
  240. }