blob: e4e3405d307dcf5ce2189c3ce2c60f4deb62a9dc [file] [log] [blame]
9487f7f2011-08-03 07:05:30 -07001/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2010, 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 ***************************************************************************/
22
23#include "setup.h"
24
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 <errno.h>
32
33#include "strtoofft.h"
34#include "strequal.h"
35#include "rawstr.h"
36
37#ifdef WIN32
38#include <time.h>
39#include <io.h>
40#else
41#ifdef HAVE_SYS_SOCKET_H
42#include <sys/socket.h>
43#endif
44#ifdef HAVE_NETINET_IN_H
45#include <netinet/in.h>
46#endif
47#ifdef HAVE_SYS_TIME_H
48#include <sys/time.h>
49#endif
50#ifdef HAVE_UNISTD_H
51#include <unistd.h>
52#endif
53#ifdef HAVE_NETDB_H
54#include <netdb.h>
55#endif
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#ifdef HAVE_SYS_IOCTL_H
63#include <sys/ioctl.h>
64#endif
65#ifdef HAVE_SIGNAL_H
66#include <signal.h>
67#endif
68
69#ifdef HAVE_SYS_PARAM_H
70#include <sys/param.h>
71#endif
72
73#ifdef HAVE_SYS_SELECT_H
74#include <sys/select.h>
75#endif
76
77#ifndef HAVE_SOCKET
78#error "We can't compile without socket() support!"
79#endif
80
81#endif /* WIN32 */
82
83#include "urldata.h"
84#include <curl/curl.h>
85#include "netrc.h"
86
87#include "content_encoding.h"
88#include "hostip.h"
89#include "transfer.h"
90#include "sendf.h"
91#include "speedcheck.h"
92#include "progress.h"
93#include "http.h"
94#include "url.h"
95#include "getinfo.h"
96#include "sslgen.h"
97#include "http_digest.h"
98#include "http_ntlm.h"
99#include "http_negotiate.h"
100#include "share.h"
101#include "curl_memory.h"
102#include "select.h"
103#include "multiif.h"
104#include "easyif.h" /* for Curl_convert_to_network prototype */
105#include "rtsp.h"
106#include "connect.h"
107
108#define _MPRINTF_REPLACE /* use our functions only */
109#include <curl/mprintf.h>
110
111/* The last #include file should be: */
112#include "memdebug.h"
113
114#define CURL_TIMEOUT_EXPECT_100 1000 /* counting ms here */
115
116/*
117 * This function will call the read callback to fill our buffer with data
118 * to upload.
119 */
120CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
121{
122 struct SessionHandle *data = conn->data;
123 size_t buffersize = (size_t)bytes;
124 int nread;
125#ifdef CURL_DOES_CONVERSIONS
126 bool sending_http_headers = FALSE;
127
128 if((conn->protocol&(PROT_HTTP|PROT_RTSP)) &&
129 (data->state.proto.http->sending == HTTPSEND_REQUEST)) {
130 /* We're sending the HTTP request headers, not the data.
131 Remember that so we don't re-translate them into garbage. */
132 sending_http_headers = TRUE;
133 }
134#endif
135
136 if(data->req.upload_chunky) {
137 /* if chunked Transfer-Encoding */
138 buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */
139 data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */
140 }
141
142 /* this function returns a size_t, so we typecast to int to prevent warnings
143 with picky compilers */
144 nread = (int)conn->fread_func(data->req.upload_fromhere, 1,
145 buffersize, conn->fread_in);
146
147 if(nread == CURL_READFUNC_ABORT) {
148 failf(data, "operation aborted by callback");
149 *nreadp = 0;
150 return CURLE_ABORTED_BY_CALLBACK;
151 }
152 else if(nread == CURL_READFUNC_PAUSE) {
153 struct SingleRequest *k = &data->req;
154 /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */
155 k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */
156 if(data->req.upload_chunky) {
157 /* Back out the preallocation done above */
158 data->req.upload_fromhere -= (8 + 2);
159 }
160 *nreadp = 0;
161 return CURLE_OK; /* nothing was read */
162 }
163 else if((size_t)nread > buffersize) {
164 /* the read function returned a too large value */
165 *nreadp = 0;
166 failf(data, "read function returned funny value");
167 return CURLE_READ_ERROR;
168 }
169
170 if(!data->req.forbidchunk && data->req.upload_chunky) {
171 /* if chunked Transfer-Encoding
172 * build chunk:
173 *
174 * <HEX SIZE> CRLF
175 * <DATA> CRLF
176 */
177 /* On non-ASCII platforms the <DATA> may or may not be
178 translated based on set.prefer_ascii while the protocol
179 portion must always be translated to the network encoding.
180 To further complicate matters, line end conversion might be
181 done later on, so we need to prevent CRLFs from becoming
182 CRCRLFs if that's the case. To do this we use bare LFs
183 here, knowing they'll become CRLFs later on.
184 */
185
186 char hexbuffer[11];
187 const char *endofline_native;
188 const char *endofline_network;
189 int hexlen;
190#ifdef CURL_DO_LINEEND_CONV
191 if((data->set.crlf) || (data->set.prefer_ascii)) {
192#else
193 if(data->set.crlf) {
194#endif /* CURL_DO_LINEEND_CONV */
195 /* \n will become \r\n later on */
196 endofline_native = "\n";
197 endofline_network = "\x0a";
198 }
199 else {
200 endofline_native = "\r\n";
201 endofline_network = "\x0d\x0a";
202 }
203 hexlen = snprintf(hexbuffer, sizeof(hexbuffer),
204 "%x%s", nread, endofline_native);
205
206 /* move buffer pointer */
207 data->req.upload_fromhere -= hexlen;
208 nread += hexlen;
209
210 /* copy the prefix to the buffer, leaving out the NUL */
211 memcpy(data->req.upload_fromhere, hexbuffer, hexlen);
212
213 /* always append ASCII CRLF to the data */
214 memcpy(data->req.upload_fromhere + nread,
215 endofline_network,
216 strlen(endofline_network));
217
218#ifdef CURL_DOES_CONVERSIONS
219 CURLcode res;
220 int length;
221 if(data->set.prefer_ascii) {
222 /* translate the protocol and data */
223 length = nread;
224 }
225 else {
226 /* just translate the protocol portion */
227 length = strlen(hexbuffer);
228 }
229 res = Curl_convert_to_network(data, data->req.upload_fromhere, length);
230 /* Curl_convert_to_network calls failf if unsuccessful */
231 if(res)
232 return(res);
233#endif /* CURL_DOES_CONVERSIONS */
234
235 if((nread - hexlen) == 0)
236 /* mark this as done once this chunk is transfered */
237 data->req.upload_done = TRUE;
238
239 nread+=(int)strlen(endofline_native); /* for the added end of line */
240 }
241#ifdef CURL_DOES_CONVERSIONS
242 else if((data->set.prefer_ascii) && (!sending_http_headers)) {
243 CURLcode res;
244 res = Curl_convert_to_network(data, data->req.upload_fromhere, nread);
245 /* Curl_convert_to_network calls failf if unsuccessful */
246 if(res != CURLE_OK)
247 return(res);
248 }
249#endif /* CURL_DOES_CONVERSIONS */
250
251 *nreadp = nread;
252
253 return CURLE_OK;
254}
255
256
257/*
258 * Curl_readrewind() rewinds the read stream. This is typically used for HTTP
259 * POST/PUT with multi-pass authentication when a sending was denied and a
260 * resend is necessary.
261 */
262CURLcode Curl_readrewind(struct connectdata *conn)
263{
264 struct SessionHandle *data = conn->data;
265
266 conn->bits.rewindaftersend = FALSE; /* we rewind now */
267
268 /* explicitly switch off sending data on this connection now since we are
269 about to restart a new transfer and thus we want to avoid inadvertently
270 sending more data on the existing connection until the next transfer
271 starts */
272 data->req.keepon &= ~KEEP_SEND;
273
274 /* We have sent away data. If not using CURLOPT_POSTFIELDS or
275 CURLOPT_HTTPPOST, call app to rewind
276 */
277 if(data->set.postfields ||
278 (data->set.httpreq == HTTPREQ_POST_FORM))
279 ; /* do nothing */
280 else {
281 if(data->set.seek_func) {
282 int err;
283
284 err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET);
285 if(err) {
286 failf(data, "seek callback returned error %d", (int)err);
287 return CURLE_SEND_FAIL_REWIND;
288 }
289 }
290 else if(data->set.ioctl_func) {
291 curlioerr err;
292
293 err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD,
294 data->set.ioctl_client);
295 infof(data, "the ioctl callback returned %d\n", (int)err);
296
297 if(err) {
298 /* FIXME: convert to a human readable error message */
299 failf(data, "ioctl callback returned error %d", (int)err);
300 return CURLE_SEND_FAIL_REWIND;
301 }
302 }
303 else {
304 /* If no CURLOPT_READFUNCTION is used, we know that we operate on a
305 given FILE * stream and we can actually attempt to rewind that
306 ourself with fseek() */
307 if(data->set.fread_func == (curl_read_callback)fread) {
308 if(-1 != fseek(data->set.in, 0, SEEK_SET))
309 /* successful rewind */
310 return CURLE_OK;
311 }
312
313 /* no callback set or failure above, makes us fail at once */
314 failf(data, "necessary data rewind wasn't possible");
315 return CURLE_SEND_FAIL_REWIND;
316 }
317 }
318 return CURLE_OK;
319}
320
321static int data_pending(const struct connectdata *conn)
322{
323 /* in the case of libssh2, we can never be really sure that we have emptied
324 its internal buffers so we MUST always try until we get EAGAIN back */
325 return conn->protocol&(PROT_SCP|PROT_SFTP) ||
326 Curl_ssl_data_pending(conn, FIRSTSOCKET);
327}
328
329static void read_rewind(struct connectdata *conn,
330 size_t thismuch)
331{
332 DEBUGASSERT(conn->read_pos >= thismuch);
333
334 conn->read_pos -= thismuch;
335 conn->bits.stream_was_rewound = TRUE;
336
337#ifdef DEBUGBUILD
338 {
339 char buf[512 + 1];
340 size_t show;
341
342 show = CURLMIN(conn->buf_len - conn->read_pos, sizeof(buf)-1);
343 if(conn->master_buffer) {
344 memcpy(buf, conn->master_buffer + conn->read_pos, show);
345 buf[show] = '\0';
346 }
347 else {
348 buf[0] = '\0';
349 }
350
351 DEBUGF(infof(conn->data,
352 "Buffer after stream rewind (read_pos = %zu): [%s]",
353 conn->read_pos, buf));
354 }
355#endif
356}
357
358
359/*
360 * Go ahead and do a read if we have a readable socket or if
361 * the stream was rewound (in which case we have data in a
362 * buffer)
363 */
364static CURLcode readwrite_data(struct SessionHandle *data,
365 struct connectdata *conn,
366 struct SingleRequest *k,
367 int *didwhat, bool *done)
368{
369 CURLcode result = CURLE_OK;
370 ssize_t nread; /* number of bytes read */
371 size_t excess = 0; /* excess bytes read */
372 bool is_empty_data = FALSE;
373#ifndef CURL_DISABLE_RTSP
374 bool readmore = FALSE; /* used by RTP to signal for more data */
375#endif
376
377 *done = FALSE;
378
379 /* This is where we loop until we have read everything there is to
380 read or we get a CURLE_AGAIN */
381 do {
382 size_t buffersize = data->set.buffer_size?
383 data->set.buffer_size : BUFSIZE;
384 size_t bytestoread = buffersize;
385
386 if(k->size != -1 && !k->header) {
387 /* make sure we don't read "too much" if we can help it since we
388 might be pipelining and then someone else might want to read what
389 follows! */
390 curl_off_t totalleft = k->size - k->bytecount;
391 if(totalleft < (curl_off_t)bytestoread)
392 bytestoread = (size_t)totalleft;
393 }
394
395 if(bytestoread) {
396 /* receive data from the network! */
397 result = Curl_read(conn, conn->sockfd, k->buf, bytestoread, &nread);
398
399 /* read would've blocked */
400 if(CURLE_AGAIN == result)
401 break; /* get out of loop */
402
403 if(result>0)
404 return result;
405 }
406 else {
407 /* read nothing but since we wanted nothing we consider this an OK
408 situation to proceed from */
409 nread = 0;
410 }
411
412 if((k->bytecount == 0) && (k->writebytecount == 0)) {
413 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
414 if(k->exp100 > EXP100_SEND_DATA)
415 /* set time stamp to compare with when waiting for the 100 */
416 k->start100 = Curl_tvnow();
417 }
418
419 *didwhat |= KEEP_RECV;
420 /* indicates data of zero size, i.e. empty file */
421 is_empty_data = (bool)((nread == 0) && (k->bodywrites == 0));
422
423 /* NUL terminate, allowing string ops to be used */
424 if(0 < nread || is_empty_data) {
425 k->buf[nread] = 0;
426 }
427 else if(0 >= nread) {
428 /* if we receive 0 or less here, the server closed the connection
429 and we bail out from this! */
430 DEBUGF(infof(data, "nread <= 0, server closed connection, bailing\n"));
431 k->keepon &= ~KEEP_RECV;
432 break;
433 }
434
435 /* Default buffer to use when we write the buffer, it may be changed
436 in the flow below before the actual storing is done. */
437 k->str = k->buf;
438
439#ifndef CURL_DISABLE_RTSP
440 /* Check for RTP at the beginning of the data */
441 if(conn->protocol & PROT_RTSP) {
442 result = Curl_rtsp_rtp_readwrite(data, conn, &nread, &readmore);
443 if(result)
444 return result;
445 if(readmore)
446 break;
447 }
448#endif
449
450#ifndef CURL_DISABLE_HTTP
451 /* Since this is a two-state thing, we check if we are parsing
452 headers at the moment or not. */
453 if(k->header) {
454 /* we are in parse-the-header-mode */
455 bool stop_reading = FALSE;
456 result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading);
457 if(result)
458 return result;
459
460#ifndef CURL_DISABLE_RTSP
461 /* Check for RTP after the headers if there is no Content */
462 if(k->maxdownload <= 0 && nread > 0 && (conn->protocol & PROT_RTSP)) {
463 result = Curl_rtsp_rtp_readwrite(data, conn, &nread, &readmore);
464 if(result)
465 return result;
466 if(readmore)
467 break;
468 }
469#endif
470
471 if(stop_reading)
472 /* We've stopped dealing with input, get out of the do-while loop */
473 break;
474 }
475#endif /* CURL_DISABLE_HTTP */
476
477
478 /* This is not an 'else if' since it may be a rest from the header
479 parsing, where the beginning of the buffer is headers and the end
480 is non-headers. */
481 if(k->str && !k->header && (nread > 0 || is_empty_data)) {
482
483
484#ifndef CURL_DISABLE_HTTP
485 if(0 == k->bodywrites && !is_empty_data) {
486 /* These checks are only made the first time we are about to
487 write a piece of the body */
488 if(conn->protocol&(PROT_HTTP|PROT_RTSP)) {
489 /* HTTP-only checks */
490
491 if(data->req.newurl) {
492 if(conn->bits.close) {
493 /* Abort after the headers if "follow Location" is set
494 and we're set to close anyway. */
495 k->keepon &= ~KEEP_RECV;
496 *done = TRUE;
497 return CURLE_OK;
498 }
499 /* We have a new url to load, but since we want to be able
500 to re-use this connection properly, we read the full
501 response in "ignore more" */
502 k->ignorebody = TRUE;
503 infof(data, "Ignoring the response-body\n");
504 }
505 if(data->state.resume_from && !k->content_range &&
506 (data->set.httpreq==HTTPREQ_GET) &&
507 !k->ignorebody) {
508 /* we wanted to resume a download, although the server doesn't
509 * seem to support this and we did this with a GET (if it
510 * wasn't a GET we did a POST or PUT resume) */
511 failf(data, "HTTP server doesn't seem to support "
512 "byte ranges. Cannot resume.");
513 return CURLE_RANGE_ERROR;
514 }
515
516 if(data->set.timecondition && !data->state.range) {
517 /* A time condition has been set AND no ranges have been
518 requested. This seems to be what chapter 13.3.4 of
519 RFC 2616 defines to be the correct action for a
520 HTTP/1.1 client */
521 if((k->timeofdoc > 0) && (data->set.timevalue > 0)) {
522 switch(data->set.timecondition) {
523 case CURL_TIMECOND_IFMODSINCE:
524 default:
525 if(k->timeofdoc < data->set.timevalue) {
526 infof(data,
527 "The requested document is not new enough\n");
528 *done = TRUE;
529 data->info.timecond = TRUE;
530 return CURLE_OK;
531 }
532 break;
533 case CURL_TIMECOND_IFUNMODSINCE:
534 if(k->timeofdoc > data->set.timevalue) {
535 infof(data,
536 "The requested document is not old enough\n");
537 *done = TRUE;
538 data->info.timecond = TRUE;
539 return CURLE_OK;
540 }
541 break;
542 } /* switch */
543 } /* two valid time strings */
544 } /* we have a time condition */
545
546 } /* this is HTTP */
547 } /* this is the first time we write a body part */
548#endif /* CURL_DISABLE_HTTP */
549 k->bodywrites++;
550
551 /* pass data to the debug function before it gets "dechunked" */
552 if(data->set.verbose) {
553 if(k->badheader) {
554 Curl_debug(data, CURLINFO_DATA_IN, data->state.headerbuff,
555 (size_t)k->hbuflen, conn);
556 if(k->badheader == HEADER_PARTHEADER)
557 Curl_debug(data, CURLINFO_DATA_IN,
558 k->str, (size_t)nread, conn);
559 }
560 else
561 Curl_debug(data, CURLINFO_DATA_IN,
562 k->str, (size_t)nread, conn);
563 }
564
565#ifndef CURL_DISABLE_HTTP
566 if(k->chunk) {
567 /*
568 * Here comes a chunked transfer flying and we need to decode this
569 * properly. While the name says read, this function both reads
570 * and writes away the data. The returned 'nread' holds the number
571 * of actual data it wrote to the client.
572 */
573
574 CHUNKcode res =
575 Curl_httpchunk_read(conn, k->str, nread, &nread);
576
577 if(CHUNKE_OK < res) {
578 if(CHUNKE_WRITE_ERROR == res) {
579 failf(data, "Failed writing data");
580 return CURLE_WRITE_ERROR;
581 }
582 failf(data, "Received problem %d in the chunky parser", (int)res);
583 return CURLE_RECV_ERROR;
584 }
585 else if(CHUNKE_STOP == res) {
586 size_t dataleft;
587 /* we're done reading chunks! */
588 k->keepon &= ~KEEP_RECV; /* read no more */
589
590 /* There are now possibly N number of bytes at the end of the
591 str buffer that weren't written to the client.
592
593 We DO care about this data if we are pipelining.
594 Push it back to be read on the next pass. */
595
596 dataleft = conn->chunk.dataleft;
597 if(dataleft != 0) {
598 infof(conn->data, "Leftovers after chunking: %zu bytes", dataleft);
599 if(conn->data->multi && Curl_multi_canPipeline(conn->data->multi)) {
600 /* only attempt the rewind if we truly are pipelining */
601 infof(conn->data, "Rewinding %zu bytes\n",dataleft);
602 read_rewind(conn, dataleft);
603 }
604 }
605 }
606 /* If it returned OK, we just keep going */
607 }
608#endif /* CURL_DISABLE_HTTP */
609
610 /* Account for body content stored in the header buffer */
611 if(k->badheader && !k->ignorebody) {
612 DEBUGF(infof(data, "Increasing bytecount by %zu from hbuflen\n",
613 k->hbuflen));
614 k->bytecount += k->hbuflen;
615 }
616
617 if((-1 != k->maxdownload) &&
618 (k->bytecount + nread >= k->maxdownload)) {
619
620 excess = (size_t)(k->bytecount + nread - k->maxdownload);
621 if(excess > 0 && !k->ignorebody) {
622 if(conn->data->multi && Curl_multi_canPipeline(conn->data->multi)) {
623 /* The 'excess' amount below can't be more than BUFSIZE which
624 always will fit in a size_t */
625 infof(data,
626 "Rewinding stream by : %zu"
627 " bytes on url %s (size = %" FORMAT_OFF_T
628 ", maxdownload = %" FORMAT_OFF_T
629 ", bytecount = %" FORMAT_OFF_T ", nread = %zd)\n",
630 excess, data->state.path,
631 k->size, k->maxdownload, k->bytecount, nread);
632 read_rewind(conn, excess);
633 }
634 else {
635 infof(data,
636 "Excess found in a non pipelined read:"
637 " excess = %zu"
638 ", size = %" FORMAT_OFF_T
639 ", maxdownload = %" FORMAT_OFF_T
640 ", bytecount = %" FORMAT_OFF_T "\n",
641 excess, k->size, k->maxdownload, k->bytecount);
642 }
643 }
644
645 nread = (ssize_t) (k->maxdownload - k->bytecount);
646 if(nread < 0 ) /* this should be unusual */
647 nread = 0;
648
649 k->keepon &= ~KEEP_RECV; /* we're done reading */
650 }
651
652 k->bytecount += nread;
653
654 Curl_pgrsSetDownloadCounter(data, k->bytecount);
655
656 if(!k->chunk && (nread || k->badheader || is_empty_data)) {
657 /* If this is chunky transfer, it was already written */
658
659 if(k->badheader && !k->ignorebody) {
660 /* we parsed a piece of data wrongly assuming it was a header
661 and now we output it as body instead */
662
663 /* Don't let excess data pollute body writes */
664 if(k->maxdownload == -1 || (curl_off_t)k->hbuflen <= k->maxdownload)
665 result = Curl_client_write(conn, CLIENTWRITE_BODY,
666 data->state.headerbuff,
667 k->hbuflen);
668 else
669 result = Curl_client_write(conn, CLIENTWRITE_BODY,
670 data->state.headerbuff,
671 (size_t)k->maxdownload);
672
673 if(result)
674 return result;
675 }
676 if(k->badheader < HEADER_ALLBAD) {
677 /* This switch handles various content encodings. If there's an
678 error here, be sure to check over the almost identical code
679 in http_chunks.c.
680 Make sure that ALL_CONTENT_ENCODINGS contains all the
681 encodings handled here. */
682#ifdef HAVE_LIBZ
683 switch (conn->data->set.http_ce_skip ?
684 IDENTITY : k->content_encoding) {
685 case IDENTITY:
686#endif
687 /* This is the default when the server sends no
688 Content-Encoding header. See Curl_readwrite_init; the
689 memset() call initializes k->content_encoding to zero. */
690 if(!k->ignorebody) {
691
692#ifndef CURL_DISABLE_POP3
693 if(conn->protocol&PROT_POP3)
694 result = Curl_pop3_write(conn, k->str, nread);
695 else
696#endif /* CURL_DISABLE_POP3 */
697
698 result = Curl_client_write(conn, CLIENTWRITE_BODY, k->str,
699 nread);
700 }
701#ifdef HAVE_LIBZ
702 break;
703
704 case DEFLATE:
705 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
706 if(!k->ignorebody)
707 result = Curl_unencode_deflate_write(conn, k, nread);
708 break;
709
710 case GZIP:
711 /* Assume CLIENTWRITE_BODY; headers are not encoded. */
712 if(!k->ignorebody)
713 result = Curl_unencode_gzip_write(conn, k, nread);
714 break;
715
716 case COMPRESS:
717 default:
718 failf (data, "Unrecognized content encoding type. "
719 "libcurl understands `identity', `deflate' and `gzip' "
720 "content encodings.");
721 result = CURLE_BAD_CONTENT_ENCODING;
722 break;
723 }
724#endif
725 }
726 k->badheader = HEADER_NORMAL; /* taken care of now */
727
728 if(result)
729 return result;
730 }
731
732 } /* if(! header and data to read ) */
733
734#ifndef CURL_DISABLE_RTSP
735 if(excess > 0 && !conn->bits.stream_was_rewound &&
736 (conn->protocol & PROT_RTSP)) {
737 /* Check for RTP after the content if there is unrewound excess */
738
739 /* Parse the excess data */
740 k->str += nread;
741 nread = (ssize_t)excess;
742
743 result = Curl_rtsp_rtp_readwrite(data, conn, &nread, &readmore);
744 if(result)
745 return result;
746
747 if(readmore)
748 k->keepon |= KEEP_RECV; /* we're not done reading */
749 break;
750 }
751#endif
752
753 if(is_empty_data) {
754 /* if we received nothing, the server closed the connection and we
755 are done */
756 k->keepon &= ~KEEP_RECV;
757 }
758
759 } while(data_pending(conn));
760
761 if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
762 conn->bits.close ) {
763 /* When we've read the entire thing and the close bit is set, the server
764 may now close the connection. If there's now any kind of sending going
765 on from our side, we need to stop that immediately. */
766 infof(data, "we are done reading and this is set to close, stop send\n");
767 k->keepon &= ~KEEP_SEND; /* no writing anymore either */
768 }
769
770 return CURLE_OK;
771}
772
773/*
774 * Send data to upload to the server, when the socket is writable.
775 */
776static CURLcode readwrite_upload(struct SessionHandle *data,
777 struct connectdata *conn,
778 struct SingleRequest *k,
779 int *didwhat)
780{
781 ssize_t i, si;
782 ssize_t bytes_written;
783 CURLcode result;
784 ssize_t nread; /* number of bytes read */
785 bool sending_http_headers = FALSE;
786
787 if((k->bytecount == 0) && (k->writebytecount == 0))
788 Curl_pgrsTime(data, TIMER_STARTTRANSFER);
789
790 *didwhat |= KEEP_SEND;
791
792 /*
793 * We loop here to do the READ and SEND loop until we run out of
794 * data to send or until we get EWOULDBLOCK back
795 */
796 do {
797
798 /* only read more data if there's no upload data already
799 present in the upload buffer */
800 if(0 == data->req.upload_present) {
801 /* init the "upload from here" pointer */
802 data->req.upload_fromhere = k->uploadbuf;
803
804 if(!k->upload_done) {
805 /* HTTP pollution, this should be written nicer to become more
806 protocol agnostic. */
807 int fillcount;
808
809 if((k->exp100 == EXP100_SENDING_REQUEST) &&
810 (data->state.proto.http->sending == HTTPSEND_BODY)) {
811 /* If this call is to send body data, we must take some action:
812 We have sent off the full HTTP 1.1 request, and we shall now
813 go into the Expect: 100 state and await such a header */
814 k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */
815 k->keepon &= ~KEEP_SEND; /* disable writing */
816 k->start100 = Curl_tvnow(); /* timeout count starts now */
817 *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */
818
819 /* set a timeout for the multi interface */
820 Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
821 break;
822 }
823
824 if(conn->protocol&(PROT_HTTP|PROT_RTSP)) {
825 if(data->state.proto.http->sending == HTTPSEND_REQUEST)
826 /* We're sending the HTTP request headers, not the data.
827 Remember that so we don't change the line endings. */
828 sending_http_headers = TRUE;
829 else
830 sending_http_headers = FALSE;
831 }
832
833 result = Curl_fillreadbuffer(conn, BUFSIZE, &fillcount);
834 if(result)
835 return result;
836
837 nread = (ssize_t)fillcount;
838 }
839 else
840 nread = 0; /* we're done uploading/reading */
841
842 if(!nread && (k->keepon & KEEP_SEND_PAUSE)) {
843 /* this is a paused transfer */
844 break;
845 }
846 else if(nread<=0) {
847 /* done */
848 k->keepon &= ~KEEP_SEND; /* we're done writing */
849
850 if(conn->bits.rewindaftersend) {
851 result = Curl_readrewind(conn);
852 if(result)
853 return result;
854 }
855 break;
856 }
857
858 /* store number of bytes available for upload */
859 data->req.upload_present = nread;
860
861#ifndef CURL_DISABLE_SMTP
862 if(conn->protocol & PROT_SMTP) {
863 result = Curl_smtp_escape_eob(conn, nread);
864 if(result)
865 return result;
866 }
867 else
868#endif /* CURL_DISABLE_SMTP */
869
870 /* convert LF to CRLF if so asked */
871 if((!sending_http_headers) &&
872#ifdef CURL_DO_LINEEND_CONV
873 /* always convert if we're FTPing in ASCII mode */
874 ((data->set.crlf) || (data->set.prefer_ascii))) {
875#else
876 (data->set.crlf)) {
877#endif
878 if(data->state.scratch == NULL)
879 data->state.scratch = malloc(2*BUFSIZE);
880 if(data->state.scratch == NULL) {
881 failf (data, "Failed to alloc scratch buffer!");
882 return CURLE_OUT_OF_MEMORY;
883 }
884 /*
885 * ASCII/EBCDIC Note: This is presumably a text (not binary)
886 * transfer so the data should already be in ASCII.
887 * That means the hex values for ASCII CR (0x0d) & LF (0x0a)
888 * must be used instead of the escape sequences \r & \n.
889 */
890 for(i = 0, si = 0; i < nread; i++, si++) {
891 if(data->req.upload_fromhere[i] == 0x0a) {
892 data->state.scratch[si++] = 0x0d;
893 data->state.scratch[si] = 0x0a;
894 if(!data->set.crlf) {
895 /* we're here only because FTP is in ASCII mode...
896 bump infilesize for the LF we just added */
897 data->set.infilesize++;
898 }
899 }
900 else
901 data->state.scratch[si] = data->req.upload_fromhere[i];
902 }
903 if(si != nread) {
904 /* only perform the special operation if we really did replace
905 anything */
906 nread = si;
907
908 /* upload from the new (replaced) buffer instead */
909 data->req.upload_fromhere = data->state.scratch;
910
911 /* set the new amount too */
912 data->req.upload_present = nread;
913 }
914 }
915 } /* if 0 == data->req.upload_present */
916 else {
917 /* We have a partial buffer left from a previous "round". Use
918 that instead of reading more data */
919 }
920
921 /* write to socket (send away data) */
922 result = Curl_write(conn,
923 conn->writesockfd, /* socket to send to */
924 data->req.upload_fromhere, /* buffer pointer */
925 data->req.upload_present, /* buffer size */
926 &bytes_written); /* actually sent */
927
928 if(result)
929 return result;
930
931 if(data->set.verbose)
932 /* show the data before we change the pointer upload_fromhere */
933 Curl_debug(data, CURLINFO_DATA_OUT, data->req.upload_fromhere,
934 (size_t)bytes_written, conn);
935
936 if(data->req.upload_present != bytes_written) {
937 /* we only wrote a part of the buffer (if anything), deal with it! */
938
939 /* store the amount of bytes left in the buffer to write */
940 data->req.upload_present -= bytes_written;
941
942 /* advance the pointer where to find the buffer when the next send
943 is to happen */
944 data->req.upload_fromhere += bytes_written;
945 }
946 else {
947 /* we've uploaded that buffer now */
948 data->req.upload_fromhere = k->uploadbuf;
949 data->req.upload_present = 0; /* no more bytes left */
950
951 if(k->upload_done) {
952 /* switch off writing, we're done! */
953 k->keepon &= ~KEEP_SEND; /* we're done writing */
954 }
955 }
956
957 k->writebytecount += bytes_written;
958 Curl_pgrsSetUploadCounter(data, k->writebytecount);
959
960 } while(0); /* just to break out from! */
961
962 return CURLE_OK;
963}
964
965/*
966 * Curl_readwrite() is the low-level function to be called when data is to
967 * be read and written to/from the connection.
968 */
969CURLcode Curl_readwrite(struct connectdata *conn,
970 bool *done)
971{
972 struct SessionHandle *data = conn->data;
973 struct SingleRequest *k = &data->req;
974 CURLcode result;
975 int didwhat=0;
976
977 curl_socket_t fd_read;
978 curl_socket_t fd_write;
979 int select_res = conn->cselect_bits;
980
981 conn->cselect_bits = 0;
982
983 /* only use the proper socket if the *_HOLD bit is not set simultaneously as
984 then we are in rate limiting state in that transfer direction */
985
986 if((k->keepon & KEEP_RECVBITS) == KEEP_RECV)
987 fd_read = conn->sockfd;
988 else
989 fd_read = CURL_SOCKET_BAD;
990
991 if((k->keepon & KEEP_SENDBITS) == KEEP_SEND)
992 fd_write = conn->writesockfd;
993 else
994 fd_write = CURL_SOCKET_BAD;
995
996 if(!select_res) /* Call for select()/poll() only, if read/write/error
997 status is not known. */
998 select_res = Curl_socket_ready(fd_read, fd_write, 0);
999
1000 if(select_res == CURL_CSELECT_ERR) {
1001 failf(data, "select/poll returned error");
1002 return CURLE_SEND_ERROR;
1003 }
1004
1005 /* We go ahead and do a read if we have a readable socket or if
1006 the stream was rewound (in which case we have data in a
1007 buffer) */
1008 if((k->keepon & KEEP_RECV) &&
1009 ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
1010
1011 result = readwrite_data(data, conn, k, &didwhat, done);
1012 if(result || *done)
1013 return result;
1014 }
1015
1016 /* If we still have writing to do, we check if we have a writable socket. */
1017 if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) {
1018 /* write */
1019
1020 result = readwrite_upload(data, conn, k, &didwhat);
1021 if(result)
1022 return result;
1023 }
1024
1025 k->now = Curl_tvnow();
1026 if(didwhat) {
1027 /* Update read/write counters */
1028 if(k->bytecountp)
1029 *k->bytecountp = k->bytecount; /* read count */
1030 if(k->writebytecountp)
1031 *k->writebytecountp = k->writebytecount; /* write count */
1032 }
1033 else {
1034 /* no read no write, this is a timeout? */
1035 if(k->exp100 == EXP100_AWAITING_CONTINUE) {
1036 /* This should allow some time for the header to arrive, but only a
1037 very short time as otherwise it'll be too much wasted time too
1038 often. */
1039
1040 /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status":
1041
1042 Therefore, when a client sends this header field to an origin server
1043 (possibly via a proxy) from which it has never seen a 100 (Continue)
1044 status, the client SHOULD NOT wait for an indefinite period before
1045 sending the request body.
1046
1047 */
1048
1049 long ms = Curl_tvdiff(k->now, k->start100);
1050 if(ms > CURL_TIMEOUT_EXPECT_100) {
1051 /* we've waited long enough, continue anyway */
1052 k->exp100 = EXP100_SEND_DATA;
1053 k->keepon |= KEEP_SEND;
1054 infof(data, "Done waiting for 100-continue\n");
1055 }
1056 }
1057 }
1058
1059 if(Curl_pgrsUpdate(conn))
1060 result = CURLE_ABORTED_BY_CALLBACK;
1061 else
1062 result = Curl_speedcheck(data, k->now);
1063 if(result)
1064 return result;
1065
1066 if(k->keepon) {
1067 if(0 > Curl_timeleft(conn, &k->now, FALSE)) {
1068 if(k->size != -1) {
1069 failf(data, "Operation timed out after %ld milliseconds with %"
1070 FORMAT_OFF_T " out of %" FORMAT_OFF_T " bytes received",
1071 Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount,
1072 k->size);
1073 }
1074 else {
1075 failf(data, "Operation timed out after %ld milliseconds with %"
1076 FORMAT_OFF_T " bytes received",
1077 Curl_tvdiff(k->now, data->progress.t_startsingle), k->bytecount);
1078 }
1079 return CURLE_OPERATION_TIMEDOUT;
1080 }
1081 }
1082 else {
1083 /*
1084 * The transfer has been performed. Just make some general checks before
1085 * returning.
1086 */
1087
1088 if(!(data->set.opt_no_body) && (k->size != -1) &&
1089 (k->bytecount != k->size) &&
1090#ifdef CURL_DO_LINEEND_CONV
1091 /* Most FTP servers don't adjust their file SIZE response for CRLFs,
1092 so we'll check to see if the discrepancy can be explained
1093 by the number of CRLFs we've changed to LFs.
1094 */
1095 (k->bytecount != (k->size + data->state.crlf_conversions)) &&
1096#endif /* CURL_DO_LINEEND_CONV */
1097 !data->req.newurl) {
1098 failf(data, "transfer closed with %" FORMAT_OFF_T
1099 " bytes remaining to read",
1100 k->size - k->bytecount);
1101 return CURLE_PARTIAL_FILE;
1102 }
1103 else if(!(data->set.opt_no_body) &&
1104 k->chunk &&
1105 (conn->chunk.state != CHUNK_STOP)) {
1106 /*
1107 * In chunked mode, return an error if the connection is closed prior to
1108 * the empty (terminiating) chunk is read.
1109 *
1110 * The condition above used to check for
1111 * conn->proto.http->chunk.datasize != 0 which is true after reading
1112 * *any* chunk, not just the empty chunk.
1113 *
1114 */
1115 failf(data, "transfer closed with outstanding read data remaining");
1116 return CURLE_PARTIAL_FILE;
1117 }
1118 if(Curl_pgrsUpdate(conn))
1119 return CURLE_ABORTED_BY_CALLBACK;
1120 }
1121
1122 /* Now update the "done" boolean we return */
1123 *done = (bool)(0 == (k->keepon&(KEEP_RECV|KEEP_SEND|
1124 KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)));
1125
1126 return CURLE_OK;
1127}
1128
1129/*
1130 * Curl_single_getsock() gets called by the multi interface code when the app
1131 * has requested to get the sockets for the current connection. This function
1132 * will then be called once for every connection that the multi interface
1133 * keeps track of. This function will only be called for connections that are
1134 * in the proper state to have this information available.
1135 */
1136int Curl_single_getsock(const struct connectdata *conn,
1137 curl_socket_t *sock, /* points to numsocks number
1138 of sockets */
1139 int numsocks)
1140{
1141 const struct SessionHandle *data = conn->data;
1142 int bitmap = GETSOCK_BLANK;
1143 unsigned sockindex = 0;
1144
1145 if(conn->handler->perform_getsock)
1146 return conn->handler->perform_getsock(conn, sock, numsocks);
1147
1148 if(numsocks < 2)
1149 /* simple check but we might need two slots */
1150 return GETSOCK_BLANK;
1151
1152 /* don't include HOLD and PAUSE connections */
1153 if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) {
1154
1155 DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD);
1156
1157 bitmap |= GETSOCK_READSOCK(sockindex);
1158 sock[sockindex] = conn->sockfd;
1159 }
1160
1161 /* don't include HOLD and PAUSE connections */
1162 if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) {
1163
1164 if((conn->sockfd != conn->writesockfd) ||
1165 !(data->req.keepon & KEEP_RECV)) {
1166 /* only if they are not the same socket or we didn't have a readable
1167 one, we increase index */
1168 if(data->req.keepon & KEEP_RECV)
1169 sockindex++; /* increase index if we need two entries */
1170
1171 DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD);
1172
1173 sock[sockindex] = conn->writesockfd;
1174 }
1175
1176 bitmap |= GETSOCK_WRITESOCK(sockindex);
1177 }
1178
1179 return bitmap;
1180}
1181
1182/*
1183 * Determine optimum sleep time based on configured rate, current rate,
1184 * and packet size.
1185 * Returns value in mili-seconds.
1186 *
1187 * The basic idea is to adjust the desired rate up/down in this method
1188 * based on whether we are running too slow or too fast. Then, calculate
1189 * how many miliseconds to wait for the next packet to achieve this new
1190 * rate.
1191 */
1192long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
1193 int pkt_size)
1194{
1195 curl_off_t min_sleep = 0;
1196 curl_off_t rv = 0;
1197
1198 if (rate_bps == 0)
1199 return 0;
1200
1201 /* If running faster than about .1% of the desired speed, slow
1202 * us down a bit. Use shift instead of division as the 0.1%
1203 * cutoff is arbitrary anyway.
1204 */
1205 if (cur_rate_bps > (rate_bps + (rate_bps >> 10))) {
1206 /* running too fast, decrease target rate by 1/64th of rate */
1207 rate_bps -= rate_bps >> 6;
1208 min_sleep = 1;
1209 }
1210 else if (cur_rate_bps < (rate_bps - (rate_bps >> 10))) {
1211 /* running too slow, increase target rate by 1/64th of rate */
1212 rate_bps += rate_bps >> 6;
1213 }
1214
1215 /* Determine number of miliseconds to wait until we do
1216 * the next packet at the adjusted rate. We should wait
1217 * longer when using larger packets, for instance.
1218 */
1219 rv = ((curl_off_t)((pkt_size * 8) * 1000) / rate_bps);
1220
1221 /* Catch rounding errors and always slow down at least 1ms if
1222 * we are running too fast.
1223 */
1224 if (rv < min_sleep)
1225 rv = min_sleep;
1226
1227 /* Bound value to fit in 'long' on 32-bit platform. That's
1228 * plenty long enough anyway!
1229 */
1230 if(rv > 0x7fffffff)
1231 rv = 0x7fffffff;
1232
1233 return (long)rv;
1234}
1235
1236
1237/*
1238 * Transfer()
1239 *
1240 * This function is what performs the actual transfer. It is capable of doing
1241 * both ways simultaneously. The transfer must already have been setup by a
1242 * call to Curl_setup_transfer().
1243 *
1244 * Note that headers are created in a preallocated buffer of a default size.
1245 * That buffer can be enlarged on demand, but it is never shrunken again.
1246 *
1247 */
1248
1249static CURLcode
1250Transfer(struct connectdata *conn)
1251{
1252 CURLcode result;
1253 struct SessionHandle *data = conn->data;
1254 struct SingleRequest *k = &data->req;
1255 bool done=FALSE;
1256 bool first=TRUE;
1257 int timeout_ms;
1258 int buffersize;
1259 int totmp;
1260
1261 if((conn->sockfd == CURL_SOCKET_BAD) &&
1262 (conn->writesockfd == CURL_SOCKET_BAD))
1263 /* nothing to read, nothing to write, we're already OK! */
1264 return CURLE_OK;
1265
1266 /* we want header and/or body, if neither then don't do this! */
1267 if(!k->getheader && data->set.opt_no_body)
1268 return CURLE_OK;
1269
1270 while(!done) {
1271 curl_socket_t fd_read = conn->sockfd;
1272 curl_socket_t fd_write = conn->writesockfd;
1273 int keepon = k->keepon;
1274 timeout_ms = 1000;
1275
1276 if(conn->waitfor) {
1277 /* if waitfor is set, get the RECV and SEND bits from that but keep the
1278 other bits */
1279 keepon &= ~ (KEEP_RECV|KEEP_SEND);
1280 keepon |= conn->waitfor & (KEEP_RECV|KEEP_SEND);
1281 }
1282
1283 /* limit-rate logic: if speed exceeds threshold, then do not include fd in
1284 select set. The current speed is recalculated in each Curl_readwrite()
1285 call */
1286 if((keepon & KEEP_SEND) &&
1287 (!data->set.max_send_speed ||
1288 (data->progress.ulspeed < data->set.max_send_speed) )) {
1289 k->keepon &= ~KEEP_SEND_HOLD;
1290 }
1291 else {
1292 if (data->set.upload && data->set.max_send_speed &&
1293 (data->progress.ulspeed > data->set.max_send_speed) ) {
1294 /* calculate upload rate-limitation timeout. */
1295 buffersize = (int)(data->set.buffer_size ?
1296 data->set.buffer_size : BUFSIZE);
1297 totmp = (int)Curl_sleep_time(data->set.max_send_speed,
1298 data->progress.ulspeed, buffersize);
1299 if (totmp < timeout_ms)
1300 timeout_ms = totmp;
1301 }
1302 fd_write = CURL_SOCKET_BAD;
1303 if(keepon & KEEP_SEND)
1304 k->keepon |= KEEP_SEND_HOLD; /* hold it */
1305 }
1306
1307 if((keepon & KEEP_RECV) &&
1308 (!data->set.max_recv_speed ||
1309 (data->progress.dlspeed < data->set.max_recv_speed)) ) {
1310 k->keepon &= ~KEEP_RECV_HOLD;
1311 }
1312 else {
1313 if ((!data->set.upload) && data->set.max_recv_speed &&
1314 (data->progress.dlspeed > data->set.max_recv_speed)) {
1315 /* Calculate download rate-limitation timeout. */
1316 buffersize = (int)(data->set.buffer_size ?
1317 data->set.buffer_size : BUFSIZE);
1318 totmp = (int)Curl_sleep_time(data->set.max_recv_speed,
1319 data->progress.dlspeed, buffersize);
1320 if (totmp < timeout_ms)
1321 timeout_ms = totmp;
1322 }
1323 fd_read = CURL_SOCKET_BAD;
1324 if(keepon & KEEP_RECV)
1325 k->keepon |= KEEP_RECV_HOLD; /* hold it */
1326 }
1327
1328 /* pause logic. Don't check descriptors for paused connections */
1329 if(k->keepon & KEEP_RECV_PAUSE)
1330 fd_read = CURL_SOCKET_BAD;
1331 if(k->keepon & KEEP_SEND_PAUSE)
1332 fd_write = CURL_SOCKET_BAD;
1333
1334 /* The *_HOLD and *_PAUSE logic is necessary since even though there might
1335 be no traffic during the select interval, we still call
1336 Curl_readwrite() for the timeout case and if we limit transfer speed we
1337 must make sure that this function doesn't transfer anything while in
1338 HOLD status.
1339
1340 The no timeout for the first round is for the protocols for which data
1341 has already been slurped off the socket and thus waiting for action
1342 won't work since it'll wait even though there is already data present
1343 to work with. */
1344 if(first &&
1345 ((fd_read != CURL_SOCKET_BAD) || (fd_write != CURL_SOCKET_BAD)))
1346 /* if this is the first lap and one of the file descriptors is fine
1347 to work with, skip the timeout */
1348 timeout_ms = 0;
1349 else {
1350 totmp = Curl_timeleft(conn, &k->now, FALSE);
1351 if(totmp < 0)
1352 return CURLE_OPERATION_TIMEDOUT;
1353 else if(!totmp)
1354 totmp = 1000;
1355
1356 if (totmp < timeout_ms)
1357 timeout_ms = totmp;
1358 }
1359
1360 switch (Curl_socket_ready(fd_read, fd_write, timeout_ms)) {
1361 case -1: /* select() error, stop reading */
1362#ifdef EINTR
1363 /* The EINTR is not serious, and it seems you might get this more
1364 often when using the lib in a multi-threaded environment! */
1365 if(SOCKERRNO == EINTR)
1366 continue;
1367#endif
1368 return CURLE_RECV_ERROR; /* indicate a network problem */
1369 case 0: /* timeout */
1370 default: /* readable descriptors */
1371
1372 result = Curl_readwrite(conn, &done);
1373 /* "done" signals to us if the transfer(s) are ready */
1374 break;
1375 }
1376 if(result)
1377 return result;
1378
1379 first = FALSE; /* not the first lap anymore */
1380 }
1381
1382 return CURLE_OK;
1383}
1384
1385static void loadhostpairs(struct SessionHandle *data)
1386{
1387 struct curl_slist *hostp;
1388 char hostname[256];
1389 char address[256];
1390 int port;
1391
1392 for(hostp = data->change.resolve; hostp; hostp = hostp->next ) {
1393 if(!hostp->data)
1394 continue;
1395 if(hostp->data[0] == '-') {
1396 /* mark an entry for removal */
1397 }
1398 else if(3 == sscanf(hostp->data, "%255[^:]:%d:%255s", hostname, &port,
1399 address)) {
1400 struct Curl_dns_entry *dns;
1401 Curl_addrinfo *addr;
1402
1403 addr = Curl_str2addr(address, port);
1404 if(!addr) {
1405 infof(data, "Resolve %s found illegal!\n", hostp->data);
1406 continue;
1407 }
1408 infof(data, "Added %s:%d:%s to DNS cache\n",
1409 hostname, port, address);
1410
1411 if(data->share)
1412 Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
1413
1414 /* put this host in the cache */
1415 dns = Curl_cache_addr(data, addr, hostname, port);
1416
1417 if(data->share)
1418 Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
1419 }
1420 }
1421 data->change.resolve = NULL; /* dealt with now */
1422}
1423
1424
1425/*
1426 * Curl_pretransfer() is called immediately before a transfer starts.
1427 */
1428CURLcode Curl_pretransfer(struct SessionHandle *data)
1429{
1430 CURLcode res;
1431 if(!data->change.url) {
1432 /* we can't do anything without URL */
1433 failf(data, "No URL set!");
1434 return CURLE_URL_MALFORMAT;
1435 }
1436
1437 /* Init the SSL session ID cache here. We do it here since we want to do it
1438 after the *_setopt() calls (that could change the size of the cache) but
1439 before any transfer takes place. */
1440 res = Curl_ssl_initsessions(data, data->set.ssl.numsessions);
1441 if(res)
1442 return res;
1443
1444 data->set.followlocation=0; /* reset the location-follow counter */
1445 data->state.this_is_a_follow = FALSE; /* reset this */
1446 data->state.errorbuf = FALSE; /* no error has occurred */
1447 data->state.httpversion = 0; /* don't assume any particular server version */
1448
1449 data->state.ssl_connect_retry = FALSE;
1450
1451 data->state.authproblem = FALSE;
1452 data->state.authhost.want = data->set.httpauth;
1453 data->state.authproxy.want = data->set.proxyauth;
1454 Curl_safefree(data->info.wouldredirect);
1455 data->info.wouldredirect = NULL;
1456
1457 /* If there is a list of cookie files to read, do it now! */
1458 if(data->change.cookielist)
1459 Curl_cookie_loadfiles(data);
1460
1461 /* If there is a list of host pairs to deal with */
1462 if(data->change.resolve)
1463 loadhostpairs(data);
1464
1465 /* Allow data->set.use_port to set which port to use. This needs to be
1466 * disabled for example when we follow Location: headers to URLs using
1467 * different ports! */
1468 data->state.allow_port = TRUE;
1469
1470#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1471 /*************************************************************
1472 * Tell signal handler to ignore SIGPIPE
1473 *************************************************************/
1474 if(!data->set.no_signal)
1475 data->state.prev_signal = signal(SIGPIPE, SIG_IGN);
1476#endif
1477
1478 Curl_initinfo(data); /* reset session-specific information "variables" */
1479 Curl_pgrsStartNow(data);
1480
1481 if(data->set.timeout)
1482 Curl_expire(data, data->set.timeout);
1483
1484 if(data->set.connecttimeout)
1485 Curl_expire(data, data->set.connecttimeout);
1486
1487 return CURLE_OK;
1488}
1489
1490/*
1491 * Curl_posttransfer() is called immediately after a transfer ends
1492 */
1493CURLcode Curl_posttransfer(struct SessionHandle *data)
1494{
1495#if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL)
1496 /* restore the signal handler for SIGPIPE before we get back */
1497 if(!data->set.no_signal)
1498 signal(SIGPIPE, data->state.prev_signal);
1499#else
1500 (void)data; /* unused parameter */
1501#endif
1502
1503 if(!(data->progress.flags & PGRS_HIDE) &&
1504 !data->progress.callback)
1505 /* only output if we don't use a progress callback and we're not hidden */
1506 fprintf(data->set.err, "\n");
1507
1508 return CURLE_OK;
1509}
1510
1511#ifndef CURL_DISABLE_HTTP
1512/*
1513 * strlen_url() returns the length of the given URL if the spaces within the
1514 * URL were properly URL encoded.
1515 */
1516static size_t strlen_url(const char *url)
1517{
1518 const char *ptr;
1519 size_t newlen=0;
1520 bool left=TRUE; /* left side of the ? */
1521
1522 for(ptr=url; *ptr; ptr++) {
1523 switch(*ptr) {
1524 case '?':
1525 left=FALSE;
1526 /* fall through */
1527 default:
1528 newlen++;
1529 break;
1530 case ' ':
1531 if(left)
1532 newlen+=3;
1533 else
1534 newlen++;
1535 break;
1536 }
1537 }
1538 return newlen;
1539}
1540
1541/* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
1542 * the source URL accordingly.
1543 */
1544static void strcpy_url(char *output, const char *url)
1545{
1546 /* we must add this with whitespace-replacing */
1547 bool left=TRUE;
1548 const char *iptr;
1549 char *optr = output;
1550 for(iptr = url; /* read from here */
1551 *iptr; /* until zero byte */
1552 iptr++) {
1553 switch(*iptr) {
1554 case '?':
1555 left=FALSE;
1556 /* fall through */
1557 default:
1558 *optr++=*iptr;
1559 break;
1560 case ' ':
1561 if(left) {
1562 *optr++='%'; /* add a '%' */
1563 *optr++='2'; /* add a '2' */
1564 *optr++='0'; /* add a '0' */
1565 }
1566 else
1567 *optr++='+'; /* add a '+' here */
1568 break;
1569 }
1570 }
1571 *optr=0; /* zero terminate output buffer */
1572
1573}
1574
1575/*
1576 * Returns true if the given URL is absolute (as opposed to relative)
1577 */
1578static bool is_absolute_url(const char *url)
1579{
1580 char prot[16]; /* URL protocol string storage */
1581 char letter; /* used for a silly sscanf */
1582
1583 return (bool)(2 == sscanf(url, "%15[^?&/:]://%c", prot, &letter));
1584}
1585
1586/*
1587 * Concatenate a relative URL to a base URL making it absolute.
1588 * URL-encodes any spaces.
1589 * The returned pointer must be freed by the caller unless NULL
1590 * (returns NULL on out of memory).
1591 */
1592static char *concat_url(const char *base, const char *relurl)
1593{
1594 /***
1595 TRY to append this new path to the old URL
1596 to the right of the host part. Oh crap, this is doomed to cause
1597 problems in the future...
1598 */
1599 char *newest;
1600 char *protsep;
1601 char *pathsep;
1602 size_t newlen;
1603
1604 const char *useurl = relurl;
1605 size_t urllen;
1606
1607 /* we must make our own copy of the URL to play with, as it may
1608 point to read-only data */
1609 char *url_clone=strdup(base);
1610
1611 if(!url_clone)
1612 return NULL; /* skip out of this NOW */
1613
1614 /* protsep points to the start of the host name */
1615 protsep=strstr(url_clone, "//");
1616 if(!protsep)
1617 protsep=url_clone;
1618 else
1619 protsep+=2; /* pass the slashes */
1620
1621 if('/' != relurl[0]) {
1622 int level=0;
1623
1624 /* First we need to find out if there's a ?-letter in the URL,
1625 and cut it and the right-side of that off */
1626 pathsep = strchr(protsep, '?');
1627 if(pathsep)
1628 *pathsep=0;
1629
1630 /* we have a relative path to append to the last slash if there's one
1631 available, or if the new URL is just a query string (starts with a
1632 '?') we append the new one at the end of the entire currently worked
1633 out URL */
1634 if(useurl[0] != '?') {
1635 pathsep = strrchr(protsep, '/');
1636 if(pathsep)
1637 *pathsep=0;
1638 }
1639
1640 /* Check if there's any slash after the host name, and if so, remember
1641 that position instead */
1642 pathsep = strchr(protsep, '/');
1643 if(pathsep)
1644 protsep = pathsep+1;
1645 else
1646 protsep = NULL;
1647
1648 /* now deal with one "./" or any amount of "../" in the newurl
1649 and act accordingly */
1650
1651 if((useurl[0] == '.') && (useurl[1] == '/'))
1652 useurl+=2; /* just skip the "./" */
1653
1654 while((useurl[0] == '.') &&
1655 (useurl[1] == '.') &&
1656 (useurl[2] == '/')) {
1657 level++;
1658 useurl+=3; /* pass the "../" */
1659 }
1660
1661 if(protsep) {
1662 while(level--) {
1663 /* cut off one more level from the right of the original URL */
1664 pathsep = strrchr(protsep, '/');
1665 if(pathsep)
1666 *pathsep=0;
1667 else {
1668 *protsep=0;
1669 break;
1670 }
1671 }
1672 }
1673 }
1674 else {
1675 /* We got a new absolute path for this server, cut off from the
1676 first slash */
1677 pathsep = strchr(protsep, '/');
1678 if(pathsep) {
1679 /* When people use badly formatted URLs, such as
1680 "http://www.url.com?dir=/home/daniel" we must not use the first
1681 slash, if there's a ?-letter before it! */
1682 char *sep = strchr(protsep, '?');
1683 if(sep && (sep < pathsep))
1684 pathsep = sep;
1685 *pathsep=0;
1686 }
1687 else {
1688 /* There was no slash. Now, since we might be operating on a badly
1689 formatted URL, such as "http://www.url.com?id=2380" which doesn't
1690 use a slash separator as it is supposed to, we need to check for a
1691 ?-letter as well! */
1692 pathsep = strchr(protsep, '?');
1693 if(pathsep)
1694 *pathsep=0;
1695 }
1696 }
1697
1698 /* If the new part contains a space, this is a mighty stupid redirect
1699 but we still make an effort to do "right". To the left of a '?'
1700 letter we replace each space with %20 while it is replaced with '+'
1701 on the right side of the '?' letter.
1702 */
1703 newlen = strlen_url(useurl);
1704
1705 urllen = strlen(url_clone);
1706
1707 newest = malloc( urllen + 1 + /* possible slash */
1708 newlen + 1 /* zero byte */);
1709
1710 if(!newest) {
1711 free(url_clone); /* don't leak this */
1712 return NULL;
1713 }
1714
1715 /* copy over the root url part */
1716 memcpy(newest, url_clone, urllen);
1717
1718 /* check if we need to append a slash */
1719 if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
1720 ;
1721 else
1722 newest[urllen++]='/';
1723
1724 /* then append the new piece on the right side */
1725 strcpy_url(&newest[urllen], useurl);
1726
1727 free(url_clone);
1728
1729 return newest;
1730}
1731#endif /* CURL_DISABLE_HTTP */
1732
1733/*
1734 * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string
1735 * as given by the remote server and set up the new URL to request.
1736 */
1737CURLcode Curl_follow(struct SessionHandle *data,
1738 char *newurl, /* this 'newurl' is the Location: string,
1739 and it must be malloc()ed before passed
1740 here */
1741 followtype type) /* see transfer.h */
1742{
1743#ifdef CURL_DISABLE_HTTP
1744 (void)data;
1745 (void)newurl;
1746 (void)type;
1747 /* Location: following will not happen when HTTP is disabled */
1748 return CURLE_TOO_MANY_REDIRECTS;
1749#else
1750
1751 /* Location: redirect */
1752 bool disallowport = FALSE;
1753
1754 if(type == FOLLOW_REDIR) {
1755 if((data->set.maxredirs != -1) &&
1756 (data->set.followlocation >= data->set.maxredirs)) {
1757 failf(data,"Maximum (%ld) redirects followed", data->set.maxredirs);
1758 return CURLE_TOO_MANY_REDIRECTS;
1759 }
1760
1761 /* mark the next request as a followed location: */
1762 data->state.this_is_a_follow = TRUE;
1763
1764 data->set.followlocation++; /* count location-followers */
1765
1766 if(data->set.http_auto_referer) {
1767 /* We are asked to automatically set the previous URL as the referer
1768 when we get the next URL. We pick the ->url field, which may or may
1769 not be 100% correct */
1770
1771 if(data->change.referer_alloc)
1772 /* If we already have an allocated referer, free this first */
1773 free(data->change.referer);
1774
1775 data->change.referer = strdup(data->change.url);
1776 if (!data->change.referer) {
1777 data->change.referer_alloc = FALSE;
1778 return CURLE_OUT_OF_MEMORY;
1779 }
1780 data->change.referer_alloc = TRUE; /* yes, free this later */
1781 }
1782 }
1783
1784 if(!is_absolute_url(newurl)) {
1785 /***
1786 *DANG* this is an RFC 2068 violation. The URL is supposed
1787 to be absolute and this doesn't seem to be that!
1788 */
1789 char *absolute = concat_url(data->change.url, newurl);
1790 if (!absolute)
1791 return CURLE_OUT_OF_MEMORY;
1792 free(newurl);
1793 newurl = absolute;
1794 }
1795 else {
1796 /* This is an absolute URL, don't allow the custom port number */
1797 disallowport = TRUE;
1798
1799 if(strchr(newurl, ' ')) {
1800 /* This new URL contains at least one space, this is a mighty stupid
1801 redirect but we still make an effort to do "right". */
1802 char *newest;
1803 size_t newlen = strlen_url(newurl);
1804
1805 newest = malloc(newlen+1); /* get memory for this */
1806 if (!newest)
1807 return CURLE_OUT_OF_MEMORY;
1808 strcpy_url(newest, newurl); /* create a space-free URL */
1809
1810 free(newurl); /* that was no good */
1811 newurl = newest; /* use this instead now */
1812 }
1813
1814 }
1815
1816 if(type == FOLLOW_FAKE) {
1817 /* we're only figuring out the new url if we would've followed locations
1818 but now we're done so we can get out! */
1819 data->info.wouldredirect = newurl;
1820 return CURLE_OK;
1821 }
1822
1823 if(disallowport)
1824 data->state.allow_port = FALSE;
1825
1826 if(data->change.url_alloc)
1827 free(data->change.url);
1828 else
1829 data->change.url_alloc = TRUE; /* the URL is allocated */
1830
1831 data->change.url = newurl;
1832 newurl = NULL; /* don't free! */
1833
1834 infof(data, "Issue another request to this URL: '%s'\n", data->change.url);
1835
1836 /*
1837 * We get here when the HTTP code is 300-399 (and 401). We need to perform
1838 * differently based on exactly what return code there was.
1839 *
1840 * News from 7.10.6: we can also get here on a 401 or 407, in case we act on
1841 * a HTTP (proxy-) authentication scheme other than Basic.
1842 */
1843 switch(data->info.httpcode) {
1844 /* 401 - Act on a WWW-Authenticate, we keep on moving and do the
1845 Authorization: XXXX header in the HTTP request code snippet */
1846 /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the
1847 Proxy-Authorization: XXXX header in the HTTP request code snippet */
1848 /* 300 - Multiple Choices */
1849 /* 306 - Not used */
1850 /* 307 - Temporary Redirect */
1851 default: /* for all above (and the unknown ones) */
1852 /* Some codes are explicitly mentioned since I've checked RFC2616 and they
1853 * seem to be OK to POST to.
1854 */
1855 break;
1856 case 301: /* Moved Permanently */
1857 /* (quote from RFC2616, section 10.3.2):
1858 *
1859 * Note: When automatically redirecting a POST request after receiving a
1860 * 301 status code, some existing HTTP/1.0 user agents will erroneously
1861 * change it into a GET request.
1862 *
1863 * ----
1864 *
1865 * Warning: Because most of importants user agents do this obvious RFC2616
1866 * violation, many webservers expect this misbehavior. So these servers
1867 * often answers to a POST request with an error page. To be sure that
1868 * libcurl gets the page that most user agents would get, libcurl has to
1869 * force GET.
1870 *
1871 * This behaviour can be overridden with CURLOPT_POSTREDIR.
1872 */
1873 if( (data->set.httpreq == HTTPREQ_POST
1874 || data->set.httpreq == HTTPREQ_POST_FORM)
1875 && !data->set.post301) {
1876 infof(data,
1877 "Violate RFC 2616/10.3.2 and switch from POST to GET\n");
1878 data->set.httpreq = HTTPREQ_GET;
1879 }
1880 break;
1881 case 302: /* Found */
1882 /* (From 10.3.3)
1883
1884 Note: RFC 1945 and RFC 2068 specify that the client is not allowed
1885 to change the method on the redirected request. However, most
1886 existing user agent implementations treat 302 as if it were a 303
1887 response, performing a GET on the Location field-value regardless
1888 of the original request method. The status codes 303 and 307 have
1889 been added for servers that wish to make unambiguously clear which
1890 kind of reaction is expected of the client.
1891
1892 (From 10.3.4)
1893
1894 Note: Many pre-HTTP/1.1 user agents do not understand the 303
1895 status. When interoperability with such clients is a concern, the
1896 302 status code may be used instead, since most user agents react
1897 to a 302 response as described here for 303.
1898
1899 This behaviour can be overriden with CURLOPT_POSTREDIR
1900 */
1901 if( (data->set.httpreq == HTTPREQ_POST
1902 || data->set.httpreq == HTTPREQ_POST_FORM)
1903 && !data->set.post302) {
1904 infof(data,
1905 "Violate RFC 2616/10.3.3 and switch from POST to GET\n");
1906 data->set.httpreq = HTTPREQ_GET;
1907 }
1908 break;
1909
1910 case 303: /* See Other */
1911 /* Disable both types of POSTs, since doing a second POST when
1912 * following isn't what anyone would want! */
1913 if(data->set.httpreq != HTTPREQ_GET) {
1914 data->set.httpreq = HTTPREQ_GET; /* enforce GET request */
1915 infof(data, "Disables POST, goes with %s\n",
1916 data->set.opt_no_body?"HEAD":"GET");
1917 }
1918 break;
1919 case 304: /* Not Modified */
1920 /* 304 means we did a conditional request and it was "Not modified".
1921 * We shouldn't get any Location: header in this response!
1922 */
1923 break;
1924 case 305: /* Use Proxy */
1925 /* (quote from RFC2616, section 10.3.6):
1926 * "The requested resource MUST be accessed through the proxy given
1927 * by the Location field. The Location field gives the URI of the
1928 * proxy. The recipient is expected to repeat this single request
1929 * via the proxy. 305 responses MUST only be generated by origin
1930 * servers."
1931 */
1932 break;
1933 }
1934 Curl_pgrsTime(data, TIMER_REDIRECT);
1935 Curl_pgrsResetTimes(data);
1936
1937 return CURLE_OK;
1938#endif /* CURL_DISABLE_HTTP */
1939}
1940
1941static CURLcode
1942connect_host(struct SessionHandle *data,
1943 struct connectdata **conn)
1944{
1945 CURLcode res = CURLE_OK;
1946
1947 bool async;
1948 bool protocol_done=TRUE; /* will be TRUE always since this is only used
1949 within the easy interface */
1950 Curl_pgrsTime(data, TIMER_STARTSINGLE);
1951 res = Curl_connect(data, conn, &async, &protocol_done);
1952
1953 if((CURLE_OK == res) && async) {
1954 /* Now, if async is TRUE here, we need to wait for the name
1955 to resolve */
1956 res = Curl_wait_for_resolv(*conn, NULL);
1957 if(CURLE_OK == res)
1958 /* Resolved, continue with the connection */
1959 res = Curl_async_resolved(*conn, &protocol_done);
1960 else
1961 /* if we can't resolve, we kill this "connection" now */
1962 (void)Curl_disconnect(*conn, /* dead_connection */ FALSE);
1963 }
1964
1965 return res;
1966}
1967
1968CURLcode
1969Curl_reconnect_request(struct connectdata **connp)
1970{
1971 CURLcode result = CURLE_OK;
1972 struct connectdata *conn = *connp;
1973 struct SessionHandle *data = conn->data;
1974
1975 /* This was a re-use of a connection and we got a write error in the
1976 * DO-phase. Then we DISCONNECT this connection and have another attempt to
1977 * CONNECT and then DO again! The retry cannot possibly find another
1978 * connection to re-use, since we only keep one possible connection for
1979 * each. */
1980
1981 infof(data, "Re-used connection seems dead, get a new one\n");
1982
1983 conn->bits.close = TRUE; /* enforce close of this connection */
1984 result = Curl_done(&conn, result, FALSE); /* we are so done with this */
1985
1986 /* conn may no longer be a good pointer */
1987
1988 /*
1989 * According to bug report #1330310. We need to check for CURLE_SEND_ERROR
1990 * here as well. I figure this could happen when the request failed on a FTP
1991 * connection and thus Curl_done() itself tried to use the connection
1992 * (again). Slight Lack of feedback in the report, but I don't think this
1993 * extra check can do much harm.
1994 */
1995 if((CURLE_OK == result) || (CURLE_SEND_ERROR == result)) {
1996 bool async;
1997 bool protocol_done = TRUE;
1998
1999 /* Now, redo the connect and get a new connection */
2000 result = Curl_connect(data, connp, &async, &protocol_done);
2001 if(CURLE_OK == result) {
2002 /* We have connected or sent away a name resolve query fine */
2003
2004 conn = *connp; /* setup conn to again point to something nice */
2005 if(async) {
2006 /* Now, if async is TRUE here, we need to wait for the name
2007 to resolve */
2008 result = Curl_wait_for_resolv(conn, NULL);
2009 if(result)
2010 return result;
2011
2012 /* Resolved, continue with the connection */
2013 result = Curl_async_resolved(conn, &protocol_done);
2014 if(result)
2015 return result;
2016 }
2017 }
2018 }
2019
2020 return result;
2021}
2022
2023/* Returns CURLE_OK *and* sets '*url' if a request retry is wanted.
2024
2025 NOTE: that the *url is malloc()ed. */
2026CURLcode Curl_retry_request(struct connectdata *conn,
2027 char **url)
2028{
2029 struct SessionHandle *data = conn->data;
2030
2031 *url = NULL;
2032
2033 /* if we're talking upload, we can't do the checks below, unless the protocol
2034 is HTTP as when uploading over HTTP we will still get a response */
2035 if(data->set.upload && !(conn->protocol&(PROT_HTTP|PROT_RTSP)))
2036 return CURLE_OK;
2037
2038 if(/* workaround for broken TLS servers */ data->state.ssl_connect_retry ||
2039 ((data->req.bytecount +
2040 data->req.headerbytecount == 0) &&
2041 conn->bits.reuse &&
2042 !data->set.opt_no_body &&
2043 data->set.rtspreq != RTSPREQ_RECEIVE)) {
2044 /* We got no data, we attempted to re-use a connection and yet we want a
2045 "body". This might happen if the connection was left alive when we were
2046 done using it before, but that was closed when we wanted to read from
2047 it again. Bad luck. Retry the same request on a fresh connect! */
2048 infof(conn->data, "Connection died, retrying a fresh connect\n");
2049 *url = strdup(conn->data->change.url);
2050 if(!*url)
2051 return CURLE_OUT_OF_MEMORY;
2052
2053 conn->bits.close = TRUE; /* close this connection */
2054 conn->bits.retry = TRUE; /* mark this as a connection we're about
2055 to retry. Marking it this way should
2056 prevent i.e HTTP transfers to return
2057 error just because nothing has been
2058 transfered! */
2059 }
2060 return CURLE_OK;
2061}
2062
2063static CURLcode Curl_do_perform(struct SessionHandle *data)
2064{
2065 CURLcode res;
2066 CURLcode res2;
2067 struct connectdata *conn=NULL;
2068 char *newurl = NULL; /* possibly a new URL to follow to! */
2069 followtype follow = FOLLOW_NONE;
2070
2071 data->state.used_interface = Curl_if_easy;
2072
2073 res = Curl_pretransfer(data);
2074 if(res)
2075 return res;
2076
2077 /*
2078 * It is important that there is NO 'return' from this function at any other
2079 * place than falling down to the end of the function! This is because we
2080 * have cleanup stuff that must be done before we get back, and that is only
2081 * performed after this do-while loop.
2082 */
2083
2084 for(;;) {
2085 res = connect_host(data, &conn); /* primary connection */
2086
2087 if(res == CURLE_OK) {
2088 bool do_done;
2089 if(data->set.connect_only) {
2090 /* keep connection open for application to use the socket */
2091 conn->bits.close = FALSE;
2092 res = Curl_done(&conn, CURLE_OK, FALSE);
2093 break;
2094 }
2095 res = Curl_do(&conn, &do_done);
2096
2097 if(res == CURLE_OK) {
2098 if(conn->data->set.wildcardmatch) {
2099 if(conn->data->wildcard.state == CURLWC_DONE ||
2100 conn->data->wildcard.state == CURLWC_SKIP) {
2101 /* keep connection open for application to use the socket */
2102 conn->bits.close = FALSE;
2103 res = Curl_done(&conn, CURLE_OK, FALSE);
2104 break;
2105 }
2106 }
2107 res = Transfer(conn); /* now fetch that URL please */
2108 if((res == CURLE_OK) || (res == CURLE_RECV_ERROR)) {
2109 bool retry = FALSE;
2110 CURLcode rc = Curl_retry_request(conn, &newurl);
2111 if(rc)
2112 res = rc;
2113 else
2114 retry = (newurl?TRUE:FALSE);
2115
2116 if(retry) {
2117 /* we know (newurl != NULL) at this point */
2118 res = CURLE_OK;
2119 follow = FOLLOW_RETRY;
2120 }
2121 else if (res == CURLE_OK) {
2122 /*
2123 * We must duplicate the new URL here as the connection data may
2124 * be free()ed in the Curl_done() function. We prefer the newurl
2125 * one since that's used for redirects or just further requests
2126 * for retries or multi-stage HTTP auth methods etc.
2127 */
2128 if(data->req.newurl) {
2129 follow = FOLLOW_REDIR;
2130 newurl = strdup(data->req.newurl);
2131 if (!newurl)
2132 res = CURLE_OUT_OF_MEMORY;
2133 }
2134 else if(data->req.location) {
2135 follow = FOLLOW_FAKE;
2136 newurl = strdup(data->req.location);
2137 if (!newurl)
2138 res = CURLE_OUT_OF_MEMORY;
2139 }
2140 }
2141
2142 /* in the above cases where 'newurl' gets assigned, we have a fresh
2143 * allocated memory pointed to */
2144 }
2145 if(res != CURLE_OK) {
2146 /* The transfer phase returned error, we mark the connection to get
2147 * closed to prevent being re-used. This is because we can't
2148 * possibly know if the connection is in a good shape or not now. */
2149 conn->bits.close = TRUE;
2150
2151 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
2152 /* if we failed anywhere, we must clean up the secondary socket if
2153 it was used */
2154 sclose(conn->sock[SECONDARYSOCKET]);
2155 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
2156 }
2157 }
2158
2159 /* Always run Curl_done(), even if some of the previous calls
2160 failed, but return the previous (original) error code */
2161 res2 = Curl_done(&conn, res, FALSE);
2162
2163 if(CURLE_OK == res)
2164 res = res2;
2165 }
2166 else if(conn)
2167 /* Curl_do() failed, clean up left-overs in the done-call, but note
2168 that at some cases the conn pointer is NULL when Curl_do() failed
2169 and the connection cache is very small so only call Curl_done() if
2170 conn is still "alive". */
2171 /* ignore return code since we already have an error to return */
2172 (void)Curl_done(&conn, res, FALSE);
2173
2174 /*
2175 * Important: 'conn' cannot be used here, since it may have been closed
2176 * in 'Curl_done' or other functions.
2177 */
2178
2179 if((res == CURLE_OK) && follow) {
2180 res = Curl_follow(data, newurl, follow);
2181 if(CURLE_OK == res) {
2182 /* if things went fine, Curl_follow() freed or otherwise took
2183 responsibility for the newurl pointer */
2184 newurl = NULL;
2185 if(follow >= FOLLOW_RETRY) {
2186 follow = FOLLOW_NONE;
2187 continue;
2188 }
2189 /* else we break out of the loop below */
2190 }
2191 }
2192 }
2193 break; /* it only reaches here when this shouldn't loop */
2194
2195 } /* loop if Location: */
2196
2197 if(newurl)
2198 free(newurl);
2199
2200 if(res && !data->state.errorbuf) {
2201 /*
2202 * As an extra precaution: if no error string has been set and there was
2203 * an error, use the strerror() string or if things are so bad that not
2204 * even that is good, set a bad string that mentions the error code.
2205 */
2206 const char *str = curl_easy_strerror(res);
2207 if(!str)
2208 failf(data, "unspecified error %d", (int)res);
2209 else
2210 failf(data, "%s", str);
2211 }
2212
2213 /* run post-transfer unconditionally, but don't clobber the return code if
2214 we already have an error code recorder */
2215 res2 = Curl_posttransfer(data);
2216 if(!res && res2)
2217 res = res2;
2218
2219 return res;
2220}
2221
2222/*
2223 * Curl_perform() is the internal high-level function that gets called by the
2224 * external curl_easy_perform() function. It inits, performs and cleans up a
2225 * single file transfer.
2226 */
2227CURLcode Curl_perform(struct SessionHandle *data)
2228{
2229 CURLcode res;
2230 if(!data->set.wildcardmatch)
2231 return Curl_do_perform(data);
2232
2233 /* init main wildcard structures */
2234 res = Curl_wildcard_init(&data->wildcard);
2235 if(res)
2236 return res;
2237
2238 res = Curl_do_perform(data);
2239 if(res) {
2240 Curl_wildcard_dtor(&data->wildcard);
2241 return res;
2242 }
2243
2244 /* wildcard loop */
2245 while(!res && data->wildcard.state != CURLWC_DONE)
2246 res = Curl_do_perform(data);
2247
2248 Curl_wildcard_dtor(&data->wildcard);
2249
2250 /* wildcard download finished or failed */
2251 data->wildcard.state = CURLWC_INIT;
2252 return res;
2253}
2254
2255/*
2256 * Curl_setup_transfer() is called to setup some basic properties for the
2257 * upcoming transfer.
2258 */
2259void
2260Curl_setup_transfer(
2261 struct connectdata *conn, /* connection data */
2262 int sockindex, /* socket index to read from or -1 */
2263 curl_off_t size, /* -1 if unknown at this point */
2264 bool getheader, /* TRUE if header parsing is wanted */
2265 curl_off_t *bytecountp, /* return number of bytes read or NULL */
2266 int writesockindex, /* socket index to write to, it may very well be
2267 the same we read from. -1 disables */
2268 curl_off_t *writecountp /* return number of bytes written or NULL */
2269 )
2270{
2271 struct SessionHandle *data;
2272 struct SingleRequest *k;
2273
2274 DEBUGASSERT(conn != NULL);
2275
2276 data = conn->data;
2277 k = &data->req;
2278
2279 DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
2280
2281 /* now copy all input parameters */
2282 conn->sockfd = sockindex == -1 ?
2283 CURL_SOCKET_BAD : conn->sock[sockindex];
2284 conn->writesockfd = writesockindex == -1 ?
2285 CURL_SOCKET_BAD:conn->sock[writesockindex];
2286 k->getheader = getheader;
2287
2288 k->size = size;
2289 k->bytecountp = bytecountp;
2290 k->writebytecountp = writecountp;
2291
2292 /* The code sequence below is placed in this function just because all
2293 necessary input is not always known in do_complete() as this function may
2294 be called after that */
2295
2296 if(!k->getheader) {
2297 k->header = FALSE;
2298 if(size > 0)
2299 Curl_pgrsSetDownloadSize(data, size);
2300 }
2301 /* we want header and/or body, if neither then don't do this! */
2302 if(k->getheader || !data->set.opt_no_body) {
2303
2304 if(conn->sockfd != CURL_SOCKET_BAD)
2305 k->keepon |= KEEP_RECV;
2306
2307 if(conn->writesockfd != CURL_SOCKET_BAD) {
2308 /* HTTP 1.1 magic:
2309
2310 Even if we require a 100-return code before uploading data, we might
2311 need to write data before that since the REQUEST may not have been
2312 finished sent off just yet.
2313
2314 Thus, we must check if the request has been sent before we set the
2315 state info where we wait for the 100-return code
2316 */
2317 if((data->state.expect100header) &&
2318 (data->state.proto.http->sending == HTTPSEND_BODY)) {
2319 /* wait with write until we either got 100-continue or a timeout */
2320 k->exp100 = EXP100_AWAITING_CONTINUE;
2321 k->start100 = k->start;
2322
2323 /* set a timeout for the multi interface */
2324 Curl_expire(data, CURL_TIMEOUT_EXPECT_100);
2325 }
2326 else {
2327 if(data->state.expect100header)
2328 /* when we've sent off the rest of the headers, we must await a
2329 100-continue but first finish sending the request */
2330 k->exp100 = EXP100_SENDING_REQUEST;
2331
2332 /* enable the write bit when we're not waiting for continue */
2333 k->keepon |= KEEP_SEND;
2334 }
2335 } /* if(conn->writesockfd != CURL_SOCKET_BAD) */
2336 } /* if(k->getheader || !data->set.opt_no_body) */
2337
2338}