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