transfer.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2004, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at 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. * $Id$
  22. ***************************************************************************/
  23. #include "setup.h"
  24. /* -- WIN32 approved -- */
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <stdarg.h>
  28. #include <stdlib.h>
  29. #include <ctype.h>
  30. #ifdef HAVE_SYS_TYPES_H
  31. #include <sys/types.h>
  32. #endif
  33. #include <sys/stat.h>
  34. #include <errno.h>
  35. #include "strtoofft.h"
  36. #include "strequal.h"
  37. #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
  38. #include <time.h>
  39. #include <io.h>
  40. #else
  41. #ifdef HAVE_SYS_SOCKET_H
  42. #include <sys/socket.h>
  43. #endif
  44. #ifdef HAVE_NETINET_IN_H
  45. #include <netinet/in.h>
  46. #endif
  47. #include <sys/time.h>
  48. #ifdef HAVE_UNISTD_H
  49. #include <unistd.h>
  50. #endif
  51. #include <netdb.h>
  52. #ifdef HAVE_ARPA_INET_H
  53. #include <arpa/inet.h>
  54. #endif
  55. #ifdef HAVE_NET_IF_H
  56. #include <net/if.h>
  57. #endif
  58. #ifdef HAVE_SYS_IOCTL_H
  59. #include <sys/ioctl.h>
  60. #endif
  61. #include <signal.h>
  62. #ifdef HAVE_SYS_PARAM_H
  63. #include <sys/param.h>
  64. #endif
  65. #ifdef HAVE_SYS_SELECT_H
  66. #include <sys/select.h>
  67. #endif
  68. #ifndef HAVE_SELECT
  69. #error "We can't compile without select() support!"
  70. #endif
  71. #ifndef HAVE_SOCKET
  72. #error "We can't compile without socket() support!"
  73. #endif
  74. #endif
  75. #include "urldata.h"
  76. #include <curl/curl.h>
  77. #include "netrc.h"
  78. #include "content_encoding.h"
  79. #include "hostip.h"
  80. #include "transfer.h"
  81. #include "sendf.h"
  82. #include "speedcheck.h"
  83. #include "progress.h"
  84. #include "getdate.h"
  85. #include "http.h"
  86. #include "url.h"
  87. #include "getinfo.h"
  88. #include "ssluse.h"
  89. #include "http_digest.h"
  90. #include "http_ntlm.h"
  91. #include "http_negotiate.h"
  92. #include "share.h"
  93. #include "curl_memory.h"
  94. #define _MPRINTF_REPLACE /* use our functions only */
  95. #include <curl/mprintf.h>
  96. /* The last #include file should be: */
  97. #include "memdebug.h"
  98. #define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
  99. enum {
  100. KEEP_NONE,
  101. KEEP_READ,
  102. KEEP_WRITE
  103. };
  104. /* We keep this static and global since this is read-only and NEVER
  105. changed. It should just remain a blanked-out timeout value. */
  106. static struct timeval notimeout={0,0};
  107. /*
  108. * This function will call the read callback to fill our buffer with data
  109. * to upload.
  110. */
  111. CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
  112. {
  113. struct SessionHandle *data = conn->data;
  114. size_t buffersize = (size_t)bytes;
  115. int nread;
  116. if(conn->bits.upload_chunky) {
  117. /* if chunked Transfer-Encoding */
  118. buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
  119. conn->upload_fromhere += 10; /* 32bit hex + CRLF */
  120. }
  121. /* this function returns a size_t, so we typecast to int to prevent warnings
  122. with picky compilers */
  123. nread = (int)conn->fread(conn->upload_fromhere, 1,
  124. buffersize, conn->fread_in);
  125. if(nread == CURL_READFUNC_ABORT) {
  126. failf(data, "operation aborted by callback\n");
  127. return CURLE_ABORTED_BY_CALLBACK;
  128. }
  129. if(!conn->bits.forbidchunk && conn->bits.upload_chunky) {
  130. /* if chunked Transfer-Encoding */
  131. char hexbuffer[11];
  132. int hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
  133. "%x\r\n", nread);
  134. /* move buffer pointer */
  135. conn->upload_fromhere -= hexlen;
  136. nread += hexlen;
  137. /* copy the prefix to the buffer */
  138. memcpy(conn->upload_fromhere, hexbuffer, hexlen);
  139. /* always append CRLF to the data */
  140. memcpy(conn->upload_fromhere + nread, "\r\n", 2);
  141. if((nread - hexlen) == 0) {
  142. /* mark this as done once this chunk is transfered */
  143. conn->keep.upload_done = TRUE;
  144. }
  145. nread+=2; /* for the added CRLF */
  146. }
  147. *nreadp = nread;
  148. return CURLE_OK;
  149. }
  150. /*
  151. * checkhttpprefix()
  152. *
  153. * Returns TRUE if member of the list matches prefix of string
  154. */
  155. static bool
  156. checkhttpprefix(struct SessionHandle *data,
  157. const char *s)
  158. {
  159. struct curl_slist *head = data->set.http200aliases;
  160. while (head) {
  161. if (checkprefix(head->data, s))
  162. return TRUE;
  163. head = head->next;
  164. }
  165. if(checkprefix("HTTP/", s))
  166. return TRUE;
  167. return FALSE;
  168. }
  169. /*
  170. * Curl_readwrite() is the low-level function to be called when data is to
  171. * be read and written to/from the connection.
  172. */
  173. CURLcode Curl_readwrite(struct connectdata *conn,
  174. bool *done)
  175. {
  176. struct Curl_transfer_keeper *k = &conn->keep;
  177. struct SessionHandle *data = conn->data;
  178. CURLcode result;
  179. ssize_t nread; /* number of bytes read */
  180. int didwhat=0;
  181. /* These two are used only if no other select() or _fdset() have been
  182. invoked before this. This typicly happens if you use the multi interface
  183. and call curl_multi_perform() without calling curl_multi_fdset()
  184. first. */
  185. fd_set extrareadfd;
  186. fd_set extrawritefd;
  187. fd_set *readfdp = k->readfdp;
  188. fd_set *writefdp = k->writefdp;
  189. curl_off_t contentlength;
  190. if((k->keepon & KEEP_READ) && !readfdp) {
  191. /* reading is requested, but no socket descriptor pointer was set */
  192. FD_ZERO(&extrareadfd);
  193. FD_SET(conn->sockfd, &extrareadfd);
  194. readfdp = &extrareadfd;
  195. /* no write, no exceptions, no timeout */
  196. select(conn->sockfd+1, readfdp, NULL, NULL, &notimeout);
  197. }
  198. if((k->keepon & KEEP_WRITE) && !writefdp) {
  199. /* writing is requested, but no socket descriptor pointer was set */
  200. FD_ZERO(&extrawritefd);
  201. FD_SET(conn->writesockfd, &extrawritefd);
  202. writefdp = &extrawritefd;
  203. /* no read, no exceptions, no timeout */
  204. select(conn->writesockfd+1, NULL, writefdp, NULL, &notimeout);
  205. }
  206. do {
  207. /* If we still have reading to do, we check if we have a readable
  208. socket. Sometimes the reafdp is NULL, if no fd_set was done using
  209. the multi interface and then we can do nothing but to attempt a
  210. read to be sure. */
  211. if((k->keepon & KEEP_READ) &&
  212. (!readfdp || FD_ISSET(conn->sockfd, readfdp))) {
  213. bool readdone = TRUE;
  214. /* This is where we loop until we have read everything there is to
  215. read or we get a EWOULDBLOCK */
  216. do {
  217. size_t buffersize = data->set.buffer_size?
  218. data->set.buffer_size:BUFSIZE -1;
  219. /* receive data from the network! */
  220. int readrc = Curl_read(conn, conn->sockfd, k->buf, buffersize, &nread);
  221. /* subzero, this would've blocked */
  222. if(0>readrc)
  223. break; /* get out of loop */
  224. /* get the CURLcode from the int */
  225. result = (CURLcode)readrc;
  226. if(result>0)
  227. return result;
  228. if ((k->bytecount == 0) && (k->writebytecount == 0)) {
  229. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  230. if(k->wait100_after_headers)
  231. /* set time stamp to compare with when waiting for the 100 */
  232. k->start100 = Curl_tvnow();
  233. }
  234. didwhat |= KEEP_READ;
  235. /* NULL terminate, allowing string ops to be used */
  236. if (0 < nread)
  237. k->buf[nread] = 0;
  238. /* if we receive 0 or less here, the server closed the connection and
  239. we bail out from this! */
  240. else if (0 >= nread) {
  241. k->keepon &= ~KEEP_READ;
  242. FD_ZERO(&k->rkeepfd);
  243. readdone = TRUE;
  244. break;
  245. }
  246. /* Default buffer to use when we write the buffer, it may be changed
  247. in the flow below before the actual storing is done. */
  248. k->str = k->buf;
  249. /* Since this is a two-state thing, we check if we are parsing
  250. headers at the moment or not. */
  251. if (k->header) {
  252. /* we are in parse-the-header-mode */
  253. bool stop_reading = FALSE;
  254. /* header line within buffer loop */
  255. do {
  256. size_t hbufp_index;
  257. size_t rest_length;
  258. size_t full_length;
  259. int writetype;
  260. /* str_start is start of line within buf */
  261. k->str_start = k->str;
  262. k->end_ptr = strchr (k->str_start, '\n');
  263. if (!k->end_ptr) {
  264. /* Not a complete header line within buffer, append the data to
  265. the end of the headerbuff. */
  266. if (k->hbuflen + nread >= data->state.headersize) {
  267. /* We enlarge the header buffer as it is too small */
  268. char *newbuff;
  269. size_t newsize=CURLMAX((k->hbuflen+nread)*3/2,
  270. data->state.headersize*2);
  271. hbufp_index = k->hbufp - data->state.headerbuff;
  272. newbuff = (char *)realloc(data->state.headerbuff, newsize);
  273. if(!newbuff) {
  274. failf (data, "Failed to alloc memory for big header!");
  275. return CURLE_OUT_OF_MEMORY;
  276. }
  277. data->state.headersize=newsize;
  278. data->state.headerbuff = newbuff;
  279. k->hbufp = data->state.headerbuff + hbufp_index;
  280. }
  281. memcpy(k->hbufp, k->str, nread);
  282. k->hbufp += nread;
  283. k->hbuflen += nread;
  284. if (!k->headerline && (k->hbuflen>5)) {
  285. /* make a first check that this looks like a HTTP header */
  286. if(!checkhttpprefix(data, data->state.headerbuff)) {
  287. /* this is not the beginning of a HTTP first header line */
  288. k->header = FALSE;
  289. k->badheader = HEADER_ALLBAD;
  290. break;
  291. }
  292. }
  293. break; /* read more and try again */
  294. }
  295. /* decrease the size of the remaining (supposed) header line */
  296. rest_length = (k->end_ptr - k->str)+1;
  297. nread -= rest_length;
  298. k->str = k->end_ptr + 1; /* move past new line */
  299. full_length = k->str - k->str_start;
  300. /*
  301. * We're about to copy a chunk of data to the end of the
  302. * already received header. We make sure that the full string
  303. * fit in the allocated header buffer, or else we enlarge
  304. * it.
  305. */
  306. if (k->hbuflen + full_length >=
  307. data->state.headersize) {
  308. char *newbuff;
  309. size_t newsize=CURLMAX((k->hbuflen+full_length)*3/2,
  310. data->state.headersize*2);
  311. hbufp_index = k->hbufp - data->state.headerbuff;
  312. newbuff = (char *)realloc(data->state.headerbuff, newsize);
  313. if(!newbuff) {
  314. failf (data, "Failed to alloc memory for big header!");
  315. return CURLE_OUT_OF_MEMORY;
  316. }
  317. data->state.headersize= newsize;
  318. data->state.headerbuff = newbuff;
  319. k->hbufp = data->state.headerbuff + hbufp_index;
  320. }
  321. /* copy to end of line */
  322. strncpy (k->hbufp, k->str_start, full_length);
  323. k->hbufp += full_length;
  324. k->hbuflen += full_length;
  325. *k->hbufp = 0;
  326. k->end_ptr = k->hbufp;
  327. k->p = data->state.headerbuff;
  328. /****
  329. * We now have a FULL header line that p points to
  330. *****/
  331. if(!k->headerline) {
  332. /* the first read header */
  333. if((k->hbuflen>5) &&
  334. !checkhttpprefix(data, data->state.headerbuff)) {
  335. /* this is not the beginning of a HTTP first header line */
  336. k->header = FALSE;
  337. if(nread)
  338. /* since there's more, this is a partial bad header */
  339. k->badheader = HEADER_PARTHEADER;
  340. else {
  341. /* this was all we read so its all a bad header */
  342. k->badheader = HEADER_ALLBAD;
  343. nread = (ssize_t)rest_length;
  344. }
  345. break;
  346. }
  347. }
  348. if (('\n' == *k->p) || ('\r' == *k->p)) {
  349. size_t headerlen;
  350. /* Zero-length header line means end of headers! */
  351. if ('\r' == *k->p)
  352. k->p++; /* pass the \r byte */
  353. if ('\n' == *k->p)
  354. k->p++; /* pass the \n byte */
  355. if(100 == k->httpcode) {
  356. /*
  357. * We have made a HTTP PUT or POST and this is 1.1-lingo
  358. * that tells us that the server is OK with this and ready
  359. * to receive the data.
  360. * However, we'll get more headers now so we must get
  361. * back into the header-parsing state!
  362. */
  363. k->header = TRUE;
  364. k->headerline = 0; /* restart the header line counter */
  365. /* if we did wait for this do enable write now! */
  366. if (k->write_after_100_header) {
  367. k->write_after_100_header = FALSE;
  368. FD_SET (conn->writesockfd, &k->writefd); /* write */
  369. k->keepon |= KEEP_WRITE;
  370. k->wkeepfd = k->writefd;
  371. }
  372. }
  373. else
  374. k->header = FALSE; /* no more header to parse! */
  375. if (417 == k->httpcode) {
  376. /*
  377. * we got: "417 Expectation Failed" this means:
  378. * we have made a HTTP call and our Expect Header
  379. * seems to cause a problem => abort the write operations
  380. * (or prevent them from starting).
  381. */
  382. k->write_after_100_header = FALSE;
  383. k->keepon &= ~KEEP_WRITE;
  384. FD_ZERO(&k->wkeepfd);
  385. }
  386. #ifndef CURL_DISABLE_HTTP
  387. /*
  388. * When all the headers have been parsed, see if we should give
  389. * up and return an error.
  390. */
  391. if (Curl_http_should_fail(conn)) {
  392. failf (data, "The requested URL returned error: %d",
  393. k->httpcode);
  394. return CURLE_HTTP_RETURNED_ERROR;
  395. }
  396. #endif /* CURL_DISABLE_HTTP */
  397. /* now, only output this if the header AND body are requested:
  398. */
  399. writetype = CLIENTWRITE_HEADER;
  400. if (data->set.include_header)
  401. writetype |= CLIENTWRITE_BODY;
  402. headerlen = k->p - data->state.headerbuff;
  403. result = Curl_client_write(data, writetype,
  404. data->state.headerbuff,
  405. headerlen);
  406. if(result)
  407. return result;
  408. data->info.header_size += headerlen;
  409. conn->headerbytecount += headerlen;
  410. conn->deductheadercount =
  411. (100 == k->httpcode)?conn->headerbytecount:0;
  412. if (conn->resume_from &&
  413. !k->content_range &&
  414. (data->set.httpreq==HTTPREQ_GET)) {
  415. if(k->httpcode == 416) {
  416. /* "Requested Range Not Satisfiable" */
  417. stop_reading = TRUE;
  418. }
  419. else {
  420. /* we wanted to resume a download, although the server
  421. * doesn't seem to support this and we did this with a GET
  422. * (if it wasn't a GET we did a POST or PUT resume) */
  423. failf (data, "HTTP server doesn't seem to support "
  424. "byte ranges. Cannot resume.");
  425. return CURLE_HTTP_RANGE_ERROR;
  426. }
  427. }
  428. #ifndef CURL_DISABLE_HTTP
  429. if(!stop_reading) {
  430. /* Curl_http_auth_act() checks what authentication methods
  431. * that are available and decides which one (if any) to
  432. * use. It will set 'newurl' if an auth metod was picked. */
  433. result = Curl_http_auth_act(conn);
  434. if(result)
  435. return result;
  436. }
  437. #endif /* CURL_DISABLE_HTTP */
  438. if(!k->header) {
  439. /*
  440. * really end-of-headers.
  441. *
  442. * If we requested a "no body", this is a good time to get
  443. * out and return home.
  444. */
  445. if(conn->bits.no_body)
  446. stop_reading = TRUE;
  447. else {
  448. /* If we know the expected size of this document, we set the
  449. maximum download size to the size of the expected
  450. document or else, we won't know when to stop reading!
  451. Note that we set the download maximum even if we read a
  452. "Connection: close" header, to make sure that
  453. "Content-Length: 0" still prevents us from attempting to
  454. read the (missing) response-body.
  455. */
  456. /* According to RFC2616 section 4.4, we MUST ignore
  457. Content-Length: headers if we are now receiving data
  458. using chunked Transfer-Encoding.
  459. */
  460. if(conn->bits.chunk)
  461. conn->size=-1;
  462. }
  463. if(-1 != conn->size) {
  464. /* We do this operation even if no_body is true, since this
  465. data might be retrieved later with curl_easy_getinfo()
  466. and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
  467. Curl_pgrsSetDownloadSize(data, conn->size);
  468. conn->maxdownload = conn->size;
  469. }
  470. /* If max download size is *zero* (nothing) we already
  471. have nothing and can safely return ok now! */
  472. if(0 == conn->maxdownload)
  473. stop_reading = TRUE;
  474. if(stop_reading) {
  475. /* we make sure that this socket isn't read more now */
  476. k->keepon &= ~KEEP_READ;
  477. FD_ZERO(&k->rkeepfd);
  478. }
  479. break; /* exit header line loop */
  480. }
  481. /* We continue reading headers, so reset the line-based
  482. header parsing variables hbufp && hbuflen */
  483. k->hbufp = data->state.headerbuff;
  484. k->hbuflen = 0;
  485. continue;
  486. }
  487. /*
  488. * Checks for special headers coming up.
  489. */
  490. if (!k->headerline++) {
  491. /* This is the first header, it MUST be the error code line
  492. or else we consiser this to be the body right away! */
  493. int httpversion_major;
  494. int nc=sscanf(k->p, " HTTP/%d.%d %3d",
  495. &httpversion_major,
  496. &k->httpversion,
  497. &k->httpcode);
  498. if (nc==3) {
  499. k->httpversion += 10 * httpversion_major;
  500. }
  501. else {
  502. /* this is the real world, not a Nirvana
  503. NCSA 1.5.x returns this crap when asked for HTTP/1.1
  504. */
  505. nc=sscanf(k->p, " HTTP %3d", &k->httpcode);
  506. k->httpversion = 10;
  507. /* If user has set option HTTP200ALIASES,
  508. compare header line against list of aliases
  509. */
  510. if (!nc) {
  511. if (checkhttpprefix(data, k->p)) {
  512. nc = 1;
  513. k->httpcode = 200;
  514. k->httpversion =
  515. (data->set.httpversion==CURL_HTTP_VERSION_1_0)? 10 : 11;
  516. }
  517. }
  518. }
  519. if (nc) {
  520. data->info.httpcode = k->httpcode;
  521. data->info.httpversion = k->httpversion;
  522. /*
  523. * This code executes as part of processing the header. As a
  524. * result, it's not totally clear how to interpret the
  525. * response code yet as that depends on what other headers may
  526. * be present. 401 and 407 may be errors, but may be OK
  527. * depending on how authentication is working. Other codes
  528. * are definitely errors, so give up here.
  529. */
  530. if (data->set.http_fail_on_error &&
  531. (k->httpcode >= 400) &&
  532. (k->httpcode != 401) &&
  533. (k->httpcode != 407)) {
  534. /* serious error, go home! */
  535. failf (data, "The requested URL returned error: %d",
  536. k->httpcode);
  537. return CURLE_HTTP_RETURNED_ERROR;
  538. }
  539. if(k->httpversion == 10)
  540. /* Default action for HTTP/1.0 must be to close, unless
  541. we get one of those fancy headers that tell us the
  542. server keeps it open for us! */
  543. conn->bits.close = TRUE;
  544. switch(k->httpcode) {
  545. case 204:
  546. /* (quote from RFC2616, section 10.2.5): The server has
  547. * fulfilled the request but does not need to return an
  548. * entity-body ... The 204 response MUST NOT include a
  549. * message-body, and thus is always terminated by the first
  550. * empty line after the header fields. */
  551. /* FALLTHROUGH */
  552. case 416: /* Requested Range Not Satisfiable, it has the
  553. Content-Length: set as the "real" document but no
  554. actual response is sent. */
  555. case 304:
  556. /* (quote from RFC2616, section 10.3.5): The 304 response
  557. * MUST NOT contain a message-body, and thus is always
  558. * terminated by the first empty line after the header
  559. * fields. */
  560. conn->size=0;
  561. conn->maxdownload=0;
  562. break;
  563. default:
  564. /* nothing */
  565. break;
  566. }
  567. }
  568. else {
  569. k->header = FALSE; /* this is not a header line */
  570. break;
  571. }
  572. }
  573. /* Check for Content-Length: header lines to get size. Ignore
  574. the header completely if we get a 416 response as then we're
  575. resuming a document that we don't get, and this header contains
  576. info about the true size of the document we didn't get now. */
  577. if ((k->httpcode != 416) &&
  578. checkprefix("Content-Length:", k->p)) {
  579. contentlength = curlx_strtoofft(k->p+15, NULL, 10);
  580. if (data->set.max_filesize &&
  581. contentlength > data->set.max_filesize) {
  582. failf(data, "Maximum file size exceeded");
  583. return CURLE_FILESIZE_EXCEEDED;
  584. }
  585. if(contentlength >= 0)
  586. conn->size = contentlength;
  587. else {
  588. /* Negative Content-Length is really odd, and we know it
  589. happens for example when older Apache servers send large
  590. files */
  591. conn->bits.close = TRUE;
  592. infof(data, "Negative content-length: %" FORMAT_OFF_T
  593. ", closing after transfer\n", contentlength);
  594. }
  595. }
  596. /* check for Content-Type: header lines to get the mime-type */
  597. else if (checkprefix("Content-Type:", k->p)) {
  598. char *start;
  599. char *end;
  600. size_t len;
  601. /* Find the first non-space letter */
  602. for(start=k->p+13;
  603. *start && isspace((int)*start);
  604. start++);
  605. end = strchr(start, '\r');
  606. if(!end)
  607. end = strchr(start, '\n');
  608. if(end) {
  609. /* skip all trailing space letters */
  610. for(; isspace((int)*end) && (end > start); end--);
  611. /* get length of the type */
  612. len = end-start+1;
  613. /* allocate memory of a cloned copy */
  614. Curl_safefree(data->info.contenttype);
  615. data->info.contenttype = malloc(len + 1);
  616. if (NULL == data->info.contenttype)
  617. return CURLE_OUT_OF_MEMORY;
  618. /* copy the content-type string */
  619. memcpy(data->info.contenttype, start, len);
  620. data->info.contenttype[len] = 0; /* zero terminate */
  621. }
  622. }
  623. #ifndef CURL_DISABLE_HTTP
  624. else if((k->httpversion == 10) &&
  625. conn->bits.httpproxy &&
  626. Curl_compareheader(k->p,
  627. "Proxy-Connection:", "keep-alive")) {
  628. /*
  629. * When a HTTP/1.0 reply comes when using a proxy, the
  630. * 'Proxy-Connection: keep-alive' line tells us the
  631. * connection will be kept alive for our pleasure.
  632. * Default action for 1.0 is to close.
  633. */
  634. conn->bits.close = FALSE; /* don't close when done */
  635. infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
  636. }
  637. else if((k->httpversion == 10) &&
  638. Curl_compareheader(k->p, "Connection:", "keep-alive")) {
  639. /*
  640. * A HTTP/1.0 reply with the 'Connection: keep-alive' line
  641. * tells us the connection will be kept alive for our
  642. * pleasure. Default action for 1.0 is to close.
  643. *
  644. * [RFC2068, section 19.7.1] */
  645. conn->bits.close = FALSE; /* don't close when done */
  646. infof(data, "HTTP/1.0 connection set to keep alive!\n");
  647. }
  648. else if (Curl_compareheader(k->p, "Connection:", "close")) {
  649. /*
  650. * [RFC 2616, section 8.1.2.1]
  651. * "Connection: close" is HTTP/1.1 language and means that
  652. * the connection will close when this request has been
  653. * served.
  654. */
  655. conn->bits.close = TRUE; /* close when done */
  656. }
  657. else if (Curl_compareheader(k->p,
  658. "Transfer-Encoding:", "chunked")) {
  659. /*
  660. * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
  661. * means that the server will send a series of "chunks". Each
  662. * chunk starts with line with info (including size of the
  663. * coming block) (terminated with CRLF), then a block of data
  664. * with the previously mentioned size. There can be any amount
  665. * of chunks, and a chunk-data set to zero signals the
  666. * end-of-chunks. */
  667. conn->bits.chunk = TRUE; /* chunks coming our way */
  668. /* init our chunky engine */
  669. Curl_httpchunk_init(conn);
  670. }
  671. else if (checkprefix("Content-Encoding:", k->p) &&
  672. data->set.encoding) {
  673. /*
  674. * Process Content-Encoding. Look for the values: identity,
  675. * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
  676. * x-compress are the same as gzip and compress. (Sec 3.5 RFC
  677. * 2616). zlib cannot handle compress. However, errors are
  678. * handled further down when the response body is processed
  679. */
  680. char *start;
  681. /* Find the first non-space letter */
  682. for(start=k->p+17;
  683. *start && isspace((int)*start);
  684. start++);
  685. /* Record the content-encoding for later use */
  686. if (checkprefix("identity", start))
  687. k->content_encoding = IDENTITY;
  688. else if (checkprefix("deflate", start))
  689. k->content_encoding = DEFLATE;
  690. else if (checkprefix("gzip", start)
  691. || checkprefix("x-gzip", start))
  692. k->content_encoding = GZIP;
  693. else if (checkprefix("compress", start)
  694. || checkprefix("x-compress", start))
  695. k->content_encoding = COMPRESS;
  696. }
  697. else if (Curl_compareheader(k->p, "Content-Range:", "bytes")) {
  698. /* Content-Range: bytes [num]-
  699. Content-Range: bytes: [num]-
  700. The second format was added August 1st 2000 by Igor
  701. Khristophorov since Sun's webserver JavaWebServer/1.1.1
  702. obviously sends the header this way! :-( */
  703. char *ptr = strstr(k->p, "bytes");
  704. ptr+=5;
  705. if(*ptr == ':')
  706. /* stupid colon skip */
  707. ptr++;
  708. k->offset = curlx_strtoofft(ptr, NULL, 10);
  709. if (conn->resume_from == k->offset)
  710. /* we asked for a resume and we got it */
  711. k->content_range = TRUE;
  712. }
  713. else if(data->cookies &&
  714. checkprefix("Set-Cookie:", k->p)) {
  715. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
  716. CURL_LOCK_ACCESS_SINGLE);
  717. Curl_cookie_add(data,
  718. data->cookies, TRUE, k->p+11,
  719. /* If there is a custom-set Host: name, use it
  720. here, or else use real peer host name. */
  721. conn->allocptr.cookiehost?
  722. conn->allocptr.cookiehost:conn->host.name,
  723. conn->path);
  724. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  725. }
  726. else if(checkprefix("Last-Modified:", k->p) &&
  727. (data->set.timecondition || data->set.get_filetime) ) {
  728. time_t secs=time(NULL);
  729. k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
  730. &secs);
  731. if(data->set.get_filetime)
  732. data->info.filetime = k->timeofdoc;
  733. }
  734. else if((checkprefix("WWW-Authenticate:", k->p) &&
  735. (401 == k->httpcode)) ||
  736. (checkprefix("Proxy-authenticate:", k->p) &&
  737. (407 == k->httpcode))) {
  738. result = Curl_http_input_auth(conn, k->httpcode, k->p);
  739. if(result)
  740. return result;
  741. }
  742. else if ((k->httpcode >= 300 && k->httpcode < 400) &&
  743. checkprefix("Location:", k->p)) {
  744. if(data->set.http_follow_location) {
  745. /* this is the URL that the server advices us to get instead */
  746. char *ptr;
  747. char *start=k->p;
  748. char backup;
  749. start += 9; /* pass "Location:" */
  750. /* Skip spaces and tabs. We do this to support multiple
  751. white spaces after the "Location:" keyword. */
  752. while(*start && isspace((int)*start ))
  753. start++;
  754. /* Scan through the string from the end to find the last
  755. non-space. k->end_ptr points to the actual terminating zero
  756. letter, move pointer one letter back and start from
  757. there. This logic strips off trailing whitespace, but keeps
  758. any embedded whitespace. */
  759. ptr = k->end_ptr-1;
  760. while((ptr>=start) && isspace((int)*ptr))
  761. ptr--;
  762. ptr++;
  763. backup = *ptr; /* store the ending letter */
  764. if(ptr != start) {
  765. *ptr = '\0'; /* zero terminate */
  766. conn->newurl = strdup(start); /* clone string */
  767. *ptr = backup; /* restore ending letter */
  768. if(!conn->newurl)
  769. return CURLE_OUT_OF_MEMORY;
  770. }
  771. }
  772. }
  773. #endif /* CURL_DISABLE_HTTP */
  774. /*
  775. * End of header-checks. Write them to the client.
  776. */
  777. writetype = CLIENTWRITE_HEADER;
  778. if (data->set.include_header)
  779. writetype |= CLIENTWRITE_BODY;
  780. if(data->set.verbose)
  781. Curl_debug(data, CURLINFO_HEADER_IN,
  782. k->p, k->hbuflen, conn->host.dispname);
  783. result = Curl_client_write(data, writetype, k->p, k->hbuflen);
  784. if(result)
  785. return result;
  786. data->info.header_size += k->hbuflen;
  787. conn->headerbytecount += k->hbuflen;
  788. /* reset hbufp pointer && hbuflen */
  789. k->hbufp = data->state.headerbuff;
  790. k->hbuflen = 0;
  791. }
  792. while (!stop_reading && *k->str); /* header line within buffer */
  793. if(stop_reading)
  794. /* We've stopped dealing with input, get out of the do-while loop */
  795. break;
  796. /* We might have reached the end of the header part here, but
  797. there might be a non-header part left in the end of the read
  798. buffer. */
  799. } /* end if header mode */
  800. /* This is not an 'else if' since it may be a rest from the header
  801. parsing, where the beginning of the buffer is headers and the end
  802. is non-headers. */
  803. if (k->str && !k->header && (nread > 0)) {
  804. if(0 == k->bodywrites) {
  805. /* These checks are only made the first time we are about to
  806. write a piece of the body */
  807. if(conn->protocol&PROT_HTTP) {
  808. /* HTTP-only checks */
  809. if (conn->newurl) {
  810. if(conn->bits.close) {
  811. /* Abort after the headers if "follow Location" is set
  812. and we're set to close anyway. */
  813. k->keepon &= ~KEEP_READ;
  814. FD_ZERO(&k->rkeepfd);
  815. *done = TRUE;
  816. return CURLE_OK;
  817. }
  818. /* We have a new url to load, but since we want to be able
  819. to re-use this connection properly, we read the full
  820. response in "ignore more" */
  821. k->ignorebody = TRUE;
  822. infof(data, "Ignoring the response-body\n");
  823. }
  824. if(data->set.timecondition && !conn->range) {
  825. /* A time condition has been set AND no ranges have been
  826. requested. This seems to be what chapter 13.3.4 of
  827. RFC 2616 defines to be the correct action for a
  828. HTTP/1.1 client */
  829. if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
  830. switch(data->set.timecondition) {
  831. case CURL_TIMECOND_IFMODSINCE:
  832. default:
  833. if(k->timeofdoc < data->set.timevalue) {
  834. infof(data,
  835. "The requested document is not new enough\n");
  836. *done = TRUE;
  837. return CURLE_OK;
  838. }
  839. break;
  840. case CURL_TIMECOND_IFUNMODSINCE:
  841. if(k->timeofdoc > data->set.timevalue) {
  842. infof(data,
  843. "The requested document is not old enough\n");
  844. *done = TRUE;
  845. return CURLE_OK;
  846. }
  847. break;
  848. } /* switch */
  849. } /* two valid time strings */
  850. } /* we have a time condition */
  851. } /* this is HTTP */
  852. } /* this is the first time we write a body part */
  853. k->bodywrites++;
  854. /* pass data to the debug function before it gets "dechunked" */
  855. if(data->set.verbose) {
  856. if(k->badheader) {
  857. Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
  858. k->hbuflen, conn->host.dispname);
  859. if(k->badheader == HEADER_PARTHEADER)
  860. Curl_debug(data, CURLINFO_DATA_IN, k->str, nread,
  861. conn->host.dispname);
  862. }
  863. else
  864. Curl_debug(data, CURLINFO_DATA_IN, k->str, nread,
  865. conn->host.dispname);
  866. }
  867. #ifndef CURL_DISABLE_HTTP
  868. if(conn->bits.chunk) {
  869. /*
  870. * Bless me father for I have sinned. Here comes a chunked
  871. * transfer flying and we need to decode this properly. While
  872. * the name says read, this function both reads and writes away
  873. * the data. The returned 'nread' holds the number of actual
  874. * data it wrote to the client. */
  875. CHUNKcode res =
  876. Curl_httpchunk_read(conn, k->str, nread, &nread);
  877. if(CHUNKE_OK < res) {
  878. if(CHUNKE_WRITE_ERROR == res) {
  879. failf(data, "Failed writing data");
  880. return CURLE_WRITE_ERROR;
  881. }
  882. failf(data, "Received problem %d in the chunky parser", res);
  883. return CURLE_RECV_ERROR;
  884. }
  885. else if(CHUNKE_STOP == res) {
  886. /* we're done reading chunks! */
  887. k->keepon &= ~KEEP_READ; /* read no more */
  888. FD_ZERO(&k->rkeepfd);
  889. /* There are now possibly N number of bytes at the end of the
  890. str buffer that weren't written to the client, but we don't
  891. care about them right now. */
  892. }
  893. /* If it returned OK, we just keep going */
  894. }
  895. #endif /* CURL_DISABLE_HTTP */
  896. if((-1 != conn->maxdownload) &&
  897. (k->bytecount + nread >= conn->maxdownload)) {
  898. nread = (ssize_t) (conn->maxdownload - k->bytecount);
  899. if(nread < 0 ) /* this should be unusual */
  900. nread = 0;
  901. k->keepon &= ~KEEP_READ; /* we're done reading */
  902. FD_ZERO(&k->rkeepfd);
  903. }
  904. k->bytecount += nread;
  905. Curl_pgrsSetDownloadCounter(data, k->bytecount);
  906. if(!conn->bits.chunk && (nread || k->badheader)) {
  907. /* If this is chunky transfer, it was already written */
  908. if(k->badheader && !k->ignorebody) {
  909. /* we parsed a piece of data wrongly assuming it was a header
  910. and now we output it as body instead */
  911. result = Curl_client_write(data, CLIENTWRITE_BODY,
  912. data->state.headerbuff,
  913. k->hbuflen);
  914. }
  915. if(k->badheader < HEADER_ALLBAD) {
  916. /* This switch handles various content encodings. If there's an
  917. error here, be sure to check over the almost identical code
  918. in http_chunks.c.
  919. Make sure that ALL_CONTENT_ENCODINGS contains all the
  920. encodings handled here. */
  921. #ifdef HAVE_LIBZ
  922. switch (k->content_encoding) {
  923. case IDENTITY:
  924. #endif
  925. /* This is the default when the server sends no
  926. Content-Encoding header. See Curl_readwrite_init; the
  927. memset() call initializes k->content_encoding to zero. */
  928. if(!k->ignorebody)
  929. result = Curl_client_write(data, CLIENTWRITE_BODY, k->str,
  930. nread);
  931. #ifdef HAVE_LIBZ
  932. break;
  933. case DEFLATE:
  934. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  935. result = Curl_unencode_deflate_write(data, k, nread);
  936. break;
  937. case GZIP:
  938. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  939. result = Curl_unencode_gzip_write(data, k, nread);
  940. break;
  941. case COMPRESS:
  942. default:
  943. failf (data, "Unrecognized content encoding type. "
  944. "libcurl understands `identity', `deflate' and `gzip' "
  945. "content encodings.");
  946. result = CURLE_BAD_CONTENT_ENCODING;
  947. break;
  948. }
  949. #endif
  950. }
  951. k->badheader = HEADER_NORMAL; /* taken care of now */
  952. if(result)
  953. return result;
  954. }
  955. } /* if (! header and data to read ) */
  956. } while(!readdone);
  957. } /* if( read from socket ) */
  958. /* If we still have writing to do, we check if we have a writable
  959. socket. Sometimes the writefdp is NULL, if no fd_set was done using
  960. the multi interface and then we can do nothing but to attempt a
  961. write to be sure. */
  962. if((k->keepon & KEEP_WRITE) &&
  963. (!writefdp || FD_ISSET(conn->writesockfd, writefdp)) ) {
  964. /* write */
  965. int i, si;
  966. ssize_t bytes_written;
  967. bool writedone=TRUE;
  968. if ((k->bytecount == 0) && (k->writebytecount == 0))
  969. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  970. didwhat |= KEEP_WRITE;
  971. /*
  972. * We loop here to do the READ and SEND loop until we run out of
  973. * data to send or until we get EWOULDBLOCK back
  974. */
  975. do {
  976. /* only read more data if there's no upload data already
  977. present in the upload buffer */
  978. if(0 == conn->upload_present) {
  979. /* init the "upload from here" pointer */
  980. conn->upload_fromhere = k->uploadbuf;
  981. if(!k->upload_done) {
  982. /* HTTP pollution, this should be written nicer to become more
  983. protocol agnostic. */
  984. int fillcount;
  985. if(k->wait100_after_headers &&
  986. (conn->proto.http->sending == HTTPSEND_BODY)) {
  987. /* If this call is to send body data, we must take some action:
  988. We have sent off the full HTTP 1.1 request, and we shall now
  989. go into the Expect: 100 state and await such a header */
  990. k->wait100_after_headers = FALSE; /* headers sent */
  991. k->write_after_100_header = TRUE; /* wait for the header */
  992. FD_ZERO (&k->writefd); /* clear it */
  993. k->wkeepfd = k->writefd; /* set the keeper variable */
  994. k->keepon &= ~KEEP_WRITE; /* disable writing */
  995. k->start100 = Curl_tvnow(); /* timeout count starts now */
  996. didwhat &= ~KEEP_WRITE; /* we didn't write anything actually */
  997. break;
  998. }
  999. result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
  1000. if(result)
  1001. return result;
  1002. nread = (ssize_t)fillcount;
  1003. }
  1004. else
  1005. nread = 0; /* we're done uploading/reading */
  1006. /* the signed int typecase of nread of for systems that has
  1007. unsigned size_t */
  1008. if (nread<=0) {
  1009. /* done */
  1010. k->keepon &= ~KEEP_WRITE; /* we're done writing */
  1011. FD_ZERO(&k->wkeepfd);
  1012. writedone = TRUE;
  1013. (void)writedone;
  1014. break;
  1015. }
  1016. /* store number of bytes available for upload */
  1017. conn->upload_present = nread;
  1018. /* convert LF to CRLF if so asked */
  1019. if (data->set.crlf) {
  1020. if(data->state.scratch == NULL)
  1021. data->state.scratch = malloc(2*BUFSIZE);
  1022. if(data->state.scratch == NULL) {
  1023. failf (data, "Failed to alloc scratch buffer!");
  1024. return CURLE_OUT_OF_MEMORY;
  1025. }
  1026. for(i = 0, si = 0; i < nread; i++, si++) {
  1027. if (conn->upload_fromhere[i] == 0x0a) {
  1028. data->state.scratch[si++] = 0x0d;
  1029. data->state.scratch[si] = 0x0a;
  1030. }
  1031. else
  1032. data->state.scratch[si] = conn->upload_fromhere[i];
  1033. }
  1034. if(si != nread) {
  1035. /* only perform the special operation if we really did replace
  1036. anything */
  1037. nread = si;
  1038. /* upload from the new (replaced) buffer instead */
  1039. conn->upload_fromhere = data->state.scratch;
  1040. /* set the new amount too */
  1041. conn->upload_present = nread;
  1042. }
  1043. }
  1044. }
  1045. else {
  1046. /* We have a partial buffer left from a previous "round". Use
  1047. that instead of reading more data */
  1048. }
  1049. /* write to socket (send away data) */
  1050. result = Curl_write(conn,
  1051. conn->writesockfd, /* socket to send to */
  1052. conn->upload_fromhere, /* buffer pointer */
  1053. conn->upload_present, /* buffer size */
  1054. &bytes_written); /* actually send away */
  1055. if(result)
  1056. return result;
  1057. if(data->set.verbose)
  1058. /* show the data before we change the pointer upload_fromhere */
  1059. Curl_debug(data, CURLINFO_DATA_OUT, conn->upload_fromhere,
  1060. bytes_written, conn->host.dispname);
  1061. if(conn->upload_present != bytes_written) {
  1062. /* we only wrote a part of the buffer (if anything), deal with it! */
  1063. /* store the amount of bytes left in the buffer to write */
  1064. conn->upload_present -= bytes_written;
  1065. /* advance the pointer where to find the buffer when the next send
  1066. is to happen */
  1067. conn->upload_fromhere += bytes_written;
  1068. writedone = TRUE; /* we are done, stop the loop */
  1069. }
  1070. else {
  1071. /* we've uploaded that buffer now */
  1072. conn->upload_fromhere = k->uploadbuf;
  1073. conn->upload_present = 0; /* no more bytes left */
  1074. if(k->upload_done) {
  1075. /* switch off writing, we're done! */
  1076. k->keepon &= ~KEEP_WRITE; /* we're done writing */
  1077. FD_ZERO(&k->wkeepfd);
  1078. writedone = TRUE;
  1079. }
  1080. }
  1081. k->writebytecount += bytes_written;
  1082. Curl_pgrsSetUploadCounter(data, k->writebytecount);
  1083. } while(!writedone); /* loop until we're done writing! */
  1084. }
  1085. } while(0); /* just to break out from! */
  1086. k->now = Curl_tvnow();
  1087. if(didwhat) {
  1088. /* Update read/write counters */
  1089. if(conn->bytecountp)
  1090. *conn->bytecountp = k->bytecount; /* read count */
  1091. if(conn->writebytecountp)
  1092. *conn->writebytecountp = k->writebytecount; /* write count */
  1093. }
  1094. else {
  1095. /* no read no write, this is a timeout? */
  1096. if (k->write_after_100_header) {
  1097. /* This should allow some time for the header to arrive, but only a
  1098. very short time as otherwise it'll be too much wasted times too
  1099. often. */
  1100. /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
  1101. Therefore, when a client sends this header field to an origin server
  1102. (possibly via a proxy) from which it has never seen a 100 (Continue)
  1103. status, the client SHOULD NOT wait for an indefinite period before
  1104. sending the request body.
  1105. */
  1106. long ms = Curl_tvdiff(k->now, k->start100);
  1107. if(ms > CURL_TIMEOUT_EXPECT_100) {
  1108. /* we've waited long enough, continue anyway */
  1109. k->write_after_100_header = FALSE;
  1110. FD_SET (conn->writesockfd, &k->writefd); /* write socket */
  1111. k->keepon |= KEEP_WRITE;
  1112. k->wkeepfd = k->writefd;
  1113. }
  1114. }
  1115. }
  1116. if(Curl_pgrsUpdate(conn))
  1117. result = CURLE_ABORTED_BY_CALLBACK;
  1118. else
  1119. result = Curl_speedcheck(data, k->now);
  1120. if (result)
  1121. return result;
  1122. if (data->set.timeout &&
  1123. ((Curl_tvdiff(k->now, k->start)/1000) >= data->set.timeout)) {
  1124. failf(data, "Operation timed out with %" FORMAT_OFF_T
  1125. " out of %" FORMAT_OFF_T " bytes received",
  1126. k->bytecount, conn->size);
  1127. return CURLE_OPERATION_TIMEOUTED;
  1128. }
  1129. if(!k->keepon) {
  1130. /*
  1131. * The transfer has been performed. Just make some general checks before
  1132. * returning.
  1133. */
  1134. if(!(conn->bits.no_body) && (conn->size != -1) &&
  1135. (k->bytecount != conn->size) &&
  1136. !conn->newurl) {
  1137. failf(data, "transfer closed with %" FORMAT_OFF_T
  1138. " bytes remaining to read",
  1139. conn->size - k->bytecount);
  1140. return CURLE_PARTIAL_FILE;
  1141. }
  1142. else if(conn->bits.chunk && conn->proto.http->chunk.datasize) {
  1143. failf(data, "transfer closed with at least %d bytes remaining",
  1144. conn->proto.http->chunk.datasize);
  1145. return CURLE_PARTIAL_FILE;
  1146. }
  1147. if(Curl_pgrsUpdate(conn))
  1148. return CURLE_ABORTED_BY_CALLBACK;
  1149. }
  1150. /* Now update the "done" boolean we return */
  1151. *done = !k->keepon;
  1152. return CURLE_OK;
  1153. }
  1154. /*
  1155. * Curl_readwrite_init() inits the readwrite session.
  1156. */
  1157. CURLcode Curl_readwrite_init(struct connectdata *conn)
  1158. {
  1159. struct SessionHandle *data;
  1160. struct Curl_transfer_keeper *k = &conn->keep;
  1161. /* NB: the content encoding software depends on this initialization of
  1162. Curl_transfer_keeper. */
  1163. memset(k, 0, sizeof(struct Curl_transfer_keeper));
  1164. k->start = Curl_tvnow(); /* start time */
  1165. k->now = k->start; /* current time is now */
  1166. k->header = TRUE; /* assume header */
  1167. k->httpversion = -1; /* unknown at this point */
  1168. data = conn->data; /* there's the root struct */
  1169. k->buf = data->state.buffer;
  1170. k->uploadbuf = data->state.uploadbuffer;
  1171. k->maxfd = (conn->sockfd>conn->writesockfd?
  1172. conn->sockfd:conn->writesockfd)+1;
  1173. k->hbufp = data->state.headerbuff;
  1174. k->ignorebody=FALSE;
  1175. Curl_pgrsTime(data, TIMER_PRETRANSFER);
  1176. Curl_speedinit(data);
  1177. Curl_pgrsSetUploadCounter(data, 0);
  1178. Curl_pgrsSetDownloadCounter(data, 0);
  1179. if (!conn->bits.getheader) {
  1180. k->header = FALSE;
  1181. if(conn->size > 0)
  1182. Curl_pgrsSetDownloadSize(data, conn->size);
  1183. }
  1184. /* we want header and/or body, if neither then don't do this! */
  1185. if(conn->bits.getheader || !conn->bits.no_body) {
  1186. FD_ZERO (&k->readfd); /* clear it */
  1187. if(conn->sockfd != CURL_SOCKET_BAD) {
  1188. FD_SET (conn->sockfd, &k->readfd); /* read socket */
  1189. k->keepon |= KEEP_READ;
  1190. }
  1191. FD_ZERO (&k->writefd); /* clear it */
  1192. if(conn->writesockfd != CURL_SOCKET_BAD) {
  1193. /* HTTP 1.1 magic:
  1194. Even if we require a 100-return code before uploading data, we might
  1195. need to write data before that since the REQUEST may not have been
  1196. finished sent off just yet.
  1197. Thus, we must check if the request has been sent before we set the
  1198. state info where we wait for the 100-return code
  1199. */
  1200. if (data->set.expect100header &&
  1201. (conn->proto.http->sending == HTTPSEND_BODY)) {
  1202. /* wait with write until we either got 100-continue or a timeout */
  1203. k->write_after_100_header = TRUE;
  1204. k->start100 = k->start;
  1205. }
  1206. else {
  1207. if(data->set.expect100header)
  1208. /* when we've sent off the rest of the headers, we must await a
  1209. 100-continue */
  1210. k->wait100_after_headers = TRUE;
  1211. FD_SET (conn->writesockfd, &k->writefd); /* write socket */
  1212. k->keepon |= KEEP_WRITE;
  1213. }
  1214. }
  1215. /* get these in backup variables to be able to restore them on each lap in
  1216. the select() loop */
  1217. k->rkeepfd = k->readfd;
  1218. k->wkeepfd = k->writefd;
  1219. }
  1220. return CURLE_OK;
  1221. }
  1222. /*
  1223. * Curl_single_fdset() gets called by the multi interface code when the app
  1224. * has requested to get the fd_sets for the current connection. This function
  1225. * will then be called once for every connection that the multi interface
  1226. * keeps track of. This function will only be called for connections that are
  1227. * in the proper state to have this information available.
  1228. */
  1229. void Curl_single_fdset(struct connectdata *conn,
  1230. fd_set *read_fd_set,
  1231. fd_set *write_fd_set,
  1232. fd_set *exc_fd_set,
  1233. int *max_fd)
  1234. {
  1235. *max_fd = -1; /* init */
  1236. if(conn->keep.keepon & KEEP_READ) {
  1237. FD_SET(conn->sockfd, read_fd_set);
  1238. *max_fd = conn->sockfd;
  1239. conn->keep.readfdp = read_fd_set; /* store the address of the set */
  1240. }
  1241. if(conn->keep.keepon & KEEP_WRITE) {
  1242. FD_SET(conn->writesockfd, write_fd_set);
  1243. /* since sockets are curl_socket_t nowadays, we typecast it to int here
  1244. to compare it nicely */
  1245. if((int)conn->writesockfd > *max_fd)
  1246. *max_fd = conn->writesockfd;
  1247. conn->keep.writefdp = write_fd_set; /* store the address of the set */
  1248. }
  1249. /* we don't use exceptions, only touch that one to prevent compiler
  1250. warnings! */
  1251. *exc_fd_set = *exc_fd_set;
  1252. }
  1253. /*
  1254. * Transfer()
  1255. *
  1256. * This function is what performs the actual transfer. It is capable of
  1257. * doing both ways simultaneously.
  1258. * The transfer must already have been setup by a call to Curl_Transfer().
  1259. *
  1260. * Note that headers are created in a preallocated buffer of a default size.
  1261. * That buffer can be enlarged on demand, but it is never shrunken again.
  1262. *
  1263. * Parts of this function was once written by the friendly Mark Butler
  1264. * <[email protected]>.
  1265. */
  1266. static CURLcode
  1267. Transfer(struct connectdata *conn)
  1268. {
  1269. CURLcode result;
  1270. struct Curl_transfer_keeper *k = &conn->keep;
  1271. bool done=FALSE;
  1272. if(!(conn->protocol & PROT_FILE))
  1273. /* Only do this if we are not transferring FILE:, since the file: treatment
  1274. is different*/
  1275. Curl_readwrite_init(conn);
  1276. if((conn->sockfd == CURL_SOCKET_BAD) &&
  1277. (conn->writesockfd == CURL_SOCKET_BAD))
  1278. /* nothing to read, nothing to write, we're already OK! */
  1279. return CURLE_OK;
  1280. /* we want header and/or body, if neither then don't do this! */
  1281. if(!conn->bits.getheader && conn->bits.no_body)
  1282. return CURLE_OK;
  1283. k->writefdp = &k->writefd; /* store the address of the set */
  1284. k->readfdp = &k->readfd; /* store the address of the set */
  1285. while (!done) {
  1286. struct timeval interval;
  1287. k->readfd = k->rkeepfd; /* set these every lap in the loop */
  1288. k->writefd = k->wkeepfd;
  1289. interval.tv_sec = 1;
  1290. interval.tv_usec = 0;
  1291. switch (select (k->maxfd, k->readfdp, k->writefdp, NULL, &interval)) {
  1292. case -1: /* select() error, stop reading */
  1293. #ifdef EINTR
  1294. /* The EINTR is not serious, and it seems you might get this more
  1295. ofen when using the lib in a multi-threaded environment! */
  1296. if(errno == EINTR)
  1297. ;
  1298. else
  1299. #endif
  1300. done = TRUE; /* no more read or write */
  1301. continue;
  1302. case 0: /* timeout */
  1303. default: /* readable descriptors */
  1304. result = Curl_readwrite(conn, &done);
  1305. break;
  1306. }
  1307. if(result)
  1308. return result;
  1309. /* "done" signals to us if the transfer(s) are ready */
  1310. }
  1311. return CURLE_OK;
  1312. }
  1313. /*
  1314. * Curl_pretransfer() is called immediately before a transfer starts.
  1315. */
  1316. CURLcode Curl_pretransfer(struct SessionHandle *data)
  1317. {
  1318. if(!data->change.url)
  1319. /* we can't do anything wihout URL */
  1320. return CURLE_URL_MALFORMAT;
  1321. #ifdef USE_SSLEAY
  1322. {
  1323. /* Init the SSL session ID cache here. We do it here since we want to do
  1324. it after the *_setopt() calls (that could change the size of the cache)
  1325. but before any transfer takes place. */
  1326. CURLcode res = Curl_SSL_InitSessions(data, data->set.ssl.numsessions);
  1327. if(res)
  1328. return res;
  1329. }
  1330. #endif
  1331. data->set.followlocation=0; /* reset the location-follow counter */
  1332. data->state.this_is_a_follow = FALSE; /* reset this */
  1333. data->state.errorbuf = FALSE; /* no error has occurred */
  1334. data->state.authproblem = FALSE;
  1335. data->state.authhost.want = data->set.httpauth;
  1336. data->state.authproxy.want = data->set.proxyauth;
  1337. #ifndef CURL_DISABLE_HTTP
  1338. /* If there was a list of cookie files to read and we haven't done it before,
  1339. do it now! */
  1340. if(data->change.cookielist) {
  1341. struct curl_slist *list = data->change.cookielist;
  1342. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  1343. while(list) {
  1344. data->cookies = Curl_cookie_init(data,
  1345. list->data,
  1346. data->cookies,
  1347. data->set.cookiesession);
  1348. list = list->next;
  1349. }
  1350. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1351. curl_slist_free_all(data->change.cookielist); /* clean up list */
  1352. data->change.cookielist = NULL; /* don't do this again! */
  1353. }
  1354. #endif /* CURL_DISABLE_HTTP */
  1355. /* Allow data->set.use_port to set which port to use. This needs to be
  1356. * disabled for example when we follow Location: headers to URLs using
  1357. * different ports! */
  1358. data->state.allow_port = TRUE;
  1359. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1360. /*************************************************************
  1361. * Tell signal handler to ignore SIGPIPE
  1362. *************************************************************/
  1363. if(!data->set.no_signal)
  1364. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1365. #endif
  1366. Curl_initinfo(data); /* reset session-specific information "variables" */
  1367. Curl_pgrsStartNow(data);
  1368. return CURLE_OK;
  1369. }
  1370. /*
  1371. * Curl_posttransfer() is called immediately after a transfer ends
  1372. */
  1373. CURLcode Curl_posttransfer(struct SessionHandle *data)
  1374. {
  1375. #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
  1376. /* restore the signal handler for SIGPIPE before we get back */
  1377. if(!data->set.no_signal)
  1378. signal(SIGPIPE, data->state.prev_signal);
  1379. #else
  1380. (void)data; /* unused parameter */
  1381. #endif
  1382. return CURLE_OK;
  1383. }
  1384. /*
  1385. * strlen_url() returns the length of the given URL if the spaces within the
  1386. * URL were properly URL encoded.
  1387. */
  1388. static int strlen_url(char *url)
  1389. {
  1390. char *ptr;
  1391. int newlen=0;
  1392. bool left=TRUE; /* left side of the ? */
  1393. for(ptr=url; *ptr; ptr++) {
  1394. switch(*ptr) {
  1395. case '?':
  1396. left=FALSE;
  1397. default:
  1398. newlen++;
  1399. break;
  1400. case ' ':
  1401. if(left)
  1402. newlen+=3;
  1403. else
  1404. newlen++;
  1405. break;
  1406. }
  1407. }
  1408. return newlen;
  1409. }
  1410. /* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
  1411. * the source URL accordingly.
  1412. */
  1413. static void strcpy_url(char *output, char *url)
  1414. {
  1415. /* we must add this with whitespace-replacing */
  1416. bool left=TRUE;
  1417. char *iptr;
  1418. char *optr = output;
  1419. for(iptr = url; /* read from here */
  1420. *iptr; /* until zero byte */
  1421. iptr++) {
  1422. switch(*iptr) {
  1423. case '?':
  1424. left=FALSE;
  1425. default:
  1426. *optr++=*iptr;
  1427. break;
  1428. case ' ':
  1429. if(left) {
  1430. *optr++='%'; /* add a '%' */
  1431. *optr++='2'; /* add a '2' */
  1432. *optr++='0'; /* add a '0' */
  1433. }
  1434. else
  1435. *optr++='+'; /* add a '+' here */
  1436. break;
  1437. }
  1438. }
  1439. *optr=0; /* zero terminate output buffer */
  1440. }
  1441. /*
  1442. * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
  1443. * as given by the remote server and set up the new URL to request.
  1444. */
  1445. CURLcode Curl_follow(struct SessionHandle *data,
  1446. char *newurl) /* this 'newurl' is the Location: string,
  1447. and it must be malloc()ed before passed
  1448. here */
  1449. {
  1450. /* Location: redirect */
  1451. char prot[16]; /* URL protocol string storage */
  1452. char letter; /* used for a silly sscanf */
  1453. size_t newlen;
  1454. char *newest;
  1455. if (data->set.maxredirs &&
  1456. (data->set.followlocation >= data->set.maxredirs)) {
  1457. failf(data,"Maximum (%d) redirects followed", data->set.maxredirs);
  1458. return CURLE_TOO_MANY_REDIRECTS;
  1459. }
  1460. /* mark the next request as a followed location: */
  1461. data->state.this_is_a_follow = TRUE;
  1462. data->set.followlocation++; /* count location-followers */
  1463. if(data->set.http_auto_referer) {
  1464. /* We are asked to automatically set the previous URL as the
  1465. referer when we get the next URL. We pick the ->url field,
  1466. which may or may not be 100% correct */
  1467. if(data->change.referer_alloc)
  1468. /* If we already have an allocated referer, free this first */
  1469. free(data->change.referer);
  1470. data->change.referer = strdup(data->change.url);
  1471. data->change.referer_alloc = TRUE; /* yes, free this later */
  1472. }
  1473. if(2 != sscanf(newurl, "%15[^?&/:]://%c", prot, &letter)) {
  1474. /***
  1475. *DANG* this is an RFC 2068 violation. The URL is supposed
  1476. to be absolute and this doesn't seem to be that!
  1477. ***
  1478. Instead, we have to TRY to append this new path to the old URL
  1479. to the right of the host part. Oh crap, this is doomed to cause
  1480. problems in the future...
  1481. */
  1482. char *protsep;
  1483. char *pathsep;
  1484. char *useurl = newurl;
  1485. size_t urllen;
  1486. /* we must make our own copy of the URL to play with, as it may
  1487. point to read-only data */
  1488. char *url_clone=strdup(data->change.url);
  1489. if(!url_clone)
  1490. return CURLE_OUT_OF_MEMORY; /* skip out of this NOW */
  1491. /* protsep points to the start of the host name */
  1492. protsep=strstr(url_clone, "//");
  1493. if(!protsep)
  1494. protsep=url_clone;
  1495. else
  1496. protsep+=2; /* pass the slashes */
  1497. if('/' != newurl[0]) {
  1498. int level=0;
  1499. /* First we need to find out if there's a ?-letter in the URL,
  1500. and cut it and the right-side of that off */
  1501. pathsep = strrchr(protsep, '?');
  1502. if(pathsep)
  1503. *pathsep=0;
  1504. /* we have a relative path to append to the last slash if
  1505. there's one available */
  1506. pathsep = strrchr(protsep, '/');
  1507. if(pathsep)
  1508. *pathsep=0;
  1509. /* Check if there's any slash after the host name, and if so,
  1510. remember that position instead */
  1511. pathsep = strchr(protsep, '/');
  1512. if(pathsep)
  1513. protsep = pathsep+1;
  1514. else
  1515. protsep = NULL;
  1516. /* now deal with one "./" or any amount of "../" in the newurl
  1517. and act accordingly */
  1518. if((useurl[0] == '.') && (useurl[1] == '/'))
  1519. useurl+=2; /* just skip the "./" */
  1520. while((useurl[0] == '.') &&
  1521. (useurl[1] == '.') &&
  1522. (useurl[2] == '/')) {
  1523. level++;
  1524. useurl+=3; /* pass the "../" */
  1525. }
  1526. if(protsep) {
  1527. while(level--) {
  1528. /* cut off one more level from the right of the original URL */
  1529. pathsep = strrchr(protsep, '/');
  1530. if(pathsep)
  1531. *pathsep=0;
  1532. else {
  1533. *protsep=0;
  1534. break;
  1535. }
  1536. }
  1537. }
  1538. }
  1539. else {
  1540. /* We got a new absolute path for this server, cut off from the
  1541. first slash */
  1542. pathsep = strchr(protsep, '/');
  1543. if(pathsep)
  1544. *pathsep=0;
  1545. else {
  1546. /* There was no slash. Now, since we might be operating on a badly
  1547. formatted URL, such as "http://www.url.com?id=2380" which doesn't
  1548. use a slash separator as it is supposed to, we need to check for a
  1549. ?-letter as well! */
  1550. pathsep = strchr(protsep, '?');
  1551. if(pathsep)
  1552. *pathsep=0;
  1553. }
  1554. }
  1555. /* If the new part contains a space, this is a mighty stupid redirect
  1556. but we still make an effort to do "right". To the left of a '?'
  1557. letter we replace each space with %20 while it is replaced with '+'
  1558. on the right side of the '?' letter.
  1559. */
  1560. newlen = strlen_url(useurl);
  1561. urllen = strlen(url_clone);
  1562. newest=(char *)malloc( urllen + 1 + /* possible slash */
  1563. newlen + 1 /* zero byte */);
  1564. if(!newest) {
  1565. free(url_clone); /* don't leak this */
  1566. return CURLE_OUT_OF_MEMORY; /* go out from this */
  1567. }
  1568. /* copy over the root url part */
  1569. memcpy(newest, url_clone, urllen);
  1570. /* check if we need to append a slash */
  1571. if(('/' == useurl[0]) || (protsep && !*protsep))
  1572. ;
  1573. else
  1574. newest[urllen++]='/';
  1575. /* then append the new piece on the right side */
  1576. strcpy_url(&newest[urllen], useurl);
  1577. free(newurl); /* newurl is the allocated pointer */
  1578. free(url_clone);
  1579. newurl = newest;
  1580. }
  1581. else {
  1582. /* This is an absolute URL, don't allow the custom port number */
  1583. data->state.allow_port = FALSE;
  1584. if(strchr(newurl, ' ')) {
  1585. /* This new URL contains at least one space, this is a mighty stupid
  1586. redirect but we still make an effort to do "right". */
  1587. newlen = strlen_url(newurl);
  1588. newest = malloc(newlen+1); /* get memory for this */
  1589. if(newest) {
  1590. strcpy_url(newest, newurl); /* create a space-free URL */
  1591. free(newurl); /* that was no good */
  1592. newurl = newest; /* use this instead now */
  1593. }
  1594. }
  1595. }
  1596. if(data->change.url_alloc)
  1597. free(data->change.url);
  1598. else
  1599. data->change.url_alloc = TRUE; /* the URL is allocated */
  1600. data->change.url = newurl;
  1601. newurl = NULL; /* don't free! */
  1602. (void)newurl;
  1603. infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
  1604. /*
  1605. * We get here when the HTTP code is 300-399 (and 401). We need to perform
  1606. * differently based on exactly what return code there was.
  1607. *
  1608. * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
  1609. * a HTTP (proxy-) authentication scheme other than Basic.
  1610. */
  1611. switch(data->info.httpcode) {
  1612. /* 401 - Act on a www-authentication, we keep on moving and do the
  1613. Authorization: XXXX header in the HTTP request code snippet */
  1614. /* 407 - Act on a proxy-authentication, we keep on moving and do the
  1615. Proxy-Authorization: XXXX header in the HTTP request code snippet */
  1616. /* 300 - Multiple Choices */
  1617. /* 306 - Not used */
  1618. /* 307 - Temporary Redirect */
  1619. default: /* for all above (and the unknown ones) */
  1620. /* Some codes are explicitly mentioned since I've checked RFC2616 and they
  1621. * seem to be OK to POST to.
  1622. */
  1623. break;
  1624. case 301: /* Moved Permanently */
  1625. /* (quote from RFC2616, section 10.3.2):
  1626. *
  1627. * Note: When automatically redirecting a POST request after receiving a
  1628. * 301 status code, some existing HTTP/1.0 user agents will erroneously
  1629. * change it into a GET request.
  1630. *
  1631. * ----
  1632. *
  1633. * Warning: Because most of importants user agents do this obvious RFC2616
  1634. * violation, many webservers expect this misbehavior. So these servers
  1635. * often answers to a POST request with an error page. To be sure that
  1636. * libcurl gets the page that most user agents would get, libcurl has to
  1637. * force GET:
  1638. */
  1639. if( data->set.httpreq == HTTPREQ_POST
  1640. || data->set.httpreq == HTTPREQ_POST_FORM) {
  1641. infof(data,
  1642. "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
  1643. data->set.httpreq = HTTPREQ_GET;
  1644. }
  1645. break;
  1646. case 302: /* Found */
  1647. /* (From 10.3.3)
  1648. Note: RFC 1945 and RFC 2068 specify that the client is not allowed
  1649. to change the method on the redirected request. However, most
  1650. existing user agent implementations treat 302 as if it were a 303
  1651. response, performing a GET on the Location field-value regardless
  1652. of the original request method. The status codes 303 and 307 have
  1653. been added for servers that wish to make unambiguously clear which
  1654. kind of reaction is expected of the client.
  1655. (From 10.3.4)
  1656. Note: Many pre-HTTP/1.1 user agents do not understand the 303
  1657. status. When interoperability with such clients is a concern, the
  1658. 302 status code may be used instead, since most user agents react
  1659. to a 302 response as described here for 303.
  1660. */
  1661. case 303: /* See Other */
  1662. /* Disable both types of POSTs, since doing a second POST when
  1663. * following isn't what anyone would want! */
  1664. if(data->set.httpreq != HTTPREQ_GET) {
  1665. data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
  1666. infof(data, "Disables POST, goes with %s\n",
  1667. data->set.opt_no_body?"HEAD":"GET");
  1668. }
  1669. break;
  1670. case 304: /* Not Modified */
  1671. /* 304 means we did a conditional request and it was "Not modified".
  1672. * We shouldn't get any Location: header in this response!
  1673. */
  1674. break;
  1675. case 305: /* Use Proxy */
  1676. /* (quote from RFC2616, section 10.3.6):
  1677. * "The requested resource MUST be accessed through the proxy given
  1678. * by the Location field. The Location field gives the URI of the
  1679. * proxy. The recipient is expected to repeat this single request
  1680. * via the proxy. 305 responses MUST only be generated by origin
  1681. * servers."
  1682. */
  1683. break;
  1684. }
  1685. Curl_pgrsTime(data, TIMER_REDIRECT);
  1686. Curl_pgrsResetTimes(data);
  1687. return CURLE_OK;
  1688. }
  1689. static CURLcode
  1690. Curl_connect_host(struct SessionHandle *data,
  1691. struct connectdata **conn)
  1692. {
  1693. CURLcode res;
  1694. int urlchanged;
  1695. do {
  1696. bool async;
  1697. Curl_pgrsTime(data, TIMER_STARTSINGLE);
  1698. data->change.url_changed = FALSE;
  1699. res = Curl_connect(data, conn, &async);
  1700. if((CURLE_OK == res) && async) {
  1701. /* Now, if async is TRUE here, we need to wait for the name
  1702. to resolve */
  1703. res = Curl_wait_for_resolv(*conn, NULL);
  1704. if(CURLE_OK == res)
  1705. /* Resolved, continue with the connection */
  1706. res = Curl_async_resolved(*conn);
  1707. }
  1708. if(res)
  1709. break;
  1710. /* If a callback (or something) has altered the URL we should use within
  1711. the Curl_connect(), we detect it here and act as if we are redirected
  1712. to the new URL */
  1713. urlchanged = data->change.url_changed;
  1714. if ((CURLE_OK == res) && urlchanged) {
  1715. res = Curl_done(conn, res);
  1716. if(CURLE_OK == res) {
  1717. char *gotourl = strdup(data->change.url);
  1718. res = Curl_follow(data, gotourl);
  1719. if(res)
  1720. free(gotourl);
  1721. }
  1722. }
  1723. } while (urlchanged && res == CURLE_OK);
  1724. return res;
  1725. }
  1726. /*
  1727. * Curl_perform() is the internal high-level function that gets called by the
  1728. * external curl_easy_perform() function. It inits, performs and cleans up a
  1729. * single file transfer.
  1730. */
  1731. CURLcode Curl_perform(struct SessionHandle *data)
  1732. {
  1733. CURLcode res;
  1734. CURLcode res2;
  1735. struct connectdata *conn=NULL;
  1736. char *newurl = NULL; /* possibly a new URL to follow to! */
  1737. data->state.used_interface = Curl_if_easy;
  1738. res = Curl_pretransfer(data);
  1739. if(res)
  1740. return res;
  1741. /*
  1742. * It is important that there is NO 'return' from this function at any other
  1743. * place than falling down to the end of the function! This is because we
  1744. * have cleanup stuff that must be done before we get back, and that is only
  1745. * performed after this do-while loop.
  1746. */
  1747. do {
  1748. res = Curl_connect_host(data, &conn); /* primary connection */
  1749. if(res == CURLE_OK) {
  1750. if (data->set.source_host) /* 3rd party transfer */
  1751. res = Curl_pretransfersec(conn);
  1752. else
  1753. conn->sec_conn = NULL;
  1754. }
  1755. if(res == CURLE_OK) {
  1756. res = Curl_do(&conn);
  1757. /* for non 3rd party transfer only */
  1758. if(res == CURLE_OK && !data->set.source_host) {
  1759. res = Transfer(conn); /* now fetch that URL please */
  1760. if(res == CURLE_OK) {
  1761. if((conn->keep.bytecount+conn->headerbytecount == 0) &&
  1762. conn->bits.reuse) {
  1763. /* We got no data and we attempted to re-use a connection. This
  1764. might happen if the connection was left alive when we were done
  1765. using it before, but that was closed when we wanted to read
  1766. from it again. Bad luck. Retry the same request on a fresh
  1767. connect! */
  1768. infof(data, "Connection died, retrying a fresh connect\n");
  1769. newurl = strdup(conn->data->change.url);
  1770. conn->bits.close = TRUE; /* close this connection */
  1771. conn->bits.retry = TRUE; /* mark this as a connection we're about
  1772. to retry. Marking it this way should
  1773. prevent i.e HTTP transfers to return
  1774. error just because nothing has been
  1775. transfered! */
  1776. }
  1777. else
  1778. /*
  1779. * We must duplicate the new URL here as the connection data
  1780. * may be free()ed in the Curl_done() function.
  1781. */
  1782. newurl = conn->newurl?strdup(conn->newurl):NULL;
  1783. }
  1784. else {
  1785. /* The transfer phase returned error, we mark the connection to get
  1786. * closed to prevent being re-used. This is becasue we can't
  1787. * possibly know if the connection is in a good shape or not now. */
  1788. conn->bits.close = TRUE;
  1789. if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
  1790. /* if we failed anywhere, we must clean up the secondary socket if
  1791. it was used */
  1792. sclose(conn->sock[SECONDARYSOCKET]);
  1793. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
  1794. }
  1795. }
  1796. /* Always run Curl_done(), even if some of the previous calls
  1797. failed, but return the previous (original) error code */
  1798. res2 = Curl_done(&conn, res);
  1799. if(CURLE_OK == res)
  1800. res = res2;
  1801. }
  1802. else
  1803. /* Curl_do() failed, clean up left-overs in the done-call */
  1804. res2 = Curl_done(&conn, res);
  1805. (void)res2;
  1806. /*
  1807. * Important: 'conn' cannot be used here, since it may have been closed
  1808. * in 'Curl_done' or other functions.
  1809. */
  1810. if((res == CURLE_OK) && newurl) {
  1811. res = Curl_follow(data, newurl);
  1812. if(CURLE_OK == res) {
  1813. newurl = NULL;
  1814. continue;
  1815. }
  1816. }
  1817. }
  1818. break; /* it only reaches here when this shouldn't loop */
  1819. } while(1); /* loop if Location: */
  1820. if(newurl)
  1821. free(newurl);
  1822. /* run post-transfer uncondionally, but don't clobber the return code if
  1823. we already have an error code recorder */
  1824. res2 = Curl_posttransfer(data);
  1825. if(!res && res2)
  1826. res = res2;
  1827. return res;
  1828. }
  1829. /*
  1830. * Curl_Transfer() is called to setup some basic properties for the upcoming
  1831. * transfer.
  1832. */
  1833. CURLcode
  1834. Curl_Transfer(struct connectdata *c_conn, /* connection data */
  1835. int sockindex, /* socket index to read from or -1 */
  1836. curl_off_t size, /* -1 if unknown at this point */
  1837. bool getheader, /* TRUE if header parsing is wanted */
  1838. curl_off_t *bytecountp, /* return number of bytes read or NULL */
  1839. int writesockindex, /* socket index to write to, it may very
  1840. well be the same we read from. -1
  1841. disables */
  1842. curl_off_t *writecountp /* return number of bytes written or
  1843. NULL */
  1844. )
  1845. {
  1846. struct connectdata *conn = (struct connectdata *)c_conn;
  1847. if(!conn)
  1848. return CURLE_BAD_FUNCTION_ARGUMENT;
  1849. curlassert((sockindex <= 1) && (sockindex >= -1));
  1850. /* now copy all input parameters */
  1851. conn->sockfd = sockindex==-1?
  1852. CURL_SOCKET_BAD:conn->sock[sockindex];
  1853. conn->size = size;
  1854. conn->bits.getheader = getheader;
  1855. conn->bytecountp = bytecountp;
  1856. conn->writesockfd = writesockindex==-1?
  1857. CURL_SOCKET_BAD:conn->sock[writesockindex];
  1858. conn->writebytecountp = writecountp;
  1859. return CURLE_OK;
  1860. }
  1861. /*
  1862. * Curl_pretransfersec() prepares the secondary connection (used for 3rd party
  1863. * FTP transfers).
  1864. */
  1865. CURLcode Curl_pretransfersec(struct connectdata *conn)
  1866. {
  1867. CURLcode status;
  1868. struct SessionHandle *data = conn->data;
  1869. struct connectdata *sec_conn = NULL; /* secondary connection */
  1870. /* update data with source host options */
  1871. char *url = aprintf( "%s://%s/", conn->protostr, data->set.source_host);
  1872. if(!url)
  1873. return CURLE_OUT_OF_MEMORY;
  1874. if(data->change.url_alloc)
  1875. free(data->change.url);
  1876. data->change.url_alloc = TRUE;
  1877. data->change.url = url;
  1878. data->set.ftpport = data->set.source_port;
  1879. data->set.userpwd = data->set.source_userpwd;
  1880. /* secondary connection */
  1881. status = Curl_connect_host(data, &sec_conn);
  1882. if(CURLE_OK == status) {
  1883. sec_conn->data = data;
  1884. conn->sec_conn = sec_conn;
  1885. }
  1886. return status;
  1887. }