Git init
[external/curl.git] / lib / url.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 /* -- WIN32 approved -- */
24
25 #include "setup.h"
26
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 #ifdef WIN32
35 #include <time.h>
36 #include <io.h>
37 #else
38 #ifdef HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
40 #endif
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
43 #endif
44 #ifdef HAVE_SYS_TIME_H
45 #include <sys/time.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #ifdef HAVE_NETDB_H
51 #include <netdb.h>
52 #endif
53 #ifdef HAVE_ARPA_INET_H
54 #include <arpa/inet.h>
55 #endif
56 #ifdef HAVE_NET_IF_H
57 #include <net/if.h>
58 #endif
59 #ifdef HAVE_SYS_IOCTL_H
60 #include <sys/ioctl.h>
61 #endif
62
63 #ifdef HAVE_SYS_PARAM_H
64 #include <sys/param.h>
65 #endif
66
67 #ifdef __VMS
68 #include <in.h>
69 #include <inet.h>
70 #endif
71
72 #ifndef HAVE_SOCKET
73 #error "We can't compile without socket() support!"
74 #endif
75
76 #endif  /* WIN32 */
77
78 #ifdef HAVE_LIMITS_H
79 #include <limits.h>
80 #endif
81
82 #ifdef USE_LIBIDN
83 #include <idna.h>
84 #include <tld.h>
85 #include <stringprep.h>
86 #ifdef HAVE_IDN_FREE_H
87 #include <idn-free.h>
88 #else
89 void idn_free (void *ptr); /* prototype from idn-free.h, not provided by
90                               libidn 0.4.5's make install! */
91 #endif
92 #ifndef HAVE_IDN_FREE
93 /* if idn_free() was not found in this version of libidn, use plain free()
94    instead */
95 #define idn_free(x) (free)(x)
96 #endif
97 #endif  /* USE_LIBIDN */
98
99 #include "urldata.h"
100 #include "netrc.h"
101
102 #include "formdata.h"
103 #include "sslgen.h"
104 #include "hostip.h"
105 #include "transfer.h"
106 #include "sendf.h"
107 #include "progress.h"
108 #include "cookie.h"
109 #include "strequal.h"
110 #include "strerror.h"
111 #include "escape.h"
112 #include "strtok.h"
113 #include "share.h"
114 #include "content_encoding.h"
115 #include "http_digest.h"
116 #include "http_negotiate.h"
117 #include "select.h"
118 #include "multiif.h"
119 #include "easyif.h"
120 #include "speedcheck.h"
121 #include "rawstr.h"
122 #include "warnless.h"
123
124 /* And now for the protocols */
125 #include "ftp.h"
126 #include "dict.h"
127 #include "telnet.h"
128 #include "tftp.h"
129 #include "http.h"
130 #include "file.h"
131 #include "curl_ldap.h"
132 #include "ssh.h"
133 #include "imap.h"
134 #include "url.h"
135 #include "connect.h"
136 #include "inet_ntop.h"
137 #include "http_ntlm.h"
138 #include "socks.h"
139 #include "rtsp.h"
140 #include "curl_rtmp.h"
141 #include "gopher.h"
142
143 #define _MPRINTF_REPLACE /* use our functions only */
144 #include <curl/mprintf.h>
145
146 #include "curl_memory.h"
147 /* The last #include file should be: */
148 #include "memdebug.h"
149
150 /* Local static prototypes */
151 static long ConnectionKillOne(struct SessionHandle *data);
152 static void conn_free(struct connectdata *conn);
153 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
154
155 /*
156  * Protocol table.
157  */
158
159 static const struct Curl_handler * const protocols[] = {
160
161 #ifndef CURL_DISABLE_HTTP
162   &Curl_handler_http,
163 #endif
164
165 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
166   &Curl_handler_https,
167 #endif
168
169 #ifndef CURL_DISABLE_FTP
170   &Curl_handler_ftp,
171 #endif
172
173 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
174   &Curl_handler_ftps,
175 #endif
176
177 #ifndef CURL_DISABLE_TELNET
178   &Curl_handler_telnet,
179 #endif
180
181 #ifndef CURL_DISABLE_DICT
182   &Curl_handler_dict,
183 #endif
184
185 #ifndef CURL_DISABLE_LDAP
186   &Curl_handler_ldap,
187 #if (defined(USE_OPENLDAP) && defined(USE_SSL)) || \
188    (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))
189   &Curl_handler_ldaps,
190 #endif
191 #endif
192
193 #ifndef CURL_DISABLE_FILE
194   &Curl_handler_file,
195 #endif
196
197 #ifndef CURL_DISABLE_TFTP
198   &Curl_handler_tftp,
199 #endif
200
201 #ifdef USE_LIBSSH2
202   &Curl_handler_scp,
203   &Curl_handler_sftp,
204 #endif
205
206 #ifndef CURL_DISABLE_IMAP
207   &Curl_handler_imap,
208 #ifdef USE_SSL
209   &Curl_handler_imaps,
210 #endif
211 #endif
212
213 #ifndef CURL_DISABLE_POP3
214   &Curl_handler_pop3,
215 #ifdef USE_SSL
216   &Curl_handler_pop3s,
217 #endif
218 #endif
219
220 #ifndef CURL_DISABLE_SMTP
221   &Curl_handler_smtp,
222 #ifdef USE_SSL
223   &Curl_handler_smtps,
224 #endif
225 #endif
226
227 #ifndef CURL_DISABLE_RTSP
228   &Curl_handler_rtsp,
229 #endif
230
231 #ifndef CURL_DISABLE_GOPHER
232   &Curl_handler_gopher,
233 #endif
234
235 #ifdef USE_LIBRTMP
236   &Curl_handler_rtmp,
237   &Curl_handler_rtmpt,
238   &Curl_handler_rtmpe,
239   &Curl_handler_rtmpte,
240   &Curl_handler_rtmps,
241   &Curl_handler_rtmpts,
242 #endif
243
244   (struct Curl_handler *) NULL
245 };
246
247 /*
248  * Dummy handler for undefined protocol schemes.
249  */
250
251 static const struct Curl_handler Curl_handler_dummy = {
252   "<no protocol>",                      /* scheme */
253   ZERO_NULL,                            /* setup_connection */
254   ZERO_NULL,                            /* do_it */
255   ZERO_NULL,                            /* done */
256   ZERO_NULL,                            /* do_more */
257   ZERO_NULL,                            /* connect_it */
258   ZERO_NULL,                            /* connecting */
259   ZERO_NULL,                            /* doing */
260   ZERO_NULL,                            /* proto_getsock */
261   ZERO_NULL,                            /* doing_getsock */
262   ZERO_NULL,                            /* perform_getsock */
263   ZERO_NULL,                            /* disconnect */
264   0,                                    /* defport */
265   0                                     /* protocol */
266 };
267
268 void Curl_safefree(void *ptr)
269 {
270   if(ptr)
271     free(ptr);
272 }
273
274 static void close_connections(struct SessionHandle *data)
275 {
276   /* Loop through all open connections and kill them one by one */
277   long i;
278   do {
279     i = ConnectionKillOne(data);
280   } while(i != -1L);
281 }
282
283 void Curl_freeset(struct SessionHandle * data)
284 {
285   /* Free all dynamic strings stored in the data->set substructure. */
286   enum dupstring i;
287   for(i=(enum dupstring)0; i < STRING_LAST; i++)
288     Curl_safefree(data->set.str[i]);
289 }
290
291 static CURLcode setstropt(char **charp, char * s)
292 {
293   /* Release the previous storage at `charp' and replace by a dynamic storage
294      copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
295
296   if(*charp) {
297     free(*charp);
298     *charp = (char *) NULL;
299   }
300
301   if(s) {
302     s = strdup(s);
303
304     if(!s)
305       return CURLE_OUT_OF_MEMORY;
306
307     *charp = s;
308   }
309
310   return CURLE_OK;
311 }
312
313 static CURLcode setstropt_userpwd(char *option, char **user_storage,
314                                   char **pwd_storage)
315 {
316   char* separator;
317   CURLcode result = CURLE_OK;
318
319   if(!option) {
320     /* we treat a NULL passed in as a hint to clear existing info */
321     Curl_safefree(*user_storage);
322     *user_storage = (char *) NULL;
323     Curl_safefree(*pwd_storage);
324     *pwd_storage = (char *) NULL;
325     return CURLE_OK;
326   }
327
328   separator = strchr(option, ':');
329   if (separator != NULL) {
330
331     /* store username part of option */
332     char * p;
333     size_t username_len = (size_t)(separator-option);
334     p = malloc(username_len+1);
335     if(!p)
336       result = CURLE_OUT_OF_MEMORY;
337     else {
338       memcpy(p, option, username_len);
339       p[username_len] = '\0';
340       Curl_safefree(*user_storage);
341       *user_storage = p;
342     }
343
344     /* store password part of option */
345     if (result == CURLE_OK) {
346       result = setstropt(pwd_storage, separator+1);
347     }
348   }
349   else {
350     result = setstropt(user_storage, option);
351   }
352   return result;
353 }
354
355 CURLcode Curl_dupset(struct SessionHandle * dst, struct SessionHandle * src)
356 {
357   CURLcode r = CURLE_OK;
358   enum dupstring i;
359
360   /* Copy src->set into dst->set first, then deal with the strings
361      afterwards */
362   dst->set = src->set;
363
364   /* clear all string pointers first */
365   memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
366
367   /* duplicate all strings */
368   for(i=(enum dupstring)0; i< STRING_LAST; i++) {
369     r = setstropt(&dst->set.str[i], src->set.str[i]);
370     if(r != CURLE_OK)
371       break;
372   }
373
374   /* If a failure occurred, freeing has to be performed externally. */
375   return r;
376 }
377
378 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
379 static void flush_cookies(struct SessionHandle *data, int cleanup)
380 {
381   if(data->set.str[STRING_COOKIEJAR]) {
382     if(data->change.cookielist) {
383       /* If there is a list of cookie files to read, do it first so that
384          we have all the told files read before we write the new jar.
385          Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
386       Curl_cookie_loadfiles(data);
387     }
388
389     Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
390
391     /* if we have a destination file for all the cookies to get dumped to */
392     if(Curl_cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR]))
393       infof(data, "WARNING: failed to save cookies in %s\n",
394             data->set.str[STRING_COOKIEJAR]);
395   }
396   else {
397     if(cleanup && data->change.cookielist)
398       /* since nothing is written, we can just free the list of cookie file
399          names */
400       curl_slist_free_all(data->change.cookielist); /* clean up list */
401     Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
402   }
403
404   if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
405     Curl_cookie_cleanup(data->cookies);
406   }
407   Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
408 }
409 #endif
410
411 /*
412  * This is the internal function curl_easy_cleanup() calls. This should
413  * cleanup and free all resources associated with this sessionhandle.
414  *
415  * NOTE: if we ever add something that attempts to write to a socket or
416  * similar here, we must ignore SIGPIPE first. It is currently only done
417  * when curl_easy_perform() is invoked.
418  */
419
420 CURLcode Curl_close(struct SessionHandle *data)
421 {
422   struct Curl_multi *m = data->multi;
423
424 #ifdef DEBUGBUILD
425   /* only for debugging, scan through all connections and see if there's a
426      pipe reference still identifying this handle */
427
428   if(data->state.connc && data->state.connc->type == CONNCACHE_MULTI) {
429     struct conncache *c = data->state.connc;
430     long i;
431     struct curl_llist *pipeline;
432     struct curl_llist_element *curr;
433     struct connectdata *connptr;
434
435     for(i=0; i< c->num; i++) {
436       connptr = c->connects[i];
437       if(!connptr)
438         continue;
439
440       pipeline = connptr->send_pipe;
441       if(pipeline) {
442         for (curr = pipeline->head; curr; curr=curr->next) {
443           if(data == (struct SessionHandle *) curr->ptr) {
444             fprintf(stderr,
445                     "problem we %p are still in send pipe for %p done %d\n",
446                     data, connptr, (int)connptr->bits.done);
447           }
448         }
449       }
450       pipeline = connptr->recv_pipe;
451       if(pipeline) {
452         for (curr = pipeline->head; curr; curr=curr->next) {
453           if(data == (struct SessionHandle *) curr->ptr) {
454             fprintf(stderr,
455                     "problem we %p are still in recv pipe for %p done %d\n",
456                     data, connptr, (int)connptr->bits.done);
457           }
458         }
459       }
460       pipeline = connptr->done_pipe;
461       if(pipeline) {
462         for (curr = pipeline->head; curr; curr=curr->next) {
463           if(data == (struct SessionHandle *) curr->ptr) {
464             fprintf(stderr,
465                     "problem we %p are still in done pipe for %p done %d\n",
466                     data, connptr, (int)connptr->bits.done);
467           }
468         }
469       }
470       pipeline = connptr->pend_pipe;
471       if(pipeline) {
472         for (curr = pipeline->head; curr; curr=curr->next) {
473           if(data == (struct SessionHandle *) curr->ptr) {
474             fprintf(stderr,
475                     "problem we %p are still in pend pipe for %p done %d\n",
476                     data, connptr, (int)connptr->bits.done);
477           }
478         }
479       }
480     }
481   }
482 #endif
483
484   Curl_expire(data, 0); /* shut off timers */
485
486   if(m)
487     /* This handle is still part of a multi handle, take care of this first
488        and detach this handle from there. */
489     curl_multi_remove_handle(data->multi, data);
490
491   /* Destroy the timeout list that is held in the easy handle. It is
492      /normally/ done by curl_multi_remove_handle() but this is "just in
493      case" */
494   if(data->state.timeoutlist) {
495     Curl_llist_destroy(data->state.timeoutlist, NULL);
496     data->state.timeoutlist = NULL;
497   }
498
499   data->magic = 0; /* force a clear AFTER the possibly enforced removal from
500                       the multi handle, since that function uses the magic
501                       field! */
502
503   if(data->state.connc) {
504
505     if(data->state.connc->type == CONNCACHE_PRIVATE) {
506       /* close all connections still alive that are in the private connection
507          cache, as we no longer have the pointer left to the shared one. */
508       close_connections(data);
509
510       /* free the connection cache if allocated privately */
511       Curl_rm_connc(data->state.connc);
512     }
513   }
514
515   if(data->state.shared_conn) {
516     /* marked to be used by a pending connection so we can't kill this handle
517        just yet */
518     data->state.closed = TRUE;
519     return CURLE_OK;
520   }
521
522   if(data->dns.hostcachetype == HCACHE_PRIVATE) {
523     Curl_hash_destroy(data->dns.hostcache);
524     data->dns.hostcachetype = HCACHE_NONE;
525     data->dns.hostcache = NULL;
526   }
527
528   if(data->state.rangestringalloc)
529     free(data->state.range);
530
531   /* Free the pathbuffer */
532   Curl_safefree(data->state.pathbuffer);
533   Curl_safefree(data->state.proto.generic);
534
535   /* Close down all open SSL info and sessions */
536   Curl_ssl_close_all(data);
537   Curl_safefree(data->state.first_host);
538   Curl_safefree(data->state.scratch);
539   Curl_ssl_free_certinfo(data);
540
541   if(data->change.referer_alloc)
542     free(data->change.referer);
543
544   if(data->change.url_alloc)
545     free(data->change.url);
546
547   Curl_safefree(data->state.headerbuff);
548
549 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
550   flush_cookies(data, 1);
551 #endif
552
553   Curl_digest_cleanup(data);
554
555   Curl_safefree(data->info.contenttype);
556   Curl_safefree(data->info.wouldredirect);
557
558   /* this destroys the channel and we cannot use it anymore after this */
559   ares_destroy(data->state.areschannel);
560
561 #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
562   /* close iconv conversion descriptors */
563   if(data->inbound_cd != (iconv_t)-1) {
564      iconv_close(data->inbound_cd);
565   }
566   if(data->outbound_cd != (iconv_t)-1) {
567      iconv_close(data->outbound_cd);
568   }
569   if(data->utf8_cd != (iconv_t)-1) {
570      iconv_close(data->utf8_cd);
571   }
572 #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
573
574   /* No longer a dirty share, if it exists */
575   if(data->share) {
576     Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
577     data->share->dirty--;
578     Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
579   }
580
581   Curl_freeset(data);
582   free(data);
583   return CURLE_OK;
584 }
585
586 /* create a connection cache of a private or multi type */
587 struct conncache *Curl_mk_connc(int type,
588                                 long amount) /* set -1 to use default */
589 {
590   /* It is subject for debate how many default connections to have for a multi
591      connection cache... */
592
593   struct conncache *c;
594   long default_amount;
595   long max_amount = (long)(((size_t)INT_MAX) / sizeof(struct connectdata *));
596
597   if(type == CONNCACHE_PRIVATE) {
598     default_amount = (amount < 1L) ? 5L : amount;
599   }
600   else {
601     default_amount = (amount < 1L) ? 10L : amount;
602   }
603
604   if(default_amount > max_amount)
605     default_amount = max_amount;
606
607   c = calloc(1, sizeof(struct conncache));
608   if(!c)
609     return NULL;
610
611   c->connects = calloc((size_t)default_amount, sizeof(struct connectdata *));
612   if(!c->connects) {
613     free(c);
614     return NULL;
615   }
616
617   c->num = default_amount;
618
619   return c;
620 }
621
622 /* Change number of entries of a connection cache */
623 CURLcode Curl_ch_connc(struct SessionHandle *data,
624                        struct conncache *c,
625                        long newamount)
626 {
627   long i;
628   struct connectdata **newptr;
629   long max_amount = (long)(((size_t)INT_MAX) / sizeof(struct connectdata *));
630
631   if(newamount < 1)
632     newamount = 1; /* we better have at least one entry */
633
634   if(!c) {
635     /* we get a NULL pointer passed in as connection cache, which means that
636        there is no cache created for this SessionHandle just yet, we create a
637        brand new with the requested size.
638     */
639     data->state.connc = Curl_mk_connc(CONNCACHE_PRIVATE, newamount);
640     if(!data->state.connc)
641       return CURLE_OUT_OF_MEMORY;
642     return CURLE_OK;
643   }
644
645   if(newamount < c->num) {
646     /* Since this number is *decreased* from the existing number, we must
647        close the possibly open connections that live on the indexes that
648        are being removed!
649
650        NOTE: for conncache_multi cases we must make sure that we only
651        close handles not in use.
652     */
653     for(i=newamount; i< c->num; i++)
654       Curl_disconnect(c->connects[i], /* dead_connection */ FALSE);
655
656     /* If the most recent connection is no longer valid, mark it
657        invalid. */
658     if(data->state.lastconnect <= newamount)
659       data->state.lastconnect = -1;
660   }
661   if(newamount > 0) {
662     if(newamount > max_amount)
663       newamount = max_amount;
664     newptr = realloc(c->connects, sizeof(struct connectdata *) * newamount);
665     if(!newptr)
666       /* we closed a few connections in vain, but so what? */
667       return CURLE_OUT_OF_MEMORY;
668
669     /* nullify the newly added pointers */
670     for(i=c->num; i<newamount; i++)
671       newptr[i] = NULL;
672
673     c->connects = newptr;
674     c->num = newamount;
675   }
676   /* we no longer support less than 1 as size for the connection cache, and
677      I'm not sure it ever worked to set it to zero */
678   return CURLE_OK;
679 }
680
681 /* Free a connection cache. This is called from Curl_close() and
682    curl_multi_cleanup(). */
683 void Curl_rm_connc(struct conncache *c)
684 {
685   if(c->connects) {
686     long i;
687     for(i = 0; i < c->num; ++i)
688       conn_free(c->connects[i]);
689
690     free(c->connects);
691   }
692
693   free(c);
694 }
695
696 /*
697  * Initialize the UserDefined fields within a SessionHandle.
698  * This may be safely called on a new or existing SessionHandle.
699  */
700 CURLcode Curl_init_userdefined(struct UserDefined *set)
701 {
702   CURLcode res = CURLE_OK;
703
704   set->out = stdout; /* default output to stdout */
705   set->in  = stdin;  /* default input from stdin */
706   set->err  = stderr;  /* default stderr to stderr */
707
708   /* use fwrite as default function to store output */
709   set->fwrite_func = (curl_write_callback)fwrite;
710
711   /* use fread as default function to read input */
712   set->fread_func = (curl_read_callback)fread;
713   set->is_fread_set = 0;
714   set->is_fwrite_set = 0;
715
716   set->seek_func = ZERO_NULL;
717   set->seek_client = ZERO_NULL;
718
719   /* conversion callbacks for non-ASCII hosts */
720   set->convfromnetwork = ZERO_NULL;
721   set->convtonetwork   = ZERO_NULL;
722   set->convfromutf8    = ZERO_NULL;
723
724   set->infilesize = -1;      /* we don't know any size */
725   set->postfieldsize = -1;   /* unknown size */
726   set->maxredirs = -1;       /* allow any amount by default */
727
728   set->httpreq = HTTPREQ_GET; /* Default HTTP request */
729   set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
730   set->ftp_use_epsv = TRUE;   /* FTP defaults to EPSV operations */
731   set->ftp_use_eprt = TRUE;   /* FTP defaults to EPRT operations */
732   set->ftp_use_pret = FALSE;  /* mainly useful for drftpd servers */
733   set->ftp_filemethod = FTPFILE_MULTICWD;
734
735   set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
736
737   /* Set the default size of the SSL session ID cache */
738   set->ssl.numsessions = 5;
739
740   set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
741   set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
742   set->httpauth = CURLAUTH_BASIC;  /* defaults to basic */
743   set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
744
745   /* make libcurl quiet by default: */
746   set->hide_progress = TRUE;  /* CURLOPT_NOPROGRESS changes these */
747
748   /*
749    * libcurl 7.10 introduced SSL verification *by default*! This needs to be
750    * switched off unless wanted.
751    */
752   set->ssl.verifypeer = TRUE;
753   set->ssl.verifyhost = 2;
754   set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
755                                                       type */
756   set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
757
758   set->new_file_perms = 0644;    /* Default permissions */
759   set->new_directory_perms = 0755; /* Default permissions */
760
761   /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
762      define since we internally only use the lower 16 bits for the passed
763      in bitmask to not conflict with the private bits */
764   set->allowed_protocols = PROT_EXTMASK;
765   set->redir_protocols =
766     PROT_EXTMASK & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
767
768 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
769   /*
770    * disallow unprotected protection negotiation NEC reference implementation
771    * seem not to follow rfc1961 section 4.3/4.4
772    */
773   set->socks5_gssapi_nec = FALSE;
774   /* set default gssapi service name */
775   res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
776                   (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
777   if (res != CURLE_OK)
778     return res;
779 #endif
780
781   /* This is our preferred CA cert bundle/path since install time */
782 #if defined(CURL_CA_BUNDLE)
783   res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
784 #elif defined(CURL_CA_PATH)
785   res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
786 #endif
787
788   set->wildcardmatch  = FALSE;
789   set->chunk_bgn      = ZERO_NULL;
790   set->chunk_end      = ZERO_NULL;
791
792   return res;
793 }
794
795 /**
796  * Curl_open()
797  *
798  * @param curl is a pointer to a sessionhandle pointer that gets set by this
799  * function.
800  * @return CURLcode
801  */
802
803 CURLcode Curl_open(struct SessionHandle **curl)
804 {
805   CURLcode res = CURLE_OK;
806   struct SessionHandle *data;
807 #ifdef USE_ARES
808   int status;
809 #endif
810
811   /* Very simple start-up: alloc the struct, init it with zeroes and return */
812   data = calloc(1, sizeof(struct SessionHandle));
813   if(!data) {
814     /* this is a very serious error */
815     DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
816     return CURLE_OUT_OF_MEMORY;
817   }
818
819   data->magic = CURLEASY_MAGIC_NUMBER;
820
821 #ifdef USE_ARES
822   if((status = ares_init(&data->state.areschannel)) != ARES_SUCCESS) {
823     DEBUGF(fprintf(stderr, "Error: ares_init failed\n"));
824     free(data);
825     if(status == ARES_ENOMEM)
826       return CURLE_OUT_OF_MEMORY;
827     else
828       return CURLE_FAILED_INIT;
829   }
830   /* make sure that all other returns from this function should destroy the
831      ares channel before returning error! */
832 #endif
833
834   /* We do some initial setup here, all those fields that can't be just 0 */
835
836   data->state.headerbuff = malloc(HEADERSIZE);
837   if(!data->state.headerbuff) {
838     DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
839     res = CURLE_OUT_OF_MEMORY;
840   }
841   else {
842     Curl_easy_initHandleData(data);
843     res = Curl_init_userdefined(&data->set);
844
845     data->state.headersize=HEADERSIZE;
846
847 #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
848     /* conversion descriptors for iconv calls */
849     data->outbound_cd = (iconv_t)-1;
850     data->inbound_cd  = (iconv_t)-1;
851     data->utf8_cd     = (iconv_t)-1;
852 #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
853
854     /* most recent connection is not yet defined */
855     data->state.lastconnect = -1;
856
857     data->progress.flags |= PGRS_HIDE;
858     data->state.current_speed = -1; /* init to negative == impossible */
859
860     data->wildcard.state = CURLWC_INIT;
861     data->wildcard.filelist = NULL;
862     data->set.fnmatch = ZERO_NULL;
863     /* This no longer creates a connection cache here. It is instead made on
864        the first call to curl_easy_perform() or when the handle is added to a
865        multi stack. */
866   }
867
868   if(res) {
869     ares_destroy(data->state.areschannel);
870     if(data->state.headerbuff)
871       free(data->state.headerbuff);
872     Curl_freeset(data);
873     free(data);
874     data = NULL;
875   }
876   else
877     *curl = data;
878
879   return res;
880 }
881
882 CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
883                      va_list param)
884 {
885   char *argptr;
886   CURLcode result = CURLE_OK;
887 #ifndef CURL_DISABLE_HTTP
888   curl_off_t bigsize;
889 #endif
890
891   switch(option) {
892   case CURLOPT_DNS_CACHE_TIMEOUT:
893     data->set.dns_cache_timeout = va_arg(param, long);
894     break;
895   case CURLOPT_DNS_USE_GLOBAL_CACHE:
896   {
897     /* remember we want this enabled */
898     long use_cache = va_arg(param, long);
899     data->set.global_dns_cache = (bool)(0 != use_cache);
900   }
901   break;
902   case CURLOPT_SSL_CIPHER_LIST:
903     /* set a list of cipher we want to use in the SSL connection */
904     result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
905                        va_arg(param, char *));
906     break;
907
908   case CURLOPT_RANDOM_FILE:
909     /*
910      * This is the path name to a file that contains random data to seed
911      * the random SSL stuff with. The file is only used for reading.
912      */
913     result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
914                        va_arg(param, char *));
915     break;
916   case CURLOPT_EGDSOCKET:
917     /*
918      * The Entropy Gathering Daemon socket pathname
919      */
920     result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
921                        va_arg(param, char *));
922     break;
923   case CURLOPT_MAXCONNECTS:
924     /*
925      * Set the absolute number of maximum simultaneous alive connection that
926      * libcurl is allowed to have.
927      */
928     result = Curl_ch_connc(data, data->state.connc, va_arg(param, long));
929     break;
930   case CURLOPT_FORBID_REUSE:
931     /*
932      * When this transfer is done, it must not be left to be reused by a
933      * subsequent transfer but shall be closed immediately.
934      */
935     data->set.reuse_forbid = (bool)(0 != va_arg(param, long));
936     break;
937   case CURLOPT_FRESH_CONNECT:
938     /*
939      * This transfer shall not use a previously cached connection but
940      * should be made with a fresh new connect!
941      */
942     data->set.reuse_fresh = (bool)(0 != va_arg(param, long));
943     break;
944   case CURLOPT_VERBOSE:
945     /*
946      * Verbose means infof() calls that give a lot of information about
947      * the connection and transfer procedures as well as internal choices.
948      */
949     data->set.verbose = (bool)(0 != va_arg(param, long));
950     break;
951   case CURLOPT_HEADER:
952     /*
953      * Set to include the header in the general data output stream.
954      */
955     data->set.include_header = (bool)(0 != va_arg(param, long));
956     break;
957   case CURLOPT_NOPROGRESS:
958     /*
959      * Shut off the internal supported progress meter
960      */
961     data->set.hide_progress = (bool)(0 != va_arg(param, long));
962     if(data->set.hide_progress)
963       data->progress.flags |= PGRS_HIDE;
964     else
965       data->progress.flags &= ~PGRS_HIDE;
966     break;
967   case CURLOPT_NOBODY:
968     /*
969      * Do not include the body part in the output data stream.
970      */
971     data->set.opt_no_body = (bool)(0 != va_arg(param, long));
972     break;
973   case CURLOPT_FAILONERROR:
974     /*
975      * Don't output the >=300 error code HTML-page, but instead only
976      * return error.
977      */
978     data->set.http_fail_on_error = (bool)(0 != va_arg(param, long));
979     break;
980   case CURLOPT_UPLOAD:
981   case CURLOPT_PUT:
982     /*
983      * We want to sent data to the remote host. If this is HTTP, that equals
984      * using the PUT request.
985      */
986     data->set.upload = (bool)(0 != va_arg(param, long));
987     if(data->set.upload) {
988       /* If this is HTTP, PUT is what's needed to "upload" */
989       data->set.httpreq = HTTPREQ_PUT;
990       data->set.opt_no_body = FALSE; /* this is implied */
991     }
992     else
993       /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
994          then this can be changed to HEAD later on) */
995       data->set.httpreq = HTTPREQ_GET;
996     break;
997   case CURLOPT_FILETIME:
998     /*
999      * Try to get the file time of the remote document. The time will
1000      * later (possibly) become available using curl_easy_getinfo().
1001      */
1002     data->set.get_filetime = (bool)(0 != va_arg(param, long));
1003     break;
1004   case CURLOPT_FTP_CREATE_MISSING_DIRS:
1005     /*
1006      * An FTP option that modifies an upload to create missing directories on
1007      * the server.
1008      */
1009     switch(va_arg(param, long)) {
1010     case 0:
1011       data->set.ftp_create_missing_dirs = 0;
1012       break;
1013     case 1:
1014       data->set.ftp_create_missing_dirs = 1;
1015       break;
1016     case 2:
1017       data->set.ftp_create_missing_dirs = 2;
1018       break;
1019     default:
1020       /* reserve other values for future use */
1021       result = CURLE_FAILED_INIT;
1022       break;
1023     }
1024     break;
1025   case CURLOPT_SERVER_RESPONSE_TIMEOUT:
1026     /*
1027      * Option that specifies how quickly an server response must be obtained
1028      * before it is considered failure. For pingpong protocols.
1029      */
1030     data->set.server_response_timeout = va_arg( param , long ) * 1000;
1031     break;
1032   case CURLOPT_TFTP_BLKSIZE:
1033     /*
1034      * TFTP option that specifies the block size to use for data transmission
1035      */
1036     data->set.tftp_blksize = va_arg(param, long);
1037     break;
1038   case CURLOPT_DIRLISTONLY:
1039     /*
1040      * An option that changes the command to one that asks for a list
1041      * only, no file info details.
1042      */
1043     data->set.ftp_list_only = (bool)(0 != va_arg(param, long));
1044     break;
1045   case CURLOPT_APPEND:
1046     /*
1047      * We want to upload and append to an existing file.
1048      */
1049     data->set.ftp_append = (bool)(0 != va_arg(param, long));
1050     break;
1051   case CURLOPT_FTP_FILEMETHOD:
1052     /*
1053      * How do access files over FTP.
1054      */
1055     data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
1056     break;
1057   case CURLOPT_NETRC:
1058     /*
1059      * Parse the $HOME/.netrc file
1060      */
1061     data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
1062     break;
1063   case CURLOPT_NETRC_FILE:
1064     /*
1065      * Use this file instead of the $HOME/.netrc file
1066      */
1067     result = setstropt(&data->set.str[STRING_NETRC_FILE],
1068                        va_arg(param, char *));
1069     break;
1070   case CURLOPT_TRANSFERTEXT:
1071     /*
1072      * This option was previously named 'FTPASCII'. Renamed to work with
1073      * more protocols than merely FTP.
1074      *
1075      * Transfer using ASCII (instead of BINARY).
1076      */
1077     data->set.prefer_ascii = (bool)(0 != va_arg(param, long));
1078     break;
1079   case CURLOPT_TIMECONDITION:
1080     /*
1081      * Set HTTP time condition. This must be one of the defines in the
1082      * curl/curl.h header file.
1083      */
1084     data->set.timecondition = (curl_TimeCond)va_arg(param, long);
1085     break;
1086   case CURLOPT_TIMEVALUE:
1087     /*
1088      * This is the value to compare with the remote document with the
1089      * method set with CURLOPT_TIMECONDITION
1090      */
1091     data->set.timevalue = (time_t)va_arg(param, long);
1092     break;
1093   case CURLOPT_SSLVERSION:
1094     /*
1095      * Set explicit SSL version to try to connect with, as some SSL
1096      * implementations are lame.
1097      */
1098     data->set.ssl.version = va_arg(param, long);
1099     break;
1100
1101 #ifndef CURL_DISABLE_HTTP
1102   case CURLOPT_AUTOREFERER:
1103     /*
1104      * Switch on automatic referer that gets set if curl follows locations.
1105      */
1106     data->set.http_auto_referer = (bool)(0 != va_arg(param, long));
1107     break;
1108
1109   case CURLOPT_ENCODING:
1110     /*
1111      * String to use at the value of Accept-Encoding header.
1112      *
1113      * If the encoding is set to "" we use an Accept-Encoding header that
1114      * encompasses all the encodings we support.
1115      * If the encoding is set to NULL we don't send an Accept-Encoding header
1116      * and ignore an received Content-Encoding header.
1117      *
1118      */
1119     argptr = va_arg(param, char *);
1120     result = setstropt(&data->set.str[STRING_ENCODING],
1121                        (argptr && !*argptr)?
1122                        (char *) ALL_CONTENT_ENCODINGS: argptr);
1123     break;
1124
1125   case CURLOPT_FOLLOWLOCATION:
1126     /*
1127      * Follow Location: header hints on a HTTP-server.
1128      */
1129     data->set.http_follow_location = (bool)(0 != va_arg(param, long));
1130     break;
1131
1132   case CURLOPT_UNRESTRICTED_AUTH:
1133     /*
1134      * Send authentication (user+password) when following locations, even when
1135      * hostname changed.
1136      */
1137     data->set.http_disable_hostname_check_before_authentication =
1138       (bool)(0 != va_arg(param, long));
1139     break;
1140
1141   case CURLOPT_MAXREDIRS:
1142     /*
1143      * The maximum amount of hops you allow curl to follow Location:
1144      * headers. This should mostly be used to detect never-ending loops.
1145      */
1146     data->set.maxredirs = va_arg(param, long);
1147     break;
1148
1149   case CURLOPT_POSTREDIR:
1150   {
1151     /*
1152      * Set the behaviour of POST when redirecting
1153      * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
1154      * CURL_REDIR_POST_301 - POST is kept as POST after 301
1155      * CURL_REDIR_POST_302 - POST is kept as POST after 302
1156      * CURL_REDIR_POST_ALL - POST is kept as POST after 301 and 302
1157      * other - POST is kept as POST after 301 and 302
1158      */
1159     long postRedir = va_arg(param, long);
1160     data->set.post301 = (bool)((postRedir & CURL_REDIR_POST_301)?TRUE:FALSE);
1161     data->set.post302 = (bool)((postRedir & CURL_REDIR_POST_302)?TRUE:FALSE);
1162   }
1163   break;
1164
1165   case CURLOPT_POST:
1166     /* Does this option serve a purpose anymore? Yes it does, when
1167        CURLOPT_POSTFIELDS isn't used and the POST data is read off the
1168        callback! */
1169     if(va_arg(param, long)) {
1170       data->set.httpreq = HTTPREQ_POST;
1171       data->set.opt_no_body = FALSE; /* this is implied */
1172     }
1173     else
1174       data->set.httpreq = HTTPREQ_GET;
1175     break;
1176
1177   case CURLOPT_COPYPOSTFIELDS:
1178     /*
1179      * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
1180      * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
1181      *  CURLOPT_COPYPOSTFIELDS and not altered later.
1182      */
1183     argptr = va_arg(param, char *);
1184
1185     if(!argptr || data->set.postfieldsize == -1)
1186       result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
1187     else {
1188       /*
1189        *  Check that requested length does not overflow the size_t type.
1190        */
1191
1192       if((data->set.postfieldsize < 0) ||
1193          ((sizeof(curl_off_t) != sizeof(size_t)) &&
1194           (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
1195         result = CURLE_OUT_OF_MEMORY;
1196       else {
1197         char * p;
1198
1199         (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1200
1201         /* Allocate even when size == 0. This satisfies the need of possible
1202            later address compare to detect the COPYPOSTFIELDS mode, and
1203            to mark that postfields is used rather than read function or
1204            form data.
1205         */
1206         p = malloc((size_t)(data->set.postfieldsize?
1207                             data->set.postfieldsize:1));
1208
1209         if(!p)
1210           result = CURLE_OUT_OF_MEMORY;
1211         else {
1212           if(data->set.postfieldsize)
1213             memcpy(p, argptr, (size_t)data->set.postfieldsize);
1214
1215           data->set.str[STRING_COPYPOSTFIELDS] = p;
1216         }
1217       }
1218     }
1219
1220     data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
1221     data->set.httpreq = HTTPREQ_POST;
1222     break;
1223
1224   case CURLOPT_POSTFIELDS:
1225     /*
1226      * Like above, but use static data instead of copying it.
1227      */
1228     data->set.postfields = va_arg(param, void *);
1229     /* Release old copied data. */
1230     (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1231     data->set.httpreq = HTTPREQ_POST;
1232     break;
1233
1234   case CURLOPT_POSTFIELDSIZE:
1235     /*
1236      * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1237      * figure it out. Enables binary posts.
1238      */
1239     bigsize = va_arg(param, long);
1240
1241     if(data->set.postfieldsize < bigsize &&
1242        data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1243       /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1244       (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1245       data->set.postfields = NULL;
1246     }
1247
1248     data->set.postfieldsize = bigsize;
1249     break;
1250
1251   case CURLOPT_POSTFIELDSIZE_LARGE:
1252     /*
1253      * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1254      * figure it out. Enables binary posts.
1255      */
1256     bigsize = va_arg(param, curl_off_t);
1257
1258     if(data->set.postfieldsize < bigsize &&
1259        data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1260       /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1261       (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1262       data->set.postfields = NULL;
1263     }
1264
1265     data->set.postfieldsize = bigsize;
1266     break;
1267
1268   case CURLOPT_HTTPPOST:
1269     /*
1270      * Set to make us do HTTP POST
1271      */
1272     data->set.httppost = va_arg(param, struct curl_httppost *);
1273     data->set.httpreq = HTTPREQ_POST_FORM;
1274     data->set.opt_no_body = FALSE; /* this is implied */
1275     break;
1276
1277   case CURLOPT_REFERER:
1278     /*
1279      * String to set in the HTTP Referer: field.
1280      */
1281     if(data->change.referer_alloc) {
1282       free(data->change.referer);
1283       data->change.referer_alloc = FALSE;
1284     }
1285     result = setstropt(&data->set.str[STRING_SET_REFERER],
1286                        va_arg(param, char *));
1287     data->change.referer = data->set.str[STRING_SET_REFERER];
1288     break;
1289
1290   case CURLOPT_USERAGENT:
1291     /*
1292      * String to use in the HTTP User-Agent field
1293      */
1294     result = setstropt(&data->set.str[STRING_USERAGENT],
1295                        va_arg(param, char *));
1296     break;
1297
1298   case CURLOPT_HTTPHEADER:
1299     /*
1300      * Set a list with HTTP headers to use (or replace internals with)
1301      */
1302     data->set.headers = va_arg(param, struct curl_slist *);
1303     break;
1304
1305   case CURLOPT_HTTP200ALIASES:
1306     /*
1307      * Set a list of aliases for HTTP 200 in response header
1308      */
1309     data->set.http200aliases = va_arg(param, struct curl_slist *);
1310     break;
1311
1312 #if !defined(CURL_DISABLE_COOKIES)
1313   case CURLOPT_COOKIE:
1314     /*
1315      * Cookie string to send to the remote server in the request.
1316      */
1317     result = setstropt(&data->set.str[STRING_COOKIE],
1318                        va_arg(param, char *));
1319     break;
1320
1321   case CURLOPT_COOKIEFILE:
1322     /*
1323      * Set cookie file to read and parse. Can be used multiple times.
1324      */
1325     argptr = (char *)va_arg(param, void *);
1326     if(argptr) {
1327       struct curl_slist *cl;
1328       /* append the cookie file name to the list of file names, and deal with
1329          them later */
1330       cl = curl_slist_append(data->change.cookielist, argptr);
1331
1332       if(!cl)
1333         return CURLE_OUT_OF_MEMORY;
1334
1335       data->change.cookielist = cl; /* store the list for later use */
1336     }
1337     break;
1338
1339   case CURLOPT_COOKIEJAR:
1340     /*
1341      * Set cookie file name to dump all cookies to when we're done.
1342      */
1343     result = setstropt(&data->set.str[STRING_COOKIEJAR],
1344                        va_arg(param, char *));
1345
1346     /*
1347      * Activate the cookie parser. This may or may not already
1348      * have been made.
1349      */
1350     data->cookies = Curl_cookie_init(data, NULL, data->cookies,
1351                                      data->set.cookiesession);
1352     break;
1353
1354   case CURLOPT_COOKIESESSION:
1355     /*
1356      * Set this option to TRUE to start a new "cookie session". It will
1357      * prevent the forthcoming read-cookies-from-file actions to accept
1358      * cookies that are marked as being session cookies, as they belong to a
1359      * previous session.
1360      *
1361      * In the original Netscape cookie spec, "session cookies" are cookies
1362      * with no expire date set. RFC2109 describes the same action if no
1363      * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1364      * a 'Discard' action that can enforce the discard even for cookies that
1365      * have a Max-Age.
1366      *
1367      * We run mostly with the original cookie spec, as hardly anyone implements
1368      * anything else.
1369      */
1370     data->set.cookiesession = (bool)(0 != va_arg(param, long));
1371     break;
1372
1373   case CURLOPT_COOKIELIST:
1374     argptr = va_arg(param, char *);
1375
1376     if(argptr == NULL)
1377       break;
1378
1379     if(Curl_raw_equal(argptr, "ALL")) {
1380       /* clear all cookies */
1381       Curl_cookie_clearall(data->cookies);
1382       break;
1383     }
1384     else if(Curl_raw_equal(argptr, "SESS")) {
1385       /* clear session cookies */
1386       Curl_cookie_clearsess(data->cookies);
1387       break;
1388     }
1389     else if(Curl_raw_equal(argptr, "FLUSH")) {
1390       /* flush cookies to file */
1391       flush_cookies(data, 0);
1392       break;
1393     }
1394
1395     if(!data->cookies)
1396       /* if cookie engine was not running, activate it */
1397       data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1398
1399     argptr = strdup(argptr);
1400     if(!argptr) {
1401       result = CURLE_OUT_OF_MEMORY;
1402       break;
1403     }
1404
1405     if(checkprefix("Set-Cookie:", argptr))
1406       /* HTTP Header format line */
1407       Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1408
1409     else
1410       /* Netscape format line */
1411       Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1412
1413     free(argptr);
1414     break;
1415 #endif /* CURL_DISABLE_COOKIES */
1416
1417   case CURLOPT_HTTPGET:
1418     /*
1419      * Set to force us do HTTP GET
1420      */
1421     if(va_arg(param, long)) {
1422       data->set.httpreq = HTTPREQ_GET;
1423       data->set.upload = FALSE; /* switch off upload */
1424       data->set.opt_no_body = FALSE; /* this is implied */
1425     }
1426     break;
1427
1428   case CURLOPT_HTTP_VERSION:
1429     /*
1430      * This sets a requested HTTP version to be used. The value is one of
1431      * the listed enums in curl/curl.h.
1432      */
1433     data->set.httpversion = va_arg(param, long);
1434     break;
1435
1436   case CURLOPT_HTTPAUTH:
1437     /*
1438      * Set HTTP Authentication type BITMASK.
1439      */
1440   {
1441     long auth = va_arg(param, long);
1442
1443     /* the DIGEST_IE bit is only used to set a special marker, for all the
1444        rest we need to handle it as normal DIGEST */
1445     data->state.authhost.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE)?
1446                                           TRUE:FALSE);
1447
1448     if(auth & CURLAUTH_DIGEST_IE) {
1449       auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1450       auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1451     }
1452
1453     /* switch off bits we can't support */
1454 #ifndef USE_NTLM
1455     auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
1456 #endif
1457 #ifndef HAVE_GSSAPI
1458     auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI */
1459 #endif
1460     if(!auth)
1461       return CURLE_FAILED_INIT; /* no supported types left! */
1462
1463     data->set.httpauth = auth;
1464   }
1465   break;
1466
1467 #endif   /* CURL_DISABLE_HTTP */
1468
1469   case CURLOPT_CUSTOMREQUEST:
1470     /*
1471      * Set a custom string to use as request
1472      */
1473     result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1474                        va_arg(param, char *));
1475
1476     /* we don't set
1477        data->set.httpreq = HTTPREQ_CUSTOM;
1478        here, we continue as if we were using the already set type
1479        and this just changes the actual request keyword */
1480     break;
1481
1482 #ifndef CURL_DISABLE_PROXY
1483   case CURLOPT_HTTPPROXYTUNNEL:
1484     /*
1485      * Tunnel operations through the proxy instead of normal proxy use
1486      */
1487     data->set.tunnel_thru_httpproxy = (bool)(0 != va_arg(param, long));
1488     break;
1489
1490   case CURLOPT_PROXYPORT:
1491     /*
1492      * Explicitly set HTTP proxy port number.
1493      */
1494     data->set.proxyport = va_arg(param, long);
1495     break;
1496
1497   case CURLOPT_PROXYAUTH:
1498     /*
1499      * Set HTTP Authentication type BITMASK.
1500      */
1501   {
1502     long auth = va_arg(param, long);
1503
1504     /* the DIGEST_IE bit is only used to set a special marker, for all the
1505        rest we need to handle it as normal DIGEST */
1506     data->state.authproxy.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE)?
1507                                            TRUE:FALSE);
1508
1509     if(auth & CURLAUTH_DIGEST_IE) {
1510       auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1511       auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1512     }
1513     /* switch off bits we can't support */
1514 #ifndef USE_NTLM
1515     auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
1516 #endif
1517 #ifndef HAVE_GSSAPI
1518     auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI */
1519 #endif
1520     if(!auth)
1521       return CURLE_FAILED_INIT; /* no supported types left! */
1522
1523     data->set.proxyauth = auth;
1524   }
1525   break;
1526
1527   case CURLOPT_PROXY:
1528     /*
1529      * Set proxy server:port to use as HTTP proxy.
1530      *
1531      * If the proxy is set to "" we explicitly say that we don't want to use a
1532      * proxy (even though there might be environment variables saying so).
1533      *
1534      * Setting it to NULL, means no proxy but allows the environment variables
1535      * to decide for us.
1536      */
1537     result = setstropt(&data->set.str[STRING_PROXY],
1538                        va_arg(param, char *));
1539     break;
1540
1541   case CURLOPT_PROXYTYPE:
1542     /*
1543      * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1544      */
1545     data->set.proxytype = (curl_proxytype)va_arg(param, long);
1546     break;
1547
1548   case CURLOPT_PROXY_TRANSFER_MODE:
1549     /*
1550      * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1551      */
1552     switch (va_arg(param, long)) {
1553     case 0:
1554       data->set.proxy_transfer_mode = FALSE;
1555       break;
1556     case 1:
1557       data->set.proxy_transfer_mode = TRUE;
1558       break;
1559     default:
1560       /* reserve other values for future use */
1561       result = CURLE_FAILED_INIT;
1562       break;
1563     }
1564     break;
1565 #endif   /* CURL_DISABLE_PROXY */
1566
1567 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1568   case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1569     /*
1570      * Set gssapi service name
1571      */
1572     result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
1573                        va_arg(param, char *));
1574     break;
1575
1576   case CURLOPT_SOCKS5_GSSAPI_NEC:
1577     /*
1578      * set flag for nec socks5 support
1579      */
1580     data->set.socks5_gssapi_nec = (bool)(0 != va_arg(param, long));
1581     break;
1582 #endif
1583
1584   case CURLOPT_WRITEHEADER:
1585     /*
1586      * Custom pointer to pass the header write callback function
1587      */
1588     data->set.writeheader = (void *)va_arg(param, void *);
1589     break;
1590   case CURLOPT_ERRORBUFFER:
1591     /*
1592      * Error buffer provided by the caller to get the human readable
1593      * error string in.
1594      */
1595     data->set.errorbuffer = va_arg(param, char *);
1596     break;
1597   case CURLOPT_FILE:
1598     /*
1599      * FILE pointer to write to or include in the data write callback
1600      */
1601     data->set.out = va_arg(param, FILE *);
1602     break;
1603   case CURLOPT_FTPPORT:
1604     /*
1605      * Use FTP PORT, this also specifies which IP address to use
1606      */
1607     result = setstropt(&data->set.str[STRING_FTPPORT],
1608                        va_arg(param, char *));
1609     data->set.ftp_use_port = (bool)(NULL != data->set.str[STRING_FTPPORT]);
1610     break;
1611
1612   case CURLOPT_FTP_USE_EPRT:
1613     data->set.ftp_use_eprt = (bool)(0 != va_arg(param, long));
1614     break;
1615
1616   case CURLOPT_FTP_USE_EPSV:
1617     data->set.ftp_use_epsv = (bool)(0 != va_arg(param, long));
1618     break;
1619
1620   case CURLOPT_FTP_USE_PRET:
1621     data->set.ftp_use_pret = (bool)(0 != va_arg(param, long));
1622     break;
1623
1624   case CURLOPT_FTP_SSL_CCC:
1625     data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1626     break;
1627
1628   case CURLOPT_FTP_SKIP_PASV_IP:
1629     /*
1630      * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1631      * bypass of the IP address in PASV responses.
1632      */
1633     data->set.ftp_skip_ip = (bool)(0 != va_arg(param, long));
1634     break;
1635
1636   case CURLOPT_INFILE:
1637     /*
1638      * FILE pointer to read the file to be uploaded from. Or possibly
1639      * used as argument to the read callback.
1640      */
1641     data->set.in = va_arg(param, FILE *);
1642     break;
1643   case CURLOPT_INFILESIZE:
1644     /*
1645      * If known, this should inform curl about the file size of the
1646      * to-be-uploaded file.
1647      */
1648     data->set.infilesize = va_arg(param, long);
1649     break;
1650   case CURLOPT_INFILESIZE_LARGE:
1651     /*
1652      * If known, this should inform curl about the file size of the
1653      * to-be-uploaded file.
1654      */
1655     data->set.infilesize = va_arg(param, curl_off_t);
1656     break;
1657   case CURLOPT_LOW_SPEED_LIMIT:
1658     /*
1659      * The low speed limit that if transfers are below this for
1660      * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1661      */
1662     data->set.low_speed_limit=va_arg(param, long);
1663     break;
1664   case CURLOPT_MAX_SEND_SPEED_LARGE:
1665     /*
1666      * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1667      * bytes per second the transfer is throttled..
1668      */
1669     data->set.max_send_speed=va_arg(param, curl_off_t);
1670     break;
1671   case CURLOPT_MAX_RECV_SPEED_LARGE:
1672     /*
1673      * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1674      * second the transfer is throttled..
1675      */
1676     data->set.max_recv_speed=va_arg(param, curl_off_t);
1677     break;
1678   case CURLOPT_LOW_SPEED_TIME:
1679     /*
1680      * The low speed time that if transfers are below the set
1681      * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1682      */
1683     data->set.low_speed_time=va_arg(param, long);
1684     break;
1685   case CURLOPT_URL:
1686     /*
1687      * The URL to fetch.
1688      */
1689     if(data->change.url_alloc) {
1690       /* the already set URL is allocated, free it first! */
1691       free(data->change.url);
1692       data->change.url_alloc=FALSE;
1693     }
1694     result = setstropt(&data->set.str[STRING_SET_URL],
1695                        va_arg(param, char *));
1696     data->change.url = data->set.str[STRING_SET_URL];
1697     break;
1698   case CURLOPT_PORT:
1699     /*
1700      * The port number to use when getting the URL
1701      */
1702     data->set.use_port = va_arg(param, long);
1703     break;
1704   case CURLOPT_TIMEOUT:
1705     /*
1706      * The maximum time you allow curl to use for a single transfer
1707      * operation.
1708      */
1709     data->set.timeout = va_arg(param, long) * 1000L;
1710     break;
1711
1712   case CURLOPT_TIMEOUT_MS:
1713     data->set.timeout = va_arg(param, long);
1714     break;
1715
1716   case CURLOPT_CONNECTTIMEOUT:
1717     /*
1718      * The maximum time you allow curl to use to connect.
1719      */
1720     data->set.connecttimeout = va_arg(param, long) * 1000L;
1721     break;
1722
1723   case CURLOPT_CONNECTTIMEOUT_MS:
1724     data->set.connecttimeout = va_arg(param, long);
1725     break;
1726
1727   case CURLOPT_USERPWD:
1728     /*
1729      * user:password to use in the operation
1730      */
1731     result = setstropt_userpwd(va_arg(param, char *),
1732                                &data->set.str[STRING_USERNAME],
1733                                &data->set.str[STRING_PASSWORD]);
1734     break;
1735   case CURLOPT_USERNAME:
1736     /*
1737      * authentication user name to use in the operation
1738      */
1739     result = setstropt(&data->set.str[STRING_USERNAME],
1740                        va_arg(param, char *));
1741     break;
1742   case CURLOPT_PASSWORD:
1743     /*
1744      * authentication password to use in the operation
1745      */
1746     result = setstropt(&data->set.str[STRING_PASSWORD],
1747                        va_arg(param, char *));
1748     break;
1749   case CURLOPT_POSTQUOTE:
1750     /*
1751      * List of RAW FTP commands to use after a transfer
1752      */
1753     data->set.postquote = va_arg(param, struct curl_slist *);
1754     break;
1755   case CURLOPT_PREQUOTE:
1756     /*
1757      * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1758      */
1759     data->set.prequote = va_arg(param, struct curl_slist *);
1760     break;
1761   case CURLOPT_QUOTE:
1762     /*
1763      * List of RAW FTP commands to use before a transfer
1764      */
1765     data->set.quote = va_arg(param, struct curl_slist *);
1766     break;
1767   case CURLOPT_RESOLVE:
1768     /*
1769      * List of NAME:[address] names to populate the DNS cache with
1770      * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1771      *
1772      * Names added with this API will remain in the cache until explicitly
1773      * removed or the handle is cleaned up.
1774      *
1775      * This API can remove any name from the DNS cache, but only entries
1776      * that aren't actually in use right now will be pruned immediately.
1777      */
1778     data->set.resolve = va_arg(param, struct curl_slist *);
1779     data->change.resolve = data->set.resolve;
1780     break;
1781   case CURLOPT_PROGRESSFUNCTION:
1782     /*
1783      * Progress callback function
1784      */
1785     data->set.fprogress = va_arg(param, curl_progress_callback);
1786     if(data->set.fprogress)
1787       data->progress.callback = TRUE; /* no longer internal */
1788     else
1789       data->progress.callback = FALSE; /* NULL enforces internal */
1790
1791     break;
1792   case CURLOPT_PROGRESSDATA:
1793     /*
1794      * Custom client data to pass to the progress callback
1795      */
1796     data->set.progress_client = va_arg(param, void *);
1797     break;
1798
1799 #ifndef CURL_DISABLE_PROXY
1800   case CURLOPT_PROXYUSERPWD:
1801     /*
1802      * user:password needed to use the proxy
1803      */
1804     result = setstropt_userpwd(va_arg(param, char *),
1805                                &data->set.str[STRING_PROXYUSERNAME],
1806                                &data->set.str[STRING_PROXYPASSWORD]);
1807     break;
1808   case CURLOPT_PROXYUSERNAME:
1809     /*
1810      * authentication user name to use in the operation
1811      */
1812     result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1813                        va_arg(param, char *));
1814     break;
1815   case CURLOPT_PROXYPASSWORD:
1816     /*
1817      * authentication password to use in the operation
1818      */
1819     result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1820                        va_arg(param, char *));
1821     break;
1822   case CURLOPT_NOPROXY:
1823     /*
1824      * proxy exception list
1825      */
1826     result = setstropt(&data->set.str[STRING_NOPROXY],
1827                        va_arg(param, char *));
1828     break;
1829 #endif
1830
1831   case CURLOPT_RANGE:
1832     /*
1833      * What range of the file you want to transfer
1834      */
1835     result = setstropt(&data->set.str[STRING_SET_RANGE],
1836                        va_arg(param, char *));
1837     break;
1838   case CURLOPT_RESUME_FROM:
1839     /*
1840      * Resume transfer at the give file position
1841      */
1842     data->set.set_resume_from = va_arg(param, long);
1843     break;
1844   case CURLOPT_RESUME_FROM_LARGE:
1845     /*
1846      * Resume transfer at the give file position
1847      */
1848     data->set.set_resume_from = va_arg(param, curl_off_t);
1849     break;
1850   case CURLOPT_DEBUGFUNCTION:
1851     /*
1852      * stderr write callback.
1853      */
1854     data->set.fdebug = va_arg(param, curl_debug_callback);
1855     /*
1856      * if the callback provided is NULL, it'll use the default callback
1857      */
1858     break;
1859   case CURLOPT_DEBUGDATA:
1860     /*
1861      * Set to a void * that should receive all error writes. This
1862      * defaults to CURLOPT_STDERR for normal operations.
1863      */
1864     data->set.debugdata = va_arg(param, void *);
1865     break;
1866   case CURLOPT_STDERR:
1867     /*
1868      * Set to a FILE * that should receive all error writes. This
1869      * defaults to stderr for normal operations.
1870      */
1871     data->set.err = va_arg(param, FILE *);
1872     if(!data->set.err)
1873       data->set.err = stderr;
1874     break;
1875   case CURLOPT_HEADERFUNCTION:
1876     /*
1877      * Set header write callback
1878      */
1879     data->set.fwrite_header = va_arg(param, curl_write_callback);
1880     break;
1881   case CURLOPT_WRITEFUNCTION:
1882     /*
1883      * Set data write callback
1884      */
1885     data->set.fwrite_func = va_arg(param, curl_write_callback);
1886     if(!data->set.fwrite_func) {
1887       data->set.is_fwrite_set = 0;
1888       /* When set to NULL, reset to our internal default function */
1889       data->set.fwrite_func = (curl_write_callback)fwrite;
1890     }
1891     else
1892       data->set.is_fwrite_set = 1;
1893     break;
1894   case CURLOPT_READFUNCTION:
1895     /*
1896      * Read data callback
1897      */
1898     data->set.fread_func = va_arg(param, curl_read_callback);
1899     if(!data->set.fread_func) {
1900       data->set.is_fread_set = 0;
1901       /* When set to NULL, reset to our internal default function */
1902       data->set.fread_func = (curl_read_callback)fread;
1903     }
1904     else
1905       data->set.is_fread_set = 1;
1906     break;
1907   case CURLOPT_SEEKFUNCTION:
1908     /*
1909      * Seek callback. Might be NULL.
1910      */
1911     data->set.seek_func = va_arg(param, curl_seek_callback);
1912     break;
1913   case CURLOPT_SEEKDATA:
1914     /*
1915      * Seek control callback. Might be NULL.
1916      */
1917     data->set.seek_client = va_arg(param, void *);
1918     break;
1919   case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1920     /*
1921      * "Convert from network encoding" callback
1922      */
1923     data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1924     break;
1925   case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1926     /*
1927      * "Convert to network encoding" callback
1928      */
1929     data->set.convtonetwork = va_arg(param, curl_conv_callback);
1930     break;
1931   case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1932     /*
1933      * "Convert from UTF-8 encoding" callback
1934      */
1935     data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1936     break;
1937   case CURLOPT_IOCTLFUNCTION:
1938     /*
1939      * I/O control callback. Might be NULL.
1940      */
1941     data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1942     break;
1943   case CURLOPT_IOCTLDATA:
1944     /*
1945      * I/O control data pointer. Might be NULL.
1946      */
1947     data->set.ioctl_client = va_arg(param, void *);
1948     break;
1949   case CURLOPT_SSLCERT:
1950     /*
1951      * String that holds file name of the SSL certificate to use
1952      */
1953     result = setstropt(&data->set.str[STRING_CERT],
1954                        va_arg(param, char *));
1955     break;
1956   case CURLOPT_SSLCERTTYPE:
1957     /*
1958      * String that holds file type of the SSL certificate to use
1959      */
1960     result = setstropt(&data->set.str[STRING_CERT_TYPE],
1961                        va_arg(param, char *));
1962     break;
1963   case CURLOPT_SSLKEY:
1964     /*
1965      * String that holds file name of the SSL key to use
1966      */
1967     result = setstropt(&data->set.str[STRING_KEY],
1968                        va_arg(param, char *));
1969     break;
1970   case CURLOPT_SSLKEYTYPE:
1971     /*
1972      * String that holds file type of the SSL key to use
1973      */
1974     result = setstropt(&data->set.str[STRING_KEY_TYPE],
1975                        va_arg(param, char *));
1976     break;
1977   case CURLOPT_KEYPASSWD:
1978     /*
1979      * String that holds the SSL or SSH private key password.
1980      */
1981     result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1982                        va_arg(param, char *));
1983     break;
1984   case CURLOPT_SSLENGINE:
1985     /*
1986      * String that holds the SSL crypto engine.
1987      */
1988     argptr = va_arg(param, char *);
1989     if(argptr && argptr[0])
1990       result = Curl_ssl_set_engine(data, argptr);
1991     break;
1992
1993   case CURLOPT_SSLENGINE_DEFAULT:
1994     /*
1995      * flag to set engine as default.
1996      */
1997     result = Curl_ssl_set_engine_default(data);
1998     break;
1999   case CURLOPT_CRLF:
2000     /*
2001      * Kludgy option to enable CRLF conversions. Subject for removal.
2002      */
2003     data->set.crlf = (bool)(0 != va_arg(param, long));
2004     break;
2005
2006   case CURLOPT_INTERFACE:
2007     /*
2008      * Set what interface or address/hostname to bind the socket to when
2009      * performing an operation and thus what from-IP your connection will use.
2010      */
2011     result = setstropt(&data->set.str[STRING_DEVICE],
2012                        va_arg(param, char *));
2013     break;
2014   case CURLOPT_LOCALPORT:
2015     /*
2016      * Set what local port to bind the socket to when performing an operation.
2017      */
2018     data->set.localport = curlx_sltous(va_arg(param, long));
2019     break;
2020   case CURLOPT_LOCALPORTRANGE:
2021     /*
2022      * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
2023      */
2024     data->set.localportrange = curlx_sltosi(va_arg(param, long));
2025     break;
2026   case CURLOPT_KRBLEVEL:
2027     /*
2028      * A string that defines the kerberos security level.
2029      */
2030     result = setstropt(&data->set.str[STRING_KRB_LEVEL],
2031                        va_arg(param, char *));
2032     data->set.krb = (bool)(NULL != data->set.str[STRING_KRB_LEVEL]);
2033     break;
2034   case CURLOPT_SSL_VERIFYPEER:
2035     /*
2036      * Enable peer SSL verifying.
2037      */
2038     data->set.ssl.verifypeer = va_arg(param, long);
2039     break;
2040   case CURLOPT_SSL_VERIFYHOST:
2041     /*
2042      * Enable verification of the CN contained in the peer certificate
2043      */
2044     data->set.ssl.verifyhost = va_arg(param, long);
2045     break;
2046 #ifdef USE_SSLEAY
2047     /* since these two options are only possible to use on an OpenSSL-
2048        powered libcurl we #ifdef them on this condition so that libcurls
2049        built against other SSL libs will return a proper error when trying
2050        to set this option! */
2051   case CURLOPT_SSL_CTX_FUNCTION:
2052     /*
2053      * Set a SSL_CTX callback
2054      */
2055     data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
2056     break;
2057   case CURLOPT_SSL_CTX_DATA:
2058     /*
2059      * Set a SSL_CTX callback parameter pointer
2060      */
2061     data->set.ssl.fsslctxp = va_arg(param, void *);
2062     break;
2063   case CURLOPT_CERTINFO:
2064     data->set.ssl.certinfo = (bool)(0 != va_arg(param, long));
2065     break;
2066 #endif
2067   case CURLOPT_CAINFO:
2068     /*
2069      * Set CA info for SSL connection. Specify file name of the CA certificate
2070      */
2071     result = setstropt(&data->set.str[STRING_SSL_CAFILE],
2072                        va_arg(param, char *));
2073     break;
2074   case CURLOPT_CAPATH:
2075     /*
2076      * Set CA path info for SSL connection. Specify directory name of the CA
2077      * certificates which have been prepared using openssl c_rehash utility.
2078      */
2079     /* This does not work on windows. */
2080     result = setstropt(&data->set.str[STRING_SSL_CAPATH],
2081                        va_arg(param, char *));
2082     break;
2083   case CURLOPT_CRLFILE:
2084     /*
2085      * Set CRL file info for SSL connection. Specify file name of the CRL
2086      * to check certificates revocation
2087      */
2088     result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
2089                        va_arg(param, char *));
2090     break;
2091   case CURLOPT_ISSUERCERT:
2092     /*
2093      * Set Issuer certificate file
2094      * to check certificates issuer
2095      */
2096     result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
2097                        va_arg(param, char *));
2098     break;
2099   case CURLOPT_TELNETOPTIONS:
2100     /*
2101      * Set a linked list of telnet options
2102      */
2103     data->set.telnet_options = va_arg(param, struct curl_slist *);
2104     break;
2105
2106   case CURLOPT_BUFFERSIZE:
2107     /*
2108      * The application kindly asks for a differently sized receive buffer.
2109      * If it seems reasonable, we'll use it.
2110      */
2111     data->set.buffer_size = va_arg(param, long);
2112
2113     if((data->set.buffer_size> (BUFSIZE -1 )) ||
2114        (data->set.buffer_size < 1))
2115       data->set.buffer_size = 0; /* huge internal default */
2116
2117     break;
2118
2119   case CURLOPT_NOSIGNAL:
2120     /*
2121      * The application asks not to set any signal() or alarm() handlers,
2122      * even when using a timeout.
2123      */
2124     data->set.no_signal = (bool)(0 != va_arg(param, long));
2125     break;
2126
2127   case CURLOPT_SHARE:
2128   {
2129     struct Curl_share *set;
2130     set = va_arg(param, struct Curl_share *);
2131
2132     /* disconnect from old share, if any */
2133     if(data->share) {
2134       Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2135
2136       if(data->dns.hostcachetype == HCACHE_SHARED) {
2137         data->dns.hostcache = NULL;
2138         data->dns.hostcachetype = HCACHE_NONE;
2139       }
2140
2141       if(data->share->cookies == data->cookies)
2142         data->cookies = NULL;
2143
2144       data->share->dirty--;
2145
2146       Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2147       data->share = NULL;
2148     }
2149
2150     /* use new share if it set */
2151     data->share = set;
2152     if(data->share) {
2153
2154       Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2155
2156       data->share->dirty++;
2157
2158       if(data->share->hostcache) {
2159         /* use shared host cache, first free the private one if any */
2160         if(data->dns.hostcachetype == HCACHE_PRIVATE)
2161           Curl_hash_destroy(data->dns.hostcache);
2162
2163         data->dns.hostcache = data->share->hostcache;
2164         data->dns.hostcachetype = HCACHE_SHARED;
2165       }
2166 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2167       if(data->share->cookies) {
2168         /* use shared cookie list, first free own one if any */
2169         if(data->cookies)
2170           Curl_cookie_cleanup(data->cookies);
2171         /* enable cookies since we now use a share that uses cookies! */
2172         data->cookies = data->share->cookies;
2173       }
2174 #endif   /* CURL_DISABLE_HTTP */
2175       Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2176
2177     }
2178     /* check for host cache not needed,
2179      * it will be done by curl_easy_perform */
2180   }
2181   break;
2182
2183   case CURLOPT_PRIVATE:
2184     /*
2185      * Set private data pointer.
2186      */
2187     data->set.private_data = va_arg(param, void *);
2188     break;
2189
2190   case CURLOPT_MAXFILESIZE:
2191     /*
2192      * Set the maximum size of a file to download.
2193      */
2194     data->set.max_filesize = va_arg(param, long);
2195     break;
2196
2197 #ifdef USE_SSL
2198   case CURLOPT_USE_SSL:
2199     /*
2200      * Make transfers attempt to use SSL/TLS.
2201      */
2202     data->set.ftp_ssl = (curl_usessl)va_arg(param, long);
2203     break;
2204 #endif
2205   case CURLOPT_FTPSSLAUTH:
2206     /*
2207      * Set a specific auth for FTP-SSL transfers.
2208      */
2209     data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2210     break;
2211
2212   case CURLOPT_IPRESOLVE:
2213     data->set.ipver = va_arg(param, long);
2214     break;
2215
2216   case CURLOPT_MAXFILESIZE_LARGE:
2217     /*
2218      * Set the maximum size of a file to download.
2219      */
2220     data->set.max_filesize = va_arg(param, curl_off_t);
2221     break;
2222
2223   case CURLOPT_TCP_NODELAY:
2224     /*
2225      * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2226      * algorithm
2227      */
2228     data->set.tcp_nodelay = (bool)(0 != va_arg(param, long));
2229     break;
2230
2231   case CURLOPT_FTP_ACCOUNT:
2232     result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2233                        va_arg(param, char *));
2234     break;
2235
2236   case CURLOPT_IGNORE_CONTENT_LENGTH:
2237     data->set.ignorecl = (bool)(0 != va_arg(param, long));
2238     break;
2239
2240   case CURLOPT_CONNECT_ONLY:
2241     /*
2242      * No data transfer, set up connection and let application use the socket
2243      */
2244     data->set.connect_only = (bool)(0 != va_arg(param, long));
2245     break;
2246
2247   case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2248     result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2249                        va_arg(param, char *));
2250     break;
2251
2252   case CURLOPT_SOCKOPTFUNCTION:
2253     /*
2254      * socket callback function: called after socket() but before connect()
2255      */
2256     data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2257     break;
2258
2259   case CURLOPT_SOCKOPTDATA:
2260     /*
2261      * socket callback data pointer. Might be NULL.
2262      */
2263     data->set.sockopt_client = va_arg(param, void *);
2264     break;
2265
2266   case CURLOPT_OPENSOCKETFUNCTION:
2267     /*
2268      * open/create socket callback function: called instead of socket(),
2269      * before connect()
2270      */
2271     data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2272     break;
2273
2274   case CURLOPT_OPENSOCKETDATA:
2275     /*
2276      * socket callback data pointer. Might be NULL.
2277      */
2278     data->set.opensocket_client = va_arg(param, void *);
2279     break;
2280
2281   case CURLOPT_SSL_SESSIONID_CACHE:
2282     data->set.ssl.sessionid = (bool)(0 != va_arg(param, long));
2283     break;
2284
2285 #ifdef USE_LIBSSH2
2286     /* we only include SSH options if explicitly built to support SSH */
2287   case CURLOPT_SSH_AUTH_TYPES:
2288     data->set.ssh_auth_types = va_arg(param, long);
2289     break;
2290
2291   case CURLOPT_SSH_PUBLIC_KEYFILE:
2292     /*
2293      * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2294      */
2295     result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2296                        va_arg(param, char *));
2297     break;
2298
2299   case CURLOPT_SSH_PRIVATE_KEYFILE:
2300     /*
2301      * Use this file instead of the $HOME/.ssh/id_dsa file
2302      */
2303     result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2304                        va_arg(param, char *));
2305     break;
2306   case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2307     /*
2308      * Option to allow for the MD5 of the host public key to be checked
2309      * for validation purposes.
2310      */
2311     result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2312                        va_arg(param, char *));
2313     break;
2314 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2315   case CURLOPT_SSH_KNOWNHOSTS:
2316     /*
2317      * Store the file name to read known hosts from.
2318      */
2319     result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2320                        va_arg(param, char *));
2321     break;
2322
2323   case CURLOPT_SSH_KEYFUNCTION:
2324     /* setting to NULL is fine since the ssh.c functions themselves will
2325        then rever to use the internal default */
2326     data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2327     break;
2328
2329   case CURLOPT_SSH_KEYDATA:
2330     /*
2331      * Custom client data to pass to the SSH keyfunc callback
2332      */
2333     data->set.ssh_keyfunc_userp = va_arg(param, void *);
2334     break;
2335 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2336
2337 #endif /* USE_LIBSSH2 */
2338
2339   case CURLOPT_HTTP_TRANSFER_DECODING:
2340     /*
2341      * disable libcurl transfer encoding is used
2342      */
2343     data->set.http_te_skip = (bool)(0 == va_arg(param, long));
2344     break;
2345
2346   case CURLOPT_HTTP_CONTENT_DECODING:
2347     /*
2348      * raw data passed to the application when content encoding is used
2349      */
2350     data->set.http_ce_skip = (bool)(0 == va_arg(param, long));
2351     break;
2352
2353   case CURLOPT_NEW_FILE_PERMS:
2354     /*
2355      * Uses these permissions instead of 0644
2356      */
2357     data->set.new_file_perms = va_arg(param, long);
2358     break;
2359
2360   case CURLOPT_NEW_DIRECTORY_PERMS:
2361     /*
2362      * Uses these permissions instead of 0755
2363      */
2364     data->set.new_directory_perms = va_arg(param, long);
2365     break;
2366
2367   case CURLOPT_ADDRESS_SCOPE:
2368     /*
2369      * We always get longs when passed plain numericals, but for this value we
2370      * know that an unsigned int will always hold the value so we blindly
2371      * typecast to this type
2372      */
2373     data->set.scope = curlx_sltoui(va_arg(param, long));
2374     break;
2375
2376   case CURLOPT_PROTOCOLS:
2377     /* set the bitmask for the protocols that are allowed to be used for the
2378        transfer, which thus helps the app which takes URLs from users or other
2379        external inputs and want to restrict what protocol(s) to deal
2380        with. Defaults to CURLPROTO_ALL. */
2381     data->set.allowed_protocols = va_arg(param, long) & PROT_EXTMASK;
2382     break;
2383
2384   case CURLOPT_REDIR_PROTOCOLS:
2385     /* set the bitmask for the protocols that libcurl is allowed to follow to,
2386        as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2387        to be set in both bitmasks to be allowed to get redirected to. Defaults
2388        to all protocols except FILE and SCP. */
2389     data->set.redir_protocols = va_arg(param, long) & PROT_EXTMASK;
2390     break;
2391
2392   case CURLOPT_MAIL_FROM:
2393     result = setstropt(&data->set.str[STRING_MAIL_FROM],
2394                        va_arg(param, char *));
2395     break;
2396
2397   case CURLOPT_MAIL_RCPT:
2398     /* get a list of mail recipients */
2399     data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2400     break;
2401
2402   case CURLOPT_RTSP_REQUEST:
2403     {
2404       /*
2405        * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2406        * Would this be better if the RTSPREQ_* were just moved into here?
2407        */
2408       long curl_rtspreq = va_arg(param, long);
2409       Curl_RtspReq rtspreq = RTSPREQ_NONE;
2410       switch(curl_rtspreq) {
2411         case CURL_RTSPREQ_OPTIONS:
2412           rtspreq = RTSPREQ_OPTIONS;
2413           break;
2414
2415         case CURL_RTSPREQ_DESCRIBE:
2416           rtspreq = RTSPREQ_DESCRIBE;
2417           break;
2418
2419         case CURL_RTSPREQ_ANNOUNCE:
2420           rtspreq = RTSPREQ_ANNOUNCE;
2421           break;
2422
2423         case CURL_RTSPREQ_SETUP:
2424           rtspreq = RTSPREQ_SETUP;
2425           break;
2426
2427         case CURL_RTSPREQ_PLAY:
2428           rtspreq = RTSPREQ_PLAY;
2429           break;
2430
2431         case CURL_RTSPREQ_PAUSE:
2432           rtspreq = RTSPREQ_PAUSE;
2433           break;
2434
2435         case CURL_RTSPREQ_TEARDOWN:
2436           rtspreq = RTSPREQ_TEARDOWN;
2437           break;
2438
2439         case CURL_RTSPREQ_GET_PARAMETER:
2440           rtspreq = RTSPREQ_GET_PARAMETER;
2441           break;
2442
2443         case CURL_RTSPREQ_SET_PARAMETER:
2444           rtspreq = RTSPREQ_SET_PARAMETER;
2445           break;
2446
2447         case CURL_RTSPREQ_RECORD:
2448           rtspreq = RTSPREQ_RECORD;
2449           break;
2450
2451         case CURL_RTSPREQ_RECEIVE:
2452           rtspreq = RTSPREQ_RECEIVE;
2453           break;
2454         default:
2455           rtspreq = RTSPREQ_NONE;
2456       }
2457
2458       data->set.rtspreq = rtspreq;
2459     break;
2460     }
2461
2462
2463   case CURLOPT_RTSP_SESSION_ID:
2464     /*
2465      * Set the RTSP Session ID manually. Useful if the application is
2466      * resuming a previously established RTSP session
2467      */
2468     result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2469                        va_arg(param, char *));
2470     break;
2471
2472   case CURLOPT_RTSP_STREAM_URI:
2473     /*
2474      * Set the Stream URI for the RTSP request. Unless the request is
2475      * for generic server options, the application will need to set this.
2476      */
2477     result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2478                        va_arg(param, char *));
2479     break;
2480
2481   case CURLOPT_RTSP_TRANSPORT:
2482     /*
2483      * The content of the Transport: header for the RTSP request
2484      */
2485     result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2486                        va_arg(param, char *));
2487     break;
2488
2489   case CURLOPT_RTSP_CLIENT_CSEQ:
2490     /*
2491      * Set the CSEQ number to issue for the next RTSP request. Useful if the
2492      * application is resuming a previously broken connection. The CSEQ
2493      * will increment from this new number henceforth.
2494      */
2495     data->state.rtsp_next_client_CSeq = va_arg(param, long);
2496     break;
2497
2498   case CURLOPT_RTSP_SERVER_CSEQ:
2499     /* Same as the above, but for server-initiated requests */
2500     data->state.rtsp_next_client_CSeq = va_arg(param, long);
2501     break;
2502
2503   case CURLOPT_INTERLEAVEDATA:
2504     data->set.rtp_out = va_arg(param, void *);
2505     break;
2506   case CURLOPT_INTERLEAVEFUNCTION:
2507     /* Set the user defined RTP write function */
2508     data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2509     break;
2510
2511   case CURLOPT_WILDCARDMATCH:
2512     data->set.wildcardmatch = (bool)(0 != va_arg(param, long));
2513     break;
2514   case CURLOPT_CHUNK_BGN_FUNCTION:
2515     data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2516     break;
2517   case CURLOPT_CHUNK_END_FUNCTION:
2518     data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2519     break;
2520   case CURLOPT_FNMATCH_FUNCTION:
2521     data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2522     break;
2523   case CURLOPT_CHUNK_DATA:
2524     data->wildcard.customptr = va_arg(param, void *);
2525     break;
2526   case CURLOPT_FNMATCH_DATA:
2527     data->set.fnmatch_data = va_arg(param, void *);
2528     break;
2529   default:
2530     /* unknown tag and its companion, just ignore: */
2531     result = CURLE_FAILED_INIT; /* correct this */
2532     break;
2533   }
2534
2535   return result;
2536 }
2537
2538 static void conn_free(struct connectdata *conn)
2539 {
2540   if(!conn)
2541     return;
2542
2543   /* close the SSL stuff before we close any sockets since they will/may
2544      write to the sockets */
2545   Curl_ssl_close(conn, FIRSTSOCKET);
2546   Curl_ssl_close(conn, SECONDARYSOCKET);
2547
2548   /* close possibly still open sockets */
2549   if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2550     sclose(conn->sock[SECONDARYSOCKET]);
2551   if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2552     sclose(conn->sock[FIRSTSOCKET]);
2553
2554   Curl_safefree(conn->user);
2555   Curl_safefree(conn->passwd);
2556   Curl_safefree(conn->proxyuser);
2557   Curl_safefree(conn->proxypasswd);
2558   Curl_safefree(conn->allocptr.proxyuserpwd);
2559   Curl_safefree(conn->allocptr.uagent);
2560   Curl_safefree(conn->allocptr.userpwd);
2561   Curl_safefree(conn->allocptr.accept_encoding);
2562   Curl_safefree(conn->allocptr.rangeline);
2563   Curl_safefree(conn->allocptr.ref);
2564   Curl_safefree(conn->allocptr.host);
2565   Curl_safefree(conn->allocptr.cookiehost);
2566   Curl_safefree(conn->allocptr.rtsp_transport);
2567   Curl_safefree(conn->trailer);
2568   Curl_safefree(conn->host.rawalloc); /* host name buffer */
2569   Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2570   Curl_safefree(conn->master_buffer);
2571
2572   Curl_llist_destroy(conn->send_pipe, NULL);
2573   Curl_llist_destroy(conn->recv_pipe, NULL);
2574   Curl_llist_destroy(conn->pend_pipe, NULL);
2575   Curl_llist_destroy(conn->done_pipe, NULL);
2576
2577   /* possible left-overs from the async name resolvers */
2578 #if defined(CURLRES_THREADED)
2579   Curl_destroy_thread_data(&conn->async);
2580 #elif defined(CURLRES_ASYNCH)
2581   Curl_safefree(conn->async.hostname);
2582   Curl_safefree(conn->async.os_specific);
2583 #endif
2584
2585   Curl_free_ssl_config(&conn->ssl_config);
2586
2587   free(conn); /* free all the connection oriented data */
2588 }
2589
2590 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2591 {
2592   struct SessionHandle *data;
2593   if(!conn)
2594     return CURLE_OK; /* this is closed and fine already */
2595   data = conn->data;
2596
2597   if(!data) {
2598     DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
2599     return CURLE_OK;
2600   }
2601
2602   if(conn->dns_entry != NULL) {
2603     Curl_resolv_unlock(data, conn->dns_entry);
2604     conn->dns_entry = NULL;
2605   }
2606
2607 #if defined(DEBUGBUILD) && defined(AGGRESIVE_TEST)
2608   /* scan for DNS cache entries still marked as in use */
2609   Curl_hash_apply(data->hostcache,
2610                   NULL, Curl_scan_cache_used);
2611 #endif
2612
2613   Curl_hostcache_prune(data); /* kill old DNS cache entries */
2614
2615   {
2616     int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
2617     int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
2618
2619     /* Authentication data is a mix of connection-related and sessionhandle-
2620        related stuff. NTLM is connection-related so when we close the shop
2621        we shall forget. */
2622
2623     if (has_host_ntlm) {
2624       data->state.authhost.done = FALSE;
2625       data->state.authhost.picked =
2626         data->state.authhost.want;
2627     }
2628
2629     if (has_proxy_ntlm) {
2630       data->state.authproxy.done = FALSE;
2631       data->state.authproxy.picked =
2632         data->state.authproxy.want;
2633     }
2634
2635     if (has_host_ntlm || has_proxy_ntlm) {
2636       data->state.authproblem = FALSE;
2637
2638       Curl_ntlm_cleanup(conn);
2639     }
2640   }
2641
2642   /* Cleanup possible redirect junk */
2643   if(data->req.newurl) {
2644     free(data->req.newurl);
2645     data->req.newurl = NULL;
2646   }
2647
2648   if(conn->handler->disconnect)
2649     /* This is set if protocol-specific cleanups should be made */
2650     conn->handler->disconnect(conn, dead_connection);
2651
2652   if(-1 != conn->connectindex) {
2653     /* unlink ourselves! */
2654     infof(data, "Closing connection #%ld\n", conn->connectindex);
2655     if(data->state.connc)
2656       /* only clear the table entry if we still know in which cache we
2657          used to be in */
2658       data->state.connc->connects[conn->connectindex] = NULL;
2659   }
2660
2661 #ifdef USE_LIBIDN
2662   if(conn->host.encalloc)
2663     idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
2664                                       with idn_free() since this was allocated
2665                                       by libidn */
2666   if(conn->proxy.encalloc)
2667     idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
2668                                        freed with idn_free() since this was
2669                                        allocated by libidn */
2670 #endif
2671
2672   Curl_ssl_close(conn, FIRSTSOCKET);
2673
2674   /* Indicate to all handles on the pipe that we're dead */
2675   if(Curl_isPipeliningEnabled(data)) {
2676     signalPipeClose(conn->send_pipe, TRUE);
2677     signalPipeClose(conn->recv_pipe, TRUE);
2678     signalPipeClose(conn->pend_pipe, TRUE);
2679     signalPipeClose(conn->done_pipe, FALSE);
2680   }
2681
2682   conn_free(conn);
2683   data->state.current_conn = NULL;
2684
2685   return CURLE_OK;
2686 }
2687
2688 /*
2689  * This function should return TRUE if the socket is to be assumed to
2690  * be dead. Most commonly this happens when the server has closed the
2691  * connection due to inactivity.
2692  */
2693 static bool SocketIsDead(curl_socket_t sock)
2694 {
2695   int sval;
2696   bool ret_val = TRUE;
2697
2698   sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2699   if(sval == 0)
2700     /* timeout */
2701     ret_val = FALSE;
2702
2703   return ret_val;
2704 }
2705
2706 #ifndef CURL_DISABLE_RTSP
2707 /*
2708  * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
2709  * want to block the application forever while receiving a stream. Therefore,
2710  * we cannot assume that an RTSP socket is dead just because it is readable.
2711  *
2712  * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
2713  * and distinguish between closed and data.
2714  */
2715 static bool RTSPConnIsDead(struct connectdata *check)
2716 {
2717   int sval;
2718   bool ret_val = TRUE;
2719
2720   sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
2721   if(sval == 0) {
2722     /* timeout */
2723     ret_val = FALSE;
2724   }
2725   else if (sval & CURL_CSELECT_ERR) {
2726     /* socket is in an error state */
2727     ret_val = TRUE;
2728   }
2729   else if (sval & CURL_CSELECT_IN) {
2730     /* readable with no error. could be closed or could be alive */
2731     curl_socket_t connectinfo =
2732       Curl_getconnectinfo(check->data, &check);
2733     if(connectinfo != CURL_SOCKET_BAD)
2734       ret_val = FALSE;
2735   }
2736
2737   return ret_val;
2738 }
2739 #endif /* CURL_DISABLE_RTSP */
2740
2741 static bool IsPipeliningPossible(const struct SessionHandle *handle,
2742                                  const struct connectdata *conn)
2743 {
2744   if((conn->handler->protocol & PROT_HTTP) &&
2745      handle->multi && Curl_multi_canPipeline(handle->multi) &&
2746      (handle->set.httpreq == HTTPREQ_GET ||
2747       handle->set.httpreq == HTTPREQ_HEAD) &&
2748      handle->set.httpversion != CURL_HTTP_VERSION_1_0)
2749     return TRUE;
2750
2751   return FALSE;
2752 }
2753
2754 bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
2755 {
2756   if(handle->multi && Curl_multi_canPipeline(handle->multi))
2757     return TRUE;
2758
2759   return FALSE;
2760 }
2761
2762 CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
2763                                   struct curl_llist *pipeline)
2764 {
2765   if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
2766     return CURLE_OUT_OF_MEMORY;
2767   return CURLE_OK;
2768 }
2769
2770 int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
2771                                   struct curl_llist *pipeline)
2772 {
2773   struct curl_llist_element *curr;
2774
2775   curr = pipeline->head;
2776   while(curr) {
2777     if(curr->ptr == handle) {
2778       Curl_llist_remove(pipeline, curr, NULL);
2779       return 1; /* we removed a handle */
2780     }
2781     curr = curr->next;
2782   }
2783
2784   return 0;
2785 }
2786
2787 #if 0 /* this code is saved here as it is useful for debugging purposes */
2788 static void Curl_printPipeline(struct curl_llist *pipeline)
2789 {
2790   struct curl_llist_element *curr;
2791
2792   curr = pipeline->head;
2793   while(curr) {
2794     struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2795     infof(data, "Handle in pipeline: %s\n", data->state.path);
2796     curr = curr->next;
2797   }
2798 }
2799 #endif
2800
2801 static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
2802 {
2803   struct curl_llist_element *curr = pipeline->head;
2804   if(curr) {
2805     return (struct SessionHandle *) curr->ptr;
2806   }
2807
2808   return NULL;
2809 }
2810
2811 /* remove the specified connection from all (possible) pipelines and related
2812    queues */
2813 void Curl_getoff_all_pipelines(struct SessionHandle *data,
2814                                struct connectdata *conn)
2815 {
2816   bool recv_head = (bool)(conn->readchannel_inuse &&
2817     (gethandleathead(conn->recv_pipe) == data));
2818
2819   bool send_head = (bool)(conn->writechannel_inuse &&
2820     (gethandleathead(conn->send_pipe) == data));
2821
2822   if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2823     conn->readchannel_inuse = FALSE;
2824   if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2825     conn->writechannel_inuse = FALSE;
2826   Curl_removeHandleFromPipeline(data, conn->pend_pipe);
2827   Curl_removeHandleFromPipeline(data, conn->done_pipe);
2828 }
2829
2830 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2831 {
2832   struct curl_llist_element *curr;
2833
2834   if(!pipeline)
2835     return;
2836
2837   curr = pipeline->head;
2838   while(curr) {
2839     struct curl_llist_element *next = curr->next;
2840     struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2841
2842 #ifdef DEBUGBUILD /* debug-only code */
2843     if(data->magic != CURLEASY_MAGIC_NUMBER) {
2844       /* MAJOR BADNESS */
2845       infof(data, "signalPipeClose() found BAAD easy handle\n");
2846     }
2847 #endif
2848
2849     if (pipe_broke)
2850        data->state.pipe_broke = TRUE;
2851     Curl_multi_handlePipeBreak(data);
2852     Curl_llist_remove(pipeline, curr, NULL);
2853     curr = next;
2854   }
2855 }
2856
2857
2858 /*
2859  * Given one filled in connection struct (named needle), this function should
2860  * detect if there already is one that has all the significant details
2861  * exactly the same and thus should be used instead.
2862  *
2863  * If there is a match, this function returns TRUE - and has marked the
2864  * connection as 'in-use'. It must later be called with ConnectionDone() to
2865  * return back to 'idle' (unused) state.
2866  */
2867 static bool
2868 ConnectionExists(struct SessionHandle *data,
2869                  struct connectdata *needle,
2870                  struct connectdata **usethis)
2871 {
2872   long i;
2873   struct connectdata *check;
2874   bool canPipeline = IsPipeliningPossible(data, needle);
2875
2876   for(i=0; i< data->state.connc->num; i++) {
2877     bool match = FALSE;
2878     size_t pipeLen = 0;
2879     /*
2880      * Note that if we use a HTTP proxy, we check connections to that
2881      * proxy and not to the actual remote server.
2882      */
2883     check = data->state.connc->connects[i];
2884     if(!check)
2885       /* NULL pointer means not filled-in entry */
2886       continue;
2887
2888     pipeLen = check->send_pipe->size + check->recv_pipe->size;
2889
2890     if(check->connectindex == -1) {
2891       check->connectindex = i; /* Set this appropriately since it might have
2892                                   been set to -1 when the easy was removed
2893                                   from the multi */
2894     }
2895
2896     if(!pipeLen && !check->inuse) {
2897       /* The check for a dead socket makes sense only if there are no
2898          handles in pipeline and the connection isn't already marked in
2899          use */
2900       bool dead;
2901 #ifndef CURL_DISABLE_RTSP
2902       if(check->protocol & PROT_RTSP)
2903         /* RTSP is a special case due to RTP interleaving */
2904         dead = RTSPConnIsDead(check);
2905       else
2906 #endif /*CURL_DISABLE_RTSP*/
2907         dead = SocketIsDead(check->sock[FIRSTSOCKET]);
2908
2909       if(dead) {
2910         check->data = data;
2911         infof(data, "Connection #%ld seems to be dead!\n", i);
2912
2913         /* disconnect resources */
2914         Curl_disconnect(check, /* dead_connection */ TRUE);
2915         data->state.connc->connects[i]=NULL; /* nothing here */
2916
2917         continue;
2918       }
2919     }
2920
2921     if(canPipeline) {
2922       /* Make sure the pipe has only GET requests */
2923       struct SessionHandle* sh = gethandleathead(check->send_pipe);
2924       struct SessionHandle* rh = gethandleathead(check->recv_pipe);
2925       if(sh) {
2926         if(!IsPipeliningPossible(sh, check))
2927           continue;
2928       }
2929       else if(rh) {
2930         if(!IsPipeliningPossible(rh, check))
2931           continue;
2932       }
2933
2934 #ifdef DEBUGBUILD
2935       if(pipeLen > MAX_PIPELINE_LENGTH) {
2936         infof(data, "BAD! Connection #%ld has too big pipeline!\n",
2937               check->connectindex);
2938       }
2939 #endif
2940     }
2941     else {
2942       if(pipeLen > 0) {
2943         /* can only happen within multi handles, and means that another easy
2944            handle is using this connection */
2945         continue;
2946       }
2947
2948 #ifdef CURLRES_ASYNCH
2949       /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
2950          completed yet and until then we don't re-use this connection */
2951       if(!check->ip_addr_str[0]) {
2952         infof(data,
2953               "Connection #%ld hasn't finished name resolve, can't reuse\n",
2954               check->connectindex);
2955         continue;
2956       }
2957 #endif
2958
2959       if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) || check->bits.close) {
2960         /* Don't pick a connection that hasn't connected yet or that is going
2961            to get closed. */
2962         infof(data, "Connection #%ld isn't open enough, can't reuse\n",
2963               check->connectindex);
2964 #ifdef DEBUGBUILD
2965         if(check->recv_pipe->size > 0) {
2966           infof(data, "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
2967                 check->connectindex);
2968         }
2969 #endif
2970         continue;
2971       }
2972     }
2973
2974     if((needle->protocol&PROT_SSL) != (check->protocol&PROT_SSL))
2975       /* don't do mixed SSL and non-SSL connections */
2976       continue;
2977
2978     if(needle->protocol&PROT_SSL) {
2979       if((data->set.ssl.verifypeer != check->verifypeer) ||
2980          (data->set.ssl.verifyhost != check->verifyhost))
2981         continue;
2982     }
2983
2984     if(needle->bits.proxy != check->bits.proxy)
2985       /* don't do mixed proxy and non-proxy connections */
2986       continue;
2987
2988     if(!canPipeline && check->inuse)
2989       /* this request can't be pipelined but the checked connection is already
2990          in use so we skip it */
2991       continue;
2992
2993     if(!needle->bits.httpproxy || needle->protocol&PROT_SSL ||
2994        (needle->bits.httpproxy && check->bits.httpproxy &&
2995         needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
2996         Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
2997         (needle->port == check->port))) {
2998       /* The requested connection does not use a HTTP proxy or it uses SSL or
2999          it is a non-SSL protocol tunneled over the same http proxy name and
3000          port number */
3001
3002       if(Curl_raw_equal(needle->handler->scheme, check->handler->scheme) &&
3003          Curl_raw_equal(needle->host.name, check->host.name) &&
3004          (needle->remote_port == check->remote_port) ) {
3005         if(needle->protocol & PROT_SSL) {
3006           /* This is SSL, verify that we're using the same
3007              ssl options as well */
3008           if(!Curl_ssl_config_matches(&needle->ssl_config,
3009                                       &check->ssl_config)) {
3010             DEBUGF(infof(data,
3011                          "Connection #%ld has different SSL parameters, "
3012                          "can't reuse\n",
3013                          check->connectindex));
3014             continue;
3015           }
3016           else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3017             DEBUGF(infof(data,
3018                          "Connection #%ld has not started ssl connect, "
3019                          "can't reuse\n",
3020                          check->connectindex));
3021             continue;
3022           }
3023         }
3024         if((needle->protocol & PROT_FTP) ||
3025            ((needle->protocol & PROT_HTTP) &&
3026             (data->state.authhost.want==CURLAUTH_NTLM))) {
3027           /* This is FTP or HTTP+NTLM, verify that we're using the same name
3028              and password as well */
3029           if(!strequal(needle->user, check->user) ||
3030              !strequal(needle->passwd, check->passwd)) {
3031             /* one of them was different */
3032             continue;
3033           }
3034         }
3035         match = TRUE;
3036       }
3037     }
3038     else { /* The requested needle connection is using a proxy,
3039               is the checked one using the same host, port and type? */
3040       if(check->bits.proxy &&
3041          (needle->proxytype == check->proxytype) &&
3042          (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
3043          Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3044          needle->port == check->port) {
3045         /* This is the same proxy connection, use it! */
3046         match = TRUE;
3047       }
3048     }
3049
3050     if(match) {
3051       check->inuse = TRUE; /* mark this as being in use so that no other
3052                               handle in a multi stack may nick it */
3053
3054       *usethis = check;
3055       return TRUE; /* yes, we found one to use! */
3056     }
3057   }
3058
3059   return FALSE; /* no matching connecting exists */
3060 }
3061
3062
3063
3064 /*
3065  * This function frees/closes a connection in the connection cache. This
3066  * should take the previously set policy into account when deciding which
3067  * of the connections to kill.
3068  */
3069 static long
3070 ConnectionKillOne(struct SessionHandle *data)
3071 {
3072   long i;
3073   struct connectdata *conn;
3074   long highscore=-1;
3075   long connindex=-1;
3076   long score;
3077   struct timeval now;
3078
3079   now = Curl_tvnow();
3080
3081   for(i=0; data->state.connc && (i< data->state.connc->num); i++) {
3082     conn = data->state.connc->connects[i];
3083
3084     if(!conn || conn->inuse)
3085       continue;
3086
3087     /* Set higher score for the age passed since the connection was used */
3088     score = Curl_tvdiff(now, conn->now);
3089
3090     if(score > highscore) {
3091       highscore = score;
3092       connindex = i;
3093     }
3094   }
3095   if(connindex >= 0) {
3096     /* Set the connection's owner correctly */
3097     conn = data->state.connc->connects[connindex];
3098     conn->data = data;
3099
3100     /* the winner gets the honour of being disconnected */
3101     (void)Curl_disconnect(conn, /* dead_connection */ FALSE);
3102
3103     /* clean the array entry */
3104     data->state.connc->connects[connindex] = NULL;
3105   }
3106
3107   return connindex; /* return the available index or -1 */
3108 }
3109
3110 /* this connection can now be marked 'idle' */
3111 static void
3112 ConnectionDone(struct connectdata *conn)
3113 {
3114   conn->inuse = FALSE;
3115 }
3116
3117 /*
3118  * The given input connection struct pointer is to be stored. If the "cache"
3119  * is already full, we must clean out the most suitable using the previously
3120  * set policy.
3121  *
3122  * The given connection should be unique. That must've been checked prior to
3123  * this call.
3124  */
3125 static long
3126 ConnectionStore(struct SessionHandle *data,
3127                 struct connectdata *conn)
3128 {
3129   long i;
3130   for(i=0; i< data->state.connc->num; i++) {
3131     if(!data->state.connc->connects[i])
3132       break;
3133   }
3134   if(i == data->state.connc->num) {
3135     /* there was no room available, kill one */
3136     i = ConnectionKillOne(data);
3137     if(-1 != i)
3138       infof(data, "Connection (#%ld) was killed to make room (holds %ld)\n",
3139             i, data->state.connc->num);
3140     else
3141       infof(data, "This connection did not fit in the connection cache\n");
3142   }
3143
3144   conn->connectindex = i; /* Make the child know where the pointer to this
3145                              particular data is stored. But note that this -1
3146                              if this is not within the cache and this is
3147                              probably not checked for everywhere (yet). */
3148   conn->inuse = TRUE;
3149   if(-1 != i) {
3150     /* Only do this if a true index was returned, if -1 was returned there
3151        is no room in the cache for an unknown reason and we cannot store
3152        this there.
3153
3154        TODO: make sure we really can work with more handles than positions in
3155        the cache, or possibly we should (allow to automatically) resize the
3156        connection cache when we add more easy handles to a multi handle!
3157     */
3158     data->state.connc->connects[i] = conn; /* fill in this */
3159     conn->data = data;
3160   }
3161
3162   return i;
3163 }
3164
3165 /* after a TCP connection to the proxy has been verified, this function does
3166    the next magic step.
3167
3168    Note: this function's sub-functions call failf()
3169
3170 */
3171 CURLcode Curl_connected_proxy(struct connectdata *conn)
3172 {
3173   CURLcode result = CURLE_OK;
3174   struct SessionHandle *data = conn->data;
3175
3176   switch(data->set.proxytype) {
3177 #ifndef CURL_DISABLE_PROXY
3178   case CURLPROXY_SOCKS5:
3179   case CURLPROXY_SOCKS5_HOSTNAME:
3180     result = Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3181                          conn->host.name, conn->remote_port,
3182                          FIRSTSOCKET, conn);
3183     break;
3184   case CURLPROXY_SOCKS4:
3185     result = Curl_SOCKS4(conn->proxyuser, conn->host.name,
3186                          conn->remote_port, FIRSTSOCKET, conn, FALSE);
3187     break;
3188   case CURLPROXY_SOCKS4A:
3189     result = Curl_SOCKS4(conn->proxyuser, conn->host.name,
3190                          conn->remote_port, FIRSTSOCKET, conn, TRUE);
3191     break;
3192 #endif /* CURL_DISABLE_PROXY */
3193   case CURLPROXY_HTTP:
3194   case CURLPROXY_HTTP_1_0:
3195     /* do nothing here. handled later. */
3196     break;
3197   default:
3198     break;
3199   } /* switch proxytype */
3200
3201   return result;
3202 }
3203
3204 static CURLcode ConnectPlease(struct SessionHandle *data,
3205                               struct connectdata *conn,
3206                               bool *connected)
3207 {
3208   CURLcode result;
3209   Curl_addrinfo *addr;
3210 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3211   char *hostname = conn->bits.proxy?conn->proxy.name:conn->host.name;
3212
3213   infof(data, "About to connect() to %s%s port %ld (#%ld)\n",
3214         conn->bits.proxy?"proxy ":"",
3215         hostname, conn->port, conn->connectindex);
3216 #else
3217   (void)data;
3218 #endif
3219
3220   /*************************************************************
3221    * Connect to server/proxy
3222    *************************************************************/
3223   result= Curl_connecthost(conn,
3224                            conn->dns_entry,
3225                            &conn->sock[FIRSTSOCKET],
3226                            &addr,
3227                            connected);
3228   if(CURLE_OK == result) {
3229     /* All is cool, we store the current information */
3230     conn->ip_addr = addr;
3231
3232     if(*connected)
3233       result = Curl_connected_proxy(conn);
3234   }
3235
3236   if(result)
3237     *connected = FALSE; /* mark it as not connected */
3238
3239   return result;
3240 }
3241
3242 /*
3243  * verboseconnect() displays verbose information after a connect
3244  */
3245 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3246 void Curl_verboseconnect(struct connectdata *conn)
3247 {
3248   if(conn->data->set.verbose)
3249     infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3250           conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3251           conn->ip_addr_str, conn->port, conn->connectindex);
3252 }
3253 #endif
3254
3255 int Curl_protocol_getsock(struct connectdata *conn,
3256                           curl_socket_t *socks,
3257                           int numsocks)
3258 {
3259   if(conn->handler->proto_getsock)
3260     return conn->handler->proto_getsock(conn, socks, numsocks);
3261   return GETSOCK_BLANK;
3262 }
3263
3264 int Curl_doing_getsock(struct connectdata *conn,
3265                        curl_socket_t *socks,
3266                        int numsocks)
3267 {
3268   if(conn && conn->handler->doing_getsock)
3269     return conn->handler->doing_getsock(conn, socks, numsocks);
3270   return GETSOCK_BLANK;
3271 }
3272
3273 /*
3274  * We are doing protocol-specific connecting and this is being called over and
3275  * over from the multi interface until the connection phase is done on
3276  * protocol layer.
3277  */
3278
3279 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3280                                   bool *done)
3281 {
3282   CURLcode result=CURLE_OK;
3283
3284   if(conn && conn->handler->connecting) {
3285     *done = FALSE;
3286     result = conn->handler->connecting(conn, done);
3287   }
3288   else
3289     *done = TRUE;
3290
3291   return result;
3292 }
3293
3294 /*
3295  * We are DOING this is being called over and over from the multi interface
3296  * until the DOING phase is done on protocol layer.
3297  */
3298
3299 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3300 {
3301   CURLcode result=CURLE_OK;
3302
3303   if(conn && conn->handler->doing) {
3304     *done = FALSE;
3305     result = conn->handler->doing(conn, done);
3306   }
3307   else
3308     *done = TRUE;
3309
3310   return result;
3311 }
3312
3313 /*
3314  * We have discovered that the TCP connection has been successful, we can now
3315  * proceed with some action.
3316  *
3317  */
3318 CURLcode Curl_protocol_connect(struct connectdata *conn,
3319                                bool *protocol_done)
3320 {
3321   CURLcode result=CURLE_OK;
3322   struct SessionHandle *data = conn->data;
3323
3324   *protocol_done = FALSE;
3325
3326   if(conn->bits.tcpconnect && conn->bits.protoconnstart) {
3327     /* We already are connected, get back. This may happen when the connect
3328        worked fine in the first call, like when we connect to a local server
3329        or proxy. Note that we don't know if the protocol is actually done.
3330
3331        Unless this protocol doesn't have any protocol-connect callback, as
3332        then we know we're done. */
3333     if(!conn->handler->connecting)
3334       *protocol_done = TRUE;
3335
3336     return CURLE_OK;
3337   }
3338
3339   if(!conn->bits.tcpconnect) {
3340
3341     Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
3342     Curl_verboseconnect(conn);
3343   }
3344
3345   if(!conn->bits.protoconnstart) {
3346     if(conn->handler->connect_it) {
3347       /* is there a protocol-specific connect() procedure? */
3348
3349       /* Set start time here for timeout purposes in the connect procedure, it
3350          is later set again for the progress meter purpose */
3351       conn->now = Curl_tvnow();
3352
3353       /* Call the protocol-specific connect function */
3354       result = conn->handler->connect_it(conn, protocol_done);
3355     }
3356     else
3357       *protocol_done = TRUE;
3358
3359     /* it has started, possibly even completed but that knowledge isn't stored
3360        in this bit! */
3361     if(!result)
3362       conn->bits.protoconnstart = TRUE;
3363   }
3364
3365   return result; /* pass back status */
3366 }
3367
3368 /*
3369  * Helpers for IDNA convertions.
3370  */
3371 #ifdef USE_LIBIDN
3372 static bool is_ASCII_name(const char *hostname)
3373 {
3374   const unsigned char *ch = (const unsigned char*)hostname;
3375
3376   while(*ch) {
3377     if(*ch++ & 0x80)
3378       return FALSE;
3379   }
3380   return TRUE;
3381 }
3382
3383 /*
3384  * Check if characters in hostname is allowed in Top Level Domain.
3385  */
3386 static bool tld_check_name(struct SessionHandle *data,
3387                            const char *ace_hostname)
3388 {
3389   size_t err_pos;
3390   char *uc_name = NULL;
3391   int rc;
3392 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3393   const char *tld_errmsg = "<no msg>";
3394 #else
3395   (void)data;
3396 #endif
3397
3398   /* Convert (and downcase) ACE-name back into locale's character set */
3399   rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3400   if(rc != IDNA_SUCCESS)
3401     return FALSE;
3402
3403   rc = tld_check_lz(uc_name, &err_pos, NULL);
3404 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3405 #ifdef HAVE_TLD_STRERROR
3406   if(rc != TLD_SUCCESS)
3407     tld_errmsg = tld_strerror((Tld_rc)rc);
3408 #endif
3409   if(rc == TLD_INVALID)
3410     infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
3411           tld_errmsg, err_pos, uc_name[err_pos],
3412           uc_name[err_pos] & 255);
3413   else if(rc != TLD_SUCCESS)
3414     infof(data, "WARNING: TLD check for %s failed; %s\n",
3415           uc_name, tld_errmsg);
3416 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3417   if(uc_name)
3418      idn_free(uc_name);
3419   if(rc != TLD_SUCCESS)
3420     return FALSE;
3421
3422   return TRUE;
3423 }
3424 #endif
3425
3426 /*
3427  * Perform any necessary IDN conversion of hostname
3428  */
3429 static void fix_hostname(struct SessionHandle *data,
3430                          struct connectdata *conn, struct hostname *host)
3431 {
3432 #ifndef USE_LIBIDN
3433   (void)data;
3434   (void)conn;
3435 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3436   (void)conn;
3437 #endif
3438
3439   /* set the name we use to display the host name */
3440   host->dispname = host->name;
3441
3442 #ifdef USE_LIBIDN
3443   /*************************************************************
3444    * Check name for non-ASCII and convert hostname to ACE form.
3445    *************************************************************/
3446   if(!is_ASCII_name(host->name) &&
3447       stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3448     char *ace_hostname = NULL;
3449     int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3450     infof (data, "Input domain encoded as `%s'\n",
3451            stringprep_locale_charset ());
3452     if(rc != IDNA_SUCCESS)
3453       infof(data, "Failed to convert %s to ACE; %s\n",
3454             host->name, Curl_idn_strerror(conn,rc));
3455     else {
3456       /* tld_check_name() displays a warning if the host name contains
3457          "illegal" characters for this TLD */
3458       (void)tld_check_name(data, ace_hostname);
3459
3460       host->encalloc = ace_hostname;
3461       /* change the name pointer to point to the encoded hostname */
3462       host->name = host->encalloc;
3463     }
3464   }
3465 #endif
3466 }
3467
3468 static void llist_dtor(void *user, void *element)
3469 {
3470   (void)user;
3471   (void)element;
3472   /* Do nothing */
3473 }
3474
3475 /*
3476  * Allocate and initialize a new connectdata object.
3477  */
3478 static struct connectdata *allocate_conn(struct SessionHandle *data)
3479 {
3480   struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3481   if(!conn)
3482     return NULL;
3483
3484   conn->handler = &Curl_handler_dummy;  /* Be sure we have a handler defined
3485                                            already from start to avoid NULL
3486                                            situations and checks */
3487
3488   /* and we setup a few fields in case we end up actually using this struct */
3489
3490   conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD;     /* no file descriptor */
3491   conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3492   conn->connectindex = -1;    /* no index */
3493   conn->port = -1; /* unknown at this point */
3494
3495   /* Default protocol-independent behavior doesn't support persistent
3496      connections, so we set this to force-close. Protocols that support
3497      this need to set this to FALSE in their "curl_do" functions. */
3498   conn->bits.close = TRUE;
3499
3500   /* Store creation time to help future close decision making */
3501   conn->created = Curl_tvnow();
3502
3503   conn->data = data; /* Setup the association between this connection
3504                         and the SessionHandle */
3505
3506   conn->proxytype = data->set.proxytype; /* type */
3507
3508 #ifdef CURL_DISABLE_PROXY
3509
3510   conn->bits.proxy = FALSE;
3511   conn->bits.httpproxy = FALSE;
3512   conn->bits.proxy_user_passwd = FALSE;
3513   conn->bits.tunnel_proxy = FALSE;
3514
3515 #else /* CURL_DISABLE_PROXY */
3516
3517   conn->bits.proxy = (bool)(data->set.str[STRING_PROXY] &&
3518                             *data->set.str[STRING_PROXY]);
3519   conn->bits.httpproxy = (bool)(conn->bits.proxy &&
3520                                 (conn->proxytype == CURLPROXY_HTTP ||
3521                                  conn->proxytype == CURLPROXY_HTTP_1_0));
3522   conn->bits.proxy_user_passwd =
3523     (bool)(NULL != data->set.str[STRING_PROXYUSERNAME]);
3524   conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3525
3526 #endif /* CURL_DISABLE_PROXY */
3527
3528   conn->bits.user_passwd = (bool)(NULL != data->set.str[STRING_USERNAME]);
3529   conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3530   conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3531
3532   conn->verifypeer = data->set.ssl.verifypeer;
3533   conn->verifyhost = data->set.ssl.verifyhost;
3534
3535   conn->ip_version = data->set.ipver;
3536
3537   if(data->multi && Curl_multi_canPipeline(data->multi) &&
3538       !conn->master_buffer) {
3539     /* Allocate master_buffer to be used for pipelining */
3540     conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3541     if(!conn->master_buffer)
3542       goto error;
3543   }
3544
3545   /* Initialize the pipeline lists */
3546   conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3547   conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3548   conn->pend_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3549   conn->done_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3550   if(!conn->send_pipe || !conn->recv_pipe || !conn->pend_pipe ||
3551      !conn->done_pipe)
3552     goto error;
3553
3554 #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI)
3555   conn->data_prot = PROT_CLEAR;
3556 #endif
3557
3558   return conn;
3559   error:
3560   Curl_llist_destroy(conn->send_pipe, NULL);
3561   Curl_llist_destroy(conn->recv_pipe, NULL);
3562   Curl_llist_destroy(conn->pend_pipe, NULL);
3563   Curl_llist_destroy(conn->done_pipe, NULL);
3564   Curl_safefree(conn->master_buffer);
3565   Curl_safefree(conn);
3566   return NULL;
3567 }
3568
3569 static CURLcode findprotocol(struct SessionHandle *data,
3570                              struct connectdata *conn,
3571                              const char *protostr)
3572 {
3573   const struct Curl_handler * const *pp;
3574   const struct Curl_handler *p;
3575
3576   /* Scan protocol handler table and match against 'protostr' to set a few
3577      variables based on the URL. Now that the handler may be changed later
3578      when the protocol specific setup function is called. */
3579   for (pp = protocols; (p = *pp) != NULL; pp++) {
3580     if(Curl_raw_equal(p->scheme, protostr)) {
3581       /* Protocol found in table. Check if allowed */
3582       if(!(data->set.allowed_protocols & p->protocol))
3583         /* nope, get out */
3584         break;
3585
3586       /* it is allowed for "normal" request, now do an extra check if this is
3587          the result of a redirect */
3588       if(data->state.this_is_a_follow &&
3589          !(data->set.redir_protocols & p->protocol))
3590         /* nope, get out */
3591         break;
3592
3593       /* Perform setup complement if some. */
3594       conn->handler = p;
3595       conn->protocol |= p->protocol;
3596
3597       /* 'port' and 'remote_port' are set in setup_connection_internals() */
3598       return CURLE_OK;
3599     }
3600   }
3601
3602
3603   /* The protocol was not found in the table, but we don't have to assign it
3604      to anything since it is already assigned to a dummy-struct in the
3605      create_conn() function when the connectdata struct is allocated. */
3606   failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
3607         protostr);
3608
3609   return CURLE_UNSUPPORTED_PROTOCOL;
3610 }
3611
3612 /*
3613  * Parse URL and fill in the relevant members of the connection struct.
3614  */
3615 static CURLcode parseurlandfillconn(struct SessionHandle *data,
3616                                     struct connectdata *conn,
3617                                     bool *prot_missing)
3618 {
3619   char *at;
3620   char *fragment;
3621   char *path = data->state.path;
3622   char *query;
3623   int rc;
3624   char protobuf[16];
3625   const char *protop;
3626
3627   *prot_missing = FALSE;
3628
3629   /*************************************************************
3630    * Parse the URL.
3631    *
3632    * We need to parse the url even when using the proxy, because we will need
3633    * the hostname and port in case we are trying to SSL connect through the
3634    * proxy -- and we don't know if we will need to use SSL until we parse the
3635    * url ...
3636    ************************************************************/
3637   if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
3638                   protobuf, path)) &&
3639      Curl_raw_equal(protobuf, "file")) {
3640     if(path[0] == '/' && path[1] == '/') {
3641       /* Allow omitted hostname (e.g. file:/<path>).  This is not strictly
3642        * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
3643        * file://localhost/<path> is similar to how other schemes treat missing
3644        * hostnames.  See RFC 1808. */
3645
3646       /* This cannot be done with strcpy() in a portable manner, since the
3647          memory areas overlap! */
3648       memmove(path, path + 2, strlen(path + 2)+1);
3649     }
3650     /*
3651      * we deal with file://<host>/<path> differently since it supports no
3652      * hostname other than "localhost" and "127.0.0.1", which is unique among
3653      * the URL protocols specified in RFC 1738
3654      */
3655     if(path[0] != '/') {
3656       /* the URL included a host name, we ignore host names in file:// URLs
3657          as the standards don't define what to do with them */
3658       char *ptr=strchr(path, '/');
3659       if(ptr) {
3660         /* there was a slash present
3661
3662            RFC1738 (section 3.1, page 5) says:
3663
3664            The rest of the locator consists of data specific to the scheme,
3665            and is known as the "url-path". It supplies the details of how the
3666            specified resource can be accessed. Note that the "/" between the
3667            host (or port) and the url-path is NOT part of the url-path.
3668
3669            As most agents use file://localhost/foo to get '/foo' although the
3670            slash preceding foo is a separator and not a slash for the path,
3671            a URL as file://localhost//foo must be valid as well, to refer to
3672            the same file with an absolute path.
3673         */
3674
3675         if(ptr[1] && ('/' == ptr[1]))
3676           /* if there was two slashes, we skip the first one as that is then
3677              used truly as a separator */
3678           ptr++;
3679
3680         /* This cannot be made with strcpy, as the memory chunks overlap! */
3681         memmove(path, ptr, strlen(ptr)+1);
3682       }
3683     }
3684
3685     protop = "file"; /* protocol string */
3686   }
3687   else {
3688     /* clear path */
3689     path[0]=0;
3690
3691     if(2 > sscanf(data->change.url,
3692                    "%15[^\n:]://%[^\n/?]%[^\n]",
3693                    protobuf,
3694                    conn->host.name, path)) {
3695
3696       /*
3697        * The URL was badly formatted, let's try the browser-style _without_
3698        * protocol specified like 'http://'.
3699        */
3700       rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
3701       if(1 > rc) {
3702         /*
3703          * We couldn't even get this format.
3704          * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
3705          * assigned, but the return value is EOF!
3706          */
3707 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
3708         if (!(rc == -1 && *conn->host.name))
3709 #endif
3710         {
3711           failf(data, "<url> malformed");
3712           return CURLE_URL_MALFORMAT;
3713         }
3714       }
3715
3716       /*
3717        * Since there was no protocol part specified, we guess what protocol it
3718        * is based on the first letters of the server name.
3719        */
3720
3721       /* Note: if you add a new protocol, please update the list in
3722        * lib/version.c too! */
3723
3724       if(checkprefix("FTP.", conn->host.name))
3725         protop = "ftp";
3726       else if(checkprefix("DICT.", conn->host.name))
3727         protop = "DICT";
3728       else if(checkprefix("LDAP.", conn->host.name))
3729         protop = "LDAP";
3730       else if(checkprefix("IMAP.", conn->host.name))
3731         protop = "IMAP";
3732       else {
3733         protop = "http";
3734       }
3735
3736       *prot_missing = TRUE; /* not given in URL */
3737     }
3738     else
3739       protop = protobuf;
3740   }
3741
3742   /* We search for '?' in the host name (but only on the right side of a
3743    * @-letter to allow ?-letters in username and password) to handle things
3744    * like http://example.com?param= (notice the missing '/').
3745    */
3746   at = strchr(conn->host.name, '@');
3747   if(at)
3748     query = strchr(at+1, '?');
3749   else
3750     query = strchr(conn->host.name, '?');
3751
3752   if(query) {
3753     /* We must insert a slash before the '?'-letter in the URL. If the URL had
3754        a slash after the '?', that is where the path currently begins and the
3755        '?string' is still part of the host name.
3756
3757        We must move the trailing part from the host name and put it first in
3758        the path. And have it all prefixed with a slash.
3759     */
3760
3761     size_t hostlen = strlen(query);
3762     size_t pathlen = strlen(path);
3763
3764     /* move the existing path plus the zero byte forward, to make room for
3765        the host-name part */
3766     memmove(path+hostlen+1, path, pathlen+1);
3767
3768      /* now copy the trailing host part in front of the existing path */
3769     memcpy(path+1, query, hostlen);
3770
3771     path[0]='/'; /* prepend the missing slash */
3772
3773     *query=0; /* now cut off the hostname at the ? */
3774   }
3775   else if(!path[0]) {
3776     /* if there's no path set, use a single slash */
3777     strcpy(path, "/");
3778   }
3779
3780   /* If the URL is malformatted (missing a '/' after hostname before path) we
3781    * insert a slash here. The only letter except '/' we accept to start a path
3782    * is '?'.
3783    */
3784   if(path[0] == '?') {
3785     /* We need this function to deal with overlapping memory areas. We know
3786        that the memory area 'path' points to is 'urllen' bytes big and that
3787        is bigger than the path. Use +1 to move the zero byte too. */
3788     memmove(&path[1], path, strlen(path)+1);
3789     path[0] = '/';
3790   }
3791
3792   if (conn->host.name[0] == '[') {
3793     /* This looks like an IPv6 address literal.  See if there is an address
3794        scope.  */
3795     char *percent = strstr (conn->host.name, "%25");
3796     if (percent) {
3797       char *endp;
3798       unsigned long scope = strtoul (percent + 3, &endp, 10);
3799       if (*endp == ']') {
3800         /* The address scope was well formed.  Knock it out of the
3801            hostname. */
3802         memmove(percent, endp, strlen(endp)+1);
3803         if (!data->state.this_is_a_follow)
3804           /* Don't honour a scope given in a Location: header */
3805           conn->scope = (unsigned int)scope;
3806       } else
3807         infof(data, "Invalid IPv6 address format\n");
3808     }
3809   }
3810
3811   if(data->set.scope)
3812     /* Override any scope that was set above.  */
3813     conn->scope = data->set.scope;
3814
3815   /* Remove the fragment part of the path. Per RFC 2396, this is always the
3816      last part of the URI. We are looking for the first '#' so that we deal
3817      gracefully with non conformant URI such as http://example.com#foo#bar. */
3818   fragment = strchr(path, '#');
3819   if(fragment)
3820     *fragment = 0;
3821
3822   /*
3823    * So if the URL was A://B/C#D,
3824    *   protop is A
3825    *   conn->host.name is B
3826    *   data->state.path is /C
3827    */
3828
3829   return findprotocol(data, conn, protop);
3830 }
3831
3832 /*
3833  * If we're doing a resumed transfer, we need to setup our stuff
3834  * properly.
3835  */
3836 static CURLcode setup_range(struct SessionHandle *data)
3837 {
3838   struct UrlState *s = &data->state;
3839   s->resume_from = data->set.set_resume_from;
3840   if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
3841     if(s->rangestringalloc)
3842       free(s->range);
3843
3844     if(s->resume_from)
3845       s->range = aprintf("%" FORMAT_OFF_TU "-", s->resume_from);
3846     else
3847       s->range = strdup(data->set.str[STRING_SET_RANGE]);
3848
3849     s->rangestringalloc = (bool)(s->range?TRUE:FALSE);
3850
3851     if(!s->range)
3852       return CURLE_OUT_OF_MEMORY;
3853
3854     /* tell ourselves to fetch this range */
3855     s->use_range = TRUE;        /* enable range download */
3856   }
3857   else
3858     s->use_range = FALSE; /* disable range download */
3859
3860   return CURLE_OK;
3861 }
3862
3863
3864 /***************************************************************
3865 * Setup connection internals specific to the requested protocol.
3866 * This MUST get called after proxy magic has been figured out.
3867 ***************************************************************/
3868 static CURLcode setup_connection_internals(struct connectdata *conn)
3869 {
3870   const struct Curl_handler * p;
3871   CURLcode result;
3872
3873   conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
3874
3875   /* Scan protocol handler table. */
3876
3877   /* Perform setup complement if some. */
3878   p = conn->handler;
3879
3880   if(p->setup_connection) {
3881     result = (*p->setup_connection)(conn);
3882
3883     if(result != CURLE_OK)
3884       return result;
3885
3886     p = conn->handler;              /* May have changed. */
3887   }
3888
3889   if(conn->port < 0)
3890     /* we check for -1 here since if proxy was detected already, this
3891        was very likely already set to the proxy port */
3892     conn->port = p->defport;
3893   conn->remote_port = (unsigned short)p->defport;
3894   conn->protocol |= p->protocol;
3895
3896   return CURLE_OK;
3897 }
3898
3899 #ifndef CURL_DISABLE_PROXY
3900 /****************************************************************
3901 * Checks if the host is in the noproxy list. returns true if it matches
3902 * and therefore the proxy should NOT be used.
3903 ****************************************************************/
3904 static bool check_noproxy(const char* name, const char* no_proxy)
3905 {
3906   /* no_proxy=domain1.dom,host.domain2.dom
3907    *   (a comma-separated list of hosts which should
3908    *   not be proxied, or an asterisk to override
3909    *   all proxy variables)
3910    */
3911   size_t tok_start;
3912   size_t tok_end;
3913   const char* separator = ", ";
3914   size_t no_proxy_len;
3915   size_t namelen;
3916   char *endptr;
3917
3918   if(no_proxy && no_proxy[0]) {
3919     if(Curl_raw_equal("*", no_proxy)) {
3920       return TRUE;
3921     }
3922
3923     /* NO_PROXY was specified and it wasn't just an asterisk */
3924
3925     no_proxy_len = strlen(no_proxy);
3926     endptr = strchr(name, ':');
3927     if(endptr)
3928       namelen = endptr - name;
3929     else
3930       namelen = strlen(name);
3931
3932     for (tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
3933       while (tok_start < no_proxy_len &&
3934              strchr(separator, no_proxy[tok_start]) != NULL) {
3935         /* Look for the beginning of the token. */
3936         ++tok_start;
3937       }
3938
3939       if(tok_start == no_proxy_len)
3940         break; /* It was all trailing separator chars, no more tokens. */
3941
3942       for (tok_end = tok_start; tok_end < no_proxy_len &&
3943              strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end) {
3944         /* Look for the end of the token. */
3945       }
3946
3947       /* To match previous behaviour, where it was necessary to specify
3948        * ".local.com" to prevent matching "notlocal.com", we will leave
3949        * the '.' off.
3950        */
3951       if(no_proxy[tok_start] == '.')
3952         ++tok_start;
3953
3954       if((tok_end - tok_start) <= namelen) {
3955         /* Match the last part of the name to the domain we are checking. */
3956         const char *checkn = name + namelen - (tok_end - tok_start);
3957         if(Curl_raw_nequal(no_proxy + tok_start, checkn,
3958                            tok_end - tok_start)) {
3959           if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
3960             /* We either have an exact match, or the previous character is a .
3961              * so it is within the same domain, so no proxy for this host.
3962              */
3963             return TRUE;
3964           }
3965         }
3966       } /* if((tok_end - tok_start) <= namelen) */
3967     } /* for (tok_start = 0; tok_start < no_proxy_len;
3968          tok_start = tok_end + 1) */
3969   } /* NO_PROXY was specified and it wasn't just an asterisk */
3970
3971   return FALSE;
3972 }
3973
3974 /****************************************************************
3975 * Detect what (if any) proxy to use. Remember that this selects a host
3976 * name and is not limited to HTTP proxies only.
3977 * The returned pointer must be freed by the caller (unless NULL)
3978 ****************************************************************/
3979 static char *detect_proxy(struct connectdata *conn)
3980 {
3981   char *proxy = NULL;
3982
3983 #ifndef CURL_DISABLE_HTTP
3984   /* If proxy was not specified, we check for default proxy environment
3985    * variables, to enable i.e Lynx compliance:
3986    *
3987    * http_proxy=http://some.server.dom:port/
3988    * https_proxy=http://some.server.dom:port/
3989    * ftp_proxy=http://some.server.dom:port/
3990    * no_proxy=domain1.dom,host.domain2.dom
3991    *   (a comma-separated list of hosts which should
3992    *   not be proxied, or an asterisk to override
3993    *   all proxy variables)
3994    * all_proxy=http://some.server.dom:port/
3995    *   (seems to exist for the CERN www lib. Probably
3996    *   the first to check for.)
3997    *
3998    * For compatibility, the all-uppercase versions of these variables are
3999    * checked if the lowercase versions don't exist.
4000    */
4001   char *no_proxy=NULL;
4002   char proxy_env[128];
4003
4004   no_proxy=curl_getenv("no_proxy");
4005   if(!no_proxy)
4006     no_proxy=curl_getenv("NO_PROXY");
4007
4008   if(!check_noproxy(conn->host.name, no_proxy)) {
4009     /* It was not listed as without proxy */
4010     const char *protop = conn->handler->scheme;
4011     char *envp = proxy_env;
4012     char *prox;
4013
4014     /* Now, build <protocol>_proxy and check for such a one to use */
4015     while(*protop)
4016       *envp++ = (char)tolower((int)*protop++);
4017
4018     /* append _proxy */
4019     strcpy(envp, "_proxy");
4020
4021     /* read the protocol proxy: */
4022     prox=curl_getenv(proxy_env);
4023
4024     /*
4025      * We don't try the uppercase version of HTTP_PROXY because of
4026      * security reasons:
4027      *
4028      * When curl is used in a webserver application
4029      * environment (cgi or php), this environment variable can
4030      * be controlled by the web server user by setting the
4031      * http header 'Proxy:' to some value.
4032      *
4033      * This can cause 'internal' http/ftp requests to be
4034      * arbitrarily redirected by any external attacker.
4035      */
4036     if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4037       /* There was no lowercase variable, try the uppercase version: */
4038       Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4039       prox=curl_getenv(proxy_env);
4040     }
4041
4042     if(prox && *prox) { /* don't count "" strings */
4043       proxy = prox; /* use this */
4044     }
4045     else {
4046       proxy = curl_getenv("all_proxy"); /* default proxy to use */
4047       if(!proxy)
4048         proxy=curl_getenv("ALL_PROXY");
4049     }
4050   } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4051        non-proxy */
4052   if(no_proxy)
4053     free(no_proxy);
4054
4055 #else /* !CURL_DISABLE_HTTP */
4056
4057   (void)conn;
4058 #endif /* CURL_DISABLE_HTTP */
4059
4060   return proxy;
4061 }
4062
4063 /*
4064  * If this is supposed to use a proxy, we need to figure out the proxy
4065  * host name, so that we can re-use an existing connection
4066  * that may exist registered to the same proxy host.
4067  * proxy will be freed before this function returns.
4068  */
4069 static CURLcode parse_proxy(struct SessionHandle *data,
4070                             struct connectdata *conn, char *proxy)
4071 {
4072   char *prox_portno;
4073   char *endofprot;
4074
4075   /* We use 'proxyptr' to point to the proxy name from now on... */
4076   char *proxyptr;
4077   char *portptr;
4078   char *atsign;
4079
4080   /* We do the proxy host string parsing here. We want the host name and the
4081    * port name. Accept a protocol:// prefix, even though it should just be
4082    * ignored.
4083    */
4084
4085   /* Skip the protocol part if present */
4086   endofprot = strstr(proxy, "://");
4087   if(endofprot)
4088     proxyptr = endofprot+3;
4089   else
4090     proxyptr = proxy;
4091
4092   /* Is there a username and password given in this proxy url? */
4093   atsign = strchr(proxyptr, '@');
4094   if(atsign) {
4095     char proxyuser[MAX_CURL_USER_LENGTH];
4096     char proxypasswd[MAX_CURL_PASSWORD_LENGTH];
4097     proxypasswd[0] = 0;
4098
4099     if(1 <= sscanf(proxyptr,
4100                    "%" MAX_CURL_USER_LENGTH_TXT"[^:@]:"
4101                    "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4102                    proxyuser, proxypasswd)) {
4103       CURLcode res = CURLE_OK;
4104
4105       /* found user and password, rip them out.  note that we are
4106          unescaping them, as there is otherwise no way to have a
4107          username or password with reserved characters like ':' in
4108          them. */
4109       Curl_safefree(conn->proxyuser);
4110       conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4111
4112       if(!conn->proxyuser)
4113         res = CURLE_OUT_OF_MEMORY;
4114       else {
4115         Curl_safefree(conn->proxypasswd);
4116         conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4117
4118         if(!conn->proxypasswd)
4119           res = CURLE_OUT_OF_MEMORY;
4120       }
4121
4122       if(CURLE_OK == res) {
4123         conn->bits.proxy_user_passwd = TRUE; /* enable it */
4124         atsign = strdup(atsign+1); /* the right side of the @-letter */
4125
4126         if(atsign) {
4127           free(proxy); /* free the former proxy string */
4128           proxy = proxyptr = atsign; /* now use this instead */
4129         }
4130         else
4131           res = CURLE_OUT_OF_MEMORY;
4132       }
4133
4134       if(res) {
4135         free(proxy); /* free the allocated proxy string */
4136         return res;
4137       }
4138     }
4139   }
4140
4141   /* start scanning for port number at this point */
4142   portptr = proxyptr;
4143
4144   /* detect and extract RFC2732-style IPv6-addresses */
4145   if(*proxyptr == '[') {
4146     char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4147     while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
4148                    (*ptr == '.')))
4149       ptr++;
4150     if(*ptr == ']') {
4151       /* yeps, it ended nicely with a bracket as well */
4152       *ptr++ = 0;
4153     } else
4154       infof(data, "Invalid IPv6 address format\n");
4155     portptr = ptr;
4156     /* Note that if this didn't end with a bracket, we still advanced the
4157      * proxyptr first, but I can't see anything wrong with that as no host
4158      * name nor a numeric can legally start with a bracket.
4159      */
4160   }
4161
4162   /* Get port number off proxy.server.com:1080 */
4163   prox_portno = strchr(portptr, ':');
4164   if(prox_portno) {
4165     *prox_portno = 0x0; /* cut off number from host name */
4166     prox_portno ++;
4167     /* now set the local port number */
4168     conn->port = strtol(prox_portno, NULL, 10);
4169   }
4170   else {
4171     /* without a port number after the host name, some people seem to use
4172        a slash so we strip everything from the first slash */
4173     atsign = strchr(proxyptr, '/');
4174     if(atsign)
4175       *atsign = 0x0; /* cut off path part from host name */
4176
4177     if(data->set.proxyport)
4178       /* None given in the proxy string, then get the default one if it is
4179          given */
4180       conn->port = data->set.proxyport;
4181   }
4182
4183   /* now, clone the cleaned proxy host name */
4184   conn->proxy.rawalloc = strdup(proxyptr);
4185   conn->proxy.name = conn->proxy.rawalloc;
4186
4187   free(proxy);
4188   if(!conn->proxy.rawalloc)
4189     return CURLE_OUT_OF_MEMORY;
4190
4191   return CURLE_OK;
4192 }
4193
4194 /*
4195  * Extract the user and password from the authentication string
4196  */
4197 static CURLcode parse_proxy_auth(struct SessionHandle *data,
4198                                  struct connectdata *conn)
4199 {
4200   char proxyuser[MAX_CURL_USER_LENGTH]="";
4201   char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4202
4203   if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4204     strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4205             MAX_CURL_USER_LENGTH);
4206     proxyuser[MAX_CURL_USER_LENGTH-1] = '\0';   /*To be on safe side*/
4207   }
4208   if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4209     strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4210             MAX_CURL_PASSWORD_LENGTH);
4211     proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4212   }
4213
4214   conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4215   if(!conn->proxyuser)
4216     return CURLE_OUT_OF_MEMORY;
4217
4218   conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4219   if(!conn->proxypasswd)
4220     return CURLE_OUT_OF_MEMORY;
4221
4222   return CURLE_OK;
4223 }
4224 #endif /* CURL_DISABLE_PROXY */
4225
4226 /*
4227  *
4228  * Parse a user name and password in the URL and strip it out of the host name
4229  *
4230  * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4231  *         conn->host.name
4232  *
4233  * Outputs: (almost :- all currently undefined)
4234  *          conn->bits.user_passwd  - non-zero if non-default passwords exist
4235  *          user                    - non-zero length if defined
4236  *          passwd                  -   ditto
4237  *          conn->host.name         - remove user name and password
4238  */
4239 static CURLcode parse_url_userpass(struct SessionHandle *data,
4240                                    struct connectdata *conn,
4241                                    char *user, char *passwd)
4242 {
4243   /* At this point, we're hoping all the other special cases have
4244    * been taken care of, so conn->host.name is at most
4245    *    [user[:password]]@]hostname
4246    *
4247    * We need somewhere to put the embedded details, so do that first.
4248    */
4249
4250   char *ptr=strchr(conn->host.name, '@');
4251   char *userpass = conn->host.name;
4252
4253   user[0] =0;   /* to make everything well-defined */
4254   passwd[0]=0;
4255
4256   /* We will now try to extract the
4257    * possible user+password pair in a string like:
4258    * ftp://user:password@ftp.my.site:8021/README */
4259   if(ptr != NULL) {
4260     /* there's a user+password given here, to the left of the @ */
4261
4262     conn->host.name = ++ptr;
4263
4264     /* So the hostname is sane.  Only bother interpreting the
4265      * results if we could care.  It could still be wasted
4266      * work because it might be overtaken by the programmatically
4267      * set user/passwd, but doing that first adds more cases here :-(
4268      */
4269
4270     conn->bits.userpwd_in_url = TRUE;
4271     if(data->set.use_netrc != CURL_NETRC_REQUIRED) {
4272       /* We could use the one in the URL */
4273
4274       conn->bits.user_passwd = TRUE; /* enable user+password */
4275
4276       if(*userpass != ':') {
4277         /* the name is given, get user+password */
4278         sscanf(userpass, "%" MAX_CURL_USER_LENGTH_TXT "[^:@]:"
4279                "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4280                user, passwd);
4281       }
4282       else
4283         /* no name given, get the password only */
4284         sscanf(userpass, ":%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]", passwd);
4285
4286       if(user[0]) {
4287         char *newname=curl_easy_unescape(data, user, 0, NULL);
4288         if(!newname)
4289           return CURLE_OUT_OF_MEMORY;
4290         if(strlen(newname) < MAX_CURL_USER_LENGTH)
4291           strcpy(user, newname);
4292
4293         /* if the new name is longer than accepted, then just use
4294            the unconverted name, it'll be wrong but what the heck */
4295         free(newname);
4296       }
4297       if(passwd[0]) {
4298         /* we have a password found in the URL, decode it! */
4299         char *newpasswd=curl_easy_unescape(data, passwd, 0, NULL);
4300         if(!newpasswd)
4301           return CURLE_OUT_OF_MEMORY;
4302         if(strlen(newpasswd) < MAX_CURL_PASSWORD_LENGTH)
4303           strcpy(passwd, newpasswd);
4304
4305         free(newpasswd);
4306       }
4307     }
4308   }
4309   return CURLE_OK;
4310 }
4311
4312 /*************************************************************
4313  * Figure out the remote port number and fix it in the URL
4314  *
4315  * No matter if we use a proxy or not, we have to figure out the remote
4316  * port number of various reasons.
4317  *
4318  * To be able to detect port number flawlessly, we must not confuse them
4319  * IPv6-specified addresses in the [0::1] style. (RFC2732)
4320  *
4321  * The conn->host.name is currently [user:passwd@]host[:port] where host
4322  * could be a hostname, IPv4 address or IPv6 address.
4323  *
4324  * The port number embedded in the URL is replaced, if necessary.
4325  *************************************************************/
4326 static CURLcode parse_remote_port(struct SessionHandle *data,
4327                                   struct connectdata *conn)
4328 {
4329   char *portptr;
4330   char endbracket;
4331
4332   /* Note that at this point, the IPv6 address cannot contain any scope
4333      suffix as that has already been removed in the parseurlandfillconn()
4334      function */
4335   if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
4336                   &endbracket)) &&
4337      (']' == endbracket)) {
4338     /* this is a RFC2732-style specified IP-address */
4339     conn->bits.ipv6_ip = TRUE;
4340
4341     conn->host.name++; /* skip over the starting bracket */
4342     portptr = strchr(conn->host.name, ']');
4343     if(portptr) {
4344       *portptr++ = '\0'; /* zero terminate, killing the bracket */
4345       if(':' != *portptr)
4346         portptr = NULL; /* no port number available */
4347     }
4348   }
4349   else
4350     portptr = strrchr(conn->host.name, ':');
4351
4352   if(data->set.use_port && data->state.allow_port) {
4353     /* if set, we use this and ignore the port possibly given in the URL */
4354     conn->remote_port = (unsigned short)data->set.use_port;
4355     if(portptr)
4356       *portptr = '\0'; /* cut off the name there anyway - if there was a port
4357                       number - since the port number is to be ignored! */
4358     if(conn->bits.httpproxy) {
4359       /* we need to create new URL with the new port number */
4360       char *url;
4361       char type[12]="";
4362
4363       if(conn->bits.type_set)
4364         snprintf(type, sizeof(type), ";type=%c",
4365                  data->set.prefer_ascii?'A':
4366                  (data->set.ftp_list_only?'D':'I'));
4367
4368       /*
4369        * This synthesized URL isn't always right--suffixes like ;type=A are
4370        * stripped off. It would be better to work directly from the original
4371        * URL and simply replace the port part of it.
4372        */
4373       url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->handler->scheme,
4374                     conn->bits.ipv6_ip?"[":"", conn->host.name,
4375                     conn->bits.ipv6_ip?"]":"", conn->remote_port,
4376                     data->state.slash_removed?"/":"", data->state.path,
4377                     type);
4378       if(!url)
4379         return CURLE_OUT_OF_MEMORY;
4380
4381       if(data->change.url_alloc)
4382         free(data->change.url);
4383
4384       data->change.url = url;
4385       data->change.url_alloc = TRUE;
4386     }
4387   }
4388   else if(portptr) {
4389     /* no CURLOPT_PORT given, extract the one from the URL */
4390
4391     char *rest;
4392     unsigned long port;
4393
4394     port=strtoul(portptr+1, &rest, 10);  /* Port number must be decimal */
4395
4396     if(rest != (portptr+1) && *rest == '\0') {
4397       /* The colon really did have only digits after it,
4398        * so it is either a port number or a mistake */
4399
4400       if(port > 0xffff) {   /* Single unix standard says port numbers are
4401                               * 16 bits long */
4402         failf(data, "Port number too large: %lu", port);
4403         return CURLE_URL_MALFORMAT;
4404       }
4405
4406       *portptr = '\0'; /* cut off the name there */
4407       conn->remote_port = curlx_ultous(port);
4408     }
4409     else if(!port)
4410       /* Browser behavior adaptation. If there's a colon with no digits after,
4411          just cut off the name there which makes us ignore the colon and just
4412          use the default port. Firefox and Chrome both do that. */
4413       *portptr = '\0';
4414   }
4415   return CURLE_OK;
4416 }
4417
4418 /*
4419  * Override a user name and password from the URL with that in the
4420  * CURLOPT_USERPWD option or a .netrc file, if applicable.
4421  */
4422 static void override_userpass(struct SessionHandle *data,
4423                               struct connectdata *conn,
4424                               char *user, char *passwd)
4425 {
4426   if(data->set.str[STRING_USERNAME] != NULL) {
4427     strncpy(user, data->set.str[STRING_USERNAME], MAX_CURL_USER_LENGTH);
4428     user[MAX_CURL_USER_LENGTH-1] = '\0';   /*To be on safe side*/
4429   }
4430   if(data->set.str[STRING_PASSWORD] != NULL) {
4431     strncpy(passwd, data->set.str[STRING_PASSWORD], MAX_CURL_PASSWORD_LENGTH);
4432     passwd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4433   }
4434
4435   conn->bits.netrc = FALSE;
4436   if(data->set.use_netrc != CURL_NETRC_IGNORED) {
4437     if(Curl_parsenetrc(conn->host.name,
4438                        user, passwd,
4439                        data->set.str[STRING_NETRC_FILE])) {
4440       infof(data, "Couldn't find host %s in the "
4441             DOT_CHAR "netrc file; using defaults\n",
4442             conn->host.name);
4443     }
4444     else {
4445       /* set bits.netrc TRUE to remember that we got the name from a .netrc
4446          file, so that it is safe to use even if we followed a Location: to a
4447          different host or similar. */
4448       conn->bits.netrc = TRUE;
4449
4450       conn->bits.user_passwd = TRUE; /* enable user+password */
4451     }
4452   }
4453 }
4454
4455 /*
4456  * Set password so it's available in the connection.
4457  */
4458 static CURLcode set_userpass(struct connectdata *conn,
4459                              const char *user, const char *passwd)
4460 {
4461   /* If our protocol needs a password and we have none, use the defaults */
4462   if( (conn->protocol & (PROT_FTP|PROT_IMAP)) &&
4463        !conn->bits.user_passwd) {
4464
4465     conn->user = strdup(CURL_DEFAULT_USER);
4466     if(conn->user)
4467       conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
4468     else
4469       conn->passwd = NULL;
4470     /* This is the default password, so DON'T set conn->bits.user_passwd */
4471   }
4472   else {
4473     /* store user + password, zero-length if not set */
4474     conn->user = strdup(user);
4475     if(conn->user)
4476       conn->passwd = strdup(passwd);
4477     else
4478       conn->passwd = NULL;
4479   }
4480   if(!conn->user || !conn->passwd)
4481     return CURLE_OUT_OF_MEMORY;
4482
4483   return CURLE_OK;
4484 }
4485
4486 /*************************************************************
4487  * Resolve the address of the server or proxy
4488  *************************************************************/
4489 static CURLcode resolve_server(struct SessionHandle *data,
4490                                struct connectdata *conn,
4491                                bool *async)
4492 {
4493   CURLcode result=CURLE_OK;
4494   long timeout_ms = Curl_timeleft(conn, NULL, TRUE);
4495
4496   /*************************************************************
4497    * Resolve the name of the server or proxy
4498    *************************************************************/
4499   if(conn->bits.reuse) {
4500     /* We're reusing the connection - no need to resolve anything */
4501     *async = FALSE;
4502
4503     if(conn->bits.proxy)
4504       fix_hostname(data, conn, &conn->host);
4505   }
4506   else {
4507     /* this is a fresh connect */
4508     int rc;
4509     struct Curl_dns_entry *hostaddr;
4510
4511     /* set a pointer to the hostname we display */
4512     fix_hostname(data, conn, &conn->host);
4513
4514     if(!conn->proxy.name || !*conn->proxy.name) {
4515       /* If not connecting via a proxy, extract the port from the URL, if it is
4516        * there, thus overriding any defaults that might have been set above. */
4517       conn->port =  conn->remote_port; /* it is the same port */
4518
4519       /* Resolve target host right on */
4520       rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
4521                                &hostaddr, timeout_ms);
4522       if(rc == CURLRESOLV_PENDING)
4523         *async = TRUE;
4524
4525       else if (rc == CURLRESOLV_TIMEDOUT)
4526         result = CURLE_OPERATION_TIMEDOUT;
4527
4528       else if(!hostaddr) {
4529         failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
4530         result =  CURLE_COULDNT_RESOLVE_HOST;
4531         /* don't return yet, we need to clean up the timeout first */
4532       }
4533     }
4534     else {
4535       /* This is a proxy that hasn't been resolved yet. */
4536
4537       /* IDN-fix the proxy name */
4538       fix_hostname(data, conn, &conn->proxy);
4539
4540       /* resolve proxy */
4541       rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
4542                                &hostaddr, timeout_ms);
4543
4544       if(rc == CURLRESOLV_PENDING)
4545         *async = TRUE;
4546
4547       else if (rc == CURLRESOLV_TIMEDOUT)
4548         result = CURLE_OPERATION_TIMEDOUT;
4549
4550       else if(!hostaddr) {
4551         failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
4552         result = CURLE_COULDNT_RESOLVE_PROXY;
4553         /* don't return yet, we need to clean up the timeout first */
4554       }
4555     }
4556     DEBUGASSERT(conn->dns_entry == NULL);
4557     conn->dns_entry = hostaddr;
4558   }
4559
4560   return result;
4561 }
4562
4563 /*
4564  * Cleanup the connection just allocated before we can move along and use the
4565  * previously existing one.  All relevant data is copied over and old_conn is
4566  * ready for freeing once this function returns.
4567  */
4568 static void reuse_conn(struct connectdata *old_conn,
4569                        struct connectdata *conn)
4570 {
4571   if(old_conn->proxy.rawalloc)
4572     free(old_conn->proxy.rawalloc);
4573
4574   /* free the SSL config struct from this connection struct as this was
4575      allocated in vain and is targeted for destruction */
4576   Curl_free_ssl_config(&old_conn->ssl_config);
4577
4578   conn->data = old_conn->data;
4579
4580   /* get the user+password information from the old_conn struct since it may
4581    * be new for this request even when we re-use an existing connection */
4582   conn->bits.user_passwd = old_conn->bits.user_passwd;
4583   if(conn->bits.user_passwd) {
4584     /* use the new user name and password though */
4585     Curl_safefree(conn->user);
4586     Curl_safefree(conn->passwd);
4587     conn->user = old_conn->user;
4588     conn->passwd = old_conn->passwd;
4589     old_conn->user = NULL;
4590     old_conn->passwd = NULL;
4591   }
4592
4593   conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
4594   if(conn->bits.proxy_user_passwd) {
4595     /* use the new proxy user name and proxy password though */
4596     Curl_safefree(conn->proxyuser);
4597     Curl_safefree(conn->proxypasswd);
4598     conn->proxyuser = old_conn->proxyuser;
4599     conn->proxypasswd = old_conn->proxypasswd;
4600     old_conn->proxyuser = NULL;
4601     old_conn->proxypasswd = NULL;
4602   }
4603
4604   /* host can change, when doing keepalive with a proxy ! */
4605   if(conn->bits.proxy) {
4606     free(conn->host.rawalloc);
4607     conn->host=old_conn->host;
4608   }
4609   else
4610     free(old_conn->host.rawalloc); /* free the newly allocated name buffer */
4611
4612   /* persist connection info in session handle */
4613   Curl_persistconninfo(conn);
4614
4615   /* re-use init */
4616   conn->bits.reuse = TRUE; /* yes, we're re-using here */
4617
4618   Curl_safefree(old_conn->user);
4619   Curl_safefree(old_conn->passwd);
4620   Curl_safefree(old_conn->proxyuser);
4621   Curl_safefree(old_conn->proxypasswd);
4622   Curl_llist_destroy(old_conn->send_pipe, NULL);
4623   Curl_llist_destroy(old_conn->recv_pipe, NULL);
4624   Curl_llist_destroy(old_conn->pend_pipe, NULL);
4625   Curl_llist_destroy(old_conn->done_pipe, NULL);
4626   Curl_safefree(old_conn->master_buffer);
4627 }
4628
4629 /**
4630  * create_conn() sets up a new connectdata struct, or re-uses an already
4631  * existing one, and resolves host name.
4632  *
4633  * if this function returns CURLE_OK and *async is set to TRUE, the resolve
4634  * response will be coming asynchronously. If *async is FALSE, the name is
4635  * already resolved.
4636  *
4637  * @param data The sessionhandle pointer
4638  * @param in_connect is set to the next connection data pointer
4639  * @param async is set TRUE when an async DNS resolution is pending
4640  * @see setup_conn()
4641  *
4642  * *NOTE* this function assigns the conn->data pointer!
4643  */
4644
4645 static CURLcode create_conn(struct SessionHandle *data,
4646                             struct connectdata **in_connect,
4647                             bool *async)
4648 {
4649   CURLcode result=CURLE_OK;
4650   struct connectdata *conn;
4651   struct connectdata *conn_temp = NULL;
4652   size_t urllen;
4653   char user[MAX_CURL_USER_LENGTH];
4654   char passwd[MAX_CURL_PASSWORD_LENGTH];
4655   bool reuse;
4656   char *proxy = NULL;
4657   bool prot_missing = FALSE;
4658
4659   *async = FALSE;
4660
4661   /*************************************************************
4662    * Check input data
4663    *************************************************************/
4664
4665   if(!data->change.url)
4666     return CURLE_URL_MALFORMAT;
4667
4668   /* First, split up the current URL in parts so that we can use the
4669      parts for checking against the already present connections. In order
4670      to not have to modify everything at once, we allocate a temporary
4671      connection data struct and fill in for comparison purposes. */
4672   conn = allocate_conn(data);
4673
4674   if(!conn)
4675     return CURLE_OUT_OF_MEMORY;
4676
4677   /* We must set the return variable as soon as possible, so that our
4678      parent can cleanup any possible allocs we may have done before
4679      any failure */
4680   *in_connect = conn;
4681
4682   /* This initing continues below, see the comment "Continue connectdata
4683    * initialization here" */
4684
4685   /***********************************************************
4686    * We need to allocate memory to store the path in. We get the size of the
4687    * full URL to be sure, and we need to make it at least 256 bytes since
4688    * other parts of the code will rely on this fact
4689    ***********************************************************/
4690 #define LEAST_PATH_ALLOC 256
4691   urllen=strlen(data->change.url);
4692   if(urllen < LEAST_PATH_ALLOC)
4693     urllen=LEAST_PATH_ALLOC;
4694
4695   /*
4696    * We malloc() the buffers below urllen+2 to make room for to possibilities:
4697    * 1 - an extra terminating zero
4698    * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
4699    */
4700
4701   Curl_safefree(data->state.pathbuffer);
4702   data->state.pathbuffer = malloc(urllen+2);
4703   if(NULL == data->state.pathbuffer)
4704     return CURLE_OUT_OF_MEMORY; /* really bad error */
4705   data->state.path = data->state.pathbuffer;
4706
4707   conn->host.rawalloc = malloc(urllen+2);
4708   if(NULL == conn->host.rawalloc)
4709     return CURLE_OUT_OF_MEMORY;
4710
4711   conn->host.name = conn->host.rawalloc;
4712   conn->host.name[0] = 0;
4713
4714   result = parseurlandfillconn(data, conn, &prot_missing);
4715   if(result != CURLE_OK) {
4716       return result;
4717   }
4718
4719   /*************************************************************
4720    * No protocol part in URL was used, add it!
4721    *************************************************************/
4722   if(prot_missing) {
4723     /* We're guessing prefixes here and if we're told to use a proxy or if
4724        we're gonna follow a Location: later or... then we need the protocol
4725        part added so that we have a valid URL. */
4726     char *reurl;
4727
4728     reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
4729
4730     if(!reurl) {
4731       Curl_safefree(proxy);
4732       return CURLE_OUT_OF_MEMORY;
4733     }
4734
4735     data->change.url = reurl;
4736     data->change.url_alloc = TRUE; /* free this later */
4737   }
4738
4739   /*************************************************************
4740    * Parse a user name and password in the URL and strip it out
4741    * of the host name
4742    *************************************************************/
4743   result = parse_url_userpass(data, conn, user, passwd);
4744   if(result != CURLE_OK)
4745     return result;
4746
4747 #ifndef CURL_DISABLE_PROXY
4748   /*************************************************************
4749    * Extract the user and password from the authentication string
4750    *************************************************************/
4751   if(conn->bits.proxy_user_passwd) {
4752     result = parse_proxy_auth(data, conn);
4753     if(result != CURLE_OK)
4754         return result;
4755   }
4756
4757   /*************************************************************
4758    * Detect what (if any) proxy to use
4759    *************************************************************/
4760   if(data->set.str[STRING_PROXY]) {
4761     proxy = strdup(data->set.str[STRING_PROXY]);
4762     /* if global proxy is set, this is it */
4763     if(NULL == proxy) {
4764       failf(data, "memory shortage");
4765       return CURLE_OUT_OF_MEMORY;
4766     }
4767   }
4768
4769   if(data->set.str[STRING_NOPROXY] &&
4770      check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
4771     if(proxy) {
4772       free(proxy);  /* proxy is in exception list */
4773       proxy = NULL;
4774     }
4775   }
4776   else if(!proxy)
4777     proxy = detect_proxy(conn);
4778
4779   if(proxy && !*proxy) {
4780     free(proxy);  /* Don't bother with an empty proxy string */
4781     proxy = NULL;
4782   }
4783   /* proxy must be freed later unless NULL */
4784   if(proxy) {
4785     long bits = conn->protocol & (PROT_HTTPS|PROT_SSL);
4786
4787     if((conn->proxytype == CURLPROXY_HTTP) ||
4788        (conn->proxytype == CURLPROXY_HTTP_1_0)) {
4789       /* force this connection's protocol to become HTTP */
4790       conn->protocol = PROT_HTTP | bits;
4791       conn->bits.httpproxy = TRUE;
4792     }
4793     conn->bits.proxy = TRUE;
4794   }
4795   else {
4796     /* we aren't using the proxy after all... */
4797     conn->bits.proxy = FALSE;
4798     conn->bits.httpproxy = FALSE;
4799     conn->bits.proxy_user_passwd = FALSE;
4800     conn->bits.tunnel_proxy = FALSE;
4801   }
4802
4803   /***********************************************************************
4804    * If this is supposed to use a proxy, we need to figure out the proxy
4805    * host name, so that we can re-use an existing connection
4806    * that may exist registered to the same proxy host.
4807    ***********************************************************************/
4808   if(proxy) {
4809     result = parse_proxy(data, conn, proxy);
4810     /* parse_proxy has freed the proxy string, so don't try to use it again */
4811     proxy = NULL;
4812     if(result != CURLE_OK)
4813       return result;
4814   }
4815 #endif /* CURL_DISABLE_PROXY */
4816
4817   /*************************************************************
4818    * Setup internals depending on protocol. Needs to be done after
4819    * we figured out what/if proxy to use.
4820    *************************************************************/
4821   result = setup_connection_internals(conn);
4822   if(result != CURLE_OK) {
4823     Curl_safefree(proxy);
4824     return result;
4825   }
4826
4827   conn->recv[FIRSTSOCKET] = Curl_recv_plain;
4828   conn->send[FIRSTSOCKET] = Curl_send_plain;
4829   conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
4830   conn->send[SECONDARYSOCKET] = Curl_send_plain;
4831
4832   /***********************************************************************
4833    * file: is a special case in that it doesn't need a network connection
4834    ***********************************************************************/
4835 #ifndef CURL_DISABLE_FILE
4836   if(conn->protocol & PROT_FILE) {
4837     bool done;
4838     /* this is supposed to be the connect function so we better at least check
4839        that the file is present here! */
4840     DEBUGASSERT(conn->handler->connect_it);
4841     result = conn->handler->connect_it(conn, &done);
4842
4843     /* Setup a "faked" transfer that'll do nothing */
4844     if(CURLE_OK == result) {
4845       conn->data = data;
4846       conn->bits.tcpconnect = TRUE; /* we are "connected */
4847
4848       ConnectionStore(data, conn);
4849
4850       /*
4851        * Setup whatever necessary for a resumed transfer
4852        */
4853       result = setup_range(data);
4854       if(result) {
4855         DEBUGASSERT(conn->handler->done);
4856         /* we ignore the return code for the protocol-specific DONE */
4857         (void)conn->handler->done(conn, result, FALSE);
4858         return result;
4859       }
4860
4861       Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
4862                           -1, NULL); /* no upload */
4863     }
4864
4865     return result;
4866   }
4867 #endif
4868
4869   /*************************************************************
4870    * If the protocol is using SSL and HTTP proxy is used, we set
4871    * the tunnel_proxy bit.
4872    *************************************************************/
4873   if((conn->protocol&PROT_SSL) && conn->bits.httpproxy)
4874     conn->bits.tunnel_proxy = TRUE;
4875
4876   /*************************************************************
4877    * Figure out the remote port number and fix it in the URL
4878    *************************************************************/
4879   result = parse_remote_port(data, conn);
4880   if(result != CURLE_OK)
4881     return result;
4882
4883   /*************************************************************
4884    * Check for an overridden user name and password, then set it
4885    * for use
4886    *************************************************************/
4887   override_userpass(data, conn, user, passwd);
4888   result = set_userpass(conn, user, passwd);
4889   if(result != CURLE_OK)
4890     return result;
4891
4892   /* Get a cloned copy of the SSL config situation stored in the
4893      connection struct. But to get this going nicely, we must first make
4894      sure that the strings in the master copy are pointing to the correct
4895      strings in the session handle strings array!
4896
4897      Keep in mind that the pointers in the master copy are pointing to strings
4898      that will be freed as part of the SessionHandle struct, but all cloned
4899      copies will be separately allocated.
4900   */
4901   data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
4902   data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
4903   data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
4904   data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
4905   data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
4906   data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
4907   data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
4908
4909   if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
4910     return CURLE_OUT_OF_MEMORY;
4911
4912   /*************************************************************
4913    * Check the current list of connections to see if we can
4914    * re-use an already existing one or if we have to create a
4915    * new one.
4916    *************************************************************/
4917
4918   /* reuse_fresh is TRUE if we are told to use a new connection by force, but
4919      we only acknowledge this option if this is not a re-used connection
4920      already (which happens due to follow-location or during a HTTP
4921      authentication phase). */
4922   if(data->set.reuse_fresh && !data->state.this_is_a_follow)
4923     reuse = FALSE;
4924   else
4925     reuse = ConnectionExists(data, conn, &conn_temp);
4926
4927   if(reuse) {
4928     /*
4929      * We already have a connection for this, we got the former connection
4930      * in the conn_temp variable and thus we need to cleanup the one we
4931      * just allocated before we can move along and use the previously
4932      * existing one.
4933      */
4934     reuse_conn(conn, conn_temp);
4935     free(conn);          /* we don't need this anymore */
4936     conn = conn_temp;
4937     *in_connect = conn;
4938     infof(data, "Re-using existing connection! (#%ld) with host %s\n",
4939           conn->connectindex,
4940           conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
4941   }
4942   else {
4943     /*
4944      * This is a brand new connection, so let's store it in the connection
4945      * cache of ours!
4946      */
4947     ConnectionStore(data, conn);
4948   }
4949
4950   /*
4951    * Setup whatever necessary for a resumed transfer
4952    */
4953   result = setup_range(data);
4954   if(result)
4955     return result;
4956
4957   /* Continue connectdata initialization here. */
4958
4959   /*
4960    * Inherit the proper values from the urldata struct AFTER we have arranged
4961    * the persistent connection stuff
4962    */
4963   conn->fread_func = data->set.fread_func;
4964   conn->fread_in = data->set.in;
4965   conn->seek_func = data->set.seek_func;
4966   conn->seek_client = data->set.seek_client;
4967
4968   /*************************************************************
4969    * Resolve the address of the server or proxy
4970    *************************************************************/
4971   result = resolve_server(data, conn, async);
4972
4973   return result;
4974 }
4975
4976 /* setup_conn() is called after the name resolve initiated in
4977  * create_conn() is all done.
4978  *
4979  * setup_conn() also handles reused connections
4980  *
4981  * conn->data MUST already have been setup fine (in create_conn)
4982  */
4983
4984 static CURLcode setup_conn(struct connectdata *conn,
4985                            bool *protocol_done)
4986 {
4987   CURLcode result=CURLE_OK;
4988   struct SessionHandle *data = conn->data;
4989
4990   Curl_pgrsTime(data, TIMER_NAMELOOKUP);
4991
4992   if(conn->protocol & PROT_FILE) {
4993     /* There's nothing in this function to setup if we're only doing
4994        a file:// transfer */
4995     *protocol_done = TRUE;
4996     return result;
4997   }
4998   *protocol_done = FALSE; /* default to not done */
4999
5000   /* set proxy_connect_closed to false unconditionally already here since it
5001      is used strictly to provide extra information to a parent function in the
5002      case of proxy CONNECT failures and we must make sure we don't have it
5003      lingering set from a previous invoke */
5004   conn->bits.proxy_connect_closed = FALSE;
5005
5006   /*
5007    * Set user-agent. Used for HTTP, but since we can attempt to tunnel
5008    * basically anything through a http proxy we can't limit this based on
5009    * protocol.
5010    */
5011   if(data->set.str[STRING_USERAGENT]) {
5012     Curl_safefree(conn->allocptr.uagent);
5013     conn->allocptr.uagent =
5014       aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
5015     if(!conn->allocptr.uagent)
5016       return CURLE_OUT_OF_MEMORY;
5017   }
5018
5019   data->req.headerbytecount = 0;
5020
5021 #ifdef CURL_DO_LINEEND_CONV
5022   data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
5023 #endif /* CURL_DO_LINEEND_CONV */
5024
5025   for(;;) {
5026     /* loop for CURL_SERVER_CLOSED_CONNECTION */
5027
5028     if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
5029       /* Try to connect only if not already connected */
5030       bool connected = FALSE;
5031
5032       result = ConnectPlease(data, conn, &connected);
5033
5034       if(connected) {
5035         result = Curl_protocol_connect(conn, protocol_done);
5036         if(CURLE_OK == result)
5037           conn->bits.tcpconnect = TRUE;
5038       }
5039       else
5040         conn->bits.tcpconnect = FALSE;
5041
5042       /* if the connection was closed by the server while exchanging
5043          authentication informations, retry with the new set
5044          authentication information */
5045       if(conn->bits.proxy_connect_closed) {
5046         /* reset the error buffer */
5047         if(data->set.errorbuffer)
5048           data->set.errorbuffer[0] = '\0';
5049         data->state.errorbuf = FALSE;
5050         continue;
5051       }
5052
5053       if(CURLE_OK != result)
5054         return result;
5055     }
5056     else {
5057       Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
5058       Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
5059       conn->bits.tcpconnect = TRUE;
5060       *protocol_done = TRUE;
5061       Curl_verboseconnect(conn);
5062       Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
5063     }
5064     /* Stop the loop now */
5065     break;
5066   }
5067
5068   conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
5069                                set this here perhaps a second time */
5070
5071 #ifdef __EMX__
5072   /*
5073    * This check is quite a hack. We're calling _fsetmode to fix the problem
5074    * with fwrite converting newline characters (you get mangled text files,
5075    * and corrupted binary files when you download to stdout and redirect it to
5076    * a file).
5077    */
5078
5079   if((data->set.out)->_handle == NULL) {
5080     _fsetmode(stdout, "b");
5081   }
5082 #endif
5083
5084   return result;
5085 }
5086
5087 CURLcode Curl_connect(struct SessionHandle *data,
5088                       struct connectdata **in_connect,
5089                       bool *asyncp,
5090                       bool *protocol_done)
5091 {
5092   CURLcode code;
5093
5094   *asyncp = FALSE; /* assume synchronous resolves by default */
5095
5096   /* call the stuff that needs to be called */
5097   code = create_conn(data, in_connect, asyncp);
5098
5099   if(CURLE_OK == code) {
5100     /* no error */
5101     if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
5102       /* pipelining */
5103       *protocol_done = TRUE;
5104     else if (!*asyncp) {
5105       /* DNS resolution is done: that's either because this is a reused
5106          connection, in which case DNS was unnecessary, or because DNS
5107          really did finish already (synch resolver/fast async resolve) */
5108       code = setup_conn(*in_connect, protocol_done);
5109     }
5110   }
5111
5112   if(code && *in_connect) {
5113     /* We're not allowed to return failure with memory left allocated
5114        in the connectdata struct, free those here */
5115     Curl_disconnect(*in_connect, FALSE); /* close the connection */
5116     *in_connect = NULL;           /* return a NULL */
5117   }
5118
5119   return code;
5120 }
5121
5122 /* Call this function after Curl_connect() has returned async=TRUE and
5123    then a successful name resolve has been received.
5124
5125    Note: this function disconnects and frees the conn data in case of
5126    resolve failure */
5127 CURLcode Curl_async_resolved(struct connectdata *conn,
5128                              bool *protocol_done)
5129 {
5130 #ifdef CURLRES_ASYNCH
5131   CURLcode code;
5132
5133   if(conn->async.dns) {
5134     conn->dns_entry = conn->async.dns;
5135     conn->async.dns = NULL;
5136   }
5137
5138   code = setup_conn(conn, protocol_done);
5139
5140   if(code)
5141     /* We're not allowed to return failure with memory left allocated
5142        in the connectdata struct, free those here */
5143     Curl_disconnect(conn, FALSE); /* close the connection */
5144
5145   return code;
5146 #else
5147   (void)conn;
5148   (void)protocol_done;
5149   return CURLE_OK;
5150 #endif
5151 }
5152
5153
5154 CURLcode Curl_done(struct connectdata **connp,
5155                    CURLcode status,  /* an error if this is called after an
5156                                         error was detected */
5157                    bool premature)
5158 {
5159   CURLcode result;
5160   struct connectdata *conn;
5161   struct SessionHandle *data;
5162
5163   DEBUGASSERT(*connp);
5164
5165   conn = *connp;
5166   data = conn->data;
5167
5168   if(conn->bits.done)
5169     /* Stop if Curl_done() has already been called */
5170     return CURLE_OK;
5171
5172   Curl_getoff_all_pipelines(data, conn);
5173
5174   if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
5175       !data->set.reuse_forbid &&
5176       !conn->bits.close))
5177     /* Stop if pipeline is not empty and we do not have to close
5178        connection. */
5179     return CURLE_OK;
5180
5181   conn->bits.done = TRUE; /* called just now! */
5182
5183   /* Cleanup possible redirect junk */
5184   if(data->req.newurl) {
5185     free(data->req.newurl);
5186     data->req.newurl = NULL;
5187   }
5188   if(data->req.location) {
5189     free(data->req.location);
5190     data->req.location = NULL;
5191   }
5192
5193   if(conn->dns_entry) {
5194     Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
5195     conn->dns_entry = NULL;
5196   }
5197
5198   /* this calls the protocol-specific function pointer previously set */
5199   if(conn->handler->done)
5200     result = conn->handler->done(conn, status, premature);
5201   else
5202     result = CURLE_OK;
5203
5204   Curl_pgrsDone(conn); /* done with the operation */
5205
5206   /* if the transfer was completed in a paused state there can be buffered
5207      data left to write and then kill */
5208   if(data->state.tempwrite) {
5209     free(data->state.tempwrite);
5210     data->state.tempwrite = NULL;
5211   }
5212
5213   /* for ares-using, make sure all possible outstanding requests are properly
5214      cancelled before we proceed */
5215   ares_cancel(data->state.areschannel);
5216
5217   /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
5218      forced us to close this no matter what we think.
5219
5220      if conn->bits.close is TRUE, it means that the connection should be
5221      closed in spite of all our efforts to be nice, due to protocol
5222      restrictions in our or the server's end
5223
5224      if premature is TRUE, it means this connection was said to be DONE before
5225      the entire request operation is complete and thus we can't know in what
5226      state it is for re-using, so we're forced to close it. In a perfect world
5227      we can add code that keep track of if we really must close it here or not,
5228      but currently we have no such detail knowledge.
5229
5230      connectindex == -1 here means that the connection has no spot in the
5231      connection cache and thus we must disconnect it here.
5232   */
5233   if(data->set.reuse_forbid || conn->bits.close || premature ||
5234      (-1 == conn->connectindex)) {
5235     CURLcode res2 = Curl_disconnect(conn, FALSE); /* close the connection */
5236
5237     /* If we had an error already, make sure we return that one. But
5238        if we got a new error, return that. */
5239     if(!result && res2)
5240       result = res2;
5241   }
5242   else {
5243     ConnectionDone(conn); /* the connection is no longer in use */
5244
5245     /* remember the most recently used connection */
5246     data->state.lastconnect = conn->connectindex;
5247
5248     infof(data, "Connection #%ld to host %s left intact\n",
5249           conn->connectindex,
5250           conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
5251   }
5252
5253   *connp = NULL; /* to make the caller of this function better detect that
5254                     this was either closed or handed over to the connection
5255                     cache here, and therefore cannot be used from this point on
5256                  */
5257
5258   return result;
5259 }
5260
5261 /*
5262  * do_init() inits the readwrite session. This is inited each time (in the DO
5263  * function before the protocol-specific DO functions are invoked) for a
5264  * transfer, sometimes multiple times on the same SessionHandle. Make sure
5265  * nothing in here depends on stuff that are setup dynamically for the
5266  * transfer.
5267  */
5268
5269 static CURLcode do_init(struct connectdata *conn)
5270 {
5271   struct SessionHandle *data = conn->data;
5272   struct SingleRequest *k = &data->req;
5273
5274   conn->bits.done = FALSE; /* Curl_done() is not called yet */
5275   conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
5276   data->state.expect100header = FALSE;
5277
5278   if(data->set.opt_no_body)
5279     /* in HTTP lingo, no body means using the HEAD request... */
5280     data->set.httpreq = HTTPREQ_HEAD;
5281   else if(HTTPREQ_HEAD == data->set.httpreq)
5282     /* ... but if unset there really is no perfect method that is the
5283        "opposite" of HEAD but in reality most people probably think GET
5284        then. The important thing is that we can't let it remain HEAD if the
5285        opt_no_body is set FALSE since then we'll behave wrong when getting
5286        HTTP. */
5287     data->set.httpreq = HTTPREQ_GET;
5288
5289   /* NB: the content encoding software depends on this initialization */
5290   Curl_easy_initHandleData(data);
5291
5292   k->start = Curl_tvnow(); /* start time */
5293   k->now = k->start;   /* current time is now */
5294   k->header = TRUE; /* assume header */
5295
5296   k->bytecount = 0;
5297
5298   k->buf = data->state.buffer;
5299   k->uploadbuf = data->state.uploadbuffer;
5300   k->hbufp = data->state.headerbuff;
5301   k->ignorebody=FALSE;
5302
5303   Curl_pgrsTime(data, TIMER_PRETRANSFER);
5304   Curl_speedinit(data);
5305
5306   Curl_pgrsSetUploadCounter(data, 0);
5307   Curl_pgrsSetDownloadCounter(data, 0);
5308
5309   return CURLE_OK;
5310 }
5311
5312 /*
5313  * do_complete is called when the DO actions are complete.
5314  *
5315  * We init chunking and trailer bits to their default values here immediately
5316  * before receiving any header data for the current request in the pipeline.
5317  */
5318 static void do_complete(struct connectdata *conn)
5319 {
5320   conn->data->req.chunk=FALSE;
5321   conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
5322                            conn->sockfd:conn->writesockfd)+1;
5323 }
5324
5325 CURLcode Curl_do(struct connectdata **connp, bool *done)
5326 {
5327   CURLcode result=CURLE_OK;
5328   struct connectdata *conn = *connp;
5329   struct SessionHandle *data = conn->data;
5330
5331   /* setup and init stuff before DO starts, in preparing for the transfer */
5332   do_init(conn);
5333
5334   if(conn->handler->do_it) {
5335     /* generic protocol-specific function pointer set in curl_connect() */
5336     result = conn->handler->do_it(conn, done);
5337
5338     /* This was formerly done in transfer.c, but we better do it here */
5339     if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
5340         /*
5341          * If the connection is using an easy handle, call reconnect
5342          * to re-establish the connection.  Otherwise, let the multi logic
5343          * figure out how to re-establish the connection.
5344          */
5345         if(!data->multi) {
5346           result = Curl_reconnect_request(connp);
5347
5348           if(result == CURLE_OK) {
5349             /* ... finally back to actually retry the DO phase */
5350             result = conn->handler->do_it(conn, done);
5351           }
5352         }
5353         else {
5354           return result;
5355         }
5356     }
5357
5358     if((result == CURLE_OK) && *done)
5359       /* do_complete must be called after the protocol-specific DO function */
5360       do_complete(conn);
5361   }
5362   return result;
5363 }
5364
5365 CURLcode Curl_do_more(struct connectdata *conn)
5366 {
5367   CURLcode result=CURLE_OK;
5368
5369   if(conn->handler->do_more)
5370     result = conn->handler->do_more(conn);
5371
5372   if(result == CURLE_OK)
5373     /* do_complete must be called after the protocol-specific DO function */
5374     do_complete(conn);
5375
5376   return result;
5377 }
5378
5379 /* Called on connect, and if there's already a protocol-specific struct
5380    allocated for a different connection, this frees it that it can be setup
5381    properly later on. */
5382 void Curl_reset_reqproto(struct connectdata *conn)
5383 {
5384   struct SessionHandle *data = conn->data;
5385   if(data->state.proto.generic && data->state.current_conn != conn) {
5386     free(data->state.proto.generic);
5387     data->state.proto.generic = NULL;
5388   }
5389   data->state.current_conn = conn;
5390 }