HttpRequest.cpp 9.0 KB

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