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