WebRequest.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. // Copyright (c) 2008-2015 the Urho3D project.
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "../Precompiled.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/Log.h"
  26. #include "../Web/WebRequest.h"
  27. #include "../DebugNew.h"
  28. // !!! WARNING! Use HttpRequest from Network if you don't want your interface
  29. // to change. This file mimics HttpRequest for now, but will be
  30. // changing, and it is here as a placeholder only!
  31. #ifdef EMSCRIPTEN
  32. // Add code to use an XMLHttpRequest or ActiveX XMLHttpRequest here.
  33. #else
  34. #include <Civetweb/include/civetweb.h>
  35. namespace Atomic
  36. {
  37. static const unsigned ERROR_BUFFER_SIZE = 256;
  38. static const unsigned READ_BUFFER_SIZE = 65536; // Must be a power of two
  39. WebRequest::WebRequest(const String& url, const String& verb, const Vector<String>& headers, const String& postData) :
  40. url_(url.Trimmed()),
  41. verb_(!verb.Empty() ? verb : "GET"),
  42. headers_(headers),
  43. postData_(postData),
  44. state_(HTTP_INITIALIZING),
  45. httpReadBuffer_(new unsigned char[READ_BUFFER_SIZE]),
  46. readBuffer_(new unsigned char[READ_BUFFER_SIZE]),
  47. readPosition_(0),
  48. writePosition_(0)
  49. {
  50. // Size of response is unknown, so just set maximum value. The position will also be changed
  51. // to maximum value once the request is done, signaling end for Deserializer::IsEof().
  52. size_ = M_MAX_UNSIGNED;
  53. LOGERROR("DO NOT USE WebRequest YET! Use the Network subsystem's HttpRequest. The WebRequest interface is under development and will change soon!");
  54. LOGDEBUG("HTTP " + verb_ + " request to URL " + url_);
  55. // Start the worker thread to actually create the connection and read the response data.
  56. Run();
  57. }
  58. WebRequest::~WebRequest()
  59. {
  60. Stop();
  61. }
  62. void WebRequest::ThreadFunction()
  63. {
  64. String protocol = "http";
  65. String host;
  66. String path = "/";
  67. int port = 80;
  68. unsigned protocolEnd = url_.Find("://");
  69. if (protocolEnd != String::NPOS)
  70. {
  71. protocol = url_.Substring(0, protocolEnd);
  72. host = url_.Substring(protocolEnd + 3);
  73. }
  74. else
  75. host = url_;
  76. unsigned pathStart = host.Find('/');
  77. if (pathStart != String::NPOS)
  78. {
  79. path = host.Substring(pathStart);
  80. host = host.Substring(0, pathStart);
  81. }
  82. unsigned portStart = host.Find(':');
  83. if (portStart != String::NPOS)
  84. {
  85. port = ToInt(host.Substring(portStart + 1));
  86. host = host.Substring(0, portStart);
  87. }
  88. char errorBuffer[ERROR_BUFFER_SIZE];
  89. memset(errorBuffer, 0, sizeof(errorBuffer));
  90. String headersStr;
  91. for (unsigned i = 0; i < headers_.Size(); ++i)
  92. {
  93. // Trim and only add non-empty header strings
  94. String header = headers_[i].Trimmed();
  95. if (header.Length())
  96. headersStr += header + "\r\n";
  97. }
  98. // Initiate the connection. This may block due to DNS query
  99. /// \todo SSL mode will not actually work unless Civetweb's SSL mode is initialized with an external SSL DLL
  100. mg_connection* connection = 0;
  101. if (postData_.Empty())
  102. {
  103. connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer),
  104. "%s %s HTTP/1.1\r\n"
  105. "Host: %s\r\n"
  106. "Connection: close\r\n"
  107. "%s"
  108. "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString());
  109. }
  110. else
  111. {
  112. connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer),
  113. "%s %s HTTP/1.1\r\n"
  114. "Host: %s\r\n"
  115. "Connection: close\r\n"
  116. "%s"
  117. "Content-Length: %d\r\n"
  118. "\r\n"
  119. "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString());
  120. }
  121. {
  122. MutexLock lock(mutex_);
  123. state_ = connection ? HTTP_OPEN : HTTP_ERROR;
  124. // If no connection could be made, store the error and exit
  125. if (state_ == HTTP_ERROR)
  126. {
  127. error_ = String(&errorBuffer[0]);
  128. return;
  129. }
  130. }
  131. // Loop while should run, read data from the connection, copy to the main thread buffer if there is space
  132. while (shouldRun_)
  133. {
  134. // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block
  135. int bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4);
  136. if (bytesRead <= 0)
  137. break;
  138. mutex_.Acquire();
  139. // Wait until enough space in the main thread's ring buffer
  140. for (;;)
  141. {
  142. unsigned spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1));
  143. if ((int)spaceInBuffer > bytesRead || !shouldRun_)
  144. break;
  145. mutex_.Release();
  146. Time::Sleep(5);
  147. mutex_.Acquire();
  148. }
  149. if (!shouldRun_)
  150. {
  151. mutex_.Release();
  152. break;
  153. }
  154. if (writePosition_ + bytesRead <= READ_BUFFER_SIZE)
  155. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), (size_t)bytesRead);
  156. else
  157. {
  158. // Handle ring buffer wrap
  159. unsigned part1 = READ_BUFFER_SIZE - writePosition_;
  160. unsigned part2 = bytesRead - part1;
  161. memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1);
  162. memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2);
  163. }
  164. writePosition_ += bytesRead;
  165. writePosition_ &= READ_BUFFER_SIZE - 1;
  166. mutex_.Release();
  167. }
  168. // Close the connection
  169. mg_close_connection(connection);
  170. {
  171. MutexLock lock(mutex_);
  172. state_ = HTTP_CLOSED;
  173. }
  174. }
  175. unsigned WebRequest::Read(void* dest, unsigned size)
  176. {
  177. mutex_.Acquire();
  178. unsigned char* destPtr = (unsigned char*)dest;
  179. unsigned sizeLeft = size;
  180. unsigned totalRead = 0;
  181. for (;;)
  182. {
  183. unsigned bytesAvailable;
  184. for (;;)
  185. {
  186. bytesAvailable = CheckEofAndAvailableSize();
  187. if (bytesAvailable || IsEof())
  188. break;
  189. // While no bytes and connection is still open, block until has some data
  190. mutex_.Release();
  191. Time::Sleep(5);
  192. mutex_.Acquire();
  193. }
  194. if (bytesAvailable)
  195. {
  196. if (bytesAvailable > sizeLeft)
  197. bytesAvailable = sizeLeft;
  198. if (readPosition_ + bytesAvailable <= READ_BUFFER_SIZE)
  199. memcpy(destPtr, readBuffer_.Get() + readPosition_, bytesAvailable);
  200. else
  201. {
  202. // Handle ring buffer wrap
  203. unsigned part1 = READ_BUFFER_SIZE - readPosition_;
  204. unsigned part2 = bytesAvailable - part1;
  205. memcpy(destPtr, readBuffer_.Get() + readPosition_, part1);
  206. memcpy(destPtr + part1, readBuffer_.Get(), part2);
  207. }
  208. readPosition_ += bytesAvailable;
  209. readPosition_ &= READ_BUFFER_SIZE - 1;
  210. sizeLeft -= bytesAvailable;
  211. totalRead += bytesAvailable;
  212. destPtr += bytesAvailable;
  213. }
  214. if (!sizeLeft || !bytesAvailable)
  215. break;
  216. }
  217. // Check for end-of-file once more after reading the bytes
  218. CheckEofAndAvailableSize();
  219. mutex_.Release();
  220. return totalRead;
  221. }
  222. unsigned WebRequest::Seek(unsigned position)
  223. {
  224. return position_;
  225. }
  226. String WebRequest::GetError() const
  227. {
  228. MutexLock lock(mutex_);
  229. const_cast<WebRequest*>(this)->CheckEofAndAvailableSize();
  230. return error_;
  231. }
  232. WebRequestState WebRequest::GetState() const
  233. {
  234. MutexLock lock(mutex_);
  235. const_cast<WebRequest*>(this)->CheckEofAndAvailableSize();
  236. return state_;
  237. }
  238. unsigned WebRequest::GetAvailableSize() const
  239. {
  240. MutexLock lock(mutex_);
  241. return const_cast<WebRequest*>(this)->CheckEofAndAvailableSize();
  242. }
  243. unsigned WebRequest::CheckEofAndAvailableSize()
  244. {
  245. unsigned bytesAvailable = (writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1);
  246. if (state_ == HTTP_ERROR || (state_ == HTTP_CLOSED && !bytesAvailable))
  247. position_ = M_MAX_UNSIGNED;
  248. return bytesAvailable;
  249. }
  250. }
  251. #endif