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