1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2016, 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 #include <stringprep.h>
66 #ifdef HAVE_IDN_FREE_H
69 /* prototype from idn-free.h, not provided by libidn 0.4.5's make install! */
70 void idn_free (void *ptr);
73 /* if idn_free() was not found in this version of libidn use free() instead */
74 #define idn_free(x) (free)(x)
76 #elif defined(USE_WIN32_IDN)
77 /* prototype for curl_win32_idn_to_ascii() */
78 bool curl_win32_idn_to_ascii(const char *in, char **out);
79 #endif /* USE_LIBIDN */
85 #include "vtls/vtls.h"
96 #include "content_encoding.h"
97 #include "http_digest.h"
98 #include "http_negotiate.h"
102 #include "speedcheck.h"
104 #include "warnless.h"
105 #include "non-ascii.h"
106 #include "inet_pton.h"
108 /* And now for the protocols */
116 #include "curl_ldap.h"
121 #include "inet_ntop.h"
122 #include "curl_ntlm.h"
123 #include "curl_ntlm_wb.h"
125 #include "curl_rtmp.h"
127 #include "http_proxy.h"
128 #include "conncache.h"
129 #include "multihandle.h"
130 #include "pipeline.h"
133 #include "curl_printf.h"
134 #include "curl_memory.h"
135 /* The last #include file should be: */
136 #include "memdebug.h"
138 /* Local static prototypes */
139 static struct connectdata *
140 find_oldest_idle_connection(struct SessionHandle *data);
141 static struct connectdata *
142 find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
143 struct connectbundle *bundle);
144 static void conn_free(struct connectdata *conn);
145 static void free_fixed_hostname(struct hostname *host);
146 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
147 static CURLcode parse_url_login(struct SessionHandle *data,
148 struct connectdata *conn,
149 char **userptr, char **passwdptr,
151 static CURLcode parse_login_details(const char *login, const size_t len,
152 char **userptr, char **passwdptr,
154 static unsigned int get_protocol_family(unsigned int protocol);
160 static const struct Curl_handler * const protocols[] = {
162 #ifndef CURL_DISABLE_HTTP
166 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
170 #ifndef CURL_DISABLE_FTP
174 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
178 #ifndef CURL_DISABLE_TELNET
179 &Curl_handler_telnet,
182 #ifndef CURL_DISABLE_DICT
186 #ifndef CURL_DISABLE_LDAP
188 #if !defined(CURL_DISABLE_LDAPS) && \
189 ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
190 (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
195 #ifndef CURL_DISABLE_FILE
199 #ifndef CURL_DISABLE_TFTP
208 #ifndef CURL_DISABLE_IMAP
215 #ifndef CURL_DISABLE_POP3
222 #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
223 (CURL_SIZEOF_CURL_OFF_T > 4) && \
224 (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
231 #ifndef CURL_DISABLE_SMTP
238 #ifndef CURL_DISABLE_RTSP
242 #ifndef CURL_DISABLE_GOPHER
243 &Curl_handler_gopher,
250 &Curl_handler_rtmpte,
252 &Curl_handler_rtmpts,
255 (struct Curl_handler *) NULL
259 * Dummy handler for undefined protocol schemes.
262 static const struct Curl_handler Curl_handler_dummy = {
263 "<no protocol>", /* scheme */
264 ZERO_NULL, /* setup_connection */
265 ZERO_NULL, /* do_it */
266 ZERO_NULL, /* done */
267 ZERO_NULL, /* do_more */
268 ZERO_NULL, /* connect_it */
269 ZERO_NULL, /* connecting */
270 ZERO_NULL, /* doing */
271 ZERO_NULL, /* proto_getsock */
272 ZERO_NULL, /* doing_getsock */
273 ZERO_NULL, /* domore_getsock */
274 ZERO_NULL, /* perform_getsock */
275 ZERO_NULL, /* disconnect */
276 ZERO_NULL, /* readwrite */
279 PROTOPT_NONE /* flags */
282 void Curl_freeset(struct SessionHandle *data)
284 /* Free all dynamic strings stored in the data->set substructure. */
286 for(i=(enum dupstring)0; i < STRING_LAST; i++) {
287 Curl_safefree(data->set.str[i]);
290 if(data->change.referer_alloc) {
291 Curl_safefree(data->change.referer);
292 data->change.referer_alloc = FALSE;
294 data->change.referer = NULL;
295 if(data->change.url_alloc) {
296 Curl_safefree(data->change.url);
297 data->change.url_alloc = FALSE;
299 data->change.url = NULL;
302 static CURLcode setstropt(char **charp, const char *s)
304 /* Release the previous storage at `charp' and replace by a dynamic storage
305 copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
307 Curl_safefree(*charp);
310 char *str = strdup(s);
313 return CURLE_OUT_OF_MEMORY;
321 static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp)
323 CURLcode result = CURLE_OK;
327 /* Parse the login details if specified. It not then we treat NULL as a hint
328 to clear the existing data */
330 result = parse_login_details(option, strlen(option),
331 (userp ? &user : NULL),
332 (passwdp ? &passwd : NULL),
337 /* Store the username part of option if required */
339 if(!user && option && option[0] == ':') {
340 /* Allocate an empty string instead of returning NULL as user name */
343 result = CURLE_OUT_OF_MEMORY;
346 Curl_safefree(*userp);
350 /* Store the password part of option if required */
352 Curl_safefree(*passwdp);
360 CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src)
362 CURLcode result = CURLE_OK;
365 /* Copy src->set into dst->set first, then deal with the strings
369 /* clear all string pointers first */
370 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
372 /* duplicate all strings */
373 for(i=(enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
374 result = setstropt(&dst->set.str[i], src->set.str[i]);
379 /* duplicate memory areas pointed to */
380 i = STRING_COPYPOSTFIELDS;
381 if(src->set.postfieldsize && src->set.str[i]) {
382 /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */
383 dst->set.str[i] = Curl_memdup(src->set.str[i],
384 curlx_sotouz(src->set.postfieldsize));
386 return CURLE_OUT_OF_MEMORY;
387 /* point to the new copy */
388 dst->set.postfields = dst->set.str[i];
395 * This is the internal function curl_easy_cleanup() calls. This should
396 * cleanup and free all resources associated with this sessionhandle.
398 * NOTE: if we ever add something that attempts to write to a socket or
399 * similar here, we must ignore SIGPIPE first. It is currently only done
400 * when curl_easy_perform() is invoked.
403 CURLcode Curl_close(struct SessionHandle *data)
405 struct Curl_multi *m;
410 Curl_expire(data, 0); /* shut off timers */
415 /* This handle is still part of a multi handle, take care of this first
416 and detach this handle from there. */
417 curl_multi_remove_handle(data->multi, data);
420 /* when curl_easy_perform() is used, it creates its own multi handle to
421 use and this is the one */
422 curl_multi_cleanup(data->multi_easy);
424 /* Destroy the timeout list that is held in the easy handle. It is
425 /normally/ done by curl_multi_remove_handle() but this is "just in
427 if(data->state.timeoutlist) {
428 Curl_llist_destroy(data->state.timeoutlist, NULL);
429 data->state.timeoutlist = NULL;
432 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
433 the multi handle, since that function uses the magic
436 if(data->state.rangestringalloc)
437 free(data->state.range);
439 /* Free the pathbuffer */
440 Curl_safefree(data->state.pathbuffer);
441 data->state.path = NULL;
443 /* freed here just in case DONE wasn't called */
444 Curl_free_request_state(data);
446 /* Close down all open SSL info and sessions */
447 Curl_ssl_close_all(data);
448 Curl_safefree(data->state.first_host);
449 Curl_safefree(data->state.scratch);
450 Curl_ssl_free_certinfo(data);
452 /* Cleanup possible redirect junk */
453 free(data->req.newurl);
454 data->req.newurl = NULL;
456 if(data->change.referer_alloc) {
457 Curl_safefree(data->change.referer);
458 data->change.referer_alloc = FALSE;
460 data->change.referer = NULL;
462 if(data->change.url_alloc) {
463 Curl_safefree(data->change.url);
464 data->change.url_alloc = FALSE;
466 data->change.url = NULL;
468 Curl_safefree(data->state.headerbuff);
470 Curl_flush_cookies(data, 1);
472 Curl_digest_cleanup(data);
474 Curl_safefree(data->info.contenttype);
475 Curl_safefree(data->info.wouldredirect);
477 /* this destroys the channel and we cannot use it anymore after this */
478 Curl_resolver_cleanup(data->state.resolver);
480 Curl_convert_close(data);
482 /* No longer a dirty share, if it exists */
484 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
485 data->share->dirty--;
486 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
495 * Initialize the UserDefined fields within a SessionHandle.
496 * This may be safely called on a new or existing SessionHandle.
498 CURLcode Curl_init_userdefined(struct UserDefined *set)
500 CURLcode result = CURLE_OK;
502 set->out = stdout; /* default output to stdout */
503 set->in_set = stdin; /* default input from stdin */
504 set->err = stderr; /* default stderr to stderr */
506 /* use fwrite as default function to store output */
507 set->fwrite_func = (curl_write_callback)fwrite;
509 /* use fread as default function to read input */
510 set->fread_func_set = (curl_read_callback)fread;
511 set->is_fread_set = 0;
512 set->is_fwrite_set = 0;
514 set->seek_func = ZERO_NULL;
515 set->seek_client = ZERO_NULL;
517 /* conversion callbacks for non-ASCII hosts */
518 set->convfromnetwork = ZERO_NULL;
519 set->convtonetwork = ZERO_NULL;
520 set->convfromutf8 = ZERO_NULL;
522 set->filesize = -1; /* we don't know the size */
523 set->postfieldsize = -1; /* unknown size */
524 set->maxredirs = -1; /* allow any amount by default */
526 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
527 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
528 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
529 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
530 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
531 set->ftp_filemethod = FTPFILE_MULTICWD;
533 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
535 /* Set the default size of the SSL session ID cache */
536 set->ssl.max_ssl_sessions = 5;
538 set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
539 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
540 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
541 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
543 /* make libcurl quiet by default: */
544 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
547 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
548 * switched off unless wanted.
550 set->ssl.verifypeer = TRUE;
551 set->ssl.verifyhost = TRUE;
553 set->ssl.authtype = CURL_TLSAUTH_NONE;
555 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
557 set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
559 set->new_file_perms = 0644; /* Default permissions */
560 set->new_directory_perms = 0755; /* Default permissions */
562 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
563 define since we internally only use the lower 16 bits for the passed
564 in bitmask to not conflict with the private bits */
565 set->allowed_protocols = CURLPROTO_ALL;
566 set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
567 ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
570 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
572 * disallow unprotected protection negotiation NEC reference implementation
573 * seem not to follow rfc1961 section 4.3/4.4
575 set->socks5_gssapi_nec = FALSE;
576 /* set default GSS-API service name */
577 result = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
578 CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
582 /* set default negotiate proxy service name */
583 result = setstropt(&set->str[STRING_PROXY_SERVICE_NAME],
584 CURL_DEFAULT_PROXY_SERVICE_NAME);
588 /* set default negotiate service name */
589 result = setstropt(&set->str[STRING_SERVICE_NAME],
590 CURL_DEFAULT_SERVICE_NAME);
595 /* This is our preferred CA cert bundle/path since install time */
596 #if defined(CURL_CA_BUNDLE)
597 result = setstropt(&set->str[STRING_SSL_CAFILE], CURL_CA_BUNDLE);
601 #if defined(CURL_CA_PATH)
602 result = setstropt(&set->str[STRING_SSL_CAPATH], CURL_CA_PATH);
607 set->wildcardmatch = FALSE;
608 set->chunk_bgn = ZERO_NULL;
609 set->chunk_end = ZERO_NULL;
611 /* tcp keepalives are disabled by default, but provide reasonable values for
612 * the interval and idle times.
614 set->tcp_keepalive = FALSE;
615 set->tcp_keepintvl = 60;
616 set->tcp_keepidle = 60;
618 set->ssl_enable_npn = TRUE;
619 set->ssl_enable_alpn = TRUE;
621 set->expect_100_timeout = 1000L; /* Wait for a second by default. */
622 set->sep_headers = TRUE; /* separated header lists by default */
624 Curl_http2_init_userset(set);
631 * @param curl is a pointer to a sessionhandle pointer that gets set by this
636 CURLcode Curl_open(struct SessionHandle **curl)
639 struct SessionHandle *data;
641 /* Very simple start-up: alloc the struct, init it with zeroes and return */
642 data = calloc(1, sizeof(struct SessionHandle));
644 /* this is a very serious error */
645 DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
646 return CURLE_OUT_OF_MEMORY;
649 data->magic = CURLEASY_MAGIC_NUMBER;
651 result = Curl_resolver_init(&data->state.resolver);
653 DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
658 /* We do some initial setup here, all those fields that can't be just 0 */
660 data->state.headerbuff = malloc(HEADERSIZE);
661 if(!data->state.headerbuff) {
662 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
663 result = CURLE_OUT_OF_MEMORY;
666 result = Curl_init_userdefined(&data->set);
668 data->state.headersize=HEADERSIZE;
670 Curl_convert_init(data);
672 /* most recent connection is not yet defined */
673 data->state.lastconnect = NULL;
675 data->progress.flags |= PGRS_HIDE;
676 data->state.current_speed = -1; /* init to negative == impossible */
678 data->wildcard.state = CURLWC_INIT;
679 data->wildcard.filelist = NULL;
680 data->set.fnmatch = ZERO_NULL;
681 data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
683 Curl_http2_init_state(&data->state);
687 Curl_resolver_cleanup(data->state.resolver);
688 free(data->state.headerbuff);
699 CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
703 CURLcode result = CURLE_OK;
705 #ifndef CURL_DISABLE_HTTP
710 case CURLOPT_DNS_CACHE_TIMEOUT:
711 data->set.dns_cache_timeout = va_arg(param, long);
713 case CURLOPT_DNS_USE_GLOBAL_CACHE:
714 /* remember we want this enabled */
715 arg = va_arg(param, long);
716 data->set.global_dns_cache = (0 != arg)?TRUE:FALSE;
718 case CURLOPT_SSL_CIPHER_LIST:
719 /* set a list of cipher we want to use in the SSL connection */
720 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
721 va_arg(param, char *));
724 case CURLOPT_RANDOM_FILE:
726 * This is the path name to a file that contains random data to seed
727 * the random SSL stuff with. The file is only used for reading.
729 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
730 va_arg(param, char *));
732 case CURLOPT_EGDSOCKET:
734 * The Entropy Gathering Daemon socket pathname
736 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
737 va_arg(param, char *));
739 case CURLOPT_MAXCONNECTS:
741 * Set the absolute number of maximum simultaneous alive connection that
742 * libcurl is allowed to have.
744 data->set.maxconnects = va_arg(param, long);
746 case CURLOPT_FORBID_REUSE:
748 * When this transfer is done, it must not be left to be reused by a
749 * subsequent transfer but shall be closed immediately.
751 data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE;
753 case CURLOPT_FRESH_CONNECT:
755 * This transfer shall not use a previously cached connection but
756 * should be made with a fresh new connect!
758 data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE;
760 case CURLOPT_VERBOSE:
762 * Verbose means infof() calls that give a lot of information about
763 * the connection and transfer procedures as well as internal choices.
765 data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE;
769 * Set to include the header in the general data output stream.
771 data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE;
773 case CURLOPT_NOPROGRESS:
775 * Shut off the internal supported progress meter
777 data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE;
778 if(data->set.hide_progress)
779 data->progress.flags |= PGRS_HIDE;
781 data->progress.flags &= ~PGRS_HIDE;
785 * Do not include the body part in the output data stream.
787 data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE;
789 case CURLOPT_FAILONERROR:
791 * Don't output the >=400 error code HTML-page, but instead only
794 data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE;
799 * We want to sent data to the remote host. If this is HTTP, that equals
800 * using the PUT request.
802 data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE;
803 if(data->set.upload) {
804 /* If this is HTTP, PUT is what's needed to "upload" */
805 data->set.httpreq = HTTPREQ_PUT;
806 data->set.opt_no_body = FALSE; /* this is implied */
809 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
810 then this can be changed to HEAD later on) */
811 data->set.httpreq = HTTPREQ_GET;
813 case CURLOPT_FILETIME:
815 * Try to get the file time of the remote document. The time will
816 * later (possibly) become available using curl_easy_getinfo().
818 data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE;
820 case CURLOPT_FTP_CREATE_MISSING_DIRS:
822 * An FTP option that modifies an upload to create missing directories on
825 switch(va_arg(param, long)) {
827 data->set.ftp_create_missing_dirs = 0;
830 data->set.ftp_create_missing_dirs = 1;
833 data->set.ftp_create_missing_dirs = 2;
836 /* reserve other values for future use */
837 result = CURLE_UNKNOWN_OPTION;
841 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
843 * Option that specifies how quickly an server response must be obtained
844 * before it is considered failure. For pingpong protocols.
846 data->set.server_response_timeout = va_arg( param , long ) * 1000;
848 case CURLOPT_TFTP_NO_OPTIONS:
850 * Option that prevents libcurl from sending TFTP option requests to the
853 data->set.tftp_no_options = va_arg(param, long) != 0;
855 case CURLOPT_TFTP_BLKSIZE:
857 * TFTP option that specifies the block size to use for data transmission.
859 data->set.tftp_blksize = va_arg(param, long);
861 case CURLOPT_DIRLISTONLY:
863 * An option that changes the command to one that asks for a list
864 * only, no file info details.
866 data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE;
870 * We want to upload and append to an existing file.
872 data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE;
874 case CURLOPT_FTP_FILEMETHOD:
876 * How do access files over FTP.
878 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
882 * Parse the $HOME/.netrc file
884 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
886 case CURLOPT_NETRC_FILE:
888 * Use this file instead of the $HOME/.netrc file
890 result = setstropt(&data->set.str[STRING_NETRC_FILE],
891 va_arg(param, char *));
893 case CURLOPT_TRANSFERTEXT:
895 * This option was previously named 'FTPASCII'. Renamed to work with
896 * more protocols than merely FTP.
898 * Transfer using ASCII (instead of BINARY).
900 data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE;
902 case CURLOPT_TIMECONDITION:
904 * Set HTTP time condition. This must be one of the defines in the
905 * curl/curl.h header file.
907 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
909 case CURLOPT_TIMEVALUE:
911 * This is the value to compare with the remote document with the
912 * method set with CURLOPT_TIMECONDITION
914 data->set.timevalue = (time_t)va_arg(param, long);
916 case CURLOPT_SSLVERSION:
918 * Set explicit SSL version to try to connect with, as some SSL
919 * implementations are lame.
922 data->set.ssl.version = va_arg(param, long);
924 result = CURLE_UNKNOWN_OPTION;
928 #ifndef CURL_DISABLE_HTTP
929 case CURLOPT_AUTOREFERER:
931 * Switch on automatic referer that gets set if curl follows locations.
933 data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE;
936 case CURLOPT_ACCEPT_ENCODING:
938 * String to use at the value of Accept-Encoding header.
940 * If the encoding is set to "" we use an Accept-Encoding header that
941 * encompasses all the encodings we support.
942 * If the encoding is set to NULL we don't send an Accept-Encoding header
943 * and ignore an received Content-Encoding header.
946 argptr = va_arg(param, char *);
947 result = setstropt(&data->set.str[STRING_ENCODING],
948 (argptr && !*argptr)?
949 ALL_CONTENT_ENCODINGS: argptr);
952 case CURLOPT_TRANSFER_ENCODING:
953 data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE;
956 case CURLOPT_FOLLOWLOCATION:
958 * Follow Location: header hints on a HTTP-server.
960 data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE;
963 case CURLOPT_UNRESTRICTED_AUTH:
965 * Send authentication (user+password) when following locations, even when
968 data->set.http_disable_hostname_check_before_authentication =
969 (0 != va_arg(param, long))?TRUE:FALSE;
972 case CURLOPT_MAXREDIRS:
974 * The maximum amount of hops you allow curl to follow Location:
975 * headers. This should mostly be used to detect never-ending loops.
977 data->set.maxredirs = va_arg(param, long);
980 case CURLOPT_POSTREDIR:
983 * Set the behaviour of POST when redirecting
984 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
985 * CURL_REDIR_POST_301 - POST is kept as POST after 301
986 * CURL_REDIR_POST_302 - POST is kept as POST after 302
987 * CURL_REDIR_POST_303 - POST is kept as POST after 303
988 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
989 * other - POST is kept as POST after 301 and 302
991 int postRedir = curlx_sltosi(va_arg(param, long));
992 data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
997 /* Does this option serve a purpose anymore? Yes it does, when
998 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
1000 if(va_arg(param, long)) {
1001 data->set.httpreq = HTTPREQ_POST;
1002 data->set.opt_no_body = FALSE; /* this is implied */
1005 data->set.httpreq = HTTPREQ_GET;
1008 case CURLOPT_COPYPOSTFIELDS:
1010 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
1011 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
1012 * CURLOPT_COPYPOSTFIELDS and not altered later.
1014 argptr = va_arg(param, char *);
1016 if(!argptr || data->set.postfieldsize == -1)
1017 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
1020 * Check that requested length does not overflow the size_t type.
1023 if((data->set.postfieldsize < 0) ||
1024 ((sizeof(curl_off_t) != sizeof(size_t)) &&
1025 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
1026 result = CURLE_OUT_OF_MEMORY;
1030 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1032 /* Allocate even when size == 0. This satisfies the need of possible
1033 later address compare to detect the COPYPOSTFIELDS mode, and
1034 to mark that postfields is used rather than read function or
1037 p = malloc((size_t)(data->set.postfieldsize?
1038 data->set.postfieldsize:1));
1041 result = CURLE_OUT_OF_MEMORY;
1043 if(data->set.postfieldsize)
1044 memcpy(p, argptr, (size_t)data->set.postfieldsize);
1046 data->set.str[STRING_COPYPOSTFIELDS] = p;
1051 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
1052 data->set.httpreq = HTTPREQ_POST;
1055 case CURLOPT_POSTFIELDS:
1057 * Like above, but use static data instead of copying it.
1059 data->set.postfields = va_arg(param, void *);
1060 /* Release old copied data. */
1061 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1062 data->set.httpreq = HTTPREQ_POST;
1065 case CURLOPT_POSTFIELDSIZE:
1067 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1068 * figure it out. Enables binary posts.
1070 bigsize = va_arg(param, long);
1072 if(data->set.postfieldsize < bigsize &&
1073 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1074 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1075 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1076 data->set.postfields = NULL;
1079 data->set.postfieldsize = bigsize;
1082 case CURLOPT_POSTFIELDSIZE_LARGE:
1084 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1085 * figure it out. Enables binary posts.
1087 bigsize = va_arg(param, curl_off_t);
1089 if(data->set.postfieldsize < bigsize &&
1090 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1091 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1092 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1093 data->set.postfields = NULL;
1096 data->set.postfieldsize = bigsize;
1099 case CURLOPT_HTTPPOST:
1101 * Set to make us do HTTP POST
1103 data->set.httppost = va_arg(param, struct curl_httppost *);
1104 data->set.httpreq = HTTPREQ_POST_FORM;
1105 data->set.opt_no_body = FALSE; /* this is implied */
1108 case CURLOPT_REFERER:
1110 * String to set in the HTTP Referer: field.
1112 if(data->change.referer_alloc) {
1113 Curl_safefree(data->change.referer);
1114 data->change.referer_alloc = FALSE;
1116 result = setstropt(&data->set.str[STRING_SET_REFERER],
1117 va_arg(param, char *));
1118 data->change.referer = data->set.str[STRING_SET_REFERER];
1121 case CURLOPT_USERAGENT:
1123 * String to use in the HTTP User-Agent field
1125 result = setstropt(&data->set.str[STRING_USERAGENT],
1126 va_arg(param, char *));
1129 case CURLOPT_HTTPHEADER:
1131 * Set a list with HTTP headers to use (or replace internals with)
1133 data->set.headers = va_arg(param, struct curl_slist *);
1136 case CURLOPT_PROXYHEADER:
1138 * Set a list with proxy headers to use (or replace internals with)
1140 * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a
1141 * long time we remain doing it this way until CURLOPT_PROXYHEADER is
1142 * used. As soon as this option has been used, if set to anything but
1143 * NULL, custom headers for proxies are only picked from this list.
1145 * Set this option to NULL to restore the previous behavior.
1147 data->set.proxyheaders = va_arg(param, struct curl_slist *);
1150 case CURLOPT_HEADEROPT:
1152 * Set header option.
1154 arg = va_arg(param, long);
1155 data->set.sep_headers = (arg & CURLHEADER_SEPARATE)? TRUE: FALSE;
1158 case CURLOPT_HTTP200ALIASES:
1160 * Set a list of aliases for HTTP 200 in response header
1162 data->set.http200aliases = va_arg(param, struct curl_slist *);
1165 #if !defined(CURL_DISABLE_COOKIES)
1166 case CURLOPT_COOKIE:
1168 * Cookie string to send to the remote server in the request.
1170 result = setstropt(&data->set.str[STRING_COOKIE],
1171 va_arg(param, char *));
1174 case CURLOPT_COOKIEFILE:
1176 * Set cookie file to read and parse. Can be used multiple times.
1178 argptr = (char *)va_arg(param, void *);
1180 struct curl_slist *cl;
1181 /* append the cookie file name to the list of file names, and deal with
1183 cl = curl_slist_append(data->change.cookielist, argptr);
1185 curl_slist_free_all(data->change.cookielist);
1186 data->change.cookielist = NULL;
1187 return CURLE_OUT_OF_MEMORY;
1189 data->change.cookielist = cl; /* store the list for later use */
1193 case CURLOPT_COOKIEJAR:
1195 * Set cookie file name to dump all cookies to when we're done.
1198 struct CookieInfo *newcookies;
1199 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1200 va_arg(param, char *));
1203 * Activate the cookie parser. This may or may not already
1206 newcookies = Curl_cookie_init(data, NULL, data->cookies,
1207 data->set.cookiesession);
1209 result = CURLE_OUT_OF_MEMORY;
1210 data->cookies = newcookies;
1214 case CURLOPT_COOKIESESSION:
1216 * Set this option to TRUE to start a new "cookie session". It will
1217 * prevent the forthcoming read-cookies-from-file actions to accept
1218 * cookies that are marked as being session cookies, as they belong to a
1221 * In the original Netscape cookie spec, "session cookies" are cookies
1222 * with no expire date set. RFC2109 describes the same action if no
1223 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1224 * a 'Discard' action that can enforce the discard even for cookies that
1227 * We run mostly with the original cookie spec, as hardly anyone implements
1230 data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE;
1233 case CURLOPT_COOKIELIST:
1234 argptr = va_arg(param, char *);
1239 if(Curl_raw_equal(argptr, "ALL")) {
1240 /* clear all cookies */
1241 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1242 Curl_cookie_clearall(data->cookies);
1243 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1245 else if(Curl_raw_equal(argptr, "SESS")) {
1246 /* clear session cookies */
1247 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1248 Curl_cookie_clearsess(data->cookies);
1249 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1251 else if(Curl_raw_equal(argptr, "FLUSH")) {
1252 /* flush cookies to file, takes care of the locking */
1253 Curl_flush_cookies(data, 0);
1255 else if(Curl_raw_equal(argptr, "RELOAD")) {
1256 /* reload cookies from file */
1257 Curl_cookie_loadfiles(data);
1262 /* if cookie engine was not running, activate it */
1263 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1265 argptr = strdup(argptr);
1266 if(!argptr || !data->cookies) {
1267 result = CURLE_OUT_OF_MEMORY;
1271 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1273 if(checkprefix("Set-Cookie:", argptr))
1274 /* HTTP Header format line */
1275 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1278 /* Netscape format line */
1279 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1281 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1287 #endif /* CURL_DISABLE_COOKIES */
1289 case CURLOPT_HTTPGET:
1291 * Set to force us do HTTP GET
1293 if(va_arg(param, long)) {
1294 data->set.httpreq = HTTPREQ_GET;
1295 data->set.upload = FALSE; /* switch off upload */
1296 data->set.opt_no_body = FALSE; /* this is implied */
1300 case CURLOPT_HTTP_VERSION:
1302 * This sets a requested HTTP version to be used. The value is one of
1303 * the listed enums in curl/curl.h.
1305 arg = va_arg(param, long);
1307 if(arg >= CURL_HTTP_VERSION_2)
1308 return CURLE_UNSUPPORTED_PROTOCOL;
1310 data->set.httpversion = arg;
1313 case CURLOPT_HTTPAUTH:
1315 * Set HTTP Authentication type BITMASK.
1320 unsigned long auth = va_arg(param, unsigned long);
1322 if(auth == CURLAUTH_NONE) {
1323 data->set.httpauth = auth;
1327 /* the DIGEST_IE bit is only used to set a special marker, for all the
1328 rest we need to handle it as normal DIGEST */
1329 data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
1331 if(auth & CURLAUTH_DIGEST_IE) {
1332 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1333 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1336 /* switch off bits we can't support */
1338 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1339 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1340 #elif !defined(NTLM_WB_ENABLED)
1341 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1344 auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
1348 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1351 while(bitcheck < 31) {
1352 if(auth & (1UL << bitcheck++)) {
1358 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1360 data->set.httpauth = auth;
1364 case CURLOPT_EXPECT_100_TIMEOUT_MS:
1366 * Time to wait for a response to a HTTP request containing an
1367 * Expect: 100-continue header before sending the data anyway.
1369 data->set.expect_100_timeout = va_arg(param, long);
1372 #endif /* CURL_DISABLE_HTTP */
1374 case CURLOPT_CUSTOMREQUEST:
1376 * Set a custom string to use as request
1378 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1379 va_arg(param, char *));
1382 data->set.httpreq = HTTPREQ_CUSTOM;
1383 here, we continue as if we were using the already set type
1384 and this just changes the actual request keyword */
1387 #ifndef CURL_DISABLE_PROXY
1388 case CURLOPT_HTTPPROXYTUNNEL:
1390 * Tunnel operations through the proxy instead of normal proxy use
1392 data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE;
1395 case CURLOPT_PROXYPORT:
1397 * Explicitly set HTTP proxy port number.
1399 data->set.proxyport = va_arg(param, long);
1402 case CURLOPT_PROXYAUTH:
1404 * Set HTTP Authentication type BITMASK.
1409 unsigned long auth = va_arg(param, unsigned long);
1411 if(auth == CURLAUTH_NONE) {
1412 data->set.proxyauth = auth;
1416 /* the DIGEST_IE bit is only used to set a special marker, for all the
1417 rest we need to handle it as normal DIGEST */
1418 data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
1420 if(auth & CURLAUTH_DIGEST_IE) {
1421 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1422 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1424 /* switch off bits we can't support */
1426 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1427 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1428 #elif !defined(NTLM_WB_ENABLED)
1429 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1432 auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
1436 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1439 while(bitcheck < 31) {
1440 if(auth & (1UL << bitcheck++)) {
1446 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1448 data->set.proxyauth = auth;
1454 * Set proxy server:port to use as HTTP proxy.
1456 * If the proxy is set to "" we explicitly say that we don't want to use a
1457 * proxy (even though there might be environment variables saying so).
1459 * Setting it to NULL, means no proxy but allows the environment variables
1462 result = setstropt(&data->set.str[STRING_PROXY],
1463 va_arg(param, char *));
1466 case CURLOPT_PROXYTYPE:
1468 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1470 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1473 case CURLOPT_PROXY_TRANSFER_MODE:
1475 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1477 switch (va_arg(param, long)) {
1479 data->set.proxy_transfer_mode = FALSE;
1482 data->set.proxy_transfer_mode = TRUE;
1485 /* reserve other values for future use */
1486 result = CURLE_UNKNOWN_OPTION;
1490 #endif /* CURL_DISABLE_PROXY */
1492 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1493 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1495 * Set GSS-API service name
1497 result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
1498 va_arg(param, char *));
1501 case CURLOPT_PROXY_SERVICE_NAME:
1503 * Set negotiate proxy service name
1505 result = setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME],
1506 va_arg(param, char *));
1509 case CURLOPT_SOCKS5_GSSAPI_NEC:
1511 * set flag for nec socks5 support
1513 data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE;
1516 case CURLOPT_SERVICE_NAME:
1518 * Set negotiate service identity
1520 result = setstropt(&data->set.str[STRING_SERVICE_NAME],
1521 va_arg(param, char *));
1526 case CURLOPT_HEADERDATA:
1528 * Custom pointer to pass the header write callback function
1530 data->set.writeheader = (void *)va_arg(param, void *);
1532 case CURLOPT_ERRORBUFFER:
1534 * Error buffer provided by the caller to get the human readable
1537 data->set.errorbuffer = va_arg(param, char *);
1539 case CURLOPT_WRITEDATA:
1541 * FILE pointer to write to. Or possibly
1542 * used as argument to the write callback.
1544 data->set.out = va_arg(param, void *);
1546 case CURLOPT_FTPPORT:
1548 * Use FTP PORT, this also specifies which IP address to use
1550 result = setstropt(&data->set.str[STRING_FTPPORT],
1551 va_arg(param, char *));
1552 data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ?
1556 case CURLOPT_FTP_USE_EPRT:
1557 data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE;
1560 case CURLOPT_FTP_USE_EPSV:
1561 data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE;
1564 case CURLOPT_FTP_USE_PRET:
1565 data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE;
1568 case CURLOPT_FTP_SSL_CCC:
1569 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1572 case CURLOPT_FTP_SKIP_PASV_IP:
1574 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1575 * bypass of the IP address in PASV responses.
1577 data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE;
1580 case CURLOPT_READDATA:
1582 * FILE pointer to read the file to be uploaded from. Or possibly
1583 * used as argument to the read callback.
1585 data->set.in_set = va_arg(param, void *);
1587 case CURLOPT_INFILESIZE:
1589 * If known, this should inform curl about the file size of the
1590 * to-be-uploaded file.
1592 data->set.filesize = va_arg(param, long);
1594 case CURLOPT_INFILESIZE_LARGE:
1596 * If known, this should inform curl about the file size of the
1597 * to-be-uploaded file.
1599 data->set.filesize = va_arg(param, curl_off_t);
1601 case CURLOPT_LOW_SPEED_LIMIT:
1603 * The low speed limit that if transfers are below this for
1604 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1606 data->set.low_speed_limit=va_arg(param, long);
1608 case CURLOPT_MAX_SEND_SPEED_LARGE:
1610 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1611 * bytes per second the transfer is throttled..
1613 data->set.max_send_speed=va_arg(param, curl_off_t);
1615 case CURLOPT_MAX_RECV_SPEED_LARGE:
1617 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1618 * second the transfer is throttled..
1620 data->set.max_recv_speed=va_arg(param, curl_off_t);
1622 case CURLOPT_LOW_SPEED_TIME:
1624 * The low speed time that if transfers are below the set
1625 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1627 data->set.low_speed_time=va_arg(param, long);
1633 if(data->change.url_alloc) {
1634 /* the already set URL is allocated, free it first! */
1635 Curl_safefree(data->change.url);
1636 data->change.url_alloc = FALSE;
1638 result = setstropt(&data->set.str[STRING_SET_URL],
1639 va_arg(param, char *));
1640 data->change.url = data->set.str[STRING_SET_URL];
1644 * The port number to use when getting the URL
1646 data->set.use_port = va_arg(param, long);
1648 case CURLOPT_TIMEOUT:
1650 * The maximum time you allow curl to use for a single transfer
1653 data->set.timeout = va_arg(param, long) * 1000L;
1656 case CURLOPT_TIMEOUT_MS:
1657 data->set.timeout = va_arg(param, long);
1660 case CURLOPT_CONNECTTIMEOUT:
1662 * The maximum time you allow curl to use to connect.
1664 data->set.connecttimeout = va_arg(param, long) * 1000L;
1667 case CURLOPT_CONNECTTIMEOUT_MS:
1668 data->set.connecttimeout = va_arg(param, long);
1671 case CURLOPT_ACCEPTTIMEOUT_MS:
1673 * The maximum time you allow curl to wait for server connect
1675 data->set.accepttimeout = va_arg(param, long);
1678 case CURLOPT_USERPWD:
1680 * user:password to use in the operation
1682 result = setstropt_userpwd(va_arg(param, char *),
1683 &data->set.str[STRING_USERNAME],
1684 &data->set.str[STRING_PASSWORD]);
1687 case CURLOPT_USERNAME:
1689 * authentication user name to use in the operation
1691 result = setstropt(&data->set.str[STRING_USERNAME],
1692 va_arg(param, char *));
1695 case CURLOPT_PASSWORD:
1697 * authentication password to use in the operation
1699 result = setstropt(&data->set.str[STRING_PASSWORD],
1700 va_arg(param, char *));
1703 case CURLOPT_LOGIN_OPTIONS:
1705 * authentication options to use in the operation
1707 result = setstropt(&data->set.str[STRING_OPTIONS],
1708 va_arg(param, char *));
1711 case CURLOPT_XOAUTH2_BEARER:
1713 * OAuth 2.0 bearer token to use in the operation
1715 result = setstropt(&data->set.str[STRING_BEARER],
1716 va_arg(param, char *));
1719 case CURLOPT_POSTQUOTE:
1721 * List of RAW FTP commands to use after a transfer
1723 data->set.postquote = va_arg(param, struct curl_slist *);
1725 case CURLOPT_PREQUOTE:
1727 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1729 data->set.prequote = va_arg(param, struct curl_slist *);
1733 * List of RAW FTP commands to use before a transfer
1735 data->set.quote = va_arg(param, struct curl_slist *);
1737 case CURLOPT_RESOLVE:
1739 * List of NAME:[address] names to populate the DNS cache with
1740 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1742 * Names added with this API will remain in the cache until explicitly
1743 * removed or the handle is cleaned up.
1745 * This API can remove any name from the DNS cache, but only entries
1746 * that aren't actually in use right now will be pruned immediately.
1748 data->set.resolve = va_arg(param, struct curl_slist *);
1749 data->change.resolve = data->set.resolve;
1751 case CURLOPT_PROGRESSFUNCTION:
1753 * Progress callback function
1755 data->set.fprogress = va_arg(param, curl_progress_callback);
1756 if(data->set.fprogress)
1757 data->progress.callback = TRUE; /* no longer internal */
1759 data->progress.callback = FALSE; /* NULL enforces internal */
1762 case CURLOPT_XFERINFOFUNCTION:
1764 * Transfer info callback function
1766 data->set.fxferinfo = va_arg(param, curl_xferinfo_callback);
1767 if(data->set.fxferinfo)
1768 data->progress.callback = TRUE; /* no longer internal */
1770 data->progress.callback = FALSE; /* NULL enforces internal */
1774 case CURLOPT_PROGRESSDATA:
1776 * Custom client data to pass to the progress callback
1778 data->set.progress_client = va_arg(param, void *);
1781 #ifndef CURL_DISABLE_PROXY
1782 case CURLOPT_PROXYUSERPWD:
1784 * user:password needed to use the proxy
1786 result = setstropt_userpwd(va_arg(param, char *),
1787 &data->set.str[STRING_PROXYUSERNAME],
1788 &data->set.str[STRING_PROXYPASSWORD]);
1790 case CURLOPT_PROXYUSERNAME:
1792 * authentication user name to use in the operation
1794 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1795 va_arg(param, char *));
1797 case CURLOPT_PROXYPASSWORD:
1799 * authentication password to use in the operation
1801 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1802 va_arg(param, char *));
1804 case CURLOPT_NOPROXY:
1806 * proxy exception list
1808 result = setstropt(&data->set.str[STRING_NOPROXY],
1809 va_arg(param, char *));
1815 * What range of the file you want to transfer
1817 result = setstropt(&data->set.str[STRING_SET_RANGE],
1818 va_arg(param, char *));
1820 case CURLOPT_RESUME_FROM:
1822 * Resume transfer at the give file position
1824 data->set.set_resume_from = va_arg(param, long);
1826 case CURLOPT_RESUME_FROM_LARGE:
1828 * Resume transfer at the give file position
1830 data->set.set_resume_from = va_arg(param, curl_off_t);
1832 case CURLOPT_DEBUGFUNCTION:
1834 * stderr write callback.
1836 data->set.fdebug = va_arg(param, curl_debug_callback);
1838 * if the callback provided is NULL, it'll use the default callback
1841 case CURLOPT_DEBUGDATA:
1843 * Set to a void * that should receive all error writes. This
1844 * defaults to CURLOPT_STDERR for normal operations.
1846 data->set.debugdata = va_arg(param, void *);
1848 case CURLOPT_STDERR:
1850 * Set to a FILE * that should receive all error writes. This
1851 * defaults to stderr for normal operations.
1853 data->set.err = va_arg(param, FILE *);
1855 data->set.err = stderr;
1857 case CURLOPT_HEADERFUNCTION:
1859 * Set header write callback
1861 data->set.fwrite_header = va_arg(param, curl_write_callback);
1863 case CURLOPT_WRITEFUNCTION:
1865 * Set data write callback
1867 data->set.fwrite_func = va_arg(param, curl_write_callback);
1868 if(!data->set.fwrite_func) {
1869 data->set.is_fwrite_set = 0;
1870 /* When set to NULL, reset to our internal default function */
1871 data->set.fwrite_func = (curl_write_callback)fwrite;
1874 data->set.is_fwrite_set = 1;
1876 case CURLOPT_READFUNCTION:
1878 * Read data callback
1880 data->set.fread_func_set = va_arg(param, curl_read_callback);
1881 if(!data->set.fread_func_set) {
1882 data->set.is_fread_set = 0;
1883 /* When set to NULL, reset to our internal default function */
1884 data->set.fread_func_set = (curl_read_callback)fread;
1887 data->set.is_fread_set = 1;
1889 case CURLOPT_SEEKFUNCTION:
1891 * Seek callback. Might be NULL.
1893 data->set.seek_func = va_arg(param, curl_seek_callback);
1895 case CURLOPT_SEEKDATA:
1897 * Seek control callback. Might be NULL.
1899 data->set.seek_client = va_arg(param, void *);
1901 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1903 * "Convert from network encoding" callback
1905 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1907 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1909 * "Convert to network encoding" callback
1911 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1913 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1915 * "Convert from UTF-8 encoding" callback
1917 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1919 case CURLOPT_IOCTLFUNCTION:
1921 * I/O control callback. Might be NULL.
1923 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1925 case CURLOPT_IOCTLDATA:
1927 * I/O control data pointer. Might be NULL.
1929 data->set.ioctl_client = va_arg(param, void *);
1931 case CURLOPT_SSLCERT:
1933 * String that holds file name of the SSL certificate to use
1935 result = setstropt(&data->set.str[STRING_CERT],
1936 va_arg(param, char *));
1938 case CURLOPT_SSLCERTTYPE:
1940 * String that holds file type of the SSL certificate to use
1942 result = setstropt(&data->set.str[STRING_CERT_TYPE],
1943 va_arg(param, char *));
1945 case CURLOPT_SSLKEY:
1947 * String that holds file name of the SSL key to use
1949 result = setstropt(&data->set.str[STRING_KEY],
1950 va_arg(param, char *));
1952 case CURLOPT_SSLKEYTYPE:
1954 * String that holds file type of the SSL key to use
1956 result = setstropt(&data->set.str[STRING_KEY_TYPE],
1957 va_arg(param, char *));
1959 case CURLOPT_KEYPASSWD:
1961 * String that holds the SSL or SSH private key password.
1963 result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1964 va_arg(param, char *));
1966 case CURLOPT_SSLENGINE:
1968 * String that holds the SSL crypto engine.
1970 argptr = va_arg(param, char *);
1971 if(argptr && argptr[0])
1972 result = Curl_ssl_set_engine(data, argptr);
1975 case CURLOPT_SSLENGINE_DEFAULT:
1977 * flag to set engine as default.
1979 result = Curl_ssl_set_engine_default(data);
1983 * Kludgy option to enable CRLF conversions. Subject for removal.
1985 data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE;
1988 case CURLOPT_INTERFACE:
1990 * Set what interface or address/hostname to bind the socket to when
1991 * performing an operation and thus what from-IP your connection will use.
1993 result = setstropt(&data->set.str[STRING_DEVICE],
1994 va_arg(param, char *));
1996 case CURLOPT_LOCALPORT:
1998 * Set what local port to bind the socket to when performing an operation.
2000 data->set.localport = curlx_sltous(va_arg(param, long));
2002 case CURLOPT_LOCALPORTRANGE:
2004 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
2006 data->set.localportrange = curlx_sltosi(va_arg(param, long));
2008 case CURLOPT_KRBLEVEL:
2010 * A string that defines the kerberos security level.
2012 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
2013 va_arg(param, char *));
2014 data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE;
2016 case CURLOPT_GSSAPI_DELEGATION:
2018 * GSS-API credential delegation
2020 data->set.gssapi_delegation = va_arg(param, long);
2022 case CURLOPT_SSL_VERIFYPEER:
2024 * Enable peer SSL verifying.
2026 data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE;
2028 case CURLOPT_SSL_VERIFYHOST:
2030 * Enable verification of the host name in the peer certificate
2032 arg = va_arg(param, long);
2034 /* Obviously people are not reading documentation and too many thought
2035 this argument took a boolean when it wasn't and misused it. We thus ban
2036 1 as a sensible input and we warn about its use. Then we only have the
2037 2 action internally stored as TRUE. */
2040 failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
2041 return CURLE_BAD_FUNCTION_ARGUMENT;
2044 data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE;
2046 case CURLOPT_SSL_VERIFYSTATUS:
2048 * Enable certificate status verifying.
2050 if(!Curl_ssl_cert_status_request()) {
2051 result = CURLE_NOT_BUILT_IN;
2055 data->set.ssl.verifystatus = (0 != va_arg(param, long))?TRUE:FALSE;
2057 case CURLOPT_SSL_CTX_FUNCTION:
2058 #ifdef have_curlssl_ssl_ctx
2060 * Set a SSL_CTX callback
2062 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
2064 result = CURLE_NOT_BUILT_IN;
2067 case CURLOPT_SSL_CTX_DATA:
2068 #ifdef have_curlssl_ssl_ctx
2070 * Set a SSL_CTX callback parameter pointer
2072 data->set.ssl.fsslctxp = va_arg(param, void *);
2074 result = CURLE_NOT_BUILT_IN;
2077 case CURLOPT_SSL_FALSESTART:
2079 * Enable TLS false start.
2081 if(!Curl_ssl_false_start()) {
2082 result = CURLE_NOT_BUILT_IN;
2086 data->set.ssl.falsestart = (0 != va_arg(param, long))?TRUE:FALSE;
2088 case CURLOPT_CERTINFO:
2089 #ifdef have_curlssl_certinfo
2090 data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE;
2092 result = CURLE_NOT_BUILT_IN;
2095 case CURLOPT_PINNEDPUBLICKEY:
2097 * Set pinned public key for SSL connection.
2098 * Specify file name of the public key in DER format.
2100 result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY],
2101 va_arg(param, char *));
2103 case CURLOPT_CAINFO:
2105 * Set CA info for SSL connection. Specify file name of the CA certificate
2107 result = setstropt(&data->set.str[STRING_SSL_CAFILE],
2108 va_arg(param, char *));
2110 case CURLOPT_CAPATH:
2111 #ifdef have_curlssl_ca_path /* not supported by all backends */
2113 * Set CA path info for SSL connection. Specify directory name of the CA
2114 * certificates which have been prepared using openssl c_rehash utility.
2116 /* This does not work on windows. */
2117 result = setstropt(&data->set.str[STRING_SSL_CAPATH],
2118 va_arg(param, char *));
2120 result = CURLE_NOT_BUILT_IN;
2123 case CURLOPT_CRLFILE:
2125 * Set CRL file info for SSL connection. Specify file name of the CRL
2126 * to check certificates revocation
2128 result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
2129 va_arg(param, char *));
2131 case CURLOPT_ISSUERCERT:
2133 * Set Issuer certificate file
2134 * to check certificates issuer
2136 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
2137 va_arg(param, char *));
2139 case CURLOPT_TELNETOPTIONS:
2141 * Set a linked list of telnet options
2143 data->set.telnet_options = va_arg(param, struct curl_slist *);
2146 case CURLOPT_BUFFERSIZE:
2148 * The application kindly asks for a differently sized receive buffer.
2149 * If it seems reasonable, we'll use it.
2151 data->set.buffer_size = va_arg(param, long);
2153 if((data->set.buffer_size> (BUFSIZE -1 )) ||
2154 (data->set.buffer_size < 1))
2155 data->set.buffer_size = 0; /* huge internal default */
2159 case CURLOPT_NOSIGNAL:
2161 * The application asks not to set any signal() or alarm() handlers,
2162 * even when using a timeout.
2164 data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE;
2169 struct Curl_share *set;
2170 set = va_arg(param, struct Curl_share *);
2172 /* disconnect from old share, if any */
2174 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2176 if(data->dns.hostcachetype == HCACHE_SHARED) {
2177 data->dns.hostcache = NULL;
2178 data->dns.hostcachetype = HCACHE_NONE;
2181 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2182 if(data->share->cookies == data->cookies)
2183 data->cookies = NULL;
2186 if(data->share->sslsession == data->state.session)
2187 data->state.session = NULL;
2189 data->share->dirty--;
2191 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2195 /* use new share if it set */
2199 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2201 data->share->dirty++;
2203 if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) {
2204 /* use shared host cache */
2205 data->dns.hostcache = &data->share->hostcache;
2206 data->dns.hostcachetype = HCACHE_SHARED;
2208 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2209 if(data->share->cookies) {
2210 /* use shared cookie list, first free own one if any */
2211 Curl_cookie_cleanup(data->cookies);
2212 /* enable cookies since we now use a share that uses cookies! */
2213 data->cookies = data->share->cookies;
2215 #endif /* CURL_DISABLE_HTTP */
2216 if(data->share->sslsession) {
2217 data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions;
2218 data->state.session = data->share->sslsession;
2220 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2223 /* check for host cache not needed,
2224 * it will be done by curl_easy_perform */
2228 case CURLOPT_PRIVATE:
2230 * Set private data pointer.
2232 data->set.private_data = va_arg(param, void *);
2235 case CURLOPT_MAXFILESIZE:
2237 * Set the maximum size of a file to download.
2239 data->set.max_filesize = va_arg(param, long);
2243 case CURLOPT_USE_SSL:
2245 * Make transfers attempt to use SSL/TLS.
2247 data->set.use_ssl = (curl_usessl)va_arg(param, long);
2250 case CURLOPT_SSL_OPTIONS:
2251 arg = va_arg(param, long);
2252 data->set.ssl_enable_beast = !!(arg & CURLSSLOPT_ALLOW_BEAST);
2253 data->set.ssl_no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE);
2257 case CURLOPT_FTPSSLAUTH:
2259 * Set a specific auth for FTP-SSL transfers.
2261 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2264 case CURLOPT_IPRESOLVE:
2265 data->set.ipver = va_arg(param, long);
2268 case CURLOPT_MAXFILESIZE_LARGE:
2270 * Set the maximum size of a file to download.
2272 data->set.max_filesize = va_arg(param, curl_off_t);
2275 case CURLOPT_TCP_NODELAY:
2277 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2280 data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE;
2283 case CURLOPT_FTP_ACCOUNT:
2284 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2285 va_arg(param, char *));
2288 case CURLOPT_IGNORE_CONTENT_LENGTH:
2289 data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE;
2292 case CURLOPT_CONNECT_ONLY:
2294 * No data transfer, set up connection and let application use the socket
2296 data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE;
2299 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2300 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2301 va_arg(param, char *));
2304 case CURLOPT_SOCKOPTFUNCTION:
2306 * socket callback function: called after socket() but before connect()
2308 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2311 case CURLOPT_SOCKOPTDATA:
2313 * socket callback data pointer. Might be NULL.
2315 data->set.sockopt_client = va_arg(param, void *);
2318 case CURLOPT_OPENSOCKETFUNCTION:
2320 * open/create socket callback function: called instead of socket(),
2323 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2326 case CURLOPT_OPENSOCKETDATA:
2328 * socket callback data pointer. Might be NULL.
2330 data->set.opensocket_client = va_arg(param, void *);
2333 case CURLOPT_CLOSESOCKETFUNCTION:
2335 * close socket callback function: called instead of close()
2336 * when shutting down a connection
2338 data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
2341 case CURLOPT_CLOSESOCKETDATA:
2343 * socket callback data pointer. Might be NULL.
2345 data->set.closesocket_client = va_arg(param, void *);
2348 case CURLOPT_SSL_SESSIONID_CACHE:
2349 data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE;
2353 /* we only include SSH options if explicitly built to support SSH */
2354 case CURLOPT_SSH_AUTH_TYPES:
2355 data->set.ssh_auth_types = va_arg(param, long);
2358 case CURLOPT_SSH_PUBLIC_KEYFILE:
2360 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2362 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2363 va_arg(param, char *));
2366 case CURLOPT_SSH_PRIVATE_KEYFILE:
2368 * Use this file instead of the $HOME/.ssh/id_dsa file
2370 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2371 va_arg(param, char *));
2373 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2375 * Option to allow for the MD5 of the host public key to be checked
2376 * for validation purposes.
2378 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2379 va_arg(param, char *));
2381 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2382 case CURLOPT_SSH_KNOWNHOSTS:
2384 * Store the file name to read known hosts from.
2386 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2387 va_arg(param, char *));
2390 case CURLOPT_SSH_KEYFUNCTION:
2391 /* setting to NULL is fine since the ssh.c functions themselves will
2392 then rever to use the internal default */
2393 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2396 case CURLOPT_SSH_KEYDATA:
2398 * Custom client data to pass to the SSH keyfunc callback
2400 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2402 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2404 #endif /* USE_LIBSSH2 */
2406 case CURLOPT_HTTP_TRANSFER_DECODING:
2408 * disable libcurl transfer encoding is used
2410 data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE;
2413 case CURLOPT_HTTP_CONTENT_DECODING:
2415 * raw data passed to the application when content encoding is used
2417 data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE;
2420 case CURLOPT_NEW_FILE_PERMS:
2422 * Uses these permissions instead of 0644
2424 data->set.new_file_perms = va_arg(param, long);
2427 case CURLOPT_NEW_DIRECTORY_PERMS:
2429 * Uses these permissions instead of 0755
2431 data->set.new_directory_perms = va_arg(param, long);
2434 case CURLOPT_ADDRESS_SCOPE:
2436 * We always get longs when passed plain numericals, but for this value we
2437 * know that an unsigned int will always hold the value so we blindly
2438 * typecast to this type
2440 data->set.scope_id = curlx_sltoui(va_arg(param, long));
2443 case CURLOPT_PROTOCOLS:
2444 /* set the bitmask for the protocols that are allowed to be used for the
2445 transfer, which thus helps the app which takes URLs from users or other
2446 external inputs and want to restrict what protocol(s) to deal
2447 with. Defaults to CURLPROTO_ALL. */
2448 data->set.allowed_protocols = va_arg(param, long);
2451 case CURLOPT_REDIR_PROTOCOLS:
2452 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2453 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2454 to be set in both bitmasks to be allowed to get redirected to. Defaults
2455 to all protocols except FILE and SCP. */
2456 data->set.redir_protocols = va_arg(param, long);
2459 case CURLOPT_DEFAULT_PROTOCOL:
2460 /* Set the protocol to use when the URL doesn't include any protocol */
2461 result = setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL],
2462 va_arg(param, char *));
2465 case CURLOPT_MAIL_FROM:
2466 /* Set the SMTP mail originator */
2467 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2468 va_arg(param, char *));
2471 case CURLOPT_MAIL_AUTH:
2472 /* Set the SMTP auth originator */
2473 result = setstropt(&data->set.str[STRING_MAIL_AUTH],
2474 va_arg(param, char *));
2477 case CURLOPT_MAIL_RCPT:
2478 /* Set the list of mail recipients */
2479 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2482 case CURLOPT_SASL_IR:
2483 /* Enable/disable SASL initial response */
2484 data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
2487 case CURLOPT_RTSP_REQUEST:
2490 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2491 * Would this be better if the RTSPREQ_* were just moved into here?
2493 long curl_rtspreq = va_arg(param, long);
2494 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2495 switch(curl_rtspreq) {
2496 case CURL_RTSPREQ_OPTIONS:
2497 rtspreq = RTSPREQ_OPTIONS;
2500 case CURL_RTSPREQ_DESCRIBE:
2501 rtspreq = RTSPREQ_DESCRIBE;
2504 case CURL_RTSPREQ_ANNOUNCE:
2505 rtspreq = RTSPREQ_ANNOUNCE;
2508 case CURL_RTSPREQ_SETUP:
2509 rtspreq = RTSPREQ_SETUP;
2512 case CURL_RTSPREQ_PLAY:
2513 rtspreq = RTSPREQ_PLAY;
2516 case CURL_RTSPREQ_PAUSE:
2517 rtspreq = RTSPREQ_PAUSE;
2520 case CURL_RTSPREQ_TEARDOWN:
2521 rtspreq = RTSPREQ_TEARDOWN;
2524 case CURL_RTSPREQ_GET_PARAMETER:
2525 rtspreq = RTSPREQ_GET_PARAMETER;
2528 case CURL_RTSPREQ_SET_PARAMETER:
2529 rtspreq = RTSPREQ_SET_PARAMETER;
2532 case CURL_RTSPREQ_RECORD:
2533 rtspreq = RTSPREQ_RECORD;
2536 case CURL_RTSPREQ_RECEIVE:
2537 rtspreq = RTSPREQ_RECEIVE;
2540 rtspreq = RTSPREQ_NONE;
2543 data->set.rtspreq = rtspreq;
2548 case CURLOPT_RTSP_SESSION_ID:
2550 * Set the RTSP Session ID manually. Useful if the application is
2551 * resuming a previously established RTSP session
2553 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2554 va_arg(param, char *));
2557 case CURLOPT_RTSP_STREAM_URI:
2559 * Set the Stream URI for the RTSP request. Unless the request is
2560 * for generic server options, the application will need to set this.
2562 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2563 va_arg(param, char *));
2566 case CURLOPT_RTSP_TRANSPORT:
2568 * The content of the Transport: header for the RTSP request
2570 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2571 va_arg(param, char *));
2574 case CURLOPT_RTSP_CLIENT_CSEQ:
2576 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2577 * application is resuming a previously broken connection. The CSEQ
2578 * will increment from this new number henceforth.
2580 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2583 case CURLOPT_RTSP_SERVER_CSEQ:
2584 /* Same as the above, but for server-initiated requests */
2585 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2588 case CURLOPT_INTERLEAVEDATA:
2589 data->set.rtp_out = va_arg(param, void *);
2591 case CURLOPT_INTERLEAVEFUNCTION:
2592 /* Set the user defined RTP write function */
2593 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2596 case CURLOPT_WILDCARDMATCH:
2597 data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE;
2599 case CURLOPT_CHUNK_BGN_FUNCTION:
2600 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2602 case CURLOPT_CHUNK_END_FUNCTION:
2603 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2605 case CURLOPT_FNMATCH_FUNCTION:
2606 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2608 case CURLOPT_CHUNK_DATA:
2609 data->wildcard.customptr = va_arg(param, void *);
2611 case CURLOPT_FNMATCH_DATA:
2612 data->set.fnmatch_data = va_arg(param, void *);
2615 case CURLOPT_TLSAUTH_USERNAME:
2616 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
2617 va_arg(param, char *));
2618 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2619 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2621 case CURLOPT_TLSAUTH_PASSWORD:
2622 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
2623 va_arg(param, char *));
2624 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2625 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2627 case CURLOPT_TLSAUTH_TYPE:
2628 if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
2629 data->set.ssl.authtype = CURL_TLSAUTH_SRP;
2631 data->set.ssl.authtype = CURL_TLSAUTH_NONE;
2634 case CURLOPT_DNS_SERVERS:
2635 result = Curl_set_dns_servers(data, va_arg(param, char *));
2637 case CURLOPT_DNS_INTERFACE:
2638 result = Curl_set_dns_interface(data, va_arg(param, char *));
2640 case CURLOPT_DNS_LOCAL_IP4:
2641 result = Curl_set_dns_local_ip4(data, va_arg(param, char *));
2643 case CURLOPT_DNS_LOCAL_IP6:
2644 result = Curl_set_dns_local_ip6(data, va_arg(param, char *));
2647 case CURLOPT_TCP_KEEPALIVE:
2648 data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE;
2650 case CURLOPT_TCP_KEEPIDLE:
2651 data->set.tcp_keepidle = va_arg(param, long);
2653 case CURLOPT_TCP_KEEPINTVL:
2654 data->set.tcp_keepintvl = va_arg(param, long);
2656 case CURLOPT_SSL_ENABLE_NPN:
2657 data->set.ssl_enable_npn = (0 != va_arg(param, long))?TRUE:FALSE;
2659 case CURLOPT_SSL_ENABLE_ALPN:
2660 data->set.ssl_enable_alpn = (0 != va_arg(param, long))?TRUE:FALSE;
2663 #ifdef USE_UNIX_SOCKETS
2664 case CURLOPT_UNIX_SOCKET_PATH:
2665 result = setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH],
2666 va_arg(param, char *));
2670 case CURLOPT_PATH_AS_IS:
2671 data->set.path_as_is = (0 != va_arg(param, long))?TRUE:FALSE;
2673 case CURLOPT_PIPEWAIT:
2674 data->set.pipewait = (0 != va_arg(param, long))?TRUE:FALSE;
2676 case CURLOPT_STREAM_WEIGHT:
2678 return CURLE_NOT_BUILT_IN;
2680 arg = va_arg(param, long);
2681 if((arg>=1) && (arg <= 256))
2682 data->set.stream_weight = (int)arg;
2685 case CURLOPT_STREAM_DEPENDS:
2686 case CURLOPT_STREAM_DEPENDS_E:
2689 return CURLE_NOT_BUILT_IN;
2691 struct SessionHandle *dep = va_arg(param, struct SessionHandle *);
2692 if(dep && GOOD_EASY_HANDLE(dep)) {
2693 data->set.stream_depends_on = dep;
2694 data->set.stream_depends_e = (option == CURLOPT_STREAM_DEPENDS_E);
2700 /* unknown tag and its companion, just ignore: */
2701 result = CURLE_UNKNOWN_OPTION;
2708 static void conn_free(struct connectdata *conn)
2713 /* possible left-overs from the async name resolvers */
2714 Curl_resolver_cancel(conn);
2716 /* close the SSL stuff before we close any sockets since they will/may
2717 write to the sockets */
2718 Curl_ssl_close(conn, FIRSTSOCKET);
2719 Curl_ssl_close(conn, SECONDARYSOCKET);
2721 /* close possibly still open sockets */
2722 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2723 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2724 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2725 Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
2726 if(CURL_SOCKET_BAD != conn->tempsock[0])
2727 Curl_closesocket(conn, conn->tempsock[0]);
2728 if(CURL_SOCKET_BAD != conn->tempsock[1])
2729 Curl_closesocket(conn, conn->tempsock[1]);
2731 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
2732 defined(NTLM_WB_ENABLED)
2733 Curl_ntlm_wb_cleanup(conn);
2736 Curl_safefree(conn->user);
2737 Curl_safefree(conn->passwd);
2738 Curl_safefree(conn->oauth_bearer);
2739 Curl_safefree(conn->options);
2740 Curl_safefree(conn->proxyuser);
2741 Curl_safefree(conn->proxypasswd);
2742 Curl_safefree(conn->allocptr.proxyuserpwd);
2743 Curl_safefree(conn->allocptr.uagent);
2744 Curl_safefree(conn->allocptr.userpwd);
2745 Curl_safefree(conn->allocptr.accept_encoding);
2746 Curl_safefree(conn->allocptr.te);
2747 Curl_safefree(conn->allocptr.rangeline);
2748 Curl_safefree(conn->allocptr.ref);
2749 Curl_safefree(conn->allocptr.host);
2750 Curl_safefree(conn->allocptr.cookiehost);
2751 Curl_safefree(conn->allocptr.rtsp_transport);
2752 Curl_safefree(conn->trailer);
2753 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2754 Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2755 Curl_safefree(conn->master_buffer);
2757 Curl_llist_destroy(conn->send_pipe, NULL);
2758 Curl_llist_destroy(conn->recv_pipe, NULL);
2760 conn->send_pipe = NULL;
2761 conn->recv_pipe = NULL;
2763 Curl_safefree(conn->localdev);
2764 Curl_free_ssl_config(&conn->ssl_config);
2766 free(conn); /* free all the connection oriented data */
2770 * Disconnects the given connection. Note the connection may not be the
2771 * primary connection, like when freeing room in the connection cache or
2772 * killing of a dead old connection.
2774 * This function MUST NOT reset state in the SessionHandle struct if that
2775 * isn't strictly bound to the life-time of *this* particular connection.
2779 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2781 struct SessionHandle *data;
2783 return CURLE_OK; /* this is closed and fine already */
2787 DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
2791 if(conn->dns_entry != NULL) {
2792 Curl_resolv_unlock(data, conn->dns_entry);
2793 conn->dns_entry = NULL;
2796 Curl_hostcache_prune(data); /* kill old DNS cache entries */
2798 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
2799 /* Cleanup NTLM connection-related data */
2800 Curl_http_ntlm_cleanup(conn);
2803 if(conn->handler->disconnect)
2804 /* This is set if protocol-specific cleanups should be made */
2805 conn->handler->disconnect(conn, dead_connection);
2807 /* unlink ourselves! */
2808 infof(data, "Closing connection %ld\n", conn->connection_id);
2809 Curl_conncache_remove_conn(data->state.conn_cache, conn);
2811 free_fixed_hostname(&conn->host);
2812 free_fixed_hostname(&conn->proxy);
2814 Curl_ssl_close(conn, FIRSTSOCKET);
2816 /* Indicate to all handles on the pipe that we're dead */
2817 if(Curl_pipeline_wanted(data->multi, CURLPIPE_ANY)) {
2818 signalPipeClose(conn->send_pipe, TRUE);
2819 signalPipeClose(conn->recv_pipe, TRUE);
2828 * This function should return TRUE if the socket is to be assumed to
2829 * be dead. Most commonly this happens when the server has closed the
2830 * connection due to inactivity.
2832 static bool SocketIsDead(curl_socket_t sock)
2835 bool ret_val = TRUE;
2837 sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2846 * IsPipeliningPossible() returns TRUE if the options set would allow
2847 * pipelining/multiplexing and the connection is using a HTTP protocol.
2849 static bool IsPipeliningPossible(const struct SessionHandle *handle,
2850 const struct connectdata *conn)
2852 /* If a HTTP protocol and pipelining is enabled */
2853 if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
2855 if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
2856 (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
2857 (handle->set.httpreq == HTTPREQ_GET ||
2858 handle->set.httpreq == HTTPREQ_HEAD))
2859 /* didn't ask for HTTP/1.0 and a GET or HEAD */
2862 if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
2863 (handle->set.httpversion >= CURL_HTTP_VERSION_2))
2870 int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
2871 struct curl_llist *pipeline)
2874 struct curl_llist_element *curr;
2876 curr = pipeline->head;
2878 if(curr->ptr == handle) {
2879 Curl_llist_remove(pipeline, curr, NULL);
2880 return 1; /* we removed a handle */
2889 #if 0 /* this code is saved here as it is useful for debugging purposes */
2890 static void Curl_printPipeline(struct curl_llist *pipeline)
2892 struct curl_llist_element *curr;
2894 curr = pipeline->head;
2896 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2897 infof(data, "Handle in pipeline: %s\n", data->state.path);
2903 static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
2905 struct curl_llist_element *curr = pipeline->head;
2907 return (struct SessionHandle *) curr->ptr;
2913 /* remove the specified connection from all (possible) pipelines and related
2915 void Curl_getoff_all_pipelines(struct SessionHandle *data,
2916 struct connectdata *conn)
2918 bool recv_head = (conn->readchannel_inuse &&
2919 Curl_recvpipe_head(data, conn));
2920 bool send_head = (conn->writechannel_inuse &&
2921 Curl_sendpipe_head(data, conn));
2923 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2924 Curl_pipeline_leave_read(conn);
2925 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2926 Curl_pipeline_leave_write(conn);
2929 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2931 struct curl_llist_element *curr;
2936 curr = pipeline->head;
2938 struct curl_llist_element *next = curr->next;
2939 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2941 #ifdef DEBUGBUILD /* debug-only code */
2942 if(data->magic != CURLEASY_MAGIC_NUMBER) {
2944 infof(data, "signalPipeClose() found BAAD easy handle\n");
2949 data->state.pipe_broke = TRUE;
2950 Curl_multi_handlePipeBreak(data);
2951 Curl_llist_remove(pipeline, curr, NULL);
2957 * This function finds the connection in the connection
2958 * cache that has been unused for the longest time.
2960 * Returns the pointer to the oldest idle connection, or NULL if none was
2963 static struct connectdata *
2964 find_oldest_idle_connection(struct SessionHandle *data)
2966 struct conncache *bc = data->state.conn_cache;
2967 struct curl_hash_iterator iter;
2968 struct curl_llist_element *curr;
2969 struct curl_hash_element *he;
2973 struct connectdata *conn_candidate = NULL;
2974 struct connectbundle *bundle;
2978 Curl_hash_start_iterate(&bc->hash, &iter);
2980 he = Curl_hash_next_element(&iter);
2982 struct connectdata *conn;
2986 curr = bundle->conn_list->head;
2991 /* Set higher score for the age passed since the connection was used */
2992 score = Curl_tvdiff(now, conn->now);
2994 if(score > highscore) {
2996 conn_candidate = conn;
3002 he = Curl_hash_next_element(&iter);
3005 return conn_candidate;
3009 * This function finds the connection in the connection
3010 * bundle that has been unused for the longest time.
3012 * Returns the pointer to the oldest idle connection, or NULL if none was
3015 static struct connectdata *
3016 find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
3017 struct connectbundle *bundle)
3019 struct curl_llist_element *curr;
3023 struct connectdata *conn_candidate = NULL;
3024 struct connectdata *conn;
3030 curr = bundle->conn_list->head;
3035 /* Set higher score for the age passed since the connection was used */
3036 score = Curl_tvdiff(now, conn->now);
3038 if(score > highscore) {
3040 conn_candidate = conn;
3046 return conn_candidate;
3050 * This function checks if given connection is dead and disconnects if so.
3051 * (That also removes it from the connection cache.)
3053 * Returns TRUE if the connection actually was dead and disconnected.
3055 static bool disconnect_if_dead(struct connectdata *conn,
3056 struct SessionHandle *data)
3058 size_t pipeLen = conn->send_pipe->size + conn->recv_pipe->size;
3059 if(!pipeLen && !conn->inuse) {
3060 /* The check for a dead socket makes sense only if there are no
3061 handles in pipeline and the connection isn't already marked in
3064 if(conn->handler->protocol & CURLPROTO_RTSP)
3065 /* RTSP is a special case due to RTP interleaving */
3066 dead = Curl_rtsp_connisdead(conn);
3068 dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
3072 infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
3074 /* disconnect resources */
3075 Curl_disconnect(conn, /* dead_connection */TRUE);
3083 * Wrapper to use disconnect_if_dead() function in Curl_conncache_foreach()
3087 static int call_disconnect_if_dead(struct connectdata *conn,
3090 struct SessionHandle* data = (struct SessionHandle*)param;
3091 disconnect_if_dead(conn, data);
3092 return 0; /* continue iteration */
3096 * This function scans the connection cache for half-open/dead connections,
3097 * closes and removes them.
3098 * The cleanup is done at most once per second.
3100 static void prune_dead_connections(struct SessionHandle *data)
3102 struct timeval now = Curl_tvnow();
3103 long elapsed = Curl_tvdiff(now, data->state.conn_cache->last_cleanup);
3105 if(elapsed >= 1000L) {
3106 Curl_conncache_foreach(data->state.conn_cache, data,
3107 call_disconnect_if_dead);
3108 data->state.conn_cache->last_cleanup = now;
3113 static size_t max_pipeline_length(struct Curl_multi *multi)
3115 return multi ? multi->max_pipeline_length : 0;
3120 * Given one filled in connection struct (named needle), this function should
3121 * detect if there already is one that has all the significant details
3122 * exactly the same and thus should be used instead.
3124 * If there is a match, this function returns TRUE - and has marked the
3125 * connection as 'in-use'. It must later be called with ConnectionDone() to
3126 * return back to 'idle' (unused) state.
3128 * The force_reuse flag is set if the connection must be used, even if
3129 * the pipelining strategy wants to open a new connection instead of reusing.
3132 ConnectionExists(struct SessionHandle *data,
3133 struct connectdata *needle,
3134 struct connectdata **usethis,
3138 struct connectdata *check;
3139 struct connectdata *chosen = 0;
3140 bool foundPendingCandidate = FALSE;
3141 bool canPipeline = IsPipeliningPossible(data, needle);
3142 struct connectbundle *bundle;
3145 bool wantNTLMhttp = ((data->state.authhost.want &
3146 (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
3147 (needle->handler->protocol & PROTO_FAMILY_HTTP));
3148 bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
3149 ((data->state.authproxy.want &
3150 (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
3151 (needle->handler->protocol & PROTO_FAMILY_HTTP)));
3154 *force_reuse = FALSE;
3157 /* We can't pipe if the site is blacklisted */
3158 if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
3159 canPipeline = FALSE;
3162 /* Look up the bundle with all the connections to this
3164 bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
3166 /* Max pipe length is zero (unlimited) for multiplexed connections */
3167 size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
3168 max_pipeline_length(data->multi):0;
3169 size_t best_pipe_len = max_pipe_len;
3170 struct curl_llist_element *curr;
3172 infof(data, "Found bundle for host %s: %p [%s]\n",
3173 needle->host.name, (void *)bundle,
3174 (bundle->multiuse== BUNDLE_PIPELINING?
3176 (bundle->multiuse== BUNDLE_MULTIPLEX?
3177 "can multiplex":"serially")));
3179 /* We can't pipe if we don't know anything about the server */
3181 if(bundle->multiuse <= BUNDLE_UNKNOWN) {
3182 if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
3183 infof(data, "Server doesn't support multi-use yet, wait\n");
3185 return FALSE; /* no re-use */
3188 infof(data, "Server doesn't support multi-use (yet)\n");
3189 canPipeline = FALSE;
3191 if((bundle->multiuse == BUNDLE_PIPELINING) &&
3192 !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
3193 /* not asked for, switch off */
3194 infof(data, "Could pipeline, but not asked to!\n");
3195 canPipeline = FALSE;
3197 else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
3198 !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
3199 infof(data, "Could multiplex, but not asked to!\n");
3200 canPipeline = FALSE;
3204 curr = bundle->conn_list->head;
3210 * Note that if we use a HTTP proxy, we check connections to that
3211 * proxy and not to the actual remote server.
3216 if(disconnect_if_dead(check, data))
3219 pipeLen = check->send_pipe->size + check->recv_pipe->size;
3223 if(!check->bits.multiplex) {
3224 /* If not multiplexing, make sure the pipe has only GET requests */
3225 struct SessionHandle* sh = gethandleathead(check->send_pipe);
3226 struct SessionHandle* rh = gethandleathead(check->recv_pipe);
3228 if(!IsPipeliningPossible(sh, check))
3232 if(!IsPipeliningPossible(rh, check))
3239 /* can only happen within multi handles, and means that another easy
3240 handle is using this connection */
3244 if(Curl_resolver_asynch()) {
3245 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
3246 completed yet and until then we don't re-use this connection */
3247 if(!check->ip_addr_str[0]) {
3249 "Connection #%ld is still name resolving, can't reuse\n",
3250 check->connection_id);
3255 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
3256 check->bits.close) {
3257 if(!check->bits.close)
3258 foundPendingCandidate = TRUE;
3259 /* Don't pick a connection that hasn't connected yet or that is going
3261 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
3262 check->connection_id);
3264 if(check->recv_pipe->size > 0) {
3266 "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
3267 check->connection_id);
3274 if((needle->handler->flags&PROTOPT_SSL) !=
3275 (check->handler->flags&PROTOPT_SSL))
3276 /* don't do mixed SSL and non-SSL connections */
3277 if(get_protocol_family(check->handler->protocol) !=
3278 needle->handler->protocol || !check->tls_upgraded)
3279 /* except protocols that have been upgraded via TLS */
3282 if(needle->handler->flags&PROTOPT_SSL) {
3283 if((data->set.ssl.verifypeer != check->verifypeer) ||
3284 (data->set.ssl.verifyhost != check->verifyhost))
3288 if(needle->bits.proxy != check->bits.proxy)
3289 /* don't do mixed proxy and non-proxy connections */
3292 if(!canPipeline && check->inuse)
3293 /* this request can't be pipelined but the checked connection is
3294 already in use so we skip it */
3297 if(needle->localdev || needle->localport) {
3298 /* If we are bound to a specific local end (IP+port), we must not
3299 re-use a random other one, although if we didn't ask for a
3300 particular one we can reuse one that was bound.
3302 This comparison is a bit rough and too strict. Since the input
3303 parameters can be specified in numerous ways and still end up the
3304 same it would take a lot of processing to make it really accurate.
3305 Instead, this matching will assume that re-uses of bound connections
3306 will most likely also re-use the exact same binding parameters and
3307 missing out a few edge cases shouldn't hurt anyone very much.
3309 if((check->localport != needle->localport) ||
3310 (check->localportrange != needle->localportrange) ||
3312 !needle->localdev ||
3313 strcmp(check->localdev, needle->localdev))
3317 if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
3318 /* This protocol requires credentials per connection,
3319 so verify that we're using the same name and password as well */
3320 if(!strequal(needle->user, check->user) ||
3321 !strequal(needle->passwd, check->passwd)) {
3322 /* one of them was different */
3327 if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
3328 (needle->bits.httpproxy && check->bits.httpproxy &&
3329 needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
3330 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3331 (needle->port == check->port))) {
3332 /* The requested connection does not use a HTTP proxy or it uses SSL or
3333 it is a non-SSL protocol tunneled over the same HTTP proxy name and
3335 if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
3336 (get_protocol_family(check->handler->protocol) ==
3337 needle->handler->protocol && check->tls_upgraded)) &&
3338 Curl_raw_equal(needle->host.name, check->host.name) &&
3339 needle->remote_port == check->remote_port) {
3340 /* The schemes match or the the protocol family is the same and the
3341 previous connection was TLS upgraded, and the hostname and host
3343 if(needle->handler->flags & PROTOPT_SSL) {
3344 /* This is a SSL connection so verify that we're using the same
3345 SSL options as well */
3346 if(!Curl_ssl_config_matches(&needle->ssl_config,
3347 &check->ssl_config)) {
3349 "Connection #%ld has different SSL parameters, "
3351 check->connection_id));
3354 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3355 foundPendingCandidate = TRUE;
3357 "Connection #%ld has not started SSL connect, "
3359 check->connection_id));
3366 else { /* The requested needle connection is using a proxy,
3367 is the checked one using the same host, port and type? */
3368 if(check->bits.proxy &&
3369 (needle->proxytype == check->proxytype) &&
3370 (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
3371 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3372 needle->port == check->port) {
3373 /* This is the same proxy connection, use it! */
3379 #if defined(USE_NTLM)
3380 /* If we are looking for an HTTP+NTLM connection, check if this is
3381 already authenticating with the right credentials. If not, keep
3382 looking so that we can reuse NTLM connections if
3383 possible. (Especially we must not reuse the same connection if
3384 partway through a handshake!) */
3386 if(!strequal(needle->user, check->user) ||
3387 !strequal(needle->passwd, check->passwd))
3390 else if(check->ntlm.state != NTLMSTATE_NONE) {
3391 /* Connection is using NTLM auth but we don't want NTLM */
3395 /* Same for Proxy NTLM authentication */
3396 if(wantProxyNTLMhttp) {
3397 if(!strequal(needle->proxyuser, check->proxyuser) ||
3398 !strequal(needle->proxypasswd, check->proxypasswd))
3401 else if(check->proxyntlm.state != NTLMSTATE_NONE) {
3402 /* Proxy connection is using NTLM auth but we don't want NTLM */
3406 if(wantNTLMhttp || wantProxyNTLMhttp) {
3407 /* Credentials are already checked, we can use this connection */
3411 (check->ntlm.state != NTLMSTATE_NONE)) ||
3412 (wantProxyNTLMhttp &&
3413 (check->proxyntlm.state != NTLMSTATE_NONE))) {
3414 /* We must use this connection, no other */
3415 *force_reuse = TRUE;
3419 /* Continue look up for a better connection */
3424 /* We can pipeline if we want to. Let's continue looking for
3425 the optimal connection to use, i.e the shortest pipe that is not
3429 /* We have the optimal connection. Let's stop looking. */
3434 /* We can't use the connection if the pipe is full */
3435 if(max_pipe_len && (pipeLen >= max_pipe_len)) {
3436 infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
3440 /* If multiplexed, make sure we don't go over concurrency limit */
3441 if(check->bits.multiplex) {
3442 /* Multiplexed connections can only be HTTP/2 for now */
3443 struct http_conn *httpc = &check->proto.httpc;
3444 if(pipeLen >= httpc->settings.max_concurrent_streams) {
3445 infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
3451 /* We can't use the connection if the pipe is penalized */
3452 if(Curl_pipeline_penalized(data, check)) {
3453 infof(data, "Penalized, skip\n");
3458 if(pipeLen < best_pipe_len) {
3459 /* This connection has a shorter pipe so far. We'll pick this
3460 and continue searching */
3462 best_pipe_len = pipeLen;
3467 /* When not pipelining (== multiplexed), we have a match here! */
3469 infof(data, "Multiplexed connection found!\n");
3474 /* We have found a connection. Let's stop searching. */
3484 return TRUE; /* yes, we found one to use! */
3487 if(foundPendingCandidate && data->set.pipewait) {
3489 "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
3493 return FALSE; /* no matching connecting exists */
3496 /* Mark the connection as 'idle', or close it if the cache is full.
3497 Returns TRUE if the connection is kept, or FALSE if it was closed. */
3499 ConnectionDone(struct SessionHandle *data, struct connectdata *conn)
3501 /* data->multi->maxconnects can be negative, deal with it. */
3502 size_t maxconnects =
3503 (data->multi->maxconnects < 0) ? data->multi->num_easy * 4:
3504 data->multi->maxconnects;
3505 struct connectdata *conn_candidate = NULL;
3507 /* Mark the current connection as 'unused' */
3508 conn->inuse = FALSE;
3510 if(maxconnects > 0 &&
3511 data->state.conn_cache->num_connections > maxconnects) {
3512 infof(data, "Connection cache is full, closing the oldest one.\n");
3514 conn_candidate = find_oldest_idle_connection(data);
3516 if(conn_candidate) {
3517 /* Set the connection's owner correctly */
3518 conn_candidate->data = data;
3520 /* the winner gets the honour of being disconnected */
3521 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
3525 return (conn_candidate == conn) ? FALSE : TRUE;
3528 /* after a TCP connection to the proxy has been verified, this function does
3529 the next magic step.
3531 Note: this function's sub-functions call failf()
3534 CURLcode Curl_connected_proxy(struct connectdata *conn,
3537 if(!conn->bits.proxy || sockindex)
3538 /* this magic only works for the primary socket as the secondary is used
3539 for FTP only and it has FTP specific magic in ftp.c */
3542 switch(conn->proxytype) {
3543 #ifndef CURL_DISABLE_PROXY
3544 case CURLPROXY_SOCKS5:
3545 case CURLPROXY_SOCKS5_HOSTNAME:
3546 return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3547 conn->host.name, conn->remote_port,
3550 case CURLPROXY_SOCKS4:
3551 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3552 conn->remote_port, FIRSTSOCKET, conn, FALSE);
3554 case CURLPROXY_SOCKS4A:
3555 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3556 conn->remote_port, FIRSTSOCKET, conn, TRUE);
3558 #endif /* CURL_DISABLE_PROXY */
3559 case CURLPROXY_HTTP:
3560 case CURLPROXY_HTTP_1_0:
3561 /* do nothing here. handled later. */
3565 } /* switch proxytype */
3571 * verboseconnect() displays verbose information after a connect
3573 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3574 void Curl_verboseconnect(struct connectdata *conn)
3576 if(conn->data->set.verbose)
3577 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3578 conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3579 conn->ip_addr_str, conn->port, conn->connection_id);
3583 int Curl_protocol_getsock(struct connectdata *conn,
3584 curl_socket_t *socks,
3587 if(conn->handler->proto_getsock)
3588 return conn->handler->proto_getsock(conn, socks, numsocks);
3589 return GETSOCK_BLANK;
3592 int Curl_doing_getsock(struct connectdata *conn,
3593 curl_socket_t *socks,
3596 if(conn && conn->handler->doing_getsock)
3597 return conn->handler->doing_getsock(conn, socks, numsocks);
3598 return GETSOCK_BLANK;
3602 * We are doing protocol-specific connecting and this is being called over and
3603 * over from the multi interface until the connection phase is done on
3607 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3610 CURLcode result=CURLE_OK;
3612 if(conn && conn->handler->connecting) {
3614 result = conn->handler->connecting(conn, done);
3623 * We are DOING this is being called over and over from the multi interface
3624 * until the DOING phase is done on protocol layer.
3627 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3629 CURLcode result=CURLE_OK;
3631 if(conn && conn->handler->doing) {
3633 result = conn->handler->doing(conn, done);
3642 * We have discovered that the TCP connection has been successful, we can now
3643 * proceed with some action.
3646 CURLcode Curl_protocol_connect(struct connectdata *conn,
3647 bool *protocol_done)
3649 CURLcode result=CURLE_OK;
3651 *protocol_done = FALSE;
3653 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
3654 /* We already are connected, get back. This may happen when the connect
3655 worked fine in the first call, like when we connect to a local server
3656 or proxy. Note that we don't know if the protocol is actually done.
3658 Unless this protocol doesn't have any protocol-connect callback, as
3659 then we know we're done. */
3660 if(!conn->handler->connecting)
3661 *protocol_done = TRUE;
3666 if(!conn->bits.protoconnstart) {
3668 result = Curl_proxy_connect(conn);
3672 if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
3673 (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
3674 /* when using an HTTP tunnel proxy, await complete tunnel establishment
3675 before proceeding further. Return CURLE_OK so we'll be called again */
3678 if(conn->handler->connect_it) {
3679 /* is there a protocol-specific connect() procedure? */
3681 /* Call the protocol-specific connect function */
3682 result = conn->handler->connect_it(conn, protocol_done);
3685 *protocol_done = TRUE;
3687 /* it has started, possibly even completed but that knowledge isn't stored
3690 conn->bits.protoconnstart = TRUE;
3693 return result; /* pass back status */
3697 * Helpers for IDNA convertions.
3699 static bool is_ASCII_name(const char *hostname)
3701 const unsigned char *ch = (const unsigned char*)hostname;
3712 * Check if characters in hostname is allowed in Top Level Domain.
3714 static bool tld_check_name(struct SessionHandle *data,
3715 const char *ace_hostname)
3718 char *uc_name = NULL;
3720 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3721 const char *tld_errmsg = "<no msg>";
3726 /* Convert (and downcase) ACE-name back into locale's character set */
3727 rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3728 if(rc != IDNA_SUCCESS)
3731 rc = tld_check_lz(uc_name, &err_pos, NULL);
3732 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3733 #ifdef HAVE_TLD_STRERROR
3734 if(rc != TLD_SUCCESS)
3735 tld_errmsg = tld_strerror((Tld_rc)rc);
3737 if(rc == TLD_INVALID)
3738 infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
3739 tld_errmsg, err_pos, uc_name[err_pos],
3740 uc_name[err_pos] & 255);
3741 else if(rc != TLD_SUCCESS)
3742 infof(data, "WARNING: TLD check for %s failed; %s\n",
3743 uc_name, tld_errmsg);
3744 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3747 if(rc != TLD_SUCCESS)
3755 * Perform any necessary IDN conversion of hostname
3757 static void fix_hostname(struct SessionHandle *data,
3758 struct connectdata *conn, struct hostname *host)
3765 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3769 /* set the name we use to display the host name */
3770 host->dispname = host->name;
3772 len = strlen(host->name);
3773 if(len && (host->name[len-1] == '.'))
3774 /* strip off a single trailing dot if present, primarily for SNI but
3775 there's no use for it */
3776 host->name[len-1]=0;
3778 /* Check name for non-ASCII and convert hostname to ACE form if we can */
3779 if(!is_ASCII_name(host->name)) {
3781 if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3782 char *ace_hostname = NULL;
3784 int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3785 infof(data, "Input domain encoded as `%s'\n",
3786 stringprep_locale_charset());
3787 if(rc == IDNA_SUCCESS) {
3788 /* tld_check_name() displays a warning if the host name contains
3789 "illegal" characters for this TLD */
3790 (void)tld_check_name(data, ace_hostname);
3792 host->encalloc = ace_hostname;
3793 /* change the name pointer to point to the encoded hostname */
3794 host->name = host->encalloc;
3797 infof(data, "Failed to convert %s to ACE; %s\n", host->name,
3798 Curl_idn_strerror(conn, rc));
3800 #elif defined(USE_WIN32_IDN)
3801 char *ace_hostname = NULL;
3803 if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
3804 host->encalloc = ace_hostname;
3805 /* change the name pointer to point to the encoded hostname */
3806 host->name = host->encalloc;
3809 infof(data, "Failed to convert %s to ACE;\n", host->name);
3811 infof(data, "IDN support not present, can't parse Unicode domains\n");
3817 * Frees data allocated by fix_hostname()
3819 static void free_fixed_hostname(struct hostname *host)
3821 #if defined(USE_LIBIDN)
3822 if(host->encalloc) {
3823 idn_free(host->encalloc); /* must be freed with idn_free() since this was
3824 allocated by libidn */
3825 host->encalloc = NULL;
3827 #elif defined(USE_WIN32_IDN)
3828 free(host->encalloc); /* must be freed withidn_free() since this was
3829 allocated by curl_win32_idn_to_ascii */
3830 host->encalloc = NULL;
3836 static void llist_dtor(void *user, void *element)
3844 * Allocate and initialize a new connectdata object.
3846 static struct connectdata *allocate_conn(struct SessionHandle *data)
3848 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3852 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
3853 already from start to avoid NULL
3854 situations and checks */
3856 /* and we setup a few fields in case we end up actually using this struct */
3858 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3859 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3860 conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
3861 conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
3862 conn->connection_id = -1; /* no ID */
3863 conn->port = -1; /* unknown at this point */
3864 conn->remote_port = -1; /* unknown */
3866 /* Default protocol-independent behavior doesn't support persistent
3867 connections, so we set this to force-close. Protocols that support
3868 this need to set this to FALSE in their "curl_do" functions. */
3869 connclose(conn, "Default to force-close");
3871 /* Store creation time to help future close decision making */
3872 conn->created = Curl_tvnow();
3874 conn->data = data; /* Setup the association between this connection
3875 and the SessionHandle */
3877 conn->proxytype = data->set.proxytype; /* type */
3879 #ifdef CURL_DISABLE_PROXY
3881 conn->bits.proxy = FALSE;
3882 conn->bits.httpproxy = FALSE;
3883 conn->bits.proxy_user_passwd = FALSE;
3884 conn->bits.tunnel_proxy = FALSE;
3886 #else /* CURL_DISABLE_PROXY */
3888 /* note that these two proxy bits are now just on what looks to be
3889 requested, they may be altered down the road */
3890 conn->bits.proxy = (data->set.str[STRING_PROXY] &&
3891 *data->set.str[STRING_PROXY])?TRUE:FALSE;
3892 conn->bits.httpproxy = (conn->bits.proxy &&
3893 (conn->proxytype == CURLPROXY_HTTP ||
3894 conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE;
3895 conn->bits.proxy_user_passwd =
3896 (NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE;
3897 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3899 #endif /* CURL_DISABLE_PROXY */
3901 conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE;
3902 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3903 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3905 conn->verifypeer = data->set.ssl.verifypeer;
3906 conn->verifyhost = data->set.ssl.verifyhost;
3908 conn->ip_version = data->set.ipver;
3910 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
3911 defined(NTLM_WB_ENABLED)
3912 conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
3913 conn->ntlm_auth_hlpr_pid = 0;
3914 conn->challenge_header = NULL;
3915 conn->response_header = NULL;
3918 if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
3919 !conn->master_buffer) {
3920 /* Allocate master_buffer to be used for HTTP/1 pipelining */
3921 conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3922 if(!conn->master_buffer)
3926 /* Initialize the pipeline lists */
3927 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3928 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3929 if(!conn->send_pipe || !conn->recv_pipe)
3933 conn->data_prot = PROT_CLEAR;
3936 /* Store the local bind parameters that will be used for this connection */
3937 if(data->set.str[STRING_DEVICE]) {
3938 conn->localdev = strdup(data->set.str[STRING_DEVICE]);
3942 conn->localportrange = data->set.localportrange;
3943 conn->localport = data->set.localport;
3945 /* the close socket stuff needs to be copied to the connection struct as
3946 it may live on without (this specific) SessionHandle */
3947 conn->fclosesocket = data->set.fclosesocket;
3948 conn->closesocket_client = data->set.closesocket_client;
3953 Curl_llist_destroy(conn->send_pipe, NULL);
3954 Curl_llist_destroy(conn->recv_pipe, NULL);
3956 conn->send_pipe = NULL;
3957 conn->recv_pipe = NULL;
3959 free(conn->master_buffer);
3960 free(conn->localdev);
3965 static CURLcode findprotocol(struct SessionHandle *data,
3966 struct connectdata *conn,
3967 const char *protostr)
3969 const struct Curl_handler * const *pp;
3970 const struct Curl_handler *p;
3972 /* Scan protocol handler table and match against 'protostr' to set a few
3973 variables based on the URL. Now that the handler may be changed later
3974 when the protocol specific setup function is called. */
3975 for(pp = protocols; (p = *pp) != NULL; pp++) {
3976 if(Curl_raw_equal(p->scheme, protostr)) {
3977 /* Protocol found in table. Check if allowed */
3978 if(!(data->set.allowed_protocols & p->protocol))
3982 /* it is allowed for "normal" request, now do an extra check if this is
3983 the result of a redirect */
3984 if(data->state.this_is_a_follow &&
3985 !(data->set.redir_protocols & p->protocol))
3989 /* Perform setup complement if some. */
3990 conn->handler = conn->given = p;
3992 /* 'port' and 'remote_port' are set in setup_connection_internals() */
3998 /* The protocol was not found in the table, but we don't have to assign it
3999 to anything since it is already assigned to a dummy-struct in the
4000 create_conn() function when the connectdata struct is allocated. */
4001 failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
4004 return CURLE_UNSUPPORTED_PROTOCOL;
4008 * Parse URL and fill in the relevant members of the connection struct.
4010 static CURLcode parseurlandfillconn(struct SessionHandle *data,
4011 struct connectdata *conn,
4013 char **userp, char **passwdp,
4018 char *path = data->state.path;
4021 char protobuf[16] = "";
4022 const char *protop = "";
4024 bool rebuild_url = FALSE;
4026 *prot_missing = FALSE;
4028 /* We might pass the entire URL into the request so we need to make sure
4029 * there are no bad characters in there.*/
4030 if(strpbrk(data->change.url, "\r\n")) {
4031 failf(data, "Illegal characters found in URL");
4032 return CURLE_URL_MALFORMAT;
4035 /*************************************************************
4038 * We need to parse the url even when using the proxy, because we will need
4039 * the hostname and port in case we are trying to SSL connect through the
4040 * proxy -- and we don't know if we will need to use SSL until we parse the
4042 ************************************************************/
4043 if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
4045 Curl_raw_equal(protobuf, "file")) {
4046 if(path[0] == '/' && path[1] == '/') {
4047 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
4048 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
4049 * file://localhost/<path> is similar to how other schemes treat missing
4050 * hostnames. See RFC 1808. */
4052 /* This cannot be done with strcpy() in a portable manner, since the
4053 memory areas overlap! */
4054 memmove(path, path + 2, strlen(path + 2)+1);
4057 * we deal with file://<host>/<path> differently since it supports no
4058 * hostname other than "localhost" and "127.0.0.1", which is unique among
4059 * the URL protocols specified in RFC 1738
4061 if(path[0] != '/') {
4062 /* the URL included a host name, we ignore host names in file:// URLs
4063 as the standards don't define what to do with them */
4064 char *ptr=strchr(path, '/');
4066 /* there was a slash present
4068 RFC1738 (section 3.1, page 5) says:
4070 The rest of the locator consists of data specific to the scheme,
4071 and is known as the "url-path". It supplies the details of how the
4072 specified resource can be accessed. Note that the "/" between the
4073 host (or port) and the url-path is NOT part of the url-path.
4075 As most agents use file://localhost/foo to get '/foo' although the
4076 slash preceding foo is a separator and not a slash for the path,
4077 a URL as file://localhost//foo must be valid as well, to refer to
4078 the same file with an absolute path.
4081 if(ptr[1] && ('/' == ptr[1]))
4082 /* if there was two slashes, we skip the first one as that is then
4083 used truly as a separator */
4086 /* This cannot be made with strcpy, as the memory chunks overlap! */
4087 memmove(path, ptr, strlen(ptr)+1);
4091 protop = "file"; /* protocol string */
4097 if(2 > sscanf(data->change.url,
4098 "%15[^\n:]://%[^\n/?]%[^\n]",
4100 conn->host.name, path)) {
4103 * The URL was badly formatted, let's try the browser-style _without_
4104 * protocol specified like 'http://'.
4106 rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
4109 * We couldn't even get this format.
4110 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
4111 * assigned, but the return value is EOF!
4113 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
4114 if(!(rc == -1 && *conn->host.name))
4117 failf(data, "<url> malformed");
4118 return CURLE_URL_MALFORMAT;
4123 * Since there was no protocol part specified in the URL use the
4124 * user-specified default protocol. If we weren't given a default make a
4125 * guess by matching some protocols against the host's outermost
4126 * sub-domain name. Finally if there was no match use HTTP.
4129 protop = data->set.str[STRING_DEFAULT_PROTOCOL];
4131 /* Note: if you add a new protocol, please update the list in
4132 * lib/version.c too! */
4133 if(checkprefix("FTP.", conn->host.name))
4135 else if(checkprefix("DICT.", conn->host.name))
4137 else if(checkprefix("LDAP.", conn->host.name))
4139 else if(checkprefix("IMAP.", conn->host.name))
4141 else if(checkprefix("SMTP.", conn->host.name))
4143 else if(checkprefix("POP3.", conn->host.name))
4149 *prot_missing = TRUE; /* not given in URL */
4155 /* We search for '?' in the host name (but only on the right side of a
4156 * @-letter to allow ?-letters in username and password) to handle things
4157 * like http://example.com?param= (notice the missing '/').
4159 at = strchr(conn->host.name, '@');
4161 query = strchr(at+1, '?');
4163 query = strchr(conn->host.name, '?');
4166 /* We must insert a slash before the '?'-letter in the URL. If the URL had
4167 a slash after the '?', that is where the path currently begins and the
4168 '?string' is still part of the host name.
4170 We must move the trailing part from the host name and put it first in
4171 the path. And have it all prefixed with a slash.
4174 size_t hostlen = strlen(query);
4175 size_t pathlen = strlen(path);
4177 /* move the existing path plus the zero byte forward, to make room for
4178 the host-name part */
4179 memmove(path+hostlen+1, path, pathlen+1);
4181 /* now copy the trailing host part in front of the existing path */
4182 memcpy(path+1, query, hostlen);
4184 path[0]='/'; /* prepend the missing slash */
4187 *query=0; /* now cut off the hostname at the ? */
4190 /* if there's no path set, use a single slash */
4195 /* If the URL is malformatted (missing a '/' after hostname before path) we
4196 * insert a slash here. The only letter except '/' we accept to start a path
4199 if(path[0] == '?') {
4200 /* We need this function to deal with overlapping memory areas. We know
4201 that the memory area 'path' points to is 'urllen' bytes big and that
4202 is bigger than the path. Use +1 to move the zero byte too. */
4203 memmove(&path[1], path, strlen(path)+1);
4207 else if(!data->set.path_as_is) {
4208 /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
4209 char *newp = Curl_dedotdotify(path);
4211 return CURLE_OUT_OF_MEMORY;
4213 if(strcmp(newp, path)) {
4215 free(data->state.pathbuffer);
4216 data->state.pathbuffer = newp;
4217 data->state.path = newp;
4225 * "rebuild_url" means that one or more URL components have been modified so
4226 * we need to generate an updated full version. We need the corrected URL
4227 * when communicating over HTTP proxy and we don't know at this point if
4228 * we're using a proxy or not.
4233 size_t plen = strlen(path); /* new path, should be 1 byte longer than
4235 size_t urllen = strlen(data->change.url); /* original URL length */
4237 size_t prefixlen = strlen(conn->host.name);
4240 prefixlen += strlen(protop) + strlen("://");
4242 reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */
4244 return CURLE_OUT_OF_MEMORY;
4246 /* copy the prefix */
4247 memcpy(reurl, data->change.url, prefixlen);
4249 /* append the trailing piece + zerobyte */
4250 memcpy(&reurl[prefixlen], path, plen + 1);
4252 /* possible free the old one */
4253 if(data->change.url_alloc) {
4254 Curl_safefree(data->change.url);
4255 data->change.url_alloc = FALSE;
4258 infof(data, "Rebuilt URL to: %s\n", reurl);
4260 data->change.url = reurl;
4261 data->change.url_alloc = TRUE; /* free this later */
4265 * Parse the login details from the URL and strip them out of
4268 result = parse_url_login(data, conn, userp, passwdp, optionsp);
4272 if(conn->host.name[0] == '[') {
4273 /* This looks like an IPv6 address literal. See if there is an address
4274 scope if there is no location header */
4275 char *percent = strchr(conn->host.name, '%');
4277 unsigned int identifier_offset = 3;
4279 unsigned long scope;
4280 if(strncmp("%25", percent, 3) != 0) {
4282 "Please URL encode %% as %%25, see RFC 6874.\n");
4283 identifier_offset = 1;
4285 scope = strtoul(percent + identifier_offset, &endp, 10);
4287 /* The address scope was well formed. Knock it out of the
4289 memmove(percent, endp, strlen(endp)+1);
4290 conn->scope_id = (unsigned int)scope;
4293 /* Zone identifier is not numeric */
4294 #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
4295 char ifname[IFNAMSIZ + 2];
4296 char *square_bracket;
4297 unsigned int scopeidx = 0;
4298 strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
4299 /* Ensure nullbyte termination */
4300 ifname[IFNAMSIZ + 1] = '\0';
4301 square_bracket = strchr(ifname, ']');
4302 if(square_bracket) {
4304 *square_bracket = '\0';
4305 scopeidx = if_nametoindex(ifname);
4307 infof(data, "Invalid network interface: %s; %s\n", ifname,
4312 char *p = percent + identifier_offset + strlen(ifname);
4314 /* Remove zone identifier from hostname */
4315 memmove(percent, p, strlen(p) + 1);
4316 conn->scope_id = scopeidx;
4319 #endif /* HAVE_NET_IF_H && IFNAMSIZ */
4320 infof(data, "Invalid IPv6 address format\n");
4325 if(data->set.scope_id)
4326 /* Override any scope that was set above. */
4327 conn->scope_id = data->set.scope_id;
4329 /* Remove the fragment part of the path. Per RFC 2396, this is always the
4330 last part of the URI. We are looking for the first '#' so that we deal
4331 gracefully with non conformant URI such as http://example.com#foo#bar. */
4332 fragment = strchr(path, '#');
4336 /* we know the path part ended with a fragment, so we know the full URL
4337 string does too and we need to cut it off from there so it isn't used
4339 fragment = strchr(data->change.url, '#');
4345 * So if the URL was A://B/C#D,
4347 * conn->host.name is B
4348 * data->state.path is /C
4351 return findprotocol(data, conn, protop);
4355 * If we're doing a resumed transfer, we need to setup our stuff
4358 static CURLcode setup_range(struct SessionHandle *data)
4360 struct UrlState *s = &data->state;
4361 s->resume_from = data->set.set_resume_from;
4362 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
4363 if(s->rangestringalloc)
4367 s->range = aprintf("%" CURL_FORMAT_CURL_OFF_TU "-", s->resume_from);
4369 s->range = strdup(data->set.str[STRING_SET_RANGE]);
4371 s->rangestringalloc = (s->range)?TRUE:FALSE;
4374 return CURLE_OUT_OF_MEMORY;
4376 /* tell ourselves to fetch this range */
4377 s->use_range = TRUE; /* enable range download */
4380 s->use_range = FALSE; /* disable range download */
4387 * setup_connection_internals() -
4389 * Setup connection internals specific to the requested protocol in the
4390 * SessionHandle. This is inited and setup before the connection is made but
4391 * is about the particular protocol that is to be used.
4393 * This MUST get called after proxy magic has been figured out.
4395 static CURLcode setup_connection_internals(struct connectdata *conn)
4397 const struct Curl_handler * p;
4399 struct SessionHandle *data = conn->data;
4401 /* in some case in the multi state-machine, we go back to the CONNECT state
4402 and then a second (or third or...) call to this function will be made
4403 without doing a DISCONNECT or DONE in between (since the connection is
4404 yet in place) and therefore this function needs to first make sure
4405 there's no lingering previous data allocated. */
4406 Curl_free_request_state(data);
4408 memset(&data->req, 0, sizeof(struct SingleRequest));
4409 data->req.maxdownload = -1;
4411 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
4413 /* Perform setup complement if some. */
4416 if(p->setup_connection) {
4417 result = (*p->setup_connection)(conn);
4422 p = conn->handler; /* May have changed. */
4426 /* we check for -1 here since if proxy was detected already, this
4427 was very likely already set to the proxy port */
4428 conn->port = p->defport;
4430 /* only if remote_port was not already parsed off the URL we use the
4431 default port number */
4432 if(conn->remote_port < 0)
4433 conn->remote_port = (unsigned short)conn->given->defport;
4439 * Curl_free_request_state() should free temp data that was allocated in the
4440 * SessionHandle for this single request.
4443 void Curl_free_request_state(struct SessionHandle *data)
4445 Curl_safefree(data->req.protop);
4446 Curl_safefree(data->req.newurl);
4450 #ifndef CURL_DISABLE_PROXY
4451 /****************************************************************
4452 * Checks if the host is in the noproxy list. returns true if it matches
4453 * and therefore the proxy should NOT be used.
4454 ****************************************************************/
4455 static bool check_noproxy(const char* name, const char* no_proxy)
4457 /* no_proxy=domain1.dom,host.domain2.dom
4458 * (a comma-separated list of hosts which should
4459 * not be proxied, or an asterisk to override
4460 * all proxy variables)
4464 const char* separator = ", ";
4465 size_t no_proxy_len;
4469 if(no_proxy && no_proxy[0]) {
4470 if(Curl_raw_equal("*", no_proxy)) {
4474 /* NO_PROXY was specified and it wasn't just an asterisk */
4476 no_proxy_len = strlen(no_proxy);
4477 endptr = strchr(name, ':');
4479 namelen = endptr - name;
4481 namelen = strlen(name);
4483 for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
4484 while(tok_start < no_proxy_len &&
4485 strchr(separator, no_proxy[tok_start]) != NULL) {
4486 /* Look for the beginning of the token. */
4490 if(tok_start == no_proxy_len)
4491 break; /* It was all trailing separator chars, no more tokens. */
4493 for(tok_end = tok_start; tok_end < no_proxy_len &&
4494 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
4495 /* Look for the end of the token. */
4498 /* To match previous behaviour, where it was necessary to specify
4499 * ".local.com" to prevent matching "notlocal.com", we will leave
4502 if(no_proxy[tok_start] == '.')
4505 if((tok_end - tok_start) <= namelen) {
4506 /* Match the last part of the name to the domain we are checking. */
4507 const char *checkn = name + namelen - (tok_end - tok_start);
4508 if(Curl_raw_nequal(no_proxy + tok_start, checkn,
4509 tok_end - tok_start)) {
4510 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
4511 /* We either have an exact match, or the previous character is a .
4512 * so it is within the same domain, so no proxy for this host.
4517 } /* if((tok_end - tok_start) <= namelen) */
4518 } /* for(tok_start = 0; tok_start < no_proxy_len;
4519 tok_start = tok_end + 1) */
4520 } /* NO_PROXY was specified and it wasn't just an asterisk */
4525 /****************************************************************
4526 * Detect what (if any) proxy to use. Remember that this selects a host
4527 * name and is not limited to HTTP proxies only.
4528 * The returned pointer must be freed by the caller (unless NULL)
4529 ****************************************************************/
4530 static char *detect_proxy(struct connectdata *conn)
4534 #ifndef CURL_DISABLE_HTTP
4535 /* If proxy was not specified, we check for default proxy environment
4536 * variables, to enable i.e Lynx compliance:
4538 * http_proxy=http://some.server.dom:port/
4539 * https_proxy=http://some.server.dom:port/
4540 * ftp_proxy=http://some.server.dom:port/
4541 * no_proxy=domain1.dom,host.domain2.dom
4542 * (a comma-separated list of hosts which should
4543 * not be proxied, or an asterisk to override
4544 * all proxy variables)
4545 * all_proxy=http://some.server.dom:port/
4546 * (seems to exist for the CERN www lib. Probably
4547 * the first to check for.)
4549 * For compatibility, the all-uppercase versions of these variables are
4550 * checked if the lowercase versions don't exist.
4552 char *no_proxy=NULL;
4553 char proxy_env[128];
4555 no_proxy=curl_getenv("no_proxy");
4557 no_proxy=curl_getenv("NO_PROXY");
4559 if(!check_noproxy(conn->host.name, no_proxy)) {
4560 /* It was not listed as without proxy */
4561 const char *protop = conn->handler->scheme;
4562 char *envp = proxy_env;
4565 /* Now, build <protocol>_proxy and check for such a one to use */
4567 *envp++ = (char)tolower((int)*protop++);
4570 strcpy(envp, "_proxy");
4572 /* read the protocol proxy: */
4573 prox=curl_getenv(proxy_env);
4576 * We don't try the uppercase version of HTTP_PROXY because of
4579 * When curl is used in a webserver application
4580 * environment (cgi or php), this environment variable can
4581 * be controlled by the web server user by setting the
4582 * http header 'Proxy:' to some value.
4584 * This can cause 'internal' http/ftp requests to be
4585 * arbitrarily redirected by any external attacker.
4587 if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4588 /* There was no lowercase variable, try the uppercase version: */
4589 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4590 prox=curl_getenv(proxy_env);
4594 proxy = prox; /* use this */
4596 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4598 proxy=curl_getenv("ALL_PROXY");
4600 } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4604 #else /* !CURL_DISABLE_HTTP */
4607 #endif /* CURL_DISABLE_HTTP */
4613 * If this is supposed to use a proxy, we need to figure out the proxy
4614 * host name, so that we can re-use an existing connection
4615 * that may exist registered to the same proxy host.
4617 static CURLcode parse_proxy(struct SessionHandle *data,
4618 struct connectdata *conn, char *proxy)
4623 /* We use 'proxyptr' to point to the proxy name from now on... */
4628 /* We do the proxy host string parsing here. We want the host name and the
4629 * port name. Accept a protocol:// prefix
4632 /* Parse the protocol part if present */
4633 endofprot = strstr(proxy, "://");
4635 proxyptr = endofprot+3;
4636 if(checkprefix("socks5h", proxy))
4637 conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
4638 else if(checkprefix("socks5", proxy))
4639 conn->proxytype = CURLPROXY_SOCKS5;
4640 else if(checkprefix("socks4a", proxy))
4641 conn->proxytype = CURLPROXY_SOCKS4A;
4642 else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
4643 conn->proxytype = CURLPROXY_SOCKS4;
4644 /* Any other xxx:// : change to http proxy */
4647 proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
4649 /* Is there a username and password given in this proxy url? */
4650 atsign = strchr(proxyptr, '@');
4652 char *proxyuser = NULL;
4653 char *proxypasswd = NULL;
4655 parse_login_details(proxyptr, atsign - proxyptr,
4656 &proxyuser, &proxypasswd, NULL);
4658 /* found user and password, rip them out. note that we are
4659 unescaping them, as there is otherwise no way to have a
4660 username or password with reserved characters like ':' in
4662 Curl_safefree(conn->proxyuser);
4663 if(proxyuser && strlen(proxyuser) < MAX_CURL_USER_LENGTH)
4664 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4666 conn->proxyuser = strdup("");
4668 if(!conn->proxyuser)
4669 result = CURLE_OUT_OF_MEMORY;
4671 Curl_safefree(conn->proxypasswd);
4672 if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
4673 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4675 conn->proxypasswd = strdup("");
4677 if(!conn->proxypasswd)
4678 result = CURLE_OUT_OF_MEMORY;
4682 conn->bits.proxy_user_passwd = TRUE; /* enable it */
4683 atsign++; /* the right side of the @-letter */
4685 proxyptr = atsign; /* now use this instead */
4696 /* start scanning for port number at this point */
4699 /* detect and extract RFC6874-style IPv6-addresses */
4700 if(*proxyptr == '[') {
4701 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4702 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
4705 /* There might be a zone identifier */
4706 if(strncmp("%25", ptr, 3))
4707 infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
4709 /* Allow unresered characters as defined in RFC 3986 */
4710 while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
4711 (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
4715 /* yeps, it ended nicely with a bracket as well */
4718 infof(data, "Invalid IPv6 address format\n");
4720 /* Note that if this didn't end with a bracket, we still advanced the
4721 * proxyptr first, but I can't see anything wrong with that as no host
4722 * name nor a numeric can legally start with a bracket.
4726 /* Get port number off proxy.server.com:1080 */
4727 prox_portno = strchr(portptr, ':');
4731 *prox_portno = 0x0; /* cut off number from host name */
4733 /* now set the local port number */
4734 port = strtol(prox_portno, &endp, 10);
4735 if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
4737 /* meant to detect for example invalid IPv6 numerical addresses without
4738 brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
4739 because we then allow "URL style" with the number followed by a
4740 slash, used in curl test cases already. Space is also an acceptable
4741 terminating symbol. */
4742 infof(data, "No valid port number in proxy string (%s)\n",
4749 if(proxyptr[0]=='/')
4750 /* If the first character in the proxy string is a slash, fail
4751 immediately. The following code will otherwise clear the string which
4752 will lead to code running as if no proxy was set! */
4753 return CURLE_COULDNT_RESOLVE_PROXY;
4755 /* without a port number after the host name, some people seem to use
4756 a slash so we strip everything from the first slash */
4757 atsign = strchr(proxyptr, '/');
4759 *atsign = 0x0; /* cut off path part from host name */
4761 if(data->set.proxyport)
4762 /* None given in the proxy string, then get the default one if it is
4764 conn->port = data->set.proxyport;
4767 /* now, clone the cleaned proxy host name */
4768 conn->proxy.rawalloc = strdup(proxyptr);
4769 conn->proxy.name = conn->proxy.rawalloc;
4771 if(!conn->proxy.rawalloc)
4772 return CURLE_OUT_OF_MEMORY;
4778 * Extract the user and password from the authentication string
4780 static CURLcode parse_proxy_auth(struct SessionHandle *data,
4781 struct connectdata *conn)
4783 char proxyuser[MAX_CURL_USER_LENGTH]="";
4784 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4786 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4787 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4788 MAX_CURL_USER_LENGTH);
4789 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4791 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4792 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4793 MAX_CURL_PASSWORD_LENGTH);
4794 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4797 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4798 if(!conn->proxyuser)
4799 return CURLE_OUT_OF_MEMORY;
4801 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4802 if(!conn->proxypasswd)
4803 return CURLE_OUT_OF_MEMORY;
4807 #endif /* CURL_DISABLE_PROXY */
4812 * Parse the login details (user name, password and options) from the URL and
4813 * strip them out of the host name
4815 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4818 * Outputs: (almost :- all currently undefined)
4819 * conn->bits.user_passwd - non-zero if non-default passwords exist
4820 * user - non-zero length if defined
4821 * passwd - non-zero length if defined
4822 * options - non-zero length if defined
4823 * conn->host.name - remove user name and password
4825 static CURLcode parse_url_login(struct SessionHandle *data,
4826 struct connectdata *conn,
4827 char **user, char **passwd, char **options)
4829 CURLcode result = CURLE_OK;
4831 char *passwdp = NULL;
4832 char *optionsp = NULL;
4834 /* At this point, we're hoping all the other special cases have
4835 * been taken care of, so conn->host.name is at most
4836 * [user[:password][;options]]@]hostname
4838 * We need somewhere to put the embedded details, so do that first.
4841 char *ptr = strchr(conn->host.name, '@');
4842 char *login = conn->host.name;
4844 DEBUGASSERT(!**user);
4845 DEBUGASSERT(!**passwd);
4846 DEBUGASSERT(!**options);
4851 /* We will now try to extract the
4852 * possible login information in a string like:
4853 * ftp://user:password@ftp.my.site:8021/README */
4854 conn->host.name = ++ptr;
4856 /* So the hostname is sane. Only bother interpreting the
4857 * results if we could care. It could still be wasted
4858 * work because it might be overtaken by the programmatically
4859 * set user/passwd, but doing that first adds more cases here :-(
4862 if(data->set.use_netrc == CURL_NETRC_REQUIRED)
4865 /* We could use the login information in the URL so extract it */
4866 result = parse_login_details(login, ptr - login - 1,
4867 &userp, &passwdp, &optionsp);
4874 /* We have a user in the URL */
4875 conn->bits.userpwd_in_url = TRUE;
4876 conn->bits.user_passwd = TRUE; /* enable user+password */
4878 /* Decode the user */
4879 newname = curl_easy_unescape(data, userp, 0, NULL);
4881 result = CURLE_OUT_OF_MEMORY;
4890 /* We have a password in the URL so decode it */
4891 char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
4893 result = CURLE_OUT_OF_MEMORY;
4898 *passwd = newpasswd;
4902 /* We have an options list in the URL so decode it */
4903 char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
4905 result = CURLE_OUT_OF_MEMORY;
4910 *options = newoptions;
4924 * parse_login_details()
4926 * This is used to parse a login string for user name, password and options in
4927 * the following formats:
4931 * user:password;options
4933 * user;options:password
4941 * login [in] - The login string.
4942 * len [in] - The length of the login string.
4943 * userp [in/out] - The address where a pointer to newly allocated memory
4944 * holding the user will be stored upon completion.
4945 * passdwp [in/out] - The address where a pointer to newly allocated memory
4946 * holding the password will be stored upon completion.
4947 * optionsp [in/out] - The address where a pointer to newly allocated memory
4948 * holding the options will be stored upon completion.
4950 * Returns CURLE_OK on success.
4952 static CURLcode parse_login_details(const char *login, const size_t len,
4953 char **userp, char **passwdp,
4956 CURLcode result = CURLE_OK;
4960 const char *psep = NULL;
4961 const char *osep = NULL;
4966 /* Attempt to find the password separator */
4968 psep = strchr(login, ':');
4970 /* Within the constraint of the login string */
4971 if(psep >= login + len)
4975 /* Attempt to find the options separator */
4977 osep = strchr(login, ';');
4979 /* Within the constraint of the login string */
4980 if(osep >= login + len)
4984 /* Calculate the portion lengths */
4986 (size_t)(osep && psep > osep ? osep - login : psep - login) :
4987 (osep ? (size_t)(osep - login) : len));
4989 (osep && osep > psep ? (size_t)(osep - psep) :
4990 (size_t)(login + len - psep)) - 1 : 0);
4992 (psep && psep > osep ? (size_t)(psep - osep) :
4993 (size_t)(login + len - osep)) - 1 : 0);
4995 /* Allocate the user portion buffer */
4997 ubuf = malloc(ulen + 1);
4999 result = CURLE_OUT_OF_MEMORY;
5002 /* Allocate the password portion buffer */
5003 if(!result && passwdp && plen) {
5004 pbuf = malloc(plen + 1);
5007 result = CURLE_OUT_OF_MEMORY;
5011 /* Allocate the options portion buffer */
5012 if(!result && optionsp && olen) {
5013 obuf = malloc(olen + 1);
5017 result = CURLE_OUT_OF_MEMORY;
5022 /* Store the user portion if necessary */
5024 memcpy(ubuf, login, ulen);
5026 Curl_safefree(*userp);
5030 /* Store the password portion if necessary */
5032 memcpy(pbuf, psep + 1, plen);
5034 Curl_safefree(*passwdp);
5038 /* Store the options portion if necessary */
5040 memcpy(obuf, osep + 1, olen);
5042 Curl_safefree(*optionsp);
5050 /*************************************************************
5051 * Figure out the remote port number and fix it in the URL
5053 * No matter if we use a proxy or not, we have to figure out the remote
5054 * port number of various reasons.
5056 * To be able to detect port number flawlessly, we must not confuse them
5057 * IPv6-specified addresses in the [0::1] style. (RFC2732)
5059 * The conn->host.name is currently [user:passwd@]host[:port] where host
5060 * could be a hostname, IPv4 address or IPv6 address.
5062 * The port number embedded in the URL is replaced, if necessary.
5063 *************************************************************/
5064 static CURLcode parse_remote_port(struct SessionHandle *data,
5065 struct connectdata *conn)
5070 /* Note that at this point, the IPv6 address cannot contain any scope
5071 suffix as that has already been removed in the parseurlandfillconn()
5073 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
5075 (']' == endbracket)) {
5076 /* this is a RFC2732-style specified IP-address */
5077 conn->bits.ipv6_ip = TRUE;
5079 conn->host.name++; /* skip over the starting bracket */
5080 portptr = strchr(conn->host.name, ']');
5082 *portptr++ = '\0'; /* zero terminate, killing the bracket */
5084 portptr = NULL; /* no port number available */
5089 struct in6_addr in6;
5090 if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
5091 /* This is a numerical IPv6 address, meaning this is a wrongly formatted
5093 failf(data, "IPv6 numerical address used in URL without brackets");
5094 return CURLE_URL_MALFORMAT;
5098 portptr = strrchr(conn->host.name, ':');
5101 if(data->set.use_port && data->state.allow_port) {
5102 /* if set, we use this and ignore the port possibly given in the URL */
5103 conn->remote_port = (unsigned short)data->set.use_port;
5105 *portptr = '\0'; /* cut off the name there anyway - if there was a port
5106 number - since the port number is to be ignored! */
5107 if(conn->bits.httpproxy) {
5108 /* we need to create new URL with the new port number */
5112 if(conn->bits.type_set)
5113 snprintf(type, sizeof(type), ";type=%c",
5114 data->set.prefer_ascii?'A':
5115 (data->set.ftp_list_only?'D':'I'));
5118 * This synthesized URL isn't always right--suffixes like ;type=A are
5119 * stripped off. It would be better to work directly from the original
5120 * URL and simply replace the port part of it.
5122 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
5123 conn->bits.ipv6_ip?"[":"", conn->host.name,
5124 conn->bits.ipv6_ip?"]":"", conn->remote_port,
5125 data->state.slash_removed?"/":"", data->state.path,
5128 return CURLE_OUT_OF_MEMORY;
5130 if(data->change.url_alloc) {
5131 Curl_safefree(data->change.url);
5132 data->change.url_alloc = FALSE;
5135 data->change.url = url;
5136 data->change.url_alloc = TRUE;
5140 /* no CURLOPT_PORT given, extract the one from the URL */
5145 port=strtol(portptr+1, &rest, 10); /* Port number must be decimal */
5147 if((port < 0) || (port > 0xffff)) {
5148 /* Single unix standard says port numbers are 16 bits long */
5149 failf(data, "Port number out of range");
5150 return CURLE_URL_MALFORMAT;
5153 else if(rest != &portptr[1]) {
5154 *portptr = '\0'; /* cut off the name there */
5155 conn->remote_port = curlx_ultous(port);
5158 /* Browser behavior adaptation. If there's a colon with no digits after,
5159 just cut off the name there which makes us ignore the colon and just
5160 use the default port. Firefox and Chrome both do that. */
5167 * Override the login details from the URL with that in the CURLOPT_USERPWD
5168 * option or a .netrc file, if applicable.
5170 static CURLcode override_login(struct SessionHandle *data,
5171 struct connectdata *conn,
5172 char **userp, char **passwdp, char **optionsp)
5174 if(data->set.str[STRING_USERNAME]) {
5176 *userp = strdup(data->set.str[STRING_USERNAME]);
5178 return CURLE_OUT_OF_MEMORY;
5181 if(data->set.str[STRING_PASSWORD]) {
5183 *passwdp = strdup(data->set.str[STRING_PASSWORD]);
5185 return CURLE_OUT_OF_MEMORY;
5188 if(data->set.str[STRING_OPTIONS]) {
5190 *optionsp = strdup(data->set.str[STRING_OPTIONS]);
5192 return CURLE_OUT_OF_MEMORY;
5195 conn->bits.netrc = FALSE;
5196 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
5197 int ret = Curl_parsenetrc(conn->host.name,
5199 data->set.str[STRING_NETRC_FILE]);
5201 infof(data, "Couldn't find host %s in the "
5202 DOT_CHAR "netrc file; using defaults\n",
5206 return CURLE_OUT_OF_MEMORY;
5209 /* set bits.netrc TRUE to remember that we got the name from a .netrc
5210 file, so that it is safe to use even if we followed a Location: to a
5211 different host or similar. */
5212 conn->bits.netrc = TRUE;
5214 conn->bits.user_passwd = TRUE; /* enable user+password */
5222 * Set the login details so they're available in the connection
5224 static CURLcode set_login(struct connectdata *conn,
5225 const char *user, const char *passwd,
5226 const char *options)
5228 CURLcode result = CURLE_OK;
5230 /* If our protocol needs a password and we have none, use the defaults */
5231 if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
5232 /* Store the default user */
5233 conn->user = strdup(CURL_DEFAULT_USER);
5235 /* Store the default password */
5237 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
5239 conn->passwd = NULL;
5241 /* This is the default password, so DON'T set conn->bits.user_passwd */
5244 /* Store the user, zero-length if not set */
5245 conn->user = strdup(user);
5247 /* Store the password (only if user is present), zero-length if not set */
5249 conn->passwd = strdup(passwd);
5251 conn->passwd = NULL;
5254 if(!conn->user || !conn->passwd)
5255 result = CURLE_OUT_OF_MEMORY;
5257 /* Store the options, null if not set */
5258 if(!result && options[0]) {
5259 conn->options = strdup(options);
5262 result = CURLE_OUT_OF_MEMORY;
5268 /*************************************************************
5269 * Resolve the address of the server or proxy
5270 *************************************************************/
5271 static CURLcode resolve_server(struct SessionHandle *data,
5272 struct connectdata *conn,
5275 CURLcode result=CURLE_OK;
5276 long timeout_ms = Curl_timeleft(data, NULL, TRUE);
5278 /*************************************************************
5279 * Resolve the name of the server or proxy
5280 *************************************************************/
5281 if(conn->bits.reuse)
5282 /* We're reusing the connection - no need to resolve anything, and
5283 fix_hostname() was called already in create_conn() for the re-use
5288 /* this is a fresh connect */
5290 struct Curl_dns_entry *hostaddr;
5292 #ifdef USE_UNIX_SOCKETS
5293 if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
5294 /* Unix domain sockets are local. The host gets ignored, just use the
5295 * specified domain socket address. Do not cache "DNS entries". There is
5296 * no DNS involved and we already have the filesystem path available */
5297 const char *path = data->set.str[STRING_UNIX_SOCKET_PATH];
5299 hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
5301 result = CURLE_OUT_OF_MEMORY;
5302 else if((hostaddr->addr = Curl_unix2addr(path)) != NULL)
5305 /* Long paths are not supported for now */
5306 if(strlen(path) >= sizeof(((struct sockaddr_un *)0)->sun_path)) {
5307 failf(data, "Unix socket path too long: '%s'", path);
5308 result = CURLE_COULDNT_RESOLVE_HOST;
5311 result = CURLE_OUT_OF_MEMORY;
5318 if(!conn->proxy.name || !*conn->proxy.name) {
5319 /* If not connecting via a proxy, extract the port from the URL, if it is
5320 * there, thus overriding any defaults that might have been set above. */
5321 conn->port = conn->remote_port; /* it is the same port */
5323 /* Resolve target host right on */
5324 rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
5325 &hostaddr, timeout_ms);
5326 if(rc == CURLRESOLV_PENDING)
5329 else if(rc == CURLRESOLV_TIMEDOUT)
5330 result = CURLE_OPERATION_TIMEDOUT;
5332 else if(!hostaddr) {
5333 failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
5334 result = CURLE_COULDNT_RESOLVE_HOST;
5335 /* don't return yet, we need to clean up the timeout first */
5339 /* This is a proxy that hasn't been resolved yet. */
5342 rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
5343 &hostaddr, timeout_ms);
5345 if(rc == CURLRESOLV_PENDING)
5348 else if(rc == CURLRESOLV_TIMEDOUT)
5349 result = CURLE_OPERATION_TIMEDOUT;
5351 else if(!hostaddr) {
5352 failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
5353 result = CURLE_COULDNT_RESOLVE_PROXY;
5354 /* don't return yet, we need to clean up the timeout first */
5357 DEBUGASSERT(conn->dns_entry == NULL);
5358 conn->dns_entry = hostaddr;
5365 * Cleanup the connection just allocated before we can move along and use the
5366 * previously existing one. All relevant data is copied over and old_conn is
5367 * ready for freeing once this function returns.
5369 static void reuse_conn(struct connectdata *old_conn,
5370 struct connectdata *conn)
5372 free_fixed_hostname(&old_conn->proxy);
5373 free(old_conn->proxy.rawalloc);
5375 /* free the SSL config struct from this connection struct as this was
5376 allocated in vain and is targeted for destruction */
5377 Curl_free_ssl_config(&old_conn->ssl_config);
5379 conn->data = old_conn->data;
5381 /* get the user+password information from the old_conn struct since it may
5382 * be new for this request even when we re-use an existing connection */
5383 conn->bits.user_passwd = old_conn->bits.user_passwd;
5384 if(conn->bits.user_passwd) {
5385 /* use the new user name and password though */
5386 Curl_safefree(conn->user);
5387 Curl_safefree(conn->passwd);
5388 conn->user = old_conn->user;
5389 conn->passwd = old_conn->passwd;
5390 old_conn->user = NULL;
5391 old_conn->passwd = NULL;
5394 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
5395 if(conn->bits.proxy_user_passwd) {
5396 /* use the new proxy user name and proxy password though */
5397 Curl_safefree(conn->proxyuser);
5398 Curl_safefree(conn->proxypasswd);
5399 conn->proxyuser = old_conn->proxyuser;
5400 conn->proxypasswd = old_conn->proxypasswd;
5401 old_conn->proxyuser = NULL;
5402 old_conn->proxypasswd = NULL;
5405 /* host can change, when doing keepalive with a proxy or if the case is
5406 different this time etc */
5407 free_fixed_hostname(&conn->host);
5408 Curl_safefree(conn->host.rawalloc);
5409 conn->host=old_conn->host;
5411 /* persist connection info in session handle */
5412 Curl_persistconninfo(conn);
5415 conn->bits.reuse = TRUE; /* yes, we're re-using here */
5417 Curl_safefree(old_conn->user);
5418 Curl_safefree(old_conn->passwd);
5419 Curl_safefree(old_conn->proxyuser);
5420 Curl_safefree(old_conn->proxypasswd);
5421 Curl_safefree(old_conn->localdev);
5423 Curl_llist_destroy(old_conn->send_pipe, NULL);
5424 Curl_llist_destroy(old_conn->recv_pipe, NULL);
5426 old_conn->send_pipe = NULL;
5427 old_conn->recv_pipe = NULL;
5429 Curl_safefree(old_conn->master_buffer);
5433 * create_conn() sets up a new connectdata struct, or re-uses an already
5434 * existing one, and resolves host name.
5436 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
5437 * response will be coming asynchronously. If *async is FALSE, the name is
5440 * @param data The sessionhandle pointer
5441 * @param in_connect is set to the next connection data pointer
5442 * @param async is set TRUE when an async DNS resolution is pending
5443 * @see Curl_setup_conn()
5445 * *NOTE* this function assigns the conn->data pointer!
5448 static CURLcode create_conn(struct SessionHandle *data,
5449 struct connectdata **in_connect,
5452 CURLcode result = CURLE_OK;
5453 struct connectdata *conn;
5454 struct connectdata *conn_temp = NULL;
5457 char *passwd = NULL;
5458 char *options = NULL;
5461 bool prot_missing = FALSE;
5462 bool connections_available = TRUE;
5463 bool force_reuse = FALSE;
5464 bool waitpipe = FALSE;
5465 size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
5466 size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
5470 /*************************************************************
5472 *************************************************************/
5474 if(!data->change.url) {
5475 result = CURLE_URL_MALFORMAT;
5479 /* First, split up the current URL in parts so that we can use the
5480 parts for checking against the already present connections. In order
5481 to not have to modify everything at once, we allocate a temporary
5482 connection data struct and fill in for comparison purposes. */
5483 conn = allocate_conn(data);
5486 result = CURLE_OUT_OF_MEMORY;
5490 /* We must set the return variable as soon as possible, so that our
5491 parent can cleanup any possible allocs we may have done before
5495 /* This initing continues below, see the comment "Continue connectdata
5496 * initialization here" */
5498 /***********************************************************
5499 * We need to allocate memory to store the path in. We get the size of the
5500 * full URL to be sure, and we need to make it at least 256 bytes since
5501 * other parts of the code will rely on this fact
5502 ***********************************************************/
5503 #define LEAST_PATH_ALLOC 256
5504 urllen=strlen(data->change.url);
5505 if(urllen < LEAST_PATH_ALLOC)
5506 urllen=LEAST_PATH_ALLOC;
5509 * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
5510 * 1 - an extra terminating zero
5511 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
5514 Curl_safefree(data->state.pathbuffer);
5515 data->state.path = NULL;
5517 data->state.pathbuffer = malloc(urllen+2);
5518 if(NULL == data->state.pathbuffer) {
5519 result = CURLE_OUT_OF_MEMORY; /* really bad error */
5522 data->state.path = data->state.pathbuffer;
5524 conn->host.rawalloc = malloc(urllen+2);
5525 if(NULL == conn->host.rawalloc) {
5526 Curl_safefree(data->state.pathbuffer);
5527 data->state.path = NULL;
5528 result = CURLE_OUT_OF_MEMORY;
5532 conn->host.name = conn->host.rawalloc;
5533 conn->host.name[0] = 0;
5536 passwd = strdup("");
5537 options = strdup("");
5538 if(!user || !passwd || !options) {
5539 result = CURLE_OUT_OF_MEMORY;
5543 result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
5548 /*************************************************************
5549 * No protocol part in URL was used, add it!
5550 *************************************************************/
5552 /* We're guessing prefixes here and if we're told to use a proxy or if
5553 we're gonna follow a Location: later or... then we need the protocol
5554 part added so that we have a valid URL. */
5558 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
5561 result = CURLE_OUT_OF_MEMORY;
5565 /* Change protocol prefix to lower-case */
5566 for(ch_lower = reurl; *ch_lower != ':'; ch_lower++)
5567 *ch_lower = (char)TOLOWER(*ch_lower);
5569 if(data->change.url_alloc) {
5570 Curl_safefree(data->change.url);
5571 data->change.url_alloc = FALSE;
5574 data->change.url = reurl;
5575 data->change.url_alloc = TRUE; /* free this later */
5578 /*************************************************************
5579 * If the protocol can't handle url query strings, then cut
5580 * off the unhandable part
5581 *************************************************************/
5582 if((conn->given->flags&PROTOPT_NOURLQUERY)) {
5583 char *path_q_sep = strchr(conn->data->state.path, '?');
5585 /* according to rfc3986, allow the query (?foo=bar)
5586 also on protocols that can't handle it.
5588 cut the string-part after '?'
5591 /* terminate the string */
5596 if(data->set.str[STRING_BEARER]) {
5597 conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
5598 if(!conn->oauth_bearer) {
5599 result = CURLE_OUT_OF_MEMORY;
5604 #ifndef CURL_DISABLE_PROXY
5605 /*************************************************************
5606 * Extract the user and password from the authentication string
5607 *************************************************************/
5608 if(conn->bits.proxy_user_passwd) {
5609 result = parse_proxy_auth(data, conn);
5614 /*************************************************************
5615 * Detect what (if any) proxy to use
5616 *************************************************************/
5617 if(data->set.str[STRING_PROXY]) {
5618 proxy = strdup(data->set.str[STRING_PROXY]);
5619 /* if global proxy is set, this is it */
5621 failf(data, "memory shortage");
5622 result = CURLE_OUT_OF_MEMORY;
5627 if(data->set.str[STRING_NOPROXY] &&
5628 check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
5629 free(proxy); /* proxy is in exception list */
5633 proxy = detect_proxy(conn);
5635 #ifdef USE_UNIX_SOCKETS
5636 if(proxy && data->set.str[STRING_UNIX_SOCKET_PATH]) {
5637 free(proxy); /* Unix domain sockets cannot be proxied, so disable it */
5642 if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
5643 free(proxy); /* Don't bother with an empty proxy string or if the
5644 protocol doesn't work with network */
5648 /***********************************************************************
5649 * If this is supposed to use a proxy, we need to figure out the proxy host
5650 * name, proxy type and port number, so that we can re-use an existing
5651 * connection that may exist registered to the same proxy host.
5652 ***********************************************************************/
5654 result = parse_proxy(data, conn, proxy);
5656 free(proxy); /* parse_proxy copies the proxy string */
5662 if((conn->proxytype == CURLPROXY_HTTP) ||
5663 (conn->proxytype == CURLPROXY_HTTP_1_0)) {
5664 #ifdef CURL_DISABLE_HTTP
5665 /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
5666 result = CURLE_UNSUPPORTED_PROTOCOL;
5669 /* force this connection's protocol to become HTTP if not already
5670 compatible - if it isn't tunneling through */
5671 if(!(conn->handler->protocol & PROTO_FAMILY_HTTP) &&
5672 !conn->bits.tunnel_proxy)
5673 conn->handler = &Curl_handler_http;
5675 conn->bits.httpproxy = TRUE;
5679 conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
5680 conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
5682 conn->bits.proxy = TRUE;
5685 /* we aren't using the proxy after all... */
5686 conn->bits.proxy = FALSE;
5687 conn->bits.httpproxy = FALSE;
5688 conn->bits.proxy_user_passwd = FALSE;
5689 conn->bits.tunnel_proxy = FALSE;
5692 #endif /* CURL_DISABLE_PROXY */
5694 /*************************************************************
5695 * If the protocol is using SSL and HTTP proxy is used, we set
5696 * the tunnel_proxy bit.
5697 *************************************************************/
5698 if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
5699 conn->bits.tunnel_proxy = TRUE;
5701 /*************************************************************
5702 * Figure out the remote port number and fix it in the URL
5703 *************************************************************/
5704 result = parse_remote_port(data, conn);
5708 /* Check for overridden login details and set them accordingly so they
5709 they are known when protocol->setup_connection is called! */
5710 result = override_login(data, conn, &user, &passwd, &options);
5713 result = set_login(conn, user, passwd, options);
5717 /*************************************************************
5718 * IDN-fix the hostnames
5719 *************************************************************/
5720 fix_hostname(data, conn, &conn->host);
5721 if(conn->proxy.name && *conn->proxy.name)
5722 fix_hostname(data, conn, &conn->proxy);
5724 /*************************************************************
5725 * Setup internals depending on protocol. Needs to be done after
5726 * we figured out what/if proxy to use.
5727 *************************************************************/
5728 result = setup_connection_internals(conn);
5732 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
5733 conn->send[FIRSTSOCKET] = Curl_send_plain;
5734 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
5735 conn->send[SECONDARYSOCKET] = Curl_send_plain;
5737 /***********************************************************************
5738 * file: is a special case in that it doesn't need a network connection
5739 ***********************************************************************/
5740 #ifndef CURL_DISABLE_FILE
5741 if(conn->handler->flags & PROTOPT_NONETWORK) {
5743 /* this is supposed to be the connect function so we better at least check
5744 that the file is present here! */
5745 DEBUGASSERT(conn->handler->connect_it);
5746 result = conn->handler->connect_it(conn, &done);
5748 /* Setup a "faked" transfer that'll do nothing */
5751 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
5753 Curl_conncache_add_conn(data->state.conn_cache, conn);
5756 * Setup whatever necessary for a resumed transfer
5758 result = setup_range(data);
5760 DEBUGASSERT(conn->handler->done);
5761 /* we ignore the return code for the protocol-specific DONE */
5762 (void)conn->handler->done(conn, result, FALSE);
5766 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
5767 -1, NULL); /* no upload */
5770 /* since we skip do_init() */
5771 Curl_init_do(data, conn);
5777 /* Get a cloned copy of the SSL config situation stored in the
5778 connection struct. But to get this going nicely, we must first make
5779 sure that the strings in the master copy are pointing to the correct
5780 strings in the session handle strings array!
5782 Keep in mind that the pointers in the master copy are pointing to strings
5783 that will be freed as part of the SessionHandle struct, but all cloned
5784 copies will be separately allocated.
5786 data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
5787 data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
5788 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
5789 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
5790 data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
5791 data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
5792 data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
5794 data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
5795 data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
5798 if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config)) {
5799 result = CURLE_OUT_OF_MEMORY;
5803 prune_dead_connections(data);
5805 /*************************************************************
5806 * Check the current list of connections to see if we can
5807 * re-use an already existing one or if we have to create a
5809 *************************************************************/
5811 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
5812 we only acknowledge this option if this is not a re-used connection
5813 already (which happens due to follow-location or during a HTTP
5814 authentication phase). */
5815 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
5818 reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
5820 /* If we found a reusable connection, we may still want to
5821 open a new connection if we are pipelining. */
5822 if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
5823 size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
5825 infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
5826 conn_temp->connection_id, pipelen);
5828 if(conn_temp->bundle->num_connections < max_host_connections &&
5829 data->state.conn_cache->num_connections < max_total_connections) {
5830 /* We want a new connection anyway */
5833 infof(data, "We can reuse, but we want a new connection anyway\n");
5840 * We already have a connection for this, we got the former connection
5841 * in the conn_temp variable and thus we need to cleanup the one we
5842 * just allocated before we can move along and use the previously
5845 conn_temp->inuse = TRUE; /* mark this as being in use so that no other
5846 handle in a multi stack may nick it */
5847 reuse_conn(conn, conn_temp);
5848 free(conn); /* we don't need this anymore */
5852 infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
5853 conn->connection_id,
5854 conn->bits.proxy?"proxy":"host",
5855 conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
5858 /* We have decided that we want a new connection. However, we may not
5859 be able to do that if we have reached the limit of how many
5860 connections we are allowed to open. */
5861 struct connectbundle *bundle = NULL;
5864 /* There is a connection that *might* become usable for pipelining
5865 "soon", and we wait for that */
5866 connections_available = FALSE;
5868 bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache);
5870 if(max_host_connections > 0 && bundle &&
5871 (bundle->num_connections >= max_host_connections)) {
5872 struct connectdata *conn_candidate;
5874 /* The bundle is full. Let's see if we can kill a connection. */
5875 conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
5877 if(conn_candidate) {
5878 /* Set the connection's owner correctly, then kill it */
5879 conn_candidate->data = data;
5880 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
5883 infof(data, "No more connections allowed to host: %d\n",
5884 max_host_connections);
5885 connections_available = FALSE;
5889 if(connections_available &&
5890 (max_total_connections > 0) &&
5891 (data->state.conn_cache->num_connections >= max_total_connections)) {
5892 struct connectdata *conn_candidate;
5894 /* The cache is full. Let's see if we can kill a connection. */
5895 conn_candidate = find_oldest_idle_connection(data);
5897 if(conn_candidate) {
5898 /* Set the connection's owner correctly, then kill it */
5899 conn_candidate->data = data;
5900 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
5903 infof(data, "No connections available in cache\n");
5904 connections_available = FALSE;
5908 if(!connections_available) {
5909 infof(data, "No connections available.\n");
5914 result = CURLE_NO_CONNECTION_AVAILABLE;
5919 * This is a brand new connection, so let's store it in the connection
5922 Curl_conncache_add_conn(data->state.conn_cache, conn);
5925 #if defined(USE_NTLM)
5926 /* If NTLM is requested in a part of this connection, make sure we don't
5927 assume the state is fine as this is a fresh connection and NTLM is
5928 connection based. */
5929 if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
5930 data->state.authhost.done) {
5931 infof(data, "NTLM picked AND auth done set, clear picked!\n");
5932 data->state.authhost.picked = CURLAUTH_NONE;
5933 data->state.authhost.done = FALSE;
5936 if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
5937 data->state.authproxy.done) {
5938 infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
5939 data->state.authproxy.picked = CURLAUTH_NONE;
5940 data->state.authproxy.done = FALSE;
5945 /* Mark the connection as used */
5948 /* Setup and init stuff before DO starts, in preparing for the transfer. */
5949 Curl_init_do(data, conn);
5952 * Setup whatever necessary for a resumed transfer
5954 result = setup_range(data);
5958 /* Continue connectdata initialization here. */
5961 * Inherit the proper values from the urldata struct AFTER we have arranged
5962 * the persistent connection stuff
5964 conn->seek_func = data->set.seek_func;
5965 conn->seek_client = data->set.seek_client;
5967 /*************************************************************
5968 * Resolve the address of the server or proxy
5969 *************************************************************/
5970 result = resolve_server(data, conn, async);
5981 /* Curl_setup_conn() is called after the name resolve initiated in
5982 * create_conn() is all done.
5984 * Curl_setup_conn() also handles reused connections
5986 * conn->data MUST already have been setup fine (in create_conn)
5989 CURLcode Curl_setup_conn(struct connectdata *conn,
5990 bool *protocol_done)
5992 CURLcode result = CURLE_OK;
5993 struct SessionHandle *data = conn->data;
5995 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
5997 if(conn->handler->flags & PROTOPT_NONETWORK) {
5998 /* nothing to setup when not using a network */
5999 *protocol_done = TRUE;
6002 *protocol_done = FALSE; /* default to not done */
6004 /* set proxy_connect_closed to false unconditionally already here since it
6005 is used strictly to provide extra information to a parent function in the
6006 case of proxy CONNECT failures and we must make sure we don't have it
6007 lingering set from a previous invoke */
6008 conn->bits.proxy_connect_closed = FALSE;
6011 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
6012 * basically anything through a http proxy we can't limit this based on
6015 if(data->set.str[STRING_USERAGENT]) {
6016 Curl_safefree(conn->allocptr.uagent);
6017 conn->allocptr.uagent =
6018 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
6019 if(!conn->allocptr.uagent)
6020 return CURLE_OUT_OF_MEMORY;
6023 data->req.headerbytecount = 0;
6025 #ifdef CURL_DO_LINEEND_CONV
6026 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
6027 #endif /* CURL_DO_LINEEND_CONV */
6029 /* set start time here for timeout purposes in the connect procedure, it
6030 is later set again for the progress meter purpose */
6031 conn->now = Curl_tvnow();
6033 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
6034 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
6035 result = Curl_connecthost(conn, conn->dns_entry);
6040 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
6041 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
6042 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
6043 *protocol_done = TRUE;
6044 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
6045 Curl_verboseconnect(conn);
6048 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
6049 set this here perhaps a second time */
6053 * This check is quite a hack. We're calling _fsetmode to fix the problem
6054 * with fwrite converting newline characters (you get mangled text files,
6055 * and corrupted binary files when you download to stdout and redirect it to
6059 if((data->set.out)->_handle == NULL) {
6060 _fsetmode(stdout, "b");
6067 CURLcode Curl_connect(struct SessionHandle *data,
6068 struct connectdata **in_connect,
6070 bool *protocol_done)
6074 *asyncp = FALSE; /* assume synchronous resolves by default */
6076 /* call the stuff that needs to be called */
6077 result = create_conn(data, in_connect, asyncp);
6081 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
6083 *protocol_done = TRUE;
6085 /* DNS resolution is done: that's either because this is a reused
6086 connection, in which case DNS was unnecessary, or because DNS
6087 really did finish already (synch resolver/fast async resolve) */
6088 result = Curl_setup_conn(*in_connect, protocol_done);
6092 if(result == CURLE_NO_CONNECTION_AVAILABLE) {
6097 if(result && *in_connect) {
6098 /* We're not allowed to return failure with memory left allocated
6099 in the connectdata struct, free those here */
6100 Curl_disconnect(*in_connect, FALSE); /* close the connection */
6101 *in_connect = NULL; /* return a NULL */
6107 CURLcode Curl_done(struct connectdata **connp,
6108 CURLcode status, /* an error if this is called after an
6109 error was detected */
6113 struct connectdata *conn;
6114 struct SessionHandle *data;
6116 DEBUGASSERT(*connp);
6121 DEBUGF(infof(data, "Curl_done\n"));
6123 if(data->state.done)
6124 /* Stop if Curl_done() has already been called */
6127 Curl_getoff_all_pipelines(data, conn);
6129 /* Cleanup possible redirect junk */
6130 free(data->req.newurl);
6131 data->req.newurl = NULL;
6132 free(data->req.location);
6133 data->req.location = NULL;
6136 case CURLE_ABORTED_BY_CALLBACK:
6137 case CURLE_READ_ERROR:
6138 case CURLE_WRITE_ERROR:
6139 /* When we're aborted due to a callback return code it basically have to
6140 be counted as premature as there is trouble ahead if we don't. We have
6141 many callbacks and protocols work differently, we could potentially do
6142 this more fine-grained in the future. */
6148 /* this calls the protocol-specific function pointer previously set */
6149 if(conn->handler->done)
6150 result = conn->handler->done(conn, status, premature);
6154 if(CURLE_ABORTED_BY_CALLBACK != result) {
6155 /* avoid this if we already aborted by callback to avoid this calling
6157 CURLcode rc = Curl_pgrsDone(conn);
6159 result = CURLE_ABORTED_BY_CALLBACK;
6163 conn->send_pipe->size + conn->recv_pipe->size != 0 &&
6164 !data->set.reuse_forbid &&
6165 !conn->bits.close)) {
6166 /* Stop if pipeline is not empty and we do not have to close
6168 DEBUGF(infof(data, "Connection still in use, no more Curl_done now!\n"));
6172 data->state.done = TRUE; /* called just now! */
6173 Curl_resolver_cancel(conn);
6175 if(conn->dns_entry) {
6176 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
6177 conn->dns_entry = NULL;
6180 /* if the transfer was completed in a paused state there can be buffered
6181 data left to write and then kill */
6182 free(data->state.tempwrite);
6183 data->state.tempwrite = NULL;
6185 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
6186 forced us to close this connection. This is ignored for requests taking
6187 place in a NTLM authentication handshake
6189 if conn->bits.close is TRUE, it means that the connection should be
6190 closed in spite of all our efforts to be nice, due to protocol
6191 restrictions in our or the server's end
6193 if premature is TRUE, it means this connection was said to be DONE before
6194 the entire request operation is complete and thus we can't know in what
6195 state it is for re-using, so we're forced to close it. In a perfect world
6196 we can add code that keep track of if we really must close it here or not,
6197 but currently we have no such detail knowledge.
6200 if((data->set.reuse_forbid
6201 #if defined(USE_NTLM)
6202 && !(conn->ntlm.state == NTLMSTATE_TYPE2 ||
6203 conn->proxyntlm.state == NTLMSTATE_TYPE2)
6205 ) || conn->bits.close || premature) {
6206 CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
6208 /* If we had an error already, make sure we return that one. But
6209 if we got a new error, return that. */
6214 /* the connection is no longer in use */
6215 if(ConnectionDone(data, conn)) {
6216 /* remember the most recently used connection */
6217 data->state.lastconnect = conn;
6219 infof(data, "Connection #%ld to host %s left intact\n",
6220 conn->connection_id,
6221 conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
6224 data->state.lastconnect = NULL;
6227 *connp = NULL; /* to make the caller of this function better detect that
6228 this was either closed or handed over to the connection
6229 cache here, and therefore cannot be used from this point on
6231 Curl_free_request_state(data);
6237 * Curl_init_do() inits the readwrite session. This is inited each time (in
6238 * the DO function before the protocol-specific DO functions are invoked) for
6239 * a transfer, sometimes multiple times on the same SessionHandle. Make sure
6240 * nothing in here depends on stuff that are setup dynamically for the
6243 * Allow this function to get called with 'conn' set to NULL.
6246 CURLcode Curl_init_do(struct SessionHandle *data, struct connectdata *conn)
6248 struct SingleRequest *k = &data->req;
6251 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
6254 data->state.done = FALSE; /* Curl_done() is not called yet */
6255 data->state.expect100header = FALSE;
6257 if(data->set.opt_no_body)
6258 /* in HTTP lingo, no body means using the HEAD request... */
6259 data->set.httpreq = HTTPREQ_HEAD;
6260 else if(HTTPREQ_HEAD == data->set.httpreq)
6261 /* ... but if unset there really is no perfect method that is the
6262 "opposite" of HEAD but in reality most people probably think GET
6263 then. The important thing is that we can't let it remain HEAD if the
6264 opt_no_body is set FALSE since then we'll behave wrong when getting
6266 data->set.httpreq = HTTPREQ_GET;
6268 k->start = Curl_tvnow(); /* start time */
6269 k->now = k->start; /* current time is now */
6270 k->header = TRUE; /* assume header */
6274 k->buf = data->state.buffer;
6275 k->uploadbuf = data->state.uploadbuffer;
6276 k->hbufp = data->state.headerbuff;
6277 k->ignorebody=FALSE;
6279 Curl_speedinit(data);
6281 Curl_pgrsSetUploadCounter(data, 0);
6282 Curl_pgrsSetDownloadCounter(data, 0);
6288 * do_complete is called when the DO actions are complete.
6290 * We init chunking and trailer bits to their default values here immediately
6291 * before receiving any header data for the current request in the pipeline.
6293 static void do_complete(struct connectdata *conn)
6295 conn->data->req.chunk=FALSE;
6296 conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
6297 conn->sockfd:conn->writesockfd)+1;
6298 Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
6301 CURLcode Curl_do(struct connectdata **connp, bool *done)
6303 CURLcode result=CURLE_OK;
6304 struct connectdata *conn = *connp;
6305 struct SessionHandle *data = conn->data;
6307 if(conn->handler->do_it) {
6308 /* generic protocol-specific function pointer set in curl_connect() */
6309 result = conn->handler->do_it(conn, done);
6311 /* This was formerly done in transfer.c, but we better do it here */
6312 if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
6314 * If the connection is using an easy handle, call reconnect
6315 * to re-establish the connection. Otherwise, let the multi logic
6316 * figure out how to re-establish the connection.
6319 result = Curl_reconnect_request(connp);
6322 /* ... finally back to actually retry the DO phase */
6323 conn = *connp; /* re-assign conn since Curl_reconnect_request
6324 creates a new connection */
6325 result = conn->handler->do_it(conn, done);
6332 if(!result && *done)
6333 /* do_complete must be called after the protocol-specific DO function */
6340 * Curl_do_more() is called during the DO_MORE multi state. It is basically a
6341 * second stage DO state which (wrongly) was introduced to support FTP's
6342 * second connection.
6344 * TODO: A future libcurl should be able to work away this state.
6346 * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
6347 * DOING state there's more work to do!
6350 CURLcode Curl_do_more(struct connectdata *conn, int *complete)
6352 CURLcode result=CURLE_OK;
6356 if(conn->handler->do_more)
6357 result = conn->handler->do_more(conn, complete);
6359 if(!result && (*complete == 1))
6360 /* do_complete must be called after the protocol-specific DO function */
6367 * get_protocol_family()
6369 * This is used to return the protocol family for a given protocol.
6373 * protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
6375 * Returns the family as a single bit protocol identifier.
6378 unsigned int get_protocol_family(unsigned int protocol)
6380 unsigned int family;
6383 case CURLPROTO_HTTP:
6384 case CURLPROTO_HTTPS:
6385 family = CURLPROTO_HTTP;
6389 case CURLPROTO_FTPS:
6390 family = CURLPROTO_IMAP;
6394 family = CURLPROTO_SCP;
6397 case CURLPROTO_SFTP:
6398 family = CURLPROTO_SFTP;
6401 case CURLPROTO_TELNET:
6402 family = CURLPROTO_TELNET;
6405 case CURLPROTO_LDAP:
6406 case CURLPROTO_LDAPS:
6407 family = CURLPROTO_IMAP;
6410 case CURLPROTO_DICT:
6411 family = CURLPROTO_DICT;
6414 case CURLPROTO_FILE:
6415 family = CURLPROTO_FILE;
6418 case CURLPROTO_TFTP:
6419 family = CURLPROTO_TFTP;
6422 case CURLPROTO_IMAP:
6423 case CURLPROTO_IMAPS:
6424 family = CURLPROTO_IMAP;
6427 case CURLPROTO_POP3:
6428 case CURLPROTO_POP3S:
6429 family = CURLPROTO_POP3;
6432 case CURLPROTO_SMTP:
6433 case CURLPROTO_SMTPS:
6434 family = CURLPROTO_SMTP;
6437 case CURLPROTO_RTSP:
6438 family = CURLPROTO_RTSP;
6441 case CURLPROTO_RTMP:
6442 case CURLPROTO_RTMPS:
6443 family = CURLPROTO_RTMP;
6446 case CURLPROTO_RTMPT:
6447 case CURLPROTO_RTMPTS:
6448 family = CURLPROTO_RTMPT;
6451 case CURLPROTO_RTMPE:
6452 family = CURLPROTO_RTMPE;
6455 case CURLPROTO_RTMPTE:
6456 family = CURLPROTO_RTMPTE;
6459 case CURLPROTO_GOPHER:
6460 family = CURLPROTO_GOPHER;
6464 case CURLPROTO_SMBS:
6465 family = CURLPROTO_SMB;