transfer.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #include "strtoofft.h"
  24. #ifdef HAVE_NETINET_IN_H
  25. #include <netinet/in.h>
  26. #endif
  27. #ifdef HAVE_NETDB_H
  28. #include <netdb.h>
  29. #endif
  30. #ifdef HAVE_ARPA_INET_H
  31. #include <arpa/inet.h>
  32. #endif
  33. #ifdef HAVE_NET_IF_H
  34. #include <net/if.h>
  35. #endif
  36. #ifdef HAVE_SYS_IOCTL_H
  37. #include <sys/ioctl.h>
  38. #endif
  39. #ifdef HAVE_SIGNAL_H
  40. #include <signal.h>
  41. #endif
  42. #ifdef HAVE_SYS_PARAM_H
  43. #include <sys/param.h>
  44. #endif
  45. #ifdef HAVE_SYS_SELECT_H
  46. #include <sys/select.h>
  47. #endif
  48. #ifndef HAVE_SOCKET
  49. #error "We can't compile without socket() support!"
  50. #endif
  51. #include "urldata.h"
  52. #include <curl/curl.h>
  53. #include "netrc.h"
  54. #include "content_encoding.h"
  55. #include "hostip.h"
  56. #include "transfer.h"
  57. #include "sendf.h"
  58. #include "speedcheck.h"
  59. #include "progress.h"
  60. #include "http.h"
  61. #include "url.h"
  62. #include "getinfo.h"
  63. #include "vtls/vtls.h"
  64. #include "select.h"
  65. #include "multiif.h"
  66. #include "connect.h"
  67. #include "non-ascii.h"
  68. #include "http2.h"
  69. #include "mime.h"
  70. #include "strcase.h"
  71. #include "urlapi-int.h"
  72. /* The last 3 #include files should be in this order */
  73. #include "curl_printf.h"
  74. #include "curl_memory.h"
  75. #include "memdebug.h"
  76. #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
  77. !defined(CURL_DISABLE_IMAP)
  78. /*
  79. * checkheaders() checks the linked list of custom headers for a
  80. * particular header (prefix). Provide the prefix without colon!
  81. *
  82. * Returns a pointer to the first matching header or NULL if none matched.
  83. */
  84. char *Curl_checkheaders(const struct connectdata *conn,
  85. const char *thisheader)
  86. {
  87. struct curl_slist *head;
  88. size_t thislen = strlen(thisheader);
  89. struct Curl_easy *data = conn->data;
  90. for(head = data->set.headers; head; head = head->next) {
  91. if(strncasecompare(head->data, thisheader, thislen) &&
  92. Curl_headersep(head->data[thislen]) )
  93. return head->data;
  94. }
  95. return NULL;
  96. }
  97. #endif
  98. CURLcode Curl_get_upload_buffer(struct Curl_easy *data)
  99. {
  100. if(!data->state.ulbuf) {
  101. data->state.ulbuf = malloc(data->set.upload_buffer_size);
  102. if(!data->state.ulbuf)
  103. return CURLE_OUT_OF_MEMORY;
  104. }
  105. return CURLE_OK;
  106. }
  107. #ifndef CURL_DISABLE_HTTP
  108. /*
  109. * This function will be called to loop through the trailers buffer
  110. * until no more data is available for sending.
  111. */
  112. static size_t Curl_trailers_read(char *buffer, size_t size, size_t nitems,
  113. void *raw)
  114. {
  115. struct Curl_easy *data = (struct Curl_easy *)raw;
  116. Curl_send_buffer *trailers_buf = data->state.trailers_buf;
  117. size_t bytes_left = trailers_buf->size_used-data->state.trailers_bytes_sent;
  118. size_t to_copy = (size*nitems < bytes_left) ? size*nitems : bytes_left;
  119. if(to_copy) {
  120. memcpy(buffer,
  121. &trailers_buf->buffer[data->state.trailers_bytes_sent],
  122. to_copy);
  123. data->state.trailers_bytes_sent += to_copy;
  124. }
  125. return to_copy;
  126. }
  127. static size_t Curl_trailers_left(void *raw)
  128. {
  129. struct Curl_easy *data = (struct Curl_easy *)raw;
  130. Curl_send_buffer *trailers_buf = data->state.trailers_buf;
  131. return trailers_buf->size_used - data->state.trailers_bytes_sent;
  132. }
  133. #endif
  134. /*
  135. * This function will call the read callback to fill our buffer with data
  136. * to upload.
  137. */
  138. CURLcode Curl_fillreadbuffer(struct connectdata *conn, size_t bytes,
  139. size_t *nreadp)
  140. {
  141. struct Curl_easy *data = conn->data;
  142. size_t buffersize = bytes;
  143. size_t nread;
  144. #ifndef CURL_DISABLE_HTTP
  145. struct curl_slist *trailers = NULL;
  146. CURLcode c;
  147. int trailers_ret_code;
  148. #endif
  149. curl_read_callback readfunc = NULL;
  150. void *extra_data = NULL;
  151. bool added_crlf = FALSE;
  152. #ifdef CURL_DOES_CONVERSIONS
  153. bool sending_http_headers = FALSE;
  154. if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
  155. const struct HTTP *http = data->req.protop;
  156. if(http->sending == HTTPSEND_REQUEST)
  157. /* We're sending the HTTP request headers, not the data.
  158. Remember that so we don't re-translate them into garbage. */
  159. sending_http_headers = TRUE;
  160. }
  161. #endif
  162. #ifndef CURL_DISABLE_HTTP
  163. if(data->state.trailers_state == TRAILERS_INITIALIZED) {
  164. /* at this point we already verified that the callback exists
  165. so we compile and store the trailers buffer, then proceed */
  166. infof(data,
  167. "Moving trailers state machine from initialized to sending.\n");
  168. data->state.trailers_state = TRAILERS_SENDING;
  169. data->state.trailers_buf = Curl_add_buffer_init();
  170. if(!data->state.trailers_buf) {
  171. failf(data, "Unable to allocate trailing headers buffer !");
  172. return CURLE_OUT_OF_MEMORY;
  173. }
  174. data->state.trailers_bytes_sent = 0;
  175. Curl_set_in_callback(data, true);
  176. trailers_ret_code = data->set.trailer_callback(&trailers,
  177. data->set.trailer_data);
  178. Curl_set_in_callback(data, false);
  179. if(trailers_ret_code == CURL_TRAILERFUNC_OK) {
  180. c = Curl_http_compile_trailers(trailers, data->state.trailers_buf, data);
  181. }
  182. else {
  183. failf(data, "operation aborted by trailing headers callback");
  184. *nreadp = 0;
  185. c = CURLE_ABORTED_BY_CALLBACK;
  186. }
  187. if(c != CURLE_OK) {
  188. Curl_add_buffer_free(&data->state.trailers_buf);
  189. curl_slist_free_all(trailers);
  190. return c;
  191. }
  192. infof(data, "Successfully compiled trailers.\r\n");
  193. curl_slist_free_all(trailers);
  194. }
  195. #endif
  196. /* if we are transmitting trailing data, we don't need to write
  197. a chunk size so we skip this */
  198. if(data->req.upload_chunky &&
  199. data->state.trailers_state == TRAILERS_NONE) {
  200. /* if chunked Transfer-Encoding */
  201. buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
  202. data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
  203. }
  204. #ifndef CURL_DISABLE_HTTP
  205. if(data->state.trailers_state == TRAILERS_SENDING) {
  206. /* if we're here then that means that we already sent the last empty chunk
  207. but we didn't send a final CR LF, so we sent 0 CR LF. We then start
  208. pulling trailing data until we ²have no more at which point we
  209. simply return to the previous point in the state machine as if
  210. nothing happened.
  211. */
  212. readfunc = Curl_trailers_read;
  213. extra_data = (void *)data;
  214. }
  215. else
  216. #endif
  217. {
  218. readfunc = data->state.fread_func;
  219. extra_data = data->state.in;
  220. }
  221. Curl_set_in_callback(data, true);
  222. nread = readfunc(data->req.upload_fromhere, 1,
  223. buffersize, extra_data);
  224. Curl_set_in_callback(data, false);
  225. if(nread == CURL_READFUNC_ABORT) {
  226. failf(data, "operation aborted by callback");
  227. *nreadp = 0;
  228. return CURLE_ABORTED_BY_CALLBACK;
  229. }
  230. if(nread == CURL_READFUNC_PAUSE) {
  231. struct SingleRequest *k = &data->req;
  232. if(conn->handler->flags & PROTOPT_NONETWORK) {
  233. /* protocols that work without network cannot be paused. This is
  234. actually only FILE:// just now, and it can't pause since the transfer
  235. isn't done using the "normal" procedure. */
  236. failf(data, "Read callback asked for PAUSE when not supported!");
  237. return CURLE_READ_ERROR;
  238. }
  239. /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
  240. k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
  241. if(data->req.upload_chunky) {
  242. /* Back out the preallocation done above */
  243. data->req.upload_fromhere -= (8 + 2);
  244. }
  245. *nreadp = 0;
  246. return CURLE_OK; /* nothing was read */
  247. }
  248. else if(nread > buffersize) {
  249. /* the read function returned a too large value */
  250. *nreadp = 0;
  251. failf(data, "read function returned funny value");
  252. return CURLE_READ_ERROR;
  253. }
  254. if(!data->req.forbidchunk && data->req.upload_chunky) {
  255. /* if chunked Transfer-Encoding
  256. * build chunk:
  257. *
  258. * <HEX SIZE> CRLF
  259. * <DATA> CRLF
  260. */
  261. /* On non-ASCII platforms the <DATA> may or may not be
  262. translated based on set.prefer_ascii while the protocol
  263. portion must always be translated to the network encoding.
  264. To further complicate matters, line end conversion might be
  265. done later on, so we need to prevent CRLFs from becoming
  266. CRCRLFs if that's the case. To do this we use bare LFs
  267. here, knowing they'll become CRLFs later on.
  268. */
  269. char hexbuffer[11] = "";
  270. int hexlen = 0;
  271. const char *endofline_native;
  272. const char *endofline_network;
  273. if(
  274. #ifdef CURL_DO_LINEEND_CONV
  275. (data->set.prefer_ascii) ||
  276. #endif
  277. (data->set.crlf)) {
  278. /* \n will become \r\n later on */
  279. endofline_native = "\n";
  280. endofline_network = "\x0a";
  281. }
  282. else {
  283. endofline_native = "\r\n";
  284. endofline_network = "\x0d\x0a";
  285. }
  286. /* if we're not handling trailing data, proceed as usual */
  287. if(data->state.trailers_state != TRAILERS_SENDING) {
  288. hexlen = msnprintf(hexbuffer, sizeof(hexbuffer),
  289. "%zx%s", nread, endofline_native);
  290. /* move buffer pointer */
  291. data->req.upload_fromhere -= hexlen;
  292. nread += hexlen;
  293. /* copy the prefix to the buffer, leaving out the NUL */
  294. memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
  295. /* always append ASCII CRLF to the data unless
  296. we have a valid trailer callback */
  297. #ifndef CURL_DISABLE_HTTP
  298. if((nread-hexlen) == 0 &&
  299. data->set.trailer_callback != NULL &&
  300. data->state.trailers_state == TRAILERS_NONE) {
  301. data->state.trailers_state = TRAILERS_INITIALIZED;
  302. }
  303. else
  304. #endif
  305. {
  306. memcpy(data->req.upload_fromhere + nread,
  307. endofline_network,
  308. strlen(endofline_network));
  309. added_crlf = TRUE;
  310. }
  311. }
  312. #ifdef CURL_DOES_CONVERSIONS
  313. {
  314. CURLcode result;
  315. size_t length;
  316. if(data->set.prefer_ascii)
  317. /* translate the protocol and data */
  318. length = nread;
  319. else
  320. /* just translate the protocol portion */
  321. length = hexlen;
  322. if(length) {
  323. result = Curl_convert_to_network(data, data->req.upload_fromhere,
  324. length);
  325. /* Curl_convert_to_network calls failf if unsuccessful */
  326. if(result)
  327. return result;
  328. }
  329. }
  330. #endif /* CURL_DOES_CONVERSIONS */
  331. #ifndef CURL_DISABLE_HTTP
  332. if(data->state.trailers_state == TRAILERS_SENDING &&
  333. !Curl_trailers_left(data)) {
  334. Curl_add_buffer_free(&data->state.trailers_buf);
  335. data->state.trailers_state = TRAILERS_DONE;
  336. data->set.trailer_data = NULL;
  337. data->set.trailer_callback = NULL;
  338. /* mark the transfer as done */
  339. data->req.upload_done = TRUE;
  340. infof(data, "Signaling end of chunked upload after trailers.\n");
  341. }
  342. else
  343. #endif
  344. if((nread - hexlen) == 0 &&
  345. data->state.trailers_state != TRAILERS_INITIALIZED) {
  346. /* mark this as done once this chunk is transferred */
  347. data->req.upload_done = TRUE;
  348. infof(data,
  349. "Signaling end of chunked upload via terminating chunk.\n");
  350. }
  351. if(added_crlf)
  352. nread += strlen(endofline_network); /* for the added end of line */
  353. }
  354. #ifdef CURL_DOES_CONVERSIONS
  355. else if((data->set.prefer_ascii) && (!sending_http_headers)) {
  356. CURLcode result;
  357. result = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
  358. /* Curl_convert_to_network calls failf if unsuccessful */
  359. if(result)
  360. return result;
  361. }
  362. #endif /* CURL_DOES_CONVERSIONS */
  363. *nreadp = nread;
  364. return CURLE_OK;
  365. }
  366. /*
  367. * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
  368. * POST/PUT with multi-pass authentication when a sending was denied and a
  369. * resend is necessary.
  370. */
  371. CURLcode Curl_readrewind(struct connectdata *conn)
  372. {
  373. struct Curl_easy *data = conn->data;
  374. curl_mimepart *mimepart = &data->set.mimepost;
  375. conn->bits.rewindaftersend = FALSE; /* we rewind now */
  376. /* explicitly switch off sending data on this connection now since we are
  377. about to restart a new transfer and thus we want to avoid inadvertently
  378. sending more data on the existing connection until the next transfer
  379. starts */
  380. data->req.keepon &= ~KEEP_SEND;
  381. /* We have sent away data. If not using CURLOPT_POSTFIELDS or
  382. CURLOPT_HTTPPOST, call app to rewind
  383. */
  384. if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
  385. struct HTTP *http = data->req.protop;
  386. if(http->sendit)
  387. mimepart = http->sendit;
  388. }
  389. if(data->set.postfields)
  390. ; /* do nothing */
  391. else if(data->set.httpreq == HTTPREQ_POST_MIME ||
  392. data->set.httpreq == HTTPREQ_POST_FORM) {
  393. if(Curl_mime_rewind(mimepart)) {
  394. failf(data, "Cannot rewind mime/post data");
  395. return CURLE_SEND_FAIL_REWIND;
  396. }
  397. }
  398. else {
  399. if(data->set.seek_func) {
  400. int err;
  401. Curl_set_in_callback(data, true);
  402. err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
  403. Curl_set_in_callback(data, false);
  404. if(err) {
  405. failf(data, "seek callback returned error %d", (int)err);
  406. return CURLE_SEND_FAIL_REWIND;
  407. }
  408. }
  409. else if(data->set.ioctl_func) {
  410. curlioerr err;
  411. Curl_set_in_callback(data, true);
  412. err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
  413. data->set.ioctl_client);
  414. Curl_set_in_callback(data, false);
  415. infof(data, "the ioctl callback returned %d\n", (int)err);
  416. if(err) {
  417. /* FIXME: convert to a human readable error message */
  418. failf(data, "ioctl callback returned error %d", (int)err);
  419. return CURLE_SEND_FAIL_REWIND;
  420. }
  421. }
  422. else {
  423. /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
  424. given FILE * stream and we can actually attempt to rewind that
  425. ourselves with fseek() */
  426. if(data->state.fread_func == (curl_read_callback)fread) {
  427. if(-1 != fseek(data->state.in, 0, SEEK_SET))
  428. /* successful rewind */
  429. return CURLE_OK;
  430. }
  431. /* no callback set or failure above, makes us fail at once */
  432. failf(data, "necessary data rewind wasn't possible");
  433. return CURLE_SEND_FAIL_REWIND;
  434. }
  435. }
  436. return CURLE_OK;
  437. }
  438. static int data_pending(const struct connectdata *conn)
  439. {
  440. /* in the case of libssh2, we can never be really sure that we have emptied
  441. its internal buffers so we MUST always try until we get EAGAIN back */
  442. return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) ||
  443. #if defined(USE_NGHTTP2)
  444. Curl_ssl_data_pending(conn, FIRSTSOCKET) ||
  445. /* For HTTP/2, we may read up everything including response body
  446. with header fields in Curl_http_readwrite_headers. If no
  447. content-length is provided, curl waits for the connection
  448. close, which we emulate it using conn->proto.httpc.closed =
  449. TRUE. The thing is if we read everything, then http2_recv won't
  450. be called and we cannot signal the HTTP/2 stream has closed. As
  451. a workaround, we return nonzero here to call http2_recv. */
  452. ((conn->handler->protocol&PROTO_FAMILY_HTTP) && conn->httpversion == 20);
  453. #else
  454. Curl_ssl_data_pending(conn, FIRSTSOCKET);
  455. #endif
  456. }
  457. static void read_rewind(struct connectdata *conn,
  458. size_t thismuch)
  459. {
  460. DEBUGASSERT(conn->read_pos >= thismuch);
  461. conn->read_pos -= thismuch;
  462. conn->bits.stream_was_rewound = TRUE;
  463. #ifdef DEBUGBUILD
  464. {
  465. char buf[512 + 1];
  466. size_t show;
  467. show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
  468. if(conn->master_buffer) {
  469. memcpy(buf, conn->master_buffer + conn->read_pos, show);
  470. buf[show] = '\0';
  471. }
  472. else {
  473. buf[0] = '\0';
  474. }
  475. DEBUGF(infof(conn->data,
  476. "Buffer after stream rewind (read_pos = %zu): [%s]\n",
  477. conn->read_pos, buf));
  478. }
  479. #endif
  480. }
  481. /*
  482. * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the
  483. * remote document with the time provided by CURLOPT_TIMEVAL
  484. */
  485. bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
  486. {
  487. if((timeofdoc == 0) || (data->set.timevalue == 0))
  488. return TRUE;
  489. switch(data->set.timecondition) {
  490. case CURL_TIMECOND_IFMODSINCE:
  491. default:
  492. if(timeofdoc <= data->set.timevalue) {
  493. infof(data,
  494. "The requested document is not new enough\n");
  495. data->info.timecond = TRUE;
  496. return FALSE;
  497. }
  498. break;
  499. case CURL_TIMECOND_IFUNMODSINCE:
  500. if(timeofdoc >= data->set.timevalue) {
  501. infof(data,
  502. "The requested document is not old enough\n");
  503. data->info.timecond = TRUE;
  504. return FALSE;
  505. }
  506. break;
  507. }
  508. return TRUE;
  509. }
  510. /*
  511. * Go ahead and do a read if we have a readable socket or if
  512. * the stream was rewound (in which case we have data in a
  513. * buffer)
  514. *
  515. * return '*comeback' TRUE if we didn't properly drain the socket so this
  516. * function should get called again without select() or similar in between!
  517. */
  518. static CURLcode readwrite_data(struct Curl_easy *data,
  519. struct connectdata *conn,
  520. struct SingleRequest *k,
  521. int *didwhat, bool *done,
  522. bool *comeback)
  523. {
  524. CURLcode result = CURLE_OK;
  525. ssize_t nread; /* number of bytes read */
  526. size_t excess = 0; /* excess bytes read */
  527. bool readmore = FALSE; /* used by RTP to signal for more data */
  528. int maxloops = 100;
  529. *done = FALSE;
  530. *comeback = FALSE;
  531. /* This is where we loop until we have read everything there is to
  532. read or we get a CURLE_AGAIN */
  533. do {
  534. bool is_empty_data = FALSE;
  535. size_t buffersize = data->set.buffer_size;
  536. size_t bytestoread = buffersize;
  537. if(
  538. #if defined(USE_NGHTTP2)
  539. /* For HTTP/2, read data without caring about the content
  540. length. This is safe because body in HTTP/2 is always
  541. segmented thanks to its framing layer. Meanwhile, we have to
  542. call Curl_read to ensure that http2_handle_stream_close is
  543. called when we read all incoming bytes for a particular
  544. stream. */
  545. !((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  546. conn->httpversion == 20) &&
  547. #endif
  548. k->size != -1 && !k->header) {
  549. /* make sure we don't read "too much" if we can help it since we
  550. might be pipelining and then someone else might want to read what
  551. follows! */
  552. curl_off_t totalleft = k->size - k->bytecount;
  553. if(totalleft < (curl_off_t)bytestoread)
  554. bytestoread = (size_t)totalleft;
  555. }
  556. if(bytestoread) {
  557. /* receive data from the network! */
  558. result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
  559. /* read would've blocked */
  560. if(CURLE_AGAIN == result)
  561. break; /* get out of loop */
  562. if(result>0)
  563. return result;
  564. }
  565. else {
  566. /* read nothing but since we wanted nothing we consider this an OK
  567. situation to proceed from */
  568. DEBUGF(infof(data, "readwrite_data: we're done!\n"));
  569. nread = 0;
  570. }
  571. if((k->bytecount == 0) && (k->writebytecount == 0)) {
  572. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  573. if(k->exp100 > EXP100_SEND_DATA)
  574. /* set time stamp to compare with when waiting for the 100 */
  575. k->start100 = Curl_now();
  576. }
  577. *didwhat |= KEEP_RECV;
  578. /* indicates data of zero size, i.e. empty file */
  579. is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE;
  580. /* NUL terminate, allowing string ops to be used */
  581. if(0 < nread || is_empty_data) {
  582. k->buf[nread] = 0;
  583. }
  584. else if(0 >= nread) {
  585. /* if we receive 0 or less here, the server closed the connection
  586. and we bail out from this! */
  587. DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
  588. k->keepon &= ~KEEP_RECV;
  589. break;
  590. }
  591. /* Default buffer to use when we write the buffer, it may be changed
  592. in the flow below before the actual storing is done. */
  593. k->str = k->buf;
  594. if(conn->handler->readwrite) {
  595. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  596. if(result)
  597. return result;
  598. if(readmore)
  599. break;
  600. }
  601. #ifndef CURL_DISABLE_HTTP
  602. /* Since this is a two-state thing, we check if we are parsing
  603. headers at the moment or not. */
  604. if(k->header) {
  605. /* we are in parse-the-header-mode */
  606. bool stop_reading = FALSE;
  607. result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
  608. if(result)
  609. return result;
  610. if(conn->handler->readwrite &&
  611. (k->maxdownload <= 0 && nread > 0)) {
  612. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  613. if(result)
  614. return result;
  615. if(readmore)
  616. break;
  617. }
  618. if(stop_reading) {
  619. /* We've stopped dealing with input, get out of the do-while loop */
  620. if(nread > 0) {
  621. if(Curl_pipeline_wanted(conn->data->multi, CURLPIPE_HTTP1)) {
  622. infof(data,
  623. "Rewinding stream by : %zd"
  624. " bytes on url %s (zero-length body)\n",
  625. nread, data->state.up.path);
  626. read_rewind(conn, (size_t)nread);
  627. }
  628. else {
  629. infof(data,
  630. "Excess found in a non pipelined read:"
  631. " excess = %zd"
  632. " url = %s (zero-length body)\n",
  633. nread, data->state.up.path);
  634. }
  635. }
  636. break;
  637. }
  638. }
  639. #endif /* CURL_DISABLE_HTTP */
  640. /* This is not an 'else if' since it may be a rest from the header
  641. parsing, where the beginning of the buffer is headers and the end
  642. is non-headers. */
  643. if(k->str && !k->header && (nread > 0 || is_empty_data)) {
  644. if(data->set.opt_no_body) {
  645. /* data arrives although we want none, bail out */
  646. streamclose(conn, "ignoring body");
  647. *done = TRUE;
  648. return CURLE_WEIRD_SERVER_REPLY;
  649. }
  650. #ifndef CURL_DISABLE_HTTP
  651. if(0 == k->bodywrites && !is_empty_data) {
  652. /* These checks are only made the first time we are about to
  653. write a piece of the body */
  654. if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
  655. /* HTTP-only checks */
  656. if(data->req.newurl) {
  657. if(conn->bits.close) {
  658. /* Abort after the headers if "follow Location" is set
  659. and we're set to close anyway. */
  660. k->keepon &= ~KEEP_RECV;
  661. *done = TRUE;
  662. return CURLE_OK;
  663. }
  664. /* We have a new url to load, but since we want to be able
  665. to re-use this connection properly, we read the full
  666. response in "ignore more" */
  667. k->ignorebody = TRUE;
  668. infof(data, "Ignoring the response-body\n");
  669. }
  670. if(data->state.resume_from && !k->content_range &&
  671. (data->set.httpreq == HTTPREQ_GET) &&
  672. !k->ignorebody) {
  673. if(k->size == data->state.resume_from) {
  674. /* The resume point is at the end of file, consider this fine
  675. even if it doesn't allow resume from here. */
  676. infof(data, "The entire document is already downloaded");
  677. connclose(conn, "already downloaded");
  678. /* Abort download */
  679. k->keepon &= ~KEEP_RECV;
  680. *done = TRUE;
  681. return CURLE_OK;
  682. }
  683. /* we wanted to resume a download, although the server doesn't
  684. * seem to support this and we did this with a GET (if it
  685. * wasn't a GET we did a POST or PUT resume) */
  686. failf(data, "HTTP server doesn't seem to support "
  687. "byte ranges. Cannot resume.");
  688. return CURLE_RANGE_ERROR;
  689. }
  690. if(data->set.timecondition && !data->state.range) {
  691. /* A time condition has been set AND no ranges have been
  692. requested. This seems to be what chapter 13.3.4 of
  693. RFC 2616 defines to be the correct action for a
  694. HTTP/1.1 client */
  695. if(!Curl_meets_timecondition(data, k->timeofdoc)) {
  696. *done = TRUE;
  697. /* We're simulating a http 304 from server so we return
  698. what should have been returned from the server */
  699. data->info.httpcode = 304;
  700. infof(data, "Simulate a HTTP 304 response!\n");
  701. /* we abort the transfer before it is completed == we ruin the
  702. re-use ability. Close the connection */
  703. connclose(conn, "Simulated 304 handling");
  704. return CURLE_OK;
  705. }
  706. } /* we have a time condition */
  707. } /* this is HTTP or RTSP */
  708. } /* this is the first time we write a body part */
  709. #endif /* CURL_DISABLE_HTTP */
  710. k->bodywrites++;
  711. /* pass data to the debug function before it gets "dechunked" */
  712. if(data->set.verbose) {
  713. if(k->badheader) {
  714. Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
  715. (size_t)k->hbuflen);
  716. if(k->badheader == HEADER_PARTHEADER)
  717. Curl_debug(data, CURLINFO_DATA_IN,
  718. k->str, (size_t)nread);
  719. }
  720. else
  721. Curl_debug(data, CURLINFO_DATA_IN,
  722. k->str, (size_t)nread);
  723. }
  724. #ifndef CURL_DISABLE_HTTP
  725. if(k->chunk) {
  726. /*
  727. * Here comes a chunked transfer flying and we need to decode this
  728. * properly. While the name says read, this function both reads
  729. * and writes away the data. The returned 'nread' holds the number
  730. * of actual data it wrote to the client.
  731. */
  732. CHUNKcode res =
  733. Curl_httpchunk_read(conn, k->str, nread, &nread);
  734. if(CHUNKE_OK < res) {
  735. if(CHUNKE_WRITE_ERROR == res) {
  736. failf(data, "Failed writing data");
  737. return CURLE_WRITE_ERROR;
  738. }
  739. failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res));
  740. return CURLE_RECV_ERROR;
  741. }
  742. if(CHUNKE_STOP == res) {
  743. size_t dataleft;
  744. /* we're done reading chunks! */
  745. k->keepon &= ~KEEP_RECV; /* read no more */
  746. /* There are now possibly N number of bytes at the end of the
  747. str buffer that weren't written to the client.
  748. We DO care about this data if we are pipelining.
  749. Push it back to be read on the next pass. */
  750. dataleft = conn->chunk.dataleft;
  751. if(dataleft != 0) {
  752. infof(conn->data, "Leftovers after chunking: %zu bytes\n",
  753. dataleft);
  754. if(Curl_pipeline_wanted(conn->data->multi, CURLPIPE_HTTP1)) {
  755. /* only attempt the rewind if we truly are pipelining */
  756. infof(conn->data, "Rewinding %zu bytes\n",dataleft);
  757. read_rewind(conn, dataleft);
  758. }
  759. }
  760. }
  761. /* If it returned OK, we just keep going */
  762. }
  763. #endif /* CURL_DISABLE_HTTP */
  764. /* Account for body content stored in the header buffer */
  765. if((k->badheader == HEADER_PARTHEADER) && !k->ignorebody) {
  766. DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n",
  767. k->hbuflen));
  768. k->bytecount += k->hbuflen;
  769. }
  770. if((-1 != k->maxdownload) &&
  771. (k->bytecount + nread >= k->maxdownload)) {
  772. excess = (size_t)(k->bytecount + nread - k->maxdownload);
  773. if(excess > 0 && !k->ignorebody) {
  774. if(Curl_pipeline_wanted(conn->data->multi, CURLPIPE_HTTP1)) {
  775. infof(data,
  776. "Rewinding stream by : %zu"
  777. " bytes on url %s (size = %" CURL_FORMAT_CURL_OFF_T
  778. ", maxdownload = %" CURL_FORMAT_CURL_OFF_T
  779. ", bytecount = %" CURL_FORMAT_CURL_OFF_T ", nread = %zd)\n",
  780. excess, data->state.up.path,
  781. k->size, k->maxdownload, k->bytecount, nread);
  782. read_rewind(conn, excess);
  783. }
  784. else {
  785. infof(data,
  786. "Excess found in a non pipelined read:"
  787. " excess = %zu"
  788. ", size = %" CURL_FORMAT_CURL_OFF_T
  789. ", maxdownload = %" CURL_FORMAT_CURL_OFF_T
  790. ", bytecount = %" CURL_FORMAT_CURL_OFF_T "\n",
  791. excess, k->size, k->maxdownload, k->bytecount);
  792. }
  793. }
  794. nread = (ssize_t) (k->maxdownload - k->bytecount);
  795. if(nread < 0) /* this should be unusual */
  796. nread = 0;
  797. k->keepon &= ~KEEP_RECV; /* we're done reading */
  798. }
  799. k->bytecount += nread;
  800. Curl_pgrsSetDownloadCounter(data, k->bytecount);
  801. if(!k->chunk && (nread || k->badheader || is_empty_data)) {
  802. /* If this is chunky transfer, it was already written */
  803. if(k->badheader && !k->ignorebody) {
  804. /* we parsed a piece of data wrongly assuming it was a header
  805. and now we output it as body instead */
  806. /* Don't let excess data pollute body writes */
  807. if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload)
  808. result = Curl_client_write(conn, CLIENTWRITE_BODY,
  809. data->state.headerbuff,
  810. k->hbuflen);
  811. else
  812. result = Curl_client_write(conn, CLIENTWRITE_BODY,
  813. data->state.headerbuff,
  814. (size_t)k->maxdownload);
  815. if(result)
  816. return result;
  817. }
  818. if(k->badheader < HEADER_ALLBAD) {
  819. /* This switch handles various content encodings. If there's an
  820. error here, be sure to check over the almost identical code
  821. in http_chunks.c.
  822. Make sure that ALL_CONTENT_ENCODINGS contains all the
  823. encodings handled here. */
  824. if(conn->data->set.http_ce_skip || !k->writer_stack) {
  825. if(!k->ignorebody) {
  826. #ifndef CURL_DISABLE_POP3
  827. if(conn->handler->protocol & PROTO_FAMILY_POP3)
  828. result = Curl_pop3_write(conn, k->str, nread);
  829. else
  830. #endif /* CURL_DISABLE_POP3 */
  831. result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
  832. nread);
  833. }
  834. }
  835. else if(!k->ignorebody)
  836. result = Curl_unencode_write(conn, k->writer_stack, k->str, nread);
  837. }
  838. k->badheader = HEADER_NORMAL; /* taken care of now */
  839. if(result)
  840. return result;
  841. }
  842. } /* if(!header and data to read) */
  843. if(conn->handler->readwrite && excess && !conn->bits.stream_was_rewound) {
  844. /* Parse the excess data */
  845. k->str += nread;
  846. if(&k->str[excess] > &k->buf[data->set.buffer_size]) {
  847. /* the excess amount was too excessive(!), make sure
  848. it doesn't read out of buffer */
  849. excess = &k->buf[data->set.buffer_size] - k->str;
  850. }
  851. nread = (ssize_t)excess;
  852. result = conn->handler->readwrite(data, conn, &nread, &readmore);
  853. if(result)
  854. return result;
  855. if(readmore)
  856. k->keepon |= KEEP_RECV; /* we're not done reading */
  857. break;
  858. }
  859. if(is_empty_data) {
  860. /* if we received nothing, the server closed the connection and we
  861. are done */
  862. k->keepon &= ~KEEP_RECV;
  863. }
  864. if(k->keepon & KEEP_RECV_PAUSE) {
  865. /* this is a paused transfer */
  866. break;
  867. }
  868. } while(data_pending(conn) && maxloops--);
  869. if(maxloops <= 0) {
  870. /* we mark it as read-again-please */
  871. conn->cselect_bits = CURL_CSELECT_IN;
  872. *comeback = TRUE;
  873. }
  874. if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
  875. conn->bits.close) {
  876. /* When we've read the entire thing and the close bit is set, the server
  877. may now close the connection. If there's now any kind of sending going
  878. on from our side, we need to stop that immediately. */
  879. infof(data, "we are done reading and this is set to close, stop send\n");
  880. k->keepon &= ~KEEP_SEND; /* no writing anymore either */
  881. }
  882. return CURLE_OK;
  883. }
  884. static CURLcode done_sending(struct connectdata *conn,
  885. struct SingleRequest *k)
  886. {
  887. k->keepon &= ~KEEP_SEND; /* we're done writing */
  888. Curl_http2_done_sending(conn);
  889. if(conn->bits.rewindaftersend) {
  890. CURLcode result = Curl_readrewind(conn);
  891. if(result)
  892. return result;
  893. }
  894. return CURLE_OK;
  895. }
  896. #if defined(WIN32) && !defined(USE_LWIPSOCK)
  897. #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY
  898. #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B
  899. #endif
  900. static void win_update_buffer_size(curl_socket_t sockfd)
  901. {
  902. int result;
  903. ULONG ideal;
  904. DWORD ideallen;
  905. result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0,
  906. &ideal, sizeof(ideal), &ideallen, 0, 0);
  907. if(result == 0) {
  908. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF,
  909. (const char *)&ideal, sizeof(ideal));
  910. }
  911. }
  912. #else
  913. #define win_update_buffer_size(x)
  914. #endif
  915. /*
  916. * Send data to upload to the server, when the socket is writable.
  917. */
  918. static CURLcode readwrite_upload(struct Curl_easy *data,
  919. struct connectdata *conn,
  920. int *didwhat)
  921. {
  922. ssize_t i, si;
  923. ssize_t bytes_written;
  924. CURLcode result;
  925. ssize_t nread; /* number of bytes read */
  926. bool sending_http_headers = FALSE;
  927. struct SingleRequest *k = &data->req;
  928. if((k->bytecount == 0) && (k->writebytecount == 0))
  929. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  930. *didwhat |= KEEP_SEND;
  931. do {
  932. /* only read more data if there's no upload data already
  933. present in the upload buffer */
  934. if(0 == k->upload_present) {
  935. result = Curl_get_upload_buffer(data);
  936. if(result)
  937. return result;
  938. /* init the "upload from here" pointer */
  939. k->upload_fromhere = data->state.ulbuf;
  940. if(!k->upload_done) {
  941. /* HTTP pollution, this should be written nicer to become more
  942. protocol agnostic. */
  943. size_t fillcount;
  944. struct HTTP *http = k->protop;
  945. if((k->exp100 == EXP100_SENDING_REQUEST) &&
  946. (http->sending == HTTPSEND_BODY)) {
  947. /* If this call is to send body data, we must take some action:
  948. We have sent off the full HTTP 1.1 request, and we shall now
  949. go into the Expect: 100 state and await such a header */
  950. k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
  951. k->keepon &= ~KEEP_SEND; /* disable writing */
  952. k->start100 = Curl_now(); /* timeout count starts now */
  953. *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
  954. /* set a timeout for the multi interface */
  955. Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
  956. break;
  957. }
  958. if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) {
  959. if(http->sending == HTTPSEND_REQUEST)
  960. /* We're sending the HTTP request headers, not the data.
  961. Remember that so we don't change the line endings. */
  962. sending_http_headers = TRUE;
  963. else
  964. sending_http_headers = FALSE;
  965. }
  966. result = Curl_fillreadbuffer(conn, data->set.upload_buffer_size,
  967. &fillcount);
  968. if(result)
  969. return result;
  970. nread = fillcount;
  971. }
  972. else
  973. nread = 0; /* we're done uploading/reading */
  974. if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
  975. /* this is a paused transfer */
  976. break;
  977. }
  978. if(nread <= 0) {
  979. result = done_sending(conn, k);
  980. if(result)
  981. return result;
  982. break;
  983. }
  984. /* store number of bytes available for upload */
  985. k->upload_present = nread;
  986. /* convert LF to CRLF if so asked */
  987. if((!sending_http_headers) && (
  988. #ifdef CURL_DO_LINEEND_CONV
  989. /* always convert if we're FTPing in ASCII mode */
  990. (data->set.prefer_ascii) ||
  991. #endif
  992. (data->set.crlf))) {
  993. /* Do we need to allocate a scratch buffer? */
  994. if(!data->state.scratch) {
  995. data->state.scratch = malloc(2 * data->set.upload_buffer_size);
  996. if(!data->state.scratch) {
  997. failf(data, "Failed to alloc scratch buffer!");
  998. return CURLE_OUT_OF_MEMORY;
  999. }
  1000. }
  1001. /*
  1002. * ASCII/EBCDIC Note: This is presumably a text (not binary)
  1003. * transfer so the data should already be in ASCII.
  1004. * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
  1005. * must be used instead of the escape sequences \r & \n.
  1006. */
  1007. for(i = 0, si = 0; i < nread; i++, si++) {
  1008. if(k->upload_fromhere[i] == 0x0a) {
  1009. data->state.scratch[si++] = 0x0d;
  1010. data->state.scratch[si] = 0x0a;
  1011. if(!data->set.crlf) {
  1012. /* we're here only because FTP is in ASCII mode...
  1013. bump infilesize for the LF we just added */
  1014. if(data->state.infilesize != -1)
  1015. data->state.infilesize++;
  1016. }
  1017. }
  1018. else
  1019. data->state.scratch[si] = k->upload_fromhere[i];
  1020. }
  1021. if(si != nread) {
  1022. /* only perform the special operation if we really did replace
  1023. anything */
  1024. nread = si;
  1025. /* upload from the new (replaced) buffer instead */
  1026. k->upload_fromhere = data->state.scratch;
  1027. /* set the new amount too */
  1028. k->upload_present = nread;
  1029. }
  1030. }
  1031. #ifndef CURL_DISABLE_SMTP
  1032. if(conn->handler->protocol & PROTO_FAMILY_SMTP) {
  1033. result = Curl_smtp_escape_eob(conn, nread);
  1034. if(result)
  1035. return result;
  1036. }
  1037. #endif /* CURL_DISABLE_SMTP */
  1038. } /* if 0 == k->upload_present */
  1039. else {
  1040. /* We have a partial buffer left from a previous "round". Use
  1041. that instead of reading more data */
  1042. }
  1043. /* write to socket (send away data) */
  1044. result = Curl_write(conn,
  1045. conn->writesockfd, /* socket to send to */
  1046. k->upload_fromhere, /* buffer pointer */
  1047. k->upload_present, /* buffer size */
  1048. &bytes_written); /* actually sent */
  1049. if(result)
  1050. return result;
  1051. win_update_buffer_size(conn->writesockfd);
  1052. if(data->set.verbose)
  1053. /* show the data before we change the pointer upload_fromhere */
  1054. Curl_debug(data, CURLINFO_DATA_OUT, k->upload_fromhere,
  1055. (size_t)bytes_written);
  1056. k->writebytecount += bytes_written;
  1057. Curl_pgrsSetUploadCounter(data, k->writebytecount);
  1058. if((!k->upload_chunky || k->forbidchunk) &&
  1059. (k->writebytecount == data->state.infilesize)) {
  1060. /* we have sent all data we were supposed to */
  1061. k->upload_done = TRUE;
  1062. infof(data, "We are completely uploaded and fine\n");
  1063. }
  1064. if(k->upload_present != bytes_written) {
  1065. /* we only wrote a part of the buffer (if anything), deal with it! */
  1066. /* store the amount of bytes left in the buffer to write */
  1067. k->upload_present -= bytes_written;
  1068. /* advance the pointer where to find the buffer when the next send
  1069. is to happen */
  1070. k->upload_fromhere += bytes_written;
  1071. }
  1072. else {
  1073. /* we've uploaded that buffer now */
  1074. result = Curl_get_upload_buffer(data);
  1075. if(result)
  1076. return result;
  1077. k->upload_fromhere = data->state.ulbuf;
  1078. k->upload_present = 0; /* no more bytes left */
  1079. if(k->upload_done) {
  1080. result = done_sending(conn, k);
  1081. if(result)
  1082. return result;
  1083. }
  1084. }
  1085. } WHILE_FALSE; /* just to break out from! */
  1086. return CURLE_OK;
  1087. }
  1088. /*
  1089. * Curl_readwrite() is the low-level function to be called when data is to
  1090. * be read and written to/from the connection.
  1091. *
  1092. * return '*comeback' TRUE if we didn't properly drain the socket so this
  1093. * function should get called again without select() or similar in between!
  1094. */
  1095. CURLcode Curl_readwrite(struct connectdata *conn,
  1096. struct Curl_easy *data,
  1097. bool *done,
  1098. bool *comeback)
  1099. {
  1100. struct SingleRequest *k = &data->req;
  1101. CURLcode result;
  1102. int didwhat = 0;
  1103. curl_socket_t fd_read;
  1104. curl_socket_t fd_write;
  1105. int select_res = conn->cselect_bits;
  1106. conn->cselect_bits = 0;
  1107. /* only use the proper socket if the *_HOLD bit is not set simultaneously as
  1108. then we are in rate limiting state in that transfer direction */
  1109. if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
  1110. fd_read = conn->sockfd;
  1111. else
  1112. fd_read = CURL_SOCKET_BAD;
  1113. if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
  1114. fd_write = conn->writesockfd;
  1115. else
  1116. fd_write = CURL_SOCKET_BAD;
  1117. if(conn->data->state.drain) {
  1118. select_res |= CURL_CSELECT_IN;
  1119. DEBUGF(infof(data, "Curl_readwrite: forcibly told to drain data\n"));
  1120. }
  1121. if(!select_res) /* Call for select()/poll() only, if read/write/error
  1122. status is not known. */
  1123. select_res = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0);
  1124. if(select_res == CURL_CSELECT_ERR) {
  1125. failf(data, "select/poll returned error");
  1126. return CURLE_SEND_ERROR;
  1127. }
  1128. /* We go ahead and do a read if we have a readable socket or if
  1129. the stream was rewound (in which case we have data in a
  1130. buffer) */
  1131. if((k->keepon & KEEP_RECV) &&
  1132. ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
  1133. result = readwrite_data(data, conn, k, &didwhat, done, comeback);
  1134. if(result || *done)
  1135. return result;
  1136. }
  1137. /* If we still have writing to do, we check if we have a writable socket. */
  1138. if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
  1139. /* write */
  1140. result = readwrite_upload(data, conn, &didwhat);
  1141. if(result)
  1142. return result;
  1143. }
  1144. k->now = Curl_now();
  1145. if(didwhat) {
  1146. ;
  1147. }
  1148. else {
  1149. /* no read no write, this is a timeout? */
  1150. if(k->exp100 == EXP100_AWAITING_CONTINUE) {
  1151. /* This should allow some time for the header to arrive, but only a
  1152. very short time as otherwise it'll be too much wasted time too
  1153. often. */
  1154. /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
  1155. Therefore, when a client sends this header field to an origin server
  1156. (possibly via a proxy) from which it has never seen a 100 (Continue)
  1157. status, the client SHOULD NOT wait for an indefinite period before
  1158. sending the request body.
  1159. */
  1160. timediff_t ms = Curl_timediff(k->now, k->start100);
  1161. if(ms >= data->set.expect_100_timeout) {
  1162. /* we've waited long enough, continue anyway */
  1163. k->exp100 = EXP100_SEND_DATA;
  1164. k->keepon |= KEEP_SEND;
  1165. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  1166. infof(data, "Done waiting for 100-continue\n");
  1167. }
  1168. }
  1169. }
  1170. if(Curl_pgrsUpdate(conn))
  1171. result = CURLE_ABORTED_BY_CALLBACK;
  1172. else
  1173. result = Curl_speedcheck(data, k->now);
  1174. if(result)
  1175. return result;
  1176. if(k->keepon) {
  1177. if(0 > Curl_timeleft(data, &k->now, FALSE)) {
  1178. if(k->size != -1) {
  1179. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1180. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %"
  1181. CURL_FORMAT_CURL_OFF_T " bytes received",
  1182. Curl_timediff(k->now, data->progress.t_startsingle),
  1183. k->bytecount, k->size);
  1184. }
  1185. else {
  1186. failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T
  1187. " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received",
  1188. Curl_timediff(k->now, data->progress.t_startsingle),
  1189. k->bytecount);
  1190. }
  1191. return CURLE_OPERATION_TIMEDOUT;
  1192. }
  1193. }
  1194. else {
  1195. /*
  1196. * The transfer has been performed. Just make some general checks before
  1197. * returning.
  1198. */
  1199. if(!(data->set.opt_no_body) && (k->size != -1) &&
  1200. (k->bytecount != k->size) &&
  1201. #ifdef CURL_DO_LINEEND_CONV
  1202. /* Most FTP servers don't adjust their file SIZE response for CRLFs,
  1203. so we'll check to see if the discrepancy can be explained
  1204. by the number of CRLFs we've changed to LFs.
  1205. */
  1206. (k->bytecount != (k->size + data->state.crlf_conversions)) &&
  1207. #endif /* CURL_DO_LINEEND_CONV */
  1208. !k->newurl) {
  1209. failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T
  1210. " bytes remaining to read", k->size - k->bytecount);
  1211. return CURLE_PARTIAL_FILE;
  1212. }
  1213. if(!(data->set.opt_no_body) && k->chunk &&
  1214. (conn->chunk.state != CHUNK_STOP)) {
  1215. /*
  1216. * In chunked mode, return an error if the connection is closed prior to
  1217. * the empty (terminating) chunk is read.
  1218. *
  1219. * The condition above used to check for
  1220. * conn->proto.http->chunk.datasize != 0 which is true after reading
  1221. * *any* chunk, not just the empty chunk.
  1222. *
  1223. */
  1224. failf(data, "transfer closed with outstanding read data remaining");
  1225. return CURLE_PARTIAL_FILE;
  1226. }
  1227. if(Curl_pgrsUpdate(conn))
  1228. return CURLE_ABORTED_BY_CALLBACK;
  1229. }
  1230. /* Now update the "done" boolean we return */
  1231. *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
  1232. KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE;
  1233. return CURLE_OK;
  1234. }
  1235. /*
  1236. * Curl_single_getsock() gets called by the multi interface code when the app
  1237. * has requested to get the sockets for the current connection. This function
  1238. * will then be called once for every connection that the multi interface
  1239. * keeps track of. This function will only be called for connections that are
  1240. * in the proper state to have this information available.
  1241. */
  1242. int Curl_single_getsock(const struct connectdata *conn,
  1243. curl_socket_t *sock, /* points to numsocks number
  1244. of sockets */
  1245. int numsocks)
  1246. {
  1247. const struct Curl_easy *data = conn->data;
  1248. int bitmap = GETSOCK_BLANK;
  1249. unsigned sockindex = 0;
  1250. if(conn->handler->perform_getsock)
  1251. return conn->handler->perform_getsock(conn, sock, numsocks);
  1252. if(numsocks < 2)
  1253. /* simple check but we might need two slots */
  1254. return GETSOCK_BLANK;
  1255. /* don't include HOLD and PAUSE connections */
  1256. if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
  1257. DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
  1258. bitmap |= GETSOCK_READSOCK(sockindex);
  1259. sock[sockindex] = conn->sockfd;
  1260. }
  1261. /* don't include HOLD and PAUSE connections */
  1262. if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
  1263. if((conn->sockfd != conn->writesockfd) ||
  1264. bitmap == GETSOCK_BLANK) {
  1265. /* only if they are not the same socket and we have a readable
  1266. one, we increase index */
  1267. if(bitmap != GETSOCK_BLANK)
  1268. sockindex++; /* increase index if we need two entries */
  1269. DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
  1270. sock[sockindex] = conn->writesockfd;
  1271. }
  1272. bitmap |= GETSOCK_WRITESOCK(sockindex);
  1273. }
  1274. return bitmap;
  1275. }
  1276. /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
  1277. which means this gets called once for each subsequent redirect etc */
  1278. void Curl_init_CONNECT(struct Curl_easy *data)
  1279. {
  1280. data->state.fread_func = data->set.fread_func_set;
  1281. data->state.in = data->set.in_set;
  1282. }
  1283. /*
  1284. * Curl_pretransfer() is called immediately before a transfer starts, and only
  1285. * once for one transfer no matter if it has redirects or do multi-pass
  1286. * authentication etc.
  1287. */
  1288. CURLcode Curl_pretransfer(struct Curl_easy *data)
  1289. {
  1290. CURLcode result;
  1291. if(!data->change.url && !data->set.uh) {
  1292. /* we can't do anything without URL */
  1293. failf(data, "No URL set!");
  1294. return CURLE_URL_MALFORMAT;
  1295. }
  1296. /* since the URL may have been redirected in a previous use of this handle */
  1297. if(data->change.url_alloc) {
  1298. /* the already set URL is allocated, free it first! */
  1299. Curl_safefree(data->change.url);
  1300. data->change.url_alloc = FALSE;
  1301. }
  1302. if(!data->change.url && data->set.uh) {
  1303. CURLUcode uc;
  1304. uc = curl_url_get(data->set.uh,
  1305. CURLUPART_URL, &data->set.str[STRING_SET_URL], 0);
  1306. if(uc) {
  1307. failf(data, "No URL set!");
  1308. return CURLE_URL_MALFORMAT;
  1309. }
  1310. }
  1311. data->change.url = data->set.str[STRING_SET_URL];
  1312. /* Init the SSL session ID cache here. We do it here since we want to do it
  1313. after the *_setopt() calls (that could specify the size of the cache) but
  1314. before any transfer takes place. */
  1315. result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions);
  1316. if(result)
  1317. return result;
  1318. data->state.wildcardmatch = data->set.wildcard_enabled;
  1319. data->set.followlocation = 0; /* reset the location-follow counter */
  1320. data->state.this_is_a_follow = FALSE; /* reset this */
  1321. data->state.errorbuf = FALSE; /* no error has occurred */
  1322. data->state.httpversion = 0; /* don't assume any particular server version */
  1323. data->state.authproblem = FALSE;
  1324. data->state.authhost.want = data->set.httpauth;
  1325. data->state.authproxy.want = data->set.proxyauth;
  1326. Curl_safefree(data->info.wouldredirect);
  1327. data->info.wouldredirect = NULL;
  1328. if(data->set.httpreq == HTTPREQ_PUT)
  1329. data->state.infilesize = data->set.filesize;
  1330. else if((data->set.httpreq != HTTPREQ_GET) &&
  1331. (data->set.httpreq != HTTPREQ_HEAD)) {
  1332. data->state.infilesize = data->set.postfieldsize;
  1333. if(data->set.postfields && (data->state.infilesize == -1))
  1334. data->state.infilesize = (curl_off_t)strlen(data->set.postfields);
  1335. }
  1336. else
  1337. data->state.infilesize = 0;
  1338. /* If there is a list of cookie files to read, do it now! */
  1339. if(data->change.cookielist)
  1340. Curl_cookie_loadfiles(data);
  1341. /* If there is a list of host pairs to deal with */
  1342. if(data->change.resolve)
  1343. result = Curl_loadhostpairs(data);
  1344. if(!result) {
  1345. /* Allow data->set.use_port to set which port to use. This needs to be
  1346. * disabled for example when we follow Location: headers to URLs using
  1347. * different ports! */
  1348. data->state.allow_port = TRUE;
  1349. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1350. /*************************************************************
  1351. * Tell signal handler to ignore SIGPIPE
  1352. *************************************************************/
  1353. if(!data->set.no_signal)
  1354. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1355. #endif
  1356. Curl_initinfo(data); /* reset session-specific information "variables" */
  1357. Curl_pgrsResetTransferSizes(data);
  1358. Curl_pgrsStartNow(data);
  1359. /* In case the handle is re-used and an authentication method was picked
  1360. in the session we need to make sure we only use the one(s) we now
  1361. consider to be fine */
  1362. data->state.authhost.picked &= data->state.authhost.want;
  1363. data->state.authproxy.picked &= data->state.authproxy.want;
  1364. if(data->state.wildcardmatch) {
  1365. struct WildcardData *wc = &data->wildcard;
  1366. if(wc->state < CURLWC_INIT) {
  1367. result = Curl_wildcard_init(wc); /* init wildcard structures */
  1368. if(result)
  1369. return CURLE_OUT_OF_MEMORY;
  1370. }
  1371. }
  1372. }
  1373. return result;
  1374. }
  1375. /*
  1376. * Curl_posttransfer() is called immediately after a transfer ends
  1377. */
  1378. CURLcode Curl_posttransfer(struct Curl_easy *data)
  1379. {
  1380. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1381. /* restore the signal handler for SIGPIPE before we get back */
  1382. if(!data->set.no_signal)
  1383. signal(SIGPIPE, data->state.prev_signal);
  1384. #else
  1385. (void)data; /* unused parameter */
  1386. #endif
  1387. return CURLE_OK;
  1388. }
  1389. /*
  1390. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1391. * as given by the remote server and set up the new URL to request.
  1392. *
  1393. * This function DOES NOT FREE the given url.
  1394. */
  1395. CURLcode Curl_follow(struct Curl_easy *data,
  1396. char *newurl, /* the Location: string */
  1397. followtype type) /* see transfer.h */
  1398. {
  1399. #ifdef CURL_DISABLE_HTTP
  1400. (void)data;
  1401. (void)newurl;
  1402. (void)type;
  1403. /* Location: following will not happen when HTTP is disabled */
  1404. return CURLE_TOO_MANY_REDIRECTS;
  1405. #else
  1406. /* Location: redirect */
  1407. bool disallowport = FALSE;
  1408. bool reachedmax = FALSE;
  1409. CURLUcode uc;
  1410. if(type == FOLLOW_REDIR) {
  1411. if((data->set.maxredirs != -1) &&
  1412. (data->set.followlocation >= data->set.maxredirs)) {
  1413. reachedmax = TRUE;
  1414. type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected
  1415. to URL */
  1416. }
  1417. else {
  1418. /* mark the next request as a followed location: */
  1419. data->state.this_is_a_follow = TRUE;
  1420. data->set.followlocation++; /* count location-followers */
  1421. if(data->set.http_auto_referer) {
  1422. /* We are asked to automatically set the previous URL as the referer
  1423. when we get the next URL. We pick the ->url field, which may or may
  1424. not be 100% correct */
  1425. if(data->change.referer_alloc) {
  1426. Curl_safefree(data->change.referer);
  1427. data->change.referer_alloc = FALSE;
  1428. }
  1429. data->change.referer = strdup(data->change.url);
  1430. if(!data->change.referer)
  1431. return CURLE_OUT_OF_MEMORY;
  1432. data->change.referer_alloc = TRUE; /* yes, free this later */
  1433. }
  1434. }
  1435. }
  1436. if(Curl_is_absolute_url(newurl, NULL, MAX_SCHEME_LEN))
  1437. /* This is an absolute URL, don't allow the custom port number */
  1438. disallowport = TRUE;
  1439. DEBUGASSERT(data->state.uh);
  1440. uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl,
  1441. (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME : 0);
  1442. if(uc) {
  1443. if(type != FOLLOW_FAKE)
  1444. return Curl_uc_to_curlcode(uc);
  1445. /* the URL could not be parsed for some reason, but since this is FAKE
  1446. mode, just duplicate the field as-is */
  1447. newurl = strdup(newurl);
  1448. if(!newurl)
  1449. return CURLE_OUT_OF_MEMORY;
  1450. }
  1451. else {
  1452. uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0);
  1453. if(uc)
  1454. return Curl_uc_to_curlcode(uc);
  1455. }
  1456. if(type == FOLLOW_FAKE) {
  1457. /* we're only figuring out the new url if we would've followed locations
  1458. but now we're done so we can get out! */
  1459. data->info.wouldredirect = newurl;
  1460. if(reachedmax) {
  1461. failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs);
  1462. return CURLE_TOO_MANY_REDIRECTS;
  1463. }
  1464. return CURLE_OK;
  1465. }
  1466. if(disallowport)
  1467. data->state.allow_port = FALSE;
  1468. if(data->change.url_alloc)
  1469. Curl_safefree(data->change.url);
  1470. data->change.url = newurl;
  1471. data->change.url_alloc = TRUE;
  1472. infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
  1473. /*
  1474. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1475. * differently based on exactly what return code there was.
  1476. *
  1477. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1478. * a HTTP (proxy-) authentication scheme other than Basic.
  1479. */
  1480. switch(data->info.httpcode) {
  1481. /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
  1482. Authorization: XXXX header in the HTTP request code snippet */
  1483. /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
  1484. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1485. /* 300 - Multiple Choices */
  1486. /* 306 - Not used */
  1487. /* 307 - Temporary Redirect */
  1488. default: /* for all above (and the unknown ones) */
  1489. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  1490. * seem to be OK to POST to.
  1491. */
  1492. break;
  1493. case 301: /* Moved Permanently */
  1494. /* (quote from RFC7231, section 6.4.2)
  1495. *
  1496. * Note: For historical reasons, a user agent MAY change the request
  1497. * method from POST to GET for the subsequent request. If this
  1498. * behavior is undesired, the 307 (Temporary Redirect) status code
  1499. * can be used instead.
  1500. *
  1501. * ----
  1502. *
  1503. * Many webservers expect this, so these servers often answers to a POST
  1504. * request with an error page. To be sure that libcurl gets the page that
  1505. * most user agents would get, libcurl has to force GET.
  1506. *
  1507. * This behaviour is forbidden by RFC1945 and the obsolete RFC2616, and
  1508. * can be overridden with CURLOPT_POSTREDIR.
  1509. */
  1510. if((data->set.httpreq == HTTPREQ_POST
  1511. || data->set.httpreq == HTTPREQ_POST_FORM
  1512. || data->set.httpreq == HTTPREQ_POST_MIME)
  1513. && !(data->set.keep_post & CURL_REDIR_POST_301)) {
  1514. infof(data, "Switch from POST to GET\n");
  1515. data->set.httpreq = HTTPREQ_GET;
  1516. }
  1517. break;
  1518. case 302: /* Found */
  1519. /* (quote from RFC7231, section 6.4.3)
  1520. *
  1521. * Note: For historical reasons, a user agent MAY change the request
  1522. * method from POST to GET for the subsequent request. If this
  1523. * behavior is undesired, the 307 (Temporary Redirect) status code
  1524. * can be used instead.
  1525. *
  1526. * ----
  1527. *
  1528. * Many webservers expect this, so these servers often answers to a POST
  1529. * request with an error page. To be sure that libcurl gets the page that
  1530. * most user agents would get, libcurl has to force GET.
  1531. *
  1532. * This behaviour is forbidden by RFC1945 and the obsolete RFC2616, and
  1533. * can be overridden with CURLOPT_POSTREDIR.
  1534. */
  1535. if((data->set.httpreq == HTTPREQ_POST
  1536. || data->set.httpreq == HTTPREQ_POST_FORM
  1537. || data->set.httpreq == HTTPREQ_POST_MIME)
  1538. && !(data->set.keep_post & CURL_REDIR_POST_302)) {
  1539. infof(data, "Switch from POST to GET\n");
  1540. data->set.httpreq = HTTPREQ_GET;
  1541. }
  1542. break;
  1543. case 303: /* See Other */
  1544. /* Disable both types of POSTs, unless the user explicitly
  1545. asks for POST after POST */
  1546. if(data->set.httpreq != HTTPREQ_GET
  1547. && !(data->set.keep_post & CURL_REDIR_POST_303)) {
  1548. data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
  1549. infof(data, "Disables POST, goes with %s\n",
  1550. data->set.opt_no_body?"HEAD":"GET");
  1551. }
  1552. break;
  1553. case 304: /* Not Modified */
  1554. /* 304 means we did a conditional request and it was "Not modified".
  1555. * We shouldn't get any Location: header in this response!
  1556. */
  1557. break;
  1558. case 305: /* Use Proxy */
  1559. /* (quote from RFC2616, section 10.3.6):
  1560. * "The requested resource MUST be accessed through the proxy given
  1561. * by the Location field. The Location field gives the URI of the
  1562. * proxy. The recipient is expected to repeat this single request
  1563. * via the proxy. 305 responses MUST only be generated by origin
  1564. * servers."
  1565. */
  1566. break;
  1567. }
  1568. Curl_pgrsTime(data, TIMER_REDIRECT);
  1569. Curl_pgrsResetTransferSizes(data);
  1570. return CURLE_OK;
  1571. #endif /* CURL_DISABLE_HTTP */
  1572. }
  1573. /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
  1574. NOTE: that the *url is malloc()ed. */
  1575. CURLcode Curl_retry_request(struct connectdata *conn,
  1576. char **url)
  1577. {
  1578. struct Curl_easy *data = conn->data;
  1579. bool retry = FALSE;
  1580. *url = NULL;
  1581. /* if we're talking upload, we can't do the checks below, unless the protocol
  1582. is HTTP as when uploading over HTTP we will still get a response */
  1583. if(data->set.upload &&
  1584. !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)))
  1585. return CURLE_OK;
  1586. if((data->req.bytecount + data->req.headerbytecount == 0) &&
  1587. conn->bits.reuse &&
  1588. (!data->set.opt_no_body
  1589. || (conn->handler->protocol & PROTO_FAMILY_HTTP)) &&
  1590. (data->set.rtspreq != RTSPREQ_RECEIVE))
  1591. /* We got no data, we attempted to re-use a connection. For HTTP this
  1592. can be a retry so we try again regardless if we expected a body.
  1593. For other protocols we only try again only if we expected a body.
  1594. This might happen if the connection was left alive when we were
  1595. done using it before, but that was closed when we wanted to read from
  1596. it again. Bad luck. Retry the same request on a fresh connect! */
  1597. retry = TRUE;
  1598. else if(data->state.refused_stream &&
  1599. (data->req.bytecount + data->req.headerbytecount == 0) ) {
  1600. /* This was sent on a refused stream, safe to rerun. A refused stream
  1601. error can typically only happen on HTTP/2 level if the stream is safe
  1602. to issue again, but the nghttp2 API can deliver the message to other
  1603. streams as well, which is why this adds the check the data counters
  1604. too. */
  1605. infof(conn->data, "REFUSED_STREAM, retrying a fresh connect\n");
  1606. data->state.refused_stream = FALSE; /* clear again */
  1607. retry = TRUE;
  1608. }
  1609. if(retry) {
  1610. infof(conn->data, "Connection died, retrying a fresh connect\n");
  1611. *url = strdup(conn->data->change.url);
  1612. if(!*url)
  1613. return CURLE_OUT_OF_MEMORY;
  1614. connclose(conn, "retry"); /* close this connection */
  1615. conn->bits.retry = TRUE; /* mark this as a connection we're about
  1616. to retry. Marking it this way should
  1617. prevent i.e HTTP transfers to return
  1618. error just because nothing has been
  1619. transferred! */
  1620. if(conn->handler->protocol&PROTO_FAMILY_HTTP) {
  1621. if(data->req.writebytecount) {
  1622. CURLcode result = Curl_readrewind(conn);
  1623. if(result) {
  1624. Curl_safefree(*url);
  1625. return result;
  1626. }
  1627. }
  1628. }
  1629. }
  1630. return CURLE_OK;
  1631. }
  1632. /*
  1633. * Curl_setup_transfer() is called to setup some basic properties for the
  1634. * upcoming transfer.
  1635. */
  1636. void
  1637. Curl_setup_transfer(
  1638. struct Curl_easy *data, /* transfer */
  1639. int sockindex, /* socket index to read from or -1 */
  1640. curl_off_t size, /* -1 if unknown at this point */
  1641. bool getheader, /* TRUE if header parsing is wanted */
  1642. int writesockindex /* socket index to write to, it may very well be
  1643. the same we read from. -1 disables */
  1644. )
  1645. {
  1646. struct SingleRequest *k = &data->req;
  1647. struct connectdata *conn = data->conn;
  1648. DEBUGASSERT(conn != NULL);
  1649. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  1650. if(conn->bits.multiplex || conn->httpversion == 20) {
  1651. /* when multiplexing, the read/write sockets need to be the same! */
  1652. conn->sockfd = sockindex == -1 ?
  1653. ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) :
  1654. conn->sock[sockindex];
  1655. conn->writesockfd = conn->sockfd;
  1656. }
  1657. else {
  1658. conn->sockfd = sockindex == -1 ?
  1659. CURL_SOCKET_BAD : conn->sock[sockindex];
  1660. conn->writesockfd = writesockindex == -1 ?
  1661. CURL_SOCKET_BAD:conn->sock[writesockindex];
  1662. }
  1663. k->getheader = getheader;
  1664. k->size = size;
  1665. /* The code sequence below is placed in this function just because all
  1666. necessary input is not always known in do_complete() as this function may
  1667. be called after that */
  1668. if(!k->getheader) {
  1669. k->header = FALSE;
  1670. if(size > 0)
  1671. Curl_pgrsSetDownloadSize(data, size);
  1672. }
  1673. /* we want header and/or body, if neither then don't do this! */
  1674. if(k->getheader || !data->set.opt_no_body) {
  1675. if(sockindex != -1)
  1676. k->keepon |= KEEP_RECV;
  1677. if(writesockindex != -1) {
  1678. struct HTTP *http = data->req.protop;
  1679. /* HTTP 1.1 magic:
  1680. Even if we require a 100-return code before uploading data, we might
  1681. need to write data before that since the REQUEST may not have been
  1682. finished sent off just yet.
  1683. Thus, we must check if the request has been sent before we set the
  1684. state info where we wait for the 100-return code
  1685. */
  1686. if((data->state.expect100header) &&
  1687. (conn->handler->protocol&PROTO_FAMILY_HTTP) &&
  1688. (http->sending == HTTPSEND_BODY)) {
  1689. /* wait with write until we either got 100-continue or a timeout */
  1690. k->exp100 = EXP100_AWAITING_CONTINUE;
  1691. k->start100 = Curl_now();
  1692. /* Set a timeout for the multi interface. Add the inaccuracy margin so
  1693. that we don't fire slightly too early and get denied to run. */
  1694. Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT);
  1695. }
  1696. else {
  1697. if(data->state.expect100header)
  1698. /* when we've sent off the rest of the headers, we must await a
  1699. 100-continue but first finish sending the request */
  1700. k->exp100 = EXP100_SENDING_REQUEST;
  1701. /* enable the write bit when we're not waiting for continue */
  1702. k->keepon |= KEEP_SEND;
  1703. }
  1704. } /* if(writesockindex != -1) */
  1705. } /* if(k->getheader || !data->set.opt_no_body) */
  1706. }