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