HttpRequest.cpp 9.1 KB

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