HttpRequest.cpp 9.0 KB

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