WebRequest.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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/WebRequest.h"
  28. #ifdef EMSCRIPTEN
  29. #include "../DebugNew.h"
  30. // Add code to use an XMLHttpRequest or ActiveX XMLHttpRequest here.
  31. #else
  32. #include "../Web/WebInternalConfig.h"
  33. #include <asio.hpp>
  34. #include <functional>
  35. #include <curl/curl.h>
  36. #include "../DebugNew.h"
  37. namespace Atomic
  38. {
  39. struct WebRequestInternalState
  40. {
  41. /// The WebRequest external state.
  42. WebRequest& es;
  43. /// The WebRequest external state to force it to stay around.
  44. SharedPtr<WebRequest> es_hold;
  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<Object> upload;
  55. /// Download stream.
  56. SharedPtr<Object> 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. LOGDEBUG("Create WebRequestInternalState");
  77. }
  78. ~WebRequestInternalState()
  79. {
  80. LOGDEBUG("Destroy WebRequestInternalState");
  81. }
  82. static int onProgress(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
  83. {
  84. WebRequestInternalState *is_(reinterpret_cast<WebRequestInternalState*>(clientp));
  85. if (is_->isAborted)
  86. {
  87. // This should probably be CURL_XFERINFO_ABORT, but that doesn't
  88. // exist. It probably would be the same numeric value, if it did.
  89. // The docs say that it just has to be a nonzero to abort.
  90. return CURL_READFUNC_ABORT;
  91. }
  92. VariantMap eventData;
  93. eventData.Insert(MakePair(StringHash("down_total"), Variant((double)dltotal)));
  94. eventData.Insert(MakePair(StringHash("down_loaded"), Variant((double)dlnow)));
  95. eventData.Insert(MakePair(StringHash("up_total"), Variant((double)ultotal)));
  96. eventData.Insert(MakePair(StringHash("up_loaded"), Variant((double)ulnow)));
  97. is_->es.SendEvent("progress", 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 = HTTP_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 = HTTP_OPEN;
  151. if (is_->isAborted)
  152. {
  153. is_->state = HTTP_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. Serializer* download(dynamic_cast<Serializer*>(is_->download.Get()));
  164. download->Write(ptr, (unsigned int)real_size);
  165. // Emit a "download_chunk" event.
  166. VariantMap eventData;
  167. eventData.Insert(MakePair(StringHash("download"), Variant(is_->download)));
  168. eventData.Insert(MakePair(StringHash("size"), Variant((unsigned int)real_size)));
  169. is_->es.SendEvent("download_chunk", 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 = HTTP_OPEN;
  176. if (is_->isAborted)
  177. {
  178. is_->state = HTTP_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. Deserializer* upload(dynamic_cast<Deserializer*>(is_->upload.Get()));
  185. size_t size_queued(upload->GetSize());
  186. size_t size_left(real_size);
  187. if ((size_left > 0) && (size_queued > 0))
  188. {
  189. size_t read_size(std::min(size_queued, size_left));
  190. upload->Read(buffer, (unsigned int)read_size);
  191. size_left -= read_size;
  192. }
  193. // If we still have bytes to fill, then emit a "upload_chunk" event.
  194. if (size_left > 0)
  195. {
  196. VariantMap eventData;
  197. eventData.Insert(MakePair(StringHash("upload"), Variant(is_->upload)));
  198. eventData.Insert(MakePair(StringHash("size"), Variant((unsigned int)size_left)));
  199. is_->es.SendEvent("upload_chunk", eventData);
  200. }
  201. // Read as much as we can from the upload buffer queue (again).
  202. size_queued = upload->GetSize();
  203. size_left = real_size;
  204. if ((size_left > 0) && (size_queued > 0))
  205. {
  206. size_t read_size(std::min(size_queued, size_left));
  207. upload->Read(buffer, (unsigned int)read_size);
  208. size_left -= read_size;
  209. }
  210. // If we still have bytes to fill, then something went wrong, so we should abort.
  211. if (size_left > 0)
  212. {
  213. is_->isAborted = true;
  214. return CURL_READFUNC_ABORT;
  215. }
  216. return real_size;
  217. }
  218. void onEnd(int code)
  219. {
  220. VariantMap eventData;
  221. if (code != CURLE_OK)
  222. {
  223. state = HTTP_ERROR;
  224. eventData.Insert(MakePair(StringHash("error"), Variant(String(error, (unsigned int)strnlen(error, sizeof(error))))));
  225. }
  226. else
  227. {
  228. state = HTTP_CLOSED;
  229. eventData.Insert(MakePair(StringHash("download"), Variant(download)));
  230. eventData.Insert(MakePair(StringHash("upload"), Variant(upload)));
  231. }
  232. es.SendEvent("complete", eventData);
  233. }
  234. };
  235. WebRequest::WebRequest(Context* context, const String& verb, const String& url, double requestContentSize) :
  236. Object(context),
  237. is_(new WebRequestInternalState(*this))
  238. {
  239. is_->url = url.Trimmed();
  240. is_->verb = verb;
  241. is_->upload = new BufferQueue(context);
  242. is_->download = new BufferQueue(context);
  243. is_->state = HTTP_INITIALIZING;
  244. is_->curlm = NULL;
  245. is_->curl = NULL;
  246. is_->requestContentSize = curl_off_t(std::floor(requestContentSize));
  247. is_->isAborted = false;
  248. is_->isAddedToMulti = false;
  249. }
  250. WebRequest::~WebRequest()
  251. {
  252. LOGDEBUG("Destroy WebRequest");
  253. curl_slist_free_all(is_->headers);
  254. if (is_->curlm == NULL)
  255. {
  256. return;
  257. }
  258. curl_easy_cleanup(is_->curl);
  259. delete is_;
  260. }
  261. void WebRequest::setup(asio::io_service *service, CURLM *curlm)
  262. {
  263. LOGDEBUG("Create WebRequest");
  264. is_->service = service;
  265. is_->curlm = curlm;
  266. is_->curl = curl_easy_init();
  267. LOGDEBUG("HTTP " + is_->verb + " request to URL " + is_->url);
  268. curl_easy_setopt(is_->curl, CURLOPT_ERRORBUFFER, is_->error);
  269. is_->error[0] = '\0';
  270. #if !(defined WIN32 || defined APPLE)
  271. // This line will eventually go away with a CA bundle in place, or other TLS options.
  272. curl_easy_setopt(is_->curl, CURLOPT_SSL_VERIFYPEER, 0L);
  273. #endif
  274. curl_easy_setopt(is_->curl, CURLOPT_URL, is_->url.CString());
  275. // All callbacks must look at is_->isAborted flag!
  276. curl_easy_setopt(is_->curl, CURLOPT_HEADERFUNCTION, &WebRequestInternalState::onHeader);
  277. curl_easy_setopt(is_->curl, CURLOPT_HEADERDATA, is_);
  278. curl_easy_setopt(is_->curl, CURLOPT_WRITEFUNCTION, &WebRequestInternalState::onWrite);
  279. curl_easy_setopt(is_->curl, CURLOPT_WRITEDATA, is_);
  280. curl_easy_setopt(is_->curl, CURLOPT_NOPROGRESS, 0L);
  281. curl_easy_setopt(is_->curl, CURLOPT_XFERINFOFUNCTION, &WebRequestInternalState::onProgress);
  282. curl_easy_setopt(is_->curl, CURLOPT_XFERINFODATA, is_);
  283. curl_easy_setopt(is_->curl, CURLOPT_CUSTOMREQUEST, is_->verb.CString());
  284. curl_easy_setopt(is_->curl, CURLOPT_PRIVATE, this);
  285. curl_easy_setopt(is_->curl, CURLOPT_READFUNCTION, &WebRequestInternalState::onRead);
  286. curl_easy_setopt(is_->curl, CURLOPT_READDATA, is_);
  287. if (is_->requestContentSize)
  288. {
  289. curl_easy_setopt(is_->curl, CURLOPT_UPLOAD, 1L);
  290. curl_easy_setopt(is_->curl, CURLOPT_INFILESIZE_LARGE, is_->requestContentSize);
  291. }
  292. }
  293. void WebRequest::internalNotify(WebRequest *wr, int code)
  294. {
  295. wr->is_->onEnd(code);
  296. if (wr->is_->isAddedToMulti)
  297. {
  298. curl_multi_remove_handle(wr->is_->curlm, wr->is_->curl);
  299. wr->is_->isAddedToMulti = false;
  300. wr->is_->es_hold.Reset();
  301. }
  302. }
  303. void WebRequest::Abort()
  304. {
  305. is_->isAborted = true;
  306. }
  307. const String& WebRequest::GetURL() const
  308. {
  309. return is_->url;
  310. }
  311. String WebRequest::GetError() const
  312. {
  313. return String(is_->error);
  314. }
  315. WebRequestState WebRequest::GetState() const
  316. {
  317. return is_->state;
  318. }
  319. String WebRequest::GetVerb() const
  320. {
  321. return is_->verb;
  322. }
  323. bool WebRequest::HasDownloadChunkEvent()
  324. {
  325. return true; // cURL based implementations always support the "download_chunk" event.
  326. }
  327. void WebRequest::SetRequestHeader(const String& key, const String& value)
  328. {
  329. // Trim and only add non-empty header strings.
  330. String header;
  331. header += key.Trimmed();
  332. header += ": ";
  333. header += value;
  334. if (header.Length())
  335. {
  336. is_->headers = curl_slist_append(is_->headers, header.CString());
  337. }
  338. }
  339. void WebRequest::Send()
  340. {
  341. if (!is_->isAddedToMulti && !is_->isAborted)
  342. {
  343. is_->es_hold = this;
  344. curl_easy_setopt(is_->curl, CURLOPT_HTTPHEADER, is_->headers);
  345. curl_multi_add_handle(is_->curlm, is_->curl);
  346. is_->isAddedToMulti = true;
  347. }
  348. }
  349. StringVector WebRequest::GetResponseHeaderKeys()
  350. {
  351. StringVector keys;
  352. for (auto it(is_->responseHeaders.Begin()),
  353. itEnd(is_->responseHeaders.End()); it != itEnd; ++it)
  354. {
  355. keys.Push(it->second_.first_);
  356. }
  357. return keys;
  358. }
  359. String WebRequest::GetResponseHeader(const String& header)
  360. {
  361. auto it(is_->responseHeaders.Find(header.ToUpper()));
  362. if (it == is_->responseHeaders.End())
  363. {
  364. return "";
  365. }
  366. return it->second_.second_;
  367. }
  368. String WebRequest::GetAllResponseHeaders()
  369. {
  370. String allHeaders;
  371. for (auto it(is_->responseHeaders.Begin()),
  372. itEnd(is_->responseHeaders.End()); it != itEnd; ++it)
  373. {
  374. allHeaders += it->second_.first_;
  375. allHeaders += ": ";
  376. allHeaders += it->second_.second_;
  377. allHeaders += "\r\n";
  378. }
  379. return allHeaders;
  380. }
  381. }
  382. #endif