1
0

http.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. #ifndef CURL_DISABLE_HTTP
  25. /* -- WIN32 approved -- */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdarg.h>
  29. #include <stdlib.h>
  30. #include <ctype.h>
  31. #include <sys/types.h>
  32. #include <sys/stat.h>
  33. #include <errno.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. #ifdef HAVE_NETINET_IN_H
  43. #include <netinet/in.h>
  44. #endif
  45. #include <sys/time.h>
  46. #ifdef HAVE_TIME_H
  47. #ifdef TIME_WITH_SYS_TIME
  48. #include <time.h>
  49. #endif
  50. #endif
  51. #include <sys/resource.h>
  52. #ifdef HAVE_UNISTD_H
  53. #include <unistd.h>
  54. #endif
  55. #include <netdb.h>
  56. #ifdef HAVE_ARPA_INET_H
  57. #include <arpa/inet.h>
  58. #endif
  59. #ifdef HAVE_NET_IF_H
  60. #include <net/if.h>
  61. #endif
  62. #include <sys/ioctl.h>
  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. #endif
  71. #include "urldata.h"
  72. #include <curl/curl.h>
  73. #include "transfer.h"
  74. #include "sendf.h"
  75. #include "formdata.h"
  76. #include "progress.h"
  77. #include "base64.h"
  78. #include "cookie.h"
  79. #include "strequal.h"
  80. #include "ssluse.h"
  81. #define _MPRINTF_REPLACE /* use our functions only */
  82. #include <curl/mprintf.h>
  83. /* The last #include file should be: */
  84. #ifdef MALLOCDEBUG
  85. #include "memdebug.h"
  86. #endif
  87. /* fread() emulation to provide POST and/or request data */
  88. static int readmoredata(char *buffer,
  89. size_t size,
  90. size_t nitems,
  91. void *userp)
  92. {
  93. struct connectdata *conn = (struct connectdata *)userp;
  94. struct HTTP *http = conn->proto.http;
  95. int fullsize = size * nitems;
  96. if(0 == http->postsize)
  97. /* nothing to return */
  98. return 0;
  99. /* make sure that a HTTP request is never sent away chunked! */
  100. conn->bits.forbidchunk= (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
  101. if(http->postsize <= fullsize) {
  102. memcpy(buffer, http->postdata, http->postsize);
  103. fullsize = http->postsize;
  104. if(http->backup.postsize) {
  105. /* move backup data into focus and continue on that */
  106. http->postdata = http->backup.postdata;
  107. http->postsize = http->backup.postsize;
  108. conn->fread = http->backup.fread;
  109. conn->fread_in = http->backup.fread_in;
  110. http->sending++; /* move one step up */
  111. http->backup.postsize=0;
  112. }
  113. else
  114. http->postsize = 0;
  115. return fullsize;
  116. }
  117. memcpy(buffer, http->postdata, fullsize);
  118. http->postdata += fullsize;
  119. http->postsize -= fullsize;
  120. return fullsize;
  121. }
  122. /* ------------------------------------------------------------------------- */
  123. /*
  124. * The add_buffer series of functions are used to build one large memory chunk
  125. * from repeated function invokes. Used so that the entire HTTP request can
  126. * be sent in one go.
  127. */
  128. struct send_buffer {
  129. char *buffer;
  130. size_t size_max;
  131. size_t size_used;
  132. };
  133. typedef struct send_buffer send_buffer;
  134. static CURLcode
  135. add_buffer(send_buffer *in, const void *inptr, size_t size);
  136. /*
  137. * add_buffer_init() returns a fine buffer struct
  138. */
  139. static
  140. send_buffer *add_buffer_init(void)
  141. {
  142. send_buffer *blonk;
  143. blonk=(send_buffer *)malloc(sizeof(send_buffer));
  144. if(blonk) {
  145. memset(blonk, 0, sizeof(send_buffer));
  146. return blonk;
  147. }
  148. return NULL; /* failed, go home */
  149. }
  150. /*
  151. * add_buffer_send() sends a buffer and frees all associated memory.
  152. */
  153. static
  154. CURLcode add_buffer_send(send_buffer *in,
  155. int sockfd,
  156. struct connectdata *conn,
  157. long *bytes_written) /* add the number of sent
  158. bytes to this counter */
  159. {
  160. ssize_t amount;
  161. CURLcode res;
  162. char *ptr;
  163. int size;
  164. struct HTTP *http = conn->proto.http;
  165. /* The looping below is required since we use non-blocking sockets, but due
  166. to the circumstances we will just loop and try again and again etc */
  167. ptr = in->buffer;
  168. size = in->size_used;
  169. res = Curl_write(conn, sockfd, ptr, size, &amount);
  170. if(CURLE_OK == res) {
  171. if(conn->data->set.verbose)
  172. /* this data _may_ contain binary stuff */
  173. Curl_debug(conn->data, CURLINFO_HEADER_OUT, ptr, amount);
  174. *bytes_written += amount;
  175. if(amount != size) {
  176. /* The whole request could not be sent in one system call. We must queue
  177. it up and send it later when we get the chance. We must not loop here
  178. and wait until it might work again. */
  179. size -= amount;
  180. ptr += amount;
  181. /* backup the currently set pointers */
  182. http->backup.fread = conn->fread;
  183. http->backup.fread_in = conn->fread_in;
  184. http->backup.postdata = http->postdata;
  185. http->backup.postsize = http->postsize;
  186. /* set the new pointers for the request-sending */
  187. conn->fread = (curl_read_callback)readmoredata;
  188. conn->fread_in = (void *)conn;
  189. http->postdata = ptr;
  190. http->postsize = size;
  191. http->send_buffer = in;
  192. http->sending = HTTPSEND_REQUEST;
  193. return CURLE_OK;
  194. }
  195. /* the full buffer was sent, clean up and return */
  196. }
  197. if(in->buffer)
  198. free(in->buffer);
  199. free(in);
  200. return res;
  201. }
  202. /*
  203. * add_bufferf() builds a buffer from the formatted input
  204. */
  205. static
  206. CURLcode add_bufferf(send_buffer *in, const char *fmt, ...)
  207. {
  208. CURLcode result = CURLE_OUT_OF_MEMORY;
  209. char *s;
  210. va_list ap;
  211. va_start(ap, fmt);
  212. s = vaprintf(fmt, ap); /* this allocs a new string to append */
  213. va_end(ap);
  214. if(s) {
  215. result = add_buffer(in, s, strlen(s));
  216. free(s);
  217. }
  218. return result;
  219. }
  220. /*
  221. * add_buffer() appends a memory chunk to the existing one
  222. */
  223. static
  224. CURLcode add_buffer(send_buffer *in, const void *inptr, size_t size)
  225. {
  226. char *new_rb;
  227. int new_size;
  228. if(!in->buffer ||
  229. ((in->size_used + size) > (in->size_max - 1))) {
  230. new_size = (in->size_used+size)*2;
  231. if(in->buffer)
  232. /* we have a buffer, enlarge the existing one */
  233. new_rb = (char *)realloc(in->buffer, new_size);
  234. else
  235. /* create a new buffer */
  236. new_rb = (char *)malloc(new_size);
  237. if(!new_rb)
  238. return CURLE_OUT_OF_MEMORY;
  239. in->buffer = new_rb;
  240. in->size_max = new_size;
  241. }
  242. memcpy(&in->buffer[in->size_used], inptr, size);
  243. in->size_used += size;
  244. return CURLE_OK;
  245. }
  246. /* end of the add_buffer functions */
  247. /* ------------------------------------------------------------------------- */
  248. /*
  249. * Curl_compareheader()
  250. *
  251. * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
  252. * Pass headers WITH the colon.
  253. */
  254. bool
  255. Curl_compareheader(char *headerline, /* line to check */
  256. const char *header, /* header keyword _with_ colon */
  257. const char *content) /* content string to find */
  258. {
  259. /* RFC2616, section 4.2 says: "Each header field consists of a name followed
  260. * by a colon (":") and the field value. Field names are case-insensitive.
  261. * The field value MAY be preceded by any amount of LWS, though a single SP
  262. * is preferred." */
  263. size_t hlen = strlen(header);
  264. size_t clen;
  265. size_t len;
  266. char *start;
  267. char *end;
  268. if(!strnequal(headerline, header, hlen))
  269. return FALSE; /* doesn't start with header */
  270. /* pass the header */
  271. start = &headerline[hlen];
  272. /* pass all white spaces */
  273. while(*start && isspace((int)*start))
  274. start++;
  275. /* find the end of the header line */
  276. end = strchr(start, '\r'); /* lines end with CRLF */
  277. if(!end) {
  278. /* in case there's a non-standard compliant line here */
  279. end = strchr(start, '\n');
  280. if(!end)
  281. /* hm, there's no line ending here, use the zero byte! */
  282. end = strchr(start, '\0');
  283. }
  284. len = end-start; /* length of the content part of the input line */
  285. clen = strlen(content); /* length of the word to find */
  286. /* find the content string in the rest of the line */
  287. for(;len>=clen;len--, start++) {
  288. if(strnequal(start, content, clen))
  289. return TRUE; /* match! */
  290. }
  291. return FALSE; /* no match */
  292. }
  293. /*
  294. * This function checks the linked list of custom HTTP headers for a particular
  295. * header (prefix).
  296. */
  297. static char *checkheaders(struct SessionHandle *data, const char *thisheader)
  298. {
  299. struct curl_slist *head;
  300. size_t thislen = strlen(thisheader);
  301. for(head = data->set.headers; head; head=head->next) {
  302. if(strnequal(head->data, thisheader, thislen))
  303. return head->data;
  304. }
  305. return NULL;
  306. }
  307. /*
  308. * ConnectHTTPProxyTunnel() requires that we're connected to a HTTP proxy. This
  309. * function will issue the necessary commands to get a seamless tunnel through
  310. * this proxy. After that, the socket can be used just as a normal socket.
  311. */
  312. CURLcode Curl_ConnectHTTPProxyTunnel(struct connectdata *conn,
  313. int tunnelsocket,
  314. char *hostname, int remote_port)
  315. {
  316. int httperror=0;
  317. int subversion=0;
  318. struct SessionHandle *data=conn->data;
  319. CURLcode result;
  320. int res;
  321. int nread; /* total size read */
  322. int perline; /* count bytes per line */
  323. bool keepon=TRUE;
  324. ssize_t gotbytes;
  325. char *ptr;
  326. int timeout = 3600; /* default timeout in seconds */
  327. struct timeval interval;
  328. fd_set rkeepfd;
  329. fd_set readfd;
  330. char *line_start;
  331. #define SELECT_OK 0
  332. #define SELECT_ERROR 1
  333. #define SELECT_TIMEOUT 2
  334. int error = SELECT_OK;
  335. infof(data, "Establish HTTP proxy tunnel to %s:%d\n", hostname, remote_port);
  336. /* OK, now send the connect request to the proxy */
  337. result =
  338. Curl_sendf(tunnelsocket, conn,
  339. "CONNECT %s:%d HTTP/1.0\015\012"
  340. "%s"
  341. "%s"
  342. "\r\n",
  343. hostname, remote_port,
  344. (conn->bits.proxy_user_passwd)?conn->allocptr.proxyuserpwd:"",
  345. (data->set.useragent?conn->allocptr.uagent:"")
  346. );
  347. if(result) {
  348. failf(data, "Failed sending CONNECT to proxy");
  349. return result;
  350. }
  351. /* Now, read the full reply we get from the proxy */
  352. if(data->set.timeout) {
  353. /* if timeout is requested, find out how much remaining time we have */
  354. timeout = data->set.timeout - /* timeout time */
  355. Curl_tvdiff(Curl_tvnow(), conn->now)/1000; /* spent time */
  356. if(timeout <=0 ) {
  357. failf(data, "Transfer aborted due to timeout");
  358. return -SELECT_TIMEOUT; /* already too little time */
  359. }
  360. }
  361. FD_ZERO (&readfd); /* clear it */
  362. FD_SET (tunnelsocket, &readfd); /* read socket */
  363. /* get this in a backup variable to be able to restore it on each lap in the
  364. select() loop */
  365. rkeepfd = readfd;
  366. ptr=data->state.buffer;
  367. line_start = ptr;
  368. nread=0;
  369. perline=0;
  370. keepon=TRUE;
  371. while((nread<BUFSIZE) && (keepon && !error)) {
  372. readfd = rkeepfd; /* set every lap */
  373. interval.tv_sec = timeout;
  374. interval.tv_usec = 0;
  375. switch (select (tunnelsocket+1, &readfd, NULL, NULL, &interval)) {
  376. case -1: /* select() error, stop reading */
  377. error = SELECT_ERROR;
  378. failf(data, "Transfer aborted due to select() error");
  379. break;
  380. case 0: /* timeout */
  381. error = SELECT_TIMEOUT;
  382. failf(data, "Transfer aborted due to timeout");
  383. break;
  384. default:
  385. /*
  386. * This code previously didn't use the kerberos sec_read() code
  387. * to read, but when we use Curl_read() it may do so. Do confirm
  388. * that this is still ok and then remove this comment!
  389. */
  390. res= Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread,
  391. &gotbytes);
  392. if(res< 0)
  393. /* EWOULDBLOCK */
  394. continue; /* go loop yourself */
  395. else if(res)
  396. keepon = FALSE;
  397. else if(gotbytes <= 0) {
  398. keepon = FALSE;
  399. error = SELECT_ERROR;
  400. failf(data, "Connection aborted");
  401. }
  402. else {
  403. /* we got a whole chunk of data, which can be anything from one
  404. * byte to a set of lines and possibly just a piece of the last
  405. * line */
  406. int i;
  407. nread += gotbytes;
  408. for(i = 0; i < gotbytes; ptr++, i++) {
  409. perline++; /* amount of bytes in this line so far */
  410. if(*ptr=='\n') {
  411. /* a newline is CRLF in ftp-talk, so the CR is ignored as
  412. the line isn't really terminated until the LF comes */
  413. /* output debug output if that is requested */
  414. if(data->set.verbose)
  415. Curl_debug(data, CURLINFO_DATA_IN, line_start, perline);
  416. if('\r' == line_start[0]) {
  417. /* end of headers */
  418. keepon=FALSE;
  419. break; /* breaks out of loop, not switch */
  420. }
  421. if(2 == sscanf(line_start, "HTTP/1.%d %d",
  422. &subversion,
  423. &httperror)) {
  424. ;
  425. }
  426. perline=0; /* line starts over here */
  427. line_start = ptr+1;
  428. }
  429. }
  430. }
  431. break;
  432. } /* switch */
  433. } /* while there's buffer left and loop is requested */
  434. if(error)
  435. return CURLE_RECV_ERROR;
  436. if(200 != httperror) {
  437. if(407 == httperror)
  438. /* Added Nov 6 1998 */
  439. failf(data, "Proxy requires authorization!");
  440. else
  441. failf(data, "Received error code %d from proxy", httperror);
  442. return CURLE_RECV_ERROR;
  443. }
  444. infof (data, "Proxy replied to CONNECT request\n");
  445. return CURLE_OK;
  446. }
  447. /*
  448. * HTTP stuff to do at connect-time.
  449. */
  450. CURLcode Curl_http_connect(struct connectdata *conn)
  451. {
  452. struct SessionHandle *data;
  453. CURLcode result;
  454. data=conn->data;
  455. /* If we are not using a proxy and we want a secure connection,
  456. * perform SSL initialization & connection now.
  457. * If using a proxy with https, then we must tell the proxy to CONNECT
  458. * us to the host we want to talk to. Only after the connect
  459. * has occured, can we start talking SSL
  460. */
  461. if(conn->bits.httpproxy &&
  462. ((conn->protocol & PROT_HTTPS) || data->set.tunnel_thru_httpproxy)) {
  463. /* either HTTPS over proxy, OR explicitly asked for a tunnel */
  464. result = Curl_ConnectHTTPProxyTunnel(conn, conn->firstsocket,
  465. conn->hostname, conn->remote_port);
  466. if(CURLE_OK != result)
  467. return result;
  468. }
  469. if(conn->protocol & PROT_HTTPS) {
  470. /* now, perform the SSL initialization for this socket */
  471. result = Curl_SSLConnect(conn);
  472. if(result)
  473. return result;
  474. }
  475. if(conn->bits.user_passwd && !data->state.this_is_a_follow) {
  476. /* Authorization: is requested, this is not a followed location, get the
  477. original host name */
  478. if (data->state.auth_host)
  479. /* Free to avoid leaking memory on multiple requests*/
  480. free(data->state.auth_host);
  481. data->state.auth_host = strdup(conn->hostname);
  482. }
  483. return CURLE_OK;
  484. }
  485. CURLcode Curl_http_done(struct connectdata *conn)
  486. {
  487. struct SessionHandle *data;
  488. struct HTTP *http;
  489. data=conn->data;
  490. http=conn->proto.http;
  491. /* set the proper values (possibly modified on POST) */
  492. conn->fread = data->set.fread; /* restore */
  493. conn->fread_in = data->set.in; /* restore */
  494. if(http->send_buffer) {
  495. send_buffer *buff = http->send_buffer;
  496. free(buff->buffer);
  497. free(buff);
  498. }
  499. if(HTTPREQ_POST_FORM == data->set.httpreq) {
  500. conn->bytecount = http->readbytecount + http->writebytecount;
  501. Curl_formclean(http->sendit); /* Now free that whole lot */
  502. }
  503. else if(HTTPREQ_PUT == data->set.httpreq)
  504. conn->bytecount = http->readbytecount + http->writebytecount;
  505. if(0 == (http->readbytecount + conn->headerbytecount)) {
  506. /* nothing was read from the HTTP server, this can't be right
  507. so we return an error here */
  508. failf(data, "Empty reply from server");
  509. return CURLE_GOT_NOTHING;
  510. }
  511. return CURLE_OK;
  512. }
  513. CURLcode Curl_http(struct connectdata *conn)
  514. {
  515. struct SessionHandle *data=conn->data;
  516. char *buf = data->state.buffer; /* this is a short cut to the buffer */
  517. CURLcode result=CURLE_OK;
  518. struct HTTP *http;
  519. struct Cookie *co=NULL; /* no cookies from start */
  520. char *ppath = conn->ppath; /* three previous function arguments */
  521. char *host = conn->name;
  522. const char *te = ""; /* tranfer-encoding */
  523. if(!conn->proto.http) {
  524. /* Only allocate this struct if we don't already have it! */
  525. http = (struct HTTP *)malloc(sizeof(struct HTTP));
  526. if(!http)
  527. return CURLE_OUT_OF_MEMORY;
  528. memset(http, 0, sizeof(struct HTTP));
  529. conn->proto.http = http;
  530. }
  531. else
  532. http = conn->proto.http;
  533. /* We default to persistant connections */
  534. conn->bits.close = FALSE;
  535. if ( (conn->protocol&(PROT_HTTP|PROT_FTP)) &&
  536. data->set.upload) {
  537. data->set.httpreq = HTTPREQ_PUT;
  538. }
  539. /* The User-Agent string has been built in url.c already, because it might
  540. have been used in the proxy connect, but if we have got a header with
  541. the user-agent string specified, we erase the previously made string
  542. here. */
  543. if(checkheaders(data, "User-Agent:") && conn->allocptr.uagent) {
  544. free(conn->allocptr.uagent);
  545. conn->allocptr.uagent=NULL;
  546. }
  547. if((conn->bits.user_passwd) && !checkheaders(data, "Authorization:")) {
  548. char *authorization;
  549. /* To prevent the user+password to get sent to other than the original
  550. host due to a location-follow, we do some weirdo checks here */
  551. if(!data->state.this_is_a_follow ||
  552. !data->state.auth_host ||
  553. curl_strequal(data->state.auth_host, conn->hostname)) {
  554. sprintf(data->state.buffer, "%s:%s",
  555. data->state.user, data->state.passwd);
  556. if(Curl_base64_encode(data->state.buffer, strlen(data->state.buffer),
  557. &authorization) >= 0) {
  558. if(conn->allocptr.userpwd)
  559. free(conn->allocptr.userpwd);
  560. conn->allocptr.userpwd = aprintf( "Authorization: Basic %s\015\012",
  561. authorization);
  562. free(authorization);
  563. }
  564. }
  565. }
  566. if((data->change.referer) && !checkheaders(data, "Referer:")) {
  567. if(conn->allocptr.ref)
  568. free(conn->allocptr.ref);
  569. conn->allocptr.ref = aprintf("Referer: %s\015\012", data->change.referer);
  570. }
  571. if(data->set.cookie && !checkheaders(data, "Cookie:")) {
  572. if(conn->allocptr.cookie)
  573. free(conn->allocptr.cookie);
  574. conn->allocptr.cookie = aprintf("Cookie: %s\015\012", data->set.cookie);
  575. }
  576. if(!conn->bits.upload_chunky && (data->set.httpreq != HTTPREQ_GET)) {
  577. /* not a chunky transfer but data is to be sent */
  578. char *ptr = checkheaders(data, "Transfer-Encoding:");
  579. if(ptr) {
  580. /* Some kind of TE is requested, check if 'chunked' is chosen */
  581. if(Curl_compareheader(ptr, "Transfer-Encoding:", "chunked"))
  582. /* we have been told explicitly to upload chunky so deal with it! */
  583. conn->bits.upload_chunky = TRUE;
  584. }
  585. }
  586. if(conn->bits.upload_chunky) {
  587. /* RFC2616 section 4.4:
  588. Messages MUST NOT include both a Content-Length header field and a
  589. non-identity transfer-coding. If the message does include a non-
  590. identity transfer-coding, the Content-Length MUST be ignored. */
  591. if(!checkheaders(data, "Transfer-Encoding:")) {
  592. te = "Transfer-Encoding: chunked\r\n";
  593. }
  594. else {
  595. /* The "Transfer-Encoding:" header was already added. */
  596. te = "";
  597. }
  598. }
  599. if(data->cookies) {
  600. co = Curl_cookie_getlist(data->cookies,
  601. host, ppath,
  602. (conn->protocol&PROT_HTTPS?TRUE:FALSE));
  603. }
  604. if (data->change.proxy && *data->change.proxy &&
  605. !data->set.tunnel_thru_httpproxy &&
  606. !(conn->protocol&PROT_HTTPS)) {
  607. /* The path sent to the proxy is in fact the entire URL */
  608. ppath = data->change.url;
  609. }
  610. if(HTTPREQ_POST_FORM == data->set.httpreq) {
  611. /* we must build the whole darned post sequence first, so that we have
  612. a size of the whole shebang before we start to send it */
  613. result = Curl_getFormData(&http->sendit, data->set.httppost,
  614. &http->postsize);
  615. if(CURLE_OK != result) {
  616. /* Curl_getFormData() doesn't use failf() */
  617. failf(data, "failed creating formpost data");
  618. return result;
  619. }
  620. }
  621. if(!checkheaders(data, "Host:")) {
  622. /* if ptr_host is already set, it is almost OK since we only re-use
  623. connections to the very same host and port, but when we use a HTTP
  624. proxy we have a persistant connect and yet we must change the Host:
  625. header! */
  626. if(conn->allocptr.host)
  627. free(conn->allocptr.host);
  628. /* When building Host: headers, we must put the host name within
  629. [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
  630. if(((conn->protocol&PROT_HTTPS) && (conn->remote_port == PORT_HTTPS)) ||
  631. (!(conn->protocol&PROT_HTTPS) && (conn->remote_port == PORT_HTTP)) )
  632. /* If (HTTPS on port 443) OR (non-HTTPS on port 80) then don't include
  633. the port number in the host string */
  634. conn->allocptr.host = aprintf("Host: %s%s%s\r\n",
  635. conn->bits.ipv6_ip?"[":"",
  636. host,
  637. conn->bits.ipv6_ip?"]":"");
  638. else
  639. conn->allocptr.host = aprintf("Host: %s%s%s:%d\r\n",
  640. conn->bits.ipv6_ip?"[":"",
  641. host,
  642. conn->bits.ipv6_ip?"]":"",
  643. conn->remote_port);
  644. }
  645. if(!checkheaders(data, "Pragma:"))
  646. http->p_pragma = "Pragma: no-cache\r\n";
  647. if(!checkheaders(data, "Accept:"))
  648. http->p_accept = "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*\r\n";
  649. if(( (HTTPREQ_POST == data->set.httpreq) ||
  650. (HTTPREQ_POST_FORM == data->set.httpreq) ||
  651. (HTTPREQ_PUT == data->set.httpreq) ) &&
  652. conn->resume_from) {
  653. /**********************************************************************
  654. * Resuming upload in HTTP means that we PUT or POST and that we have
  655. * got a resume_from value set. The resume value has already created
  656. * a Range: header that will be passed along. We need to "fast forward"
  657. * the file the given number of bytes and decrease the assume upload
  658. * file size before we continue this venture in the dark lands of HTTP.
  659. *********************************************************************/
  660. if(conn->resume_from < 0 ) {
  661. /*
  662. * This is meant to get the size of the present remote-file by itself.
  663. * We don't support this now. Bail out!
  664. */
  665. conn->resume_from = 0;
  666. }
  667. if(conn->resume_from) {
  668. /* do we still game? */
  669. int passed=0;
  670. /* Now, let's read off the proper amount of bytes from the
  671. input. If we knew it was a proper file we could've just
  672. fseek()ed but we only have a stream here */
  673. do {
  674. int readthisamountnow = (conn->resume_from - passed);
  675. int actuallyread;
  676. if(readthisamountnow > BUFSIZE)
  677. readthisamountnow = BUFSIZE;
  678. actuallyread =
  679. data->set.fread(data->state.buffer, 1, readthisamountnow,
  680. data->set.in);
  681. passed += actuallyread;
  682. if(actuallyread != readthisamountnow) {
  683. failf(data, "Could only read %d bytes from the input",
  684. passed);
  685. return CURLE_READ_ERROR;
  686. }
  687. } while(passed != conn->resume_from); /* loop until done */
  688. /* now, decrease the size of the read */
  689. if(data->set.infilesize>0) {
  690. data->set.infilesize -= conn->resume_from;
  691. if(data->set.infilesize <= 0) {
  692. failf(data, "File already completely uploaded");
  693. return CURLE_PARTIAL_FILE;
  694. }
  695. }
  696. /* we've passed, proceed as normal */
  697. }
  698. }
  699. if(conn->bits.use_range) {
  700. /*
  701. * A range is selected. We use different headers whether we're downloading
  702. * or uploading and we always let customized headers override our internal
  703. * ones if any such are specified.
  704. */
  705. if((data->set.httpreq == HTTPREQ_GET) &&
  706. !checkheaders(data, "Range:")) {
  707. /* if a line like this was already allocated, free the previous one */
  708. if(conn->allocptr.rangeline)
  709. free(conn->allocptr.rangeline);
  710. conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n", conn->range);
  711. }
  712. else if((data->set.httpreq != HTTPREQ_GET) &&
  713. !checkheaders(data, "Content-Range:")) {
  714. if(conn->resume_from) {
  715. /* This is because "resume" was selected */
  716. long total_expected_size= conn->resume_from + data->set.infilesize;
  717. conn->allocptr.rangeline = aprintf("Content-Range: bytes %s%ld/%ld\r\n",
  718. conn->range, total_expected_size-1,
  719. total_expected_size);
  720. }
  721. else {
  722. /* Range was selected and then we just pass the incoming range and
  723. append total size */
  724. conn->allocptr.rangeline = aprintf("Content-Range: bytes %s/%d\r\n",
  725. conn->range, data->set.infilesize);
  726. }
  727. }
  728. }
  729. do {
  730. /* Use 1.1 unless the use specificly asked for 1.0 */
  731. const char *httpstring=
  732. data->set.httpversion==CURL_HTTP_VERSION_1_0?"1.0":"1.1";
  733. send_buffer *req_buffer;
  734. struct curl_slist *headers=data->set.headers;
  735. /* initialize a dynamic send-buffer */
  736. req_buffer = add_buffer_init();
  737. /* add the main request stuff */
  738. add_bufferf(req_buffer,
  739. "%s " /* GET/HEAD/POST/PUT */
  740. "%s HTTP/%s\r\n" /* path */
  741. "%s" /* proxyuserpwd */
  742. "%s" /* userpwd */
  743. "%s" /* range */
  744. "%s" /* user agent */
  745. "%s" /* cookie */
  746. "%s" /* host */
  747. "%s" /* pragma */
  748. "%s" /* accept */
  749. "%s" /* accept-encoding */
  750. "%s" /* referer */
  751. "%s",/* transfer-encoding */
  752. data->set.customrequest?data->set.customrequest:
  753. (data->set.no_body?"HEAD":
  754. ((HTTPREQ_POST == data->set.httpreq) ||
  755. (HTTPREQ_POST_FORM == data->set.httpreq))?"POST":
  756. (HTTPREQ_PUT == data->set.httpreq)?"PUT":"GET"),
  757. ppath, httpstring,
  758. (conn->bits.proxy_user_passwd &&
  759. conn->allocptr.proxyuserpwd)?conn->allocptr.proxyuserpwd:"",
  760. (conn->bits.user_passwd && conn->allocptr.userpwd)?
  761. conn->allocptr.userpwd:"",
  762. (conn->bits.use_range && conn->allocptr.rangeline)?
  763. conn->allocptr.rangeline:"",
  764. (data->set.useragent && *data->set.useragent && conn->allocptr.uagent)?
  765. conn->allocptr.uagent:"",
  766. (conn->allocptr.cookie?conn->allocptr.cookie:""), /* Cookie: <data> */
  767. (conn->allocptr.host?conn->allocptr.host:""), /* Host: host */
  768. http->p_pragma?http->p_pragma:"",
  769. http->p_accept?http->p_accept:"",
  770. (data->set.encoding && *data->set.encoding && conn->allocptr.accept_encoding)?
  771. conn->allocptr.accept_encoding:"", /* 08/28/02 jhrg */
  772. (data->change.referer && conn->allocptr.ref)?conn->allocptr.ref:"" /* Referer: <data> <CRLF> */,
  773. te
  774. );
  775. if(co) {
  776. int count=0;
  777. struct Cookie *store=co;
  778. /* now loop through all cookies that matched */
  779. while(co) {
  780. if(co->value && strlen(co->value)) {
  781. if(0 == count) {
  782. add_bufferf(req_buffer, "Cookie: ");
  783. }
  784. add_bufferf(req_buffer,
  785. "%s%s=%s", count?"; ":"", co->name, co->value);
  786. count++;
  787. }
  788. co = co->next; /* next cookie please */
  789. }
  790. if(count) {
  791. add_buffer(req_buffer, "\r\n", 2);
  792. }
  793. Curl_cookie_freelist(store); /* free the cookie list */
  794. co=NULL;
  795. }
  796. if(data->set.timecondition) {
  797. struct tm *thistime;
  798. /* Phil Karn (Fri, 13 Apr 2001) pointed out that the If-Modified-Since
  799. * header family should have their times set in GMT as RFC2616 defines:
  800. * "All HTTP date/time stamps MUST be represented in Greenwich Mean Time
  801. * (GMT), without exception. For the purposes of HTTP, GMT is exactly
  802. * equal to UTC (Coordinated Universal Time)." (see page 20 of RFC2616).
  803. */
  804. #ifdef HAVE_GMTIME_R
  805. /* thread-safe version */
  806. struct tm keeptime;
  807. thistime = (struct tm *)gmtime_r(&data->set.timevalue, &keeptime);
  808. #else
  809. thistime = gmtime(&data->set.timevalue);
  810. #endif
  811. if(NULL == thistime) {
  812. failf(data, "localtime() failed!");
  813. return CURLE_OUT_OF_MEMORY;
  814. }
  815. #ifdef HAVE_STRFTIME
  816. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  817. strftime(buf, BUFSIZE-1, "%a, %d %b %Y %H:%M:%S GMT", thistime);
  818. #else
  819. /* TODO: Right, we *could* write a replacement here */
  820. strcpy(buf, "no strftime() support");
  821. #endif
  822. switch(data->set.timecondition) {
  823. case CURL_TIMECOND_IFMODSINCE:
  824. default:
  825. add_bufferf(req_buffer,
  826. "If-Modified-Since: %s\r\n", buf);
  827. break;
  828. case CURL_TIMECOND_IFUNMODSINCE:
  829. add_bufferf(req_buffer,
  830. "If-Unmodified-Since: %s\r\n", buf);
  831. break;
  832. case CURL_TIMECOND_LASTMOD:
  833. add_bufferf(req_buffer,
  834. "Last-Modified: %s\r\n", buf);
  835. break;
  836. }
  837. }
  838. while(headers) {
  839. char *ptr = strchr(headers->data, ':');
  840. if(ptr) {
  841. /* we require a colon for this to be a true header */
  842. ptr++; /* pass the colon */
  843. while(*ptr && isspace((int)*ptr))
  844. ptr++;
  845. if(*ptr) {
  846. /* only send this if the contents was non-blank */
  847. add_bufferf(req_buffer, "%s\r\n", headers->data);
  848. }
  849. }
  850. headers = headers->next;
  851. }
  852. switch(data->set.httpreq) {
  853. case HTTPREQ_POST_FORM:
  854. if(Curl_FormInit(&http->form, http->sendit)) {
  855. failf(data, "Internal HTTP POST error!");
  856. return CURLE_HTTP_POST_ERROR;
  857. }
  858. /* set the read function to read from the generated form data */
  859. conn->fread = (curl_read_callback)Curl_FormReader;
  860. conn->fread_in = &http->form;
  861. http->sending = HTTPSEND_BODY;
  862. if(!conn->bits.upload_chunky)
  863. /* only add Content-Length if not uploading chunked */
  864. add_bufferf(req_buffer,
  865. "Content-Length: %d\r\n", http->postsize);
  866. if(!checkheaders(data, "Expect:")) {
  867. /* if not disabled explicitly we add a Expect: 100-continue
  868. to the headers which actually speeds up post operations (as
  869. there is one packet coming back from the web server) */
  870. add_bufferf(req_buffer,
  871. "Expect: 100-continue\r\n");
  872. data->set.expect100header = TRUE;
  873. }
  874. if(!checkheaders(data, "Content-Type:")) {
  875. /* Get Content-Type: line from Curl_FormReadOneLine, which happens
  876. to always be the first line. We can know this for sure since
  877. we always build the formpost linked list the same way!
  878. The Content-Type header line also contains the MIME boundary
  879. string etc why disabling this header is likely to not make things
  880. work, but we support it anyway.
  881. */
  882. char contentType[256];
  883. int linelength=0;
  884. linelength = Curl_FormReadOneLine (contentType,
  885. sizeof(contentType),
  886. 1,
  887. (FILE *)&http->form);
  888. if(linelength == -1) {
  889. failf(data, "Could not get Content-Type header line!");
  890. return CURLE_HTTP_POST_ERROR;
  891. }
  892. add_buffer(req_buffer, contentType, linelength);
  893. }
  894. /* make the request end in a true CRLF */
  895. add_buffer(req_buffer, "\r\n", 2);
  896. /* set upload size to the progress meter */
  897. Curl_pgrsSetUploadSize(data, http->postsize);
  898. /* fire away the whole request to the server */
  899. result = add_buffer_send(req_buffer, conn->firstsocket, conn,
  900. &data->info.request_size);
  901. if(result)
  902. failf(data, "Failed sending POST request");
  903. else
  904. /* setup variables for the upcoming transfer */
  905. result = Curl_Transfer(conn, conn->firstsocket, -1, TRUE,
  906. &http->readbytecount,
  907. conn->firstsocket,
  908. &http->writebytecount);
  909. if(result) {
  910. Curl_formclean(http->sendit); /* free that whole lot */
  911. return result;
  912. }
  913. break;
  914. case HTTPREQ_PUT: /* Let's PUT the data to the server! */
  915. if((data->set.infilesize>0) && !conn->bits.upload_chunky)
  916. /* only add Content-Length if not uploading chunked */
  917. add_bufferf(req_buffer,
  918. "Content-Length: %d\r\n", /* file size */
  919. data->set.infilesize );
  920. add_bufferf(req_buffer, "\r\n");
  921. /* set the upload size to the progress meter */
  922. Curl_pgrsSetUploadSize(data, data->set.infilesize);
  923. /* this sends the buffer and frees all the buffer resources */
  924. result = add_buffer_send(req_buffer, conn->firstsocket, conn,
  925. &data->info.request_size);
  926. if(result)
  927. failf(data, "Failed sending POST request");
  928. else
  929. /* prepare for transfer */
  930. result = Curl_Transfer(conn, conn->firstsocket, -1, TRUE,
  931. &http->readbytecount,
  932. conn->firstsocket,
  933. &http->writebytecount);
  934. if(result)
  935. return result;
  936. break;
  937. case HTTPREQ_POST:
  938. /* this is the simple POST, using x-www-form-urlencoded style */
  939. if(!conn->bits.upload_chunky) {
  940. /* We only set Content-Length and allow a custom Content-Length if
  941. we don't upload data chunked, as RFC2616 forbids us to set both
  942. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  943. if(!checkheaders(data, "Content-Length:"))
  944. /* we allow replacing this header, although it isn't very wise to
  945. actually set your own */
  946. add_bufferf(req_buffer,
  947. "Content-Length: %d\r\n",
  948. data->set.postfieldsize?
  949. data->set.postfieldsize:
  950. (data->set.postfields?strlen(data->set.postfields):0) );
  951. }
  952. if(!checkheaders(data, "Content-Type:"))
  953. add_bufferf(req_buffer,
  954. "Content-Type: application/x-www-form-urlencoded\r\n");
  955. add_buffer(req_buffer, "\r\n", 2);
  956. /* and here we setup the pointers to the actual data */
  957. if(data->set.postfields) {
  958. if(data->set.postfieldsize)
  959. http->postsize = data->set.postfieldsize;
  960. else
  961. http->postsize = strlen(data->set.postfields);
  962. http->postdata = data->set.postfields;
  963. http->sending = HTTPSEND_BODY;
  964. conn->fread = (curl_read_callback)readmoredata;
  965. conn->fread_in = (void *)conn;
  966. /* set the upload size to the progress meter */
  967. Curl_pgrsSetUploadSize(data, http->postsize);
  968. }
  969. else
  970. /* set the upload size to the progress meter */
  971. Curl_pgrsSetUploadSize(data, data->set.infilesize);
  972. /* issue the request, headers-only */
  973. result = add_buffer_send(req_buffer, conn->firstsocket, conn,
  974. &data->info.request_size);
  975. if(result)
  976. failf(data, "Failed sending HTTP POST request");
  977. else
  978. result =
  979. Curl_Transfer(conn, conn->firstsocket, -1, TRUE,
  980. &http->readbytecount,
  981. conn->firstsocket,
  982. &http->writebytecount);
  983. break;
  984. default:
  985. add_buffer(req_buffer, "\r\n", 2);
  986. /* issue the request */
  987. result = add_buffer_send(req_buffer, conn->firstsocket, conn,
  988. &data->info.request_size);
  989. if(result)
  990. failf(data, "Failed sending HTTP request");
  991. else
  992. /* HTTP GET/HEAD download: */
  993. result = Curl_Transfer(conn, conn->firstsocket, -1, TRUE,
  994. &http->readbytecount,
  995. http->postdata?conn->firstsocket:-1,
  996. http->postdata?&http->writebytecount:NULL);
  997. }
  998. if(result)
  999. return result;
  1000. } while (0); /* this is just a left-over from the multiple document download
  1001. attempts */
  1002. return CURLE_OK;
  1003. }
  1004. /*
  1005. * local variables:
  1006. * eval: (load-file "../curl-mode.el")
  1007. * end:
  1008. * vim600: fdm=marker
  1009. * vim: et sw=2 ts=2 sts=2 tw=78
  1010. */
  1011. #endif