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