transfer.c 63 KB

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