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