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