llcorehttpoprequest.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. /**
  2. * @file llcorehttpoprequest.cpp
  3. * @brief Definitions for internal class HttpOpRequest
  4. *
  5. * $LicenseInfo:firstyear=2012&license=viewerlgpl$
  6. * Second Life Viewer Source Code
  7. * Copyright (C) 2012-2013, Linden Research, Inc.
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation;
  12. * version 2.1 of the License only.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. *
  23. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  24. * $/LicenseInfo$
  25. */
  26. #include "linden_common.h"
  27. #include <algorithm>
  28. #include "curl/curlver.h"
  29. #include "llcorehttpoprequest.h"
  30. #include "llcorebufferarray.h"
  31. #include "llcorehttpcommon.h"
  32. #include "llcorehttphandler.h"
  33. #include "llcorehttpheaders.h"
  34. #include "llcorehttpinternal.h"
  35. #include "llcorehttplibcurl.h"
  36. #include "llcorehttpoptions.h"
  37. #include "llcorehttppolicy.h"
  38. #include "llcorehttppolicyglobal.h"
  39. #include "llcorehttpreplyqueue.h"
  40. #include "llcorehttprequestqueue.h"
  41. #include "llcorehttpresponse.h"
  42. #include "llcorehttpservice.h"
  43. #include "llhttpconstants.h"
  44. #include "llproxy.h"
  45. namespace
  46. {
  47. // Attempts to parse a 'Content-Range:' header. Caller must already have
  48. // verified that the header tag is present. The 'buffer' argument will be
  49. // processed by strtok_r calls which will modify the buffer.
  50. //
  51. // @return -1 if invalid and response should be dropped, 0 if valid and
  52. // correct, 1 if couldn't be parsed. If 0, the first, last, and length
  53. // arguments are also written. 'length' may be 0 if the length wasn't
  54. // available to the server.
  55. //
  56. int parse_content_range_header(char* buffer,
  57. unsigned int* first,
  58. unsigned int* last,
  59. unsigned int* length);
  60. // Similar for Retry-After headers. Only parses the delta form of the header,
  61. // HTTP time formats aren't interesting for client purposes.
  62. //
  63. // @return 0 if successfully parsed and seconds time delta returned in time
  64. // argument.
  65. //
  66. int parse_retry_after_header(char* buffer, int* time);
  67. // Take data from libcurl's CURLOPT_DEBUGFUNCTION callback and escape and
  68. // format it for a tracing line in logging. Absolutely anything including NULs
  69. // can be in the data. If @scrub is true, non-printing or non-ascii characters
  70. // are replaced with spaces otherwise a %XX form of escaping is used.
  71. void escape_libcurl_debug_data(char* buffer, size_t len, bool scrub,
  72. std::string& safe_line);
  73. // OS-neutral string comparisons of various types.
  74. int os_strcasecmp(const char* s1, const char* s2);
  75. char* os_strtok_r(char* str, const char* delim, char** saveptr);
  76. char* os_strtrim(char* str);
  77. char* os_strltrim(char* str);
  78. void os_strlower(char* str);
  79. // Error testing and reporting for libcurl status codes
  80. void check_curl_easy_code(CURLcode code, int curl_setopt_option);
  81. } // end anonymous namespace
  82. namespace LLCore
  83. {
  84. HttpOpRequest::HttpOpRequest()
  85. : HttpOperation(),
  86. mProcFlags(0U),
  87. mReqMethod(HOR_GET),
  88. mReqBody(NULL),
  89. mReqOffset(0),
  90. mReqLength(0),
  91. mCurlActive(false),
  92. mCurlHandle(NULL),
  93. mCurlService(NULL),
  94. mCurlHeaders(NULL),
  95. mCurlBodyPos(0),
  96. mCurlTemp(NULL),
  97. mCurlTempLen(0),
  98. mReplyBody(NULL),
  99. mReplyOffset(0),
  100. mReplyLength(0),
  101. mReplyFullLength(0),
  102. mReplyRetryAfter(0),
  103. mPolicyRetries(0),
  104. mPolicy503Retries(0),
  105. mPolicyRetryAt(HttpTime(0)),
  106. mPolicyRetryLimit(HTTP_RETRY_COUNT_DEFAULT),
  107. mCallbackSSLVerify(NULL)
  108. {
  109. // *NOTE: As members are added, retry initialization/cleanup may need to be
  110. // extended in @see prepareRequest().
  111. }
  112. HttpOpRequest::~HttpOpRequest()
  113. {
  114. if (mReqBody)
  115. {
  116. mReqBody->release();
  117. mReqBody = NULL;
  118. }
  119. if (mCurlHandle)
  120. {
  121. // Uncertain of thread context so free using safest method.
  122. curl_easy_cleanup(mCurlHandle);
  123. mCurlHandle = NULL;
  124. }
  125. mCurlService = NULL;
  126. if (mCurlHeaders)
  127. {
  128. curl_slist_free_all(mCurlHeaders);
  129. mCurlHeaders = NULL;
  130. }
  131. if (mCurlTemp)
  132. {
  133. delete[] mCurlTemp;
  134. mCurlTemp = NULL;
  135. }
  136. mCurlTempLen = 0;
  137. if (mReplyBody)
  138. {
  139. mReplyBody->release();
  140. mReplyBody = NULL;
  141. }
  142. }
  143. void HttpOpRequest::stageFromRequest(HttpService* service)
  144. {
  145. HttpOpRequest::ptr_t self(std::dynamic_pointer_cast<HttpOpRequest>(shared_from_this()));
  146. service->getPolicy().addOp(self); // Transfers refcount
  147. }
  148. void HttpOpRequest::stageFromReady(HttpService* service)
  149. {
  150. HttpOpRequest::ptr_t self(std::dynamic_pointer_cast<HttpOpRequest>(shared_from_this()));
  151. service->getTransport().addOp(self); // Transfers refcount
  152. }
  153. void HttpOpRequest::stageFromActive(HttpService* service)
  154. {
  155. if (mReplyLength)
  156. {
  157. // If non-zero, we received and processed a Content-Range header with
  158. // the response. If there is received data (and there may not be due to
  159. // protocol violations, HEAD requests, etc, see BUG-2295) Verify that
  160. // what it says is consistent with the received data.
  161. if (mReplyBody && mReplyBody->size() &&
  162. mReplyLength != mReplyBody->size())
  163. {
  164. // Not as expected, fail the request
  165. mStatus = HttpStatus(HttpStatus::LLCORE, HE_INV_CONTENT_RANGE_HDR);
  166. }
  167. }
  168. if (mCurlHeaders)
  169. {
  170. // We take these headers out of the request now as they were allocated
  171. // originally in this thread and the notifier doesn't need them. This
  172. // eliminates one source of heap moving across threads.
  173. curl_slist_free_all(mCurlHeaders);
  174. mCurlHeaders = NULL;
  175. }
  176. // Also not needed on the other side
  177. if (mCurlTemp)
  178. {
  179. delete[] mCurlTemp;
  180. mCurlTemp = NULL;
  181. }
  182. mCurlTempLen = 0;
  183. addAsReply();
  184. }
  185. void HttpOpRequest::visitNotifier(HttpRequest* request)
  186. {
  187. if (mUserHandler)
  188. {
  189. HttpResponse* response = new HttpResponse();
  190. response->setStatus(mStatus);
  191. response->setBody(mReplyBody);
  192. // *HACK: restore any "location" header entry, that gets mysteriously
  193. // wiped out of mReplyHeaders after the headerCallback() call...
  194. if (!mLocation.empty() && mReplyHeaders &&
  195. !mReplyHeaders->find("location"))
  196. {
  197. LL_DEBUGS("CoreHttp") << "Re-adding the 'location' header, which vanished..."
  198. << LL_ENDL;
  199. mReplyHeaders->append("location", mLocation);
  200. }
  201. response->setHeaders(mReplyHeaders);
  202. response->setRequestURL(mReqURL);
  203. if (mReplyOffset || mReplyLength)
  204. {
  205. // Got an explicit offset/length in response
  206. response->setRange(mReplyOffset, mReplyLength, mReplyFullLength);
  207. }
  208. response->setContentType(mReplyConType);
  209. response->setRetries(mPolicyRetries, mPolicy503Retries);
  210. HttpResponse::TransferStats::ptr_t stats =
  211. std::make_shared<HttpResponse::TransferStats>();
  212. curl_easy_getinfo(mCurlHandle, CURLINFO_SIZE_DOWNLOAD,
  213. &stats->mSizeDownload);
  214. curl_easy_getinfo(mCurlHandle, CURLINFO_TOTAL_TIME,
  215. &stats->mTotalTime);
  216. curl_easy_getinfo(mCurlHandle, CURLINFO_SPEED_DOWNLOAD,
  217. &stats->mSpeedDownload);
  218. response->setTransferStats(stats);
  219. mUserHandler->onCompleted(this->getHandle(), response);
  220. response->release();
  221. }
  222. }
  223. HttpStatus HttpOpRequest::cancel()
  224. {
  225. mStatus = HttpStatus(HttpStatus::LLCORE, HE_OP_CANCELLED);
  226. addAsReply();
  227. return HttpStatus();
  228. }
  229. HttpStatus HttpOpRequest::setupGet(HttpRequest::policy_t policy_id,
  230. const std::string& url,
  231. const HttpOptions::ptr_t& options,
  232. const HttpHeaders::ptr_t& headers)
  233. {
  234. setupCommon(policy_id, url, NULL, options, headers);
  235. mReqMethod = HOR_GET;
  236. return HttpStatus();
  237. }
  238. HttpStatus HttpOpRequest::setupGetByteRange(HttpRequest::policy_t policy_id,
  239. const std::string& url,
  240. size_t offset,
  241. size_t len,
  242. const HttpOptions::ptr_t& options,
  243. const HttpHeaders::ptr_t& headers)
  244. {
  245. setupCommon(policy_id, url, NULL, options, headers);
  246. mReqMethod = HOR_GET;
  247. mReqOffset = offset;
  248. mReqLength = len;
  249. if (offset || len)
  250. {
  251. mProcFlags |= PF_SCAN_RANGE_HEADER;
  252. }
  253. return HttpStatus();
  254. }
  255. HttpStatus HttpOpRequest::setupPost(HttpRequest::policy_t policy_id,
  256. const std::string& url,
  257. BufferArray* body,
  258. const HttpOptions::ptr_t& options,
  259. const HttpHeaders::ptr_t& headers)
  260. {
  261. setupCommon(policy_id, url, body, options, headers);
  262. mReqMethod = HOR_POST;
  263. return HttpStatus();
  264. }
  265. HttpStatus HttpOpRequest::setupPut(HttpRequest::policy_t policy_id,
  266. const std::string& url,
  267. BufferArray* body,
  268. const HttpOptions::ptr_t& options,
  269. const HttpHeaders::ptr_t& headers)
  270. {
  271. setupCommon(policy_id, url, body, options, headers);
  272. mReqMethod = HOR_PUT;
  273. return HttpStatus();
  274. }
  275. HttpStatus HttpOpRequest::setupDelete(HttpRequest::policy_t policy_id,
  276. const std::string& url,
  277. const HttpOptions::ptr_t& options,
  278. const HttpHeaders::ptr_t& headers)
  279. {
  280. setupCommon(policy_id, url, NULL, options, headers);
  281. mReqMethod = HOR_DELETE;
  282. return HttpStatus();
  283. }
  284. HttpStatus HttpOpRequest::setupPatch(HttpRequest::policy_t policy_id,
  285. const std::string& url,
  286. BufferArray* body,
  287. const HttpOptions::ptr_t& options,
  288. const HttpHeaders::ptr_t& headers)
  289. {
  290. setupCommon(policy_id, url, body, options, headers);
  291. mReqMethod = HOR_PATCH;
  292. return HttpStatus();
  293. }
  294. HttpStatus HttpOpRequest::setupCopy(HttpRequest::policy_t policy_id,
  295. const std::string& url,
  296. const HttpOptions::ptr_t& options,
  297. const HttpHeaders::ptr_t& headers)
  298. {
  299. setupCommon(policy_id, url, NULL, options, headers);
  300. mReqMethod = HOR_COPY;
  301. return HttpStatus();
  302. }
  303. HttpStatus HttpOpRequest::setupMove(HttpRequest::policy_t policy_id,
  304. const std::string& url,
  305. const HttpOptions::ptr_t& options,
  306. const HttpHeaders::ptr_t& headers)
  307. {
  308. setupCommon(policy_id, url, NULL, options, headers);
  309. mReqMethod = HOR_MOVE;
  310. return HttpStatus();
  311. }
  312. void HttpOpRequest::setupCommon(HttpRequest::policy_t policy_id,
  313. const std::string& url,
  314. BufferArray* body,
  315. const HttpOptions::ptr_t& options,
  316. const HttpHeaders::ptr_t& headers)
  317. {
  318. mProcFlags = 0U;
  319. mReqPolicy = policy_id;
  320. mReqURL = url;
  321. if (body)
  322. {
  323. body->addRef();
  324. mReqBody = body;
  325. }
  326. if (headers && !mReqHeaders)
  327. {
  328. mReqHeaders = headers;
  329. }
  330. if (options && !mReqOptions)
  331. {
  332. mReqOptions = options;
  333. if (options->getWantHeaders())
  334. {
  335. mProcFlags |= PF_SAVE_HEADERS;
  336. }
  337. if (options->getUseRetryAfter())
  338. {
  339. mProcFlags |= PF_USE_RETRY_AFTER;
  340. }
  341. mPolicyRetryLimit = options->getRetries();
  342. mPolicyRetryLimit = llclamp(mPolicyRetryLimit, HTTP_RETRY_COUNT_MIN,
  343. HTTP_RETRY_COUNT_MAX);
  344. mTracing = llmax(mTracing,
  345. llclamp((long)options->getTrace(), HTTP_TRACE_MIN,
  346. HTTP_TRACE_MAX));
  347. }
  348. }
  349. // Sets all libcurl options and data for a request.
  350. //
  351. // Used both for initial requests and to 'reload' for a retry, generally with a
  352. // different CURL handle. Junk may be left around from a failed request and
  353. // that needs to be cleaned out.
  354. // *TODO: Move this to llcorehttplibcurl where it belongs.
  355. HttpStatus HttpOpRequest::prepareRequest(HttpService* service)
  356. {
  357. CURLcode code;
  358. // Scrub transport and result data for retried op case
  359. mCurlActive = false;
  360. mCurlHandle = NULL;
  361. mCurlService = NULL;
  362. if (mCurlHeaders)
  363. {
  364. curl_slist_free_all(mCurlHeaders);
  365. mCurlHeaders = NULL;
  366. }
  367. mCurlBodyPos = 0;
  368. if (mReplyBody)
  369. {
  370. mReplyBody->release();
  371. mReplyBody = NULL;
  372. }
  373. mReplyOffset = 0;
  374. mReplyLength = 0;
  375. mReplyFullLength = 0;
  376. mReplyHeaders.reset();
  377. mReplyConType.clear();
  378. // *FIXME: better error handling later
  379. HttpStatus status;
  380. // Get global and class policy options
  381. HttpPolicyGlobal& gpolicy = service->getPolicy().getGlobalOptions();
  382. HttpPolicyClass& cpolicy = service->getPolicy().getClassOptions(mReqPolicy);
  383. mCurlHandle = service->getTransport().getHandle();
  384. if (!mCurlHandle)
  385. {
  386. // We're in trouble. We'll continue but it won't go well.
  387. llwarns << "Failed to allocate libcurl easy handle. Continuing."
  388. << llendl;
  389. return HttpStatus(HttpStatus::LLCORE, HE_BAD_ALLOC);
  390. }
  391. code = curl_easy_setopt(mCurlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  392. check_curl_easy_code(code, CURLOPT_IPRESOLVE);
  393. code = curl_easy_setopt(mCurlHandle, CURLOPT_NOSIGNAL, 1);
  394. check_curl_easy_code(code, CURLOPT_NOSIGNAL);
  395. code = curl_easy_setopt(mCurlHandle, CURLOPT_NOPROGRESS, 1);
  396. check_curl_easy_code(code, CURLOPT_NOPROGRESS);
  397. code = curl_easy_setopt(mCurlHandle, CURLOPT_URL, mReqURL.c_str());
  398. check_curl_easy_code(code, CURLOPT_URL);
  399. code = curl_easy_setopt(mCurlHandle, CURLOPT_PRIVATE, getHandle());
  400. check_curl_easy_code(code, CURLOPT_PRIVATE);
  401. #if LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR < 60
  402. code = curl_easy_setopt(mCurlHandle, CURLOPT_ENCODING, "");
  403. check_curl_easy_code(code, CURLOPT_ENCODING);
  404. #endif
  405. code = curl_easy_setopt(mCurlHandle, CURLOPT_AUTOREFERER, 1);
  406. check_curl_easy_code(code, CURLOPT_AUTOREFERER);
  407. code = curl_easy_setopt(mCurlHandle, CURLOPT_MAXREDIRS,
  408. HTTP_REDIRECTS_DEFAULT);
  409. check_curl_easy_code(code, CURLOPT_MAXREDIRS);
  410. code = curl_easy_setopt(mCurlHandle, CURLOPT_WRITEFUNCTION, writeCallback);
  411. check_curl_easy_code(code, CURLOPT_WRITEFUNCTION);
  412. code = curl_easy_setopt(mCurlHandle, CURLOPT_WRITEDATA, getHandle());
  413. check_curl_easy_code(code, CURLOPT_WRITEDATA);
  414. code = curl_easy_setopt(mCurlHandle, CURLOPT_READFUNCTION, readCallback);
  415. check_curl_easy_code(code, CURLOPT_READFUNCTION);
  416. code = curl_easy_setopt(mCurlHandle, CURLOPT_READDATA, getHandle());
  417. check_curl_easy_code(code, CURLOPT_READDATA);
  418. code = curl_easy_setopt(mCurlHandle, CURLOPT_SEEKFUNCTION, seekCallback);
  419. check_curl_easy_code(code, CURLOPT_SEEKFUNCTION);
  420. code = curl_easy_setopt(mCurlHandle, CURLOPT_SEEKDATA, getHandle());
  421. check_curl_easy_code(code, CURLOPT_SEEKDATA);
  422. code = curl_easy_setopt(mCurlHandle, CURLOPT_COOKIEFILE, "");
  423. check_curl_easy_code(code, CURLOPT_COOKIEFILE);
  424. if (gpolicy.mSslCtxCallback)
  425. {
  426. code = curl_easy_setopt(mCurlHandle, CURLOPT_SSL_CTX_FUNCTION,
  427. curlSslCtxCallback);
  428. check_curl_easy_code(code, CURLOPT_SSL_CTX_FUNCTION);
  429. code = curl_easy_setopt(mCurlHandle, CURLOPT_SSL_CTX_DATA,
  430. getHandle());
  431. check_curl_easy_code(code, CURLOPT_SSL_CTX_DATA);
  432. mCallbackSSLVerify = gpolicy.mSslCtxCallback;
  433. }
  434. long follow_redirect = 1L;
  435. long ssl_peer_v = 0L;
  436. long ssl_host_v = 0L;
  437. long dns_cache_timeout = -1L;
  438. long nobody = 0L;
  439. if (mReqOptions)
  440. {
  441. follow_redirect = mReqOptions->getFollowRedirects() ? 1L : 0L;
  442. ssl_peer_v = mReqOptions->getSSLVerifyPeer() ? 1L : 0L;
  443. ssl_host_v = mReqOptions->getSSLVerifyHost() ? 2L : 0L;
  444. dns_cache_timeout = mReqOptions->getDNSCacheTimeout();
  445. nobody = mReqOptions->getHeadersOnly() ? 1L : 0L;
  446. }
  447. code = curl_easy_setopt(mCurlHandle, CURLOPT_FOLLOWLOCATION,
  448. follow_redirect);
  449. check_curl_easy_code(code, CURLOPT_FOLLOWLOCATION);
  450. code = curl_easy_setopt(mCurlHandle, CURLOPT_SSL_VERIFYPEER, ssl_peer_v);
  451. check_curl_easy_code(code, CURLOPT_SSL_VERIFYPEER);
  452. code = curl_easy_setopt(mCurlHandle, CURLOPT_SSL_VERIFYHOST, ssl_host_v);
  453. check_curl_easy_code(code, CURLOPT_SSL_VERIFYHOST);
  454. code = curl_easy_setopt(mCurlHandle, CURLOPT_NOBODY, nobody);
  455. check_curl_easy_code(code, CURLOPT_NOBODY);
  456. // The Linksys WRT54G V5 router has an issue with frequent DNS lookups from
  457. // LAN machines. If they happen too often, like for every HTTP request, the
  458. // router gets annoyed after about 700 or so requests and starts issuing
  459. // TCP RSTs to new connections. Reuse the DNS lookups for even a few
  460. // seconds and no RSTs.
  461. code = curl_easy_setopt(mCurlHandle, CURLOPT_DNS_CACHE_TIMEOUT,
  462. dns_cache_timeout);
  463. check_curl_easy_code(code, CURLOPT_DNS_CACHE_TIMEOUT);
  464. if (gpolicy.mUseLLProxy)
  465. {
  466. if (LLProxy::instanceExists())
  467. {
  468. // Use the viewer-based thread-safe API which has a fast/safe check
  469. // for proxy enable. Would like to encapsulate this someway...
  470. LLProxy::getInstance()->applyProxySettings(mCurlHandle);
  471. }
  472. else
  473. {
  474. llwarns << "Proxy not initialized; settings not applied to curl handle: "
  475. << mCurlHandle << llendl;
  476. llassert(false);
  477. }
  478. }
  479. else if (gpolicy.mHttpProxy.size())
  480. {
  481. // *TODO: This is fine for now but get fuller socks5/authentication
  482. // thing going later....
  483. code = curl_easy_setopt(mCurlHandle, CURLOPT_PROXY,
  484. gpolicy.mHttpProxy.c_str());
  485. check_curl_easy_code(code, CURLOPT_PROXY);
  486. code = curl_easy_setopt(mCurlHandle, CURLOPT_PROXYTYPE,
  487. CURLPROXY_HTTP);
  488. check_curl_easy_code(code, CURLOPT_PROXYTYPE);
  489. }
  490. if (gpolicy.mCAPath.size())
  491. {
  492. code = curl_easy_setopt(mCurlHandle, CURLOPT_CAPATH,
  493. gpolicy.mCAPath.c_str());
  494. check_curl_easy_code(code, CURLOPT_CAPATH);
  495. }
  496. if (gpolicy.mCAFile.size())
  497. {
  498. code = curl_easy_setopt(mCurlHandle, CURLOPT_CAINFO,
  499. gpolicy.mCAFile.c_str());
  500. check_curl_easy_code(code, CURLOPT_CAINFO);
  501. }
  502. switch (mReqMethod)
  503. {
  504. case HOR_GET:
  505. {
  506. if (nobody == 0)
  507. {
  508. code = curl_easy_setopt(mCurlHandle, CURLOPT_HTTPGET, 1);
  509. }
  510. check_curl_easy_code(code, CURLOPT_HTTPGET);
  511. break;
  512. }
  513. case HOR_POST:
  514. {
  515. code = curl_easy_setopt(mCurlHandle, CURLOPT_POST, 1);
  516. check_curl_easy_code(code, CURLOPT_POST);
  517. #if LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR < 60
  518. code = curl_easy_setopt(mCurlHandle, CURLOPT_ENCODING, "");
  519. check_curl_easy_code(code, CURLOPT_ENCODING);
  520. #endif
  521. long data_size = mReqBody ? mReqBody->size() : 0;
  522. code = curl_easy_setopt(mCurlHandle, CURLOPT_POSTFIELDS, NULL);
  523. check_curl_easy_code(code, CURLOPT_POSTFIELDS);
  524. code = curl_easy_setopt(mCurlHandle, CURLOPT_POSTFIELDSIZE,
  525. data_size);
  526. check_curl_easy_code(code, CURLOPT_POSTFIELDSIZE);
  527. mCurlHeaders = curl_slist_append(mCurlHeaders, "Expect:");
  528. break;
  529. }
  530. case HOR_PATCH:
  531. {
  532. code = curl_easy_setopt(mCurlHandle, CURLOPT_CUSTOMREQUEST,
  533. "PATCH");
  534. check_curl_easy_code(code, CURLOPT_CUSTOMREQUEST);
  535. // fall through. The rest is the same as PUT
  536. }
  537. case HOR_PUT:
  538. {
  539. code = curl_easy_setopt(mCurlHandle, CURLOPT_UPLOAD, 1);
  540. check_curl_easy_code(code, CURLOPT_UPLOAD);
  541. long data_size = mReqBody ? mReqBody->size() : 0L;
  542. code = curl_easy_setopt(mCurlHandle, CURLOPT_INFILESIZE,
  543. data_size);
  544. check_curl_easy_code(code, CURLOPT_INFILESIZE);
  545. mCurlHeaders = curl_slist_append(mCurlHeaders, "Expect:");
  546. break;
  547. }
  548. case HOR_DELETE:
  549. {
  550. code = curl_easy_setopt(mCurlHandle, CURLOPT_CUSTOMREQUEST,
  551. "DELETE");
  552. check_curl_easy_code(code, CURLOPT_CUSTOMREQUEST);
  553. break;
  554. }
  555. case HOR_COPY:
  556. {
  557. code = curl_easy_setopt(mCurlHandle, CURLOPT_CUSTOMREQUEST,
  558. "COPY");
  559. check_curl_easy_code(code, CURLOPT_CUSTOMREQUEST);
  560. break;
  561. }
  562. case HOR_MOVE:
  563. {
  564. code = curl_easy_setopt(mCurlHandle, CURLOPT_CUSTOMREQUEST,
  565. "MOVE");
  566. check_curl_easy_code(code, CURLOPT_CUSTOMREQUEST);
  567. break;
  568. }
  569. default:
  570. {
  571. llerrs << "Invalid HTTP method in request: " << (S32)mReqMethod
  572. << ". Cannot recover." << llendl;
  573. }
  574. }
  575. if (!mReqHeaders || !mReqHeaders->find("Connection"))
  576. {
  577. mCurlHeaders = curl_slist_append(mCurlHeaders, "Connection: keep-alive");
  578. }
  579. if (!mReqHeaders || !mReqHeaders->find("Keep-Alive"))
  580. {
  581. mCurlHeaders = curl_slist_append(mCurlHeaders, "Keep-alive: 300");
  582. }
  583. // Tracing
  584. mTracing = llmax(mTracing, cpolicy.mTrace);
  585. if (mTracing >= HTTP_TRACE_CURL_HEADERS)
  586. {
  587. code = curl_easy_setopt(mCurlHandle, CURLOPT_VERBOSE, 1);
  588. check_curl_easy_code(code, CURLOPT_VERBOSE);
  589. code = curl_easy_setopt(mCurlHandle, CURLOPT_DEBUGDATA, this);
  590. check_curl_easy_code(code, CURLOPT_DEBUGDATA);
  591. code = curl_easy_setopt(mCurlHandle, CURLOPT_DEBUGFUNCTION,
  592. debugCallback);
  593. check_curl_easy_code(code, CURLOPT_DEBUGFUNCTION);
  594. }
  595. // There is a CURLOPT for this now...
  596. if ((mReqOffset || mReqLength) && HOR_GET == mReqMethod)
  597. {
  598. static const char* const fmt1("Range: bytes=%lu-%lu");
  599. static const char* const fmt2("Range: bytes=%lu-");
  600. char range_line[64];
  601. #if LL_WINDOWS
  602. _snprintf_s(range_line, sizeof(range_line), sizeof(range_line) - 1,
  603. (mReqLength ? fmt1 : fmt2),
  604. (unsigned long)mReqOffset,
  605. (unsigned long)(mReqOffset + mReqLength - 1));
  606. #else
  607. if (mReqLength)
  608. {
  609. snprintf(range_line, sizeof(range_line), fmt1,
  610. (unsigned long)mReqOffset,
  611. (unsigned long)(mReqOffset + mReqLength - 1));
  612. }
  613. else
  614. {
  615. snprintf(range_line, sizeof(range_line), fmt2,
  616. (unsigned long)mReqOffset);
  617. }
  618. #endif // LL_WINDOWS
  619. range_line[sizeof(range_line) - 1] = '\0';
  620. mCurlHeaders = curl_slist_append(mCurlHeaders, range_line);
  621. }
  622. mCurlHeaders = curl_slist_append(mCurlHeaders, "Pragma:");
  623. // Request options
  624. long timeout = HTTP_REQUEST_TIMEOUT_DEFAULT;
  625. long xfer_timeout = HTTP_REQUEST_XFER_TIMEOUT_DEFAULT;
  626. if (mReqOptions)
  627. {
  628. timeout = mReqOptions->getTimeout();
  629. timeout = llclamp(timeout, HTTP_REQUEST_TIMEOUT_MIN,
  630. HTTP_REQUEST_TIMEOUT_MAX);
  631. xfer_timeout = mReqOptions->getTransferTimeout();
  632. xfer_timeout = llclamp(xfer_timeout, HTTP_REQUEST_TIMEOUT_MIN,
  633. HTTP_REQUEST_TIMEOUT_MAX);
  634. }
  635. if (xfer_timeout == 0L)
  636. {
  637. xfer_timeout = timeout;
  638. }
  639. if (cpolicy.mPipelining > 1L)
  640. {
  641. // Pipelining affects both connection and transfer timeout values.
  642. // Requests that are added to a pipeling immediately have completed
  643. // their connection so the connection delay tends to be less than the
  644. // non-pipelined value. Transfers are the opposite. Transfer timeout
  645. // starts once the connection is established and completion can be
  646. // delayed due to the pipelined requests ahead. So, it's a handwave but
  647. // bump the transfer timeout up by the pipelining depth to give some
  648. // room.
  649. #if 0 // BUG-7698, BUG-7688, BUG-7694 (others). Scylla and Charybdis
  650. // situation. Operating against a CDN having service issues may lead to
  651. // requests stalling for an arbitrarily long time with only the
  652. // CURLOPT_TIMEOUT value leading to a closed connection. Sadly for
  653. // pipelining, libcurl (7.39.0 and earlier, at minimum) starts the
  654. // clock on this value as soon as a request is started down the wire.
  655. // We want a short value to recover and retry from the CDN. We need a
  656. // long value to safely deal with a succession of piled-up pipelined
  657. // requests.
  658. // *TODO: Find a better scheme than timeouts to guarantee liveness.
  659. // Progress on the connection is what we really want, not timeouts. But
  660. // we don't have access to that and the request progress indicators
  661. // (various libcurl callbacks) have the same problem TIMEOUT does.
  662. xfer_timeout *= cpolicy.mPipelining;
  663. #else
  664. xfer_timeout *= 2L;
  665. #endif
  666. #if LIBCURL_VERSION_MAJOR > 7 || LIBCURL_VERSION_MINOR >= 54
  667. if (LLCore::LLHttp::gEnabledHTTP2)
  668. {
  669. code = curl_easy_setopt(mCurlHandle, CURLOPT_HTTP_VERSION,
  670. CURL_HTTP_VERSION_2_0);
  671. check_curl_easy_code(code, CURLOPT_HTTP_VERSION);
  672. }
  673. #endif
  674. }
  675. #if 0 // *DEBUG: Enable following override for timeout handling and
  676. // "[curl:bugs] #1420" tests
  677. xfer_timeout = 1L;
  678. #endif
  679. code = curl_easy_setopt(mCurlHandle, CURLOPT_TIMEOUT, xfer_timeout);
  680. check_curl_easy_code(code, CURLOPT_TIMEOUT);
  681. code = curl_easy_setopt(mCurlHandle, CURLOPT_CONNECTTIMEOUT, timeout);
  682. check_curl_easy_code(code, CURLOPT_CONNECTTIMEOUT);
  683. // Request headers
  684. if (mReqHeaders)
  685. {
  686. // Caller's headers last to override
  687. mCurlHeaders = append_headers_to_slist(mReqHeaders, mCurlHeaders);
  688. }
  689. code = curl_easy_setopt(mCurlHandle, CURLOPT_HTTPHEADER, mCurlHeaders);
  690. check_curl_easy_code(code, CURLOPT_HTTPHEADER);
  691. if (mProcFlags &
  692. (PF_SCAN_RANGE_HEADER | PF_SAVE_HEADERS | PF_USE_RETRY_AFTER))
  693. {
  694. code = curl_easy_setopt(mCurlHandle, CURLOPT_HEADERFUNCTION,
  695. headerCallback);
  696. check_curl_easy_code(code, CURLOPT_HEADERFUNCTION);
  697. code = curl_easy_setopt(mCurlHandle, CURLOPT_HEADERDATA, this);
  698. check_curl_easy_code(code, CURLOPT_HEADERDATA);
  699. }
  700. if (status)
  701. {
  702. mCurlService = service;
  703. }
  704. return status;
  705. }
  706. size_t HttpOpRequest::writeCallback(void* data, size_t size, size_t nmemb,
  707. void* userdata)
  708. {
  709. if (!userdata)
  710. {
  711. llwarns << "NULL userdata in callback !" << llendl;
  712. return 0;
  713. }
  714. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  715. if (!op->mReplyBody)
  716. {
  717. op->mReplyBody = new BufferArray();
  718. }
  719. const size_t req_size = size * nmemb;
  720. const size_t write_size = op->mReplyBody->append(static_cast<char*>(data),
  721. req_size);
  722. return write_size;
  723. }
  724. size_t HttpOpRequest::readCallback(void* data, size_t size, size_t nmemb,
  725. void* userdata)
  726. {
  727. if (!userdata)
  728. {
  729. llwarns << "NULL userdata in callback !" << llendl;
  730. return 0;
  731. }
  732. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  733. if (!op->mReqBody)
  734. {
  735. return 0;
  736. }
  737. const size_t req_size = size * nmemb;
  738. const size_t body_size = op->mReqBody->size();
  739. if (body_size <= op->mCurlBodyPos)
  740. {
  741. if (body_size < op->mCurlBodyPos)
  742. {
  743. llwarns << "Request body position beyond body size. Truncating request body."
  744. << llendl;
  745. }
  746. return 0;
  747. }
  748. const size_t do_size = (std::min)(req_size, body_size - op->mCurlBodyPos);
  749. const size_t read_size = op->mReqBody->read(op->mCurlBodyPos,
  750. static_cast<char*>(data),
  751. do_size);
  752. op->mCurlBodyPos += read_size;
  753. return read_size;
  754. }
  755. int HttpOpRequest::seekCallback(void* userdata, curl_off_t offset, int origin)
  756. {
  757. if (!userdata)
  758. {
  759. llwarns << "NULL userdata in callback !" << llendl;
  760. return 0;
  761. }
  762. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  763. if (!op->mReqBody)
  764. {
  765. return 0;
  766. }
  767. size_t newPos = 0;
  768. if (origin == SEEK_SET)
  769. {
  770. newPos = offset;
  771. }
  772. else if (origin == SEEK_END)
  773. {
  774. newPos = static_cast<curl_off_t>(op->mReqBody->size()) + offset;
  775. }
  776. else if (origin == SEEK_CUR)
  777. {
  778. newPos = static_cast<curl_off_t>(op->mCurlBodyPos) + offset;
  779. }
  780. else
  781. {
  782. return 2;
  783. }
  784. if (newPos >= op->mReqBody->size())
  785. {
  786. llwarns << "Attempt to seek to position outside post body." << llendl;
  787. return 2;
  788. }
  789. op->mCurlBodyPos = (size_t)newPos;
  790. return 0;
  791. }
  792. size_t HttpOpRequest::headerCallback(void* data, size_t size, size_t nmemb,
  793. void* userdata)
  794. {
  795. static const char status_line[] = "HTTP/";
  796. static const size_t status_line_len = sizeof(status_line) - 1;
  797. static const char con_ran_line[] = "content-range";
  798. static const char con_retry_line[] = "retry-after";
  799. if (!userdata)
  800. {
  801. llwarns << "NULL userdata in callback !" << llendl;
  802. return 0;
  803. }
  804. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  805. const size_t hdr_size = size * nmemb;
  806. const char* hdr_data = (const char*)data; // Not NUL-terminated
  807. bool is_header = true;
  808. if (hdr_size >= status_line_len &&
  809. !strncmp(status_line, hdr_data, status_line_len))
  810. {
  811. // One of possibly several status lines. Reset what we know and start
  812. // over taking results from the last header stanza we receive.
  813. op->mReplyOffset = 0;
  814. op->mReplyLength = 0;
  815. op->mReplyFullLength = 0;
  816. op->mReplyRetryAfter = 0;
  817. op->mStatus = HttpStatus();
  818. if (op->mReplyHeaders)
  819. {
  820. op->mReplyHeaders->clear();
  821. }
  822. is_header = false;
  823. }
  824. // Nothing in here wants a final CR/LF combination. Remove it as much as
  825. // possible.
  826. size_t wanted_hdr_size = hdr_size;
  827. if (wanted_hdr_size && '\n' == hdr_data[wanted_hdr_size - 1])
  828. {
  829. if (--wanted_hdr_size && '\r' == hdr_data[wanted_hdr_size - 1])
  830. {
  831. --wanted_hdr_size;
  832. }
  833. }
  834. // Copy and normalize header fragments for the following stages. Would like
  835. // to modify the data in-place but that may not be allowed and we need one
  836. // byte extra for NUL. At the end of this we will have:
  837. //
  838. // If ':' present in header:
  839. // 1. name points to text to left of colon which will be ASCII lower-
  840. // cased and left and right trimmed of whitespace.
  841. // 2. value points to text to right of colon which will be left trimmed
  842. // of whitespace.
  843. // Otherwise:
  844. // 1. name points to header which will be left trimmed of whitespace.
  845. // 2. value is NULL
  846. // Any non-NULL pointer may point to a zero-length string.
  847. if (wanted_hdr_size >= op->mCurlTempLen)
  848. {
  849. delete[] op->mCurlTemp;
  850. op->mCurlTempLen = 2 * wanted_hdr_size + 1;
  851. op->mCurlTemp = new char[op->mCurlTempLen];
  852. }
  853. memcpy(op->mCurlTemp, hdr_data, wanted_hdr_size);
  854. op->mCurlTemp[wanted_hdr_size] = '\0';
  855. char* name = op->mCurlTemp;
  856. char* value = strchr(name, ':');
  857. if (value)
  858. {
  859. *value++ = '\0';
  860. os_strlower(name);
  861. name = os_strtrim(name);
  862. value = os_strltrim(value);
  863. }
  864. else
  865. {
  866. // Does not look well-formed, do minimal normalization on it
  867. name = os_strltrim(name);
  868. }
  869. // Normalized, now reject headers with empty names.
  870. if (*name == '\0')
  871. {
  872. // No use continuing
  873. return hdr_size;
  874. }
  875. // Save headers if caller wants them in the response
  876. if (is_header && (op->mProcFlags & PF_SAVE_HEADERS))
  877. {
  878. // Save headers in response
  879. if (!op->mReplyHeaders)
  880. {
  881. op->mReplyHeaders = DEFAULT_HTTP_HEADERS;
  882. }
  883. op->mReplyHeaders->append(name, value ? value : "");
  884. // *HACK: some safe place to store any "location" header entry, that
  885. // would otherwise get mysteriously wiped out of mReplyHeaders between
  886. // this call and the visitNotifier() call...
  887. if (value && !strcmp(name, "location"))
  888. {
  889. op->mLocation.assign(value);
  890. }
  891. }
  892. // Detect and parse 'Content-Range' headers
  893. if (is_header && (op->mProcFlags & PF_SCAN_RANGE_HEADER) &&
  894. value && *value && !strcmp(name, con_ran_line))
  895. {
  896. unsigned int first(0), last(0), length(0);
  897. int status;
  898. if (!(status = parse_content_range_header(value, &first, &last,
  899. &length)))
  900. {
  901. // Success, record the fragment position
  902. op->mReplyOffset = first;
  903. op->mReplyLength = last - first + 1;
  904. op->mReplyFullLength = length;
  905. }
  906. else if (status == -1)
  907. {
  908. // Response is badly formed and shouldn't be accepted
  909. op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_INV_CONTENT_RANGE_HDR);
  910. }
  911. else
  912. {
  913. // Ignore the unparsable.
  914. llwarns_once << "Problem parsing odd Content-Range header: '"
  915. << std::string(hdr_data, wanted_hdr_size)
  916. << "'. Ignoring." << llendl;
  917. }
  918. }
  919. // Detect and parse 'Retry-After' headers
  920. if (is_header && (op->mProcFlags & PF_USE_RETRY_AFTER) && value &&
  921. *value && !strcmp(name, con_retry_line))
  922. {
  923. int time = 0;
  924. if (!parse_retry_after_header(value, &time))
  925. {
  926. op->mReplyRetryAfter = time;
  927. }
  928. }
  929. return hdr_size;
  930. }
  931. CURLcode HttpOpRequest::curlSslCtxCallback(CURL* curl, void* sslctx,
  932. void* userdata)
  933. {
  934. if (!userdata)
  935. {
  936. llwarns << "NULL userdata in callback !" << llendl;
  937. return CURLE_OK;
  938. }
  939. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  940. if (op->mCallbackSSLVerify)
  941. {
  942. SSL_CTX* ctx = (SSL_CTX*)sslctx;
  943. // disable any default verification for server certs
  944. SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  945. // set the verification callback.
  946. SSL_CTX_set_cert_verify_callback(ctx, sslCertVerifyCallback, userdata);
  947. // the calls are void
  948. }
  949. return CURLE_OK;
  950. }
  951. int HttpOpRequest::sslCertVerifyCallback(X509_STORE_CTX* ctx, void* userdata)
  952. {
  953. if (!userdata)
  954. {
  955. llwarns << "NULL userdata in callback !" << llendl;
  956. return 0;
  957. }
  958. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  959. if (op->mCallbackSSLVerify)
  960. {
  961. op->mStatus = op->mCallbackSSLVerify(op->mReqURL, op->mUserHandler,
  962. ctx);
  963. }
  964. return op->mStatus ? 1 : 0;
  965. }
  966. int HttpOpRequest::debugCallback(CURL* handle, curl_infotype info,
  967. char* buffer, size_t len, void* userdata)
  968. {
  969. if (!userdata)
  970. {
  971. llwarns << "NULL userdata in callback !" << llendl;
  972. return 0;
  973. }
  974. HttpOpRequest::ptr_t op(HttpOpRequest::fromHandle<HttpOpRequest>(userdata));
  975. std::string safe_line;
  976. std::string tag;
  977. bool logit = false;
  978. // Keep things reasonable in all cases
  979. const size_t log_len = (std::min)(len, size_t(256));
  980. switch (info)
  981. {
  982. case CURLINFO_TEXT:
  983. if (op->mTracing >= HTTP_TRACE_CURL_HEADERS)
  984. {
  985. tag = "TEXT";
  986. escape_libcurl_debug_data(buffer, log_len, true, safe_line);
  987. logit = true;
  988. }
  989. break;
  990. case CURLINFO_HEADER_IN:
  991. if (op->mTracing >= HTTP_TRACE_CURL_HEADERS)
  992. {
  993. tag = "HEADERIN";
  994. escape_libcurl_debug_data(buffer, log_len, true, safe_line);
  995. logit = true;
  996. }
  997. break;
  998. case CURLINFO_HEADER_OUT:
  999. if (op->mTracing >= HTTP_TRACE_CURL_HEADERS)
  1000. {
  1001. tag = "HEADEROUT";
  1002. // Goes out as one line
  1003. escape_libcurl_debug_data(buffer, log_len, true, safe_line);
  1004. logit = true;
  1005. }
  1006. break;
  1007. case CURLINFO_DATA_IN:
  1008. if (op->mTracing >= HTTP_TRACE_CURL_HEADERS)
  1009. {
  1010. tag = "DATAIN";
  1011. logit = true;
  1012. if (op->mTracing >= HTTP_TRACE_CURL_BODIES)
  1013. {
  1014. escape_libcurl_debug_data(buffer, log_len, false,
  1015. safe_line);
  1016. }
  1017. else
  1018. {
  1019. std::ostringstream out;
  1020. out << len << " Bytes";
  1021. safe_line = out.str();
  1022. }
  1023. }
  1024. break;
  1025. case CURLINFO_DATA_OUT:
  1026. if (op->mTracing >= HTTP_TRACE_CURL_HEADERS)
  1027. {
  1028. tag = "DATAOUT";
  1029. logit = true;
  1030. if (op->mTracing >= HTTP_TRACE_CURL_BODIES)
  1031. {
  1032. escape_libcurl_debug_data(buffer, log_len, false,
  1033. safe_line);
  1034. }
  1035. else
  1036. {
  1037. std::ostringstream out;
  1038. out << len << " Bytes";
  1039. safe_line = out.str();
  1040. }
  1041. }
  1042. break;
  1043. default:
  1044. break;
  1045. }
  1046. if (logit)
  1047. {
  1048. llinfos << "TRACE, LibcurlDebug, Handle: " << op->getHandle()
  1049. << " - Type: " << tag << " - Data: " << safe_line << llendl;
  1050. }
  1051. return 0;
  1052. }
  1053. } // End namespace LLCore
  1054. // =======================================
  1055. // Anonymous Namespace
  1056. // =======================================
  1057. namespace
  1058. {
  1059. int parse_content_range_header(char* buffer,
  1060. unsigned int* first,
  1061. unsigned int* last,
  1062. unsigned int* length)
  1063. {
  1064. static const char* const hdr_whitespace = " \t";
  1065. char* tok_state(NULL);
  1066. char* tok(NULL);
  1067. bool match = true;
  1068. if (!(tok = os_strtok_r(buffer, hdr_whitespace, &tok_state)))
  1069. {
  1070. match = false;
  1071. }
  1072. else
  1073. {
  1074. match = os_strcasecmp("bytes", tok) == 0;
  1075. }
  1076. if (match && !(tok = os_strtok_r(NULL, hdr_whitespace, &tok_state)))
  1077. {
  1078. match = false;
  1079. }
  1080. if (match)
  1081. {
  1082. unsigned int lcl_first(0), lcl_last(0), lcl_len(0);
  1083. #if LL_WINDOWS
  1084. if (3 == sscanf_s(tok, "%u-%u/%u", &lcl_first, &lcl_last, &lcl_len))
  1085. #else
  1086. if (3 == sscanf(tok, "%u-%u/%u", &lcl_first, &lcl_last, &lcl_len))
  1087. #endif // LL_WINDOWS
  1088. {
  1089. if (lcl_first > lcl_last || lcl_last >= lcl_len)
  1090. {
  1091. return -1;
  1092. }
  1093. *first = lcl_first;
  1094. *last = lcl_last;
  1095. *length = lcl_len;
  1096. return 0;
  1097. }
  1098. #if LL_WINDOWS
  1099. if (2 == sscanf_s(tok, "%u-%u/*", &lcl_first, &lcl_last))
  1100. #else
  1101. if (2 == sscanf(tok, "%u-%u/*", &lcl_first, &lcl_last))
  1102. #endif // LL_WINDOWS
  1103. {
  1104. if (lcl_first > lcl_last)
  1105. return -1;
  1106. *first = lcl_first;
  1107. *last = lcl_last;
  1108. *length = 0;
  1109. return 0;
  1110. }
  1111. }
  1112. // Header is there but badly/unexpectedly formed, try to ignore it.
  1113. return 1;
  1114. }
  1115. int parse_retry_after_header(char* buffer, int* time)
  1116. {
  1117. char* endptr = buffer;
  1118. long lcl_time = strtol(buffer, &endptr, 10);
  1119. if (*endptr == '\0' && endptr != buffer && lcl_time > 0)
  1120. {
  1121. *time = lcl_time;
  1122. return 0;
  1123. }
  1124. // Could attempt to parse HTTP time here but we're not really interested in
  1125. // it. Scheduling based on wallclock time on user hardware will lead to
  1126. // tears.
  1127. // Header is there but badly/unexpectedly formed, try to ignore it.
  1128. return 1;
  1129. }
  1130. void escape_libcurl_debug_data(char* buffer, size_t len, bool scrub,
  1131. std::string& safe_line)
  1132. {
  1133. std::string out;
  1134. len = (std::min)(len, size_t(200));
  1135. out.reserve(3 * len);
  1136. for (size_t i = 0; i < len; ++i)
  1137. {
  1138. unsigned char uc(static_cast<unsigned char>(buffer[i]));
  1139. if (uc < 32 || uc > 126)
  1140. {
  1141. if (scrub)
  1142. {
  1143. out.append(1, ' ');
  1144. }
  1145. else
  1146. {
  1147. static const char hex[] = "0123456789ABCDEF";
  1148. char convert[4];
  1149. convert[0] = '%';
  1150. convert[1] = hex[(uc >> 4) % 16];
  1151. convert[2] = hex[uc % 16];
  1152. convert[3] = '\0';
  1153. out.append(convert);
  1154. }
  1155. }
  1156. else
  1157. {
  1158. out.append(1, buffer[i]);
  1159. }
  1160. }
  1161. safe_line.swap(out);
  1162. }
  1163. int os_strcasecmp(const char* s1, const char* s2)
  1164. {
  1165. #if LL_WINDOWS
  1166. return _stricmp(s1, s2);
  1167. #else
  1168. return strcasecmp(s1, s2);
  1169. #endif // LL_WINDOWS
  1170. }
  1171. char* os_strtok_r(char* str, const char* delim, char** savestate)
  1172. {
  1173. #if LL_WINDOWS
  1174. return strtok_s(str, delim, savestate);
  1175. #else
  1176. return strtok_r(str, delim, savestate);
  1177. #endif
  1178. }
  1179. void os_strlower(char* str)
  1180. {
  1181. for (char c = 0; (c = *str); ++str)
  1182. {
  1183. *str = tolower(c);
  1184. }
  1185. }
  1186. char* os_strtrim(char* lstr)
  1187. {
  1188. while (' ' == *lstr || '\t' == *lstr)
  1189. {
  1190. ++lstr;
  1191. }
  1192. if (*lstr)
  1193. {
  1194. char* rstr = lstr + strlen(lstr);
  1195. while (lstr < rstr && *--rstr)
  1196. {
  1197. if (' ' == *rstr || '\t' == *rstr)
  1198. {
  1199. *rstr = '\0';
  1200. }
  1201. }
  1202. llassert(lstr <= rstr);
  1203. }
  1204. return lstr;
  1205. }
  1206. char* os_strltrim(char* lstr)
  1207. {
  1208. while (' ' == *lstr || '\t' == *lstr)
  1209. {
  1210. ++lstr;
  1211. }
  1212. return lstr;
  1213. }
  1214. void check_curl_easy_code(CURLcode code, int curl_setopt_option)
  1215. {
  1216. if (CURLE_OK != code)
  1217. {
  1218. // Comment from old llcurl code which may no longer apply:
  1219. // Linux appears to throw a curl error once per session for a bad
  1220. // initialization at a pretty random time (when enabling cookies).
  1221. llwarns << "libcurl error detected: " << curl_easy_strerror(code)
  1222. << ", curl_easy_setopt option: " << curl_setopt_option
  1223. << llendl;
  1224. }
  1225. }
  1226. } // end anonymous namespace