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