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