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