1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #ifdef HAVE_NETINET_IN_H
26 #include <netinet/in.h>
31 #ifdef HAVE_ARPA_INET_H
32 #include <arpa/inet.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 #include <sys/ioctl.h>
41 #ifdef HAVE_SYS_PARAM_H
42 #include <sys/param.h>
55 #error "We can't compile without socket() support!"
65 #elif defined(USE_WIN32_IDN)
66 /* prototype for curl_win32_idn_to_ascii() */
67 bool curl_win32_idn_to_ascii(const char *in, char **out);
68 #endif /* USE_LIBIDN2 */
74 #include "vtls/vtls.h"
85 #include "content_encoding.h"
86 #include "http_digest.h"
87 #include "http_negotiate.h"
91 #include "speedcheck.h"
93 #include "non-ascii.h"
94 #include "inet_pton.h"
97 /* And now for the protocols */
105 #include "curl_ldap.h"
110 #include "inet_ntop.h"
111 #include "http_ntlm.h"
112 #include "curl_ntlm_wb.h"
114 #include "curl_rtmp.h"
116 #include "http_proxy.h"
117 #include "conncache.h"
118 #include "multihandle.h"
119 #include "pipeline.h"
122 /* The last 3 #include files should be in this order */
123 #include "curl_printf.h"
124 #include "curl_memory.h"
125 #include "memdebug.h"
127 /* Local static prototypes */
128 static struct connectdata *
129 find_oldest_idle_connection_in_bundle(struct Curl_easy *data,
130 struct connectbundle *bundle);
131 static void conn_free(struct connectdata *conn);
132 static void free_fixed_hostname(struct hostname *host);
133 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
134 static CURLcode parse_url_login(struct Curl_easy *data,
135 struct connectdata *conn,
136 char **userptr, char **passwdptr,
138 static CURLcode parse_login_details(const char *login, const size_t len,
139 char **userptr, char **passwdptr,
141 static unsigned int get_protocol_family(unsigned int protocol);
147 static const struct Curl_handler * const protocols[] = {
149 #ifndef CURL_DISABLE_HTTP
153 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
157 #ifndef CURL_DISABLE_FTP
161 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
165 #ifndef CURL_DISABLE_TELNET
166 &Curl_handler_telnet,
169 #ifndef CURL_DISABLE_DICT
173 #ifndef CURL_DISABLE_LDAP
175 #if !defined(CURL_DISABLE_LDAPS) && \
176 ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
177 (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
182 #ifndef CURL_DISABLE_FILE
186 #ifndef CURL_DISABLE_TFTP
195 #ifndef CURL_DISABLE_IMAP
202 #ifndef CURL_DISABLE_POP3
209 #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
210 (CURL_SIZEOF_CURL_OFF_T > 4) && \
211 (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
218 #ifndef CURL_DISABLE_SMTP
225 #ifndef CURL_DISABLE_RTSP
229 #ifndef CURL_DISABLE_GOPHER
230 &Curl_handler_gopher,
237 &Curl_handler_rtmpte,
239 &Curl_handler_rtmpts,
242 (struct Curl_handler *) NULL
246 * Dummy handler for undefined protocol schemes.
249 static const struct Curl_handler Curl_handler_dummy = {
250 "<no protocol>", /* scheme */
251 ZERO_NULL, /* setup_connection */
252 ZERO_NULL, /* do_it */
253 ZERO_NULL, /* done */
254 ZERO_NULL, /* do_more */
255 ZERO_NULL, /* connect_it */
256 ZERO_NULL, /* connecting */
257 ZERO_NULL, /* doing */
258 ZERO_NULL, /* proto_getsock */
259 ZERO_NULL, /* doing_getsock */
260 ZERO_NULL, /* domore_getsock */
261 ZERO_NULL, /* perform_getsock */
262 ZERO_NULL, /* disconnect */
263 ZERO_NULL, /* readwrite */
266 PROTOPT_NONE /* flags */
269 void Curl_freeset(struct Curl_easy *data)
271 /* Free all dynamic strings stored in the data->set substructure. */
273 for(i=(enum dupstring)0; i < STRING_LAST; i++) {
274 Curl_safefree(data->set.str[i]);
277 if(data->change.referer_alloc) {
278 Curl_safefree(data->change.referer);
279 data->change.referer_alloc = FALSE;
281 data->change.referer = NULL;
282 if(data->change.url_alloc) {
283 Curl_safefree(data->change.url);
284 data->change.url_alloc = FALSE;
286 data->change.url = NULL;
289 static CURLcode setstropt(char **charp, const char *s)
291 /* Release the previous storage at `charp' and replace by a dynamic storage
292 copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
294 Curl_safefree(*charp);
297 char *str = strdup(s);
300 return CURLE_OUT_OF_MEMORY;
308 static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp)
310 CURLcode result = CURLE_OK;
314 /* Parse the login details if specified. It not then we treat NULL as a hint
315 to clear the existing data */
317 result = parse_login_details(option, strlen(option),
318 (userp ? &user : NULL),
319 (passwdp ? &passwd : NULL),
324 /* Store the username part of option if required */
326 if(!user && option && option[0] == ':') {
327 /* Allocate an empty string instead of returning NULL as user name */
330 result = CURLE_OUT_OF_MEMORY;
333 Curl_safefree(*userp);
337 /* Store the password part of option if required */
339 Curl_safefree(*passwdp);
347 CURLcode Curl_dupset(struct Curl_easy *dst, struct Curl_easy *src)
349 CURLcode result = CURLE_OK;
352 /* Copy src->set into dst->set first, then deal with the strings
356 /* clear all string pointers first */
357 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
359 /* duplicate all strings */
360 for(i=(enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
361 result = setstropt(&dst->set.str[i], src->set.str[i]);
366 /* duplicate memory areas pointed to */
367 i = STRING_COPYPOSTFIELDS;
368 if(src->set.postfieldsize && src->set.str[i]) {
369 /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */
370 dst->set.str[i] = Curl_memdup(src->set.str[i],
371 curlx_sotouz(src->set.postfieldsize));
373 return CURLE_OUT_OF_MEMORY;
374 /* point to the new copy */
375 dst->set.postfields = dst->set.str[i];
382 * This is the internal function curl_easy_cleanup() calls. This should
383 * cleanup and free all resources associated with this sessionhandle.
385 * NOTE: if we ever add something that attempts to write to a socket or
386 * similar here, we must ignore SIGPIPE first. It is currently only done
387 * when curl_easy_perform() is invoked.
390 CURLcode Curl_close(struct Curl_easy *data)
392 struct Curl_multi *m;
397 Curl_expire_clear(data); /* shut off timers */
402 /* This handle is still part of a multi handle, take care of this first
403 and detach this handle from there. */
404 curl_multi_remove_handle(data->multi, data);
407 /* when curl_easy_perform() is used, it creates its own multi handle to
408 use and this is the one */
409 curl_multi_cleanup(data->multi_easy);
411 /* Destroy the timeout list that is held in the easy handle. It is
412 /normally/ done by curl_multi_remove_handle() but this is "just in
414 if(data->state.timeoutlist) {
415 Curl_llist_destroy(data->state.timeoutlist, NULL);
416 data->state.timeoutlist = NULL;
419 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
420 the multi handle, since that function uses the magic
423 if(data->state.rangestringalloc)
424 free(data->state.range);
426 /* Free the pathbuffer */
427 Curl_safefree(data->state.pathbuffer);
428 data->state.path = NULL;
430 /* freed here just in case DONE wasn't called */
431 Curl_free_request_state(data);
433 /* Close down all open SSL info and sessions */
434 Curl_ssl_close_all(data);
435 Curl_safefree(data->state.first_host);
436 Curl_safefree(data->state.scratch);
437 Curl_ssl_free_certinfo(data);
439 /* Cleanup possible redirect junk */
440 free(data->req.newurl);
441 data->req.newurl = NULL;
443 if(data->change.referer_alloc) {
444 Curl_safefree(data->change.referer);
445 data->change.referer_alloc = FALSE;
447 data->change.referer = NULL;
449 if(data->change.url_alloc) {
450 Curl_safefree(data->change.url);
451 data->change.url_alloc = FALSE;
453 data->change.url = NULL;
455 Curl_safefree(data->state.buffer);
456 Curl_safefree(data->state.headerbuff);
458 Curl_flush_cookies(data, 1);
460 Curl_digest_cleanup(data);
462 Curl_safefree(data->info.contenttype);
463 Curl_safefree(data->info.wouldredirect);
465 /* this destroys the channel and we cannot use it anymore after this */
466 Curl_resolver_cleanup(data->state.resolver);
468 Curl_http2_cleanup_dependencies(data);
469 Curl_convert_close(data);
471 /* No longer a dirty share, if it exists */
473 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
474 data->share->dirty--;
475 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
478 if(data->set.wildcardmatch) {
479 /* destruct wildcard structures if it is needed */
480 struct WildcardData *wc = &data->wildcard;
481 Curl_wildcard_dtor(wc);
490 * Initialize the UserDefined fields within a Curl_easy.
491 * This may be safely called on a new or existing Curl_easy.
493 CURLcode Curl_init_userdefined(struct UserDefined *set)
495 CURLcode result = CURLE_OK;
497 set->out = stdout; /* default output to stdout */
498 set->in_set = stdin; /* default input from stdin */
499 set->err = stderr; /* default stderr to stderr */
501 /* use fwrite as default function to store output */
502 set->fwrite_func = (curl_write_callback)fwrite;
504 /* use fread as default function to read input */
505 set->fread_func_set = (curl_read_callback)fread;
506 set->is_fread_set = 0;
507 set->is_fwrite_set = 0;
509 set->seek_func = ZERO_NULL;
510 set->seek_client = ZERO_NULL;
512 /* conversion callbacks for non-ASCII hosts */
513 set->convfromnetwork = ZERO_NULL;
514 set->convtonetwork = ZERO_NULL;
515 set->convfromutf8 = ZERO_NULL;
517 set->filesize = -1; /* we don't know the size */
518 set->postfieldsize = -1; /* unknown size */
519 set->maxredirs = -1; /* allow any amount by default */
521 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
522 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
523 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
524 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
525 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
526 set->ftp_filemethod = FTPFILE_MULTICWD;
528 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
530 /* Set the default size of the SSL session ID cache */
531 set->general_ssl.max_ssl_sessions = 5;
534 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
535 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
536 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
538 /* make libcurl quiet by default: */
539 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
542 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
543 * switched off unless wanted.
545 set->ssl.primary.verifypeer = TRUE;
546 set->ssl.primary.verifyhost = TRUE;
548 set->ssl.authtype = CURL_TLSAUTH_NONE;
550 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
552 set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
554 set->proxy_ssl = set->ssl;
556 set->new_file_perms = 0644; /* Default permissions */
557 set->new_directory_perms = 0755; /* Default permissions */
559 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
560 define since we internally only use the lower 16 bits for the passed
561 in bitmask to not conflict with the private bits */
562 set->allowed_protocols = CURLPROTO_ALL;
563 set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
564 ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
567 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
569 * disallow unprotected protection negotiation NEC reference implementation
570 * seem not to follow rfc1961 section 4.3/4.4
572 set->socks5_gssapi_nec = FALSE;
575 /* This is our preferred CA cert bundle/path since install time */
576 #if defined(CURL_CA_BUNDLE)
577 result = setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
581 result = setstropt(&set->str[STRING_SSL_CAFILE_PROXY], CURL_CA_BUNDLE);
585 #if defined(CURL_CA_PATH)
586 result = setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
590 result = setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
595 set->wildcardmatch = FALSE;
596 set->chunk_bgn = ZERO_NULL;
597 set->chunk_end = ZERO_NULL;
599 /* tcp keepalives are disabled by default, but provide reasonable values for
600 * the interval and idle times.
602 set->tcp_keepalive = FALSE;
603 set->tcp_keepintvl = 60;
604 set->tcp_keepidle = 60;
605 set->tcp_fastopen = FALSE;
606 set->tcp_nodelay = TRUE;
608 set->ssl_enable_npn = TRUE;
609 set->ssl_enable_alpn = TRUE;
611 set->expect_100_timeout = 1000L; /* Wait for a second by default. */
612 set->sep_headers = TRUE; /* separated header lists by default */
614 Curl_http2_init_userset(set);
621 * @param curl is a pointer to a sessionhandle pointer that gets set by this
626 CURLcode Curl_open(struct Curl_easy **curl)
629 struct Curl_easy *data;
631 /* Very simple start-up: alloc the struct, init it with zeroes and return */
632 data = calloc(1, sizeof(struct Curl_easy));
634 /* this is a very serious error */
635 DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
636 return CURLE_OUT_OF_MEMORY;
639 data->magic = CURLEASY_MAGIC_NUMBER;
641 result = Curl_resolver_init(&data->state.resolver);
643 DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
648 /* We do some initial setup here, all those fields that can't be just 0 */
650 data->state.buffer = malloc(BUFSIZE + 1);
651 if(!data->state.buffer) {
652 DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n"));
653 result = CURLE_OUT_OF_MEMORY;
656 data->state.headerbuff = malloc(HEADERSIZE);
657 if(!data->state.headerbuff) {
658 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
659 result = CURLE_OUT_OF_MEMORY;
662 result = Curl_init_userdefined(&data->set);
664 data->state.headersize=HEADERSIZE;
666 Curl_convert_init(data);
670 /* most recent connection is not yet defined */
671 data->state.lastconnect = NULL;
673 data->progress.flags |= PGRS_HIDE;
674 data->state.current_speed = -1; /* init to negative == impossible */
676 data->wildcard.state = CURLWC_INIT;
677 data->wildcard.filelist = NULL;
678 data->set.fnmatch = ZERO_NULL;
679 data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
681 Curl_http2_init_state(&data->state);
685 Curl_resolver_cleanup(data->state.resolver);
686 free(data->state.buffer);
687 free(data->state.headerbuff);
698 CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
702 CURLcode result = CURLE_OK;
704 #ifndef CURL_DISABLE_HTTP
709 case CURLOPT_DNS_CACHE_TIMEOUT:
710 data->set.dns_cache_timeout = va_arg(param, long);
712 case CURLOPT_DNS_USE_GLOBAL_CACHE:
713 /* remember we want this enabled */
714 arg = va_arg(param, long);
715 data->set.global_dns_cache = (0 != arg) ? TRUE : FALSE;
717 case CURLOPT_SSL_CIPHER_LIST:
718 /* set a list of cipher we want to use in the SSL connection */
719 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_ORIG],
720 va_arg(param, char *));
722 case CURLOPT_PROXY_SSL_CIPHER_LIST:
723 /* set a list of cipher we want to use in the SSL connection for proxy */
724 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_PROXY],
725 va_arg(param, char *));
728 case CURLOPT_RANDOM_FILE:
730 * This is the path name to a file that contains random data to seed
731 * the random SSL stuff with. The file is only used for reading.
733 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
734 va_arg(param, char *));
736 case CURLOPT_EGDSOCKET:
738 * The Entropy Gathering Daemon socket pathname
740 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
741 va_arg(param, char *));
743 case CURLOPT_MAXCONNECTS:
745 * Set the absolute number of maximum simultaneous alive connection that
746 * libcurl is allowed to have.
748 data->set.maxconnects = va_arg(param, long);
750 case CURLOPT_FORBID_REUSE:
752 * When this transfer is done, it must not be left to be reused by a
753 * subsequent transfer but shall be closed immediately.
755 data->set.reuse_forbid = (0 != va_arg(param, long)) ? TRUE : FALSE;
757 case CURLOPT_FRESH_CONNECT:
759 * This transfer shall not use a previously cached connection but
760 * should be made with a fresh new connect!
762 data->set.reuse_fresh = (0 != va_arg(param, long)) ? TRUE : FALSE;
764 case CURLOPT_VERBOSE:
766 * Verbose means infof() calls that give a lot of information about
767 * the connection and transfer procedures as well as internal choices.
769 data->set.verbose = (0 != va_arg(param, long)) ? TRUE : FALSE;
773 * Set to include the header in the general data output stream.
775 data->set.include_header = (0 != va_arg(param, long)) ? TRUE : FALSE;
777 case CURLOPT_NOPROGRESS:
779 * Shut off the internal supported progress meter
781 data->set.hide_progress = (0 != va_arg(param, long)) ? TRUE : FALSE;
782 if(data->set.hide_progress)
783 data->progress.flags |= PGRS_HIDE;
785 data->progress.flags &= ~PGRS_HIDE;
789 * Do not include the body part in the output data stream.
791 data->set.opt_no_body = (0 != va_arg(param, long)) ? TRUE : FALSE;
793 case CURLOPT_FAILONERROR:
795 * Don't output the >=400 error code HTML-page, but instead only
798 data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE;
800 case CURLOPT_KEEP_SENDING_ON_ERROR:
801 data->set.http_keep_sending_on_error = (0 != va_arg(param, long)) ?
807 * We want to sent data to the remote host. If this is HTTP, that equals
808 * using the PUT request.
810 data->set.upload = (0 != va_arg(param, long)) ? TRUE : FALSE;
811 if(data->set.upload) {
812 /* If this is HTTP, PUT is what's needed to "upload" */
813 data->set.httpreq = HTTPREQ_PUT;
814 data->set.opt_no_body = FALSE; /* this is implied */
817 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
818 then this can be changed to HEAD later on) */
819 data->set.httpreq = HTTPREQ_GET;
821 case CURLOPT_FILETIME:
823 * Try to get the file time of the remote document. The time will
824 * later (possibly) become available using curl_easy_getinfo().
826 data->set.get_filetime = (0 != va_arg(param, long)) ? TRUE : FALSE;
828 case CURLOPT_FTP_CREATE_MISSING_DIRS:
830 * An FTP option that modifies an upload to create missing directories on
833 switch(va_arg(param, long)) {
835 data->set.ftp_create_missing_dirs = 0;
838 data->set.ftp_create_missing_dirs = 1;
841 data->set.ftp_create_missing_dirs = 2;
844 /* reserve other values for future use */
845 result = CURLE_UNKNOWN_OPTION;
849 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
851 * Option that specifies how quickly an server response must be obtained
852 * before it is considered failure. For pingpong protocols.
854 data->set.server_response_timeout = va_arg(param, long) * 1000;
856 case CURLOPT_TFTP_NO_OPTIONS:
858 * Option that prevents libcurl from sending TFTP option requests to the
861 data->set.tftp_no_options = va_arg(param, long) != 0;
863 case CURLOPT_TFTP_BLKSIZE:
865 * TFTP option that specifies the block size to use for data transmission.
867 data->set.tftp_blksize = va_arg(param, long);
869 case CURLOPT_DIRLISTONLY:
871 * An option that changes the command to one that asks for a list
872 * only, no file info details.
874 data->set.ftp_list_only = (0 != va_arg(param, long)) ? TRUE : FALSE;
878 * We want to upload and append to an existing file.
880 data->set.ftp_append = (0 != va_arg(param, long)) ? TRUE : FALSE;
882 case CURLOPT_FTP_FILEMETHOD:
884 * How do access files over FTP.
886 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
890 * Parse the $HOME/.netrc file
892 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
894 case CURLOPT_NETRC_FILE:
896 * Use this file instead of the $HOME/.netrc file
898 result = setstropt(&data->set.str[STRING_NETRC_FILE],
899 va_arg(param, char *));
901 case CURLOPT_TRANSFERTEXT:
903 * This option was previously named 'FTPASCII'. Renamed to work with
904 * more protocols than merely FTP.
906 * Transfer using ASCII (instead of BINARY).
908 data->set.prefer_ascii = (0 != va_arg(param, long)) ? TRUE : FALSE;
910 case CURLOPT_TIMECONDITION:
912 * Set HTTP time condition. This must be one of the defines in the
913 * curl/curl.h header file.
915 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
917 case CURLOPT_TIMEVALUE:
919 * This is the value to compare with the remote document with the
920 * method set with CURLOPT_TIMECONDITION
922 data->set.timevalue = (time_t)va_arg(param, long);
924 case CURLOPT_SSLVERSION:
926 * Set explicit SSL version to try to connect with, as some SSL
927 * implementations are lame.
930 data->set.ssl.primary.version = va_arg(param, long);
932 result = CURLE_UNKNOWN_OPTION;
935 case CURLOPT_PROXY_SSLVERSION:
937 * Set explicit SSL version to try to connect with for proxy, as some SSL
938 * implementations are lame.
941 data->set.proxy_ssl.primary.version = va_arg(param, long);
943 result = CURLE_UNKNOWN_OPTION;
947 #ifndef CURL_DISABLE_HTTP
948 case CURLOPT_AUTOREFERER:
950 * Switch on automatic referer that gets set if curl follows locations.
952 data->set.http_auto_referer = (0 != va_arg(param, long)) ? TRUE : FALSE;
955 case CURLOPT_ACCEPT_ENCODING:
957 * String to use at the value of Accept-Encoding header.
959 * If the encoding is set to "" we use an Accept-Encoding header that
960 * encompasses all the encodings we support.
961 * If the encoding is set to NULL we don't send an Accept-Encoding header
962 * and ignore an received Content-Encoding header.
965 argptr = va_arg(param, char *);
966 result = setstropt(&data->set.str[STRING_ENCODING],
967 (argptr && !*argptr)?
968 ALL_CONTENT_ENCODINGS: argptr);
971 case CURLOPT_TRANSFER_ENCODING:
972 data->set.http_transfer_encoding = (0 != va_arg(param, long)) ?
976 case CURLOPT_FOLLOWLOCATION:
978 * Follow Location: header hints on a HTTP-server.
980 data->set.http_follow_location = (0 != va_arg(param, long)) ? TRUE : FALSE;
983 case CURLOPT_UNRESTRICTED_AUTH:
985 * Send authentication (user+password) when following locations, even when
988 data->set.http_disable_hostname_check_before_authentication =
989 (0 != va_arg(param, long)) ? TRUE : FALSE;
992 case CURLOPT_MAXREDIRS:
994 * The maximum amount of hops you allow curl to follow Location:
995 * headers. This should mostly be used to detect never-ending loops.
997 data->set.maxredirs = va_arg(param, long);
1000 case CURLOPT_POSTREDIR:
1003 * Set the behaviour of POST when redirecting
1004 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
1005 * CURL_REDIR_POST_301 - POST is kept as POST after 301
1006 * CURL_REDIR_POST_302 - POST is kept as POST after 302
1007 * CURL_REDIR_POST_303 - POST is kept as POST after 303
1008 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
1009 * other - POST is kept as POST after 301 and 302
1011 int postRedir = curlx_sltosi(va_arg(param, long));
1012 data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
1017 /* Does this option serve a purpose anymore? Yes it does, when
1018 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
1020 if(va_arg(param, long)) {
1021 data->set.httpreq = HTTPREQ_POST;
1022 data->set.opt_no_body = FALSE; /* this is implied */
1025 data->set.httpreq = HTTPREQ_GET;
1028 case CURLOPT_COPYPOSTFIELDS:
1030 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
1031 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
1032 * CURLOPT_COPYPOSTFIELDS and not altered later.
1034 argptr = va_arg(param, char *);
1036 if(!argptr || data->set.postfieldsize == -1)
1037 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
1040 * Check that requested length does not overflow the size_t type.
1043 if((data->set.postfieldsize < 0) ||
1044 ((sizeof(curl_off_t) != sizeof(size_t)) &&
1045 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
1046 result = CURLE_OUT_OF_MEMORY;
1050 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1052 /* Allocate even when size == 0. This satisfies the need of possible
1053 later address compare to detect the COPYPOSTFIELDS mode, and
1054 to mark that postfields is used rather than read function or
1057 p = malloc((size_t)(data->set.postfieldsize?
1058 data->set.postfieldsize:1));
1061 result = CURLE_OUT_OF_MEMORY;
1063 if(data->set.postfieldsize)
1064 memcpy(p, argptr, (size_t)data->set.postfieldsize);
1066 data->set.str[STRING_COPYPOSTFIELDS] = p;
1071 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
1072 data->set.httpreq = HTTPREQ_POST;
1075 case CURLOPT_POSTFIELDS:
1077 * Like above, but use static data instead of copying it.
1079 data->set.postfields = va_arg(param, void *);
1080 /* Release old copied data. */
1081 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1082 data->set.httpreq = HTTPREQ_POST;
1085 case CURLOPT_POSTFIELDSIZE:
1087 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1088 * figure it out. Enables binary posts.
1090 bigsize = va_arg(param, long);
1092 if(data->set.postfieldsize < bigsize &&
1093 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1094 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1095 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1096 data->set.postfields = NULL;
1099 data->set.postfieldsize = bigsize;
1102 case CURLOPT_POSTFIELDSIZE_LARGE:
1104 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1105 * figure it out. Enables binary posts.
1107 bigsize = va_arg(param, curl_off_t);
1109 if(data->set.postfieldsize < bigsize &&
1110 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1111 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1112 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1113 data->set.postfields = NULL;
1116 data->set.postfieldsize = bigsize;
1119 case CURLOPT_HTTPPOST:
1121 * Set to make us do HTTP POST
1123 data->set.httppost = va_arg(param, struct curl_httppost *);
1124 data->set.httpreq = HTTPREQ_POST_FORM;
1125 data->set.opt_no_body = FALSE; /* this is implied */
1128 case CURLOPT_REFERER:
1130 * String to set in the HTTP Referer: field.
1132 if(data->change.referer_alloc) {
1133 Curl_safefree(data->change.referer);
1134 data->change.referer_alloc = FALSE;
1136 result = setstropt(&data->set.str[STRING_SET_REFERER],
1137 va_arg(param, char *));
1138 data->change.referer = data->set.str[STRING_SET_REFERER];
1141 case CURLOPT_USERAGENT:
1143 * String to use in the HTTP User-Agent field
1145 result = setstropt(&data->set.str[STRING_USERAGENT],
1146 va_arg(param, char *));
1149 case CURLOPT_HTTPHEADER:
1151 * Set a list with HTTP headers to use (or replace internals with)
1153 data->set.headers = va_arg(param, struct curl_slist *);
1156 case CURLOPT_PROXYHEADER:
1158 * Set a list with proxy headers to use (or replace internals with)
1160 * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a
1161 * long time we remain doing it this way until CURLOPT_PROXYHEADER is
1162 * used. As soon as this option has been used, if set to anything but
1163 * NULL, custom headers for proxies are only picked from this list.
1165 * Set this option to NULL to restore the previous behavior.
1167 data->set.proxyheaders = va_arg(param, struct curl_slist *);
1170 case CURLOPT_HEADEROPT:
1172 * Set header option.
1174 arg = va_arg(param, long);
1175 data->set.sep_headers = (arg & CURLHEADER_SEPARATE)? TRUE: FALSE;
1178 case CURLOPT_HTTP200ALIASES:
1180 * Set a list of aliases for HTTP 200 in response header
1182 data->set.http200aliases = va_arg(param, struct curl_slist *);
1185 #if !defined(CURL_DISABLE_COOKIES)
1186 case CURLOPT_COOKIE:
1188 * Cookie string to send to the remote server in the request.
1190 result = setstropt(&data->set.str[STRING_COOKIE],
1191 va_arg(param, char *));
1194 case CURLOPT_COOKIEFILE:
1196 * Set cookie file to read and parse. Can be used multiple times.
1198 argptr = (char *)va_arg(param, void *);
1200 struct curl_slist *cl;
1201 /* append the cookie file name to the list of file names, and deal with
1203 cl = curl_slist_append(data->change.cookielist, argptr);
1205 curl_slist_free_all(data->change.cookielist);
1206 data->change.cookielist = NULL;
1207 return CURLE_OUT_OF_MEMORY;
1209 data->change.cookielist = cl; /* store the list for later use */
1213 case CURLOPT_COOKIEJAR:
1215 * Set cookie file name to dump all cookies to when we're done.
1218 struct CookieInfo *newcookies;
1219 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1220 va_arg(param, char *));
1223 * Activate the cookie parser. This may or may not already
1226 newcookies = Curl_cookie_init(data, NULL, data->cookies,
1227 data->set.cookiesession);
1229 result = CURLE_OUT_OF_MEMORY;
1230 data->cookies = newcookies;
1234 case CURLOPT_COOKIESESSION:
1236 * Set this option to TRUE to start a new "cookie session". It will
1237 * prevent the forthcoming read-cookies-from-file actions to accept
1238 * cookies that are marked as being session cookies, as they belong to a
1241 * In the original Netscape cookie spec, "session cookies" are cookies
1242 * with no expire date set. RFC2109 describes the same action if no
1243 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1244 * a 'Discard' action that can enforce the discard even for cookies that
1247 * We run mostly with the original cookie spec, as hardly anyone implements
1250 data->set.cookiesession = (0 != va_arg(param, long)) ? TRUE : FALSE;
1253 case CURLOPT_COOKIELIST:
1254 argptr = va_arg(param, char *);
1259 if(strcasecompare(argptr, "ALL")) {
1260 /* clear all cookies */
1261 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1262 Curl_cookie_clearall(data->cookies);
1263 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1265 else if(strcasecompare(argptr, "SESS")) {
1266 /* clear session cookies */
1267 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1268 Curl_cookie_clearsess(data->cookies);
1269 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1271 else if(strcasecompare(argptr, "FLUSH")) {
1272 /* flush cookies to file, takes care of the locking */
1273 Curl_flush_cookies(data, 0);
1275 else if(strcasecompare(argptr, "RELOAD")) {
1276 /* reload cookies from file */
1277 Curl_cookie_loadfiles(data);
1282 /* if cookie engine was not running, activate it */
1283 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1285 argptr = strdup(argptr);
1286 if(!argptr || !data->cookies) {
1287 result = CURLE_OUT_OF_MEMORY;
1291 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1293 if(checkprefix("Set-Cookie:", argptr))
1294 /* HTTP Header format line */
1295 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1298 /* Netscape format line */
1299 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1301 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1307 #endif /* CURL_DISABLE_COOKIES */
1309 case CURLOPT_HTTPGET:
1311 * Set to force us do HTTP GET
1313 if(va_arg(param, long)) {
1314 data->set.httpreq = HTTPREQ_GET;
1315 data->set.upload = FALSE; /* switch off upload */
1316 data->set.opt_no_body = FALSE; /* this is implied */
1320 case CURLOPT_HTTP_VERSION:
1322 * This sets a requested HTTP version to be used. The value is one of
1323 * the listed enums in curl/curl.h.
1325 arg = va_arg(param, long);
1327 if(arg >= CURL_HTTP_VERSION_2)
1328 return CURLE_UNSUPPORTED_PROTOCOL;
1330 data->set.httpversion = arg;
1333 case CURLOPT_HTTPAUTH:
1335 * Set HTTP Authentication type BITMASK.
1340 unsigned long auth = va_arg(param, unsigned long);
1342 if(auth == CURLAUTH_NONE) {
1343 data->set.httpauth = auth;
1347 /* the DIGEST_IE bit is only used to set a special marker, for all the
1348 rest we need to handle it as normal DIGEST */
1349 data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE;
1351 if(auth & CURLAUTH_DIGEST_IE) {
1352 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1353 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1356 /* switch off bits we can't support */
1358 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1359 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1360 #elif !defined(NTLM_WB_ENABLED)
1361 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1364 auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
1368 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1371 while(bitcheck < 31) {
1372 if(auth & (1UL << bitcheck++)) {
1378 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1380 data->set.httpauth = auth;
1384 case CURLOPT_EXPECT_100_TIMEOUT_MS:
1386 * Time to wait for a response to a HTTP request containing an
1387 * Expect: 100-continue header before sending the data anyway.
1389 data->set.expect_100_timeout = va_arg(param, long);
1392 #endif /* CURL_DISABLE_HTTP */
1394 case CURLOPT_CUSTOMREQUEST:
1396 * Set a custom string to use as request
1398 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1399 va_arg(param, char *));
1402 data->set.httpreq = HTTPREQ_CUSTOM;
1403 here, we continue as if we were using the already set type
1404 and this just changes the actual request keyword */
1407 #ifndef CURL_DISABLE_PROXY
1408 case CURLOPT_HTTPPROXYTUNNEL:
1410 * Tunnel operations through the proxy instead of normal proxy use
1412 data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)) ?
1416 case CURLOPT_PROXYPORT:
1418 * Explicitly set HTTP proxy port number.
1420 data->set.proxyport = va_arg(param, long);
1423 case CURLOPT_PROXYAUTH:
1425 * Set HTTP Authentication type BITMASK.
1430 unsigned long auth = va_arg(param, unsigned long);
1432 if(auth == CURLAUTH_NONE) {
1433 data->set.proxyauth = auth;
1437 /* the DIGEST_IE bit is only used to set a special marker, for all the
1438 rest we need to handle it as normal DIGEST */
1439 data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE;
1441 if(auth & CURLAUTH_DIGEST_IE) {
1442 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1443 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1445 /* switch off bits we can't support */
1447 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1448 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1449 #elif !defined(NTLM_WB_ENABLED)
1450 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1453 auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
1457 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1460 while(bitcheck < 31) {
1461 if(auth & (1UL << bitcheck++)) {
1467 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1469 data->set.proxyauth = auth;
1475 * Set proxy server:port to use as proxy.
1477 * If the proxy is set to "" (and CURLOPT_SOCKS_PROXY is set to "" or NULL)
1478 * we explicitly say that we don't want to use a proxy
1479 * (even though there might be environment variables saying so).
1481 * Setting it to NULL, means no proxy but allows the environment variables
1482 * to decide for us (if CURLOPT_SOCKS_PROXY setting it to NULL).
1484 result = setstropt(&data->set.str[STRING_PROXY],
1485 va_arg(param, char *));
1488 case CURLOPT_PRE_PROXY:
1490 * Set proxy server:port to use as SOCKS proxy.
1492 * If the proxy is set to "" or NULL we explicitly say that we don't want
1493 * to use the socks proxy.
1495 result = setstropt(&data->set.str[STRING_PRE_PROXY],
1496 va_arg(param, char *));
1499 case CURLOPT_PROXYTYPE:
1501 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1503 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1506 case CURLOPT_PROXY_TRANSFER_MODE:
1508 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1510 switch(va_arg(param, long)) {
1512 data->set.proxy_transfer_mode = FALSE;
1515 data->set.proxy_transfer_mode = TRUE;
1518 /* reserve other values for future use */
1519 result = CURLE_UNKNOWN_OPTION;
1523 #endif /* CURL_DISABLE_PROXY */
1525 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1526 case CURLOPT_SOCKS5_GSSAPI_NEC:
1528 * Set flag for NEC SOCK5 support
1530 data->set.socks5_gssapi_nec = (0 != va_arg(param, long)) ? TRUE : FALSE;
1533 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1534 case CURLOPT_PROXY_SERVICE_NAME:
1536 * Set proxy authentication service name for Kerberos 5 and SPNEGO
1538 result = setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME],
1539 va_arg(param, char *));
1543 #if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \
1545 case CURLOPT_SERVICE_NAME:
1547 * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO
1549 result = setstropt(&data->set.str[STRING_SERVICE_NAME],
1550 va_arg(param, char *));
1555 case CURLOPT_HEADERDATA:
1557 * Custom pointer to pass the header write callback function
1559 data->set.writeheader = (void *)va_arg(param, void *);
1561 case CURLOPT_ERRORBUFFER:
1563 * Error buffer provided by the caller to get the human readable
1566 data->set.errorbuffer = va_arg(param, char *);
1568 case CURLOPT_WRITEDATA:
1570 * FILE pointer to write to. Or possibly
1571 * used as argument to the write callback.
1573 data->set.out = va_arg(param, void *);
1575 case CURLOPT_FTPPORT:
1577 * Use FTP PORT, this also specifies which IP address to use
1579 result = setstropt(&data->set.str[STRING_FTPPORT],
1580 va_arg(param, char *));
1581 data->set.ftp_use_port = (data->set.str[STRING_FTPPORT]) ? TRUE : FALSE;
1584 case CURLOPT_FTP_USE_EPRT:
1585 data->set.ftp_use_eprt = (0 != va_arg(param, long)) ? TRUE : FALSE;
1588 case CURLOPT_FTP_USE_EPSV:
1589 data->set.ftp_use_epsv = (0 != va_arg(param, long)) ? TRUE : FALSE;
1592 case CURLOPT_FTP_USE_PRET:
1593 data->set.ftp_use_pret = (0 != va_arg(param, long)) ? TRUE : FALSE;
1596 case CURLOPT_FTP_SSL_CCC:
1597 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1600 case CURLOPT_FTP_SKIP_PASV_IP:
1602 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1603 * bypass of the IP address in PASV responses.
1605 data->set.ftp_skip_ip = (0 != va_arg(param, long)) ? TRUE : FALSE;
1608 case CURLOPT_READDATA:
1610 * FILE pointer to read the file to be uploaded from. Or possibly
1611 * used as argument to the read callback.
1613 data->set.in_set = va_arg(param, void *);
1615 case CURLOPT_INFILESIZE:
1617 * If known, this should inform curl about the file size of the
1618 * to-be-uploaded file.
1620 data->set.filesize = va_arg(param, long);
1622 case CURLOPT_INFILESIZE_LARGE:
1624 * If known, this should inform curl about the file size of the
1625 * to-be-uploaded file.
1627 data->set.filesize = va_arg(param, curl_off_t);
1629 case CURLOPT_LOW_SPEED_LIMIT:
1631 * The low speed limit that if transfers are below this for
1632 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1634 data->set.low_speed_limit=va_arg(param, long);
1636 case CURLOPT_MAX_SEND_SPEED_LARGE:
1638 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1639 * bytes per second the transfer is throttled..
1641 data->set.max_send_speed=va_arg(param, curl_off_t);
1643 case CURLOPT_MAX_RECV_SPEED_LARGE:
1645 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1646 * second the transfer is throttled..
1648 data->set.max_recv_speed=va_arg(param, curl_off_t);
1650 case CURLOPT_LOW_SPEED_TIME:
1652 * The low speed time that if transfers are below the set
1653 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1655 data->set.low_speed_time=va_arg(param, long);
1661 if(data->change.url_alloc) {
1662 /* the already set URL is allocated, free it first! */
1663 Curl_safefree(data->change.url);
1664 data->change.url_alloc = FALSE;
1666 result = setstropt(&data->set.str[STRING_SET_URL],
1667 va_arg(param, char *));
1668 data->change.url = data->set.str[STRING_SET_URL];
1672 * The port number to use when getting the URL
1674 data->set.use_port = va_arg(param, long);
1676 case CURLOPT_TIMEOUT:
1678 * The maximum time you allow curl to use for a single transfer
1681 data->set.timeout = va_arg(param, long) * 1000L;
1684 case CURLOPT_TIMEOUT_MS:
1685 data->set.timeout = va_arg(param, long);
1688 case CURLOPT_CONNECTTIMEOUT:
1690 * The maximum time you allow curl to use to connect.
1692 data->set.connecttimeout = va_arg(param, long) * 1000L;
1695 case CURLOPT_CONNECTTIMEOUT_MS:
1696 data->set.connecttimeout = va_arg(param, long);
1699 case CURLOPT_ACCEPTTIMEOUT_MS:
1701 * The maximum time you allow curl to wait for server connect
1703 data->set.accepttimeout = va_arg(param, long);
1706 case CURLOPT_USERPWD:
1708 * user:password to use in the operation
1710 result = setstropt_userpwd(va_arg(param, char *),
1711 &data->set.str[STRING_USERNAME],
1712 &data->set.str[STRING_PASSWORD]);
1715 case CURLOPT_USERNAME:
1717 * authentication user name to use in the operation
1719 result = setstropt(&data->set.str[STRING_USERNAME],
1720 va_arg(param, char *));
1723 case CURLOPT_PASSWORD:
1725 * authentication password to use in the operation
1727 result = setstropt(&data->set.str[STRING_PASSWORD],
1728 va_arg(param, char *));
1731 case CURLOPT_LOGIN_OPTIONS:
1733 * authentication options to use in the operation
1735 result = setstropt(&data->set.str[STRING_OPTIONS],
1736 va_arg(param, char *));
1739 case CURLOPT_XOAUTH2_BEARER:
1741 * OAuth 2.0 bearer token to use in the operation
1743 result = setstropt(&data->set.str[STRING_BEARER],
1744 va_arg(param, char *));
1747 case CURLOPT_POSTQUOTE:
1749 * List of RAW FTP commands to use after a transfer
1751 data->set.postquote = va_arg(param, struct curl_slist *);
1753 case CURLOPT_PREQUOTE:
1755 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1757 data->set.prequote = va_arg(param, struct curl_slist *);
1761 * List of RAW FTP commands to use before a transfer
1763 data->set.quote = va_arg(param, struct curl_slist *);
1765 case CURLOPT_RESOLVE:
1767 * List of NAME:[address] names to populate the DNS cache with
1768 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1770 * Names added with this API will remain in the cache until explicitly
1771 * removed or the handle is cleaned up.
1773 * This API can remove any name from the DNS cache, but only entries
1774 * that aren't actually in use right now will be pruned immediately.
1776 data->set.resolve = va_arg(param, struct curl_slist *);
1777 data->change.resolve = data->set.resolve;
1779 case CURLOPT_PROGRESSFUNCTION:
1781 * Progress callback function
1783 data->set.fprogress = va_arg(param, curl_progress_callback);
1784 if(data->set.fprogress)
1785 data->progress.callback = TRUE; /* no longer internal */
1787 data->progress.callback = FALSE; /* NULL enforces internal */
1790 case CURLOPT_XFERINFOFUNCTION:
1792 * Transfer info callback function
1794 data->set.fxferinfo = va_arg(param, curl_xferinfo_callback);
1795 if(data->set.fxferinfo)
1796 data->progress.callback = TRUE; /* no longer internal */
1798 data->progress.callback = FALSE; /* NULL enforces internal */
1802 case CURLOPT_PROGRESSDATA:
1804 * Custom client data to pass to the progress callback
1806 data->set.progress_client = va_arg(param, void *);
1809 #ifndef CURL_DISABLE_PROXY
1810 case CURLOPT_PROXYUSERPWD:
1812 * user:password needed to use the proxy
1814 result = setstropt_userpwd(va_arg(param, char *),
1815 &data->set.str[STRING_PROXYUSERNAME],
1816 &data->set.str[STRING_PROXYPASSWORD]);
1818 case CURLOPT_PROXYUSERNAME:
1820 * authentication user name to use in the operation
1822 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1823 va_arg(param, char *));
1825 case CURLOPT_PROXYPASSWORD:
1827 * authentication password to use in the operation
1829 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1830 va_arg(param, char *));
1832 case CURLOPT_NOPROXY:
1834 * proxy exception list
1836 result = setstropt(&data->set.str[STRING_NOPROXY],
1837 va_arg(param, char *));
1843 * What range of the file you want to transfer
1845 result = setstropt(&data->set.str[STRING_SET_RANGE],
1846 va_arg(param, char *));
1848 case CURLOPT_RESUME_FROM:
1850 * Resume transfer at the give file position
1852 data->set.set_resume_from = va_arg(param, long);
1854 case CURLOPT_RESUME_FROM_LARGE:
1856 * Resume transfer at the give file position
1858 data->set.set_resume_from = va_arg(param, curl_off_t);
1860 case CURLOPT_DEBUGFUNCTION:
1862 * stderr write callback.
1864 data->set.fdebug = va_arg(param, curl_debug_callback);
1866 * if the callback provided is NULL, it'll use the default callback
1869 case CURLOPT_DEBUGDATA:
1871 * Set to a void * that should receive all error writes. This
1872 * defaults to CURLOPT_STDERR for normal operations.
1874 data->set.debugdata = va_arg(param, void *);
1876 case CURLOPT_STDERR:
1878 * Set to a FILE * that should receive all error writes. This
1879 * defaults to stderr for normal operations.
1881 data->set.err = va_arg(param, FILE *);
1883 data->set.err = stderr;
1885 case CURLOPT_HEADERFUNCTION:
1887 * Set header write callback
1889 data->set.fwrite_header = va_arg(param, curl_write_callback);
1891 case CURLOPT_WRITEFUNCTION:
1893 * Set data write callback
1895 data->set.fwrite_func = va_arg(param, curl_write_callback);
1896 if(!data->set.fwrite_func) {
1897 data->set.is_fwrite_set = 0;
1898 /* When set to NULL, reset to our internal default function */
1899 data->set.fwrite_func = (curl_write_callback)fwrite;
1902 data->set.is_fwrite_set = 1;
1904 case CURLOPT_READFUNCTION:
1906 * Read data callback
1908 data->set.fread_func_set = va_arg(param, curl_read_callback);
1909 if(!data->set.fread_func_set) {
1910 data->set.is_fread_set = 0;
1911 /* When set to NULL, reset to our internal default function */
1912 data->set.fread_func_set = (curl_read_callback)fread;
1915 data->set.is_fread_set = 1;
1917 case CURLOPT_SEEKFUNCTION:
1919 * Seek callback. Might be NULL.
1921 data->set.seek_func = va_arg(param, curl_seek_callback);
1923 case CURLOPT_SEEKDATA:
1925 * Seek control callback. Might be NULL.
1927 data->set.seek_client = va_arg(param, void *);
1929 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1931 * "Convert from network encoding" callback
1933 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1935 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1937 * "Convert to network encoding" callback
1939 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1941 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1943 * "Convert from UTF-8 encoding" callback
1945 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1947 case CURLOPT_IOCTLFUNCTION:
1949 * I/O control callback. Might be NULL.
1951 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1953 case CURLOPT_IOCTLDATA:
1955 * I/O control data pointer. Might be NULL.
1957 data->set.ioctl_client = va_arg(param, void *);
1959 case CURLOPT_SSLCERT:
1961 * String that holds file name of the SSL certificate to use
1963 result = setstropt(&data->set.str[STRING_CERT_ORIG],
1964 va_arg(param, char *));
1966 case CURLOPT_PROXY_SSLCERT:
1968 * String that holds file name of the SSL certificate to use for proxy
1970 result = setstropt(&data->set.str[STRING_CERT_PROXY],
1971 va_arg(param, char *));
1973 case CURLOPT_SSLCERTTYPE:
1975 * String that holds file type of the SSL certificate to use
1977 result = setstropt(&data->set.str[STRING_CERT_TYPE_ORIG],
1978 va_arg(param, char *));
1980 case CURLOPT_PROXY_SSLCERTTYPE:
1982 * String that holds file type of the SSL certificate to use for proxy
1984 result = setstropt(&data->set.str[STRING_CERT_TYPE_PROXY],
1985 va_arg(param, char *));
1987 case CURLOPT_SSLKEY:
1989 * String that holds file name of the SSL key to use
1991 result = setstropt(&data->set.str[STRING_KEY_ORIG],
1992 va_arg(param, char *));
1994 case CURLOPT_PROXY_SSLKEY:
1996 * String that holds file name of the SSL key to use for proxy
1998 result = setstropt(&data->set.str[STRING_KEY_PROXY],
1999 va_arg(param, char *));
2001 case CURLOPT_SSLKEYTYPE:
2003 * String that holds file type of the SSL key to use
2005 result = setstropt(&data->set.str[STRING_KEY_TYPE_ORIG],
2006 va_arg(param, char *));
2008 case CURLOPT_PROXY_SSLKEYTYPE:
2010 * String that holds file type of the SSL key to use for proxy
2012 result = setstropt(&data->set.str[STRING_KEY_TYPE_PROXY],
2013 va_arg(param, char *));
2015 case CURLOPT_KEYPASSWD:
2017 * String that holds the SSL or SSH private key password.
2019 result = setstropt(&data->set.str[STRING_KEY_PASSWD_ORIG],
2020 va_arg(param, char *));
2022 case CURLOPT_PROXY_KEYPASSWD:
2024 * String that holds the SSL private key password for proxy.
2026 result = setstropt(&data->set.str[STRING_KEY_PASSWD_PROXY],
2027 va_arg(param, char *));
2029 case CURLOPT_SSLENGINE:
2031 * String that holds the SSL crypto engine.
2033 argptr = va_arg(param, char *);
2034 if(argptr && argptr[0])
2035 result = Curl_ssl_set_engine(data, argptr);
2038 case CURLOPT_SSLENGINE_DEFAULT:
2040 * flag to set engine as default.
2042 result = Curl_ssl_set_engine_default(data);
2046 * Kludgy option to enable CRLF conversions. Subject for removal.
2048 data->set.crlf = (0 != va_arg(param, long)) ? TRUE : FALSE;
2051 case CURLOPT_INTERFACE:
2053 * Set what interface or address/hostname to bind the socket to when
2054 * performing an operation and thus what from-IP your connection will use.
2056 result = setstropt(&data->set.str[STRING_DEVICE],
2057 va_arg(param, char *));
2059 case CURLOPT_LOCALPORT:
2061 * Set what local port to bind the socket to when performing an operation.
2063 data->set.localport = curlx_sltous(va_arg(param, long));
2065 case CURLOPT_LOCALPORTRANGE:
2067 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
2069 data->set.localportrange = curlx_sltosi(va_arg(param, long));
2071 case CURLOPT_KRBLEVEL:
2073 * A string that defines the kerberos security level.
2075 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
2076 va_arg(param, char *));
2077 data->set.krb = (data->set.str[STRING_KRB_LEVEL]) ? TRUE : FALSE;
2079 case CURLOPT_GSSAPI_DELEGATION:
2081 * GSS-API credential delegation
2083 data->set.gssapi_delegation = va_arg(param, long);
2085 case CURLOPT_SSL_VERIFYPEER:
2087 * Enable peer SSL verifying.
2089 data->set.ssl.primary.verifypeer = (0 != va_arg(param, long)) ?
2092 case CURLOPT_PROXY_SSL_VERIFYPEER:
2094 * Enable peer SSL verifying for proxy.
2096 data->set.proxy_ssl.primary.verifypeer =
2097 (0 != va_arg(param, long))?TRUE:FALSE;
2099 case CURLOPT_SSL_VERIFYHOST:
2101 * Enable verification of the host name in the peer certificate
2103 arg = va_arg(param, long);
2105 /* Obviously people are not reading documentation and too many thought
2106 this argument took a boolean when it wasn't and misused it. We thus ban
2107 1 as a sensible input and we warn about its use. Then we only have the
2108 2 action internally stored as TRUE. */
2111 failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
2112 return CURLE_BAD_FUNCTION_ARGUMENT;
2115 data->set.ssl.primary.verifyhost = (0 != arg) ? TRUE : FALSE;
2117 case CURLOPT_PROXY_SSL_VERIFYHOST:
2119 * Enable verification of the host name in the peer certificate for proxy
2121 arg = va_arg(param, long);
2123 /* Obviously people are not reading documentation and too many thought
2124 this argument took a boolean when it wasn't and misused it. We thus ban
2125 1 as a sensible input and we warn about its use. Then we only have the
2126 2 action internally stored as TRUE. */
2129 failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
2130 return CURLE_BAD_FUNCTION_ARGUMENT;
2133 data->set.proxy_ssl.primary.verifyhost = (0 != arg)?TRUE:FALSE;
2135 case CURLOPT_SSL_VERIFYSTATUS:
2137 * Enable certificate status verifying.
2139 if(!Curl_ssl_cert_status_request()) {
2140 result = CURLE_NOT_BUILT_IN;
2144 data->set.ssl.primary.verifystatus = (0 != va_arg(param, long)) ?
2147 case CURLOPT_SSL_CTX_FUNCTION:
2148 #ifdef have_curlssl_ssl_ctx
2150 * Set a SSL_CTX callback
2152 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
2154 result = CURLE_NOT_BUILT_IN;
2157 case CURLOPT_SSL_CTX_DATA:
2158 #ifdef have_curlssl_ssl_ctx
2160 * Set a SSL_CTX callback parameter pointer
2162 data->set.ssl.fsslctxp = va_arg(param, void *);
2164 result = CURLE_NOT_BUILT_IN;
2167 case CURLOPT_SSL_FALSESTART:
2169 * Enable TLS false start.
2171 if(!Curl_ssl_false_start()) {
2172 result = CURLE_NOT_BUILT_IN;
2176 data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE;
2178 case CURLOPT_CERTINFO:
2179 #ifdef have_curlssl_certinfo
2180 data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE;
2182 result = CURLE_NOT_BUILT_IN;
2185 case CURLOPT_PINNEDPUBLICKEY:
2186 #ifdef have_curlssl_pinnedpubkey /* only by supported backends */
2188 * Set pinned public key for SSL connection.
2189 * Specify file name of the public key in DER format.
2191 result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG],
2192 va_arg(param, char *));
2194 result = CURLE_NOT_BUILT_IN;
2197 case CURLOPT_PROXY_PINNEDPUBLICKEY:
2198 #ifdef have_curlssl_pinnedpubkey /* only by supported backends */
2200 * Set pinned public key for SSL connection.
2201 * Specify file name of the public key in DER format.
2203 result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY],
2204 va_arg(param, char *));
2206 result = CURLE_NOT_BUILT_IN;
2209 case CURLOPT_CAINFO:
2211 * Set CA info for SSL connection. Specify file name of the CA certificate
2213 result = setstropt(&data->set.str[STRING_SSL_CAFILE_ORIG],
2214 va_arg(param, char *));
2216 case CURLOPT_PROXY_CAINFO:
2218 * Set CA info SSL connection for proxy. Specify file name of the
2221 result = setstropt(&data->set.str[STRING_SSL_CAFILE_PROXY],
2222 va_arg(param, char *));
2224 case CURLOPT_CAPATH:
2225 #ifdef have_curlssl_ca_path /* not supported by all backends */
2227 * Set CA path info for SSL connection. Specify directory name of the CA
2228 * certificates which have been prepared using openssl c_rehash utility.
2230 /* This does not work on windows. */
2231 result = setstropt(&data->set.str[STRING_SSL_CAPATH_ORIG],
2232 va_arg(param, char *));
2234 result = CURLE_NOT_BUILT_IN;
2237 case CURLOPT_PROXY_CAPATH:
2238 #ifdef have_curlssl_ca_path /* not supported by all backends */
2240 * Set CA path info for SSL connection proxy. Specify directory name of the
2241 * CA certificates which have been prepared using openssl c_rehash utility.
2243 /* This does not work on windows. */
2244 result = setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY],
2245 va_arg(param, char *));
2247 result = CURLE_NOT_BUILT_IN;
2250 case CURLOPT_CRLFILE:
2252 * Set CRL file info for SSL connection. Specify file name of the CRL
2253 * to check certificates revocation
2255 result = setstropt(&data->set.str[STRING_SSL_CRLFILE_ORIG],
2256 va_arg(param, char *));
2258 case CURLOPT_PROXY_CRLFILE:
2260 * Set CRL file info for SSL connection for proxy. Specify file name of the
2261 * CRL to check certificates revocation
2263 result = setstropt(&data->set.str[STRING_SSL_CRLFILE_PROXY],
2264 va_arg(param, char *));
2266 case CURLOPT_ISSUERCERT:
2268 * Set Issuer certificate file
2269 * to check certificates issuer
2271 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT_ORIG],
2272 va_arg(param, char *));
2274 case CURLOPT_TELNETOPTIONS:
2276 * Set a linked list of telnet options
2278 data->set.telnet_options = va_arg(param, struct curl_slist *);
2281 case CURLOPT_BUFFERSIZE:
2283 * The application kindly asks for a differently sized receive buffer.
2284 * If it seems reasonable, we'll use it.
2286 data->set.buffer_size = va_arg(param, long);
2288 if(data->set.buffer_size > MAX_BUFSIZE)
2289 data->set.buffer_size = MAX_BUFSIZE; /* huge internal default */
2290 else if(data->set.buffer_size < 1)
2291 data->set.buffer_size = BUFSIZE;
2293 /* Resize only if larger than default buffer size. */
2294 if(data->set.buffer_size > BUFSIZE) {
2295 data->state.buffer = realloc(data->state.buffer,
2296 data->set.buffer_size + 1);
2297 if(!data->state.buffer) {
2298 DEBUGF(fprintf(stderr, "Error: realloc of buffer failed\n"));
2299 result = CURLE_OUT_OF_MEMORY;
2305 case CURLOPT_NOSIGNAL:
2307 * The application asks not to set any signal() or alarm() handlers,
2308 * even when using a timeout.
2310 data->set.no_signal = (0 != va_arg(param, long)) ? TRUE : FALSE;
2315 struct Curl_share *set;
2316 set = va_arg(param, struct Curl_share *);
2318 /* disconnect from old share, if any */
2320 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2322 if(data->dns.hostcachetype == HCACHE_SHARED) {
2323 data->dns.hostcache = NULL;
2324 data->dns.hostcachetype = HCACHE_NONE;
2327 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2328 if(data->share->cookies == data->cookies)
2329 data->cookies = NULL;
2332 if(data->share->sslsession == data->state.session)
2333 data->state.session = NULL;
2335 data->share->dirty--;
2337 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2341 /* use new share if it set */
2345 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2347 data->share->dirty++;
2349 if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) {
2350 /* use shared host cache */
2351 data->dns.hostcache = &data->share->hostcache;
2352 data->dns.hostcachetype = HCACHE_SHARED;
2354 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2355 if(data->share->cookies) {
2356 /* use shared cookie list, first free own one if any */
2357 Curl_cookie_cleanup(data->cookies);
2358 /* enable cookies since we now use a share that uses cookies! */
2359 data->cookies = data->share->cookies;
2361 #endif /* CURL_DISABLE_HTTP */
2362 if(data->share->sslsession) {
2363 data->set.general_ssl.max_ssl_sessions = data->share->max_ssl_sessions;
2364 data->state.session = data->share->sslsession;
2366 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2369 /* check for host cache not needed,
2370 * it will be done by curl_easy_perform */
2374 case CURLOPT_PRIVATE:
2376 * Set private data pointer.
2378 data->set.private_data = va_arg(param, void *);
2381 case CURLOPT_MAXFILESIZE:
2383 * Set the maximum size of a file to download.
2385 data->set.max_filesize = va_arg(param, long);
2389 case CURLOPT_USE_SSL:
2391 * Make transfers attempt to use SSL/TLS.
2393 data->set.use_ssl = (curl_usessl)va_arg(param, long);
2396 case CURLOPT_SSL_OPTIONS:
2397 arg = va_arg(param, long);
2398 data->set.ssl.enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE;
2399 data->set.ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE);
2402 case CURLOPT_PROXY_SSL_OPTIONS:
2403 arg = va_arg(param, long);
2404 data->set.proxy_ssl.enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE;
2405 data->set.proxy_ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE);
2409 case CURLOPT_FTPSSLAUTH:
2411 * Set a specific auth for FTP-SSL transfers.
2413 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2416 case CURLOPT_IPRESOLVE:
2417 data->set.ipver = va_arg(param, long);
2420 case CURLOPT_MAXFILESIZE_LARGE:
2422 * Set the maximum size of a file to download.
2424 data->set.max_filesize = va_arg(param, curl_off_t);
2427 case CURLOPT_TCP_NODELAY:
2429 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2432 data->set.tcp_nodelay = (0 != va_arg(param, long)) ? TRUE : FALSE;
2435 case CURLOPT_FTP_ACCOUNT:
2436 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2437 va_arg(param, char *));
2440 case CURLOPT_IGNORE_CONTENT_LENGTH:
2441 data->set.ignorecl = (0 != va_arg(param, long)) ? TRUE : FALSE;
2444 case CURLOPT_CONNECT_ONLY:
2446 * No data transfer, set up connection and let application use the socket
2448 data->set.connect_only = (0 != va_arg(param, long)) ? TRUE : FALSE;
2451 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2452 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2453 va_arg(param, char *));
2456 case CURLOPT_SOCKOPTFUNCTION:
2458 * socket callback function: called after socket() but before connect()
2460 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2463 case CURLOPT_SOCKOPTDATA:
2465 * socket callback data pointer. Might be NULL.
2467 data->set.sockopt_client = va_arg(param, void *);
2470 case CURLOPT_OPENSOCKETFUNCTION:
2472 * open/create socket callback function: called instead of socket(),
2475 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2478 case CURLOPT_OPENSOCKETDATA:
2480 * socket callback data pointer. Might be NULL.
2482 data->set.opensocket_client = va_arg(param, void *);
2485 case CURLOPT_CLOSESOCKETFUNCTION:
2487 * close socket callback function: called instead of close()
2488 * when shutting down a connection
2490 data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
2493 case CURLOPT_CLOSESOCKETDATA:
2495 * socket callback data pointer. Might be NULL.
2497 data->set.closesocket_client = va_arg(param, void *);
2500 case CURLOPT_SSL_SESSIONID_CACHE:
2501 data->set.ssl.primary.sessionid = (0 != va_arg(param, long)) ?
2503 data->set.proxy_ssl.primary.sessionid = data->set.ssl.primary.sessionid;
2507 /* we only include SSH options if explicitly built to support SSH */
2508 case CURLOPT_SSH_AUTH_TYPES:
2509 data->set.ssh_auth_types = va_arg(param, long);
2512 case CURLOPT_SSH_PUBLIC_KEYFILE:
2514 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2516 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2517 va_arg(param, char *));
2520 case CURLOPT_SSH_PRIVATE_KEYFILE:
2522 * Use this file instead of the $HOME/.ssh/id_dsa file
2524 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2525 va_arg(param, char *));
2527 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2529 * Option to allow for the MD5 of the host public key to be checked
2530 * for validation purposes.
2532 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2533 va_arg(param, char *));
2535 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2536 case CURLOPT_SSH_KNOWNHOSTS:
2538 * Store the file name to read known hosts from.
2540 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2541 va_arg(param, char *));
2544 case CURLOPT_SSH_KEYFUNCTION:
2545 /* setting to NULL is fine since the ssh.c functions themselves will
2546 then rever to use the internal default */
2547 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2550 case CURLOPT_SSH_KEYDATA:
2552 * Custom client data to pass to the SSH keyfunc callback
2554 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2556 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2558 #endif /* USE_LIBSSH2 */
2560 case CURLOPT_HTTP_TRANSFER_DECODING:
2562 * disable libcurl transfer encoding is used
2564 data->set.http_te_skip = (0 == va_arg(param, long)) ? TRUE : FALSE;
2567 case CURLOPT_HTTP_CONTENT_DECODING:
2569 * raw data passed to the application when content encoding is used
2571 data->set.http_ce_skip = (0 == va_arg(param, long)) ? TRUE : FALSE;
2574 case CURLOPT_NEW_FILE_PERMS:
2576 * Uses these permissions instead of 0644
2578 data->set.new_file_perms = va_arg(param, long);
2581 case CURLOPT_NEW_DIRECTORY_PERMS:
2583 * Uses these permissions instead of 0755
2585 data->set.new_directory_perms = va_arg(param, long);
2588 case CURLOPT_ADDRESS_SCOPE:
2590 * We always get longs when passed plain numericals, but for this value we
2591 * know that an unsigned int will always hold the value so we blindly
2592 * typecast to this type
2594 data->set.scope_id = curlx_sltoui(va_arg(param, long));
2597 case CURLOPT_PROTOCOLS:
2598 /* set the bitmask for the protocols that are allowed to be used for the
2599 transfer, which thus helps the app which takes URLs from users or other
2600 external inputs and want to restrict what protocol(s) to deal
2601 with. Defaults to CURLPROTO_ALL. */
2602 data->set.allowed_protocols = va_arg(param, long);
2605 case CURLOPT_REDIR_PROTOCOLS:
2606 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2607 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2608 to be set in both bitmasks to be allowed to get redirected to. Defaults
2609 to all protocols except FILE and SCP. */
2610 data->set.redir_protocols = va_arg(param, long);
2613 case CURLOPT_DEFAULT_PROTOCOL:
2614 /* Set the protocol to use when the URL doesn't include any protocol */
2615 result = setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL],
2616 va_arg(param, char *));
2619 case CURLOPT_MAIL_FROM:
2620 /* Set the SMTP mail originator */
2621 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2622 va_arg(param, char *));
2625 case CURLOPT_MAIL_AUTH:
2626 /* Set the SMTP auth originator */
2627 result = setstropt(&data->set.str[STRING_MAIL_AUTH],
2628 va_arg(param, char *));
2631 case CURLOPT_MAIL_RCPT:
2632 /* Set the list of mail recipients */
2633 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2636 case CURLOPT_SASL_IR:
2637 /* Enable/disable SASL initial response */
2638 data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
2641 case CURLOPT_RTSP_REQUEST:
2644 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2645 * Would this be better if the RTSPREQ_* were just moved into here?
2647 long curl_rtspreq = va_arg(param, long);
2648 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2649 switch(curl_rtspreq) {
2650 case CURL_RTSPREQ_OPTIONS:
2651 rtspreq = RTSPREQ_OPTIONS;
2654 case CURL_RTSPREQ_DESCRIBE:
2655 rtspreq = RTSPREQ_DESCRIBE;
2658 case CURL_RTSPREQ_ANNOUNCE:
2659 rtspreq = RTSPREQ_ANNOUNCE;
2662 case CURL_RTSPREQ_SETUP:
2663 rtspreq = RTSPREQ_SETUP;
2666 case CURL_RTSPREQ_PLAY:
2667 rtspreq = RTSPREQ_PLAY;
2670 case CURL_RTSPREQ_PAUSE:
2671 rtspreq = RTSPREQ_PAUSE;
2674 case CURL_RTSPREQ_TEARDOWN:
2675 rtspreq = RTSPREQ_TEARDOWN;
2678 case CURL_RTSPREQ_GET_PARAMETER:
2679 rtspreq = RTSPREQ_GET_PARAMETER;
2682 case CURL_RTSPREQ_SET_PARAMETER:
2683 rtspreq = RTSPREQ_SET_PARAMETER;
2686 case CURL_RTSPREQ_RECORD:
2687 rtspreq = RTSPREQ_RECORD;
2690 case CURL_RTSPREQ_RECEIVE:
2691 rtspreq = RTSPREQ_RECEIVE;
2694 rtspreq = RTSPREQ_NONE;
2697 data->set.rtspreq = rtspreq;
2702 case CURLOPT_RTSP_SESSION_ID:
2704 * Set the RTSP Session ID manually. Useful if the application is
2705 * resuming a previously established RTSP session
2707 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2708 va_arg(param, char *));
2711 case CURLOPT_RTSP_STREAM_URI:
2713 * Set the Stream URI for the RTSP request. Unless the request is
2714 * for generic server options, the application will need to set this.
2716 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2717 va_arg(param, char *));
2720 case CURLOPT_RTSP_TRANSPORT:
2722 * The content of the Transport: header for the RTSP request
2724 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2725 va_arg(param, char *));
2728 case CURLOPT_RTSP_CLIENT_CSEQ:
2730 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2731 * application is resuming a previously broken connection. The CSEQ
2732 * will increment from this new number henceforth.
2734 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2737 case CURLOPT_RTSP_SERVER_CSEQ:
2738 /* Same as the above, but for server-initiated requests */
2739 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2742 case CURLOPT_INTERLEAVEDATA:
2743 data->set.rtp_out = va_arg(param, void *);
2745 case CURLOPT_INTERLEAVEFUNCTION:
2746 /* Set the user defined RTP write function */
2747 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2750 case CURLOPT_WILDCARDMATCH:
2751 data->set.wildcardmatch = (0 != va_arg(param, long)) ? TRUE : FALSE;
2753 case CURLOPT_CHUNK_BGN_FUNCTION:
2754 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2756 case CURLOPT_CHUNK_END_FUNCTION:
2757 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2759 case CURLOPT_FNMATCH_FUNCTION:
2760 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2762 case CURLOPT_CHUNK_DATA:
2763 data->wildcard.customptr = va_arg(param, void *);
2765 case CURLOPT_FNMATCH_DATA:
2766 data->set.fnmatch_data = va_arg(param, void *);
2769 case CURLOPT_TLSAUTH_USERNAME:
2770 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_ORIG],
2771 va_arg(param, char *));
2772 if(data->set.str[STRING_TLSAUTH_USERNAME_ORIG] && !data->set.ssl.authtype)
2773 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2775 case CURLOPT_PROXY_TLSAUTH_USERNAME:
2776 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_PROXY],
2777 va_arg(param, char *));
2778 if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] &&
2779 !data->set.proxy_ssl.authtype)
2780 data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2782 case CURLOPT_TLSAUTH_PASSWORD:
2783 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_ORIG],
2784 va_arg(param, char *));
2785 if(data->set.str[STRING_TLSAUTH_USERNAME_ORIG] && !data->set.ssl.authtype)
2786 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2788 case CURLOPT_PROXY_TLSAUTH_PASSWORD:
2789 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_PROXY],
2790 va_arg(param, char *));
2791 if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] &&
2792 !data->set.proxy_ssl.authtype)
2793 data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2795 case CURLOPT_TLSAUTH_TYPE:
2796 if(strncasecompare((char *)va_arg(param, char *), "SRP", strlen("SRP")))
2797 data->set.ssl.authtype = CURL_TLSAUTH_SRP;
2799 data->set.ssl.authtype = CURL_TLSAUTH_NONE;
2801 case CURLOPT_PROXY_TLSAUTH_TYPE:
2802 if(strncasecompare((char *)va_arg(param, char *), "SRP", strlen("SRP")))
2803 data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP;
2805 data->set.proxy_ssl.authtype = CURL_TLSAUTH_NONE;
2808 case CURLOPT_DNS_SERVERS:
2809 result = Curl_set_dns_servers(data, va_arg(param, char *));
2811 case CURLOPT_DNS_INTERFACE:
2812 result = Curl_set_dns_interface(data, va_arg(param, char *));
2814 case CURLOPT_DNS_LOCAL_IP4:
2815 result = Curl_set_dns_local_ip4(data, va_arg(param, char *));
2817 case CURLOPT_DNS_LOCAL_IP6:
2818 result = Curl_set_dns_local_ip6(data, va_arg(param, char *));
2821 case CURLOPT_TCP_KEEPALIVE:
2822 data->set.tcp_keepalive = (0 != va_arg(param, long)) ? TRUE : FALSE;
2824 case CURLOPT_TCP_KEEPIDLE:
2825 data->set.tcp_keepidle = va_arg(param, long);
2827 case CURLOPT_TCP_KEEPINTVL:
2828 data->set.tcp_keepintvl = va_arg(param, long);
2830 case CURLOPT_TCP_FASTOPEN:
2831 #if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN)
2832 data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE;
2834 result = CURLE_NOT_BUILT_IN;
2837 case CURLOPT_SSL_ENABLE_NPN:
2838 data->set.ssl_enable_npn = (0 != va_arg(param, long)) ? TRUE : FALSE;
2840 case CURLOPT_SSL_ENABLE_ALPN:
2841 data->set.ssl_enable_alpn = (0 != va_arg(param, long)) ? TRUE : FALSE;
2844 #ifdef USE_UNIX_SOCKETS
2845 case CURLOPT_UNIX_SOCKET_PATH:
2846 data->set.abstract_unix_socket = FALSE;
2847 result = setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH],
2848 va_arg(param, char *));
2850 case CURLOPT_ABSTRACT_UNIX_SOCKET:
2851 data->set.abstract_unix_socket = TRUE;
2852 result = setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH],
2853 va_arg(param, char *));
2857 case CURLOPT_PATH_AS_IS:
2858 data->set.path_as_is = (0 != va_arg(param, long)) ? TRUE : FALSE;
2860 case CURLOPT_PIPEWAIT:
2861 data->set.pipewait = (0 != va_arg(param, long)) ? TRUE : FALSE;
2863 case CURLOPT_STREAM_WEIGHT:
2865 return CURLE_NOT_BUILT_IN;
2867 arg = va_arg(param, long);
2868 if((arg>=1) && (arg <= 256))
2869 data->set.stream_weight = (int)arg;
2872 case CURLOPT_STREAM_DEPENDS:
2873 case CURLOPT_STREAM_DEPENDS_E:
2876 return CURLE_NOT_BUILT_IN;
2878 struct Curl_easy *dep = va_arg(param, struct Curl_easy *);
2879 if(!dep || GOOD_EASY_HANDLE(dep)) {
2880 if(data->set.stream_depends_on) {
2881 Curl_http2_remove_child(data->set.stream_depends_on, data);
2883 Curl_http2_add_child(dep, data, (option == CURLOPT_STREAM_DEPENDS_E));
2888 case CURLOPT_CONNECT_TO:
2889 data->set.connect_to = va_arg(param, struct curl_slist *);
2892 /* unknown tag and its companion, just ignore: */
2893 result = CURLE_UNKNOWN_OPTION;
2900 #ifdef USE_RECV_BEFORE_SEND_WORKAROUND
2901 static void conn_reset_postponed_data(struct connectdata *conn, int num)
2903 struct postponed_data * const psnd = &(conn->postponed[num]);
2905 DEBUGASSERT(psnd->allocated_size > 0);
2906 DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
2907 DEBUGASSERT(psnd->recv_size ?
2908 (psnd->recv_processed < psnd->recv_size) :
2909 (psnd->recv_processed == 0));
2910 DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
2912 psnd->buffer = NULL;
2913 psnd->allocated_size = 0;
2914 psnd->recv_size = 0;
2915 psnd->recv_processed = 0;
2917 psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
2918 #endif /* DEBUGBUILD */
2921 DEBUGASSERT(psnd->allocated_size == 0);
2922 DEBUGASSERT(psnd->recv_size == 0);
2923 DEBUGASSERT(psnd->recv_processed == 0);
2924 DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
2928 static void conn_reset_all_postponed_data(struct connectdata *conn)
2930 conn_reset_postponed_data(conn, 0);
2931 conn_reset_postponed_data(conn, 1);
2933 #else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
2934 /* Use "do-nothing" macros instead of functions when workaround not used */
2935 #define conn_reset_postponed_data(c,n) do {} WHILE_FALSE
2936 #define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
2937 #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
2939 static void conn_free(struct connectdata *conn)
2944 /* possible left-overs from the async name resolvers */
2945 Curl_resolver_cancel(conn);
2947 /* close the SSL stuff before we close any sockets since they will/may
2948 write to the sockets */
2949 Curl_ssl_close(conn, FIRSTSOCKET);
2950 Curl_ssl_close(conn, SECONDARYSOCKET);
2952 /* close possibly still open sockets */
2953 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2954 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2955 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2956 Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
2957 if(CURL_SOCKET_BAD != conn->tempsock[0])
2958 Curl_closesocket(conn, conn->tempsock[0]);
2959 if(CURL_SOCKET_BAD != conn->tempsock[1])
2960 Curl_closesocket(conn, conn->tempsock[1]);
2962 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
2963 defined(NTLM_WB_ENABLED)
2964 Curl_ntlm_wb_cleanup(conn);
2967 Curl_safefree(conn->user);
2968 Curl_safefree(conn->passwd);
2969 Curl_safefree(conn->oauth_bearer);
2970 Curl_safefree(conn->options);
2971 Curl_safefree(conn->http_proxy.user);
2972 Curl_safefree(conn->socks_proxy.user);
2973 Curl_safefree(conn->http_proxy.passwd);
2974 Curl_safefree(conn->socks_proxy.passwd);
2975 Curl_safefree(conn->allocptr.proxyuserpwd);
2976 Curl_safefree(conn->allocptr.uagent);
2977 Curl_safefree(conn->allocptr.userpwd);
2978 Curl_safefree(conn->allocptr.accept_encoding);
2979 Curl_safefree(conn->allocptr.te);
2980 Curl_safefree(conn->allocptr.rangeline);
2981 Curl_safefree(conn->allocptr.ref);
2982 Curl_safefree(conn->allocptr.host);
2983 Curl_safefree(conn->allocptr.cookiehost);
2984 Curl_safefree(conn->allocptr.rtsp_transport);
2985 Curl_safefree(conn->trailer);
2986 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2987 Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
2988 Curl_safefree(conn->secondaryhostname);
2989 Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
2990 Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
2991 Curl_safefree(conn->master_buffer);
2993 conn_reset_all_postponed_data(conn);
2995 Curl_llist_destroy(conn->send_pipe, NULL);
2996 Curl_llist_destroy(conn->recv_pipe, NULL);
2998 conn->send_pipe = NULL;
2999 conn->recv_pipe = NULL;
3001 Curl_safefree(conn->localdev);
3002 Curl_free_primary_ssl_config(&conn->ssl_config);
3003 Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
3005 #ifdef USE_UNIX_SOCKETS
3006 Curl_safefree(conn->unix_domain_socket);
3009 free(conn); /* free all the connection oriented data */
3013 * Disconnects the given connection. Note the connection may not be the
3014 * primary connection, like when freeing room in the connection cache or
3015 * killing of a dead old connection.
3017 * This function MUST NOT reset state in the Curl_easy struct if that
3018 * isn't strictly bound to the life-time of *this* particular connection.
3022 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
3024 struct Curl_easy *data;
3026 return CURLE_OK; /* this is closed and fine already */
3030 DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
3035 * If this connection isn't marked to force-close, leave it open if there
3036 * are other users of it
3038 if(!conn->bits.close &&
3039 (conn->send_pipe->size + conn->recv_pipe->size)) {
3040 DEBUGF(infof(data, "Curl_disconnect, usecounter: %d\n",
3041 conn->send_pipe->size + conn->recv_pipe->size));
3045 if(conn->dns_entry != NULL) {
3046 Curl_resolv_unlock(data, conn->dns_entry);
3047 conn->dns_entry = NULL;
3050 Curl_hostcache_prune(data); /* kill old DNS cache entries */
3052 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
3053 /* Cleanup NTLM connection-related data */
3054 Curl_http_ntlm_cleanup(conn);
3057 if(conn->handler->disconnect)
3058 /* This is set if protocol-specific cleanups should be made */
3059 conn->handler->disconnect(conn, dead_connection);
3061 /* unlink ourselves! */
3062 infof(data, "Closing connection %ld\n", conn->connection_id);
3063 Curl_conncache_remove_conn(data->state.conn_cache, conn);
3065 free_fixed_hostname(&conn->host);
3066 free_fixed_hostname(&conn->conn_to_host);
3067 free_fixed_hostname(&conn->http_proxy.host);
3068 free_fixed_hostname(&conn->socks_proxy.host);
3070 Curl_ssl_close(conn, FIRSTSOCKET);
3072 /* Indicate to all handles on the pipe that we're dead */
3073 if(Curl_pipeline_wanted(data->multi, CURLPIPE_ANY)) {
3074 signalPipeClose(conn->send_pipe, TRUE);
3075 signalPipeClose(conn->recv_pipe, TRUE);
3084 * This function should return TRUE if the socket is to be assumed to
3085 * be dead. Most commonly this happens when the server has closed the
3086 * connection due to inactivity.
3088 static bool SocketIsDead(curl_socket_t sock)
3091 bool ret_val = TRUE;
3093 sval = SOCKET_READABLE(sock, 0);
3102 * IsPipeliningPossible() returns TRUE if the options set would allow
3103 * pipelining/multiplexing and the connection is using a HTTP protocol.
3105 static bool IsPipeliningPossible(const struct Curl_easy *handle,
3106 const struct connectdata *conn)
3108 /* If a HTTP protocol and pipelining is enabled */
3109 if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
3110 (!conn->bits.protoconnstart || !conn->bits.close)) {
3112 if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
3113 (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
3114 (handle->set.httpreq == HTTPREQ_GET ||
3115 handle->set.httpreq == HTTPREQ_HEAD))
3116 /* didn't ask for HTTP/1.0 and a GET or HEAD */
3119 if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
3120 (handle->set.httpversion >= CURL_HTTP_VERSION_2))
3127 int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
3128 struct curl_llist *pipeline)
3131 struct curl_llist_element *curr;
3133 curr = pipeline->head;
3135 if(curr->ptr == handle) {
3136 Curl_llist_remove(pipeline, curr, NULL);
3137 return 1; /* we removed a handle */
3146 #if 0 /* this code is saved here as it is useful for debugging purposes */
3147 static void Curl_printPipeline(struct curl_llist *pipeline)
3149 struct curl_llist_element *curr;
3151 curr = pipeline->head;
3153 struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
3154 infof(data, "Handle in pipeline: %s\n", data->state.path);
3160 static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
3162 struct curl_llist_element *curr = pipeline->head;
3164 return (struct Curl_easy *) curr->ptr;
3170 /* remove the specified connection from all (possible) pipelines and related
3172 void Curl_getoff_all_pipelines(struct Curl_easy *data,
3173 struct connectdata *conn)
3175 bool recv_head = (conn->readchannel_inuse &&
3176 Curl_recvpipe_head(data, conn));
3177 bool send_head = (conn->writechannel_inuse &&
3178 Curl_sendpipe_head(data, conn));
3180 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
3181 Curl_pipeline_leave_read(conn);
3182 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
3183 Curl_pipeline_leave_write(conn);
3186 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
3188 struct curl_llist_element *curr;
3193 curr = pipeline->head;
3195 struct curl_llist_element *next = curr->next;
3196 struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
3198 #ifdef DEBUGBUILD /* debug-only code */
3199 if(data->magic != CURLEASY_MAGIC_NUMBER) {
3201 infof(data, "signalPipeClose() found BAAD easy handle\n");
3206 data->state.pipe_broke = TRUE;
3207 Curl_multi_handlePipeBreak(data);
3208 Curl_llist_remove(pipeline, curr, NULL);
3214 * This function finds the connection in the connection
3215 * cache that has been unused for the longest time.
3217 * Returns the pointer to the oldest idle connection, or NULL if none was
3220 struct connectdata *
3221 Curl_oldest_idle_connection(struct Curl_easy *data)
3223 struct conncache *bc = data->state.conn_cache;
3224 struct curl_hash_iterator iter;
3225 struct curl_llist_element *curr;
3226 struct curl_hash_element *he;
3227 time_t highscore=-1;
3230 struct connectdata *conn_candidate = NULL;
3231 struct connectbundle *bundle;
3235 Curl_hash_start_iterate(&bc->hash, &iter);
3237 he = Curl_hash_next_element(&iter);
3239 struct connectdata *conn;
3243 curr = bundle->conn_list->head;
3248 /* Set higher score for the age passed since the connection was used */
3249 score = Curl_tvdiff(now, conn->now);
3251 if(score > highscore) {
3253 conn_candidate = conn;
3259 he = Curl_hash_next_element(&iter);
3262 return conn_candidate;
3266 proxy_info_matches(const struct proxy_info* data,
3267 const struct proxy_info* needle)
3269 if((data->proxytype == needle->proxytype) &&
3270 (data->port == needle->port) &&
3271 Curl_safe_strcasecompare(data->host.name, needle->host.name) &&
3272 Curl_safe_strcasecompare(data->user, needle->user) &&
3273 Curl_safe_strcasecompare(data->passwd, needle->passwd))
3281 * This function finds the connection in the connection
3282 * bundle that has been unused for the longest time.
3284 * Returns the pointer to the oldest idle connection, or NULL if none was
3287 static struct connectdata *
3288 find_oldest_idle_connection_in_bundle(struct Curl_easy *data,
3289 struct connectbundle *bundle)
3291 struct curl_llist_element *curr;
3292 time_t highscore=-1;
3295 struct connectdata *conn_candidate = NULL;
3296 struct connectdata *conn;
3302 curr = bundle->conn_list->head;
3307 /* Set higher score for the age passed since the connection was used */
3308 score = Curl_tvdiff(now, conn->now);
3310 if(score > highscore) {
3312 conn_candidate = conn;
3318 return conn_candidate;
3322 * This function checks if given connection is dead and disconnects if so.
3323 * (That also removes it from the connection cache.)
3325 * Returns TRUE if the connection actually was dead and disconnected.
3327 static bool disconnect_if_dead(struct connectdata *conn,
3328 struct Curl_easy *data)
3330 size_t pipeLen = conn->send_pipe->size + conn->recv_pipe->size;
3331 if(!pipeLen && !conn->inuse) {
3332 /* The check for a dead socket makes sense only if there are no
3333 handles in pipeline and the connection isn't already marked in
3336 if(conn->handler->protocol & CURLPROTO_RTSP)
3337 /* RTSP is a special case due to RTP interleaving */
3338 dead = Curl_rtsp_connisdead(conn);
3340 dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
3344 infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
3346 /* disconnect resources */
3347 Curl_disconnect(conn, /* dead_connection */TRUE);
3355 * Wrapper to use disconnect_if_dead() function in Curl_conncache_foreach()
3359 static int call_disconnect_if_dead(struct connectdata *conn,
3362 struct Curl_easy* data = (struct Curl_easy*)param;
3363 disconnect_if_dead(conn, data);
3364 return 0; /* continue iteration */
3368 * This function scans the connection cache for half-open/dead connections,
3369 * closes and removes them.
3370 * The cleanup is done at most once per second.
3372 static void prune_dead_connections(struct Curl_easy *data)
3374 struct timeval now = Curl_tvnow();
3375 time_t elapsed = Curl_tvdiff(now, data->state.conn_cache->last_cleanup);
3377 if(elapsed >= 1000L) {
3378 Curl_conncache_foreach(data->state.conn_cache, data,
3379 call_disconnect_if_dead);
3380 data->state.conn_cache->last_cleanup = now;
3385 static size_t max_pipeline_length(struct Curl_multi *multi)
3387 return multi ? multi->max_pipeline_length : 0;
3392 * Given one filled in connection struct (named needle), this function should
3393 * detect if there already is one that has all the significant details
3394 * exactly the same and thus should be used instead.
3396 * If there is a match, this function returns TRUE - and has marked the
3397 * connection as 'in-use'. It must later be called with ConnectionDone() to
3398 * return back to 'idle' (unused) state.
3400 * The force_reuse flag is set if the connection must be used, even if
3401 * the pipelining strategy wants to open a new connection instead of reusing.
3404 ConnectionExists(struct Curl_easy *data,
3405 struct connectdata *needle,
3406 struct connectdata **usethis,
3410 struct connectdata *check;
3411 struct connectdata *chosen = 0;
3412 bool foundPendingCandidate = FALSE;
3413 bool canPipeline = IsPipeliningPossible(data, needle);
3414 struct connectbundle *bundle;
3417 bool wantNTLMhttp = ((data->state.authhost.want &
3418 (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
3419 (needle->handler->protocol & PROTO_FAMILY_HTTP));
3420 bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
3421 ((data->state.authproxy.want &
3422 (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
3423 (needle->handler->protocol & PROTO_FAMILY_HTTP)));
3426 *force_reuse = FALSE;
3429 /* We can't pipe if the site is blacklisted */
3430 if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
3431 canPipeline = FALSE;
3434 /* Look up the bundle with all the connections to this
3436 bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
3438 /* Max pipe length is zero (unlimited) for multiplexed connections */
3439 size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
3440 max_pipeline_length(data->multi):0;
3441 size_t best_pipe_len = max_pipe_len;
3442 struct curl_llist_element *curr;
3444 infof(data, "Found bundle for host %s: %p [%s]\n",
3445 (needle->bits.conn_to_host ? needle->conn_to_host.name :
3446 needle->host.name), (void *)bundle,
3447 (bundle->multiuse == BUNDLE_PIPELINING ?
3449 (bundle->multiuse == BUNDLE_MULTIPLEX ?
3450 "can multiplex" : "serially")));
3452 /* We can't pipe if we don't know anything about the server */
3454 if(bundle->multiuse <= BUNDLE_UNKNOWN) {
3455 if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
3456 infof(data, "Server doesn't support multi-use yet, wait\n");
3458 return FALSE; /* no re-use */
3461 infof(data, "Server doesn't support multi-use (yet)\n");
3462 canPipeline = FALSE;
3464 if((bundle->multiuse == BUNDLE_PIPELINING) &&
3465 !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
3466 /* not asked for, switch off */
3467 infof(data, "Could pipeline, but not asked to!\n");
3468 canPipeline = FALSE;
3470 else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
3471 !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
3472 infof(data, "Could multiplex, but not asked to!\n");
3473 canPipeline = FALSE;
3477 curr = bundle->conn_list->head;
3483 * Note that if we use a HTTP proxy in normal mode (no tunneling), we
3484 * check connections to that proxy and not to the actual remote server.
3489 if(disconnect_if_dead(check, data))
3492 pipeLen = check->send_pipe->size + check->recv_pipe->size;
3495 if(check->bits.protoconnstart && check->bits.close)
3498 if(!check->bits.multiplex) {
3499 /* If not multiplexing, make sure the pipe has only GET requests */
3500 struct Curl_easy* sh = gethandleathead(check->send_pipe);
3501 struct Curl_easy* rh = gethandleathead(check->recv_pipe);
3503 if(!IsPipeliningPossible(sh, check))
3507 if(!IsPipeliningPossible(rh, check))
3514 /* can only happen within multi handles, and means that another easy
3515 handle is using this connection */
3519 if(Curl_resolver_asynch()) {
3520 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
3521 completed yet and until then we don't re-use this connection */
3522 if(!check->ip_addr_str[0]) {
3524 "Connection #%ld is still name resolving, can't reuse\n",
3525 check->connection_id);
3530 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
3531 check->bits.close) {
3532 if(!check->bits.close)
3533 foundPendingCandidate = TRUE;
3534 /* Don't pick a connection that hasn't connected yet or that is going
3536 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
3537 check->connection_id);
3539 if(check->recv_pipe->size > 0) {
3541 "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
3542 check->connection_id);
3549 #ifdef USE_UNIX_SOCKETS
3550 if(needle->unix_domain_socket) {
3551 if(!check->unix_domain_socket)
3553 if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
3555 if(needle->abstract_unix_socket != check->abstract_unix_socket)
3558 else if(check->unix_domain_socket)
3562 if((needle->handler->flags&PROTOPT_SSL) !=
3563 (check->handler->flags&PROTOPT_SSL))
3564 /* don't do mixed SSL and non-SSL connections */
3565 if(get_protocol_family(check->handler->protocol) !=
3566 needle->handler->protocol || !check->tls_upgraded)
3567 /* except protocols that have been upgraded via TLS */
3570 if(needle->bits.httpproxy != check->bits.httpproxy ||
3571 needle->bits.socksproxy != check->bits.socksproxy)
3574 if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy,
3575 &check->socks_proxy))
3578 if(needle->bits.conn_to_host != check->bits.conn_to_host)
3579 /* don't mix connections that use the "connect to host" feature and
3580 * connections that don't use this feature */
3583 if(needle->bits.conn_to_port != check->bits.conn_to_port)
3584 /* don't mix connections that use the "connect to port" feature and
3585 * connections that don't use this feature */
3588 if(needle->bits.httpproxy) {
3589 if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
3592 if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
3595 if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) {
3596 /* use https proxy */
3597 if(needle->handler->flags&PROTOPT_SSL) {
3598 /* use double layer ssl */
3599 if(!Curl_ssl_config_matches(&needle->proxy_ssl_config,
3600 &check->proxy_ssl_config))
3602 if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete)
3606 if(!Curl_ssl_config_matches(&needle->ssl_config,
3607 &check->ssl_config))
3609 if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete)
3615 if(!canPipeline && check->inuse)
3616 /* this request can't be pipelined but the checked connection is
3617 already in use so we skip it */
3620 if(needle->localdev || needle->localport) {
3621 /* If we are bound to a specific local end (IP+port), we must not
3622 re-use a random other one, although if we didn't ask for a
3623 particular one we can reuse one that was bound.
3625 This comparison is a bit rough and too strict. Since the input
3626 parameters can be specified in numerous ways and still end up the
3627 same it would take a lot of processing to make it really accurate.
3628 Instead, this matching will assume that re-uses of bound connections
3629 will most likely also re-use the exact same binding parameters and
3630 missing out a few edge cases shouldn't hurt anyone very much.
3632 if((check->localport != needle->localport) ||
3633 (check->localportrange != needle->localportrange) ||
3634 (needle->localdev &&
3635 (!check->localdev || strcmp(check->localdev, needle->localdev))))
3639 if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
3640 /* This protocol requires credentials per connection,
3641 so verify that we're using the same name and password as well */
3642 if(strcmp(needle->user, check->user) ||
3643 strcmp(needle->passwd, check->passwd)) {
3644 /* one of them was different */
3649 if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
3650 needle->bits.tunnel_proxy) {
3651 /* The requested connection does not use a HTTP proxy or it uses SSL or
3652 it is a non-SSL protocol tunneled or it is a non-SSL protocol which
3653 is allowed to be upgraded via TLS */
3655 if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
3656 (get_protocol_family(check->handler->protocol) ==
3657 needle->handler->protocol && check->tls_upgraded)) &&
3658 (!needle->bits.conn_to_host || strcasecompare(
3659 needle->conn_to_host.name, check->conn_to_host.name)) &&
3660 (!needle->bits.conn_to_port ||
3661 needle->conn_to_port == check->conn_to_port) &&
3662 strcasecompare(needle->host.name, check->host.name) &&
3663 needle->remote_port == check->remote_port) {
3664 /* The schemes match or the the protocol family is the same and the
3665 previous connection was TLS upgraded, and the hostname and host
3667 if(needle->handler->flags & PROTOPT_SSL) {
3668 /* This is a SSL connection so verify that we're using the same
3669 SSL options as well */
3670 if(!Curl_ssl_config_matches(&needle->ssl_config,
3671 &check->ssl_config)) {
3673 "Connection #%ld has different SSL parameters, "
3675 check->connection_id));
3678 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3679 foundPendingCandidate = TRUE;
3681 "Connection #%ld has not started SSL connect, "
3683 check->connection_id));
3691 /* The requested connection is using the same HTTP proxy in normal
3692 mode (no tunneling) */
3697 #if defined(USE_NTLM)
3698 /* If we are looking for an HTTP+NTLM connection, check if this is
3699 already authenticating with the right credentials. If not, keep
3700 looking so that we can reuse NTLM connections if
3701 possible. (Especially we must not reuse the same connection if
3702 partway through a handshake!) */
3704 if(strcmp(needle->user, check->user) ||
3705 strcmp(needle->passwd, check->passwd))
3708 else if(check->ntlm.state != NTLMSTATE_NONE) {
3709 /* Connection is using NTLM auth but we don't want NTLM */
3713 /* Same for Proxy NTLM authentication */
3714 if(wantProxyNTLMhttp) {
3715 /* Both check->http_proxy.user and check->http_proxy.passwd can be
3717 if(!check->http_proxy.user || !check->http_proxy.passwd)
3720 if(strcmp(needle->http_proxy.user, check->http_proxy.user) ||
3721 strcmp(needle->http_proxy.passwd, check->http_proxy.passwd))
3724 else if(check->proxyntlm.state != NTLMSTATE_NONE) {
3725 /* Proxy connection is using NTLM auth but we don't want NTLM */
3729 if(wantNTLMhttp || wantProxyNTLMhttp) {
3730 /* Credentials are already checked, we can use this connection */
3734 (check->ntlm.state != NTLMSTATE_NONE)) ||
3735 (wantProxyNTLMhttp &&
3736 (check->proxyntlm.state != NTLMSTATE_NONE))) {
3737 /* We must use this connection, no other */
3738 *force_reuse = TRUE;
3742 /* Continue look up for a better connection */
3747 /* We can pipeline if we want to. Let's continue looking for
3748 the optimal connection to use, i.e the shortest pipe that is not
3752 /* We have the optimal connection. Let's stop looking. */
3757 /* We can't use the connection if the pipe is full */
3758 if(max_pipe_len && (pipeLen >= max_pipe_len)) {
3759 infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
3763 /* If multiplexed, make sure we don't go over concurrency limit */
3764 if(check->bits.multiplex) {
3765 /* Multiplexed connections can only be HTTP/2 for now */
3766 struct http_conn *httpc = &check->proto.httpc;
3767 if(pipeLen >= httpc->settings.max_concurrent_streams) {
3768 infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
3774 /* We can't use the connection if the pipe is penalized */
3775 if(Curl_pipeline_penalized(data, check)) {
3776 infof(data, "Penalized, skip\n");
3781 if(pipeLen < best_pipe_len) {
3782 /* This connection has a shorter pipe so far. We'll pick this
3783 and continue searching */
3785 best_pipe_len = pipeLen;
3790 /* When not pipelining (== multiplexed), we have a match here! */
3792 infof(data, "Multiplexed connection found!\n");
3797 /* We have found a connection. Let's stop searching. */
3807 return TRUE; /* yes, we found one to use! */
3810 if(foundPendingCandidate && data->set.pipewait) {
3812 "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
3816 return FALSE; /* no matching connecting exists */
3819 /* after a TCP connection to the proxy has been verified, this function does
3820 the next magic step.
3822 Note: this function's sub-functions call failf()
3825 CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex)
3827 CURLcode result = CURLE_OK;
3829 if(conn->bits.socksproxy) {
3830 #ifndef CURL_DISABLE_PROXY
3831 /* for the secondary socket (FTP), use the "connect to host"
3832 * but ignore the "connect to port" (use the secondary port)
3834 const char * const host = conn->bits.httpproxy ?
3835 conn->http_proxy.host.name :
3836 conn->bits.conn_to_host ?
3837 conn->conn_to_host.name :
3838 sockindex == SECONDARYSOCKET ?
3839 conn->secondaryhostname : conn->host.name;
3840 const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port :
3841 sockindex == SECONDARYSOCKET ? conn->secondary_port :
3842 conn->bits.conn_to_port ? conn->conn_to_port :
3844 conn->bits.socksproxy_connecting = TRUE;
3845 switch(conn->socks_proxy.proxytype) {
3846 case CURLPROXY_SOCKS5:
3847 case CURLPROXY_SOCKS5_HOSTNAME:
3848 result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
3849 host, port, sockindex, conn);
3852 case CURLPROXY_SOCKS4:
3853 case CURLPROXY_SOCKS4A:
3854 result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
3859 failf(conn->data, "unknown proxytype option given");
3860 result = CURLE_COULDNT_CONNECT;
3861 } /* switch proxytype */
3862 conn->bits.socksproxy_connecting = FALSE;
3865 #endif /* CURL_DISABLE_PROXY */
3872 * verboseconnect() displays verbose information after a connect
3874 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3875 void Curl_verboseconnect(struct connectdata *conn)
3877 if(conn->data->set.verbose)
3878 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3879 conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
3880 conn->bits.httpproxy ? conn->http_proxy.host.dispname :
3881 conn->bits.conn_to_host ? conn->conn_to_host.dispname :
3882 conn->host.dispname,
3883 conn->ip_addr_str, conn->port, conn->connection_id);
3887 int Curl_protocol_getsock(struct connectdata *conn,
3888 curl_socket_t *socks,
3891 if(conn->handler->proto_getsock)
3892 return conn->handler->proto_getsock(conn, socks, numsocks);
3893 return GETSOCK_BLANK;
3896 int Curl_doing_getsock(struct connectdata *conn,
3897 curl_socket_t *socks,
3900 if(conn && conn->handler->doing_getsock)
3901 return conn->handler->doing_getsock(conn, socks, numsocks);
3902 return GETSOCK_BLANK;
3906 * We are doing protocol-specific connecting and this is being called over and
3907 * over from the multi interface until the connection phase is done on
3911 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3914 CURLcode result=CURLE_OK;
3916 if(conn && conn->handler->connecting) {
3918 result = conn->handler->connecting(conn, done);
3927 * We are DOING this is being called over and over from the multi interface
3928 * until the DOING phase is done on protocol layer.
3931 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3933 CURLcode result=CURLE_OK;
3935 if(conn && conn->handler->doing) {
3937 result = conn->handler->doing(conn, done);
3946 * We have discovered that the TCP connection has been successful, we can now
3947 * proceed with some action.
3950 CURLcode Curl_protocol_connect(struct connectdata *conn,
3951 bool *protocol_done)
3953 CURLcode result=CURLE_OK;
3955 *protocol_done = FALSE;
3957 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
3958 /* We already are connected, get back. This may happen when the connect
3959 worked fine in the first call, like when we connect to a local server
3960 or proxy. Note that we don't know if the protocol is actually done.
3962 Unless this protocol doesn't have any protocol-connect callback, as
3963 then we know we're done. */
3964 if(!conn->handler->connecting)
3965 *protocol_done = TRUE;
3970 if(!conn->bits.protoconnstart) {
3972 result = Curl_proxy_connect(conn, FIRSTSOCKET);
3976 if(CONNECT_FIRSTSOCKET_PROXY_SSL())
3977 /* wait for HTTPS proxy SSL initialization to complete */
3980 if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
3981 (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
3982 /* when using an HTTP tunnel proxy, await complete tunnel establishment
3983 before proceeding further. Return CURLE_OK so we'll be called again */
3986 if(conn->handler->connect_it) {
3987 /* is there a protocol-specific connect() procedure? */
3989 /* Call the protocol-specific connect function */
3990 result = conn->handler->connect_it(conn, protocol_done);
3993 *protocol_done = TRUE;
3995 /* it has started, possibly even completed but that knowledge isn't stored
3998 conn->bits.protoconnstart = TRUE;
4001 return result; /* pass back status */
4005 * Helpers for IDNA convertions.
4007 static bool is_ASCII_name(const char *hostname)
4009 const unsigned char *ch = (const unsigned char *)hostname;
4019 * Perform any necessary IDN conversion of hostname
4021 static void fix_hostname(struct connectdata *conn, struct hostname *host)
4024 struct Curl_easy *data = conn->data;
4029 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
4033 /* set the name we use to display the host name */
4034 host->dispname = host->name;
4036 len = strlen(host->name);
4037 if(len && (host->name[len-1] == '.'))
4038 /* strip off a single trailing dot if present, primarily for SNI but
4039 there's no use for it */
4040 host->name[len-1]=0;
4042 /* Check name for non-ASCII and convert hostname to ACE form if we can */
4043 if(!is_ASCII_name(host->name)) {
4045 if(idn2_check_version(IDN2_VERSION)) {
4046 char *ace_hostname = NULL;
4047 #if IDN2_VERSION_NUMBER >= 0x00140000
4048 /* IDN2_NFC_INPUT: Normalize input string using normalization form C.
4049 IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional
4051 int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL;
4053 int flags = IDN2_NFC_INPUT;
4055 int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags);
4057 host->encalloc = (char *)ace_hostname;
4058 /* change the name pointer to point to the encoded hostname */
4059 host->name = host->encalloc;
4062 infof(data, "Failed to convert %s to ACE; %s\n", host->name,
4065 #elif defined(USE_WIN32_IDN)
4066 char *ace_hostname = NULL;
4068 if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
4069 host->encalloc = ace_hostname;
4070 /* change the name pointer to point to the encoded hostname */
4071 host->name = host->encalloc;
4074 infof(data, "Failed to convert %s to ACE;\n", host->name);
4076 infof(data, "IDN support not present, can't parse Unicode domains\n");
4082 * Frees data allocated by fix_hostname()
4084 static void free_fixed_hostname(struct hostname *host)
4086 #if defined(USE_LIBIDN2)
4087 if(host->encalloc) {
4088 idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
4089 allocated by libidn */
4090 host->encalloc = NULL;
4092 #elif defined(USE_WIN32_IDN)
4093 free(host->encalloc); /* must be freed withidn_free() since this was
4094 allocated by curl_win32_idn_to_ascii */
4095 host->encalloc = NULL;
4101 static void llist_dtor(void *user, void *element)
4109 * Allocate and initialize a new connectdata object.
4111 static struct connectdata *allocate_conn(struct Curl_easy *data)
4113 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
4117 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
4118 already from start to avoid NULL
4119 situations and checks */
4121 /* and we setup a few fields in case we end up actually using this struct */
4123 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
4124 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
4125 conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
4126 conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
4127 conn->connection_id = -1; /* no ID */
4128 conn->port = -1; /* unknown at this point */
4129 conn->remote_port = -1; /* unknown at this point */
4130 #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
4131 conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
4132 conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
4133 #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
4135 /* Default protocol-independent behavior doesn't support persistent
4136 connections, so we set this to force-close. Protocols that support
4137 this need to set this to FALSE in their "curl_do" functions. */
4138 connclose(conn, "Default to force-close");
4140 /* Store creation time to help future close decision making */
4141 conn->created = Curl_tvnow();
4143 conn->data = data; /* Setup the association between this connection
4144 and the Curl_easy */
4146 conn->http_proxy.proxytype = data->set.proxytype;
4147 conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
4149 #ifdef CURL_DISABLE_PROXY
4151 conn->bits.proxy = FALSE;
4152 conn->bits.httpproxy = FALSE;
4153 conn->bits.socksproxy = FALSE;
4154 conn->bits.proxy_user_passwd = FALSE;
4155 conn->bits.tunnel_proxy = FALSE;
4157 #else /* CURL_DISABLE_PROXY */
4159 /* note that these two proxy bits are now just on what looks to be
4160 requested, they may be altered down the road */
4161 conn->bits.proxy = (data->set.str[STRING_PROXY] &&
4162 *data->set.str[STRING_PROXY]) ? TRUE : FALSE;
4163 conn->bits.httpproxy = (conn->bits.proxy &&
4164 (conn->http_proxy.proxytype == CURLPROXY_HTTP ||
4165 conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
4166 conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
4168 conn->bits.socksproxy = (conn->bits.proxy &&
4169 !conn->bits.httpproxy) ? TRUE : FALSE;
4171 if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
4172 conn->bits.proxy = TRUE;
4173 conn->bits.socksproxy = TRUE;
4176 conn->bits.proxy_user_passwd =
4177 (data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
4178 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
4180 #endif /* CURL_DISABLE_PROXY */
4182 conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
4183 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
4184 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
4186 conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
4187 conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
4188 conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost;
4189 conn->proxy_ssl_config.verifystatus =
4190 data->set.proxy_ssl.primary.verifystatus;
4191 conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
4192 conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
4194 conn->ip_version = data->set.ipver;
4196 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
4197 defined(NTLM_WB_ENABLED)
4198 conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
4199 conn->ntlm_auth_hlpr_pid = 0;
4200 conn->challenge_header = NULL;
4201 conn->response_header = NULL;
4204 if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
4205 !conn->master_buffer) {
4206 /* Allocate master_buffer to be used for HTTP/1 pipelining */
4207 conn->master_buffer = calloc(BUFSIZE, sizeof(char));
4208 if(!conn->master_buffer)
4212 /* Initialize the pipeline lists */
4213 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
4214 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
4215 if(!conn->send_pipe || !conn->recv_pipe)
4219 conn->data_prot = PROT_CLEAR;
4222 /* Store the local bind parameters that will be used for this connection */
4223 if(data->set.str[STRING_DEVICE]) {
4224 conn->localdev = strdup(data->set.str[STRING_DEVICE]);
4228 conn->localportrange = data->set.localportrange;
4229 conn->localport = data->set.localport;
4231 /* the close socket stuff needs to be copied to the connection struct as
4232 it may live on without (this specific) Curl_easy */
4233 conn->fclosesocket = data->set.fclosesocket;
4234 conn->closesocket_client = data->set.closesocket_client;
4239 Curl_llist_destroy(conn->send_pipe, NULL);
4240 Curl_llist_destroy(conn->recv_pipe, NULL);
4242 conn->send_pipe = NULL;
4243 conn->recv_pipe = NULL;
4245 free(conn->master_buffer);
4246 free(conn->localdev);
4251 static CURLcode findprotocol(struct Curl_easy *data,
4252 struct connectdata *conn,
4253 const char *protostr)
4255 const struct Curl_handler * const *pp;
4256 const struct Curl_handler *p;
4258 /* Scan protocol handler table and match against 'protostr' to set a few
4259 variables based on the URL. Now that the handler may be changed later
4260 when the protocol specific setup function is called. */
4261 for(pp = protocols; (p = *pp) != NULL; pp++) {
4262 if(strcasecompare(p->scheme, protostr)) {
4263 /* Protocol found in table. Check if allowed */
4264 if(!(data->set.allowed_protocols & p->protocol))
4268 /* it is allowed for "normal" request, now do an extra check if this is
4269 the result of a redirect */
4270 if(data->state.this_is_a_follow &&
4271 !(data->set.redir_protocols & p->protocol))
4275 /* Perform setup complement if some. */
4276 conn->handler = conn->given = p;
4278 /* 'port' and 'remote_port' are set in setup_connection_internals() */
4284 /* The protocol was not found in the table, but we don't have to assign it
4285 to anything since it is already assigned to a dummy-struct in the
4286 create_conn() function when the connectdata struct is allocated. */
4287 failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
4290 return CURLE_UNSUPPORTED_PROTOCOL;
4294 * Parse URL and fill in the relevant members of the connection struct.
4296 static CURLcode parseurlandfillconn(struct Curl_easy *data,
4297 struct connectdata *conn,
4299 char **userp, char **passwdp,
4304 char *path = data->state.path;
4308 const char *protop = "";
4310 bool rebuild_url = FALSE;
4311 bool url_has_scheme = FALSE;
4314 *prot_missing = FALSE;
4316 /* We might pass the entire URL into the request so we need to make sure
4317 * there are no bad characters in there.*/
4318 if(strpbrk(data->change.url, "\r\n")) {
4319 failf(data, "Illegal characters found in URL");
4320 return CURLE_URL_MALFORMAT;
4323 /*************************************************************
4326 * We need to parse the url even when using the proxy, because we will need
4327 * the hostname and port in case we are trying to SSL connect through the
4328 * proxy -- and we don't know if we will need to use SSL until we parse the
4330 ************************************************************/
4331 if(data->change.url[0] == ':') {
4332 failf(data, "Bad URL, colon is first character");
4333 return CURLE_URL_MALFORMAT;
4336 /* Make sure we don't mistake a drive letter for a scheme, for example:
4337 curld --proto-default file c:/foo/bar.txt */
4338 if((('a' <= data->change.url[0] && data->change.url[0] <= 'z') ||
4339 ('A' <= data->change.url[0] && data->change.url[0] <= 'Z')) &&
4340 data->change.url[1] == ':' && data->set.str[STRING_DEFAULT_PROTOCOL] &&
4341 strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file")) {
4344 else { /* check for a scheme */
4345 for(i = 0; i < 16 && data->change.url[i]; ++i) {
4346 if(data->change.url[i] == '/')
4348 if(data->change.url[i] == ':') {
4349 url_has_scheme = TRUE;
4355 /* handle the file: scheme */
4356 if((url_has_scheme && strncasecompare(data->change.url, "file:", 5)) ||
4357 (!url_has_scheme && data->set.str[STRING_DEFAULT_PROTOCOL] &&
4358 strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file"))) {
4359 bool path_has_drive = FALSE;
4362 rc = sscanf(data->change.url, "%*15[^\n/:]:%[^\n]", path);
4364 rc = sscanf(data->change.url, "%[^\n]", path);
4367 failf(data, "Bad URL");
4368 return CURLE_URL_MALFORMAT;
4371 if(url_has_scheme && path[0] == '/' && path[1] == '/') {
4372 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
4373 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
4374 * file://localhost/<path> is similar to how other schemes treat missing
4375 * hostnames. See RFC 1808. */
4377 /* This cannot be done with strcpy() in a portable manner, since the
4378 memory areas overlap! */
4379 memmove(path, path + 2, strlen(path + 2)+1);
4382 /* the path may start with a drive letter. for backwards compatibility
4383 we skip some processing on those paths. */
4384 path_has_drive = (('a' <= path[0] && path[0] <= 'z') ||
4385 ('A' <= path[0] && path[0] <= 'Z')) && path[1] == ':';
4388 * we deal with file://<host>/<path> differently since it supports no
4389 * hostname other than "localhost" and "127.0.0.1", which is unique among
4390 * the URL protocols specified in RFC 1738
4392 if(path[0] != '/' && !path_has_drive) {
4393 /* the URL includes a host name, it must match "localhost" or
4394 "127.0.0.1" to be valid */
4396 if(!checkprefix("localhost/", path) &&
4397 !checkprefix("127.0.0.1/", path)) {
4398 failf(data, "Invalid file://hostname/, "
4399 "expected localhost or 127.0.0.1 or none");
4400 return CURLE_URL_MALFORMAT;
4402 ptr = &path[9]; /* now points to the slash after the host */
4404 /* there was a host name and slash present
4406 RFC1738 (section 3.1, page 5) says:
4408 The rest of the locator consists of data specific to the scheme,
4409 and is known as the "url-path". It supplies the details of how the
4410 specified resource can be accessed. Note that the "/" between the
4411 host (or port) and the url-path is NOT part of the url-path.
4413 As most agents use file://localhost/foo to get '/foo' although the
4414 slash preceding foo is a separator and not a slash for the path,
4415 a URL as file://localhost//foo must be valid as well, to refer to
4416 the same file with an absolute path.
4420 /* if there was two slashes, we skip the first one as that is then
4421 used truly as a separator */
4424 /* This cannot be made with strcpy, as the memory chunks overlap! */
4425 memmove(path, ptr, strlen(ptr)+1);
4427 path_has_drive = (('a' <= path[0] && path[0] <= 'z') ||
4428 ('A' <= path[0] && path[0] <= 'Z')) && path[1] == ':';
4431 #if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
4432 if(path_has_drive) {
4433 failf(data, "File drive letters are only accepted in MSDOS/Windows.");
4434 return CURLE_URL_MALFORMAT;
4438 protop = "file"; /* protocol string */
4439 *prot_missing = !url_has_scheme;
4446 rc = sscanf(data->change.url,
4447 "%15[^\n/:]:%3[/]%[^\n/?#]%[^\n]",
4448 protobuf, slashbuf, conn->host.name, path);
4450 failf(data, "Bad URL");
4451 return CURLE_URL_MALFORMAT;
4456 * The URL was badly formatted, let's try the browser-style _without_
4457 * protocol specified like 'http://'.
4459 rc = sscanf(data->change.url, "%[^\n/?#]%[^\n]", conn->host.name, path);
4462 * We couldn't even get this format.
4463 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
4464 * assigned, but the return value is EOF!
4466 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
4467 if(!(rc == -1 && *conn->host.name))
4470 failf(data, "<url> malformed");
4471 return CURLE_URL_MALFORMAT;
4476 * Since there was no protocol part specified in the URL use the
4477 * user-specified default protocol. If we weren't given a default make a
4478 * guess by matching some protocols against the host's outermost
4479 * sub-domain name. Finally if there was no match use HTTP.
4482 protop = data->set.str[STRING_DEFAULT_PROTOCOL];
4484 /* Note: if you add a new protocol, please update the list in
4485 * lib/version.c too! */
4486 if(checkprefix("FTP.", conn->host.name))
4488 else if(checkprefix("DICT.", conn->host.name))
4490 else if(checkprefix("LDAP.", conn->host.name))
4492 else if(checkprefix("IMAP.", conn->host.name))
4494 else if(checkprefix("SMTP.", conn->host.name))
4496 else if(checkprefix("POP3.", conn->host.name))
4502 *prot_missing = TRUE; /* not given in URL */
4505 size_t s = strlen(slashbuf);
4508 infof(data, "Unwillingly accepted illegal URL using %d slash%s!\n",
4511 if(data->change.url_alloc)
4512 free(data->change.url);
4513 /* repair the URL to use two slashes */
4514 data->change.url = aprintf("%s://%s%s",
4515 protobuf, conn->host.name, path);
4516 if(!data->change.url)
4517 return CURLE_OUT_OF_MEMORY;
4518 data->change.url_alloc = TRUE;
4523 /* We search for '?' in the host name (but only on the right side of a
4524 * @-letter to allow ?-letters in username and password) to handle things
4525 * like http://example.com?param= (notice the missing '/').
4527 at = strchr(conn->host.name, '@');
4529 query = strchr(at+1, '?');
4531 query = strchr(conn->host.name, '?');
4534 /* We must insert a slash before the '?'-letter in the URL. If the URL had
4535 a slash after the '?', that is where the path currently begins and the
4536 '?string' is still part of the host name.
4538 We must move the trailing part from the host name and put it first in
4539 the path. And have it all prefixed with a slash.
4542 size_t hostlen = strlen(query);
4543 size_t pathlen = strlen(path);
4545 /* move the existing path plus the zero byte forward, to make room for
4546 the host-name part */
4547 memmove(path+hostlen+1, path, pathlen+1);
4549 /* now copy the trailing host part in front of the existing path */
4550 memcpy(path+1, query, hostlen);
4552 path[0]='/'; /* prepend the missing slash */
4555 *query=0; /* now cut off the hostname at the ? */
4558 /* if there's no path set, use a single slash */
4563 /* If the URL is malformatted (missing a '/' after hostname before path) we
4564 * insert a slash here. The only letters except '/' that can start a path is
4565 * '?' and '#' - as controlled by the two sscanf() patterns above.
4567 if(path[0] != '/') {
4568 /* We need this function to deal with overlapping memory areas. We know
4569 that the memory area 'path' points to is 'urllen' bytes big and that
4570 is bigger than the path. Use +1 to move the zero byte too. */
4571 memmove(&path[1], path, strlen(path)+1);
4575 else if(!data->set.path_as_is) {
4576 /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
4577 char *newp = Curl_dedotdotify(path);
4579 return CURLE_OUT_OF_MEMORY;
4581 if(strcmp(newp, path)) {
4583 free(data->state.pathbuffer);
4584 data->state.pathbuffer = newp;
4585 data->state.path = newp;
4593 * "rebuild_url" means that one or more URL components have been modified so
4594 * we need to generate an updated full version. We need the corrected URL
4595 * when communicating over HTTP proxy and we don't know at this point if
4596 * we're using a proxy or not.
4601 size_t plen = strlen(path); /* new path, should be 1 byte longer than
4603 size_t prefixlen = strlen(conn->host.name);
4605 if(!*prot_missing) {
4606 size_t protolen = strlen(protop);
4608 if(curl_strnequal(protop, data->change.url, protolen))
4609 prefixlen += protolen;
4611 failf(data, "<url> malformed");
4612 return CURLE_URL_MALFORMAT;
4615 if(curl_strnequal("://", &data->change.url[protolen], 3))
4617 /* only file: is allowed to omit one or both slashes */
4618 else if(curl_strnequal("file:", data->change.url, 5))
4619 prefixlen += 1 + (data->change.url[5] == '/');
4621 failf(data, "<url> malformed");
4622 return CURLE_URL_MALFORMAT;
4626 reurl = malloc(prefixlen + plen + 1);
4628 return CURLE_OUT_OF_MEMORY;
4630 /* copy the prefix */
4631 memcpy(reurl, data->change.url, prefixlen);
4633 /* append the trailing piece + zerobyte */
4634 memcpy(&reurl[prefixlen], path, plen + 1);
4636 /* possible free the old one */
4637 if(data->change.url_alloc) {
4638 Curl_safefree(data->change.url);
4639 data->change.url_alloc = FALSE;
4642 infof(data, "Rebuilt URL to: %s\n", reurl);
4644 data->change.url = reurl;
4645 data->change.url_alloc = TRUE; /* free this later */
4648 result = findprotocol(data, conn, protop);
4653 * Parse the login details from the URL and strip them out of
4656 result = parse_url_login(data, conn, userp, passwdp, optionsp);
4660 if(conn->host.name[0] == '[') {
4661 /* This looks like an IPv6 address literal. See if there is an address
4662 scope if there is no location header */
4663 char *percent = strchr(conn->host.name, '%');
4665 unsigned int identifier_offset = 3;
4667 unsigned long scope;
4668 if(strncmp("%25", percent, 3) != 0) {
4670 "Please URL encode %% as %%25, see RFC 6874.\n");
4671 identifier_offset = 1;
4673 scope = strtoul(percent + identifier_offset, &endp, 10);
4675 /* The address scope was well formed. Knock it out of the
4677 memmove(percent, endp, strlen(endp)+1);
4678 conn->scope_id = (unsigned int)scope;
4681 /* Zone identifier is not numeric */
4682 #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
4683 char ifname[IFNAMSIZ + 2];
4684 char *square_bracket;
4685 unsigned int scopeidx = 0;
4686 strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
4687 /* Ensure nullbyte termination */
4688 ifname[IFNAMSIZ + 1] = '\0';
4689 square_bracket = strchr(ifname, ']');
4690 if(square_bracket) {
4692 *square_bracket = '\0';
4693 scopeidx = if_nametoindex(ifname);
4695 infof(data, "Invalid network interface: %s; %s\n", ifname,
4700 char *p = percent + identifier_offset + strlen(ifname);
4702 /* Remove zone identifier from hostname */
4703 memmove(percent, p, strlen(p) + 1);
4704 conn->scope_id = scopeidx;
4707 #endif /* HAVE_NET_IF_H && IFNAMSIZ */
4708 infof(data, "Invalid IPv6 address format\n");
4713 if(data->set.scope_id)
4714 /* Override any scope that was set above. */
4715 conn->scope_id = data->set.scope_id;
4717 /* Remove the fragment part of the path. Per RFC 2396, this is always the
4718 last part of the URI. We are looking for the first '#' so that we deal
4719 gracefully with non conformant URI such as http://example.com#foo#bar. */
4720 fragment = strchr(path, '#');
4724 /* we know the path part ended with a fragment, so we know the full URL
4725 string does too and we need to cut it off from there so it isn't used
4727 fragment = strchr(data->change.url, '#');
4733 * So if the URL was A://B/C#D,
4735 * conn->host.name is B
4736 * data->state.path is /C
4742 * If we're doing a resumed transfer, we need to setup our stuff
4745 static CURLcode setup_range(struct Curl_easy *data)
4747 struct UrlState *s = &data->state;
4748 s->resume_from = data->set.set_resume_from;
4749 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
4750 if(s->rangestringalloc)
4754 s->range = aprintf("%" CURL_FORMAT_CURL_OFF_TU "-", s->resume_from);
4756 s->range = strdup(data->set.str[STRING_SET_RANGE]);
4758 s->rangestringalloc = (s->range) ? TRUE : FALSE;
4761 return CURLE_OUT_OF_MEMORY;
4763 /* tell ourselves to fetch this range */
4764 s->use_range = TRUE; /* enable range download */
4767 s->use_range = FALSE; /* disable range download */
4774 * setup_connection_internals() -
4776 * Setup connection internals specific to the requested protocol in the
4777 * Curl_easy. This is inited and setup before the connection is made but
4778 * is about the particular protocol that is to be used.
4780 * This MUST get called after proxy magic has been figured out.
4782 static CURLcode setup_connection_internals(struct connectdata *conn)
4784 const struct Curl_handler * p;
4786 struct Curl_easy *data = conn->data;
4788 /* in some case in the multi state-machine, we go back to the CONNECT state
4789 and then a second (or third or...) call to this function will be made
4790 without doing a DISCONNECT or DONE in between (since the connection is
4791 yet in place) and therefore this function needs to first make sure
4792 there's no lingering previous data allocated. */
4793 Curl_free_request_state(data);
4795 memset(&data->req, 0, sizeof(struct SingleRequest));
4796 data->req.maxdownload = -1;
4798 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
4800 /* Perform setup complement if some. */
4803 if(p->setup_connection) {
4804 result = (*p->setup_connection)(conn);
4809 p = conn->handler; /* May have changed. */
4813 /* we check for -1 here since if proxy was detected already, this
4814 was very likely already set to the proxy port */
4815 conn->port = p->defport;
4821 * Curl_free_request_state() should free temp data that was allocated in the
4822 * Curl_easy for this single request.
4825 void Curl_free_request_state(struct Curl_easy *data)
4827 Curl_safefree(data->req.protop);
4828 Curl_safefree(data->req.newurl);
4832 #ifndef CURL_DISABLE_PROXY
4833 /****************************************************************
4834 * Checks if the host is in the noproxy list. returns true if it matches
4835 * and therefore the proxy should NOT be used.
4836 ****************************************************************/
4837 static bool check_noproxy(const char *name, const char *no_proxy)
4839 /* no_proxy=domain1.dom,host.domain2.dom
4840 * (a comma-separated list of hosts which should
4841 * not be proxied, or an asterisk to override
4842 * all proxy variables)
4846 const char *separator = ", ";
4847 size_t no_proxy_len;
4851 if(no_proxy && no_proxy[0]) {
4852 if(strcasecompare("*", no_proxy)) {
4856 /* NO_PROXY was specified and it wasn't just an asterisk */
4858 no_proxy_len = strlen(no_proxy);
4859 endptr = strchr(name, ':');
4861 namelen = endptr - name;
4863 namelen = strlen(name);
4865 for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
4866 while(tok_start < no_proxy_len &&
4867 strchr(separator, no_proxy[tok_start]) != NULL) {
4868 /* Look for the beginning of the token. */
4872 if(tok_start == no_proxy_len)
4873 break; /* It was all trailing separator chars, no more tokens. */
4875 for(tok_end = tok_start; tok_end < no_proxy_len &&
4876 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
4877 /* Look for the end of the token. */
4880 /* To match previous behaviour, where it was necessary to specify
4881 * ".local.com" to prevent matching "notlocal.com", we will leave
4884 if(no_proxy[tok_start] == '.')
4887 if((tok_end - tok_start) <= namelen) {
4888 /* Match the last part of the name to the domain we are checking. */
4889 const char *checkn = name + namelen - (tok_end - tok_start);
4890 if(strncasecompare(no_proxy + tok_start, checkn,
4891 tok_end - tok_start)) {
4892 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
4893 /* We either have an exact match, or the previous character is a .
4894 * so it is within the same domain, so no proxy for this host.
4899 } /* if((tok_end - tok_start) <= namelen) */
4900 } /* for(tok_start = 0; tok_start < no_proxy_len;
4901 tok_start = tok_end + 1) */
4902 } /* NO_PROXY was specified and it wasn't just an asterisk */
4907 /****************************************************************
4908 * Detect what (if any) proxy to use. Remember that this selects a host
4909 * name and is not limited to HTTP proxies only.
4910 * The returned pointer must be freed by the caller (unless NULL)
4911 ****************************************************************/
4912 static char *detect_proxy(struct connectdata *conn)
4916 /* If proxy was not specified, we check for default proxy environment
4917 * variables, to enable i.e Lynx compliance:
4919 * http_proxy=http://some.server.dom:port/
4920 * https_proxy=http://some.server.dom:port/
4921 * ftp_proxy=http://some.server.dom:port/
4922 * no_proxy=domain1.dom,host.domain2.dom
4923 * (a comma-separated list of hosts which should
4924 * not be proxied, or an asterisk to override
4925 * all proxy variables)
4926 * all_proxy=http://some.server.dom:port/
4927 * (seems to exist for the CERN www lib. Probably
4928 * the first to check for.)
4930 * For compatibility, the all-uppercase versions of these variables are
4931 * checked if the lowercase versions don't exist.
4933 char proxy_env[128];
4934 const char *protop = conn->handler->scheme;
4935 char *envp = proxy_env;
4938 /* Now, build <protocol>_proxy and check for such a one to use */
4940 *envp++ = (char)tolower((int)*protop++);
4943 strcpy(envp, "_proxy");
4945 /* read the protocol proxy: */
4946 prox=curl_getenv(proxy_env);
4949 * We don't try the uppercase version of HTTP_PROXY because of
4952 * When curl is used in a webserver application
4953 * environment (cgi or php), this environment variable can
4954 * be controlled by the web server user by setting the
4955 * http header 'Proxy:' to some value.
4957 * This can cause 'internal' http/ftp requests to be
4958 * arbitrarily redirected by any external attacker.
4960 if(!prox && !strcasecompare("http_proxy", proxy_env)) {
4961 /* There was no lowercase variable, try the uppercase version: */
4962 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4963 prox=curl_getenv(proxy_env);
4967 proxy = prox; /* use this */
4969 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4971 proxy=curl_getenv("ALL_PROXY");
4978 * If this is supposed to use a proxy, we need to figure out the proxy
4979 * host name, so that we can re-use an existing connection
4980 * that may exist registered to the same proxy host.
4982 static CURLcode parse_proxy(struct Curl_easy *data,
4983 struct connectdata *conn, char *proxy,
4984 curl_proxytype proxytype)
4989 /* We use 'proxyptr' to point to the proxy name from now on... */
4994 char *proxyuser = NULL;
4995 char *proxypasswd = NULL;
4998 /* We do the proxy host string parsing here. We want the host name and the
4999 * port name. Accept a protocol:// prefix
5002 /* Parse the protocol part if present */
5003 endofprot = strstr(proxy, "://");
5005 proxyptr = endofprot+3;
5006 if(checkprefix("https", proxy))
5007 proxytype = CURLPROXY_HTTPS;
5008 else if(checkprefix("socks5h", proxy))
5009 proxytype = CURLPROXY_SOCKS5_HOSTNAME;
5010 else if(checkprefix("socks5", proxy))
5011 proxytype = CURLPROXY_SOCKS5;
5012 else if(checkprefix("socks4a", proxy))
5013 proxytype = CURLPROXY_SOCKS4A;
5014 else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
5015 proxytype = CURLPROXY_SOCKS4;
5016 else if(checkprefix("http:", proxy))
5017 ; /* leave it as HTTP or HTTP/1.0 */
5019 /* Any other xxx:// reject! */
5020 failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
5021 return CURLE_COULDNT_CONNECT;
5025 proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
5027 #ifndef HTTPS_PROXY_SUPPORT
5028 if(proxytype == CURLPROXY_HTTPS) {
5029 failf(data, "Unsupported proxy \'%s\'"
5030 ", libcurl is built without the HTTPS-proxy support.", proxy);
5031 return CURLE_NOT_BUILT_IN;
5035 sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
5036 proxytype == CURLPROXY_SOCKS5 ||
5037 proxytype == CURLPROXY_SOCKS4A ||
5038 proxytype == CURLPROXY_SOCKS4;
5040 /* Is there a username and password given in this proxy url? */
5041 atsign = strchr(proxyptr, '@');
5044 parse_login_details(proxyptr, atsign - proxyptr,
5045 &proxyuser, &proxypasswd, NULL);
5048 proxyptr = atsign + 1;
5051 /* start scanning for port number at this point */
5054 /* detect and extract RFC6874-style IPv6-addresses */
5055 if(*proxyptr == '[') {
5056 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
5057 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
5060 /* There might be a zone identifier */
5061 if(strncmp("%25", ptr, 3))
5062 infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
5064 /* Allow unreserved characters as defined in RFC 3986 */
5065 while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
5066 (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
5070 /* yeps, it ended nicely with a bracket as well */
5073 infof(data, "Invalid IPv6 address format\n");
5075 /* Note that if this didn't end with a bracket, we still advanced the
5076 * proxyptr first, but I can't see anything wrong with that as no host
5077 * name nor a numeric can legally start with a bracket.
5081 /* Get port number off proxy.server.com:1080 */
5082 prox_portno = strchr(portptr, ':');
5086 *prox_portno = 0x0; /* cut off number from host name */
5088 /* now set the local port number */
5089 port = strtol(prox_portno, &endp, 10);
5090 if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
5091 (port < 0) || (port > 65535)) {
5092 /* meant to detect for example invalid IPv6 numerical addresses without
5093 brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
5094 because we then allow "URL style" with the number followed by a
5095 slash, used in curl test cases already. Space is also an acceptable
5096 terminating symbol. */
5097 infof(data, "No valid port number in proxy string (%s)\n",
5104 if(proxyptr[0]=='/')
5105 /* If the first character in the proxy string is a slash, fail
5106 immediately. The following code will otherwise clear the string which
5107 will lead to code running as if no proxy was set! */
5108 return CURLE_COULDNT_RESOLVE_PROXY;
5110 /* without a port number after the host name, some people seem to use
5111 a slash so we strip everything from the first slash */
5112 atsign = strchr(proxyptr, '/');
5114 *atsign = '\0'; /* cut off path part from host name */
5116 if(data->set.proxyport)
5117 /* None given in the proxy string, then get the default one if it is
5119 port = data->set.proxyport;
5121 if(proxytype == CURLPROXY_HTTPS)
5122 port = CURL_DEFAULT_HTTPS_PROXY_PORT;
5124 port = CURL_DEFAULT_PROXY_PORT;
5129 struct proxy_info *proxyinfo =
5130 sockstype ? &conn->socks_proxy : &conn->http_proxy;
5131 proxyinfo->proxytype = proxytype;
5134 /* found user and password, rip them out. note that we are unescaping
5135 them, as there is otherwise no way to have a username or password
5136 with reserved characters like ':' in them. */
5137 Curl_safefree(proxyinfo->user);
5138 proxyinfo->user = curl_easy_unescape(data, proxyuser, 0, NULL);
5140 if(!proxyinfo->user)
5141 return CURLE_OUT_OF_MEMORY;
5143 Curl_safefree(proxyinfo->passwd);
5144 if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
5145 proxyinfo->passwd = curl_easy_unescape(data, proxypasswd, 0, NULL);
5147 proxyinfo->passwd = strdup("");
5149 if(!proxyinfo->passwd)
5150 return CURLE_OUT_OF_MEMORY;
5152 conn->bits.proxy_user_passwd = TRUE; /* enable it */
5156 proxyinfo->port = port;
5157 if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
5161 /* now, clone the cleaned proxy host name */
5162 Curl_safefree(proxyinfo->host.rawalloc);
5163 proxyinfo->host.rawalloc = strdup(proxyptr);
5164 proxyinfo->host.name = proxyinfo->host.rawalloc;
5166 if(!proxyinfo->host.rawalloc)
5167 return CURLE_OUT_OF_MEMORY;
5170 Curl_safefree(proxyuser);
5171 Curl_safefree(proxypasswd);
5177 * Extract the user and password from the authentication string
5179 static CURLcode parse_proxy_auth(struct Curl_easy *data,
5180 struct connectdata *conn)
5182 char proxyuser[MAX_CURL_USER_LENGTH]="";
5183 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
5186 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
5187 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
5188 MAX_CURL_USER_LENGTH);
5189 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
5191 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
5192 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
5193 MAX_CURL_PASSWORD_LENGTH);
5194 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
5197 result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
5200 result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
5204 #endif /* CURL_DISABLE_PROXY */
5209 * Parse the login details (user name, password and options) from the URL and
5210 * strip them out of the host name
5212 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
5215 * Outputs: (almost :- all currently undefined)
5216 * conn->bits.user_passwd - non-zero if non-default passwords exist
5217 * user - non-zero length if defined
5218 * passwd - non-zero length if defined
5219 * options - non-zero length if defined
5220 * conn->host.name - remove user name and password
5222 static CURLcode parse_url_login(struct Curl_easy *data,
5223 struct connectdata *conn,
5224 char **user, char **passwd, char **options)
5226 CURLcode result = CURLE_OK;
5228 char *passwdp = NULL;
5229 char *optionsp = NULL;
5231 /* At this point, we're hoping all the other special cases have
5232 * been taken care of, so conn->host.name is at most
5233 * [user[:password][;options]]@]hostname
5235 * We need somewhere to put the embedded details, so do that first.
5238 char *ptr = strchr(conn->host.name, '@');
5239 char *login = conn->host.name;
5241 DEBUGASSERT(!**user);
5242 DEBUGASSERT(!**passwd);
5243 DEBUGASSERT(!**options);
5244 DEBUGASSERT(conn->handler);
5249 /* We will now try to extract the
5250 * possible login information in a string like:
5251 * ftp://user:password@ftp.my.site:8021/README */
5252 conn->host.name = ++ptr;
5254 /* So the hostname is sane. Only bother interpreting the
5255 * results if we could care. It could still be wasted
5256 * work because it might be overtaken by the programmatically
5257 * set user/passwd, but doing that first adds more cases here :-(
5260 if(data->set.use_netrc == CURL_NETRC_REQUIRED)
5263 /* We could use the login information in the URL so extract it. Only parse
5264 options if the handler says we should. */
5265 result = parse_login_details(login, ptr - login - 1,
5267 (conn->handler->flags & PROTOPT_URLOPTIONS)?
5275 /* We have a user in the URL */
5276 conn->bits.userpwd_in_url = TRUE;
5277 conn->bits.user_passwd = TRUE; /* enable user+password */
5279 /* Decode the user */
5280 result = Curl_urldecode(data, userp, 0, &newname, NULL, FALSE);
5290 /* We have a password in the URL so decode it */
5292 result = Curl_urldecode(data, passwdp, 0, &newpasswd, NULL, FALSE);
5298 *passwd = newpasswd;
5302 /* We have an options list in the URL so decode it */
5304 result = Curl_urldecode(data, optionsp, 0, &newoptions, NULL, FALSE);
5310 *options = newoptions;
5324 * parse_login_details()
5326 * This is used to parse a login string for user name, password and options in
5327 * the following formats:
5331 * user:password;options
5333 * user;options:password
5341 * login [in] - The login string.
5342 * len [in] - The length of the login string.
5343 * userp [in/out] - The address where a pointer to newly allocated memory
5344 * holding the user will be stored upon completion.
5345 * passdwp [in/out] - The address where a pointer to newly allocated memory
5346 * holding the password will be stored upon completion.
5347 * optionsp [in/out] - The address where a pointer to newly allocated memory
5348 * holding the options will be stored upon completion.
5350 * Returns CURLE_OK on success.
5352 static CURLcode parse_login_details(const char *login, const size_t len,
5353 char **userp, char **passwdp,
5356 CURLcode result = CURLE_OK;
5360 const char *psep = NULL;
5361 const char *osep = NULL;
5366 /* Attempt to find the password separator */
5368 psep = strchr(login, ':');
5370 /* Within the constraint of the login string */
5371 if(psep >= login + len)
5375 /* Attempt to find the options separator */
5377 osep = strchr(login, ';');
5379 /* Within the constraint of the login string */
5380 if(osep >= login + len)
5384 /* Calculate the portion lengths */
5386 (size_t)(osep && psep > osep ? osep - login : psep - login) :
5387 (osep ? (size_t)(osep - login) : len));
5389 (osep && osep > psep ? (size_t)(osep - psep) :
5390 (size_t)(login + len - psep)) - 1 : 0);
5392 (psep && psep > osep ? (size_t)(psep - osep) :
5393 (size_t)(login + len - osep)) - 1 : 0);
5395 /* Allocate the user portion buffer */
5397 ubuf = malloc(ulen + 1);
5399 result = CURLE_OUT_OF_MEMORY;
5402 /* Allocate the password portion buffer */
5403 if(!result && passwdp && plen) {
5404 pbuf = malloc(plen + 1);
5407 result = CURLE_OUT_OF_MEMORY;
5411 /* Allocate the options portion buffer */
5412 if(!result && optionsp && olen) {
5413 obuf = malloc(olen + 1);
5417 result = CURLE_OUT_OF_MEMORY;
5422 /* Store the user portion if necessary */
5424 memcpy(ubuf, login, ulen);
5426 Curl_safefree(*userp);
5430 /* Store the password portion if necessary */
5432 memcpy(pbuf, psep + 1, plen);
5434 Curl_safefree(*passwdp);
5438 /* Store the options portion if necessary */
5440 memcpy(obuf, osep + 1, olen);
5442 Curl_safefree(*optionsp);
5450 /*************************************************************
5451 * Figure out the remote port number and fix it in the URL
5453 * No matter if we use a proxy or not, we have to figure out the remote
5454 * port number of various reasons.
5456 * To be able to detect port number flawlessly, we must not confuse them
5457 * IPv6-specified addresses in the [0::1] style. (RFC2732)
5459 * The conn->host.name is currently [user:passwd@]host[:port] where host
5460 * could be a hostname, IPv4 address or IPv6 address.
5462 * The port number embedded in the URL is replaced, if necessary.
5463 *************************************************************/
5464 static CURLcode parse_remote_port(struct Curl_easy *data,
5465 struct connectdata *conn)
5470 /* Note that at this point, the IPv6 address cannot contain any scope
5471 suffix as that has already been removed in the parseurlandfillconn()
5473 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
5475 (']' == endbracket)) {
5476 /* this is a RFC2732-style specified IP-address */
5477 conn->bits.ipv6_ip = TRUE;
5479 conn->host.name++; /* skip over the starting bracket */
5480 portptr = strchr(conn->host.name, ']');
5482 *portptr++ = '\0'; /* zero terminate, killing the bracket */
5484 portptr = NULL; /* no port number available */
5489 struct in6_addr in6;
5490 if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
5491 /* This is a numerical IPv6 address, meaning this is a wrongly formatted
5493 failf(data, "IPv6 numerical address used in URL without brackets");
5494 return CURLE_URL_MALFORMAT;
5498 portptr = strrchr(conn->host.name, ':');
5501 if(data->set.use_port && data->state.allow_port) {
5502 /* if set, we use this and ignore the port possibly given in the URL */
5503 conn->remote_port = (unsigned short)data->set.use_port;
5505 *portptr = '\0'; /* cut off the name there anyway - if there was a port
5506 number - since the port number is to be ignored! */
5507 if(conn->bits.httpproxy) {
5508 /* we need to create new URL with the new port number */
5512 if(conn->bits.type_set)
5513 snprintf(type, sizeof(type), ";type=%c",
5514 data->set.prefer_ascii?'A':
5515 (data->set.ftp_list_only?'D':'I'));
5518 * This synthesized URL isn't always right--suffixes like ;type=A are
5519 * stripped off. It would be better to work directly from the original
5520 * URL and simply replace the port part of it.
5522 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
5523 conn->bits.ipv6_ip?"[":"", conn->host.name,
5524 conn->bits.ipv6_ip?"]":"", conn->remote_port,
5525 data->state.slash_removed?"/":"", data->state.path,
5528 return CURLE_OUT_OF_MEMORY;
5530 if(data->change.url_alloc) {
5531 Curl_safefree(data->change.url);
5532 data->change.url_alloc = FALSE;
5535 data->change.url = url;
5536 data->change.url_alloc = TRUE;
5540 /* no CURLOPT_PORT given, extract the one from the URL */
5545 port=strtol(portptr+1, &rest, 10); /* Port number must be decimal */
5547 if((port < 0) || (port > 0xffff)) {
5548 /* Single unix standard says port numbers are 16 bits long */
5549 failf(data, "Port number out of range");
5550 return CURLE_URL_MALFORMAT;
5553 else if(rest != &portptr[1]) {
5554 *portptr = '\0'; /* cut off the name there */
5555 conn->remote_port = curlx_ultous(port);
5559 failf(data, "Illegal port number");
5560 return CURLE_URL_MALFORMAT;
5562 /* Browser behavior adaptation. If there's a colon with no digits after,
5563 just cut off the name there which makes us ignore the colon and just
5564 use the default port. Firefox and Chrome both do that. */
5569 /* only if remote_port was not already parsed off the URL we use the
5570 default port number */
5571 if(conn->remote_port < 0)
5572 conn->remote_port = (unsigned short)conn->given->defport;
5578 * Override the login details from the URL with that in the CURLOPT_USERPWD
5579 * option or a .netrc file, if applicable.
5581 static CURLcode override_login(struct Curl_easy *data,
5582 struct connectdata *conn,
5583 char **userp, char **passwdp, char **optionsp)
5585 if(data->set.str[STRING_USERNAME]) {
5587 *userp = strdup(data->set.str[STRING_USERNAME]);
5589 return CURLE_OUT_OF_MEMORY;
5592 if(data->set.str[STRING_PASSWORD]) {
5594 *passwdp = strdup(data->set.str[STRING_PASSWORD]);
5596 return CURLE_OUT_OF_MEMORY;
5599 if(data->set.str[STRING_OPTIONS]) {
5601 *optionsp = strdup(data->set.str[STRING_OPTIONS]);
5603 return CURLE_OUT_OF_MEMORY;
5606 conn->bits.netrc = FALSE;
5607 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
5608 int ret = Curl_parsenetrc(conn->host.name,
5610 data->set.str[STRING_NETRC_FILE]);
5612 infof(data, "Couldn't find host %s in the "
5613 DOT_CHAR "netrc file; using defaults\n",
5617 return CURLE_OUT_OF_MEMORY;
5620 /* set bits.netrc TRUE to remember that we got the name from a .netrc
5621 file, so that it is safe to use even if we followed a Location: to a
5622 different host or similar. */
5623 conn->bits.netrc = TRUE;
5625 conn->bits.user_passwd = TRUE; /* enable user+password */
5633 * Set the login details so they're available in the connection
5635 static CURLcode set_login(struct connectdata *conn,
5636 const char *user, const char *passwd,
5637 const char *options)
5639 CURLcode result = CURLE_OK;
5641 /* If our protocol needs a password and we have none, use the defaults */
5642 if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
5643 /* Store the default user */
5644 conn->user = strdup(CURL_DEFAULT_USER);
5646 /* Store the default password */
5648 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
5650 conn->passwd = NULL;
5652 /* This is the default password, so DON'T set conn->bits.user_passwd */
5655 /* Store the user, zero-length if not set */
5656 conn->user = strdup(user);
5658 /* Store the password (only if user is present), zero-length if not set */
5660 conn->passwd = strdup(passwd);
5662 conn->passwd = NULL;
5665 if(!conn->user || !conn->passwd)
5666 result = CURLE_OUT_OF_MEMORY;
5668 /* Store the options, null if not set */
5669 if(!result && options[0]) {
5670 conn->options = strdup(options);
5673 result = CURLE_OUT_OF_MEMORY;
5680 * Parses a "host:port" string to connect to.
5681 * The hostname and the port may be empty; in this case, NULL is returned for
5682 * the hostname and -1 for the port.
5684 static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
5686 char **hostname_result,
5695 #if defined(CURL_DISABLE_VERBOSE_STRINGS)
5699 *hostname_result = NULL;
5705 host_dup = strdup(host);
5707 return CURLE_OUT_OF_MEMORY;
5711 /* start scanning for port number at this point */
5714 /* detect and extract RFC6874-style IPv6-addresses */
5715 if(*hostptr == '[') {
5716 char *ptr = ++hostptr; /* advance beyond the initial bracket */
5717 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
5720 /* There might be a zone identifier */
5721 if(strncmp("%25", ptr, 3))
5722 infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
5724 /* Allow unreserved characters as defined in RFC 3986 */
5725 while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
5726 (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
5730 /* yeps, it ended nicely with a bracket as well */
5733 infof(data, "Invalid IPv6 address format\n");
5735 /* Note that if this didn't end with a bracket, we still advanced the
5736 * hostptr first, but I can't see anything wrong with that as no host
5737 * name nor a numeric can legally start with a bracket.
5741 /* Get port number off server.com:1080 */
5742 host_portno = strchr(portptr, ':');
5745 *host_portno = '\0'; /* cut off number from host name */
5748 long portparse = strtol(host_portno, &endp, 10);
5749 if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
5750 infof(data, "No valid port number in connect to host string (%s)\n",
5756 port = (int)portparse; /* we know it will fit */
5760 /* now, clone the cleaned host name */
5762 *hostname_result = strdup(hostptr);
5763 if(!*hostname_result) {
5765 return CURLE_OUT_OF_MEMORY;
5769 *port_result = port;
5776 * Parses one "connect to" string in the form:
5777 * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
5779 static CURLcode parse_connect_to_string(struct Curl_easy *data,
5780 struct connectdata *conn,
5781 const char *conn_to_host,
5785 CURLcode result = CURLE_OK;
5786 const char *ptr = conn_to_host;
5787 int host_match = FALSE;
5788 int port_match = FALSE;
5790 *host_result = NULL;
5794 /* an empty hostname always matches */
5799 /* check whether the URL's hostname matches */
5800 size_t hostname_to_match_len;
5801 char *hostname_to_match = aprintf("%s%s%s",
5802 conn->bits.ipv6_ip ? "[" : "",
5804 conn->bits.ipv6_ip ? "]" : "");
5805 if(!hostname_to_match)
5806 return CURLE_OUT_OF_MEMORY;
5807 hostname_to_match_len = strlen(hostname_to_match);
5808 host_match = strncasecompare(ptr, hostname_to_match,
5809 hostname_to_match_len);
5810 free(hostname_to_match);
5811 ptr += hostname_to_match_len;
5813 host_match = host_match && *ptr == ':';
5819 /* an empty port always matches */
5824 /* check whether the URL's port matches */
5825 char *ptr_next = strchr(ptr, ':');
5828 long port_to_match = strtol(ptr, &endp, 10);
5829 if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
5837 if(host_match && port_match) {
5838 /* parse the hostname and port to connect to */
5839 result = parse_connect_to_host_port(data, ptr, host_result, port_result);
5846 * Processes all strings in the "connect to" slist, and uses the "connect
5847 * to host" and "connect to port" of the first string that matches.
5849 static CURLcode parse_connect_to_slist(struct Curl_easy *data,
5850 struct connectdata *conn,
5851 struct curl_slist *conn_to_host)
5853 CURLcode result = CURLE_OK;
5857 while(conn_to_host && !host && port == -1) {
5858 result = parse_connect_to_string(data, conn, conn_to_host->data,
5864 conn->conn_to_host.rawalloc = host;
5865 conn->conn_to_host.name = host;
5866 conn->bits.conn_to_host = TRUE;
5868 infof(data, "Connecting to hostname: %s\n", host);
5871 /* no "connect to host" */
5872 conn->bits.conn_to_host = FALSE;
5873 Curl_safefree(host);
5877 conn->conn_to_port = port;
5878 conn->bits.conn_to_port = TRUE;
5879 infof(data, "Connecting to port: %d\n", port);
5882 /* no "connect to port" */
5883 conn->bits.conn_to_port = FALSE;
5887 conn_to_host = conn_to_host->next;
5893 /*************************************************************
5894 * Resolve the address of the server or proxy
5895 *************************************************************/
5896 static CURLcode resolve_server(struct Curl_easy *data,
5897 struct connectdata *conn,
5900 CURLcode result=CURLE_OK;
5901 time_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
5903 /*************************************************************
5904 * Resolve the name of the server or proxy
5905 *************************************************************/
5906 if(conn->bits.reuse)
5907 /* We're reusing the connection - no need to resolve anything, and
5908 fix_hostname() was called already in create_conn() for the re-use
5913 /* this is a fresh connect */
5915 struct Curl_dns_entry *hostaddr;
5917 #ifdef USE_UNIX_SOCKETS
5918 if(conn->unix_domain_socket) {
5919 /* Unix domain sockets are local. The host gets ignored, just use the
5920 * specified domain socket address. Do not cache "DNS entries". There is
5921 * no DNS involved and we already have the filesystem path available */
5922 const char *path = conn->unix_domain_socket;
5924 hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
5926 result = CURLE_OUT_OF_MEMORY;
5928 bool longpath = FALSE;
5929 hostaddr->addr = Curl_unix2addr(path, &longpath,
5930 conn->abstract_unix_socket);
5934 /* Long paths are not supported for now */
5936 failf(data, "Unix socket path too long: '%s'", path);
5937 result = CURLE_COULDNT_RESOLVE_HOST;
5940 result = CURLE_OUT_OF_MEMORY;
5948 if(!conn->bits.proxy) {
5949 struct hostname *connhost;
5950 if(conn->bits.conn_to_host)
5951 connhost = &conn->conn_to_host;
5953 connhost = &conn->host;
5955 /* If not connecting via a proxy, extract the port from the URL, if it is
5956 * there, thus overriding any defaults that might have been set above. */
5957 if(conn->bits.conn_to_port)
5958 conn->port = conn->conn_to_port;
5960 conn->port = conn->remote_port;
5962 /* Resolve target host right on */
5963 rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
5964 &hostaddr, timeout_ms);
5965 if(rc == CURLRESOLV_PENDING)
5968 else if(rc == CURLRESOLV_TIMEDOUT)
5969 result = CURLE_OPERATION_TIMEDOUT;
5971 else if(!hostaddr) {
5972 failf(data, "Couldn't resolve host '%s'", connhost->dispname);
5973 result = CURLE_COULDNT_RESOLVE_HOST;
5974 /* don't return yet, we need to clean up the timeout first */
5978 /* This is a proxy that hasn't been resolved yet. */
5980 struct hostname * const host = conn->bits.socksproxy ?
5981 &conn->socks_proxy.host : &conn->http_proxy.host;
5984 rc = Curl_resolv_timeout(conn, host->name, (int)conn->port,
5985 &hostaddr, timeout_ms);
5987 if(rc == CURLRESOLV_PENDING)
5990 else if(rc == CURLRESOLV_TIMEDOUT)
5991 result = CURLE_OPERATION_TIMEDOUT;
5993 else if(!hostaddr) {
5994 failf(data, "Couldn't resolve proxy '%s'", host->dispname);
5995 result = CURLE_COULDNT_RESOLVE_PROXY;
5996 /* don't return yet, we need to clean up the timeout first */
5999 DEBUGASSERT(conn->dns_entry == NULL);
6000 conn->dns_entry = hostaddr;
6007 * Cleanup the connection just allocated before we can move along and use the
6008 * previously existing one. All relevant data is copied over and old_conn is
6009 * ready for freeing once this function returns.
6011 static void reuse_conn(struct connectdata *old_conn,
6012 struct connectdata *conn)
6014 free_fixed_hostname(&old_conn->http_proxy.host);
6015 free_fixed_hostname(&old_conn->socks_proxy.host);
6017 free(old_conn->http_proxy.host.rawalloc);
6018 free(old_conn->socks_proxy.host.rawalloc);
6020 /* free the SSL config struct from this connection struct as this was
6021 allocated in vain and is targeted for destruction */
6022 Curl_free_primary_ssl_config(&old_conn->ssl_config);
6023 Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
6025 conn->data = old_conn->data;
6027 /* get the user+password information from the old_conn struct since it may
6028 * be new for this request even when we re-use an existing connection */
6029 conn->bits.user_passwd = old_conn->bits.user_passwd;
6030 if(conn->bits.user_passwd) {
6031 /* use the new user name and password though */
6032 Curl_safefree(conn->user);
6033 Curl_safefree(conn->passwd);
6034 conn->user = old_conn->user;
6035 conn->passwd = old_conn->passwd;
6036 old_conn->user = NULL;
6037 old_conn->passwd = NULL;
6040 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
6041 if(conn->bits.proxy_user_passwd) {
6042 /* use the new proxy user name and proxy password though */
6043 Curl_safefree(conn->http_proxy.user);
6044 Curl_safefree(conn->socks_proxy.user);
6045 Curl_safefree(conn->http_proxy.passwd);
6046 Curl_safefree(conn->socks_proxy.passwd);
6047 conn->http_proxy.user = old_conn->http_proxy.user;
6048 conn->socks_proxy.user = old_conn->socks_proxy.user;
6049 conn->http_proxy.passwd = old_conn->http_proxy.passwd;
6050 conn->socks_proxy.passwd = old_conn->socks_proxy.passwd;
6051 old_conn->http_proxy.user = NULL;
6052 old_conn->socks_proxy.user = NULL;
6053 old_conn->http_proxy.passwd = NULL;
6054 old_conn->socks_proxy.passwd = NULL;
6057 /* host can change, when doing keepalive with a proxy or if the case is
6058 different this time etc */
6059 free_fixed_hostname(&conn->host);
6060 free_fixed_hostname(&conn->conn_to_host);
6061 Curl_safefree(conn->host.rawalloc);
6062 Curl_safefree(conn->conn_to_host.rawalloc);
6063 conn->host=old_conn->host;
6064 conn->bits.conn_to_host = old_conn->bits.conn_to_host;
6065 conn->conn_to_host = old_conn->conn_to_host;
6066 conn->bits.conn_to_port = old_conn->bits.conn_to_port;
6067 conn->conn_to_port = old_conn->conn_to_port;
6069 /* persist connection info in session handle */
6070 Curl_persistconninfo(conn);
6072 conn_reset_all_postponed_data(old_conn); /* free buffers */
6073 conn_reset_all_postponed_data(conn); /* reset unprocessed data */
6076 conn->bits.reuse = TRUE; /* yes, we're re-using here */
6078 Curl_safefree(old_conn->user);
6079 Curl_safefree(old_conn->passwd);
6080 Curl_safefree(old_conn->http_proxy.user);
6081 Curl_safefree(old_conn->socks_proxy.user);
6082 Curl_safefree(old_conn->http_proxy.passwd);
6083 Curl_safefree(old_conn->socks_proxy.passwd);
6084 Curl_safefree(old_conn->localdev);
6086 Curl_llist_destroy(old_conn->send_pipe, NULL);
6087 Curl_llist_destroy(old_conn->recv_pipe, NULL);
6089 old_conn->send_pipe = NULL;
6090 old_conn->recv_pipe = NULL;
6092 Curl_safefree(old_conn->master_buffer);
6094 #ifdef USE_UNIX_SOCKETS
6095 Curl_safefree(old_conn->unix_domain_socket);
6100 * create_conn() sets up a new connectdata struct, or re-uses an already
6101 * existing one, and resolves host name.
6103 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
6104 * response will be coming asynchronously. If *async is FALSE, the name is
6107 * @param data The sessionhandle pointer
6108 * @param in_connect is set to the next connection data pointer
6109 * @param async is set TRUE when an async DNS resolution is pending
6110 * @see Curl_setup_conn()
6112 * *NOTE* this function assigns the conn->data pointer!
6115 static CURLcode create_conn(struct Curl_easy *data,
6116 struct connectdata **in_connect,
6119 CURLcode result = CURLE_OK;
6120 struct connectdata *conn;
6121 struct connectdata *conn_temp = NULL;
6124 char *passwd = NULL;
6125 char *options = NULL;
6128 char *socksproxy = NULL;
6129 char *no_proxy = NULL;
6130 bool prot_missing = FALSE;
6131 bool connections_available = TRUE;
6132 bool force_reuse = FALSE;
6133 bool waitpipe = FALSE;
6134 size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
6135 size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
6139 /*************************************************************
6141 *************************************************************/
6143 if(!data->change.url) {
6144 result = CURLE_URL_MALFORMAT;
6148 /* First, split up the current URL in parts so that we can use the
6149 parts for checking against the already present connections. In order
6150 to not have to modify everything at once, we allocate a temporary
6151 connection data struct and fill in for comparison purposes. */
6152 conn = allocate_conn(data);
6155 result = CURLE_OUT_OF_MEMORY;
6159 /* We must set the return variable as soon as possible, so that our
6160 parent can cleanup any possible allocs we may have done before
6164 /* This initing continues below, see the comment "Continue connectdata
6165 * initialization here" */
6167 /***********************************************************
6168 * We need to allocate memory to store the path in. We get the size of the
6169 * full URL to be sure, and we need to make it at least 256 bytes since
6170 * other parts of the code will rely on this fact
6171 ***********************************************************/
6172 #define LEAST_PATH_ALLOC 256
6173 urllen=strlen(data->change.url);
6174 if(urllen < LEAST_PATH_ALLOC)
6175 urllen=LEAST_PATH_ALLOC;
6178 * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
6179 * 1 - an extra terminating zero
6180 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
6183 Curl_safefree(data->state.pathbuffer);
6184 data->state.path = NULL;
6186 data->state.pathbuffer = malloc(urllen+2);
6187 if(NULL == data->state.pathbuffer) {
6188 result = CURLE_OUT_OF_MEMORY; /* really bad error */
6191 data->state.path = data->state.pathbuffer;
6193 conn->host.rawalloc = malloc(urllen+2);
6194 if(NULL == conn->host.rawalloc) {
6195 Curl_safefree(data->state.pathbuffer);
6196 data->state.path = NULL;
6197 result = CURLE_OUT_OF_MEMORY;
6201 conn->host.name = conn->host.rawalloc;
6202 conn->host.name[0] = 0;
6205 passwd = strdup("");
6206 options = strdup("");
6207 if(!user || !passwd || !options) {
6208 result = CURLE_OUT_OF_MEMORY;
6212 result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
6217 /*************************************************************
6218 * No protocol part in URL was used, add it!
6219 *************************************************************/
6221 /* We're guessing prefixes here and if we're told to use a proxy or if
6222 we're gonna follow a Location: later or... then we need the protocol
6223 part added so that we have a valid URL. */
6227 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
6230 result = CURLE_OUT_OF_MEMORY;
6234 /* Change protocol prefix to lower-case */
6235 for(ch_lower = reurl; *ch_lower != ':'; ch_lower++)
6236 *ch_lower = (char)TOLOWER(*ch_lower);
6238 if(data->change.url_alloc) {
6239 Curl_safefree(data->change.url);
6240 data->change.url_alloc = FALSE;
6243 data->change.url = reurl;
6244 data->change.url_alloc = TRUE; /* free this later */
6247 /*************************************************************
6248 * If the protocol can't handle url query strings, then cut
6249 * off the unhandable part
6250 *************************************************************/
6251 if((conn->given->flags&PROTOPT_NOURLQUERY)) {
6252 char *path_q_sep = strchr(conn->data->state.path, '?');
6254 /* according to rfc3986, allow the query (?foo=bar)
6255 also on protocols that can't handle it.
6257 cut the string-part after '?'
6260 /* terminate the string */
6265 if(data->set.str[STRING_BEARER]) {
6266 conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
6267 if(!conn->oauth_bearer) {
6268 result = CURLE_OUT_OF_MEMORY;
6273 #ifndef CURL_DISABLE_PROXY
6274 /*************************************************************
6275 * Extract the user and password from the authentication string
6276 *************************************************************/
6277 if(conn->bits.proxy_user_passwd) {
6278 result = parse_proxy_auth(data, conn);
6283 /*************************************************************
6284 * Detect what (if any) proxy to use
6285 *************************************************************/
6286 if(data->set.str[STRING_PROXY]) {
6287 proxy = strdup(data->set.str[STRING_PROXY]);
6288 /* if global proxy is set, this is it */
6290 failf(data, "memory shortage");
6291 result = CURLE_OUT_OF_MEMORY;
6296 if(data->set.str[STRING_PRE_PROXY]) {
6297 socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
6298 /* if global socks proxy is set, this is it */
6299 if(NULL == socksproxy) {
6300 failf(data, "memory shortage");
6301 result = CURLE_OUT_OF_MEMORY;
6306 no_proxy = curl_getenv("no_proxy");
6308 no_proxy = curl_getenv("NO_PROXY");
6310 if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY]) ||
6311 (!data->set.str[STRING_NOPROXY] &&
6312 check_noproxy(conn->host.name, no_proxy))) {
6313 Curl_safefree(proxy);
6314 Curl_safefree(socksproxy);
6316 else if(!proxy && !socksproxy)
6317 #ifndef CURL_DISABLE_HTTP
6318 /* if the host is not in the noproxy list, detect proxy. */
6319 proxy = detect_proxy(conn);
6320 #else /* !CURL_DISABLE_HTTP */
6322 #endif /* CURL_DISABLE_HTTP */
6324 Curl_safefree(no_proxy);
6326 #ifdef USE_UNIX_SOCKETS
6327 if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
6329 free(proxy); /* Unix domain sockets cannot be proxied, so disable it */
6332 conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
6333 if(conn->unix_domain_socket == NULL) {
6334 result = CURLE_OUT_OF_MEMORY;
6337 conn->abstract_unix_socket = data->set.abstract_unix_socket;
6341 if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
6342 free(proxy); /* Don't bother with an empty proxy string or if the
6343 protocol doesn't work with network */
6346 if(socksproxy && (!*socksproxy ||
6347 (conn->handler->flags & PROTOPT_NONETWORK))) {
6348 free(socksproxy); /* Don't bother with an empty socks proxy string or if
6349 the protocol doesn't work with network */
6353 /***********************************************************************
6354 * If this is supposed to use a proxy, we need to figure out the proxy host
6355 * name, proxy type and port number, so that we can re-use an existing
6356 * connection that may exist registered to the same proxy host.
6357 ***********************************************************************/
6358 if(proxy || socksproxy) {
6360 result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype);
6361 Curl_safefree(proxy); /* parse_proxy copies the proxy string */
6367 result = parse_proxy(data, conn, socksproxy,
6368 conn->socks_proxy.proxytype);
6369 /* parse_proxy copies the socks proxy string */
6370 Curl_safefree(socksproxy);
6375 if(conn->http_proxy.host.rawalloc) {
6376 #ifdef CURL_DISABLE_HTTP
6377 /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
6378 result = CURLE_UNSUPPORTED_PROTOCOL;
6381 /* force this connection's protocol to become HTTP if not already
6382 compatible - if it isn't tunneling through */
6383 if(!(conn->handler->protocol & PROTO_FAMILY_HTTP) &&
6384 !conn->bits.tunnel_proxy)
6385 conn->handler = &Curl_handler_http;
6387 conn->bits.httpproxy = TRUE;
6391 conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
6392 conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
6395 if(conn->socks_proxy.host.rawalloc) {
6396 if(!conn->http_proxy.host.rawalloc) {
6397 /* once a socks proxy */
6398 if(!conn->socks_proxy.user) {
6399 conn->socks_proxy.user = conn->http_proxy.user;
6400 conn->http_proxy.user = NULL;
6401 Curl_safefree(conn->socks_proxy.passwd);
6402 conn->socks_proxy.passwd = conn->http_proxy.passwd;
6403 conn->http_proxy.passwd = NULL;
6406 conn->bits.socksproxy = TRUE;
6409 conn->bits.socksproxy = FALSE; /* not a socks proxy */
6412 conn->bits.socksproxy = FALSE;
6413 conn->bits.httpproxy = FALSE;
6415 conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
6417 if(!conn->bits.proxy) {
6418 /* we aren't using the proxy after all... */
6419 conn->bits.proxy = FALSE;
6420 conn->bits.httpproxy = FALSE;
6421 conn->bits.socksproxy = FALSE;
6422 conn->bits.proxy_user_passwd = FALSE;
6423 conn->bits.tunnel_proxy = FALSE;
6426 #endif /* CURL_DISABLE_PROXY */
6428 /*************************************************************
6429 * If the protocol is using SSL and HTTP proxy is used, we set
6430 * the tunnel_proxy bit.
6431 *************************************************************/
6432 if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
6433 conn->bits.tunnel_proxy = TRUE;
6435 /*************************************************************
6436 * Figure out the remote port number and fix it in the URL
6437 *************************************************************/
6438 result = parse_remote_port(data, conn);
6442 /* Check for overridden login details and set them accordingly so they
6443 they are known when protocol->setup_connection is called! */
6444 result = override_login(data, conn, &user, &passwd, &options);
6447 result = set_login(conn, user, passwd, options);
6451 /*************************************************************
6452 * Process the "connect to" linked list of hostname/port mappings.
6453 * Do this after the remote port number has been fixed in the URL.
6454 *************************************************************/
6455 result = parse_connect_to_slist(data, conn, data->set.connect_to);
6459 /*************************************************************
6460 * IDN-fix the hostnames
6461 *************************************************************/
6462 fix_hostname(conn, &conn->host);
6463 if(conn->bits.conn_to_host)
6464 fix_hostname(conn, &conn->conn_to_host);
6465 if(conn->bits.httpproxy)
6466 fix_hostname(conn, &conn->http_proxy.host);
6467 if(conn->bits.socksproxy)
6468 fix_hostname(conn, &conn->socks_proxy.host);
6470 /*************************************************************
6471 * Check whether the host and the "connect to host" are equal.
6472 * Do this after the hostnames have been IDN-fixed.
6473 *************************************************************/
6474 if(conn->bits.conn_to_host &&
6475 strcasecompare(conn->conn_to_host.name, conn->host.name)) {
6476 conn->bits.conn_to_host = FALSE;
6479 /*************************************************************
6480 * Check whether the port and the "connect to port" are equal.
6481 * Do this after the remote port number has been fixed in the URL.
6482 *************************************************************/
6483 if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
6484 conn->bits.conn_to_port = FALSE;
6487 /*************************************************************
6488 * If the "connect to" feature is used with an HTTP proxy,
6489 * we set the tunnel_proxy bit.
6490 *************************************************************/
6491 if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
6492 conn->bits.httpproxy)
6493 conn->bits.tunnel_proxy = TRUE;
6495 /*************************************************************
6496 * Setup internals depending on protocol. Needs to be done after
6497 * we figured out what/if proxy to use.
6498 *************************************************************/
6499 result = setup_connection_internals(conn);
6503 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
6504 conn->send[FIRSTSOCKET] = Curl_send_plain;
6505 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
6506 conn->send[SECONDARYSOCKET] = Curl_send_plain;
6508 conn->bits.tcp_fastopen = data->set.tcp_fastopen;
6510 /***********************************************************************
6511 * file: is a special case in that it doesn't need a network connection
6512 ***********************************************************************/
6513 #ifndef CURL_DISABLE_FILE
6514 if(conn->handler->flags & PROTOPT_NONETWORK) {
6516 /* this is supposed to be the connect function so we better at least check
6517 that the file is present here! */
6518 DEBUGASSERT(conn->handler->connect_it);
6519 result = conn->handler->connect_it(conn, &done);
6521 /* Setup a "faked" transfer that'll do nothing */
6524 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
6526 Curl_conncache_add_conn(data->state.conn_cache, conn);
6529 * Setup whatever necessary for a resumed transfer
6531 result = setup_range(data);
6533 DEBUGASSERT(conn->handler->done);
6534 /* we ignore the return code for the protocol-specific DONE */
6535 (void)conn->handler->done(conn, result, FALSE);
6539 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
6540 -1, NULL); /* no upload */
6543 /* since we skip do_init() */
6544 Curl_init_do(data, conn);
6550 /* Get a cloned copy of the SSL config situation stored in the
6551 connection struct. But to get this going nicely, we must first make
6552 sure that the strings in the master copy are pointing to the correct
6553 strings in the session handle strings array!
6555 Keep in mind that the pointers in the master copy are pointing to strings
6556 that will be freed as part of the Curl_easy struct, but all cloned
6557 copies will be separately allocated.
6559 data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
6560 data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
6561 data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
6562 data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
6563 data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
6564 data->set.proxy_ssl.primary.random_file =
6565 data->set.str[STRING_SSL_RANDOM_FILE];
6566 data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
6567 data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
6568 data->set.ssl.primary.cipher_list =
6569 data->set.str[STRING_SSL_CIPHER_LIST_ORIG];
6570 data->set.proxy_ssl.primary.cipher_list =
6571 data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
6573 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG];
6574 data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY];
6575 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG];
6576 data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY];
6577 data->set.ssl.cert = data->set.str[STRING_CERT_ORIG];
6578 data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY];
6579 data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG];
6580 data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
6581 data->set.ssl.key = data->set.str[STRING_KEY_ORIG];
6582 data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
6583 data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
6584 data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
6585 data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
6586 data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
6587 data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
6588 data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
6590 data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
6591 data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
6592 data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
6593 data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
6596 if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
6597 &conn->ssl_config)) {
6598 result = CURLE_OUT_OF_MEMORY;
6602 if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
6603 &conn->proxy_ssl_config)) {
6604 result = CURLE_OUT_OF_MEMORY;
6608 prune_dead_connections(data);
6610 /*************************************************************
6611 * Check the current list of connections to see if we can
6612 * re-use an already existing one or if we have to create a
6614 *************************************************************/
6616 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
6617 we only acknowledge this option if this is not a re-used connection
6618 already (which happens due to follow-location or during a HTTP
6619 authentication phase). */
6620 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
6623 reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
6625 /* If we found a reusable connection, we may still want to
6626 open a new connection if we are pipelining. */
6627 if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
6628 size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
6630 infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
6631 conn_temp->connection_id, pipelen);
6633 if(conn_temp->bundle->num_connections < max_host_connections &&
6634 data->state.conn_cache->num_connections < max_total_connections) {
6635 /* We want a new connection anyway */
6638 infof(data, "We can reuse, but we want a new connection anyway\n");
6645 * We already have a connection for this, we got the former connection
6646 * in the conn_temp variable and thus we need to cleanup the one we
6647 * just allocated before we can move along and use the previously
6650 conn_temp->inuse = TRUE; /* mark this as being in use so that no other
6651 handle in a multi stack may nick it */
6652 reuse_conn(conn, conn_temp);
6653 free(conn); /* we don't need this anymore */
6657 infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
6658 conn->connection_id,
6659 conn->bits.proxy?"proxy":"host",
6660 conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
6661 conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
6662 conn->host.dispname);
6665 /* We have decided that we want a new connection. However, we may not
6666 be able to do that if we have reached the limit of how many
6667 connections we are allowed to open. */
6668 struct connectbundle *bundle = NULL;
6670 if(conn->handler->flags & PROTOPT_ALPN_NPN) {
6671 /* The protocol wants it, so set the bits if enabled in the easy handle
6673 if(data->set.ssl_enable_alpn)
6674 conn->bits.tls_enable_alpn = TRUE;
6675 if(data->set.ssl_enable_npn)
6676 conn->bits.tls_enable_npn = TRUE;
6680 /* There is a connection that *might* become usable for pipelining
6681 "soon", and we wait for that */
6682 connections_available = FALSE;
6684 bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache);
6686 if(max_host_connections > 0 && bundle &&
6687 (bundle->num_connections >= max_host_connections)) {
6688 struct connectdata *conn_candidate;
6690 /* The bundle is full. Let's see if we can kill a connection. */
6691 conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
6693 if(conn_candidate) {
6694 /* Set the connection's owner correctly, then kill it */
6695 conn_candidate->data = data;
6696 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
6699 infof(data, "No more connections allowed to host: %d\n",
6700 max_host_connections);
6701 connections_available = FALSE;
6705 if(connections_available &&
6706 (max_total_connections > 0) &&
6707 (data->state.conn_cache->num_connections >= max_total_connections)) {
6708 struct connectdata *conn_candidate;
6710 /* The cache is full. Let's see if we can kill a connection. */
6711 conn_candidate = Curl_oldest_idle_connection(data);
6713 if(conn_candidate) {
6714 /* Set the connection's owner correctly, then kill it */
6715 conn_candidate->data = data;
6716 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
6719 infof(data, "No connections available in cache\n");
6720 connections_available = FALSE;
6724 if(!connections_available) {
6725 infof(data, "No connections available.\n");
6730 result = CURLE_NO_CONNECTION_AVAILABLE;
6735 * This is a brand new connection, so let's store it in the connection
6738 Curl_conncache_add_conn(data->state.conn_cache, conn);
6741 #if defined(USE_NTLM)
6742 /* If NTLM is requested in a part of this connection, make sure we don't
6743 assume the state is fine as this is a fresh connection and NTLM is
6744 connection based. */
6745 if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
6746 data->state.authhost.done) {
6747 infof(data, "NTLM picked AND auth done set, clear picked!\n");
6748 data->state.authhost.picked = CURLAUTH_NONE;
6749 data->state.authhost.done = FALSE;
6752 if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
6753 data->state.authproxy.done) {
6754 infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
6755 data->state.authproxy.picked = CURLAUTH_NONE;
6756 data->state.authproxy.done = FALSE;
6761 /* Mark the connection as used */
6764 /* Setup and init stuff before DO starts, in preparing for the transfer. */
6765 Curl_init_do(data, conn);
6768 * Setup whatever necessary for a resumed transfer
6770 result = setup_range(data);
6774 /* Continue connectdata initialization here. */
6777 * Inherit the proper values from the urldata struct AFTER we have arranged
6778 * the persistent connection stuff
6780 conn->seek_func = data->set.seek_func;
6781 conn->seek_client = data->set.seek_client;
6783 /*************************************************************
6784 * Resolve the address of the server or proxy
6785 *************************************************************/
6786 result = resolve_server(data, conn, async);
6798 /* Curl_setup_conn() is called after the name resolve initiated in
6799 * create_conn() is all done.
6801 * Curl_setup_conn() also handles reused connections
6803 * conn->data MUST already have been setup fine (in create_conn)
6806 CURLcode Curl_setup_conn(struct connectdata *conn,
6807 bool *protocol_done)
6809 CURLcode result = CURLE_OK;
6810 struct Curl_easy *data = conn->data;
6812 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
6814 if(conn->handler->flags & PROTOPT_NONETWORK) {
6815 /* nothing to setup when not using a network */
6816 *protocol_done = TRUE;
6819 *protocol_done = FALSE; /* default to not done */
6821 /* set proxy_connect_closed to false unconditionally already here since it
6822 is used strictly to provide extra information to a parent function in the
6823 case of proxy CONNECT failures and we must make sure we don't have it
6824 lingering set from a previous invoke */
6825 conn->bits.proxy_connect_closed = FALSE;
6828 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
6829 * basically anything through a http proxy we can't limit this based on
6832 if(data->set.str[STRING_USERAGENT]) {
6833 Curl_safefree(conn->allocptr.uagent);
6834 conn->allocptr.uagent =
6835 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
6836 if(!conn->allocptr.uagent)
6837 return CURLE_OUT_OF_MEMORY;
6840 data->req.headerbytecount = 0;
6842 #ifdef CURL_DO_LINEEND_CONV
6843 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
6844 #endif /* CURL_DO_LINEEND_CONV */
6846 /* set start time here for timeout purposes in the connect procedure, it
6847 is later set again for the progress meter purpose */
6848 conn->now = Curl_tvnow();
6850 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
6851 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
6852 result = Curl_connecthost(conn, conn->dns_entry);
6857 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
6858 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
6859 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
6860 *protocol_done = TRUE;
6861 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
6862 Curl_verboseconnect(conn);
6865 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
6866 set this here perhaps a second time */
6870 * This check is quite a hack. We're calling _fsetmode to fix the problem
6871 * with fwrite converting newline characters (you get mangled text files,
6872 * and corrupted binary files when you download to stdout and redirect it to
6876 if((data->set.out)->_handle == NULL) {
6877 _fsetmode(stdout, "b");
6884 CURLcode Curl_connect(struct Curl_easy *data,
6885 struct connectdata **in_connect,
6887 bool *protocol_done)
6891 *asyncp = FALSE; /* assume synchronous resolves by default */
6893 /* call the stuff that needs to be called */
6894 result = create_conn(data, in_connect, asyncp);
6898 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
6900 *protocol_done = TRUE;
6902 /* DNS resolution is done: that's either because this is a reused
6903 connection, in which case DNS was unnecessary, or because DNS
6904 really did finish already (synch resolver/fast async resolve) */
6905 result = Curl_setup_conn(*in_connect, protocol_done);
6909 if(result == CURLE_NO_CONNECTION_AVAILABLE) {
6914 if(result && *in_connect) {
6915 /* We're not allowed to return failure with memory left allocated
6916 in the connectdata struct, free those here */
6917 Curl_disconnect(*in_connect, FALSE); /* close the connection */
6918 *in_connect = NULL; /* return a NULL */
6925 * Curl_init_do() inits the readwrite session. This is inited each time (in
6926 * the DO function before the protocol-specific DO functions are invoked) for
6927 * a transfer, sometimes multiple times on the same Curl_easy. Make sure
6928 * nothing in here depends on stuff that are setup dynamically for the
6931 * Allow this function to get called with 'conn' set to NULL.
6934 CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
6936 struct SingleRequest *k = &data->req;
6939 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
6942 data->state.done = FALSE; /* *_done() is not called yet */
6943 data->state.expect100header = FALSE;
6945 if(data->set.opt_no_body)
6946 /* in HTTP lingo, no body means using the HEAD request... */
6947 data->set.httpreq = HTTPREQ_HEAD;
6948 else if(HTTPREQ_HEAD == data->set.httpreq)
6949 /* ... but if unset there really is no perfect method that is the
6950 "opposite" of HEAD but in reality most people probably think GET
6951 then. The important thing is that we can't let it remain HEAD if the
6952 opt_no_body is set FALSE since then we'll behave wrong when getting
6954 data->set.httpreq = HTTPREQ_GET;
6956 k->start = Curl_tvnow(); /* start time */
6957 k->now = k->start; /* current time is now */
6958 k->header = TRUE; /* assume header */
6962 k->buf = data->state.buffer;
6963 k->uploadbuf = data->state.uploadbuffer;
6964 k->hbufp = data->state.headerbuff;
6965 k->ignorebody=FALSE;
6967 Curl_speedinit(data);
6969 Curl_pgrsSetUploadCounter(data, 0);
6970 Curl_pgrsSetDownloadCounter(data, 0);
6976 * get_protocol_family()
6978 * This is used to return the protocol family for a given protocol.
6982 * protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
6984 * Returns the family as a single bit protocol identifier.
6987 unsigned int get_protocol_family(unsigned int protocol)
6989 unsigned int family;
6992 case CURLPROTO_HTTP:
6993 case CURLPROTO_HTTPS:
6994 family = CURLPROTO_HTTP;
6998 case CURLPROTO_FTPS:
6999 family = CURLPROTO_FTP;
7003 family = CURLPROTO_SCP;
7006 case CURLPROTO_SFTP:
7007 family = CURLPROTO_SFTP;
7010 case CURLPROTO_TELNET:
7011 family = CURLPROTO_TELNET;
7014 case CURLPROTO_LDAP:
7015 case CURLPROTO_LDAPS:
7016 family = CURLPROTO_LDAP;
7019 case CURLPROTO_DICT:
7020 family = CURLPROTO_DICT;
7023 case CURLPROTO_FILE:
7024 family = CURLPROTO_FILE;
7027 case CURLPROTO_TFTP:
7028 family = CURLPROTO_TFTP;
7031 case CURLPROTO_IMAP:
7032 case CURLPROTO_IMAPS:
7033 family = CURLPROTO_IMAP;
7036 case CURLPROTO_POP3:
7037 case CURLPROTO_POP3S:
7038 family = CURLPROTO_POP3;
7041 case CURLPROTO_SMTP:
7042 case CURLPROTO_SMTPS:
7043 family = CURLPROTO_SMTP;
7046 case CURLPROTO_RTSP:
7047 family = CURLPROTO_RTSP;
7050 case CURLPROTO_RTMP:
7051 case CURLPROTO_RTMPS:
7052 family = CURLPROTO_RTMP;
7055 case CURLPROTO_RTMPT:
7056 case CURLPROTO_RTMPTS:
7057 family = CURLPROTO_RTMPT;
7060 case CURLPROTO_RTMPE:
7061 family = CURLPROTO_RTMPE;
7064 case CURLPROTO_RTMPTE:
7065 family = CURLPROTO_RTMPTE;
7068 case CURLPROTO_GOPHER:
7069 family = CURLPROTO_GOPHER;
7073 case CURLPROTO_SMBS:
7074 family = CURLPROTO_SMB;