HttpRequest.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. //
  2. // Copyright (c) 2008-2013 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 "HttpRequest.h"
  24. #include "Log.h"
  25. #include "Profiler.h"
  26. #include "StringUtils.h"
  27. #include "Timer.h"
  28. #include <civetweb.h>
  29. #include "DebugNew.h"
  30. namespace Urho3D
  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. LOGDEBUG("HTTP " + verb_ + " request to URL " + url_);
  49. // Start the worker thread to actually create the connection and read the response data.
  50. Run();
  51. }
  52. HttpRequest::~HttpRequest()
  53. {
  54. Stop();
  55. }
  56. void HttpRequest::ThreadFunction()
  57. {
  58. String protocol = "http";
  59. String host;
  60. String path = "/";
  61. int port = 80;
  62. unsigned protocolEnd = url_.Find("://");
  63. if (protocolEnd != String::NPOS)
  64. {
  65. protocol = url_.Substring(0, protocolEnd);
  66. host = url_.Substring(protocolEnd + 3);
  67. }
  68. else
  69. host = url_;
  70. unsigned pathStart = host.Find('/');
  71. if (pathStart != String::NPOS)
  72. {
  73. path = host.Substring(pathStart);
  74. host = host.Substring(0, pathStart);
  75. }
  76. unsigned portStart = host.Find(':');
  77. if (portStart != String::NPOS)
  78. {
  79. port = ToInt(host.Substring(portStart + 1));
  80. host = host.Substring(0, portStart);
  81. }
  82. char errorBuffer[ERROR_BUFFER_SIZE];
  83. memset(errorBuffer, 0, sizeof(errorBuffer));
  84. String headersStr;
  85. for (unsigned i = 0; i < headers_.Size(); ++i)
  86. {
  87. // Trim and only add non-empty header strings
  88. String header = headers_[i].Trimmed();
  89. if (header.Length())
  90. headersStr += header + "\r\n";
  91. }
  92. // Initiate the connection. This may block due to DNS query
  93. /// \todo SSL mode will not actually work unless Civetweb's SSL mode is initialized with an external SSL DLL
  94. mg_connection* connection = 0;
  95. if (postData_.Empty())
  96. {
  97. connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer),
  98. "%s %s HTTP/1.0\r\n"
  99. "Host: %s\r\n"
  100. "%s"
  101. "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString());
  102. }
  103. else
  104. {
  105. connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer),
  106. "%s %s HTTP/1.0\r\n"
  107. "Host: %s\r\n"
  108. "%s"
  109. "Content-Length: %d\r\n"
  110. "\r\n"
  111. "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString());
  112. }
  113. {
  114. MutexLock lock(mutex_);
  115. state_ = connection ? HTTP_OPEN : HTTP_ERROR;
  116. // If no connection could be made, store the error and exit
  117. if (state_ == HTTP_ERROR)
  118. {
  119. error_ = String(&errorBuffer[0]);
  120. return;
  121. }
  122. }
  123. // Loop while should run, read data from the connection, copy to the main thread buffer if there is space
  124. while (shouldRun_)
  125. {
  126. // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block
  127. int bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4);
  128. if (bytesRead <= 0)
  129. break;
  130. mutex_.Acquire();
  131. // Wait until enough space in the main thread's ring buffer
  132. for (;;)
  133. {
  134. unsigned spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1));
  135. if ((int)spaceInBuffer > bytesRead || !shouldRun_)
  136. break;
  137. mutex_.Release();
  138. Time::Sleep(5);
  139. mutex_.Acquire();
  140. }
  141. if (!shouldRun_)
  142. {
  143. mutex_.Release();
  144. break;
  145. }
  146. if (writePosition_ + bytesRead <= READ_BUFFER_SIZE)
  147. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), bytesRead);
  148. else
  149. {
  150. // Handle ring buffer wrap
  151. unsigned part1 = READ_BUFFER_SIZE - writePosition_;
  152. unsigned part2 = bytesRead - part1;
  153. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1);
  154. memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2);
  155. }
  156. writePosition_ += bytesRead;
  157. writePosition_ &= READ_BUFFER_SIZE - 1;
  158. mutex_.Release();
  159. }
  160. // Close the connection
  161. mg_close_connection(connection);
  162. {
  163. MutexLock lock(mutex_);
  164. state_ = HTTP_CLOSED;
  165. }
  166. }
  167. unsigned HttpRequest::Read(void* dest, unsigned size)
  168. {
  169. mutex_.Acquire();
  170. unsigned char* destPtr = (unsigned char*)dest;
  171. unsigned bytesAvailable = (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  172. if (size > bytesAvailable)
  173. size = bytesAvailable;
  174. if (size)
  175. {
  176. if (readPosition_ + size <= READ_BUFFER_SIZE)
  177. memcpy(destPtr, readBuffer_.Get() + readPosition_, size);
  178. else
  179. {
  180. // Handle ring buffer wrap
  181. unsigned part1 = READ_BUFFER_SIZE - readPosition_;
  182. unsigned part2 = size - part1;
  183. memcpy(destPtr, readBuffer_.Get() + readPosition_, part1);
  184. memcpy(destPtr + part1, readBuffer_.Get(), part2);
  185. }
  186. readPosition_ += size;
  187. readPosition_ &= READ_BUFFER_SIZE - 1;
  188. }
  189. // If connection has been closed and there is no more buffered data, we are at the end
  190. CheckEof();
  191. mutex_.Release();
  192. return size;
  193. }
  194. String HttpRequest::GetError() const
  195. {
  196. MutexLock lock(mutex_);
  197. const_cast<HttpRequest*>(this)->CheckEof();
  198. return error_;
  199. }
  200. HttpRequestState HttpRequest::GetState() const
  201. {
  202. MutexLock lock(mutex_);
  203. const_cast<HttpRequest*>(this)->CheckEof();
  204. return state_;
  205. }
  206. unsigned HttpRequest::GetAvailableSize() const
  207. {
  208. MutexLock lock(mutex_);
  209. const_cast<HttpRequest*>(this)->CheckEof();
  210. return (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  211. }
  212. void HttpRequest::CheckEof()
  213. {
  214. unsigned bytesAvailable = (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  215. if (state_ == HTTP_ERROR || (state_ == HTTP_CLOSED && !bytesAvailable))
  216. position_ = M_MAX_UNSIGNED;
  217. }
  218. }