transfer.c 67 KB

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