WebRequest.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  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 "../Container/HashMap.h"
  25. #include "../IO/BufferQueue.h"
  26. #include "../IO/Log.h"
  27. #include "../Web/Web.h"
  28. #include "../Web/WebEvents.h"
  29. #include "../Web/WebRequest.h"
  30. #ifdef EMSCRIPTEN
  31. #include "../DebugNew.h"
  32. // Add code to use an XMLHttpRequest or ActiveX XMLHttpRequest here.
  33. #else
  34. #include "../Web/WebInternalConfig.h"
  35. #include <asio.hpp>
  36. #include <functional>
  37. #include <curl/curl.h>
  38. #include "../DebugNew.h"
  39. namespace Atomic
  40. {
  41. struct WebRequestInternalState
  42. {
  43. /// The WebRequest external state
  44. WebRequest& es;
  45. /// The work queue.
  46. asio::io_service* service;
  47. /// URL.
  48. String url;
  49. /// Verb.
  50. String verb;
  51. /// Response headers.
  52. HashMap<StringHash, Pair<String, String>> responseHeaders;
  53. /// Upload stream.
  54. SharedPtr<BufferQueue> upload;
  55. /// Download stream.
  56. SharedPtr<BufferQueue> download;
  57. /// Request Headers.
  58. curl_slist* headers = NULL;
  59. /// Connection state.
  60. WebRequestState state;
  61. /// cURL multi handle.
  62. CURLM* curlm;
  63. /// cURL easy handle.
  64. CURL* curl;
  65. /// A flag to know if the request has contents (has data to upload).
  66. curl_off_t requestContentSize;
  67. /// A flag to know if the operation has been aborted.
  68. bool isAborted;
  69. /// A flag to know if the easy handle has been added to the Web class's multi handle.
  70. bool isAddedToMulti;
  71. /// Error string. Empty if no error.
  72. char error[CURL_ERROR_SIZE];
  73. WebRequestInternalState(WebRequest &es_) :
  74. es(es_)
  75. {
  76. }
  77. ~WebRequestInternalState()
  78. {
  79. }
  80. static int onProgress(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
  81. {
  82. WebRequestInternalState *is_(reinterpret_cast<WebRequestInternalState*>(clientp));
  83. if (is_->isAborted)
  84. {
  85. // This should probably be CURL_XFERINFO_ABORT, but that doesn't
  86. // exist. It probably would be the same numeric value, if it did.
  87. // The docs say that it just has to be a nonzero to abort.
  88. return CURL_READFUNC_ABORT;
  89. }
  90. using namespace WebRequestProgress;
  91. VariantMap eventData;
  92. eventData[P_REQUEST] = &is_->es;
  93. eventData[P_DOWNLOADTOTAL] = (int) dltotal;
  94. eventData[P_DOWNLOADED] = (int) dlnow;
  95. eventData[P_UPLOADTOTAL] = (int) ultotal;
  96. eventData[P_UPLOADED] = (int) ulnow;
  97. is_->es.SendEvent(E_WEBREQUESTPROGRESS, eventData);
  98. return 0;
  99. }
  100. static size_t onHeader(char *ptr, size_t size, size_t nmemb, void *userdata)
  101. {
  102. WebRequestInternalState *is_(reinterpret_cast<WebRequestInternalState*>(userdata));
  103. if (is_->isAborted)
  104. {
  105. is_->state = WR_CLOSED;
  106. // This should probably be CURL_HEADERFUNC_ABORT, but that doesn't
  107. // exist. It probably would be the same numeric value, if it did.
  108. // The docs say that it just has to be a number of bytes that is
  109. // not "size * nmemb" to abort.
  110. return CURL_READFUNC_ABORT;
  111. }
  112. // Find the size in bytes.
  113. size_t real_size(size * nmemb);
  114. // Check for some known values.
  115. if (real_size == 2 && ptr[0] == '\r' && ptr[1] == '\n')
  116. {
  117. return real_size;
  118. }
  119. if (real_size > 5 && !strncmp(ptr, "HTTP/", 5))
  120. {
  121. return real_size;
  122. }
  123. // Get the header key and value, and add them to the map.
  124. unsigned int key_end = 0;
  125. unsigned int value_begin = 2;
  126. while (value_begin < real_size)
  127. {
  128. if (ptr[key_end] == ':' && ptr[key_end + 1] == ' ')
  129. {
  130. break;
  131. }
  132. ++key_end;
  133. ++value_begin;
  134. }
  135. if (value_begin == real_size)
  136. {
  137. String key(ptr, (unsigned int)real_size);
  138. is_->responseHeaders.InsertNew(key.ToUpper(), MakePair(key, String()));
  139. }
  140. else
  141. {
  142. String key(ptr, (unsigned int)key_end);
  143. is_->responseHeaders.InsertNew(key.ToUpper(), MakePair(key, String(ptr + value_begin, (unsigned int)real_size - value_begin - 2)));
  144. }
  145. return real_size;
  146. }
  147. static size_t onWrite(char *ptr, size_t size, size_t nmemb, void *userdata)
  148. {
  149. WebRequestInternalState *is_(reinterpret_cast<WebRequestInternalState*>(userdata));
  150. is_->state = WR_OPEN;
  151. if (is_->isAborted)
  152. {
  153. is_->state = WR_CLOSED;
  154. // This should probably be CURL_WRITEFUNC_ABORT, but that doesn't
  155. // exist. It probably would be the same numeric value, if it did.
  156. // The docs say that it just has to be a number of bytes that is
  157. // not "size * nmemb" to abort.
  158. return CURL_READFUNC_ABORT;
  159. }
  160. // Find the size in bytes.
  161. size_t real_size(size * nmemb);
  162. // Write the date into the download buffer queue.
  163. is_->download->Write(ptr, (unsigned int)real_size);
  164. using namespace WebRequestDownloadChunk;
  165. VariantMap eventData;
  166. eventData[P_REQUEST] = &is_->es;
  167. eventData[P_DOWNLOAD] = is_->download;
  168. eventData[P_CHUNKSIZE] = (unsigned) real_size;
  169. is_->es.SendEvent(E_WEBREQUESTDOWNLOADCHUNK, eventData);
  170. return real_size;
  171. }
  172. static size_t onRead(char *buffer, size_t size, size_t nitems, void *instream)
  173. {
  174. WebRequestInternalState *is_(reinterpret_cast<WebRequestInternalState*>(instream));
  175. is_->state = WR_OPEN;
  176. if (is_->isAborted)
  177. {
  178. is_->state = WR_CLOSED;
  179. return CURL_READFUNC_ABORT;
  180. }
  181. // Find the size in bytes.
  182. size_t real_size(size * nitems);
  183. // Read as much as we can from the upload buffer queue.
  184. size_t size_queued(is_->upload->GetSize());
  185. size_t size_left(real_size);
  186. if ((size_left > 0) && (size_queued > 0))
  187. {
  188. size_t read_size(std::min(size_queued, size_left));
  189. is_->upload->Read(buffer, (unsigned int)read_size);
  190. size_left -= read_size;
  191. }
  192. // If we still have bytes to fill, then emit a E_WEBREQUESTUPLOADCHUNK event.
  193. if (size_left > 0)
  194. {
  195. using namespace WebRequestUploadChunk;
  196. VariantMap eventData;
  197. eventData[P_REQUEST] = &is_->es;
  198. eventData[P_UPLOAD] = is_->upload;
  199. eventData[P_BYTESREMAINING] = (unsigned)size_left;
  200. is_->es.SendEvent(E_WEBREQUESTUPLOADCHUNK, eventData);
  201. }
  202. // Read as much as we can from the upload buffer queue (again).
  203. size_queued = is_->upload->GetSize();
  204. size_left = real_size;
  205. if ((size_left > 0) && (size_queued > 0))
  206. {
  207. size_t read_size(std::min(size_queued, size_left));
  208. is_->upload->Read(buffer, (unsigned int)read_size);
  209. size_left -= read_size;
  210. }
  211. // If we still have bytes to fill, then something went wrong, so we should abort.
  212. if (size_left > 0)
  213. {
  214. is_->isAborted = true;
  215. return CURL_READFUNC_ABORT;
  216. }
  217. return real_size;
  218. }
  219. void onEnd(int code)
  220. {
  221. using namespace WebRequestComplete;
  222. VariantMap eventData;
  223. eventData[P_REQUEST] = &es;
  224. if (code != CURLE_OK)
  225. {
  226. state = WR_ERROR;
  227. eventData[P_ERROR] = String(error, (unsigned int)strnlen(error, sizeof(error)));
  228. }
  229. else
  230. {
  231. state = WR_CLOSED;
  232. eventData[P_DOWNLOAD] = download;
  233. eventData[P_UPLOAD] = upload;
  234. }
  235. es.SendEvent(E_WEBREQUESTCOMPLETE, eventData);
  236. }
  237. };
  238. WebRequest::WebRequest(Context* context, const String& verb, const String& url, double requestContentSize) :
  239. Object(context),
  240. is_(new WebRequestInternalState(*this))
  241. {
  242. is_->url = url.Trimmed();
  243. is_->verb = verb;
  244. is_->upload = new BufferQueue(context);
  245. is_->download = new BufferQueue(context);
  246. is_->state = WR_INITIALIZING;
  247. is_->curlm = NULL;
  248. is_->curl = NULL;
  249. is_->requestContentSize = curl_off_t(std::floor(requestContentSize));
  250. is_->isAborted = false;
  251. is_->isAddedToMulti = false;
  252. Web* web = GetSubsystem<Web>();
  253. web->setup(*this);
  254. }
  255. WebRequest::~WebRequest()
  256. {
  257. curl_slist_free_all(is_->headers);
  258. if (is_->curlm == NULL)
  259. {
  260. return;
  261. }
  262. curl_easy_cleanup(is_->curl);
  263. delete is_;
  264. }
  265. void WebRequest::setup(asio::io_service *service, CURLM *curlm)
  266. {
  267. is_->service = service;
  268. is_->curlm = curlm;
  269. is_->curl = curl_easy_init();
  270. curl_easy_setopt(is_->curl, CURLOPT_ERRORBUFFER, is_->error);
  271. is_->error[0] = '\0';
  272. #if !(defined WIN32 || defined APPLE)
  273. // This line will eventually go away with a CA bundle in place, or other TLS options.
  274. curl_easy_setopt(is_->curl, CURLOPT_SSL_VERIFYPEER, 0L);
  275. #endif
  276. curl_easy_setopt(is_->curl, CURLOPT_URL, is_->url.CString());
  277. // All callbacks must look at is_->isAborted flag!
  278. curl_easy_setopt(is_->curl, CURLOPT_HEADERFUNCTION, &WebRequestInternalState::onHeader);
  279. curl_easy_setopt(is_->curl, CURLOPT_HEADERDATA, is_);
  280. curl_easy_setopt(is_->curl, CURLOPT_WRITEFUNCTION, &WebRequestInternalState::onWrite);
  281. curl_easy_setopt(is_->curl, CURLOPT_WRITEDATA, is_);
  282. curl_easy_setopt(is_->curl, CURLOPT_NOPROGRESS, 0L);
  283. curl_easy_setopt(is_->curl, CURLOPT_XFERINFOFUNCTION, &WebRequestInternalState::onProgress);
  284. curl_easy_setopt(is_->curl, CURLOPT_XFERINFODATA, is_);
  285. curl_easy_setopt(is_->curl, CURLOPT_CUSTOMREQUEST, is_->verb.CString());
  286. curl_easy_setopt(is_->curl, CURLOPT_PRIVATE, this);
  287. curl_easy_setopt(is_->curl, CURLOPT_READFUNCTION, &WebRequestInternalState::onRead);
  288. curl_easy_setopt(is_->curl, CURLOPT_READDATA, is_);
  289. if (is_->requestContentSize)
  290. {
  291. curl_easy_setopt(is_->curl, CURLOPT_UPLOAD, 1L);
  292. curl_easy_setopt(is_->curl, CURLOPT_INFILESIZE_LARGE, is_->requestContentSize);
  293. }
  294. }
  295. void WebRequest::internalNotify(WebRequest *wr, int code)
  296. {
  297. wr->is_->onEnd(code);
  298. if (wr->is_->isAddedToMulti)
  299. {
  300. curl_multi_remove_handle(wr->is_->curlm, wr->is_->curl);
  301. wr->is_->isAddedToMulti = false;
  302. // release the reference held from the Send method
  303. wr->ReleaseRef();
  304. }
  305. }
  306. void WebRequest::Abort()
  307. {
  308. is_->isAborted = true;
  309. }
  310. const String& WebRequest::GetURL() const
  311. {
  312. return is_->url;
  313. }
  314. String WebRequest::GetError() const
  315. {
  316. return String(is_->error);
  317. }
  318. WebRequestState WebRequest::GetState() const
  319. {
  320. return is_->state;
  321. }
  322. String WebRequest::GetVerb() const
  323. {
  324. return is_->verb;
  325. }
  326. bool WebRequest::HasDownloadChunkEvent()
  327. {
  328. return true; // cURL based implementations always support the "download_chunk" event.
  329. }
  330. void WebRequest::SetRequestHeader(const String& key, const String& value)
  331. {
  332. // Trim and only add non-empty header strings.
  333. String header;
  334. header += key.Trimmed();
  335. header += ": ";
  336. header += value;
  337. if (header.Length())
  338. {
  339. is_->headers = curl_slist_append(is_->headers, header.CString());
  340. }
  341. }
  342. void WebRequest::Send()
  343. {
  344. if (!is_->isAddedToMulti && !is_->isAborted)
  345. {
  346. // Add a reference to ourselves during the Send, this is released
  347. // in notifyInternal, if we're leaking WebRequests check that
  348. // this is being called
  349. AddRef();
  350. curl_easy_setopt(is_->curl, CURLOPT_HTTPHEADER, is_->headers);
  351. if (CURLM_OK != curl_multi_add_handle(is_->curlm, is_->curl))
  352. {
  353. ATOMIC_LOGERROR("WebRequest::Send() - ERROR SENDING REQUEST!");
  354. }
  355. is_->isAddedToMulti = true;
  356. }
  357. }
  358. StringVector WebRequest::GetResponseHeaderKeys()
  359. {
  360. StringVector keys;
  361. for (auto it(is_->responseHeaders.Begin()),
  362. itEnd(is_->responseHeaders.End()); it != itEnd; ++it)
  363. {
  364. keys.Push(it->second_.first_);
  365. }
  366. return keys;
  367. }
  368. String WebRequest::GetResponseHeader(const String& header)
  369. {
  370. auto it(is_->responseHeaders.Find(header.ToUpper()));
  371. if (it == is_->responseHeaders.End())
  372. {
  373. return "";
  374. }
  375. return it->second_.second_;
  376. }
  377. String WebRequest::GetAllResponseHeaders()
  378. {
  379. String allHeaders;
  380. for (auto it(is_->responseHeaders.Begin()),
  381. itEnd(is_->responseHeaders.End()); it != itEnd; ++it)
  382. {
  383. allHeaders += it->second_.first_;
  384. allHeaders += ": ";
  385. allHeaders += it->second_.second_;
  386. allHeaders += "\r\n";
  387. }
  388. return allHeaders;
  389. }
  390. void WebRequest::SetPostData(const String& postData)
  391. {
  392. // use the copy post fields option so we don't need to hold onto the string buffer
  393. curl_easy_setopt(is_->curl, CURLOPT_COPYPOSTFIELDS, postData.CString());
  394. }
  395. SharedPtr<BufferQueue> WebRequest::GetDownloadBufferQueue()
  396. {
  397. return is_->download;
  398. }
  399. }
  400. #endif