2
0

transfer.c 64 KB

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