Merge tag 'upstream/7.62.0' into tizen_base
[platform/upstream/curl.git] / lib / url.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #ifdef HAVE_NETINET_IN_H
26 #include <netinet/in.h>
27 #endif
28 #ifdef HAVE_NETDB_H
29 #include <netdb.h>
30 #endif
31 #ifdef HAVE_ARPA_INET_H
32 #include <arpa/inet.h>
33 #endif
34 #ifdef HAVE_NET_IF_H
35 #include <net/if.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 #include <sys/ioctl.h>
39 #endif
40
41 #ifdef HAVE_SYS_PARAM_H
42 #include <sys/param.h>
43 #endif
44
45 #ifdef __VMS
46 #include <in.h>
47 #include <inet.h>
48 #endif
49
50 #ifdef HAVE_SYS_UN_H
51 #include <sys/un.h>
52 #endif
53
54 #ifndef HAVE_SOCKET
55 #error "We can't compile without socket() support!"
56 #endif
57
58 #include <limits.h>
59
60 #ifdef USE_LIBIDN2
61 #include <idn2.h>
62
63 #elif defined(USE_WIN32_IDN)
64 /* prototype for curl_win32_idn_to_ascii() */
65 bool curl_win32_idn_to_ascii(const char *in, char **out);
66 #elif defined(USE_ICU_IDNA)
67 #include <unicode/uidna.h>
68 #endif  /* USE_LIBIDN2 */
69
70 #include "urldata.h"
71 #include "netrc.h"
72
73 #include "formdata.h"
74 #include "mime.h"
75 #include "vtls/vtls.h"
76 #include "hostip.h"
77 #include "transfer.h"
78 #include "sendf.h"
79 #include "progress.h"
80 #include "cookie.h"
81 #include "strcase.h"
82 #include "strerror.h"
83 #include "escape.h"
84 #include "strtok.h"
85 #include "share.h"
86 #include "content_encoding.h"
87 #include "http_digest.h"
88 #include "http_negotiate.h"
89 #include "select.h"
90 #include "multiif.h"
91 #include "easyif.h"
92 #include "speedcheck.h"
93 #include "warnless.h"
94 #include "non-ascii.h"
95 #include "inet_pton.h"
96 #include "getinfo.h"
97 #include "urlapi-int.h"
98
99 /* And now for the protocols */
100 #include "ftp.h"
101 #include "dict.h"
102 #include "telnet.h"
103 #include "tftp.h"
104 #include "http.h"
105 #include "http2.h"
106 #include "file.h"
107 #include "curl_ldap.h"
108 #include "ssh.h"
109 #include "imap.h"
110 #include "url.h"
111 #include "connect.h"
112 #include "inet_ntop.h"
113 #include "http_ntlm.h"
114 #include "curl_ntlm_wb.h"
115 #include "socks.h"
116 #include "curl_rtmp.h"
117 #include "gopher.h"
118 #include "http_proxy.h"
119 #include "conncache.h"
120 #include "multihandle.h"
121 #include "pipeline.h"
122 #include "dotdot.h"
123 #include "strdup.h"
124 #include "setopt.h"
125
126 /* The last 3 #include files should be in this order */
127 #include "curl_printf.h"
128 #include "curl_memory.h"
129 #include "memdebug.h"
130
131 #if defined(USE_ICU_IDNA)
132 #define MAX_DOMAIN_NAME_LEN 256
133 #endif  /* USE_ICU_IDNA */
134
135 static void conn_free(struct connectdata *conn);
136 static void free_fixed_hostname(struct hostname *host);
137 static unsigned int get_protocol_family(unsigned int protocol);
138
139 /* Some parts of the code (e.g. chunked encoding) assume this buffer has at
140  * more than just a few bytes to play with. Don't let it become too small or
141  * bad things will happen.
142  */
143 #if READBUFFER_SIZE < READBUFFER_MIN
144 # error READBUFFER_SIZE is too small
145 #endif
146
147
148 /*
149  * Protocol table.
150  */
151
152 static const struct Curl_handler * const protocols[] = {
153
154 #ifndef CURL_DISABLE_HTTP
155   &Curl_handler_http,
156 #endif
157
158 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
159   &Curl_handler_https,
160 #endif
161
162 #ifndef CURL_DISABLE_FTP
163   &Curl_handler_ftp,
164 #endif
165
166 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
167   &Curl_handler_ftps,
168 #endif
169
170 #ifndef CURL_DISABLE_TELNET
171   &Curl_handler_telnet,
172 #endif
173
174 #ifndef CURL_DISABLE_DICT
175   &Curl_handler_dict,
176 #endif
177
178 #ifndef CURL_DISABLE_LDAP
179   &Curl_handler_ldap,
180 #if !defined(CURL_DISABLE_LDAPS) && \
181     ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
182      (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
183   &Curl_handler_ldaps,
184 #endif
185 #endif
186
187 #ifndef CURL_DISABLE_FILE
188   &Curl_handler_file,
189 #endif
190
191 #ifndef CURL_DISABLE_TFTP
192   &Curl_handler_tftp,
193 #endif
194
195 #if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
196   &Curl_handler_scp,
197 #endif
198
199 #if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
200   &Curl_handler_sftp,
201 #endif
202
203 #ifndef CURL_DISABLE_IMAP
204   &Curl_handler_imap,
205 #ifdef USE_SSL
206   &Curl_handler_imaps,
207 #endif
208 #endif
209
210 #ifndef CURL_DISABLE_POP3
211   &Curl_handler_pop3,
212 #ifdef USE_SSL
213   &Curl_handler_pop3s,
214 #endif
215 #endif
216
217 #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
218    (CURL_SIZEOF_CURL_OFF_T > 4) && \
219    (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
220   &Curl_handler_smb,
221 #ifdef USE_SSL
222   &Curl_handler_smbs,
223 #endif
224 #endif
225
226 #ifndef CURL_DISABLE_SMTP
227   &Curl_handler_smtp,
228 #ifdef USE_SSL
229   &Curl_handler_smtps,
230 #endif
231 #endif
232
233 #ifndef CURL_DISABLE_RTSP
234   &Curl_handler_rtsp,
235 #endif
236
237 #ifndef CURL_DISABLE_GOPHER
238   &Curl_handler_gopher,
239 #endif
240
241 #ifdef USE_LIBRTMP
242   &Curl_handler_rtmp,
243   &Curl_handler_rtmpt,
244   &Curl_handler_rtmpe,
245   &Curl_handler_rtmpte,
246   &Curl_handler_rtmps,
247   &Curl_handler_rtmpts,
248 #endif
249
250   (struct Curl_handler *) NULL
251 };
252
253 /*
254  * Dummy handler for undefined protocol schemes.
255  */
256
257 static const struct Curl_handler Curl_handler_dummy = {
258   "<no protocol>",                      /* scheme */
259   ZERO_NULL,                            /* setup_connection */
260   ZERO_NULL,                            /* do_it */
261   ZERO_NULL,                            /* done */
262   ZERO_NULL,                            /* do_more */
263   ZERO_NULL,                            /* connect_it */
264   ZERO_NULL,                            /* connecting */
265   ZERO_NULL,                            /* doing */
266   ZERO_NULL,                            /* proto_getsock */
267   ZERO_NULL,                            /* doing_getsock */
268   ZERO_NULL,                            /* domore_getsock */
269   ZERO_NULL,                            /* perform_getsock */
270   ZERO_NULL,                            /* disconnect */
271   ZERO_NULL,                            /* readwrite */
272   ZERO_NULL,                            /* connection_check */
273   0,                                    /* defport */
274   0,                                    /* protocol */
275   PROTOPT_NONE                          /* flags */
276 };
277
278 void Curl_freeset(struct Curl_easy *data)
279 {
280   /* Free all dynamic strings stored in the data->set substructure. */
281   enum dupstring i;
282   for(i = (enum dupstring)0; i < STRING_LAST; i++) {
283     Curl_safefree(data->set.str[i]);
284   }
285
286   if(data->change.referer_alloc) {
287     Curl_safefree(data->change.referer);
288     data->change.referer_alloc = FALSE;
289   }
290   data->change.referer = NULL;
291   if(data->change.url_alloc) {
292     Curl_safefree(data->change.url);
293     data->change.url_alloc = FALSE;
294   }
295   data->change.url = NULL;
296
297   Curl_mime_cleanpart(&data->set.mimepost);
298 }
299
300 /* free the URL pieces */
301 void Curl_up_free(struct Curl_easy *data)
302 {
303   struct urlpieces *up = &data->state.up;
304   Curl_safefree(up->scheme);
305   Curl_safefree(up->hostname);
306   Curl_safefree(up->port);
307   Curl_safefree(up->user);
308   Curl_safefree(up->password);
309   Curl_safefree(up->options);
310   Curl_safefree(up->path);
311   Curl_safefree(up->query);
312   curl_url_cleanup(data->state.uh);
313   data->state.uh = NULL;
314 }
315
316 /*
317  * This is the internal function curl_easy_cleanup() calls. This should
318  * cleanup and free all resources associated with this sessionhandle.
319  *
320  * NOTE: if we ever add something that attempts to write to a socket or
321  * similar here, we must ignore SIGPIPE first. It is currently only done
322  * when curl_easy_perform() is invoked.
323  */
324
325 CURLcode Curl_close(struct Curl_easy *data)
326 {
327   struct Curl_multi *m;
328
329   if(!data)
330     return CURLE_OK;
331
332   Curl_expire_clear(data); /* shut off timers */
333
334   m = data->multi;
335   if(m)
336     /* This handle is still part of a multi handle, take care of this first
337        and detach this handle from there. */
338     curl_multi_remove_handle(data->multi, data);
339
340   if(data->multi_easy) {
341     /* when curl_easy_perform() is used, it creates its own multi handle to
342        use and this is the one */
343     curl_multi_cleanup(data->multi_easy);
344     data->multi_easy = NULL;
345   }
346
347   /* Destroy the timeout list that is held in the easy handle. It is
348      /normally/ done by curl_multi_remove_handle() but this is "just in
349      case" */
350   Curl_llist_destroy(&data->state.timeoutlist, NULL);
351
352   data->magic = 0; /* force a clear AFTER the possibly enforced removal from
353                       the multi handle, since that function uses the magic
354                       field! */
355
356   if(data->state.rangestringalloc)
357     free(data->state.range);
358
359   /* freed here just in case DONE wasn't called */
360   Curl_free_request_state(data);
361
362   /* Close down all open SSL info and sessions */
363   Curl_ssl_close_all(data);
364   Curl_safefree(data->state.first_host);
365   Curl_safefree(data->state.scratch);
366   Curl_ssl_free_certinfo(data);
367
368   /* Cleanup possible redirect junk */
369   free(data->req.newurl);
370   data->req.newurl = NULL;
371
372   if(data->change.referer_alloc) {
373     Curl_safefree(data->change.referer);
374     data->change.referer_alloc = FALSE;
375   }
376   data->change.referer = NULL;
377
378   Curl_up_free(data);
379   Curl_safefree(data->state.buffer);
380   Curl_safefree(data->state.headerbuff);
381   Curl_safefree(data->state.ulbuf);
382   Curl_flush_cookies(data, 1);
383   Curl_digest_cleanup(data);
384   Curl_safefree(data->info.contenttype);
385   Curl_safefree(data->info.wouldredirect);
386
387   /* this destroys the channel and we cannot use it anymore after this */
388   Curl_resolver_cleanup(data->state.resolver);
389
390   Curl_http2_cleanup_dependencies(data);
391   Curl_convert_close(data);
392
393   /* No longer a dirty share, if it exists */
394   if(data->share) {
395     Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
396     data->share->dirty--;
397     Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
398   }
399
400   /* destruct wildcard structures if it is needed */
401   Curl_wildcard_dtor(&data->wildcard);
402   Curl_freeset(data);
403   free(data);
404   return CURLE_OK;
405 }
406
407 /*
408  * Initialize the UserDefined fields within a Curl_easy.
409  * This may be safely called on a new or existing Curl_easy.
410  */
411 CURLcode Curl_init_userdefined(struct Curl_easy *data)
412 {
413   struct UserDefined *set = &data->set;
414   CURLcode result = CURLE_OK;
415
416   set->out = stdout; /* default output to stdout */
417   set->in_set = stdin;  /* default input from stdin */
418   set->err  = stderr;  /* default stderr to stderr */
419
420   /* use fwrite as default function to store output */
421   set->fwrite_func = (curl_write_callback)fwrite;
422
423   /* use fread as default function to read input */
424   set->fread_func_set = (curl_read_callback)fread;
425   set->is_fread_set = 0;
426   set->is_fwrite_set = 0;
427
428   set->seek_func = ZERO_NULL;
429   set->seek_client = ZERO_NULL;
430
431   /* conversion callbacks for non-ASCII hosts */
432   set->convfromnetwork = ZERO_NULL;
433   set->convtonetwork   = ZERO_NULL;
434   set->convfromutf8    = ZERO_NULL;
435
436   set->filesize = -1;        /* we don't know the size */
437   set->postfieldsize = -1;   /* unknown size */
438   set->maxredirs = -1;       /* allow any amount by default */
439
440   set->httpreq = HTTPREQ_GET; /* Default HTTP request */
441   set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
442   set->ftp_use_epsv = TRUE;   /* FTP defaults to EPSV operations */
443   set->ftp_use_eprt = TRUE;   /* FTP defaults to EPRT operations */
444   set->ftp_use_pret = FALSE;  /* mainly useful for drftpd servers */
445   set->ftp_filemethod = FTPFILE_MULTICWD;
446
447   set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
448
449   /* Set the default size of the SSL session ID cache */
450   set->general_ssl.max_ssl_sessions = 5;
451
452   set->proxyport = 0;
453   set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
454   set->httpauth = CURLAUTH_BASIC;  /* defaults to basic */
455   set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
456
457   /* SOCKS5 proxy auth defaults to username/password + GSS-API */
458   set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
459
460   /* make libcurl quiet by default: */
461   set->hide_progress = TRUE;  /* CURLOPT_NOPROGRESS changes these */
462
463   Curl_mime_initpart(&set->mimepost, data);
464
465   /*
466    * libcurl 7.10 introduced SSL verification *by default*! This needs to be
467    * switched off unless wanted.
468    */
469   set->ssl.primary.verifypeer = TRUE;
470   set->ssl.primary.verifyhost = TRUE;
471 #ifdef USE_TLS_SRP
472   set->ssl.authtype = CURL_TLSAUTH_NONE;
473 #endif
474   set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
475                                                       type */
476   set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
477                                         default */
478   set->proxy_ssl = set->ssl;
479
480   set->new_file_perms = 0644;    /* Default permissions */
481   set->new_directory_perms = 0755; /* Default permissions */
482
483   /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
484      define since we internally only use the lower 16 bits for the passed
485      in bitmask to not conflict with the private bits */
486   set->allowed_protocols = CURLPROTO_ALL;
487   set->redir_protocols = CURLPROTO_ALL &  /* All except FILE, SCP and SMB */
488                           ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
489                             CURLPROTO_SMBS);
490
491 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
492   /*
493    * disallow unprotected protection negotiation NEC reference implementation
494    * seem not to follow rfc1961 section 4.3/4.4
495    */
496   set->socks5_gssapi_nec = FALSE;
497 #endif
498
499   /* Set the default CA cert bundle/path detected/specified at build time.
500    *
501    * If Schannel (WinSSL) is the selected SSL backend then these locations
502    * are ignored. We allow setting CA location for schannel only when
503    * explicitly specified by the user via CURLOPT_CAINFO / --cacert.
504    */
505   if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) {
506 #if defined(CURL_CA_BUNDLE)
507     result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
508     if(result)
509       return result;
510
511     result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY],
512                             CURL_CA_BUNDLE);
513     if(result)
514       return result;
515 #endif
516 #if defined(CURL_CA_PATH)
517     result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
518     if(result)
519       return result;
520
521     result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
522     if(result)
523       return result;
524 #endif
525   }
526
527   set->wildcard_enabled = FALSE;
528   set->chunk_bgn      = ZERO_NULL;
529   set->chunk_end      = ZERO_NULL;
530   set->tcp_keepalive = FALSE;
531   set->tcp_keepintvl = 60;
532   set->tcp_keepidle = 60;
533   set->tcp_fastopen = FALSE;
534   set->tcp_nodelay = TRUE;
535   set->ssl_enable_npn = TRUE;
536   set->ssl_enable_alpn = TRUE;
537   set->expect_100_timeout = 1000L; /* Wait for a second by default. */
538   set->sep_headers = TRUE; /* separated header lists by default */
539   set->buffer_size = READBUFFER_SIZE;
540   set->upload_buffer_size = UPLOADBUFFER_DEFAULT;
541   set->happy_eyeballs_timeout = CURL_HET_DEFAULT;
542   set->fnmatch = ZERO_NULL;
543   set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT;
544   set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
545   set->httpversion =
546 #ifdef USE_NGHTTP2
547     CURL_HTTP_VERSION_2TLS
548 #else
549     CURL_HTTP_VERSION_1_1
550 #endif
551     ;
552   Curl_http2_init_userset(set);
553   return result;
554 }
555
556 /**
557  * Curl_open()
558  *
559  * @param curl is a pointer to a sessionhandle pointer that gets set by this
560  * function.
561  * @return CURLcode
562  */
563
564 CURLcode Curl_open(struct Curl_easy **curl)
565 {
566   CURLcode result;
567   struct Curl_easy *data;
568
569   /* Very simple start-up: alloc the struct, init it with zeroes and return */
570   data = calloc(1, sizeof(struct Curl_easy));
571   if(!data) {
572     /* this is a very serious error */
573     DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
574     return CURLE_OUT_OF_MEMORY;
575   }
576
577   data->magic = CURLEASY_MAGIC_NUMBER;
578
579   result = Curl_resolver_init(&data->state.resolver);
580   if(result) {
581     DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
582     free(data);
583     return result;
584   }
585
586   /* We do some initial setup here, all those fields that can't be just 0 */
587
588   data->state.buffer = malloc(READBUFFER_SIZE + 1);
589   if(!data->state.buffer) {
590     DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n"));
591     result = CURLE_OUT_OF_MEMORY;
592   }
593   else {
594     data->state.headerbuff = malloc(HEADERSIZE);
595     if(!data->state.headerbuff) {
596       DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
597       result = CURLE_OUT_OF_MEMORY;
598     }
599     else {
600       result = Curl_init_userdefined(data);
601
602       data->state.headersize = HEADERSIZE;
603       Curl_convert_init(data);
604       Curl_initinfo(data);
605
606       /* most recent connection is not yet defined */
607       data->state.lastconnect = NULL;
608
609       data->progress.flags |= PGRS_HIDE;
610       data->state.current_speed = -1; /* init to negative == impossible */
611
612       Curl_http2_init_state(&data->state);
613     }
614   }
615
616   if(result) {
617     Curl_resolver_cleanup(data->state.resolver);
618     free(data->state.buffer);
619     free(data->state.headerbuff);
620     Curl_freeset(data);
621     free(data);
622     data = NULL;
623   }
624   else
625     *curl = data;
626
627   return result;
628 }
629
630 #ifdef USE_RECV_BEFORE_SEND_WORKAROUND
631 static void conn_reset_postponed_data(struct connectdata *conn, int num)
632 {
633   struct postponed_data * const psnd = &(conn->postponed[num]);
634   if(psnd->buffer) {
635     DEBUGASSERT(psnd->allocated_size > 0);
636     DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
637     DEBUGASSERT(psnd->recv_size ?
638                 (psnd->recv_processed < psnd->recv_size) :
639                 (psnd->recv_processed == 0));
640     DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
641     free(psnd->buffer);
642     psnd->buffer = NULL;
643     psnd->allocated_size = 0;
644     psnd->recv_size = 0;
645     psnd->recv_processed = 0;
646 #ifdef DEBUGBUILD
647     psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
648 #endif /* DEBUGBUILD */
649   }
650   else {
651     DEBUGASSERT(psnd->allocated_size == 0);
652     DEBUGASSERT(psnd->recv_size == 0);
653     DEBUGASSERT(psnd->recv_processed == 0);
654     DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
655   }
656 }
657
658 static void conn_reset_all_postponed_data(struct connectdata *conn)
659 {
660   conn_reset_postponed_data(conn, 0);
661   conn_reset_postponed_data(conn, 1);
662 }
663 #else  /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
664 /* Use "do-nothing" macro instead of function when workaround not used */
665 #define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
666 #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
667
668 static void conn_free(struct connectdata *conn)
669 {
670   if(!conn)
671     return;
672
673   /* possible left-overs from the async name resolvers */
674   Curl_resolver_cancel(conn);
675
676   /* close the SSL stuff before we close any sockets since they will/may
677      write to the sockets */
678   Curl_ssl_close(conn, FIRSTSOCKET);
679   Curl_ssl_close(conn, SECONDARYSOCKET);
680
681   /* close possibly still open sockets */
682   if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
683     Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
684   if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
685     Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
686   if(CURL_SOCKET_BAD != conn->tempsock[0])
687     Curl_closesocket(conn, conn->tempsock[0]);
688   if(CURL_SOCKET_BAD != conn->tempsock[1])
689     Curl_closesocket(conn, conn->tempsock[1]);
690
691 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
692     defined(NTLM_WB_ENABLED)
693   Curl_ntlm_wb_cleanup(conn);
694 #endif
695
696   Curl_safefree(conn->user);
697   Curl_safefree(conn->passwd);
698   Curl_safefree(conn->oauth_bearer);
699   Curl_safefree(conn->options);
700   Curl_safefree(conn->http_proxy.user);
701   Curl_safefree(conn->socks_proxy.user);
702   Curl_safefree(conn->http_proxy.passwd);
703   Curl_safefree(conn->socks_proxy.passwd);
704   Curl_safefree(conn->allocptr.proxyuserpwd);
705   Curl_safefree(conn->allocptr.uagent);
706   Curl_safefree(conn->allocptr.userpwd);
707   Curl_safefree(conn->allocptr.accept_encoding);
708   Curl_safefree(conn->allocptr.te);
709   Curl_safefree(conn->allocptr.rangeline);
710   Curl_safefree(conn->allocptr.ref);
711   Curl_safefree(conn->allocptr.host);
712   Curl_safefree(conn->allocptr.cookiehost);
713   Curl_safefree(conn->allocptr.rtsp_transport);
714   Curl_safefree(conn->trailer);
715   Curl_safefree(conn->host.rawalloc); /* host name buffer */
716   Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
717   Curl_safefree(conn->secondaryhostname);
718   Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
719   Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
720   Curl_safefree(conn->master_buffer);
721   Curl_safefree(conn->connect_state);
722
723   conn_reset_all_postponed_data(conn);
724
725   Curl_llist_destroy(&conn->send_pipe, NULL);
726   Curl_llist_destroy(&conn->recv_pipe, NULL);
727
728   Curl_safefree(conn->localdev);
729   Curl_free_primary_ssl_config(&conn->ssl_config);
730   Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
731
732 #ifdef USE_UNIX_SOCKETS
733   Curl_safefree(conn->unix_domain_socket);
734 #endif
735
736 #ifdef USE_SSL
737   Curl_safefree(conn->ssl_extra);
738 #endif
739   free(conn); /* free all the connection oriented data */
740 }
741
742 /*
743  * Disconnects the given connection. Note the connection may not be the
744  * primary connection, like when freeing room in the connection cache or
745  * killing of a dead old connection.
746  *
747  * A connection needs an easy handle when closing down. We support this passed
748  * in separately since the connection to get closed here is often already
749  * disassociated from an easy handle.
750  *
751  * This function MUST NOT reset state in the Curl_easy struct if that
752  * isn't strictly bound to the life-time of *this* particular connection.
753  *
754  */
755
756 CURLcode Curl_disconnect(struct Curl_easy *data,
757                          struct connectdata *conn, bool dead_connection)
758 {
759   if(!conn)
760     return CURLE_OK; /* this is closed and fine already */
761
762   if(!data) {
763     DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
764     return CURLE_OK;
765   }
766
767   /*
768    * If this connection isn't marked to force-close, leave it open if there
769    * are other users of it
770    */
771   if(CONN_INUSE(conn) && !dead_connection) {
772     DEBUGF(infof(data, "Curl_disconnect when inuse: %zu\n", CONN_INUSE(conn)));
773     return CURLE_OK;
774   }
775
776   conn->data = data;
777   if(conn->dns_entry != NULL) {
778     Curl_resolv_unlock(data, conn->dns_entry);
779     conn->dns_entry = NULL;
780   }
781
782   Curl_hostcache_prune(data); /* kill old DNS cache entries */
783
784 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
785   /* Cleanup NTLM connection-related data */
786   Curl_http_ntlm_cleanup(conn);
787 #endif
788
789   if(conn->handler->disconnect)
790     /* This is set if protocol-specific cleanups should be made */
791     conn->handler->disconnect(conn, dead_connection);
792
793     /* unlink ourselves! */
794   infof(data, "Closing connection %ld\n", conn->connection_id);
795   Curl_conncache_remove_conn(conn, TRUE);
796
797   free_fixed_hostname(&conn->host);
798   free_fixed_hostname(&conn->conn_to_host);
799   free_fixed_hostname(&conn->http_proxy.host);
800   free_fixed_hostname(&conn->socks_proxy.host);
801
802   DEBUGASSERT(conn->data == data);
803   /* this assumes that the pointer is still there after the connection was
804      detected from the cache */
805   Curl_ssl_close(conn, FIRSTSOCKET);
806
807   conn_free(conn);
808   return CURLE_OK;
809 }
810
811 /*
812  * This function should return TRUE if the socket is to be assumed to
813  * be dead. Most commonly this happens when the server has closed the
814  * connection due to inactivity.
815  */
816 static bool SocketIsDead(curl_socket_t sock)
817 {
818   int sval;
819   bool ret_val = TRUE;
820
821   sval = SOCKET_READABLE(sock, 0);
822   if(sval == 0)
823     /* timeout */
824     ret_val = FALSE;
825
826   return ret_val;
827 }
828
829 /*
830  * IsPipeliningPossible()
831  *
832  * Return a bitmask with the available pipelining and multiplexing options for
833  * the given requested connection.
834  */
835 static int IsPipeliningPossible(const struct Curl_easy *handle,
836                                 const struct connectdata *conn)
837 {
838   int avail = 0;
839
840   /* If a HTTP protocol and pipelining is enabled */
841   if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
842      (!conn->bits.protoconnstart || !conn->bits.close)) {
843
844     if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
845        (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
846        (handle->set.httpreq == HTTPREQ_GET ||
847         handle->set.httpreq == HTTPREQ_HEAD))
848       /* didn't ask for HTTP/1.0 and a GET or HEAD */
849       avail |= CURLPIPE_HTTP1;
850
851     if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
852        (handle->set.httpversion >= CURL_HTTP_VERSION_2))
853       /* allows HTTP/2 */
854       avail |= CURLPIPE_MULTIPLEX;
855   }
856   return avail;
857 }
858
859 /* Returns non-zero if a handle was removed */
860 int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
861                                   struct curl_llist *pipeline)
862 {
863   if(pipeline) {
864     struct curl_llist_element *curr;
865
866     curr = pipeline->head;
867     while(curr) {
868       if(curr->ptr == handle) {
869         Curl_llist_remove(pipeline, curr, NULL);
870         return 1; /* we removed a handle */
871       }
872       curr = curr->next;
873     }
874   }
875
876   return 0;
877 }
878
879 #if 0 /* this code is saved here as it is useful for debugging purposes */
880 static void Curl_printPipeline(struct curl_llist *pipeline)
881 {
882   struct curl_llist_element *curr;
883
884   curr = pipeline->head;
885   while(curr) {
886     struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
887     infof(data, "Handle in pipeline: %s\n", data->state.path);
888     curr = curr->next;
889   }
890 }
891 #endif
892
893 static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
894 {
895   struct curl_llist_element *curr = pipeline->head;
896 #ifdef DEBUGBUILD
897   {
898     struct curl_llist_element *p = pipeline->head;
899     while(p) {
900       struct Curl_easy *e = p->ptr;
901       DEBUGASSERT(GOOD_EASY_HANDLE(e));
902       p = p->next;
903     }
904   }
905 #endif
906   if(curr) {
907     return (struct Curl_easy *) curr->ptr;
908   }
909
910   return NULL;
911 }
912
913 /* remove the specified connection from all (possible) pipelines and related
914    queues */
915 void Curl_getoff_all_pipelines(struct Curl_easy *data,
916                                struct connectdata *conn)
917 {
918   if(!conn->bundle)
919     return;
920   if(conn->bundle->multiuse == BUNDLE_PIPELINING) {
921     bool recv_head = (conn->readchannel_inuse &&
922                       Curl_recvpipe_head(data, conn));
923     bool send_head = (conn->writechannel_inuse &&
924                       Curl_sendpipe_head(data, conn));
925
926     if(Curl_removeHandleFromPipeline(data, &conn->recv_pipe) && recv_head)
927       Curl_pipeline_leave_read(conn);
928     if(Curl_removeHandleFromPipeline(data, &conn->send_pipe) && send_head)
929       Curl_pipeline_leave_write(conn);
930   }
931   else {
932     (void)Curl_removeHandleFromPipeline(data, &conn->recv_pipe);
933     (void)Curl_removeHandleFromPipeline(data, &conn->send_pipe);
934   }
935 }
936
937 static bool
938 proxy_info_matches(const struct proxy_info* data,
939                    const struct proxy_info* needle)
940 {
941   if((data->proxytype == needle->proxytype) &&
942      (data->port == needle->port) &&
943      Curl_safe_strcasecompare(data->host.name, needle->host.name))
944     return TRUE;
945
946   return FALSE;
947 }
948
949 /*
950  * This function checks if the given connection is dead and extracts it from
951  * the connection cache if so.
952  *
953  * When this is called as a Curl_conncache_foreach() callback, the connection
954  * cache lock is held!
955  *
956  * Returns TRUE if the connection was dead and extracted.
957  */
958 static bool extract_if_dead(struct connectdata *conn,
959                             struct Curl_easy *data)
960 {
961   size_t pipeLen = conn->send_pipe.size + conn->recv_pipe.size;
962   if(!pipeLen && !CONN_INUSE(conn)) {
963     /* The check for a dead socket makes sense only if there are no
964        handles in pipeline and the connection isn't already marked in
965        use */
966     bool dead;
967
968     conn->data = data;
969     if(conn->handler->connection_check) {
970       /* The protocol has a special method for checking the state of the
971          connection. Use it to check if the connection is dead. */
972       unsigned int state;
973
974       state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD);
975       dead = (state & CONNRESULT_DEAD);
976     }
977     else {
978       /* Use the general method for determining the death of a connection */
979       dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
980     }
981
982     if(dead) {
983       infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
984       Curl_conncache_remove_conn(conn, FALSE);
985       conn->data = NULL; /* detach */
986       return TRUE;
987     }
988   }
989   return FALSE;
990 }
991
992 struct prunedead {
993   struct Curl_easy *data;
994   struct connectdata *extracted;
995 };
996
997 /*
998  * Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
999  *
1000  */
1001 static int call_extract_if_dead(struct connectdata *conn, void *param)
1002 {
1003   struct prunedead *p = (struct prunedead *)param;
1004   if(extract_if_dead(conn, p->data)) {
1005     /* stop the iteration here, pass back the connection that was extracted */
1006     p->extracted = conn;
1007     return 1;
1008   }
1009   return 0; /* continue iteration */
1010 }
1011
1012 /*
1013  * This function scans the connection cache for half-open/dead connections,
1014  * closes and removes them.
1015  * The cleanup is done at most once per second.
1016  */
1017 static void prune_dead_connections(struct Curl_easy *data)
1018 {
1019   struct curltime now = Curl_now();
1020   time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup);
1021
1022   if(elapsed >= 1000L) {
1023     struct prunedead prune;
1024     prune.data = data;
1025     prune.extracted = NULL;
1026     while(Curl_conncache_foreach(data, data->state.conn_cache, &prune,
1027                                  call_extract_if_dead)) {
1028       /* disconnect it */
1029       (void)Curl_disconnect(data, prune.extracted, /* dead_connection */TRUE);
1030     }
1031     data->state.conn_cache->last_cleanup = now;
1032   }
1033 }
1034
1035
1036 static size_t max_pipeline_length(struct Curl_multi *multi)
1037 {
1038   return multi ? multi->max_pipeline_length : 0;
1039 }
1040
1041
1042 /*
1043  * Given one filled in connection struct (named needle), this function should
1044  * detect if there already is one that has all the significant details
1045  * exactly the same and thus should be used instead.
1046  *
1047  * If there is a match, this function returns TRUE - and has marked the
1048  * connection as 'in-use'. It must later be called with ConnectionDone() to
1049  * return back to 'idle' (unused) state.
1050  *
1051  * The force_reuse flag is set if the connection must be used, even if
1052  * the pipelining strategy wants to open a new connection instead of reusing.
1053  */
1054 static bool
1055 ConnectionExists(struct Curl_easy *data,
1056                  struct connectdata *needle,
1057                  struct connectdata **usethis,
1058                  bool *force_reuse,
1059                  bool *waitpipe)
1060 {
1061   struct connectdata *check;
1062   struct connectdata *chosen = 0;
1063   bool foundPendingCandidate = FALSE;
1064   int canpipe = IsPipeliningPossible(data, needle);
1065   struct connectbundle *bundle;
1066
1067 #ifdef USE_NTLM
1068   bool wantNTLMhttp = ((data->state.authhost.want &
1069                       (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
1070                       (needle->handler->protocol & PROTO_FAMILY_HTTP));
1071   bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
1072                            ((data->state.authproxy.want &
1073                            (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
1074                            (needle->handler->protocol & PROTO_FAMILY_HTTP)));
1075 #endif
1076
1077   *force_reuse = FALSE;
1078   *waitpipe = FALSE;
1079
1080   /* We can't pipeline if the site is blacklisted */
1081   if((canpipe & CURLPIPE_HTTP1) &&
1082      Curl_pipeline_site_blacklisted(data, needle))
1083     canpipe &= ~ CURLPIPE_HTTP1;
1084
1085   /* Look up the bundle with all the connections to this particular host.
1086      Locks the connection cache, beware of early returns! */
1087   bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
1088   if(bundle) {
1089     /* Max pipe length is zero (unlimited) for multiplexed connections */
1090     size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
1091       max_pipeline_length(data->multi):0;
1092     size_t best_pipe_len = max_pipe_len;
1093     struct curl_llist_element *curr;
1094
1095     infof(data, "Found bundle for host %s: %p [%s]\n",
1096           (needle->bits.conn_to_host ? needle->conn_to_host.name :
1097            needle->host.name), (void *)bundle,
1098           (bundle->multiuse == BUNDLE_PIPELINING ?
1099            "can pipeline" :
1100            (bundle->multiuse == BUNDLE_MULTIPLEX ?
1101             "can multiplex" : "serially")));
1102
1103     /* We can't pipeline if we don't know anything about the server */
1104     if(canpipe) {
1105       if(bundle->multiuse <= BUNDLE_UNKNOWN) {
1106         if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
1107           infof(data, "Server doesn't support multi-use yet, wait\n");
1108           *waitpipe = TRUE;
1109           Curl_conncache_unlock(needle);
1110           return FALSE; /* no re-use */
1111         }
1112
1113         infof(data, "Server doesn't support multi-use (yet)\n");
1114         canpipe = 0;
1115       }
1116       if((bundle->multiuse == BUNDLE_PIPELINING) &&
1117          !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
1118         /* not asked for, switch off */
1119         infof(data, "Could pipeline, but not asked to!\n");
1120         canpipe = 0;
1121       }
1122       else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
1123               !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
1124         infof(data, "Could multiplex, but not asked to!\n");
1125         canpipe = 0;
1126       }
1127     }
1128
1129     curr = bundle->conn_list.head;
1130     while(curr) {
1131       bool match = FALSE;
1132       size_t pipeLen;
1133
1134       /*
1135        * Note that if we use a HTTP proxy in normal mode (no tunneling), we
1136        * check connections to that proxy and not to the actual remote server.
1137        */
1138       check = curr->ptr;
1139       curr = curr->next;
1140
1141       if(extract_if_dead(check, data)) {
1142         /* disconnect it */
1143         (void)Curl_disconnect(data, check, /* dead_connection */TRUE);
1144         continue;
1145       }
1146
1147       pipeLen = check->send_pipe.size + check->recv_pipe.size;
1148
1149       if(canpipe) {
1150         if(check->bits.protoconnstart && check->bits.close)
1151           continue;
1152
1153         if(!check->bits.multiplex) {
1154           /* If not multiplexing, make sure the connection is fine for HTTP/1
1155              pipelining */
1156           struct Curl_easy* sh = gethandleathead(&check->send_pipe);
1157           struct Curl_easy* rh = gethandleathead(&check->recv_pipe);
1158           if(sh) {
1159             if(!(IsPipeliningPossible(sh, check) & CURLPIPE_HTTP1))
1160               continue;
1161           }
1162           else if(rh) {
1163             if(!(IsPipeliningPossible(rh, check) & CURLPIPE_HTTP1))
1164               continue;
1165           }
1166         }
1167       }
1168       else {
1169         if(pipeLen > 0) {
1170           /* can only happen within multi handles, and means that another easy
1171              handle is using this connection */
1172           continue;
1173         }
1174
1175         if(Curl_resolver_asynch()) {
1176           /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
1177              completed yet and until then we don't re-use this connection */
1178           if(!check->ip_addr_str[0]) {
1179             infof(data,
1180                   "Connection #%ld is still name resolving, can't reuse\n",
1181                   check->connection_id);
1182             continue;
1183           }
1184         }
1185
1186         if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
1187            check->bits.close) {
1188           if(!check->bits.close)
1189             foundPendingCandidate = TRUE;
1190           /* Don't pick a connection that hasn't connected yet or that is going
1191              to get closed. */
1192           infof(data, "Connection #%ld isn't open enough, can't reuse\n",
1193                 check->connection_id);
1194 #ifdef DEBUGBUILD
1195           if(check->recv_pipe.size > 0) {
1196             infof(data,
1197                   "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
1198                   check->connection_id);
1199           }
1200 #endif
1201           continue;
1202         }
1203       }
1204
1205 #ifdef USE_UNIX_SOCKETS
1206       if(needle->unix_domain_socket) {
1207         if(!check->unix_domain_socket)
1208           continue;
1209         if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
1210           continue;
1211         if(needle->abstract_unix_socket != check->abstract_unix_socket)
1212           continue;
1213       }
1214       else if(check->unix_domain_socket)
1215         continue;
1216 #endif
1217
1218       if((needle->handler->flags&PROTOPT_SSL) !=
1219          (check->handler->flags&PROTOPT_SSL))
1220         /* don't do mixed SSL and non-SSL connections */
1221         if(get_protocol_family(check->handler->protocol) !=
1222            needle->handler->protocol || !check->tls_upgraded)
1223           /* except protocols that have been upgraded via TLS */
1224           continue;
1225
1226       if(needle->bits.httpproxy != check->bits.httpproxy ||
1227          needle->bits.socksproxy != check->bits.socksproxy)
1228         continue;
1229
1230       if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy,
1231                                                         &check->socks_proxy))
1232         continue;
1233
1234       if(needle->bits.conn_to_host != check->bits.conn_to_host)
1235         /* don't mix connections that use the "connect to host" feature and
1236          * connections that don't use this feature */
1237         continue;
1238
1239       if(needle->bits.conn_to_port != check->bits.conn_to_port)
1240         /* don't mix connections that use the "connect to port" feature and
1241          * connections that don't use this feature */
1242         continue;
1243
1244       if(needle->bits.httpproxy) {
1245         if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
1246           continue;
1247
1248         if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
1249           continue;
1250
1251         if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) {
1252           /* use https proxy */
1253           if(needle->handler->flags&PROTOPT_SSL) {
1254             /* use double layer ssl */
1255             if(!Curl_ssl_config_matches(&needle->proxy_ssl_config,
1256                                         &check->proxy_ssl_config))
1257               continue;
1258             if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete)
1259               continue;
1260           }
1261           else {
1262             if(!Curl_ssl_config_matches(&needle->ssl_config,
1263                                         &check->ssl_config))
1264               continue;
1265             if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete)
1266               continue;
1267           }
1268         }
1269       }
1270
1271       if(!canpipe && CONN_INUSE(check))
1272         /* this request can't be pipelined but the checked connection is
1273            already in use so we skip it */
1274         continue;
1275
1276       if(CONN_INUSE(check) && (check->data->multi != needle->data->multi))
1277         /* this could be subject for pipeline/multiplex use, but only
1278            if they belong to the same multi handle */
1279         continue;
1280
1281       if(needle->localdev || needle->localport) {
1282         /* If we are bound to a specific local end (IP+port), we must not
1283            re-use a random other one, although if we didn't ask for a
1284            particular one we can reuse one that was bound.
1285
1286            This comparison is a bit rough and too strict. Since the input
1287            parameters can be specified in numerous ways and still end up the
1288            same it would take a lot of processing to make it really accurate.
1289            Instead, this matching will assume that re-uses of bound connections
1290            will most likely also re-use the exact same binding parameters and
1291            missing out a few edge cases shouldn't hurt anyone very much.
1292         */
1293         if((check->localport != needle->localport) ||
1294            (check->localportrange != needle->localportrange) ||
1295            (needle->localdev &&
1296             (!check->localdev || strcmp(check->localdev, needle->localdev))))
1297           continue;
1298       }
1299
1300       if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
1301         /* This protocol requires credentials per connection,
1302            so verify that we're using the same name and password as well */
1303         if(strcmp(needle->user, check->user) ||
1304            strcmp(needle->passwd, check->passwd)) {
1305           /* one of them was different */
1306           continue;
1307         }
1308       }
1309
1310       if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
1311          needle->bits.tunnel_proxy) {
1312         /* The requested connection does not use a HTTP proxy or it uses SSL or
1313            it is a non-SSL protocol tunneled or it is a non-SSL protocol which
1314            is allowed to be upgraded via TLS */
1315
1316         if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
1317             (get_protocol_family(check->handler->protocol) ==
1318              needle->handler->protocol && check->tls_upgraded)) &&
1319            (!needle->bits.conn_to_host || strcasecompare(
1320             needle->conn_to_host.name, check->conn_to_host.name)) &&
1321            (!needle->bits.conn_to_port ||
1322              needle->conn_to_port == check->conn_to_port) &&
1323            strcasecompare(needle->host.name, check->host.name) &&
1324            needle->remote_port == check->remote_port) {
1325           /* The schemes match or the the protocol family is the same and the
1326              previous connection was TLS upgraded, and the hostname and host
1327              port match */
1328           if(needle->handler->flags & PROTOPT_SSL) {
1329             /* This is a SSL connection so verify that we're using the same
1330                SSL options as well */
1331             if(!Curl_ssl_config_matches(&needle->ssl_config,
1332                                         &check->ssl_config)) {
1333               DEBUGF(infof(data,
1334                            "Connection #%ld has different SSL parameters, "
1335                            "can't reuse\n",
1336                            check->connection_id));
1337               continue;
1338             }
1339             if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
1340               foundPendingCandidate = TRUE;
1341               DEBUGF(infof(data,
1342                            "Connection #%ld has not started SSL connect, "
1343                            "can't reuse\n",
1344                            check->connection_id));
1345               continue;
1346             }
1347           }
1348           match = TRUE;
1349         }
1350       }
1351       else {
1352         /* The requested connection is using the same HTTP proxy in normal
1353            mode (no tunneling) */
1354         match = TRUE;
1355       }
1356
1357       if(match) {
1358 #if defined(USE_NTLM)
1359         /* If we are looking for an HTTP+NTLM connection, check if this is
1360            already authenticating with the right credentials. If not, keep
1361            looking so that we can reuse NTLM connections if
1362            possible. (Especially we must not reuse the same connection if
1363            partway through a handshake!) */
1364         if(wantNTLMhttp) {
1365           if(strcmp(needle->user, check->user) ||
1366              strcmp(needle->passwd, check->passwd))
1367             continue;
1368         }
1369         else if(check->ntlm.state != NTLMSTATE_NONE) {
1370           /* Connection is using NTLM auth but we don't want NTLM */
1371           continue;
1372         }
1373
1374         /* Same for Proxy NTLM authentication */
1375         if(wantProxyNTLMhttp) {
1376           /* Both check->http_proxy.user and check->http_proxy.passwd can be
1377            * NULL */
1378           if(!check->http_proxy.user || !check->http_proxy.passwd)
1379             continue;
1380
1381           if(strcmp(needle->http_proxy.user, check->http_proxy.user) ||
1382              strcmp(needle->http_proxy.passwd, check->http_proxy.passwd))
1383             continue;
1384         }
1385         else if(check->proxyntlm.state != NTLMSTATE_NONE) {
1386           /* Proxy connection is using NTLM auth but we don't want NTLM */
1387           continue;
1388         }
1389
1390         if(wantNTLMhttp || wantProxyNTLMhttp) {
1391           /* Credentials are already checked, we can use this connection */
1392           chosen = check;
1393
1394           if((wantNTLMhttp &&
1395              (check->ntlm.state != NTLMSTATE_NONE)) ||
1396               (wantProxyNTLMhttp &&
1397                (check->proxyntlm.state != NTLMSTATE_NONE))) {
1398             /* We must use this connection, no other */
1399             *force_reuse = TRUE;
1400             break;
1401           }
1402
1403           /* Continue look up for a better connection */
1404           continue;
1405         }
1406 #endif
1407         if(canpipe) {
1408           /* We can pipeline if we want to. Let's continue looking for
1409              the optimal connection to use, i.e the shortest pipe that is not
1410              blacklisted. */
1411
1412           if(pipeLen == 0) {
1413             /* We have the optimal connection. Let's stop looking. */
1414             chosen = check;
1415             break;
1416           }
1417
1418           /* We can't use the connection if the pipe is full */
1419           if(max_pipe_len && (pipeLen >= max_pipe_len)) {
1420             infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
1421             continue;
1422           }
1423 #ifdef USE_NGHTTP2
1424           /* If multiplexed, make sure we don't go over concurrency limit */
1425           if(check->bits.multiplex) {
1426             /* Multiplexed connections can only be HTTP/2 for now */
1427             struct http_conn *httpc = &check->proto.httpc;
1428             if(pipeLen >= httpc->settings.max_concurrent_streams) {
1429               infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
1430                     pipeLen);
1431               continue;
1432             }
1433           }
1434 #endif
1435           /* We can't use the connection if the pipe is penalized */
1436           if(Curl_pipeline_penalized(data, check)) {
1437             infof(data, "Penalized, skip\n");
1438             continue;
1439           }
1440
1441           if(max_pipe_len) {
1442             if(pipeLen < best_pipe_len) {
1443               /* This connection has a shorter pipe so far. We'll pick this
1444                  and continue searching */
1445               chosen = check;
1446               best_pipe_len = pipeLen;
1447               continue;
1448             }
1449           }
1450           else {
1451             /* When not pipelining (== multiplexed), we have a match here! */
1452             chosen = check;
1453             infof(data, "Multiplexed connection found!\n");
1454             break;
1455           }
1456         }
1457         else {
1458           /* We have found a connection. Let's stop searching. */
1459           chosen = check;
1460           break;
1461         }
1462       }
1463     }
1464   }
1465
1466   if(chosen) {
1467     /* mark it as used before releasing the lock */
1468     chosen->data = data; /* own it! */
1469     Curl_conncache_unlock(needle);
1470     *usethis = chosen;
1471     return TRUE; /* yes, we found one to use! */
1472   }
1473   Curl_conncache_unlock(needle);
1474
1475   if(foundPendingCandidate && data->set.pipewait) {
1476     infof(data,
1477           "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
1478     *waitpipe = TRUE;
1479   }
1480
1481   return FALSE; /* no matching connecting exists */
1482 }
1483
1484 /* after a TCP connection to the proxy has been verified, this function does
1485    the next magic step.
1486
1487    Note: this function's sub-functions call failf()
1488
1489 */
1490 CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex)
1491 {
1492   CURLcode result = CURLE_OK;
1493
1494   if(conn->bits.socksproxy) {
1495 #ifndef CURL_DISABLE_PROXY
1496     /* for the secondary socket (FTP), use the "connect to host"
1497      * but ignore the "connect to port" (use the secondary port)
1498      */
1499     const char * const host = conn->bits.httpproxy ?
1500                               conn->http_proxy.host.name :
1501                               conn->bits.conn_to_host ?
1502                               conn->conn_to_host.name :
1503                               sockindex == SECONDARYSOCKET ?
1504                               conn->secondaryhostname : conn->host.name;
1505     const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port :
1506                      sockindex == SECONDARYSOCKET ? conn->secondary_port :
1507                      conn->bits.conn_to_port ? conn->conn_to_port :
1508                      conn->remote_port;
1509     conn->bits.socksproxy_connecting = TRUE;
1510     switch(conn->socks_proxy.proxytype) {
1511     case CURLPROXY_SOCKS5:
1512     case CURLPROXY_SOCKS5_HOSTNAME:
1513       result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
1514                          host, port, sockindex, conn);
1515       break;
1516
1517     case CURLPROXY_SOCKS4:
1518     case CURLPROXY_SOCKS4A:
1519       result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
1520                            conn);
1521       break;
1522
1523     default:
1524       failf(conn->data, "unknown proxytype option given");
1525       result = CURLE_COULDNT_CONNECT;
1526     } /* switch proxytype */
1527     conn->bits.socksproxy_connecting = FALSE;
1528 #else
1529   (void)sockindex;
1530 #endif /* CURL_DISABLE_PROXY */
1531   }
1532
1533   return result;
1534 }
1535
1536 /*
1537  * verboseconnect() displays verbose information after a connect
1538  */
1539 #ifndef CURL_DISABLE_VERBOSE_STRINGS
1540 void Curl_verboseconnect(struct connectdata *conn)
1541 {
1542   if(conn->data->set.verbose)
1543     infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
1544           conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
1545           conn->bits.httpproxy ? conn->http_proxy.host.dispname :
1546           conn->bits.conn_to_host ? conn->conn_to_host.dispname :
1547           conn->host.dispname,
1548           conn->ip_addr_str, conn->port, conn->connection_id);
1549 }
1550 #endif
1551
1552 int Curl_protocol_getsock(struct connectdata *conn,
1553                           curl_socket_t *socks,
1554                           int numsocks)
1555 {
1556   if(conn->handler->proto_getsock)
1557     return conn->handler->proto_getsock(conn, socks, numsocks);
1558   /* Backup getsock logic. Since there is a live socket in use, we must wait
1559      for it or it will be removed from watching when the multi_socket API is
1560      used. */
1561   socks[0] = conn->sock[FIRSTSOCKET];
1562   return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0);
1563 }
1564
1565 int Curl_doing_getsock(struct connectdata *conn,
1566                        curl_socket_t *socks,
1567                        int numsocks)
1568 {
1569   if(conn && conn->handler->doing_getsock)
1570     return conn->handler->doing_getsock(conn, socks, numsocks);
1571   return GETSOCK_BLANK;
1572 }
1573
1574 /*
1575  * We are doing protocol-specific connecting and this is being called over and
1576  * over from the multi interface until the connection phase is done on
1577  * protocol layer.
1578  */
1579
1580 CURLcode Curl_protocol_connecting(struct connectdata *conn,
1581                                   bool *done)
1582 {
1583   CURLcode result = CURLE_OK;
1584
1585   if(conn && conn->handler->connecting) {
1586     *done = FALSE;
1587     result = conn->handler->connecting(conn, done);
1588   }
1589   else
1590     *done = TRUE;
1591
1592   return result;
1593 }
1594
1595 /*
1596  * We are DOING this is being called over and over from the multi interface
1597  * until the DOING phase is done on protocol layer.
1598  */
1599
1600 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
1601 {
1602   CURLcode result = CURLE_OK;
1603
1604   if(conn && conn->handler->doing) {
1605     *done = FALSE;
1606     result = conn->handler->doing(conn, done);
1607   }
1608   else
1609     *done = TRUE;
1610
1611   return result;
1612 }
1613
1614 /*
1615  * We have discovered that the TCP connection has been successful, we can now
1616  * proceed with some action.
1617  *
1618  */
1619 CURLcode Curl_protocol_connect(struct connectdata *conn,
1620                                bool *protocol_done)
1621 {
1622   CURLcode result = CURLE_OK;
1623
1624   *protocol_done = FALSE;
1625
1626   if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
1627     /* We already are connected, get back. This may happen when the connect
1628        worked fine in the first call, like when we connect to a local server
1629        or proxy. Note that we don't know if the protocol is actually done.
1630
1631        Unless this protocol doesn't have any protocol-connect callback, as
1632        then we know we're done. */
1633     if(!conn->handler->connecting)
1634       *protocol_done = TRUE;
1635
1636     return CURLE_OK;
1637   }
1638
1639   if(!conn->bits.protoconnstart) {
1640
1641     result = Curl_proxy_connect(conn, FIRSTSOCKET);
1642     if(result)
1643       return result;
1644
1645     if(CONNECT_FIRSTSOCKET_PROXY_SSL())
1646       /* wait for HTTPS proxy SSL initialization to complete */
1647       return CURLE_OK;
1648
1649     if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
1650        Curl_connect_ongoing(conn))
1651       /* when using an HTTP tunnel proxy, await complete tunnel establishment
1652          before proceeding further. Return CURLE_OK so we'll be called again */
1653       return CURLE_OK;
1654
1655     if(conn->handler->connect_it) {
1656       /* is there a protocol-specific connect() procedure? */
1657
1658       /* Call the protocol-specific connect function */
1659       result = conn->handler->connect_it(conn, protocol_done);
1660     }
1661     else
1662       *protocol_done = TRUE;
1663
1664     /* it has started, possibly even completed but that knowledge isn't stored
1665        in this bit! */
1666     if(!result)
1667       conn->bits.protoconnstart = TRUE;
1668   }
1669
1670   return result; /* pass back status */
1671 }
1672
1673 /*
1674  * Helpers for IDNA conversions.
1675  */
1676 static bool is_ASCII_name(const char *hostname)
1677 {
1678   const unsigned char *ch = (const unsigned char *)hostname;
1679
1680   while(*ch) {
1681     if(*ch++ & 0x80)
1682       return FALSE;
1683   }
1684   return TRUE;
1685 }
1686
1687 /*
1688  * Perform any necessary IDN conversion of hostname
1689  */
1690 static CURLcode fix_hostname(struct connectdata *conn, struct hostname *host)
1691 {
1692   size_t len;
1693   struct Curl_easy *data = conn->data;
1694
1695 #ifndef USE_LIBIDN2
1696   (void)data;
1697   (void)conn;
1698 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
1699   (void)conn;
1700 #endif
1701
1702   /* set the name we use to display the host name */
1703   host->dispname = host->name;
1704
1705   len = strlen(host->name);
1706   if(len && (host->name[len-1] == '.'))
1707     /* strip off a single trailing dot if present, primarily for SNI but
1708        there's no use for it */
1709     host->name[len-1] = 0;
1710
1711   /* Check name for non-ASCII and convert hostname to ACE form if we can */
1712   if(!is_ASCII_name(host->name)) {
1713 #ifdef USE_LIBIDN2
1714     if(idn2_check_version(IDN2_VERSION)) {
1715       char *ace_hostname = NULL;
1716 #if IDN2_VERSION_NUMBER >= 0x00140000
1717       /* IDN2_NFC_INPUT: Normalize input string using normalization form C.
1718          IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional
1719          processing. */
1720       int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL;
1721 #else
1722       int flags = IDN2_NFC_INPUT;
1723 #endif
1724       int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags);
1725       if(rc == IDN2_OK) {
1726         host->encalloc = (char *)ace_hostname;
1727         /* change the name pointer to point to the encoded hostname */
1728         host->name = host->encalloc;
1729       }
1730       else {
1731         failf(data, "Failed to convert %s to ACE; %s\n", host->name,
1732               idn2_strerror(rc));
1733         return CURLE_URL_MALFORMAT;
1734       }
1735     }
1736 #elif defined(USE_WIN32_IDN)
1737     char *ace_hostname = NULL;
1738
1739     if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
1740       host->encalloc = ace_hostname;
1741       /* change the name pointer to point to the encoded hostname */
1742       host->name = host->encalloc;
1743     }
1744     else {
1745       failf(data, "Failed to convert %s to ACE;\n", host->name);
1746       return CURLE_URL_MALFORMAT;
1747 #elif defined(USE_ICU_IDNA)
1748     char *ace_hostname = malloc(MAX_DOMAIN_NAME_LEN * sizeof(char));
1749     UErrorCode errorCode = U_ZERO_ERROR;
1750     UIDNAInfo info = UIDNA_INFO_INITIALIZER;
1751     UIDNA *uts46 =
1752       uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE,
1753       &errorCode);
1754     int32_t length = uidna_nameToASCII_UTF8(uts46,
1755       host->name, strlen(host->name),
1756       ace_hostname, MAX_DOMAIN_NAME_LEN, &info, &errorCode);
1757     uidna_close(uts46);
1758
1759     if(errorCode != U_ZERO_ERROR || info.errors || length < 1)
1760       infof(data, "Failed to convert %s to ACE;\n", host->name);
1761     else {
1762       host->encalloc = ace_hostname;
1763       host->name = host->encalloc;
1764     }
1765 #else
1766     infof(data, "IDN support not present, can't parse Unicode domains\n");
1767 #endif
1768   }
1769   {
1770     char *hostp;
1771     for(hostp = host->name; *hostp; hostp++) {
1772       if(*hostp <= 32) {
1773         failf(data, "Host name '%s' contains bad letter", host->name);
1774         return CURLE_URL_MALFORMAT;
1775       }
1776     }
1777   }
1778   return CURLE_OK;
1779 }
1780
1781 /*
1782  * Frees data allocated by fix_hostname()
1783  */
1784 static void free_fixed_hostname(struct hostname *host)
1785 {
1786 #if defined(USE_LIBIDN2)
1787   if(host->encalloc) {
1788     idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
1789                                  allocated by libidn */
1790     host->encalloc = NULL;
1791   }
1792 #elif defined(USE_WIN32_IDN)
1793   free(host->encalloc); /* must be freed with free() since this was
1794                            allocated by curl_win32_idn_to_ascii */
1795   host->encalloc = NULL;
1796 #elif defined(USE_ICU_IDNA)
1797   free(host->encalloc);
1798   host->encalloc = NULL;
1799 #else
1800   (void)host;
1801 #endif
1802 }
1803
1804 static void llist_dtor(void *user, void *element)
1805 {
1806   (void)user;
1807   (void)element;
1808   /* Do nothing */
1809 }
1810
1811 /*
1812  * Allocate and initialize a new connectdata object.
1813  */
1814 static struct connectdata *allocate_conn(struct Curl_easy *data)
1815 {
1816   struct connectdata *conn = calloc(1, sizeof(struct connectdata));
1817   if(!conn)
1818     return NULL;
1819
1820 #ifdef USE_SSL
1821   /* The SSL backend-specific data (ssl_backend_data) objects are allocated as
1822      a separate array to ensure suitable alignment.
1823      Note that these backend pointers can be swapped by vtls (eg ssl backend
1824      data becomes proxy backend data). */
1825   {
1826     size_t sslsize = Curl_ssl->sizeof_ssl_backend_data;
1827     char *ssl = calloc(4, sslsize);
1828     if(!ssl) {
1829       free(conn);
1830       return NULL;
1831     }
1832     conn->ssl_extra = ssl;
1833     conn->ssl[0].backend = (void *)ssl;
1834     conn->ssl[1].backend = (void *)(ssl + sslsize);
1835     conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize);
1836     conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize);
1837   }
1838 #endif
1839
1840   conn->handler = &Curl_handler_dummy;  /* Be sure we have a handler defined
1841                                            already from start to avoid NULL
1842                                            situations and checks */
1843
1844   /* and we setup a few fields in case we end up actually using this struct */
1845
1846   conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD;     /* no file descriptor */
1847   conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
1848   conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
1849   conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
1850   conn->connection_id = -1;    /* no ID */
1851   conn->port = -1; /* unknown at this point */
1852   conn->remote_port = -1; /* unknown at this point */
1853 #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
1854   conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
1855   conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
1856 #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
1857
1858   /* Default protocol-independent behavior doesn't support persistent
1859      connections, so we set this to force-close. Protocols that support
1860      this need to set this to FALSE in their "curl_do" functions. */
1861   connclose(conn, "Default to force-close");
1862
1863   /* Store creation time to help future close decision making */
1864   conn->created = Curl_now();
1865
1866   /* Store current time to give a baseline to keepalive connection times. */
1867   conn->keepalive = Curl_now();
1868
1869   /* Store off the configured connection upkeep time. */
1870   conn->upkeep_interval_ms = data->set.upkeep_interval_ms;
1871
1872   conn->data = data; /* Setup the association between this connection
1873                         and the Curl_easy */
1874
1875   conn->http_proxy.proxytype = data->set.proxytype;
1876   conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
1877
1878 #ifdef CURL_DISABLE_PROXY
1879
1880   conn->bits.proxy = FALSE;
1881   conn->bits.httpproxy = FALSE;
1882   conn->bits.socksproxy = FALSE;
1883   conn->bits.proxy_user_passwd = FALSE;
1884   conn->bits.tunnel_proxy = FALSE;
1885
1886 #else /* CURL_DISABLE_PROXY */
1887
1888   /* note that these two proxy bits are now just on what looks to be
1889      requested, they may be altered down the road */
1890   conn->bits.proxy = (data->set.str[STRING_PROXY] &&
1891                       *data->set.str[STRING_PROXY]) ? TRUE : FALSE;
1892   conn->bits.httpproxy = (conn->bits.proxy &&
1893                           (conn->http_proxy.proxytype == CURLPROXY_HTTP ||
1894                            conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
1895                            conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
1896                            TRUE : FALSE;
1897   conn->bits.socksproxy = (conn->bits.proxy &&
1898                            !conn->bits.httpproxy) ? TRUE : FALSE;
1899
1900   if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
1901     conn->bits.proxy = TRUE;
1902     conn->bits.socksproxy = TRUE;
1903   }
1904
1905   conn->bits.proxy_user_passwd =
1906     (data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
1907   conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
1908
1909 #endif /* CURL_DISABLE_PROXY */
1910
1911   conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
1912   conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
1913   conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
1914
1915   conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
1916   conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
1917   conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost;
1918   conn->proxy_ssl_config.verifystatus =
1919     data->set.proxy_ssl.primary.verifystatus;
1920   conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
1921   conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
1922
1923   conn->ip_version = data->set.ipver;
1924
1925 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
1926     defined(NTLM_WB_ENABLED)
1927   conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
1928   conn->ntlm_auth_hlpr_pid = 0;
1929   conn->challenge_header = NULL;
1930   conn->response_header = NULL;
1931 #endif
1932
1933   if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
1934      !conn->master_buffer) {
1935     /* Allocate master_buffer to be used for HTTP/1 pipelining */
1936     conn->master_buffer = calloc(MASTERBUF_SIZE, sizeof(char));
1937     if(!conn->master_buffer)
1938       goto error;
1939   }
1940
1941   /* Initialize the pipeline lists */
1942   Curl_llist_init(&conn->send_pipe, (curl_llist_dtor) llist_dtor);
1943   Curl_llist_init(&conn->recv_pipe, (curl_llist_dtor) llist_dtor);
1944
1945 #ifdef HAVE_GSSAPI
1946   conn->data_prot = PROT_CLEAR;
1947 #endif
1948
1949   /* Store the local bind parameters that will be used for this connection */
1950   if(data->set.str[STRING_DEVICE]) {
1951     conn->localdev = strdup(data->set.str[STRING_DEVICE]);
1952     if(!conn->localdev)
1953       goto error;
1954   }
1955   conn->localportrange = data->set.localportrange;
1956   conn->localport = data->set.localport;
1957
1958   /* the close socket stuff needs to be copied to the connection struct as
1959      it may live on without (this specific) Curl_easy */
1960   conn->fclosesocket = data->set.fclosesocket;
1961   conn->closesocket_client = data->set.closesocket_client;
1962
1963   return conn;
1964   error:
1965
1966   Curl_llist_destroy(&conn->send_pipe, NULL);
1967   Curl_llist_destroy(&conn->recv_pipe, NULL);
1968
1969   free(conn->master_buffer);
1970   free(conn->localdev);
1971 #ifdef USE_SSL
1972   free(conn->ssl_extra);
1973 #endif
1974   free(conn);
1975   return NULL;
1976 }
1977
1978 /* returns the handler if the given scheme is built-in */
1979 const struct Curl_handler *Curl_builtin_scheme(const char *scheme)
1980 {
1981   const struct Curl_handler * const *pp;
1982   const struct Curl_handler *p;
1983   /* Scan protocol handler table and match against 'scheme'. The handler may
1984      be changed later when the protocol specific setup function is called. */
1985   for(pp = protocols; (p = *pp) != NULL; pp++)
1986     if(strcasecompare(p->scheme, scheme))
1987       /* Protocol found in table. Check if allowed */
1988       return p;
1989   return NULL; /* not found */
1990 }
1991
1992
1993 static CURLcode findprotocol(struct Curl_easy *data,
1994                              struct connectdata *conn,
1995                              const char *protostr)
1996 {
1997   const struct Curl_handler *p = Curl_builtin_scheme(protostr);
1998
1999   if(p && /* Protocol found in table. Check if allowed */
2000      (data->set.allowed_protocols & p->protocol)) {
2001
2002     /* it is allowed for "normal" request, now do an extra check if this is
2003        the result of a redirect */
2004     if(data->state.this_is_a_follow &&
2005        !(data->set.redir_protocols & p->protocol))
2006       /* nope, get out */
2007       ;
2008     else {
2009       /* Perform setup complement if some. */
2010       conn->handler = conn->given = p;
2011
2012       /* 'port' and 'remote_port' are set in setup_connection_internals() */
2013       return CURLE_OK;
2014     }
2015   }
2016
2017   /* The protocol was not found in the table, but we don't have to assign it
2018      to anything since it is already assigned to a dummy-struct in the
2019      create_conn() function when the connectdata struct is allocated. */
2020   failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
2021         protostr);
2022
2023   return CURLE_UNSUPPORTED_PROTOCOL;
2024 }
2025
2026
2027 CURLcode Curl_uc_to_curlcode(CURLUcode uc)
2028 {
2029   switch(uc) {
2030   default:
2031     return CURLE_URL_MALFORMAT;
2032   case CURLUE_UNSUPPORTED_SCHEME:
2033     return CURLE_UNSUPPORTED_PROTOCOL;
2034   case CURLUE_OUT_OF_MEMORY:
2035     return CURLE_OUT_OF_MEMORY;
2036   case CURLUE_USER_NOT_ALLOWED:
2037     return CURLE_LOGIN_DENIED;
2038   }
2039 }
2040
2041 /*
2042  * Parse URL and fill in the relevant members of the connection struct.
2043  */
2044 static CURLcode parseurlandfillconn(struct Curl_easy *data,
2045                                     struct connectdata *conn)
2046 {
2047   CURLcode result;
2048   CURLU *uh;
2049   CURLUcode uc;
2050   char *hostname;
2051
2052   Curl_up_free(data); /* cleanup previous leftovers first */
2053
2054   /* parse the URL */
2055   uh = data->state.uh = curl_url();
2056   if(!uh)
2057     return CURLE_OUT_OF_MEMORY;
2058
2059   if(data->set.str[STRING_DEFAULT_PROTOCOL] &&
2060      !Curl_is_absolute_url(data->change.url, NULL, MAX_SCHEME_LEN)) {
2061     char *url;
2062     if(data->change.url_alloc)
2063       free(data->change.url);
2064     url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL],
2065                   data->change.url);
2066     if(!url)
2067       return CURLE_OUT_OF_MEMORY;
2068     data->change.url = url;
2069     data->change.url_alloc = TRUE;
2070   }
2071
2072   uc = curl_url_set(uh, CURLUPART_URL, data->change.url,
2073                     CURLU_GUESS_SCHEME |
2074                     CURLU_NON_SUPPORT_SCHEME |
2075                     (data->set.disallow_username_in_url ?
2076                      CURLU_DISALLOW_USER : 0) |
2077                     (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
2078   if(uc)
2079     return Curl_uc_to_curlcode(uc);
2080
2081   uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0);
2082   if(uc)
2083     return Curl_uc_to_curlcode(uc);
2084
2085   result = findprotocol(data, conn, data->state.up.scheme);
2086   if(result)
2087     return result;
2088
2089   uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user,
2090                     CURLU_URLDECODE);
2091   if(!uc) {
2092     conn->user = strdup(data->state.up.user);
2093     if(!conn->user)
2094       return CURLE_OUT_OF_MEMORY;
2095     conn->bits.user_passwd = TRUE;
2096   }
2097   else if(uc != CURLUE_NO_USER)
2098     return Curl_uc_to_curlcode(uc);
2099
2100   uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password,
2101                     CURLU_URLDECODE);
2102   if(!uc) {
2103     conn->passwd = strdup(data->state.up.password);
2104     if(!conn->passwd)
2105       return CURLE_OUT_OF_MEMORY;
2106     conn->bits.user_passwd = TRUE;
2107   }
2108   else if(uc != CURLUE_NO_PASSWORD)
2109     return Curl_uc_to_curlcode(uc);
2110
2111   uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options,
2112                     CURLU_URLDECODE);
2113   if(!uc) {
2114     conn->options = strdup(data->state.up.options);
2115     if(!conn->options)
2116       return CURLE_OUT_OF_MEMORY;
2117   }
2118   else if(uc != CURLUE_NO_OPTIONS)
2119     return Curl_uc_to_curlcode(uc);
2120
2121   uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0);
2122   if(uc) {
2123     if(!strcasecompare("file", data->state.up.scheme))
2124       return CURLE_OUT_OF_MEMORY;
2125   }
2126
2127   uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, 0);
2128   if(uc)
2129     return Curl_uc_to_curlcode(uc);
2130
2131   uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port,
2132                     CURLU_DEFAULT_PORT);
2133   if(uc) {
2134     if(!strcasecompare("file", data->state.up.scheme))
2135       return CURLE_OUT_OF_MEMORY;
2136   }
2137   else {
2138     unsigned long port = strtoul(data->state.up.port, NULL, 10);
2139     conn->remote_port = curlx_ultous(port);
2140   }
2141
2142   (void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0);
2143
2144   hostname = data->state.up.hostname;
2145   if(!hostname)
2146     /* this is for file:// transfers, get a dummy made */
2147     hostname = (char *)"";
2148
2149   if(hostname[0] == '[') {
2150     /* This looks like an IPv6 address literal.  See if there is an address
2151        scope. */
2152     char *percent = strchr(++hostname, '%');
2153     conn->bits.ipv6_ip = TRUE;
2154     if(percent) {
2155       unsigned int identifier_offset = 3;
2156       char *endp;
2157       unsigned long scope;
2158       if(strncmp("%25", percent, 3) != 0) {
2159         infof(data,
2160               "Please URL encode %% as %%25, see RFC 6874.\n");
2161         identifier_offset = 1;
2162       }
2163       scope = strtoul(percent + identifier_offset, &endp, 10);
2164       if(*endp == ']') {
2165         /* The address scope was well formed.  Knock it out of the
2166            hostname. */
2167         memmove(percent, endp, strlen(endp) + 1);
2168         conn->scope_id = (unsigned int)scope;
2169       }
2170       else {
2171         /* Zone identifier is not numeric */
2172 #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
2173         char ifname[IFNAMSIZ + 2];
2174         char *square_bracket;
2175         unsigned int scopeidx = 0;
2176         strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
2177         /* Ensure nullbyte termination */
2178         ifname[IFNAMSIZ + 1] = '\0';
2179         square_bracket = strchr(ifname, ']');
2180         if(square_bracket) {
2181           /* Remove ']' */
2182           *square_bracket = '\0';
2183           scopeidx = if_nametoindex(ifname);
2184           if(scopeidx == 0) {
2185             infof(data, "Invalid network interface: %s; %s\n", ifname,
2186                   strerror(errno));
2187           }
2188         }
2189         if(scopeidx > 0) {
2190           char *p = percent + identifier_offset + strlen(ifname);
2191
2192           /* Remove zone identifier from hostname */
2193           memmove(percent, p, strlen(p) + 1);
2194           conn->scope_id = scopeidx;
2195         }
2196         else
2197 #endif /* HAVE_NET_IF_H && IFNAMSIZ */
2198           infof(data, "Invalid IPv6 address format\n");
2199       }
2200     }
2201     percent = strchr(hostname, ']');
2202     if(percent)
2203       /* terminate IPv6 numerical at end bracket */
2204       *percent = 0;
2205   }
2206
2207   /* make sure the connect struct gets its own copy of the host name */
2208   conn->host.rawalloc = strdup(hostname);
2209   if(!conn->host.rawalloc)
2210     return CURLE_OUT_OF_MEMORY;
2211   conn->host.name = conn->host.rawalloc;
2212
2213   if(data->set.scope_id)
2214     /* Override any scope that was set above.  */
2215     conn->scope_id = data->set.scope_id;
2216
2217   return CURLE_OK;
2218 }
2219
2220 /*
2221  * If we're doing a resumed transfer, we need to setup our stuff
2222  * properly.
2223  */
2224 static CURLcode setup_range(struct Curl_easy *data)
2225 {
2226   struct UrlState *s = &data->state;
2227   s->resume_from = data->set.set_resume_from;
2228   if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
2229     if(s->rangestringalloc)
2230       free(s->range);
2231
2232     if(s->resume_from)
2233       s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from);
2234     else
2235       s->range = strdup(data->set.str[STRING_SET_RANGE]);
2236
2237     s->rangestringalloc = (s->range) ? TRUE : FALSE;
2238
2239     if(!s->range)
2240       return CURLE_OUT_OF_MEMORY;
2241
2242     /* tell ourselves to fetch this range */
2243     s->use_range = TRUE;        /* enable range download */
2244   }
2245   else
2246     s->use_range = FALSE; /* disable range download */
2247
2248   return CURLE_OK;
2249 }
2250
2251
2252 /*
2253  * setup_connection_internals() -
2254  *
2255  * Setup connection internals specific to the requested protocol in the
2256  * Curl_easy. This is inited and setup before the connection is made but
2257  * is about the particular protocol that is to be used.
2258  *
2259  * This MUST get called after proxy magic has been figured out.
2260  */
2261 static CURLcode setup_connection_internals(struct connectdata *conn)
2262 {
2263   const struct Curl_handler * p;
2264   CURLcode result;
2265   conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
2266
2267   /* Perform setup complement if some. */
2268   p = conn->handler;
2269
2270   if(p->setup_connection) {
2271     result = (*p->setup_connection)(conn);
2272
2273     if(result)
2274       return result;
2275
2276     p = conn->handler;              /* May have changed. */
2277   }
2278
2279   if(conn->port < 0)
2280     /* we check for -1 here since if proxy was detected already, this
2281        was very likely already set to the proxy port */
2282     conn->port = p->defport;
2283
2284   return CURLE_OK;
2285 }
2286
2287 /*
2288  * Curl_free_request_state() should free temp data that was allocated in the
2289  * Curl_easy for this single request.
2290  */
2291
2292 void Curl_free_request_state(struct Curl_easy *data)
2293 {
2294   Curl_safefree(data->req.protop);
2295   Curl_safefree(data->req.newurl);
2296 }
2297
2298
2299 #ifndef CURL_DISABLE_PROXY
2300 /****************************************************************
2301 * Checks if the host is in the noproxy list. returns true if it matches
2302 * and therefore the proxy should NOT be used.
2303 ****************************************************************/
2304 static bool check_noproxy(const char *name, const char *no_proxy)
2305 {
2306   /* no_proxy=domain1.dom,host.domain2.dom
2307    *   (a comma-separated list of hosts which should
2308    *   not be proxied, or an asterisk to override
2309    *   all proxy variables)
2310    */
2311   if(no_proxy && no_proxy[0]) {
2312     size_t tok_start;
2313     size_t tok_end;
2314     const char *separator = ", ";
2315     size_t no_proxy_len;
2316     size_t namelen;
2317     char *endptr;
2318     if(strcasecompare("*", no_proxy)) {
2319       return TRUE;
2320     }
2321
2322     /* NO_PROXY was specified and it wasn't just an asterisk */
2323
2324     no_proxy_len = strlen(no_proxy);
2325     if(name[0] == '[') {
2326       /* IPv6 numerical address */
2327       endptr = strchr(name, ']');
2328       if(!endptr)
2329         return FALSE;
2330       name++;
2331       namelen = endptr - name;
2332     }
2333     else
2334       namelen = strlen(name);
2335
2336     for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
2337       while(tok_start < no_proxy_len &&
2338             strchr(separator, no_proxy[tok_start]) != NULL) {
2339         /* Look for the beginning of the token. */
2340         ++tok_start;
2341       }
2342
2343       if(tok_start == no_proxy_len)
2344         break; /* It was all trailing separator chars, no more tokens. */
2345
2346       for(tok_end = tok_start; tok_end < no_proxy_len &&
2347             strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
2348         /* Look for the end of the token. */
2349         ;
2350
2351       /* To match previous behaviour, where it was necessary to specify
2352        * ".local.com" to prevent matching "notlocal.com", we will leave
2353        * the '.' off.
2354        */
2355       if(no_proxy[tok_start] == '.')
2356         ++tok_start;
2357
2358       if((tok_end - tok_start) <= namelen) {
2359         /* Match the last part of the name to the domain we are checking. */
2360         const char *checkn = name + namelen - (tok_end - tok_start);
2361         if(strncasecompare(no_proxy + tok_start, checkn,
2362                            tok_end - tok_start)) {
2363           if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
2364             /* We either have an exact match, or the previous character is a .
2365              * so it is within the same domain, so no proxy for this host.
2366              */
2367             return TRUE;
2368           }
2369         }
2370       } /* if((tok_end - tok_start) <= namelen) */
2371     } /* for(tok_start = 0; tok_start < no_proxy_len;
2372          tok_start = tok_end + 1) */
2373   } /* NO_PROXY was specified and it wasn't just an asterisk */
2374
2375   return FALSE;
2376 }
2377
2378 #ifndef CURL_DISABLE_HTTP
2379 /****************************************************************
2380 * Detect what (if any) proxy to use. Remember that this selects a host
2381 * name and is not limited to HTTP proxies only.
2382 * The returned pointer must be freed by the caller (unless NULL)
2383 ****************************************************************/
2384 static char *detect_proxy(struct connectdata *conn)
2385 {
2386   char *proxy = NULL;
2387
2388   /* If proxy was not specified, we check for default proxy environment
2389    * variables, to enable i.e Lynx compliance:
2390    *
2391    * http_proxy=http://some.server.dom:port/
2392    * https_proxy=http://some.server.dom:port/
2393    * ftp_proxy=http://some.server.dom:port/
2394    * no_proxy=domain1.dom,host.domain2.dom
2395    *   (a comma-separated list of hosts which should
2396    *   not be proxied, or an asterisk to override
2397    *   all proxy variables)
2398    * all_proxy=http://some.server.dom:port/
2399    *   (seems to exist for the CERN www lib. Probably
2400    *   the first to check for.)
2401    *
2402    * For compatibility, the all-uppercase versions of these variables are
2403    * checked if the lowercase versions don't exist.
2404    */
2405   char proxy_env[128];
2406   const char *protop = conn->handler->scheme;
2407   char *envp = proxy_env;
2408   char *prox;
2409
2410   /* Now, build <protocol>_proxy and check for such a one to use */
2411   while(*protop)
2412     *envp++ = (char)tolower((int)*protop++);
2413
2414   /* append _proxy */
2415   strcpy(envp, "_proxy");
2416
2417   /* read the protocol proxy: */
2418   prox = curl_getenv(proxy_env);
2419
2420   /*
2421    * We don't try the uppercase version of HTTP_PROXY because of
2422    * security reasons:
2423    *
2424    * When curl is used in a webserver application
2425    * environment (cgi or php), this environment variable can
2426    * be controlled by the web server user by setting the
2427    * http header 'Proxy:' to some value.
2428    *
2429    * This can cause 'internal' http/ftp requests to be
2430    * arbitrarily redirected by any external attacker.
2431    */
2432   if(!prox && !strcasecompare("http_proxy", proxy_env)) {
2433     /* There was no lowercase variable, try the uppercase version: */
2434     Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
2435     prox = curl_getenv(proxy_env);
2436   }
2437
2438   envp = proxy_env;
2439   if(prox) {
2440     proxy = prox; /* use this */
2441   }
2442   else {
2443     envp = (char *)"all_proxy";
2444     proxy = curl_getenv(envp); /* default proxy to use */
2445     if(!proxy) {
2446       envp = (char *)"ALL_PROXY";
2447       proxy = curl_getenv(envp);
2448     }
2449   }
2450   if(proxy)
2451     infof(conn->data, "Uses proxy env variable %s == '%s'\n", envp, proxy);
2452
2453   return proxy;
2454 }
2455 #endif /* CURL_DISABLE_HTTP */
2456
2457 /*
2458  * If this is supposed to use a proxy, we need to figure out the proxy
2459  * host name, so that we can re-use an existing connection
2460  * that may exist registered to the same proxy host.
2461  */
2462 static CURLcode parse_proxy(struct Curl_easy *data,
2463                             struct connectdata *conn, char *proxy,
2464                             curl_proxytype proxytype)
2465 {
2466   char *prox_portno;
2467   char *endofprot;
2468
2469   /* We use 'proxyptr' to point to the proxy name from now on... */
2470   char *proxyptr;
2471   char *portptr;
2472   char *atsign;
2473   long port = -1;
2474   char *proxyuser = NULL;
2475   char *proxypasswd = NULL;
2476   bool sockstype;
2477
2478   /* We do the proxy host string parsing here. We want the host name and the
2479    * port name. Accept a protocol:// prefix
2480    */
2481
2482   /* Parse the protocol part if present */
2483   endofprot = strstr(proxy, "://");
2484   if(endofprot) {
2485     proxyptr = endofprot + 3;
2486     if(checkprefix("https", proxy))
2487       proxytype = CURLPROXY_HTTPS;
2488     else if(checkprefix("socks5h", proxy))
2489       proxytype = CURLPROXY_SOCKS5_HOSTNAME;
2490     else if(checkprefix("socks5", proxy))
2491       proxytype = CURLPROXY_SOCKS5;
2492     else if(checkprefix("socks4a", proxy))
2493       proxytype = CURLPROXY_SOCKS4A;
2494     else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
2495       proxytype = CURLPROXY_SOCKS4;
2496     else if(checkprefix("http:", proxy))
2497       ; /* leave it as HTTP or HTTP/1.0 */
2498     else {
2499       /* Any other xxx:// reject! */
2500       failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
2501       return CURLE_COULDNT_CONNECT;
2502     }
2503   }
2504   else
2505     proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
2506
2507 #ifdef USE_SSL
2508   if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY))
2509 #endif
2510     if(proxytype == CURLPROXY_HTTPS) {
2511       failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
2512                   "HTTPS-proxy support.", proxy);
2513       return CURLE_NOT_BUILT_IN;
2514     }
2515
2516   sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
2517               proxytype == CURLPROXY_SOCKS5 ||
2518               proxytype == CURLPROXY_SOCKS4A ||
2519               proxytype == CURLPROXY_SOCKS4;
2520
2521   /* Is there a username and password given in this proxy url? */
2522   atsign = strchr(proxyptr, '@');
2523   if(atsign) {
2524     CURLcode result =
2525       Curl_parse_login_details(proxyptr, atsign - proxyptr,
2526                                &proxyuser, &proxypasswd, NULL);
2527     if(result)
2528       return result;
2529     proxyptr = atsign + 1;
2530   }
2531
2532   /* start scanning for port number at this point */
2533   portptr = proxyptr;
2534
2535   /* detect and extract RFC6874-style IPv6-addresses */
2536   if(*proxyptr == '[') {
2537     char *ptr = ++proxyptr; /* advance beyond the initial bracket */
2538     while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
2539       ptr++;
2540     if(*ptr == '%') {
2541       /* There might be a zone identifier */
2542       if(strncmp("%25", ptr, 3))
2543         infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
2544       ptr++;
2545       /* Allow unreserved characters as defined in RFC 3986 */
2546       while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
2547                      (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
2548         ptr++;
2549     }
2550     if(*ptr == ']')
2551       /* yeps, it ended nicely with a bracket as well */
2552       *ptr++ = 0;
2553     else
2554       infof(data, "Invalid IPv6 address format\n");
2555     portptr = ptr;
2556     /* Note that if this didn't end with a bracket, we still advanced the
2557      * proxyptr first, but I can't see anything wrong with that as no host
2558      * name nor a numeric can legally start with a bracket.
2559      */
2560   }
2561
2562   /* Get port number off proxy.server.com:1080 */
2563   prox_portno = strchr(portptr, ':');
2564   if(prox_portno) {
2565     char *endp = NULL;
2566
2567     *prox_portno = 0x0; /* cut off number from host name */
2568     prox_portno ++;
2569     /* now set the local port number */
2570     port = strtol(prox_portno, &endp, 10);
2571     if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
2572        (port < 0) || (port > 65535)) {
2573       /* meant to detect for example invalid IPv6 numerical addresses without
2574          brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
2575          because we then allow "URL style" with the number followed by a
2576          slash, used in curl test cases already. Space is also an acceptable
2577          terminating symbol. */
2578       infof(data, "No valid port number in proxy string (%s)\n",
2579             prox_portno);
2580     }
2581     else
2582       conn->port = port;
2583   }
2584   else {
2585     if(proxyptr[0]=='/') {
2586       /* If the first character in the proxy string is a slash, fail
2587          immediately. The following code will otherwise clear the string which
2588          will lead to code running as if no proxy was set! */
2589       Curl_safefree(proxyuser);
2590       Curl_safefree(proxypasswd);
2591       return CURLE_COULDNT_RESOLVE_PROXY;
2592     }
2593
2594     /* without a port number after the host name, some people seem to use
2595        a slash so we strip everything from the first slash */
2596     atsign = strchr(proxyptr, '/');
2597     if(atsign)
2598       *atsign = '\0'; /* cut off path part from host name */
2599
2600     if(data->set.proxyport)
2601       /* None given in the proxy string, then get the default one if it is
2602          given */
2603       port = data->set.proxyport;
2604     else {
2605       if(proxytype == CURLPROXY_HTTPS)
2606         port = CURL_DEFAULT_HTTPS_PROXY_PORT;
2607       else
2608         port = CURL_DEFAULT_PROXY_PORT;
2609     }
2610   }
2611
2612   if(*proxyptr) {
2613     struct proxy_info *proxyinfo =
2614       sockstype ? &conn->socks_proxy : &conn->http_proxy;
2615     proxyinfo->proxytype = proxytype;
2616
2617     if(proxyuser) {
2618       /* found user and password, rip them out.  note that we are unescaping
2619          them, as there is otherwise no way to have a username or password
2620          with reserved characters like ':' in them. */
2621       Curl_safefree(proxyinfo->user);
2622       proxyinfo->user = curl_easy_unescape(data, proxyuser, 0, NULL);
2623       Curl_safefree(proxyuser);
2624
2625       if(!proxyinfo->user) {
2626         Curl_safefree(proxypasswd);
2627         return CURLE_OUT_OF_MEMORY;
2628       }
2629
2630       Curl_safefree(proxyinfo->passwd);
2631       if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
2632         proxyinfo->passwd = curl_easy_unescape(data, proxypasswd, 0, NULL);
2633       else
2634         proxyinfo->passwd = strdup("");
2635       Curl_safefree(proxypasswd);
2636
2637       if(!proxyinfo->passwd)
2638         return CURLE_OUT_OF_MEMORY;
2639
2640       conn->bits.proxy_user_passwd = TRUE; /* enable it */
2641     }
2642
2643     if(port >= 0) {
2644       proxyinfo->port = port;
2645       if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
2646         conn->port = port;
2647     }
2648
2649     /* now, clone the cleaned proxy host name */
2650     Curl_safefree(proxyinfo->host.rawalloc);
2651     proxyinfo->host.rawalloc = strdup(proxyptr);
2652     proxyinfo->host.name = proxyinfo->host.rawalloc;
2653
2654     if(!proxyinfo->host.rawalloc)
2655       return CURLE_OUT_OF_MEMORY;
2656   }
2657
2658   Curl_safefree(proxyuser);
2659   Curl_safefree(proxypasswd);
2660
2661   return CURLE_OK;
2662 }
2663
2664 /*
2665  * Extract the user and password from the authentication string
2666  */
2667 static CURLcode parse_proxy_auth(struct Curl_easy *data,
2668                                  struct connectdata *conn)
2669 {
2670   char proxyuser[MAX_CURL_USER_LENGTH]="";
2671   char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
2672   CURLcode result;
2673
2674   if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
2675     strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
2676             MAX_CURL_USER_LENGTH);
2677     proxyuser[MAX_CURL_USER_LENGTH-1] = '\0';   /*To be on safe side*/
2678   }
2679   if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
2680     strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
2681             MAX_CURL_PASSWORD_LENGTH);
2682     proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
2683   }
2684
2685   result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
2686                           FALSE);
2687   if(!result)
2688     result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
2689                             NULL, FALSE);
2690   return result;
2691 }
2692
2693 /* create_conn helper to parse and init proxy values. to be called after unix
2694    socket init but before any proxy vars are evaluated. */
2695 static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
2696 {
2697   char *proxy = NULL;
2698   char *socksproxy = NULL;
2699   char *no_proxy = NULL;
2700   CURLcode result = CURLE_OK;
2701   struct Curl_easy *data = conn->data;
2702
2703   /*************************************************************
2704    * Extract the user and password from the authentication string
2705    *************************************************************/
2706   if(conn->bits.proxy_user_passwd) {
2707     result = parse_proxy_auth(data, conn);
2708     if(result)
2709       goto out;
2710   }
2711
2712   /*************************************************************
2713    * Detect what (if any) proxy to use
2714    *************************************************************/
2715   if(data->set.str[STRING_PROXY]) {
2716     proxy = strdup(data->set.str[STRING_PROXY]);
2717     /* if global proxy is set, this is it */
2718     if(NULL == proxy) {
2719       failf(data, "memory shortage");
2720       result = CURLE_OUT_OF_MEMORY;
2721       goto out;
2722     }
2723   }
2724
2725   if(data->set.str[STRING_PRE_PROXY]) {
2726     socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
2727     /* if global socks proxy is set, this is it */
2728     if(NULL == socksproxy) {
2729       failf(data, "memory shortage");
2730       result = CURLE_OUT_OF_MEMORY;
2731       goto out;
2732     }
2733   }
2734
2735   if(!data->set.str[STRING_NOPROXY]) {
2736     const char *p = "no_proxy";
2737     no_proxy = curl_getenv(p);
2738     if(!no_proxy) {
2739       p = "NO_PROXY";
2740       no_proxy = curl_getenv(p);
2741     }
2742     if(no_proxy) {
2743       infof(conn->data, "Uses proxy env variable %s == '%s'\n", p, no_proxy);
2744     }
2745   }
2746
2747   if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
2748       data->set.str[STRING_NOPROXY] : no_proxy)) {
2749     Curl_safefree(proxy);
2750     Curl_safefree(socksproxy);
2751   }
2752 #ifndef CURL_DISABLE_HTTP
2753   else if(!proxy && !socksproxy)
2754     /* if the host is not in the noproxy list, detect proxy. */
2755     proxy = detect_proxy(conn);
2756 #endif /* CURL_DISABLE_HTTP */
2757
2758   Curl_safefree(no_proxy);
2759
2760 #ifdef USE_UNIX_SOCKETS
2761   /* For the time being do not mix proxy and unix domain sockets. See #1274 */
2762   if(proxy && conn->unix_domain_socket) {
2763     free(proxy);
2764     proxy = NULL;
2765   }
2766 #endif
2767
2768   if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
2769     free(proxy);  /* Don't bother with an empty proxy string or if the
2770                      protocol doesn't work with network */
2771     proxy = NULL;
2772   }
2773   if(socksproxy && (!*socksproxy ||
2774                     (conn->handler->flags & PROTOPT_NONETWORK))) {
2775     free(socksproxy);  /* Don't bother with an empty socks proxy string or if
2776                           the protocol doesn't work with network */
2777     socksproxy = NULL;
2778   }
2779
2780   /***********************************************************************
2781    * If this is supposed to use a proxy, we need to figure out the proxy host
2782    * name, proxy type and port number, so that we can re-use an existing
2783    * connection that may exist registered to the same proxy host.
2784    ***********************************************************************/
2785   if(proxy || socksproxy) {
2786     if(proxy) {
2787       result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype);
2788       Curl_safefree(proxy); /* parse_proxy copies the proxy string */
2789       if(result)
2790         goto out;
2791     }
2792
2793     if(socksproxy) {
2794       result = parse_proxy(data, conn, socksproxy,
2795                            conn->socks_proxy.proxytype);
2796       /* parse_proxy copies the socks proxy string */
2797       Curl_safefree(socksproxy);
2798       if(result)
2799         goto out;
2800     }
2801
2802     if(conn->http_proxy.host.rawalloc) {
2803 #ifdef CURL_DISABLE_HTTP
2804       /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
2805       result = CURLE_UNSUPPORTED_PROTOCOL;
2806       goto out;
2807 #else
2808       /* force this connection's protocol to become HTTP if compatible */
2809       if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
2810         if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
2811            !conn->bits.tunnel_proxy)
2812           conn->handler = &Curl_handler_http;
2813         else
2814           /* if not converting to HTTP over the proxy, enforce tunneling */
2815           conn->bits.tunnel_proxy = TRUE;
2816       }
2817       conn->bits.httpproxy = TRUE;
2818 #endif
2819     }
2820     else {
2821       conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
2822       conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
2823     }
2824
2825     if(conn->socks_proxy.host.rawalloc) {
2826       if(!conn->http_proxy.host.rawalloc) {
2827         /* once a socks proxy */
2828         if(!conn->socks_proxy.user) {
2829           conn->socks_proxy.user = conn->http_proxy.user;
2830           conn->http_proxy.user = NULL;
2831           Curl_safefree(conn->socks_proxy.passwd);
2832           conn->socks_proxy.passwd = conn->http_proxy.passwd;
2833           conn->http_proxy.passwd = NULL;
2834         }
2835       }
2836       conn->bits.socksproxy = TRUE;
2837     }
2838     else
2839       conn->bits.socksproxy = FALSE; /* not a socks proxy */
2840   }
2841   else {
2842     conn->bits.socksproxy = FALSE;
2843     conn->bits.httpproxy = FALSE;
2844   }
2845   conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
2846
2847   if(!conn->bits.proxy) {
2848     /* we aren't using the proxy after all... */
2849     conn->bits.proxy = FALSE;
2850     conn->bits.httpproxy = FALSE;
2851     conn->bits.socksproxy = FALSE;
2852     conn->bits.proxy_user_passwd = FALSE;
2853     conn->bits.tunnel_proxy = FALSE;
2854   }
2855
2856 out:
2857
2858   free(socksproxy);
2859   free(proxy);
2860   return result;
2861 }
2862 #endif /* CURL_DISABLE_PROXY */
2863
2864 /*
2865  * Curl_parse_login_details()
2866  *
2867  * This is used to parse a login string for user name, password and options in
2868  * the following formats:
2869  *
2870  *   user
2871  *   user:password
2872  *   user:password;options
2873  *   user;options
2874  *   user;options:password
2875  *   :password
2876  *   :password;options
2877  *   ;options
2878  *   ;options:password
2879  *
2880  * Parameters:
2881  *
2882  * login    [in]     - The login string.
2883  * len      [in]     - The length of the login string.
2884  * userp    [in/out] - The address where a pointer to newly allocated memory
2885  *                     holding the user will be stored upon completion.
2886  * passwdp  [in/out] - The address where a pointer to newly allocated memory
2887  *                     holding the password will be stored upon completion.
2888  * optionsp [in/out] - The address where a pointer to newly allocated memory
2889  *                     holding the options will be stored upon completion.
2890  *
2891  * Returns CURLE_OK on success.
2892  */
2893 CURLcode Curl_parse_login_details(const char *login, const size_t len,
2894                                   char **userp, char **passwdp,
2895                                   char **optionsp)
2896 {
2897   CURLcode result = CURLE_OK;
2898   char *ubuf = NULL;
2899   char *pbuf = NULL;
2900   char *obuf = NULL;
2901   const char *psep = NULL;
2902   const char *osep = NULL;
2903   size_t ulen;
2904   size_t plen;
2905   size_t olen;
2906
2907   /* Attempt to find the password separator */
2908   if(passwdp) {
2909     psep = strchr(login, ':');
2910
2911     /* Within the constraint of the login string */
2912     if(psep >= login + len)
2913       psep = NULL;
2914   }
2915
2916   /* Attempt to find the options separator */
2917   if(optionsp) {
2918     osep = strchr(login, ';');
2919
2920     /* Within the constraint of the login string */
2921     if(osep >= login + len)
2922       osep = NULL;
2923   }
2924
2925   /* Calculate the portion lengths */
2926   ulen = (psep ?
2927           (size_t)(osep && psep > osep ? osep - login : psep - login) :
2928           (osep ? (size_t)(osep - login) : len));
2929   plen = (psep ?
2930           (osep && osep > psep ? (size_t)(osep - psep) :
2931                                  (size_t)(login + len - psep)) - 1 : 0);
2932   olen = (osep ?
2933           (psep && psep > osep ? (size_t)(psep - osep) :
2934                                  (size_t)(login + len - osep)) - 1 : 0);
2935
2936   /* Allocate the user portion buffer */
2937   if(userp && ulen) {
2938     ubuf = malloc(ulen + 1);
2939     if(!ubuf)
2940       result = CURLE_OUT_OF_MEMORY;
2941   }
2942
2943   /* Allocate the password portion buffer */
2944   if(!result && passwdp && plen) {
2945     pbuf = malloc(plen + 1);
2946     if(!pbuf) {
2947       free(ubuf);
2948       result = CURLE_OUT_OF_MEMORY;
2949     }
2950   }
2951
2952   /* Allocate the options portion buffer */
2953   if(!result && optionsp && olen) {
2954     obuf = malloc(olen + 1);
2955     if(!obuf) {
2956       free(pbuf);
2957       free(ubuf);
2958       result = CURLE_OUT_OF_MEMORY;
2959     }
2960   }
2961
2962   if(!result) {
2963     /* Store the user portion if necessary */
2964     if(ubuf) {
2965       memcpy(ubuf, login, ulen);
2966       ubuf[ulen] = '\0';
2967       Curl_safefree(*userp);
2968       *userp = ubuf;
2969     }
2970
2971     /* Store the password portion if necessary */
2972     if(pbuf) {
2973       memcpy(pbuf, psep + 1, plen);
2974       pbuf[plen] = '\0';
2975       Curl_safefree(*passwdp);
2976       *passwdp = pbuf;
2977     }
2978
2979     /* Store the options portion if necessary */
2980     if(obuf) {
2981       memcpy(obuf, osep + 1, olen);
2982       obuf[olen] = '\0';
2983       Curl_safefree(*optionsp);
2984       *optionsp = obuf;
2985     }
2986   }
2987
2988   return result;
2989 }
2990
2991 /*************************************************************
2992  * Figure out the remote port number and fix it in the URL
2993  *
2994  * No matter if we use a proxy or not, we have to figure out the remote
2995  * port number of various reasons.
2996  *
2997  * The port number embedded in the URL is replaced, if necessary.
2998  *************************************************************/
2999 static CURLcode parse_remote_port(struct Curl_easy *data,
3000                                   struct connectdata *conn)
3001 {
3002
3003   if(data->set.use_port && data->state.allow_port) {
3004     /* if set, we use this instead of the port possibly given in the URL */
3005     char portbuf[16];
3006     CURLUcode uc;
3007     conn->remote_port = (unsigned short)data->set.use_port;
3008     snprintf(portbuf, sizeof(portbuf), "%u", conn->remote_port);
3009     uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0);
3010     if(uc)
3011       return CURLE_OUT_OF_MEMORY;
3012   }
3013
3014   return CURLE_OK;
3015 }
3016
3017 /*
3018  * Override the login details from the URL with that in the CURLOPT_USERPWD
3019  * option or a .netrc file, if applicable.
3020  */
3021 static CURLcode override_login(struct Curl_easy *data,
3022                                struct connectdata *conn,
3023                                char **userp, char **passwdp, char **optionsp)
3024 {
3025   bool user_changed = FALSE;
3026   bool passwd_changed = FALSE;
3027   CURLUcode uc;
3028   if(data->set.str[STRING_USERNAME]) {
3029     free(*userp);
3030     *userp = strdup(data->set.str[STRING_USERNAME]);
3031     if(!*userp)
3032       return CURLE_OUT_OF_MEMORY;
3033     conn->bits.user_passwd = TRUE; /* enable user+password */
3034     user_changed = TRUE;
3035   }
3036
3037   if(data->set.str[STRING_PASSWORD]) {
3038     free(*passwdp);
3039     *passwdp = strdup(data->set.str[STRING_PASSWORD]);
3040     if(!*passwdp)
3041       return CURLE_OUT_OF_MEMORY;
3042     conn->bits.user_passwd = TRUE; /* enable user+password */
3043     passwd_changed = TRUE;
3044   }
3045
3046   if(data->set.str[STRING_OPTIONS]) {
3047     free(*optionsp);
3048     *optionsp = strdup(data->set.str[STRING_OPTIONS]);
3049     if(!*optionsp)
3050       return CURLE_OUT_OF_MEMORY;
3051   }
3052
3053   conn->bits.netrc = FALSE;
3054   if(data->set.use_netrc != CURL_NETRC_IGNORED) {
3055     char *nuser = NULL;
3056     char *npasswd = NULL;
3057     int ret;
3058
3059     if(data->set.use_netrc == CURL_NETRC_OPTIONAL)
3060       nuser = *userp; /* to separate otherwise identical machines */
3061
3062     ret = Curl_parsenetrc(conn->host.name,
3063                           &nuser, &npasswd,
3064                           data->set.str[STRING_NETRC_FILE]);
3065     if(ret > 0) {
3066       infof(data, "Couldn't find host %s in the "
3067             DOT_CHAR "netrc file; using defaults\n",
3068             conn->host.name);
3069     }
3070     else if(ret < 0) {
3071       return CURLE_OUT_OF_MEMORY;
3072     }
3073     else {
3074       /* set bits.netrc TRUE to remember that we got the name from a .netrc
3075          file, so that it is safe to use even if we followed a Location: to a
3076          different host or similar. */
3077       conn->bits.netrc = TRUE;
3078       conn->bits.user_passwd = TRUE; /* enable user+password */
3079
3080       if(data->set.use_netrc == CURL_NETRC_OPTIONAL) {
3081         /* prefer credentials outside netrc */
3082         if(nuser && !*userp) {
3083           free(*userp);
3084           *userp = nuser;
3085           user_changed = TRUE;
3086         }
3087         if(npasswd && !*passwdp) {
3088           free(*passwdp);
3089           *passwdp = npasswd;
3090           passwd_changed = TRUE;
3091         }
3092       }
3093       else {
3094         /* prefer netrc credentials */
3095         if(nuser) {
3096           free(*userp);
3097           *userp = nuser;
3098           user_changed = TRUE;
3099         }
3100         if(npasswd) {
3101           free(*passwdp);
3102           *passwdp = npasswd;
3103           passwd_changed = TRUE;
3104         }
3105       }
3106     }
3107   }
3108
3109   /* for updated strings, we update them in the URL */
3110   if(user_changed) {
3111     uc = curl_url_set(data->state.uh, CURLUPART_USER, *userp, 0);
3112     if(uc)
3113       return Curl_uc_to_curlcode(uc);
3114   }
3115   if(passwd_changed) {
3116     uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, *passwdp, 0);
3117     if(uc)
3118       return Curl_uc_to_curlcode(uc);
3119   }
3120   return CURLE_OK;
3121 }
3122
3123 /*
3124  * Set the login details so they're available in the connection
3125  */
3126 static CURLcode set_login(struct connectdata *conn)
3127 {
3128   CURLcode result = CURLE_OK;
3129   const char *setuser = CURL_DEFAULT_USER;
3130   const char *setpasswd = CURL_DEFAULT_PASSWORD;
3131
3132   /* If our protocol needs a password and we have none, use the defaults */
3133   if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd)
3134     ;
3135   else {
3136     setuser = "";
3137     setpasswd = "";
3138   }
3139   /* Store the default user */
3140   if(!conn->user) {
3141     conn->user = strdup(setuser);
3142     if(!conn->user)
3143       return CURLE_OUT_OF_MEMORY;
3144   }
3145
3146   /* Store the default password */
3147   if(!conn->passwd) {
3148     conn->passwd = strdup(setpasswd);
3149     if(!conn->passwd)
3150       result = CURLE_OUT_OF_MEMORY;
3151   }
3152
3153   /* if there's a user without password, consider password blank */
3154   if(conn->user && !conn->passwd) {
3155     conn->passwd = strdup("");
3156     if(!conn->passwd)
3157       result = CURLE_OUT_OF_MEMORY;
3158   }
3159
3160   return result;
3161 }
3162
3163 /*
3164  * Parses a "host:port" string to connect to.
3165  * The hostname and the port may be empty; in this case, NULL is returned for
3166  * the hostname and -1 for the port.
3167  */
3168 static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
3169                                            const char *host,
3170                                            char **hostname_result,
3171                                            int *port_result)
3172 {
3173   char *host_dup;
3174   char *hostptr;
3175   char *host_portno;
3176   char *portptr;
3177   int port = -1;
3178
3179 #if defined(CURL_DISABLE_VERBOSE_STRINGS)
3180   (void) data;
3181 #endif
3182
3183   *hostname_result = NULL;
3184   *port_result = -1;
3185
3186   if(!host || !*host)
3187     return CURLE_OK;
3188
3189   host_dup = strdup(host);
3190   if(!host_dup)
3191     return CURLE_OUT_OF_MEMORY;
3192
3193   hostptr = host_dup;
3194
3195   /* start scanning for port number at this point */
3196   portptr = hostptr;
3197
3198   /* detect and extract RFC6874-style IPv6-addresses */
3199   if(*hostptr == '[') {
3200 #ifdef ENABLE_IPV6
3201     char *ptr = ++hostptr; /* advance beyond the initial bracket */
3202     while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
3203       ptr++;
3204     if(*ptr == '%') {
3205       /* There might be a zone identifier */
3206       if(strncmp("%25", ptr, 3))
3207         infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
3208       ptr++;
3209       /* Allow unreserved characters as defined in RFC 3986 */
3210       while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
3211                      (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
3212         ptr++;
3213     }
3214     if(*ptr == ']')
3215       /* yeps, it ended nicely with a bracket as well */
3216       *ptr++ = '\0';
3217     else
3218       infof(data, "Invalid IPv6 address format\n");
3219     portptr = ptr;
3220     /* Note that if this didn't end with a bracket, we still advanced the
3221      * hostptr first, but I can't see anything wrong with that as no host
3222      * name nor a numeric can legally start with a bracket.
3223      */
3224 #else
3225     failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!");
3226     free(host_dup);
3227     return CURLE_NOT_BUILT_IN;
3228 #endif
3229   }
3230
3231   /* Get port number off server.com:1080 */
3232   host_portno = strchr(portptr, ':');
3233   if(host_portno) {
3234     char *endp = NULL;
3235     *host_portno = '\0'; /* cut off number from host name */
3236     host_portno++;
3237     if(*host_portno) {
3238       long portparse = strtol(host_portno, &endp, 10);
3239       if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
3240         infof(data, "No valid port number in connect to host string (%s)\n",
3241               host_portno);
3242         hostptr = NULL;
3243         port = -1;
3244       }
3245       else
3246         port = (int)portparse; /* we know it will fit */
3247     }
3248   }
3249
3250   /* now, clone the cleaned host name */
3251   if(hostptr) {
3252     *hostname_result = strdup(hostptr);
3253     if(!*hostname_result) {
3254       free(host_dup);
3255       return CURLE_OUT_OF_MEMORY;
3256     }
3257   }
3258
3259   *port_result = port;
3260
3261   free(host_dup);
3262   return CURLE_OK;
3263 }
3264
3265 /*
3266  * Parses one "connect to" string in the form:
3267  * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
3268  */
3269 static CURLcode parse_connect_to_string(struct Curl_easy *data,
3270                                         struct connectdata *conn,
3271                                         const char *conn_to_host,
3272                                         char **host_result,
3273                                         int *port_result)
3274 {
3275   CURLcode result = CURLE_OK;
3276   const char *ptr = conn_to_host;
3277   int host_match = FALSE;
3278   int port_match = FALSE;
3279
3280   *host_result = NULL;
3281   *port_result = -1;
3282
3283   if(*ptr == ':') {
3284     /* an empty hostname always matches */
3285     host_match = TRUE;
3286     ptr++;
3287   }
3288   else {
3289     /* check whether the URL's hostname matches */
3290     size_t hostname_to_match_len;
3291     char *hostname_to_match = aprintf("%s%s%s",
3292                                       conn->bits.ipv6_ip ? "[" : "",
3293                                       conn->host.name,
3294                                       conn->bits.ipv6_ip ? "]" : "");
3295     if(!hostname_to_match)
3296       return CURLE_OUT_OF_MEMORY;
3297     hostname_to_match_len = strlen(hostname_to_match);
3298     host_match = strncasecompare(ptr, hostname_to_match,
3299                                  hostname_to_match_len);
3300     free(hostname_to_match);
3301     ptr += hostname_to_match_len;
3302
3303     host_match = host_match && *ptr == ':';
3304     ptr++;
3305   }
3306
3307   if(host_match) {
3308     if(*ptr == ':') {
3309       /* an empty port always matches */
3310       port_match = TRUE;
3311       ptr++;
3312     }
3313     else {
3314       /* check whether the URL's port matches */
3315       char *ptr_next = strchr(ptr, ':');
3316       if(ptr_next) {
3317         char *endp = NULL;
3318         long port_to_match = strtol(ptr, &endp, 10);
3319         if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
3320           port_match = TRUE;
3321           ptr = ptr_next + 1;
3322         }
3323       }
3324     }
3325   }
3326
3327   if(host_match && port_match) {
3328     /* parse the hostname and port to connect to */
3329     result = parse_connect_to_host_port(data, ptr, host_result, port_result);
3330   }
3331
3332   return result;
3333 }
3334
3335 /*
3336  * Processes all strings in the "connect to" slist, and uses the "connect
3337  * to host" and "connect to port" of the first string that matches.
3338  */
3339 static CURLcode parse_connect_to_slist(struct Curl_easy *data,
3340                                        struct connectdata *conn,
3341                                        struct curl_slist *conn_to_host)
3342 {
3343   CURLcode result = CURLE_OK;
3344   char *host = NULL;
3345   int port = -1;
3346
3347   while(conn_to_host && !host && port == -1) {
3348     result = parse_connect_to_string(data, conn, conn_to_host->data,
3349                                      &host, &port);
3350     if(result)
3351       return result;
3352
3353     if(host && *host) {
3354       conn->conn_to_host.rawalloc = host;
3355       conn->conn_to_host.name = host;
3356       conn->bits.conn_to_host = TRUE;
3357
3358       infof(data, "Connecting to hostname: %s\n", host);
3359     }
3360     else {
3361       /* no "connect to host" */
3362       conn->bits.conn_to_host = FALSE;
3363       Curl_safefree(host);
3364     }
3365
3366     if(port >= 0) {
3367       conn->conn_to_port = port;
3368       conn->bits.conn_to_port = TRUE;
3369       infof(data, "Connecting to port: %d\n", port);
3370     }
3371     else {
3372       /* no "connect to port" */
3373       conn->bits.conn_to_port = FALSE;
3374       port = -1;
3375     }
3376
3377     conn_to_host = conn_to_host->next;
3378   }
3379
3380   return result;
3381 }
3382
3383 /*************************************************************
3384  * Resolve the address of the server or proxy
3385  *************************************************************/
3386 static CURLcode resolve_server(struct Curl_easy *data,
3387                                struct connectdata *conn,
3388                                bool *async)
3389 {
3390   CURLcode result = CURLE_OK;
3391   timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
3392
3393   /*************************************************************
3394    * Resolve the name of the server or proxy
3395    *************************************************************/
3396   if(conn->bits.reuse)
3397     /* We're reusing the connection - no need to resolve anything, and
3398        fix_hostname() was called already in create_conn() for the re-use
3399        case. */
3400     *async = FALSE;
3401
3402   else {
3403     /* this is a fresh connect */
3404     int rc;
3405     struct Curl_dns_entry *hostaddr;
3406
3407 #ifdef USE_UNIX_SOCKETS
3408     if(conn->unix_domain_socket) {
3409       /* Unix domain sockets are local. The host gets ignored, just use the
3410        * specified domain socket address. Do not cache "DNS entries". There is
3411        * no DNS involved and we already have the filesystem path available */
3412       const char *path = conn->unix_domain_socket;
3413
3414       hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
3415       if(!hostaddr)
3416         result = CURLE_OUT_OF_MEMORY;
3417       else {
3418         bool longpath = FALSE;
3419         hostaddr->addr = Curl_unix2addr(path, &longpath,
3420                                         conn->abstract_unix_socket);
3421         if(hostaddr->addr)
3422           hostaddr->inuse++;
3423         else {
3424           /* Long paths are not supported for now */
3425           if(longpath) {
3426             failf(data, "Unix socket path too long: '%s'", path);
3427             result = CURLE_COULDNT_RESOLVE_HOST;
3428           }
3429           else
3430             result = CURLE_OUT_OF_MEMORY;
3431           free(hostaddr);
3432           hostaddr = NULL;
3433         }
3434       }
3435     }
3436     else
3437 #endif
3438     if(!conn->bits.proxy) {
3439       struct hostname *connhost;
3440       if(conn->bits.conn_to_host)
3441         connhost = &conn->conn_to_host;
3442       else
3443         connhost = &conn->host;
3444
3445       /* If not connecting via a proxy, extract the port from the URL, if it is
3446        * there, thus overriding any defaults that might have been set above. */
3447       if(conn->bits.conn_to_port)
3448         conn->port = conn->conn_to_port;
3449       else
3450         conn->port = conn->remote_port;
3451
3452       /* Resolve target host right on */
3453       rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
3454                                &hostaddr, timeout_ms);
3455       if(rc == CURLRESOLV_PENDING)
3456         *async = TRUE;
3457
3458       else if(rc == CURLRESOLV_TIMEDOUT)
3459         result = CURLE_OPERATION_TIMEDOUT;
3460
3461       else if(!hostaddr) {
3462         failf(data, "Couldn't resolve host '%s'", connhost->dispname);
3463         result =  CURLE_COULDNT_RESOLVE_HOST;
3464         /* don't return yet, we need to clean up the timeout first */
3465       }
3466     }
3467     else {
3468       /* This is a proxy that hasn't been resolved yet. */
3469
3470       struct hostname * const host = conn->bits.socksproxy ?
3471         &conn->socks_proxy.host : &conn->http_proxy.host;
3472
3473       /* resolve proxy */
3474       rc = Curl_resolv_timeout(conn, host->name, (int)conn->port,
3475                                &hostaddr, timeout_ms);
3476
3477       if(rc == CURLRESOLV_PENDING)
3478         *async = TRUE;
3479
3480       else if(rc == CURLRESOLV_TIMEDOUT)
3481         result = CURLE_OPERATION_TIMEDOUT;
3482
3483       else if(!hostaddr) {
3484         failf(data, "Couldn't resolve proxy '%s'", host->dispname);
3485         result = CURLE_COULDNT_RESOLVE_PROXY;
3486         /* don't return yet, we need to clean up the timeout first */
3487       }
3488     }
3489     DEBUGASSERT(conn->dns_entry == NULL);
3490     conn->dns_entry = hostaddr;
3491   }
3492
3493   return result;
3494 }
3495
3496 /*
3497  * Cleanup the connection just allocated before we can move along and use the
3498  * previously existing one.  All relevant data is copied over and old_conn is
3499  * ready for freeing once this function returns.
3500  */
3501 static void reuse_conn(struct connectdata *old_conn,
3502                        struct connectdata *conn)
3503 {
3504   free_fixed_hostname(&old_conn->http_proxy.host);
3505   free_fixed_hostname(&old_conn->socks_proxy.host);
3506
3507   free(old_conn->http_proxy.host.rawalloc);
3508   free(old_conn->socks_proxy.host.rawalloc);
3509
3510   /* free the SSL config struct from this connection struct as this was
3511      allocated in vain and is targeted for destruction */
3512   Curl_free_primary_ssl_config(&old_conn->ssl_config);
3513   Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
3514
3515   conn->data = old_conn->data;
3516
3517   /* get the user+password information from the old_conn struct since it may
3518    * be new for this request even when we re-use an existing connection */
3519   conn->bits.user_passwd = old_conn->bits.user_passwd;
3520   if(conn->bits.user_passwd) {
3521     /* use the new user name and password though */
3522     Curl_safefree(conn->user);
3523     Curl_safefree(conn->passwd);
3524     conn->user = old_conn->user;
3525     conn->passwd = old_conn->passwd;
3526     old_conn->user = NULL;
3527     old_conn->passwd = NULL;
3528   }
3529
3530   conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
3531   if(conn->bits.proxy_user_passwd) {
3532     /* use the new proxy user name and proxy password though */
3533     Curl_safefree(conn->http_proxy.user);
3534     Curl_safefree(conn->socks_proxy.user);
3535     Curl_safefree(conn->http_proxy.passwd);
3536     Curl_safefree(conn->socks_proxy.passwd);
3537     conn->http_proxy.user = old_conn->http_proxy.user;
3538     conn->socks_proxy.user = old_conn->socks_proxy.user;
3539     conn->http_proxy.passwd = old_conn->http_proxy.passwd;
3540     conn->socks_proxy.passwd = old_conn->socks_proxy.passwd;
3541     old_conn->http_proxy.user = NULL;
3542     old_conn->socks_proxy.user = NULL;
3543     old_conn->http_proxy.passwd = NULL;
3544     old_conn->socks_proxy.passwd = NULL;
3545   }
3546
3547   /* host can change, when doing keepalive with a proxy or if the case is
3548      different this time etc */
3549   free_fixed_hostname(&conn->host);
3550   free_fixed_hostname(&conn->conn_to_host);
3551   Curl_safefree(conn->host.rawalloc);
3552   Curl_safefree(conn->conn_to_host.rawalloc);
3553   conn->host = old_conn->host;
3554   conn->conn_to_host = old_conn->conn_to_host;
3555   conn->conn_to_port = old_conn->conn_to_port;
3556   conn->remote_port = old_conn->remote_port;
3557
3558   /* persist connection info in session handle */
3559   Curl_persistconninfo(conn);
3560
3561   conn_reset_all_postponed_data(old_conn); /* free buffers */
3562
3563   /* re-use init */
3564   conn->bits.reuse = TRUE; /* yes, we're re-using here */
3565
3566   Curl_safefree(old_conn->user);
3567   Curl_safefree(old_conn->passwd);
3568   Curl_safefree(old_conn->options);
3569   Curl_safefree(old_conn->http_proxy.user);
3570   Curl_safefree(old_conn->socks_proxy.user);
3571   Curl_safefree(old_conn->http_proxy.passwd);
3572   Curl_safefree(old_conn->socks_proxy.passwd);
3573   Curl_safefree(old_conn->localdev);
3574
3575   Curl_llist_destroy(&old_conn->send_pipe, NULL);
3576   Curl_llist_destroy(&old_conn->recv_pipe, NULL);
3577
3578   Curl_safefree(old_conn->master_buffer);
3579
3580 #ifdef USE_UNIX_SOCKETS
3581   Curl_safefree(old_conn->unix_domain_socket);
3582 #endif
3583 }
3584
3585 /**
3586  * create_conn() sets up a new connectdata struct, or re-uses an already
3587  * existing one, and resolves host name.
3588  *
3589  * if this function returns CURLE_OK and *async is set to TRUE, the resolve
3590  * response will be coming asynchronously. If *async is FALSE, the name is
3591  * already resolved.
3592  *
3593  * @param data The sessionhandle pointer
3594  * @param in_connect is set to the next connection data pointer
3595  * @param async is set TRUE when an async DNS resolution is pending
3596  * @see Curl_setup_conn()
3597  *
3598  * *NOTE* this function assigns the conn->data pointer!
3599  */
3600
3601 static CURLcode create_conn(struct Curl_easy *data,
3602                             struct connectdata **in_connect,
3603                             bool *async)
3604 {
3605   CURLcode result = CURLE_OK;
3606   struct connectdata *conn;
3607   struct connectdata *conn_temp = NULL;
3608   bool reuse;
3609   bool connections_available = TRUE;
3610   bool force_reuse = FALSE;
3611   bool waitpipe = FALSE;
3612   size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
3613   size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
3614
3615   *async = FALSE;
3616
3617   /*************************************************************
3618    * Check input data
3619    *************************************************************/
3620   if(!data->change.url) {
3621     result = CURLE_URL_MALFORMAT;
3622     goto out;
3623   }
3624
3625   /* First, split up the current URL in parts so that we can use the
3626      parts for checking against the already present connections. In order
3627      to not have to modify everything at once, we allocate a temporary
3628      connection data struct and fill in for comparison purposes. */
3629   conn = allocate_conn(data);
3630
3631   if(!conn) {
3632     result = CURLE_OUT_OF_MEMORY;
3633     goto out;
3634   }
3635
3636   /* We must set the return variable as soon as possible, so that our
3637      parent can cleanup any possible allocs we may have done before
3638      any failure */
3639   *in_connect = conn;
3640
3641   result = parseurlandfillconn(data, conn);
3642   if(result)
3643     goto out;
3644
3645   if(data->set.str[STRING_BEARER]) {
3646     conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
3647     if(!conn->oauth_bearer) {
3648       result = CURLE_OUT_OF_MEMORY;
3649       goto out;
3650     }
3651   }
3652
3653 #ifdef USE_UNIX_SOCKETS
3654   if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
3655     conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
3656     if(conn->unix_domain_socket == NULL) {
3657       result = CURLE_OUT_OF_MEMORY;
3658       goto out;
3659     }
3660     conn->abstract_unix_socket = data->set.abstract_unix_socket;
3661   }
3662 #endif
3663
3664   /* After the unix socket init but before the proxy vars are used, parse and
3665      initialize the proxy vars */
3666 #ifndef CURL_DISABLE_PROXY
3667   result = create_conn_helper_init_proxy(conn);
3668   if(result)
3669     goto out;
3670 #endif
3671
3672   /*************************************************************
3673    * If the protocol is using SSL and HTTP proxy is used, we set
3674    * the tunnel_proxy bit.
3675    *************************************************************/
3676   if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
3677     conn->bits.tunnel_proxy = TRUE;
3678
3679   /*************************************************************
3680    * Figure out the remote port number and fix it in the URL
3681    *************************************************************/
3682   result = parse_remote_port(data, conn);
3683   if(result)
3684     goto out;
3685
3686   /* Check for overridden login details and set them accordingly so they
3687      they are known when protocol->setup_connection is called! */
3688   result = override_login(data, conn, &conn->user, &conn->passwd,
3689                           &conn->options);
3690   if(result)
3691     goto out;
3692
3693   result = set_login(conn); /* default credentials */
3694   if(result)
3695     goto out;
3696
3697   /*************************************************************
3698    * Process the "connect to" linked list of hostname/port mappings.
3699    * Do this after the remote port number has been fixed in the URL.
3700    *************************************************************/
3701   result = parse_connect_to_slist(data, conn, data->set.connect_to);
3702   if(result)
3703     goto out;
3704
3705   /*************************************************************
3706    * IDN-fix the hostnames
3707    *************************************************************/
3708   result = fix_hostname(conn, &conn->host);
3709   if(result)
3710     goto out;
3711   if(conn->bits.conn_to_host) {
3712     result = fix_hostname(conn, &conn->conn_to_host);
3713     if(result)
3714       goto out;
3715   }
3716   if(conn->bits.httpproxy) {
3717     result = fix_hostname(conn, &conn->http_proxy.host);
3718     if(result)
3719       goto out;
3720   }
3721   if(conn->bits.socksproxy) {
3722     result = fix_hostname(conn, &conn->socks_proxy.host);
3723     if(result)
3724       goto out;
3725   }
3726
3727   /*************************************************************
3728    * Check whether the host and the "connect to host" are equal.
3729    * Do this after the hostnames have been IDN-fixed.
3730    *************************************************************/
3731   if(conn->bits.conn_to_host &&
3732      strcasecompare(conn->conn_to_host.name, conn->host.name)) {
3733     conn->bits.conn_to_host = FALSE;
3734   }
3735
3736   /*************************************************************
3737    * Check whether the port and the "connect to port" are equal.
3738    * Do this after the remote port number has been fixed in the URL.
3739    *************************************************************/
3740   if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
3741     conn->bits.conn_to_port = FALSE;
3742   }
3743
3744   /*************************************************************
3745    * If the "connect to" feature is used with an HTTP proxy,
3746    * we set the tunnel_proxy bit.
3747    *************************************************************/
3748   if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
3749       conn->bits.httpproxy)
3750     conn->bits.tunnel_proxy = TRUE;
3751
3752   /*************************************************************
3753    * Setup internals depending on protocol. Needs to be done after
3754    * we figured out what/if proxy to use.
3755    *************************************************************/
3756   result = setup_connection_internals(conn);
3757   if(result)
3758     goto out;
3759
3760   conn->recv[FIRSTSOCKET] = Curl_recv_plain;
3761   conn->send[FIRSTSOCKET] = Curl_send_plain;
3762   conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
3763   conn->send[SECONDARYSOCKET] = Curl_send_plain;
3764
3765   conn->bits.tcp_fastopen = data->set.tcp_fastopen;
3766
3767   /***********************************************************************
3768    * file: is a special case in that it doesn't need a network connection
3769    ***********************************************************************/
3770 #ifndef CURL_DISABLE_FILE
3771   if(conn->handler->flags & PROTOPT_NONETWORK) {
3772     bool done;
3773     /* this is supposed to be the connect function so we better at least check
3774        that the file is present here! */
3775     DEBUGASSERT(conn->handler->connect_it);
3776     Curl_persistconninfo(conn);
3777     result = conn->handler->connect_it(conn, &done);
3778
3779     /* Setup a "faked" transfer that'll do nothing */
3780     if(!result) {
3781       conn->data = data;
3782       conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
3783
3784       result = Curl_conncache_add_conn(data->state.conn_cache, conn);
3785       if(result)
3786         goto out;
3787
3788       /*
3789        * Setup whatever necessary for a resumed transfer
3790        */
3791       result = setup_range(data);
3792       if(result) {
3793         DEBUGASSERT(conn->handler->done);
3794         /* we ignore the return code for the protocol-specific DONE */
3795         (void)conn->handler->done(conn, result, FALSE);
3796         goto out;
3797       }
3798
3799       Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
3800                           -1, NULL); /* no upload */
3801     }
3802
3803     /* since we skip do_init() */
3804     Curl_init_do(data, conn);
3805
3806     goto out;
3807   }
3808 #endif
3809
3810   /* Get a cloned copy of the SSL config situation stored in the
3811      connection struct. But to get this going nicely, we must first make
3812      sure that the strings in the master copy are pointing to the correct
3813      strings in the session handle strings array!
3814
3815      Keep in mind that the pointers in the master copy are pointing to strings
3816      that will be freed as part of the Curl_easy struct, but all cloned
3817      copies will be separately allocated.
3818   */
3819   data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
3820   data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
3821   data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
3822   data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
3823   data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
3824   data->set.proxy_ssl.primary.random_file =
3825     data->set.str[STRING_SSL_RANDOM_FILE];
3826   data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
3827   data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
3828   data->set.ssl.primary.cipher_list =
3829     data->set.str[STRING_SSL_CIPHER_LIST_ORIG];
3830   data->set.proxy_ssl.primary.cipher_list =
3831     data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
3832   data->set.ssl.primary.cipher_list13 =
3833     data->set.str[STRING_SSL_CIPHER13_LIST_ORIG];
3834   data->set.proxy_ssl.primary.cipher_list13 =
3835     data->set.str[STRING_SSL_CIPHER13_LIST_PROXY];
3836
3837   data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG];
3838   data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY];
3839   data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG];
3840   data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY];
3841   data->set.ssl.cert = data->set.str[STRING_CERT_ORIG];
3842   data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY];
3843   data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG];
3844   data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
3845   data->set.ssl.key = data->set.str[STRING_KEY_ORIG];
3846   data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
3847   data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
3848   data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
3849   data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
3850   data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
3851   data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
3852   data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
3853 #ifdef USE_TLS_SRP
3854   data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
3855   data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
3856   data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
3857   data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
3858 #endif
3859
3860   if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
3861      &conn->ssl_config)) {
3862     result = CURLE_OUT_OF_MEMORY;
3863     goto out;
3864   }
3865
3866   if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
3867                                     &conn->proxy_ssl_config)) {
3868     result = CURLE_OUT_OF_MEMORY;
3869     goto out;
3870   }
3871
3872   prune_dead_connections(data);
3873
3874   /*************************************************************
3875    * Check the current list of connections to see if we can
3876    * re-use an already existing one or if we have to create a
3877    * new one.
3878    *************************************************************/
3879
3880   DEBUGASSERT(conn->user);
3881   DEBUGASSERT(conn->passwd);
3882
3883   /* reuse_fresh is TRUE if we are told to use a new connection by force, but
3884      we only acknowledge this option if this is not a re-used connection
3885      already (which happens due to follow-location or during a HTTP
3886      authentication phase). */
3887   if(data->set.reuse_fresh && !data->state.this_is_a_follow)
3888     reuse = FALSE;
3889   else
3890     reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
3891
3892   /* If we found a reusable connection that is now marked as in use, we may
3893      still want to open a new connection if we are pipelining. */
3894   if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
3895     size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size;
3896     if(pipelen > 0) {
3897       infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
3898             conn_temp->connection_id, pipelen);
3899
3900       if(Curl_conncache_bundle_size(conn_temp) < max_host_connections &&
3901          Curl_conncache_size(data) < max_total_connections) {
3902         /* We want a new connection anyway */
3903         reuse = FALSE;
3904
3905         infof(data, "We can reuse, but we want a new connection anyway\n");
3906         Curl_conncache_return_conn(conn_temp);
3907       }
3908     }
3909   }
3910
3911   if(reuse) {
3912     /*
3913      * We already have a connection for this, we got the former connection
3914      * in the conn_temp variable and thus we need to cleanup the one we
3915      * just allocated before we can move along and use the previously
3916      * existing one.
3917      */
3918     reuse_conn(conn, conn_temp);
3919 #ifdef USE_SSL
3920     free(conn->ssl_extra);
3921 #endif
3922     free(conn);          /* we don't need this anymore */
3923     conn = conn_temp;
3924     *in_connect = conn;
3925
3926     infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
3927           conn->connection_id,
3928           conn->bits.proxy?"proxy":"host",
3929           conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
3930           conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
3931                                        conn->host.dispname);
3932   }
3933   else {
3934     /* We have decided that we want a new connection. However, we may not
3935        be able to do that if we have reached the limit of how many
3936        connections we are allowed to open. */
3937
3938     if(conn->handler->flags & PROTOPT_ALPN_NPN) {
3939       /* The protocol wants it, so set the bits if enabled in the easy handle
3940          (default) */
3941       if(data->set.ssl_enable_alpn)
3942         conn->bits.tls_enable_alpn = TRUE;
3943       if(data->set.ssl_enable_npn)
3944         conn->bits.tls_enable_npn = TRUE;
3945     }
3946
3947     if(waitpipe)
3948       /* There is a connection that *might* become usable for pipelining
3949          "soon", and we wait for that */
3950       connections_available = FALSE;
3951     else {
3952       /* this gets a lock on the conncache */
3953       struct connectbundle *bundle =
3954         Curl_conncache_find_bundle(conn, data->state.conn_cache);
3955
3956       if(max_host_connections > 0 && bundle &&
3957          (bundle->num_connections >= max_host_connections)) {
3958         struct connectdata *conn_candidate;
3959
3960         /* The bundle is full. Extract the oldest connection. */
3961         conn_candidate = Curl_conncache_extract_bundle(data, bundle);
3962         Curl_conncache_unlock(conn);
3963
3964         if(conn_candidate)
3965           (void)Curl_disconnect(data, conn_candidate,
3966                                 /* dead_connection */ FALSE);
3967         else {
3968           infof(data, "No more connections allowed to host: %zu\n",
3969                 max_host_connections);
3970           connections_available = FALSE;
3971         }
3972       }
3973       else
3974         Curl_conncache_unlock(conn);
3975
3976     }
3977
3978     if(connections_available &&
3979        (max_total_connections > 0) &&
3980        (Curl_conncache_size(data) >= max_total_connections)) {
3981       struct connectdata *conn_candidate;
3982
3983       /* The cache is full. Let's see if we can kill a connection. */
3984       conn_candidate = Curl_conncache_extract_oldest(data);
3985       if(conn_candidate)
3986         (void)Curl_disconnect(data, conn_candidate,
3987                               /* dead_connection */ FALSE);
3988       else {
3989         infof(data, "No connections available in cache\n");
3990         connections_available = FALSE;
3991       }
3992     }
3993
3994     if(!connections_available) {
3995       infof(data, "No connections available.\n");
3996
3997       conn_free(conn);
3998       *in_connect = NULL;
3999
4000       result = CURLE_NO_CONNECTION_AVAILABLE;
4001       goto out;
4002     }
4003     else {
4004       /*
4005        * This is a brand new connection, so let's store it in the connection
4006        * cache of ours!
4007        */
4008       result = Curl_conncache_add_conn(data->state.conn_cache, conn);
4009       if(result)
4010         goto out;
4011     }
4012
4013 #if defined(USE_NTLM)
4014     /* If NTLM is requested in a part of this connection, make sure we don't
4015        assume the state is fine as this is a fresh connection and NTLM is
4016        connection based. */
4017     if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
4018        data->state.authhost.done) {
4019       infof(data, "NTLM picked AND auth done set, clear picked!\n");
4020       data->state.authhost.picked = CURLAUTH_NONE;
4021       data->state.authhost.done = FALSE;
4022     }
4023
4024     if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
4025        data->state.authproxy.done) {
4026       infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
4027       data->state.authproxy.picked = CURLAUTH_NONE;
4028       data->state.authproxy.done = FALSE;
4029     }
4030 #endif
4031   }
4032
4033   /* Setup and init stuff before DO starts, in preparing for the transfer. */
4034   Curl_init_do(data, conn);
4035
4036   /*
4037    * Setup whatever necessary for a resumed transfer
4038    */
4039   result = setup_range(data);
4040   if(result)
4041     goto out;
4042
4043   /* Continue connectdata initialization here. */
4044
4045   /*
4046    * Inherit the proper values from the urldata struct AFTER we have arranged
4047    * the persistent connection stuff
4048    */
4049   conn->seek_func = data->set.seek_func;
4050   conn->seek_client = data->set.seek_client;
4051
4052   /*************************************************************
4053    * Resolve the address of the server or proxy
4054    *************************************************************/
4055   result = resolve_server(data, conn, async);
4056
4057 out:
4058   return result;
4059 }
4060
4061 /* Curl_setup_conn() is called after the name resolve initiated in
4062  * create_conn() is all done.
4063  *
4064  * Curl_setup_conn() also handles reused connections
4065  *
4066  * conn->data MUST already have been setup fine (in create_conn)
4067  */
4068
4069 CURLcode Curl_setup_conn(struct connectdata *conn,
4070                          bool *protocol_done)
4071 {
4072   CURLcode result = CURLE_OK;
4073   struct Curl_easy *data = conn->data;
4074
4075   Curl_pgrsTime(data, TIMER_NAMELOOKUP);
4076
4077   if(conn->handler->flags & PROTOPT_NONETWORK) {
4078     /* nothing to setup when not using a network */
4079     *protocol_done = TRUE;
4080     return result;
4081   }
4082   *protocol_done = FALSE; /* default to not done */
4083
4084   /* set proxy_connect_closed to false unconditionally already here since it
4085      is used strictly to provide extra information to a parent function in the
4086      case of proxy CONNECT failures and we must make sure we don't have it
4087      lingering set from a previous invoke */
4088   conn->bits.proxy_connect_closed = FALSE;
4089
4090   /*
4091    * Set user-agent. Used for HTTP, but since we can attempt to tunnel
4092    * basically anything through a http proxy we can't limit this based on
4093    * protocol.
4094    */
4095   if(data->set.str[STRING_USERAGENT]) {
4096     Curl_safefree(conn->allocptr.uagent);
4097     conn->allocptr.uagent =
4098       aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
4099     if(!conn->allocptr.uagent)
4100       return CURLE_OUT_OF_MEMORY;
4101   }
4102
4103   data->req.headerbytecount = 0;
4104
4105 #ifdef CURL_DO_LINEEND_CONV
4106   data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
4107 #endif /* CURL_DO_LINEEND_CONV */
4108
4109   /* set start time here for timeout purposes in the connect procedure, it
4110      is later set again for the progress meter purpose */
4111   conn->now = Curl_now();
4112
4113   if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
4114     conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
4115     result = Curl_connecthost(conn, conn->dns_entry);
4116     if(result)
4117       return result;
4118   }
4119   else {
4120     Curl_pgrsTime(data, TIMER_CONNECT);    /* we're connected already */
4121     Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
4122     conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
4123     *protocol_done = TRUE;
4124     Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
4125     Curl_verboseconnect(conn);
4126   }
4127
4128   conn->now = Curl_now(); /* time this *after* the connect is done, we set
4129                              this here perhaps a second time */
4130   return result;
4131 }
4132
4133 CURLcode Curl_connect(struct Curl_easy *data,
4134                       struct connectdata **in_connect,
4135                       bool *asyncp,
4136                       bool *protocol_done)
4137 {
4138   CURLcode result;
4139
4140   *asyncp = FALSE; /* assume synchronous resolves by default */
4141
4142   /* init the single-transfer specific data */
4143   Curl_free_request_state(data);
4144   memset(&data->req, 0, sizeof(struct SingleRequest));
4145   data->req.maxdownload = -1;
4146
4147   /* call the stuff that needs to be called */
4148   result = create_conn(data, in_connect, asyncp);
4149
4150   if(!result) {
4151     if(CONN_INUSE(*in_connect))
4152       /* pipelining */
4153       *protocol_done = TRUE;
4154     else if(!*asyncp) {
4155       /* DNS resolution is done: that's either because this is a reused
4156          connection, in which case DNS was unnecessary, or because DNS
4157          really did finish already (synch resolver/fast async resolve) */
4158       result = Curl_setup_conn(*in_connect, protocol_done);
4159     }
4160   }
4161
4162   if(result == CURLE_NO_CONNECTION_AVAILABLE) {
4163     *in_connect = NULL;
4164     return result;
4165   }
4166   else if(result && *in_connect) {
4167     /* We're not allowed to return failure with memory left allocated in the
4168        connectdata struct, free those here */
4169     Curl_disconnect(data, *in_connect, TRUE);
4170     *in_connect = NULL; /* return a NULL */
4171   }
4172
4173   return result;
4174 }
4175
4176 /*
4177  * Curl_init_do() inits the readwrite session. This is inited each time (in
4178  * the DO function before the protocol-specific DO functions are invoked) for
4179  * a transfer, sometimes multiple times on the same Curl_easy. Make sure
4180  * nothing in here depends on stuff that are setup dynamically for the
4181  * transfer.
4182  *
4183  * Allow this function to get called with 'conn' set to NULL.
4184  */
4185
4186 CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
4187 {
4188   struct SingleRequest *k = &data->req;
4189
4190   if(conn) {
4191     conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
4192                                    use */
4193     /* if the protocol used doesn't support wildcards, switch it off */
4194     if(data->state.wildcardmatch &&
4195        !(conn->handler->flags & PROTOPT_WILDCARD))
4196       data->state.wildcardmatch = FALSE;
4197   }
4198
4199   data->state.done = FALSE; /* *_done() is not called yet */
4200   data->state.expect100header = FALSE;
4201
4202
4203   if(data->set.opt_no_body)
4204     /* in HTTP lingo, no body means using the HEAD request... */
4205     data->set.httpreq = HTTPREQ_HEAD;
4206   else if(HTTPREQ_HEAD == data->set.httpreq)
4207     /* ... but if unset there really is no perfect method that is the
4208        "opposite" of HEAD but in reality most people probably think GET
4209        then. The important thing is that we can't let it remain HEAD if the
4210        opt_no_body is set FALSE since then we'll behave wrong when getting
4211        HTTP. */
4212     data->set.httpreq = HTTPREQ_GET;
4213
4214   k->start = Curl_now(); /* start time */
4215   k->now = k->start;   /* current time is now */
4216   k->header = TRUE; /* assume header */
4217
4218   k->bytecount = 0;
4219
4220   k->buf = data->state.buffer;
4221   k->hbufp = data->state.headerbuff;
4222   k->ignorebody = FALSE;
4223
4224   Curl_speedinit(data);
4225
4226   Curl_pgrsSetUploadCounter(data, 0);
4227   Curl_pgrsSetDownloadCounter(data, 0);
4228
4229   return CURLE_OK;
4230 }
4231
4232 /*
4233 * get_protocol_family()
4234 *
4235 * This is used to return the protocol family for a given protocol.
4236 *
4237 * Parameters:
4238 *
4239 * protocol  [in]  - A single bit protocol identifier such as HTTP or HTTPS.
4240 *
4241 * Returns the family as a single bit protocol identifier.
4242 */
4243
4244 static unsigned int get_protocol_family(unsigned int protocol)
4245 {
4246   unsigned int family;
4247
4248   switch(protocol) {
4249   case CURLPROTO_HTTP:
4250   case CURLPROTO_HTTPS:
4251     family = CURLPROTO_HTTP;
4252     break;
4253
4254   case CURLPROTO_FTP:
4255   case CURLPROTO_FTPS:
4256     family = CURLPROTO_FTP;
4257     break;
4258
4259   case CURLPROTO_SCP:
4260     family = CURLPROTO_SCP;
4261     break;
4262
4263   case CURLPROTO_SFTP:
4264     family = CURLPROTO_SFTP;
4265     break;
4266
4267   case CURLPROTO_TELNET:
4268     family = CURLPROTO_TELNET;
4269     break;
4270
4271   case CURLPROTO_LDAP:
4272   case CURLPROTO_LDAPS:
4273     family = CURLPROTO_LDAP;
4274     break;
4275
4276   case CURLPROTO_DICT:
4277     family = CURLPROTO_DICT;
4278     break;
4279
4280   case CURLPROTO_FILE:
4281     family = CURLPROTO_FILE;
4282     break;
4283
4284   case CURLPROTO_TFTP:
4285     family = CURLPROTO_TFTP;
4286     break;
4287
4288   case CURLPROTO_IMAP:
4289   case CURLPROTO_IMAPS:
4290     family = CURLPROTO_IMAP;
4291     break;
4292
4293   case CURLPROTO_POP3:
4294   case CURLPROTO_POP3S:
4295     family = CURLPROTO_POP3;
4296     break;
4297
4298   case CURLPROTO_SMTP:
4299   case CURLPROTO_SMTPS:
4300       family = CURLPROTO_SMTP;
4301       break;
4302
4303   case CURLPROTO_RTSP:
4304     family = CURLPROTO_RTSP;
4305     break;
4306
4307   case CURLPROTO_RTMP:
4308   case CURLPROTO_RTMPS:
4309     family = CURLPROTO_RTMP;
4310     break;
4311
4312   case CURLPROTO_RTMPT:
4313   case CURLPROTO_RTMPTS:
4314     family = CURLPROTO_RTMPT;
4315     break;
4316
4317   case CURLPROTO_RTMPE:
4318     family = CURLPROTO_RTMPE;
4319     break;
4320
4321   case CURLPROTO_RTMPTE:
4322     family = CURLPROTO_RTMPTE;
4323     break;
4324
4325   case CURLPROTO_GOPHER:
4326     family = CURLPROTO_GOPHER;
4327     break;
4328
4329   case CURLPROTO_SMB:
4330   case CURLPROTO_SMBS:
4331     family = CURLPROTO_SMB;
4332     break;
4333
4334   default:
4335       family = 0;
4336       break;
4337   }
4338
4339   return family;
4340 }
4341
4342
4343 /*
4344  * Wrapper to call functions in Curl_conncache_foreach()
4345  *
4346  * Returns always 0.
4347  */
4348 static int conn_upkeep(struct connectdata *conn,
4349                        void *param)
4350 {
4351   /* Param is unused. */
4352   (void)param;
4353
4354   if(conn->handler->connection_check) {
4355     /* Do a protocol-specific keepalive check on the connection. */
4356     conn->handler->connection_check(conn, CONNCHECK_KEEPALIVE);
4357   }
4358
4359   return 0; /* continue iteration */
4360 }
4361
4362 CURLcode Curl_upkeep(struct conncache *conn_cache,
4363                           void *data)
4364 {
4365   /* Loop over every connection and make connection alive. */
4366   Curl_conncache_foreach(data,
4367                          conn_cache,
4368                          data,
4369                          conn_upkeep);
4370   return CURLE_OK;
4371 }