transfer.c 78 KB

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