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