transfer.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2002, 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. #include <sys/types.h>
  31. #include <sys/stat.h>
  32. #include <errno.h>
  33. #include "strequal.h"
  34. #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
  35. #include <winsock.h>
  36. #include <time.h>
  37. #include <io.h>
  38. #else
  39. #ifdef HAVE_SYS_SOCKET_H
  40. #include <sys/socket.h>
  41. #endif
  42. #include <netinet/in.h>
  43. #include <sys/time.h>
  44. #include <sys/resource.h>
  45. #ifdef HAVE_UNISTD_H
  46. #include <unistd.h>
  47. #endif
  48. #include <netdb.h>
  49. #ifdef HAVE_ARPA_INET_H
  50. #include <arpa/inet.h>
  51. #endif
  52. #ifdef HAVE_NET_IF_H
  53. #include <net/if.h>
  54. #endif
  55. #include <sys/ioctl.h>
  56. #include <signal.h>
  57. #ifdef HAVE_SYS_PARAM_H
  58. #include <sys/param.h>
  59. #endif
  60. #ifdef HAVE_SYS_SELECT_H
  61. #include <sys/select.h>
  62. #endif
  63. #ifndef HAVE_SELECT
  64. #error "We can't compile without select() support!"
  65. #endif
  66. #ifndef HAVE_SOCKET
  67. #error "We can't compile without socket() support!"
  68. #endif
  69. #endif
  70. #include "urldata.h"
  71. #include <curl/curl.h>
  72. #include <curl/types.h>
  73. #include "netrc.h"
  74. #include "content_encoding.h" /* content encoding support. 08/27/02 jhrg */
  75. #include "hostip.h"
  76. #include "transfer.h"
  77. #include "sendf.h"
  78. #include "speedcheck.h"
  79. #include "getpass.h"
  80. #include "progress.h"
  81. #include "getdate.h"
  82. #include "http.h"
  83. #include "url.h"
  84. #include "getinfo.h"
  85. #include "ssluse.h"
  86. #define _MPRINTF_REPLACE /* use our functions only */
  87. #include <curl/mprintf.h>
  88. /* The last #include file should be: */
  89. #ifdef MALLOCDEBUG
  90. #include "memdebug.h"
  91. #endif
  92. #ifndef min
  93. #define min(a, b) ((a) < (b) ? (a) : (b))
  94. #endif
  95. enum {
  96. KEEP_NONE,
  97. KEEP_READ,
  98. KEEP_WRITE
  99. };
  100. /* We keep this static and global since this is read-only and NEVER
  101. changed. It should just remain a blanked-out timeout value. */
  102. static struct timeval notimeout={0,0};
  103. /*
  104. * This function will call the read callback to fill our buffer with data
  105. * to upload.
  106. */
  107. static int fillbuffer(struct connectdata *conn,
  108. int bytes)
  109. {
  110. int buffersize = bytes;
  111. int nread;
  112. if(conn->bits.upload_chunky) {
  113. /* if chunked Transfer-Encoding */
  114. buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
  115. conn->upload_fromhere += 10; /* 32bit hex + CRLF */
  116. }
  117. nread = conn->fread(conn->upload_fromhere, 1,
  118. buffersize, conn->fread_in);
  119. if(!conn->bits.forbidchunk && conn->bits.upload_chunky) {
  120. /* if chunked Transfer-Encoding */
  121. char hexbuffer[11];
  122. int hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
  123. "%x\r\n", nread);
  124. /* move buffer pointer */
  125. conn->upload_fromhere -= hexlen;
  126. nread += hexlen;
  127. /* copy the prefix to the buffer */
  128. memcpy(conn->upload_fromhere, hexbuffer, hexlen);
  129. if(nread>hexlen) {
  130. /* append CRLF to the data */
  131. memcpy(conn->upload_fromhere +
  132. nread, "\r\n", 2);
  133. nread+=2;
  134. }
  135. else {
  136. /* mark this as done once this chunk is transfered */
  137. conn->keep.upload_done = TRUE;
  138. }
  139. }
  140. return nread;
  141. }
  142. /*
  143. * checkhttpprefix()
  144. *
  145. * Returns TRUE if member of the list matches prefix of string
  146. */
  147. static bool
  148. checkhttpprefix(struct SessionHandle *data,
  149. const char *s)
  150. {
  151. struct curl_slist *head = data->set.http200aliases;
  152. while (head) {
  153. if (checkprefix(head->data, s))
  154. return TRUE;
  155. head = head->next;
  156. }
  157. if(checkprefix("HTTP/", s))
  158. return TRUE;
  159. return FALSE;
  160. }
  161. CURLcode Curl_readwrite(struct connectdata *conn,
  162. bool *done)
  163. {
  164. struct Curl_transfer_keeper *k = &conn->keep;
  165. struct SessionHandle *data = conn->data;
  166. int result;
  167. ssize_t nread; /* number of bytes read */
  168. int didwhat=0;
  169. /* These two are used only if no other select() or _fdset() have been
  170. invoked before this. This typicly happens if you use the multi interface
  171. and call curl_multi_perform() without calling curl_multi_fdset()
  172. first. */
  173. fd_set extrareadfd;
  174. fd_set extrawritefd;
  175. fd_set *readfdp = k->readfdp;
  176. fd_set *writefdp = k->writefdp;
  177. if((k->keepon & KEEP_READ) && !readfdp) {
  178. /* reading is requested, but no socket descriptor pointer was set */
  179. FD_ZERO(&extrareadfd);
  180. FD_SET(conn->sockfd, &extrareadfd);
  181. readfdp = &extrareadfd;
  182. /* no write, no exceptions, no timeout */
  183. select(conn->sockfd+1, readfdp, NULL, NULL, &notimeout);
  184. }
  185. if((k->keepon & KEEP_WRITE) && !writefdp) {
  186. /* writing is requested, but no socket descriptor pointer was set */
  187. FD_ZERO(&extrawritefd);
  188. FD_SET(conn->writesockfd, &extrawritefd);
  189. writefdp = &extrawritefd;
  190. /* no read, no exceptions, no timeout */
  191. select(conn->writesockfd+1, NULL, writefdp, NULL, &notimeout);
  192. }
  193. do {
  194. /* If we still have reading to do, we check if we have a readable
  195. socket. Sometimes the reafdp is NULL, it no fd_set was done using
  196. the multi interface and then we can do nothing but to attempt a
  197. read to be sure. */
  198. if((k->keepon & KEEP_READ) &&
  199. (FD_ISSET(conn->sockfd, readfdp))) {
  200. bool readdone = FALSE;
  201. /* This is where we loop until we have read everything there is to
  202. read or we get a EWOULDBLOCK */
  203. do {
  204. /* read! */
  205. result = Curl_read(conn, conn->sockfd, k->buf,
  206. data->set.buffer_size?
  207. data->set.buffer_size:BUFSIZE -1,
  208. &nread);
  209. if(0>result)
  210. break; /* get out of loop */
  211. if(result>0)
  212. return result;
  213. if ((k->bytecount == 0) && (k->writebytecount == 0))
  214. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  215. didwhat |= KEEP_READ;
  216. /* NULL terminate, allowing string ops to be used */
  217. if (0 < nread)
  218. k->buf[nread] = 0;
  219. /* if we receive 0 or less here, the server closed the connection and
  220. we bail out from this! */
  221. else if (0 >= nread) {
  222. k->keepon &= ~KEEP_READ;
  223. FD_ZERO(&k->rkeepfd);
  224. readdone = TRUE;
  225. break;
  226. }
  227. /* Default buffer to use when we write the buffer, it may be changed
  228. in the flow below before the actual storing is done. */
  229. k->str = k->buf;
  230. /* Since this is a two-state thing, we check if we are parsing
  231. headers at the moment or not. */
  232. if (k->header) {
  233. /* we are in parse-the-header-mode */
  234. bool stop_reading = FALSE;
  235. /* header line within buffer loop */
  236. do {
  237. int hbufp_index;
  238. /* str_start is start of line within buf */
  239. k->str_start = k->str;
  240. k->end_ptr = strchr (k->str_start, '\n');
  241. if (!k->end_ptr) {
  242. /* Not a complete header line within buffer, append the data to
  243. the end of the headerbuff. */
  244. if (k->hbuflen + nread >= data->state.headersize) {
  245. /* We enlarge the header buffer as it is too small */
  246. char *newbuff;
  247. long newsize=MAX((k->hbuflen+nread)*3/2,
  248. data->state.headersize*2);
  249. hbufp_index = k->hbufp - data->state.headerbuff;
  250. newbuff = (char *)realloc(data->state.headerbuff, newsize);
  251. if(!newbuff) {
  252. failf (data, "Failed to alloc memory for big header!");
  253. return CURLE_OUT_OF_MEMORY;
  254. }
  255. data->state.headersize=newsize;
  256. data->state.headerbuff = newbuff;
  257. k->hbufp = data->state.headerbuff + hbufp_index;
  258. }
  259. memcpy(k->hbufp, k->str, nread);
  260. k->hbufp += nread;
  261. k->hbuflen += nread;
  262. if (!k->headerline && (k->hbuflen>5)) {
  263. /* make a first check that this looks like a HTTP header */
  264. if(!checkhttpprefix(data, data->state.headerbuff)) {
  265. /* this is not the beginning of a HTTP first header line */
  266. k->header = FALSE;
  267. k->badheader = HEADER_ALLBAD;
  268. break;
  269. }
  270. }
  271. break; /* read more and try again */
  272. }
  273. /* decrease the size of the remaining buffer */
  274. nread -= (k->end_ptr - k->str)+1;
  275. k->str = k->end_ptr + 1; /* move past new line */
  276. /*
  277. * We're about to copy a chunk of data to the end of the
  278. * already received header. We make sure that the full string
  279. * fit in the allocated header buffer, or else we enlarge
  280. * it.
  281. */
  282. if (k->hbuflen + (k->str - k->str_start) >=
  283. data->state.headersize) {
  284. char *newbuff;
  285. long newsize=MAX((k->hbuflen+
  286. (k->str-k->str_start))*3/2,
  287. data->state.headersize*2);
  288. hbufp_index = k->hbufp - data->state.headerbuff;
  289. newbuff = (char *)realloc(data->state.headerbuff, newsize);
  290. if(!newbuff) {
  291. failf (data, "Failed to alloc memory for big header!");
  292. return CURLE_OUT_OF_MEMORY;
  293. }
  294. data->state.headersize= newsize;
  295. data->state.headerbuff = newbuff;
  296. k->hbufp = data->state.headerbuff + hbufp_index;
  297. }
  298. /* copy to end of line */
  299. strncpy (k->hbufp, k->str_start, k->str - k->str_start);
  300. k->hbufp += k->str - k->str_start;
  301. k->hbuflen += k->str - k->str_start;
  302. *k->hbufp = 0;
  303. k->p = data->state.headerbuff;
  304. /****
  305. * We now have a FULL header line that p points to
  306. *****/
  307. if(!k->headerline) {
  308. /* the first read header */
  309. if((k->hbuflen>5) &&
  310. !checkhttpprefix(data, data->state.headerbuff)) {
  311. /* this is not the beginning of a HTTP first header line */
  312. k->header = FALSE;
  313. k->badheader = HEADER_PARTHEADER;
  314. break;
  315. }
  316. }
  317. if (('\n' == *k->p) || ('\r' == *k->p)) {
  318. int headerlen;
  319. /* Zero-length header line means end of headers! */
  320. if ('\r' == *k->p)
  321. k->p++; /* pass the \r byte */
  322. if ('\n' == *k->p)
  323. k->p++; /* pass the \n byte */
  324. if(100 == k->httpcode) {
  325. /*
  326. * we have made a HTTP PUT or POST and this is 1.1-lingo
  327. * that tells us that the server is OK with this and ready
  328. * to receive our stuff.
  329. * However, we'll get more headers now so we must get
  330. * back into the header-parsing state!
  331. */
  332. k->header = TRUE;
  333. k->headerline = 0; /* restart the header line counter */
  334. /* if we did wait for this do enable write now! */
  335. if (k->write_after_100_header) {
  336. k->write_after_100_header = FALSE;
  337. FD_SET (conn->writesockfd, &k->writefd); /* write */
  338. k->keepon |= KEEP_WRITE;
  339. k->wkeepfd = k->writefd;
  340. }
  341. }
  342. else
  343. k->header = FALSE; /* no more header to parse! */
  344. if (417 == k->httpcode) {
  345. /*
  346. * we got: "417 Expectation Failed" this means:
  347. * we have made a HTTP call and our Expect Header
  348. * seems to cause a problem => abort the write operations
  349. * (or prevent them from starting).
  350. */
  351. k->write_after_100_header = FALSE;
  352. k->keepon &= ~KEEP_WRITE;
  353. FD_ZERO(&k->wkeepfd);
  354. }
  355. /* now, only output this if the header AND body are requested:
  356. */
  357. k->writetype = CLIENTWRITE_HEADER;
  358. if (data->set.http_include_header)
  359. k->writetype |= CLIENTWRITE_BODY;
  360. headerlen = k->p - data->state.headerbuff;
  361. result = Curl_client_write(data, k->writetype,
  362. data->state.headerbuff,
  363. headerlen);
  364. if(result)
  365. return result;
  366. data->info.header_size += headerlen;
  367. conn->headerbytecount += headerlen;
  368. if(!k->header) {
  369. /*
  370. * really end-of-headers.
  371. *
  372. * If we requested a "no body", this is a good time to get
  373. * out and return home.
  374. */
  375. if(data->set.no_body)
  376. stop_reading = TRUE;
  377. else if(!conn->bits.close) {
  378. /* If this is not the last request before a close, we must
  379. set the maximum download size to the size of the
  380. expected document or else, we won't know when to stop
  381. reading! */
  382. if(-1 != conn->size)
  383. conn->maxdownload = conn->size;
  384. }
  385. /* If max download size is *zero* (nothing) we already
  386. have nothing and can safely return ok now! */
  387. if(0 == conn->maxdownload)
  388. stop_reading = TRUE;
  389. if(stop_reading) {
  390. /* we make sure that this socket isn't read more now */
  391. k->keepon &= ~KEEP_READ;
  392. FD_ZERO(&k->rkeepfd);
  393. }
  394. break; /* exit header line loop */
  395. }
  396. /* We continue reading headers, so reset the line-based
  397. header parsing variables hbufp && hbuflen */
  398. k->hbufp = data->state.headerbuff;
  399. k->hbuflen = 0;
  400. continue;
  401. }
  402. /*
  403. * Checks for special headers coming up.
  404. */
  405. if (!k->headerline++) {
  406. /* This is the first header, it MUST be the error code line
  407. or else we consiser this to be the body right away! */
  408. int httpversion_major;
  409. int nc=sscanf (k->p, " HTTP/%d.%d %3d",
  410. &httpversion_major,
  411. &k->httpversion,
  412. &k->httpcode);
  413. if (nc==3) {
  414. k->httpversion += 10 * httpversion_major;
  415. }
  416. else {
  417. /* this is the real world, not a Nirvana
  418. NCSA 1.5.x returns this crap when asked for HTTP/1.1
  419. */
  420. nc=sscanf (k->p, " HTTP %3d", &k->httpcode);
  421. k->httpversion = 10;
  422. /* If user has set option HTTP200ALIASES,
  423. compare header line against list of aliases
  424. */
  425. if (!nc) {
  426. if (checkhttpprefix(data, k->p)) {
  427. nc = 1;
  428. k->httpcode = 200;
  429. k->httpversion =
  430. (data->set.httpversion==CURL_HTTP_VERSION_1_0)? 10 : 11;
  431. }
  432. }
  433. }
  434. if (nc) {
  435. data->info.httpcode = k->httpcode;
  436. data->info.httpversion = k->httpversion;
  437. /* 404 -> URL not found! */
  438. if (data->set.http_fail_on_error &&
  439. (k->httpcode >= 400)) {
  440. /* If we have been told to fail hard on HTTP-errors,
  441. here is the check for that: */
  442. /* serious error, go home! */
  443. failf (data, "The requested file was not found");
  444. return CURLE_HTTP_RETURNED_ERROR;
  445. }
  446. if(k->httpversion == 10)
  447. /* Default action for HTTP/1.0 must be to close, unless
  448. we get one of those fancy headers that tell us the
  449. server keeps it open for us! */
  450. conn->bits.close = TRUE;
  451. switch(k->httpcode) {
  452. case 204:
  453. /* (quote from RFC2616, section 10.2.5): The server has
  454. * fulfilled the request but does not need to return an
  455. * entity-body ... The 204 response MUST NOT include a
  456. * message-body, and thus is always terminated by the first
  457. * empty line after the header fields. */
  458. /* FALLTHROUGH */
  459. case 304:
  460. /* (quote from RFC2616, section 10.3.5): The 304 response MUST
  461. * NOT contain a message-body, and thus is always terminated
  462. * by the first empty line after the header fields. */
  463. conn->size=0;
  464. conn->maxdownload=0;
  465. break;
  466. default:
  467. /* nothing */
  468. break;
  469. }
  470. }
  471. else {
  472. k->header = FALSE; /* this is not a header line */
  473. break;
  474. }
  475. }
  476. /* check for Content-Length: header lines to get size */
  477. if (checkprefix("Content-Length:", k->p) &&
  478. sscanf (k->p+15, " %ld", &k->contentlength)) {
  479. conn->size = k->contentlength;
  480. Curl_pgrsSetDownloadSize(data, k->contentlength);
  481. }
  482. /* check for Content-Type: header lines to get the mime-type */
  483. else if (checkprefix("Content-Type:", k->p)) {
  484. char *start;
  485. char *end;
  486. int len;
  487. /* Find the first non-space letter */
  488. for(start=k->p+14;
  489. *start && isspace((int)*start);
  490. start++);
  491. /* count all non-space letters following */
  492. for(end=start, len=0;
  493. *end && !isspace((int)*end);
  494. end++, len++);
  495. /* allocate memory of a cloned copy */
  496. data->info.contenttype = malloc(len + 1);
  497. if (NULL == data->info.contenttype)
  498. return CURLE_OUT_OF_MEMORY;
  499. /* copy the content-type string */
  500. memcpy(data->info.contenttype, start, len);
  501. data->info.contenttype[len] = 0; /* zero terminate */
  502. }
  503. else if((k->httpversion == 10) &&
  504. conn->bits.httpproxy &&
  505. Curl_compareheader(k->p,
  506. "Proxy-Connection:", "keep-alive")) {
  507. /*
  508. * When a HTTP/1.0 reply comes when using a proxy, the
  509. * 'Proxy-Connection: keep-alive' line tells us the
  510. * connection will be kept alive for our pleasure.
  511. * Default action for 1.0 is to close.
  512. */
  513. conn->bits.close = FALSE; /* don't close when done */
  514. infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
  515. }
  516. else if((k->httpversion == 10) &&
  517. Curl_compareheader(k->p, "Connection:", "keep-alive")) {
  518. /*
  519. * A HTTP/1.0 reply with the 'Connection: keep-alive' line
  520. * tells us the connection will be kept alive for our
  521. * pleasure. Default action for 1.0 is to close.
  522. *
  523. * [RFC2068, section 19.7.1] */
  524. conn->bits.close = FALSE; /* don't close when done */
  525. infof(data, "HTTP/1.0 connection set to keep alive!\n");
  526. }
  527. else if (Curl_compareheader(k->p, "Connection:", "close")) {
  528. /*
  529. * [RFC 2616, section 8.1.2.1]
  530. * "Connection: close" is HTTP/1.1 language and means that
  531. * the connection will close when this request has been
  532. * served.
  533. */
  534. conn->bits.close = TRUE; /* close when done */
  535. }
  536. else if (Curl_compareheader(k->p,
  537. "Transfer-Encoding:", "chunked")) {
  538. /*
  539. * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
  540. * means that the server will send a series of "chunks". Each
  541. * chunk starts with line with info (including size of the
  542. * coming block) (terminated with CRLF), then a block of data
  543. * with the previously mentioned size. There can be any amount
  544. * of chunks, and a chunk-data set to zero signals the
  545. * end-of-chunks. */
  546. conn->bits.chunk = TRUE; /* chunks coming our way */
  547. /* init our chunky engine */
  548. Curl_httpchunk_init(conn);
  549. }
  550. else if (checkprefix("Content-Encoding:", k->p) &&
  551. data->set.encoding) {
  552. /*
  553. * Process Content-Encoding. Look for the values: identity, gzip,
  554. * defalte, compress, x-gzip and x-compress. x-gzip and
  555. * x-compress are the same as gzip and compress. (Sec 3.5 RFC
  556. * 2616). zlib cannot handle compress, and gzip is not currently
  557. * implemented. However, errors are handled further down when the
  558. * response body is processed 08/27/02 jhrg */
  559. char *start;
  560. /* Find the first non-space letter */
  561. for(start=k->p+17;
  562. *start && isspace((int)*start);
  563. start++);
  564. /* Record the content-encoding for later use. 08/27/02 jhrg */
  565. if (checkprefix("identity", start))
  566. k->content_encoding = IDENTITY;
  567. else if (checkprefix("deflate", start))
  568. k->content_encoding = DEFLATE;
  569. else if (checkprefix("gzip", start)
  570. || checkprefix("x-gzip", start))
  571. k->content_encoding = GZIP;
  572. else if (checkprefix("compress", start)
  573. || checkprefix("x-compress", start))
  574. k->content_encoding = COMPRESS;
  575. }
  576. else if (checkprefix("Content-Range:", k->p)) {
  577. if (sscanf (k->p+14, " bytes %d-", &k->offset) ||
  578. sscanf (k->p+14, " bytes: %d-", &k->offset)) {
  579. /* This second format was added August 1st 2000 by Igor
  580. Khristophorov since Sun's webserver JavaWebServer/1.1.1
  581. obviously sends the header this way! :-( */
  582. if (conn->resume_from == k->offset) {
  583. /* we asked for a resume and we got it */
  584. k->content_range = TRUE;
  585. }
  586. }
  587. }
  588. else if(data->cookies &&
  589. checkprefix("Set-Cookie:", k->p)) {
  590. Curl_cookie_add(data->cookies, TRUE, k->p+11, conn->name);
  591. }
  592. else if(checkprefix("Last-Modified:", k->p) &&
  593. (data->set.timecondition || data->set.get_filetime) ) {
  594. time_t secs=time(NULL);
  595. k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
  596. &secs);
  597. if(data->set.get_filetime)
  598. data->info.filetime = k->timeofdoc;
  599. }
  600. else if ((k->httpcode >= 300 && k->httpcode < 400) &&
  601. (data->set.http_follow_location) &&
  602. checkprefix("Location:", k->p)) {
  603. /* this is the URL that the server advices us to get instead */
  604. char *ptr;
  605. char *start=k->p;
  606. char backup;
  607. start += 9; /* pass "Location:" */
  608. /* Skip spaces and tabs. We do this to support multiple
  609. white spaces after the "Location:" keyword. */
  610. while(*start && isspace((int)*start ))
  611. start++;
  612. ptr = start; /* start scanning here */
  613. /* scan through the string to find the end */
  614. while(*ptr && !isspace((int)*ptr))
  615. ptr++;
  616. backup = *ptr; /* store the ending letter */
  617. if(ptr != start) {
  618. *ptr = '\0'; /* zero terminate */
  619. conn->newurl = strdup(start); /* clone string */
  620. *ptr = backup; /* restore ending letter */
  621. }
  622. }
  623. /*
  624. * End of header-checks. Write them to the client.
  625. */
  626. k->writetype = CLIENTWRITE_HEADER;
  627. if (data->set.http_include_header)
  628. k->writetype |= CLIENTWRITE_BODY;
  629. if(data->set.verbose)
  630. Curl_debug(data, CURLINFO_HEADER_IN,
  631. k->p, k->hbuflen);
  632. result = Curl_client_write(data, k->writetype, k->p,
  633. k->hbuflen);
  634. if(result)
  635. return result;
  636. data->info.header_size += k->hbuflen;
  637. conn->headerbytecount += k->hbuflen;
  638. /* reset hbufp pointer && hbuflen */
  639. k->hbufp = data->state.headerbuff;
  640. k->hbuflen = 0;
  641. }
  642. while (!stop_reading && *k->str); /* header line within buffer */
  643. if(stop_reading)
  644. /* We've stopped dealing with input, get out of the do-while loop */
  645. break;
  646. /* We might have reached the end of the header part here, but
  647. there might be a non-header part left in the end of the read
  648. buffer. */
  649. } /* end if header mode */
  650. /* This is not an 'else if' since it may be a rest from the header
  651. parsing, where the beginning of the buffer is headers and the end
  652. is non-headers. */
  653. if (k->str && !k->header && (nread > 0)) {
  654. if(0 == k->bodywrites) {
  655. /* These checks are only made the first time we are about to
  656. write a piece of the body */
  657. if(conn->protocol&PROT_HTTP) {
  658. /* HTTP-only checks */
  659. if (conn->newurl) {
  660. /* abort after the headers if "follow Location" is set */
  661. infof (data, "Follow to new URL: %s\n", conn->newurl);
  662. k->keepon &= ~KEEP_READ;
  663. FD_ZERO(&k->rkeepfd);
  664. *done = TRUE;
  665. return CURLE_OK;
  666. }
  667. else if (conn->resume_from &&
  668. !k->content_range &&
  669. (data->set.httpreq==HTTPREQ_GET)) {
  670. /* we wanted to resume a download, although the server
  671. doesn't seem to support this and we did this with a GET
  672. (if it wasn't a GET we did a POST or PUT resume) */
  673. failf (data, "HTTP server doesn't seem to support "
  674. "byte ranges. Cannot resume.");
  675. return CURLE_HTTP_RANGE_ERROR;
  676. }
  677. else if(data->set.timecondition && !conn->range) {
  678. /* A time condition has been set AND no ranges have been
  679. requested. This seems to be what chapter 13.3.4 of
  680. RFC 2616 defines to be the correct action for a
  681. HTTP/1.1 client */
  682. if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
  683. switch(data->set.timecondition) {
  684. case TIMECOND_IFMODSINCE:
  685. default:
  686. if(k->timeofdoc < data->set.timevalue) {
  687. infof(data,
  688. "The requested document is not new enough\n");
  689. *done = TRUE;
  690. return CURLE_OK;
  691. }
  692. break;
  693. case TIMECOND_IFUNMODSINCE:
  694. if(k->timeofdoc > data->set.timevalue) {
  695. infof(data,
  696. "The requested document is not old enough\n");
  697. *done = TRUE;
  698. return CURLE_OK;
  699. }
  700. break;
  701. } /* switch */
  702. } /* two valid time strings */
  703. } /* we have a time condition */
  704. } /* this is HTTP */
  705. } /* this is the first time we write a body part */
  706. k->bodywrites++;
  707. /* pass data to the debug function before it gets "dechunked" */
  708. if(data->set.verbose) {
  709. if(k->badheader) {
  710. Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
  711. k->hbuflen);
  712. if(k->badheader == HEADER_PARTHEADER)
  713. Curl_debug(data, CURLINFO_DATA_IN, k->str, nread);
  714. }
  715. else
  716. Curl_debug(data, CURLINFO_DATA_IN, k->str, nread);
  717. }
  718. if(conn->bits.chunk) {
  719. /*
  720. * Bless me father for I have sinned. Here comes a chunked
  721. * transfer flying and we need to decode this properly. While
  722. * the name says read, this function both reads and writes away
  723. * the data. The returned 'nread' holds the number of actual
  724. * data it wrote to the client. */
  725. CHUNKcode res =
  726. Curl_httpchunk_read(conn, k->str, nread, &nread);
  727. if(CHUNKE_OK < res) {
  728. if(CHUNKE_WRITE_ERROR == res) {
  729. failf(data, "Failed writing data");
  730. return CURLE_WRITE_ERROR;
  731. }
  732. failf(data, "Received problem in the chunky parser");
  733. return CURLE_RECV_ERROR;
  734. }
  735. else if(CHUNKE_STOP == res) {
  736. /* we're done reading chunks! */
  737. k->keepon &= ~KEEP_READ; /* read no more */
  738. FD_ZERO(&k->rkeepfd);
  739. /* There are now possibly N number of bytes at the end of the
  740. str buffer that weren't written to the client, but we don't
  741. care about them right now. */
  742. }
  743. /* If it returned OK, we just keep going */
  744. }
  745. if((-1 != conn->maxdownload) &&
  746. (k->bytecount + nread >= conn->maxdownload)) {
  747. nread = conn->maxdownload - k->bytecount;
  748. if(nread < 0 ) /* this should be unusual */
  749. nread = 0;
  750. k->keepon &= ~KEEP_READ; /* we're done reading */
  751. FD_ZERO(&k->rkeepfd);
  752. }
  753. k->bytecount += nread;
  754. Curl_pgrsSetDownloadCounter(data, (double)k->bytecount);
  755. if(!conn->bits.chunk && (nread || k->badheader)) {
  756. /* If this is chunky transfer, it was already written */
  757. if(k->badheader) {
  758. /* we parsed a piece of data wrongly assuming it was a header
  759. and now we output it as body instead */
  760. result = Curl_client_write(data, CLIENTWRITE_BODY,
  761. data->state.headerbuff,
  762. k->hbuflen);
  763. }
  764. if(k->badheader < HEADER_ALLBAD) {
  765. /* This switch handles various content encodings. If there's an
  766. error here, be sure to check over the almost identical code
  767. in http_chunk.c. 08/29/02 jhrg */
  768. #ifdef HAVE_LIBZ
  769. switch (k->content_encoding) {
  770. case IDENTITY:
  771. #endif
  772. /* This is the default when the server sends no
  773. Content-Encoding header. See Curl_readwrite_init; the
  774. memset() call initializes k->content_encoding to zero.
  775. 08/28/02 jhrg */
  776. result = Curl_client_write(data, CLIENTWRITE_BODY, k->str,
  777. nread);
  778. #ifdef HAVE_LIBZ
  779. break;
  780. case DEFLATE:
  781. /* Assume CLIENTWRITE_BODY; headers are not encoded. */
  782. result = Curl_unencode_deflate_write(data, k, nread);
  783. break;
  784. case GZIP: /* FIXME 08/27/02 jhrg */
  785. case COMPRESS:
  786. default:
  787. failf (data, "Unrecognized content encoding type. "
  788. "libcurl understands `identity' and `deflate' "
  789. "content encodings.");
  790. result = CURLE_BAD_CONTENT_ENCODING;
  791. break;
  792. }
  793. #endif
  794. }
  795. k->badheader = HEADER_NORMAL; /* taken care of now */
  796. if(result)
  797. return result;
  798. }
  799. } /* if (! header and data to read ) */
  800. } while(!readdone);
  801. } /* if( read from socket ) */
  802. /* If we still have writing to do, we check if we have a writable
  803. socket. Sometimes the writefdp is NULL, it no fd_set was done using
  804. the multi interface and then we can do nothing but to attempt a
  805. write to be sure. */
  806. if((k->keepon & KEEP_WRITE) &&
  807. (FD_ISSET(conn->writesockfd, writefdp)) ) {
  808. /* write */
  809. int i, si;
  810. ssize_t bytes_written;
  811. bool writedone=FALSE;
  812. if ((k->bytecount == 0) && (k->writebytecount == 0))
  813. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  814. didwhat |= KEEP_WRITE;
  815. /*
  816. * We loop here to do the READ and SEND loop until we run out of
  817. * data to send or until we get EWOULDBLOCK back
  818. */
  819. do {
  820. /* only read more data if there's no upload data already
  821. present in the upload buffer */
  822. if(0 == conn->upload_present) {
  823. /* init the "upload from here" pointer */
  824. conn->upload_fromhere = k->uploadbuf;
  825. if(!k->upload_done)
  826. nread = fillbuffer(conn, BUFSIZE);
  827. else
  828. nread = 0; /* we're done uploading/reading */
  829. /* the signed int typecase of nread of for systems that has
  830. unsigned size_t */
  831. if (nread<=0) {
  832. /* done */
  833. k->keepon &= ~KEEP_WRITE; /* we're done writing */
  834. FD_ZERO(&k->wkeepfd);
  835. writedone = TRUE;
  836. break;
  837. }
  838. /* store number of bytes available for upload */
  839. conn->upload_present = nread;
  840. /* convert LF to CRLF if so asked */
  841. if (data->set.crlf) {
  842. for(i = 0, si = 0; i < nread; i++, si++) {
  843. if (conn->upload_fromhere[i] == 0x0a) {
  844. data->state.scratch[si++] = 0x0d;
  845. data->state.scratch[si] = 0x0a;
  846. }
  847. else
  848. data->state.scratch[si] = conn->upload_fromhere[i];
  849. }
  850. if(si != nread) {
  851. /* only perform the special operation if we really did replace
  852. anything */
  853. nread = si;
  854. /* upload from the new (replaced) buffer instead */
  855. conn->upload_fromhere = data->state.scratch;
  856. /* set the new amount too */
  857. conn->upload_present = nread;
  858. }
  859. }
  860. }
  861. else {
  862. /* We have a partial buffer left from a previous "round". Use
  863. that instead of reading more data */
  864. }
  865. /* write to socket (send away data) */
  866. result = Curl_write(conn,
  867. conn->writesockfd, /* socket to send to */
  868. conn->upload_fromhere, /* buffer pointer */
  869. conn->upload_present, /* buffer size */
  870. &bytes_written); /* actually send away */
  871. if(result)
  872. return result;
  873. else if(conn->upload_present != bytes_written) {
  874. /* we only wrote a part of the buffer (if anything), deal with it! */
  875. /* store the amount of bytes left in the buffer to write */
  876. conn->upload_present -= bytes_written;
  877. /* advance the pointer where to find the buffer when the next send
  878. is to happen */
  879. conn->upload_fromhere += bytes_written;
  880. writedone = TRUE; /* we are done, stop the loop */
  881. }
  882. else {
  883. /* we've uploaded that buffer now */
  884. conn->upload_fromhere = k->uploadbuf;
  885. conn->upload_present = 0; /* no more bytes left */
  886. if(k->upload_done) {
  887. /* switch off writing, we're done! */
  888. k->keepon &= ~KEEP_WRITE; /* we're done writing */
  889. FD_ZERO(&k->wkeepfd);
  890. writedone = TRUE;
  891. }
  892. }
  893. if(data->set.verbose)
  894. Curl_debug(data, CURLINFO_DATA_OUT, conn->upload_fromhere,
  895. bytes_written);
  896. k->writebytecount += bytes_written;
  897. Curl_pgrsSetUploadCounter(data, (double)k->writebytecount);
  898. } while(!writedone); /* loop until we're done writing! */
  899. }
  900. } while(0); /* just to break out from! */
  901. if(didwhat) {
  902. /* Update read/write counters */
  903. if(conn->bytecountp)
  904. *conn->bytecountp = k->bytecount; /* read count */
  905. if(conn->writebytecountp)
  906. *conn->writebytecountp = k->writebytecount; /* write count */
  907. }
  908. else {
  909. /* no read no write, this is a timeout? */
  910. if (k->write_after_100_header) {
  911. /* This should allow some time for the header to arrive, but only a
  912. very short time as otherwise it'll be too much wasted times too
  913. often. */
  914. k->write_after_100_header = FALSE;
  915. FD_SET (conn->writesockfd, &k->writefd); /* write socket */
  916. k->keepon |= KEEP_WRITE;
  917. k->wkeepfd = k->writefd;
  918. }
  919. }
  920. k->now = Curl_tvnow();
  921. if(Curl_pgrsUpdate(conn))
  922. result = CURLE_ABORTED_BY_CALLBACK;
  923. else
  924. result = Curl_speedcheck (data, k->now);
  925. if (result)
  926. return result;
  927. if (data->set.timeout &&
  928. ((Curl_tvdiff(k->now, k->start)/1000) >= data->set.timeout)) {
  929. failf (data, "Operation timed out with %d out of %d bytes received",
  930. k->bytecount, conn->size);
  931. return CURLE_OPERATION_TIMEOUTED;
  932. }
  933. if(!k->keepon) {
  934. /*
  935. * The transfer has been performed. Just make some general checks before
  936. * returning.
  937. */
  938. if(!(data->set.no_body) && k->contentlength &&
  939. (k->bytecount != k->contentlength) &&
  940. !conn->newurl) {
  941. failf(data, "transfer closed with %d bytes remaining to read",
  942. k->contentlength-k->bytecount);
  943. return CURLE_PARTIAL_FILE;
  944. }
  945. else if(conn->bits.chunk && conn->proto.http->chunk.datasize) {
  946. failf(data, "transfer closed with at least %d bytes remaining",
  947. conn->proto.http->chunk.datasize);
  948. return CURLE_PARTIAL_FILE;
  949. }
  950. if(Curl_pgrsUpdate(conn))
  951. return CURLE_ABORTED_BY_CALLBACK;
  952. }
  953. /* Now update the "done" boolean we return */
  954. *done = !k->keepon;
  955. return CURLE_OK;
  956. }
  957. CURLcode Curl_readwrite_init(struct connectdata *conn)
  958. {
  959. struct SessionHandle *data = conn->data;
  960. struct Curl_transfer_keeper *k = &conn->keep;
  961. /* NB: the content encoding software depends on this initialization of
  962. Curl_transfer_keeper. 08/28/02 jhrg */
  963. memset(k, 0, sizeof(struct Curl_transfer_keeper));
  964. k->start = Curl_tvnow(); /* start time */
  965. k->now = k->start; /* current time is now */
  966. k->header = TRUE; /* assume header */
  967. k->httpversion = -1; /* unknown at this point */
  968. data = conn->data; /* there's the root struct */
  969. k->buf = data->state.buffer;
  970. k->uploadbuf = data->state.uploadbuffer;
  971. k->maxfd = (conn->sockfd>conn->writesockfd?
  972. conn->sockfd:conn->writesockfd)+1;
  973. k->hbufp = data->state.headerbuff;
  974. Curl_pgrsTime(data, TIMER_PRETRANSFER);
  975. Curl_speedinit(data);
  976. Curl_pgrsSetUploadCounter(data, 0);
  977. Curl_pgrsSetDownloadCounter(data, 0);
  978. if (!conn->bits.getheader) {
  979. k->header = FALSE;
  980. if(conn->size > 0)
  981. Curl_pgrsSetDownloadSize(data, conn->size);
  982. }
  983. /* we want header and/or body, if neither then don't do this! */
  984. if(conn->bits.getheader || !data->set.no_body) {
  985. FD_ZERO (&k->readfd); /* clear it */
  986. if(conn->sockfd != -1) {
  987. FD_SET (conn->sockfd, &k->readfd); /* read socket */
  988. k->keepon |= KEEP_READ;
  989. }
  990. FD_ZERO (&k->writefd); /* clear it */
  991. if(conn->writesockfd != -1) {
  992. if (data->set.expect100header)
  993. /* wait with write until we either got 100-continue or a timeout */
  994. k->write_after_100_header = TRUE;
  995. else {
  996. FD_SET (conn->writesockfd, &k->writefd); /* write socket */
  997. k->keepon |= KEEP_WRITE;
  998. }
  999. }
  1000. /* get these in backup variables to be able to restore them on each lap in
  1001. the select() loop */
  1002. k->rkeepfd = k->readfd;
  1003. k->wkeepfd = k->writefd;
  1004. }
  1005. return CURLE_OK;
  1006. }
  1007. void Curl_single_fdset(struct connectdata *conn,
  1008. fd_set *read_fd_set,
  1009. fd_set *write_fd_set,
  1010. fd_set *exc_fd_set,
  1011. int *max_fd)
  1012. {
  1013. *max_fd = -1; /* init */
  1014. if(conn->keep.keepon & KEEP_READ) {
  1015. FD_SET(conn->sockfd, read_fd_set);
  1016. *max_fd = conn->sockfd;
  1017. conn->keep.readfdp = read_fd_set; /* store the address of the set */
  1018. }
  1019. if(conn->keep.keepon & KEEP_WRITE) {
  1020. FD_SET(conn->writesockfd, write_fd_set);
  1021. if(conn->writesockfd > *max_fd)
  1022. *max_fd = conn->writesockfd;
  1023. conn->keep.writefdp = write_fd_set; /* store the address of the set */
  1024. }
  1025. /* we don't use exceptions, only touch that one to prevent compiler
  1026. warnings! */
  1027. *exc_fd_set = *exc_fd_set;
  1028. }
  1029. /*
  1030. * Transfer()
  1031. *
  1032. * This function is what performs the actual transfer. It is capable of
  1033. * doing both ways simultaneously.
  1034. * The transfer must already have been setup by a call to Curl_Transfer().
  1035. *
  1036. * Note that headers are created in a preallocated buffer of a default size.
  1037. * That buffer can be enlarged on demand, but it is never shrinken again.
  1038. *
  1039. * Parts of this function was once written by the friendly Mark Butler
  1040. * <[email protected]>.
  1041. */
  1042. static CURLcode
  1043. Transfer(struct connectdata *conn)
  1044. {
  1045. struct SessionHandle *data = conn->data;
  1046. CURLcode result;
  1047. struct Curl_transfer_keeper *k = &conn->keep;
  1048. bool done=FALSE;
  1049. Curl_readwrite_init(conn);
  1050. if((conn->sockfd == -1) && (conn->writesockfd == -1))
  1051. /* nothing to read, nothing to write, we're already OK! */
  1052. return CURLE_OK;
  1053. /* we want header and/or body, if neither then don't do this! */
  1054. if(!conn->bits.getheader && data->set.no_body)
  1055. return CURLE_OK;
  1056. k->writefdp = &k->writefd; /* store the address of the set */
  1057. k->readfdp = &k->readfd; /* store the address of the set */
  1058. while (!done) {
  1059. struct timeval interval;
  1060. k->readfd = k->rkeepfd; /* set these every lap in the loop */
  1061. k->writefd = k->wkeepfd;
  1062. interval.tv_sec = 1;
  1063. interval.tv_usec = 0;
  1064. switch (select (k->maxfd, k->readfdp, k->writefdp, NULL, &interval)) {
  1065. case -1: /* select() error, stop reading */
  1066. #ifdef EINTR
  1067. /* The EINTR is not serious, and it seems you might get this more
  1068. ofen when using the lib in a multi-threaded environment! */
  1069. if(errno == EINTR)
  1070. ;
  1071. else
  1072. #endif
  1073. done = TRUE; /* no more read or write */
  1074. continue;
  1075. case 0: /* timeout */
  1076. result = Curl_readwrite(conn, &done);
  1077. break;
  1078. default: /* readable descriptors */
  1079. result = Curl_readwrite(conn, &done);
  1080. break;
  1081. }
  1082. if(result)
  1083. return result;
  1084. /* "done" signals to us if the transfer(s) are ready */
  1085. }
  1086. return CURLE_OK;
  1087. }
  1088. CURLcode Curl_pretransfer(struct SessionHandle *data)
  1089. {
  1090. if(!data->change.url)
  1091. /* we can't do anything wihout URL */
  1092. return CURLE_URL_MALFORMAT;
  1093. #ifdef USE_SSLEAY
  1094. /* Init the SSL session ID cache here. We do it here since we want to
  1095. do it after the *_setopt() calls (that could change the size) but
  1096. before any transfer. */
  1097. Curl_SSL_InitSessions(data, data->set.ssl.numsessions);
  1098. #endif
  1099. data->set.followlocation=0; /* reset the location-follow counter */
  1100. data->state.this_is_a_follow = FALSE; /* reset this */
  1101. data->state.errorbuf = FALSE; /* no error has occurred */
  1102. /* If there was a list of cookie files to read and we haven't done it before,
  1103. do it now! */
  1104. if(data->change.cookielist) {
  1105. struct curl_slist *list = data->change.cookielist;
  1106. while(list) {
  1107. data->cookies = Curl_cookie_init(list->data,
  1108. data->cookies,
  1109. data->set.cookiesession);
  1110. list = list->next;
  1111. }
  1112. curl_slist_free_all(data->change.cookielist); /* clean up list */
  1113. data->change.cookielist = NULL; /* don't do this again! */
  1114. }
  1115. /* Allow data->set.use_port to set which port to use. This needs to be
  1116. * disabled for example when we follow Location: headers to URLs using
  1117. * different ports! */
  1118. data->state.allow_port = TRUE;
  1119. #if defined(HAVE_SIGNAL) && defined(SIGPIPE)
  1120. /*************************************************************
  1121. * Tell signal handler to ignore SIGPIPE
  1122. *************************************************************/
  1123. if(!data->set.no_signal)
  1124. data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
  1125. #endif
  1126. Curl_initinfo(data); /* reset session-specific information "variables" */
  1127. Curl_pgrsStartNow(data);
  1128. return CURLE_OK;
  1129. }
  1130. CURLcode Curl_posttransfer(struct SessionHandle *data)
  1131. {
  1132. #if defined(HAVE_SIGNAL) && defined(SIGPIPE)
  1133. /* restore the signal handler for SIGPIPE before we get back */
  1134. if(!data->set.no_signal)
  1135. signal(SIGPIPE, data->state.prev_signal);
  1136. #endif
  1137. return CURLE_OK;
  1138. }
  1139. CURLcode Curl_follow(struct SessionHandle *data,
  1140. char *newurl) /* this 'newurl' is the Location: string,
  1141. and it must be malloc()ed before passed
  1142. here */
  1143. {
  1144. /* Location: redirect */
  1145. char prot[16]; /* URL protocol string storage */
  1146. char letter; /* used for a silly sscanf */
  1147. if (data->set.maxredirs &&
  1148. (data->set.followlocation >= data->set.maxredirs)) {
  1149. failf(data,"Maximum (%d) redirects followed", data->set.maxredirs);
  1150. return CURLE_TOO_MANY_REDIRECTS;
  1151. }
  1152. /* mark the next request as a followed location: */
  1153. data->state.this_is_a_follow = TRUE;
  1154. data->set.followlocation++; /* count location-followers */
  1155. if(data->set.http_auto_referer) {
  1156. /* We are asked to automatically set the previous URL as the
  1157. referer when we get the next URL. We pick the ->url field,
  1158. which may or may not be 100% correct */
  1159. if(data->change.referer_alloc)
  1160. /* If we already have an allocated referer, free this first */
  1161. free(data->change.referer);
  1162. data->change.referer = strdup(data->change.url);
  1163. data->change.referer_alloc = TRUE; /* yes, free this later */
  1164. }
  1165. if(2 != sscanf(newurl, "%15[^?&/:]://%c", prot, &letter)) {
  1166. /***
  1167. *DANG* this is an RFC 2068 violation. The URL is supposed
  1168. to be absolute and this doesn't seem to be that!
  1169. ***
  1170. Instead, we have to TRY to append this new path to the old URL
  1171. to the right of the host part. Oh crap, this is doomed to cause
  1172. problems in the future...
  1173. */
  1174. char *protsep;
  1175. char *pathsep;
  1176. char *newest;
  1177. char *useurl = newurl;
  1178. /* we must make our own copy of the URL to play with, as it may
  1179. point to read-only data */
  1180. char *url_clone=strdup(data->change.url);
  1181. if(!url_clone)
  1182. return CURLE_OUT_OF_MEMORY; /* skip out of this NOW */
  1183. /* protsep points to the start of the host name */
  1184. protsep=strstr(url_clone, "//");
  1185. if(!protsep)
  1186. protsep=url_clone;
  1187. else
  1188. protsep+=2; /* pass the slashes */
  1189. if('/' != newurl[0]) {
  1190. int level=0;
  1191. /* First we need to find out if there's a ?-letter in the URL,
  1192. and cut it and the right-side of that off */
  1193. pathsep = strrchr(protsep, '?');
  1194. if(pathsep)
  1195. *pathsep=0;
  1196. /* we have a relative path to append to the last slash if
  1197. there's one available */
  1198. pathsep = strrchr(protsep, '/');
  1199. if(pathsep)
  1200. *pathsep=0;
  1201. /* Check if there's any slash after the host name, and if so,
  1202. remember that position instead */
  1203. pathsep = strchr(protsep, '/');
  1204. if(pathsep)
  1205. protsep = pathsep+1;
  1206. else
  1207. protsep = NULL;
  1208. /* now deal with one "./" or any amount of "../" in the newurl
  1209. and act accordingly */
  1210. if((useurl[0] == '.') && (useurl[1] == '/'))
  1211. useurl+=2; /* just skip the "./" */
  1212. while((useurl[0] == '.') &&
  1213. (useurl[1] == '.') &&
  1214. (useurl[2] == '/')) {
  1215. level++;
  1216. useurl+=3; /* pass the "../" */
  1217. }
  1218. if(protsep) {
  1219. while(level--) {
  1220. /* cut off one more level from the right of the original URL */
  1221. pathsep = strrchr(protsep, '/');
  1222. if(pathsep)
  1223. *pathsep=0;
  1224. else {
  1225. *protsep=0;
  1226. break;
  1227. }
  1228. }
  1229. }
  1230. }
  1231. else {
  1232. /* We got a new absolute path for this server, cut off from the
  1233. first slash */
  1234. pathsep = strchr(protsep, '/');
  1235. if(pathsep)
  1236. *pathsep=0;
  1237. }
  1238. newest=(char *)malloc( strlen(url_clone) +
  1239. 1 + /* possible slash */
  1240. strlen(useurl) + 1/* zero byte */);
  1241. if(!newest)
  1242. return CURLE_OUT_OF_MEMORY; /* go out from this */
  1243. sprintf(newest, "%s%s%s", url_clone,
  1244. (('/' == useurl[0]) || (protsep && !*protsep))?"":"/",
  1245. useurl);
  1246. free(newurl); /* newurl is the allocated pointer */
  1247. free(url_clone);
  1248. newurl = newest;
  1249. }
  1250. else
  1251. /* This is an absolute URL, don't allow the custom port number */
  1252. data->state.allow_port = FALSE;
  1253. if(data->change.url_alloc)
  1254. free(data->change.url);
  1255. else
  1256. data->change.url_alloc = TRUE; /* the URL is allocated */
  1257. /* TBD: set the URL with curl_setopt() */
  1258. data->change.url = newurl;
  1259. newurl = NULL; /* don't free! */
  1260. infof(data, "Follows Location: to new URL: '%s'\n", data->change.url);
  1261. /*
  1262. * We get here when the HTTP code is 300-399. We need to perform
  1263. * differently based on exactly what return code there was.
  1264. * Discussed on the curl mailing list and posted about on the 26th
  1265. * of January 2001.
  1266. */
  1267. switch(data->info.httpcode) {
  1268. case 300: /* Multiple Choices */
  1269. case 306: /* Not used */
  1270. case 307: /* Temporary Redirect */
  1271. default: /* for all unknown ones */
  1272. /* These are explicitly mention since I've checked RFC2616 and they
  1273. * seem to be OK to POST to.
  1274. */
  1275. break;
  1276. case 301: /* Moved Permanently */
  1277. /* (quote from RFC2616, section 10.3.2):
  1278. *
  1279. * Note: When automatically redirecting a POST request after
  1280. * receiving a 301 status code, some existing HTTP/1.0 user agents
  1281. * will erroneously change it into a GET request.
  1282. *
  1283. * ----
  1284. * Warning: Because most of importants user agents do this clear
  1285. * RFC2616 violation, many webservers expect this misbehavior. So
  1286. * these servers often answers to a POST request with an error page.
  1287. * To be sure that libcurl gets the page that most user agents
  1288. * would get, libcurl has to force GET:
  1289. */
  1290. if( data->set.httpreq == HTTPREQ_POST
  1291. || data->set.httpreq == HTTPREQ_POST_FORM) {
  1292. infof(data,
  1293. "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
  1294. data->set.httpreq = HTTPREQ_GET;
  1295. }
  1296. break;
  1297. case 302: /* Found */
  1298. /* (From 10.3.3)
  1299. Note: RFC 1945 and RFC 2068 specify that the client is not allowed
  1300. to change the method on the redirected request. However, most
  1301. existing user agent implementations treat 302 as if it were a 303
  1302. response, performing a GET on the Location field-value regardless
  1303. of the original request method. The status codes 303 and 307 have
  1304. been added for servers that wish to make unambiguously clear which
  1305. kind of reaction is expected of the client.
  1306. (From 10.3.4)
  1307. Note: Many pre-HTTP/1.1 user agents do not understand the 303
  1308. status. When interoperability with such clients is a concern, the
  1309. 302 status code may be used instead, since most user agents react
  1310. to a 302 response as described here for 303.
  1311. */
  1312. case 303: /* See Other */
  1313. /* Disable both types of POSTs, since doing a second POST when
  1314. * following isn't what anyone would want! */
  1315. if(data->set.httpreq != HTTPREQ_GET) {
  1316. data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
  1317. infof(data, "Disables POST, goes with %s\n",
  1318. data->set.no_body?"HEAD":"GET");
  1319. }
  1320. break;
  1321. case 304: /* Not Modified */
  1322. /* 304 means we did a conditional request and it was "Not modified".
  1323. * We shouldn't get any Location: header in this response!
  1324. */
  1325. break;
  1326. case 305: /* Use Proxy */
  1327. /* (quote from RFC2616, section 10.3.6):
  1328. * "The requested resource MUST be accessed through the proxy given
  1329. * by the Location field. The Location field gives the URI of the
  1330. * proxy. The recipient is expected to repeat this single request
  1331. * via the proxy. 305 responses MUST only be generated by origin
  1332. * servers."
  1333. */
  1334. break;
  1335. }
  1336. Curl_pgrsTime(data, TIMER_REDIRECT);
  1337. Curl_pgrsResetTimes(data);
  1338. return CURLE_OK;
  1339. }
  1340. CURLcode Curl_perform(struct SessionHandle *data)
  1341. {
  1342. CURLcode res;
  1343. CURLcode res2;
  1344. struct connectdata *conn=NULL;
  1345. char *newurl = NULL; /* possibly a new URL to follow to! */
  1346. data->state.used_interface = Curl_if_easy;
  1347. res = Curl_pretransfer(data);
  1348. if(res)
  1349. return res;
  1350. /*
  1351. * It is important that there is NO 'return' from this function at any other
  1352. * place than falling down to the end of the function! This is because we
  1353. * have cleanup stuff that must be done before we get back, and that is only
  1354. * performed after this do-while loop.
  1355. */
  1356. do {
  1357. Curl_pgrsTime(data, TIMER_STARTSINGLE);
  1358. res = Curl_connect(data, &conn);
  1359. if(res == CURLE_OK) {
  1360. res = Curl_do(&conn);
  1361. if(res == CURLE_OK) {
  1362. CURLcode res2; /* just a local extra result container */
  1363. if(conn->protocol&PROT_FTPS)
  1364. /* FTPS, disable ssl while transfering data */
  1365. conn->ssl.use = FALSE;
  1366. res = Transfer(conn); /* now fetch that URL please */
  1367. if(conn->protocol&PROT_FTPS)
  1368. /* FTPS, enable ssl again after havving transferred data */
  1369. conn->ssl.use = TRUE;
  1370. if(res == CURLE_OK)
  1371. /*
  1372. * We must duplicate the new URL here as the connection data
  1373. * may be free()ed in the Curl_done() function.
  1374. */
  1375. newurl = conn->newurl?strdup(conn->newurl):NULL;
  1376. else {
  1377. /* The transfer phase returned error, we mark the connection to get
  1378. * closed to prevent being re-used. This is becasue we can't
  1379. * possibly know if the connection is in a good shape or not now. */
  1380. conn->bits.close = TRUE;
  1381. if(-1 !=conn->secondarysocket) {
  1382. /* if we failed anywhere, we must clean up the secondary socket if
  1383. it was used */
  1384. sclose(conn->secondarysocket);
  1385. conn->secondarysocket=-1;
  1386. }
  1387. }
  1388. /* Always run Curl_done(), even if some of the previous calls
  1389. failed, but return the previous (original) error code */
  1390. res2 = Curl_done(conn);
  1391. if(CURLE_OK == res)
  1392. res = res2;
  1393. }
  1394. /*
  1395. * Important: 'conn' cannot be used here, since it may have been closed
  1396. * in 'Curl_done' or other functions.
  1397. */
  1398. if((res == CURLE_OK) && newurl) {
  1399. res = Curl_follow(data, newurl);
  1400. if(CURLE_OK == res) {
  1401. newurl = NULL;
  1402. continue;
  1403. }
  1404. }
  1405. }
  1406. break; /* it only reaches here when this shouldn't loop */
  1407. } while(1); /* loop if Location: */
  1408. if(newurl)
  1409. free(newurl);
  1410. /* run post-transfer uncondionally, but don't clobber the return code if
  1411. we already have an error code recorder */
  1412. res2 = Curl_posttransfer(data);
  1413. if(!res && res2)
  1414. res = res2;
  1415. return res;
  1416. }
  1417. CURLcode
  1418. Curl_Transfer(struct connectdata *c_conn, /* connection data */
  1419. int sockfd, /* socket to read from or -1 */
  1420. int size, /* -1 if unknown at this point */
  1421. bool getheader, /* TRUE if header parsing is wanted */
  1422. long *bytecountp, /* return number of bytes read or NULL */
  1423. int writesockfd, /* socket to write to, it may very well be
  1424. the same we read from. -1 disables */
  1425. long *writebytecountp /* return number of bytes written or
  1426. NULL */
  1427. )
  1428. {
  1429. struct connectdata *conn = (struct connectdata *)c_conn;
  1430. if(!conn)
  1431. return CURLE_BAD_FUNCTION_ARGUMENT;
  1432. /* now copy all input parameters */
  1433. conn->sockfd = sockfd;
  1434. conn->size = size;
  1435. conn->bits.getheader = getheader;
  1436. conn->bytecountp = bytecountp;
  1437. conn->writesockfd = writesockfd;
  1438. conn->writebytecountp = writebytecountp;
  1439. return CURLE_OK;
  1440. }
  1441. /*
  1442. * local variables:
  1443. * eval: (load-file "../curl-mode.el")
  1444. * end:
  1445. * vim600: fdm=marker
  1446. * vim: et sw=2 ts=2 sts=2 tw=78
  1447. */