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