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