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 "http_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 /* The last 3 #include files should be in this order */
134 #include "curl_printf.h"
135 #include "curl_memory.h"
136 #include "memdebug.h"
138 /* Local static prototypes */
139 static struct connectdata *
140 find_oldest_idle_connection_in_bundle(struct Curl_easy *data,
141 struct connectbundle *bundle);
142 static void conn_free(struct connectdata *conn);
143 static void free_fixed_hostname(struct hostname *host);
144 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
145 static CURLcode parse_url_login(struct Curl_easy *data,
146 struct connectdata *conn,
147 char **userptr, char **passwdptr,
149 static CURLcode parse_login_details(const char *login, const size_t len,
150 char **userptr, char **passwdptr,
152 static unsigned int get_protocol_family(unsigned int protocol);
158 static const struct Curl_handler * const protocols[] = {
160 #ifndef CURL_DISABLE_HTTP
164 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
168 #ifndef CURL_DISABLE_FTP
172 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
176 #ifndef CURL_DISABLE_TELNET
177 &Curl_handler_telnet,
180 #ifndef CURL_DISABLE_DICT
184 #ifndef CURL_DISABLE_LDAP
186 #if !defined(CURL_DISABLE_LDAPS) && \
187 ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
188 (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
193 #ifndef CURL_DISABLE_FILE
197 #ifndef CURL_DISABLE_TFTP
206 #ifndef CURL_DISABLE_IMAP
213 #ifndef CURL_DISABLE_POP3
220 #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
221 (CURL_SIZEOF_CURL_OFF_T > 4) && \
222 (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
229 #ifndef CURL_DISABLE_SMTP
236 #ifndef CURL_DISABLE_RTSP
240 #ifndef CURL_DISABLE_GOPHER
241 &Curl_handler_gopher,
248 &Curl_handler_rtmpte,
250 &Curl_handler_rtmpts,
253 (struct Curl_handler *) NULL
257 * Dummy handler for undefined protocol schemes.
260 static const struct Curl_handler Curl_handler_dummy = {
261 "<no protocol>", /* scheme */
262 ZERO_NULL, /* setup_connection */
263 ZERO_NULL, /* do_it */
264 ZERO_NULL, /* done */
265 ZERO_NULL, /* do_more */
266 ZERO_NULL, /* connect_it */
267 ZERO_NULL, /* connecting */
268 ZERO_NULL, /* doing */
269 ZERO_NULL, /* proto_getsock */
270 ZERO_NULL, /* doing_getsock */
271 ZERO_NULL, /* domore_getsock */
272 ZERO_NULL, /* perform_getsock */
273 ZERO_NULL, /* disconnect */
274 ZERO_NULL, /* readwrite */
277 PROTOPT_NONE /* flags */
280 void Curl_freeset(struct Curl_easy *data)
282 /* Free all dynamic strings stored in the data->set substructure. */
284 for(i=(enum dupstring)0; i < STRING_LAST; i++) {
285 Curl_safefree(data->set.str[i]);
288 if(data->change.referer_alloc) {
289 Curl_safefree(data->change.referer);
290 data->change.referer_alloc = FALSE;
292 data->change.referer = NULL;
293 if(data->change.url_alloc) {
294 Curl_safefree(data->change.url);
295 data->change.url_alloc = FALSE;
297 data->change.url = NULL;
300 static CURLcode setstropt(char **charp, const char *s)
302 /* Release the previous storage at `charp' and replace by a dynamic storage
303 copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
305 Curl_safefree(*charp);
308 char *str = strdup(s);
311 return CURLE_OUT_OF_MEMORY;
319 static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp)
321 CURLcode result = CURLE_OK;
325 /* Parse the login details if specified. It not then we treat NULL as a hint
326 to clear the existing data */
328 result = parse_login_details(option, strlen(option),
329 (userp ? &user : NULL),
330 (passwdp ? &passwd : NULL),
335 /* Store the username part of option if required */
337 if(!user && option && option[0] == ':') {
338 /* Allocate an empty string instead of returning NULL as user name */
341 result = CURLE_OUT_OF_MEMORY;
344 Curl_safefree(*userp);
348 /* Store the password part of option if required */
350 Curl_safefree(*passwdp);
358 CURLcode Curl_dupset(struct Curl_easy *dst, struct Curl_easy *src)
360 CURLcode result = CURLE_OK;
363 /* Copy src->set into dst->set first, then deal with the strings
367 /* clear all string pointers first */
368 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
370 /* duplicate all strings */
371 for(i=(enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
372 result = setstropt(&dst->set.str[i], src->set.str[i]);
377 /* duplicate memory areas pointed to */
378 i = STRING_COPYPOSTFIELDS;
379 if(src->set.postfieldsize && src->set.str[i]) {
380 /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */
381 dst->set.str[i] = Curl_memdup(src->set.str[i],
382 curlx_sotouz(src->set.postfieldsize));
384 return CURLE_OUT_OF_MEMORY;
385 /* point to the new copy */
386 dst->set.postfields = dst->set.str[i];
393 * This is the internal function curl_easy_cleanup() calls. This should
394 * cleanup and free all resources associated with this sessionhandle.
396 * NOTE: if we ever add something that attempts to write to a socket or
397 * similar here, we must ignore SIGPIPE first. It is currently only done
398 * when curl_easy_perform() is invoked.
401 CURLcode Curl_close(struct Curl_easy *data)
403 struct Curl_multi *m;
408 Curl_expire_clear(data); /* shut off timers */
413 /* This handle is still part of a multi handle, take care of this first
414 and detach this handle from there. */
415 curl_multi_remove_handle(data->multi, data);
418 /* when curl_easy_perform() is used, it creates its own multi handle to
419 use and this is the one */
420 curl_multi_cleanup(data->multi_easy);
422 /* Destroy the timeout list that is held in the easy handle. It is
423 /normally/ done by curl_multi_remove_handle() but this is "just in
425 if(data->state.timeoutlist) {
426 Curl_llist_destroy(data->state.timeoutlist, NULL);
427 data->state.timeoutlist = NULL;
430 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
431 the multi handle, since that function uses the magic
434 if(data->state.rangestringalloc)
435 free(data->state.range);
437 /* Free the pathbuffer */
438 Curl_safefree(data->state.pathbuffer);
439 data->state.path = NULL;
441 /* freed here just in case DONE wasn't called */
442 Curl_free_request_state(data);
444 /* Close down all open SSL info and sessions */
445 Curl_ssl_close_all(data);
446 Curl_safefree(data->state.first_host);
447 Curl_safefree(data->state.scratch);
448 Curl_ssl_free_certinfo(data);
450 /* Cleanup possible redirect junk */
451 free(data->req.newurl);
452 data->req.newurl = NULL;
454 if(data->change.referer_alloc) {
455 Curl_safefree(data->change.referer);
456 data->change.referer_alloc = FALSE;
458 data->change.referer = NULL;
460 if(data->change.url_alloc) {
461 Curl_safefree(data->change.url);
462 data->change.url_alloc = FALSE;
464 data->change.url = NULL;
466 Curl_safefree(data->state.headerbuff);
468 Curl_flush_cookies(data, 1);
470 Curl_digest_cleanup(data);
472 Curl_safefree(data->info.contenttype);
473 Curl_safefree(data->info.wouldredirect);
475 /* this destroys the channel and we cannot use it anymore after this */
476 Curl_resolver_cleanup(data->state.resolver);
478 Curl_convert_close(data);
480 /* No longer a dirty share, if it exists */
482 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
483 data->share->dirty--;
484 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
487 if(data->set.wildcardmatch) {
488 /* destruct wildcard structures if it is needed */
489 struct WildcardData *wc = &data->wildcard;
490 Curl_wildcard_dtor(wc);
499 * Initialize the UserDefined fields within a Curl_easy.
500 * This may be safely called on a new or existing Curl_easy.
502 CURLcode Curl_init_userdefined(struct UserDefined *set)
504 CURLcode result = CURLE_OK;
506 set->out = stdout; /* default output to stdout */
507 set->in_set = stdin; /* default input from stdin */
508 set->err = stderr; /* default stderr to stderr */
510 /* use fwrite as default function to store output */
511 set->fwrite_func = (curl_write_callback)fwrite;
513 /* use fread as default function to read input */
514 set->fread_func_set = (curl_read_callback)fread;
515 set->is_fread_set = 0;
516 set->is_fwrite_set = 0;
518 set->seek_func = ZERO_NULL;
519 set->seek_client = ZERO_NULL;
521 /* conversion callbacks for non-ASCII hosts */
522 set->convfromnetwork = ZERO_NULL;
523 set->convtonetwork = ZERO_NULL;
524 set->convfromutf8 = ZERO_NULL;
526 set->filesize = -1; /* we don't know the size */
527 set->postfieldsize = -1; /* unknown size */
528 set->maxredirs = -1; /* allow any amount by default */
530 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
531 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
532 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
533 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
534 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
535 set->ftp_filemethod = FTPFILE_MULTICWD;
537 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
539 /* Set the default size of the SSL session ID cache */
540 set->ssl.max_ssl_sessions = 5;
542 set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
543 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
544 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
545 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
547 /* make libcurl quiet by default: */
548 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
551 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
552 * switched off unless wanted.
554 set->ssl.verifypeer = TRUE;
555 set->ssl.verifyhost = TRUE;
557 set->ssl.authtype = CURL_TLSAUTH_NONE;
559 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
561 set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
563 set->new_file_perms = 0644; /* Default permissions */
564 set->new_directory_perms = 0755; /* Default permissions */
566 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
567 define since we internally only use the lower 16 bits for the passed
568 in bitmask to not conflict with the private bits */
569 set->allowed_protocols = CURLPROTO_ALL;
570 set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
571 ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
574 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
576 * disallow unprotected protection negotiation NEC reference implementation
577 * seem not to follow rfc1961 section 4.3/4.4
579 set->socks5_gssapi_nec = FALSE;
582 /* This is our preferred CA cert bundle/path since install time */
583 #if defined(CURL_CA_BUNDLE)
584 result = setstropt(&set->str[STRING_SSL_CAFILE], CURL_CA_BUNDLE);
588 #if defined(CURL_CA_PATH)
589 result = setstropt(&set->str[STRING_SSL_CAPATH], CURL_CA_PATH);
594 set->wildcardmatch = FALSE;
595 set->chunk_bgn = ZERO_NULL;
596 set->chunk_end = ZERO_NULL;
598 /* tcp keepalives are disabled by default, but provide reasonable values for
599 * the interval and idle times.
601 set->tcp_keepalive = FALSE;
602 set->tcp_keepintvl = 60;
603 set->tcp_keepidle = 60;
604 set->tcp_fastopen = FALSE;
605 set->tcp_nodelay = TRUE;
607 set->ssl_enable_npn = TRUE;
608 set->ssl_enable_alpn = TRUE;
610 set->expect_100_timeout = 1000L; /* Wait for a second by default. */
611 set->sep_headers = TRUE; /* separated header lists by default */
613 Curl_http2_init_userset(set);
620 * @param curl is a pointer to a sessionhandle pointer that gets set by this
625 CURLcode Curl_open(struct Curl_easy **curl)
628 struct Curl_easy *data;
630 /* Very simple start-up: alloc the struct, init it with zeroes and return */
631 data = calloc(1, sizeof(struct Curl_easy));
633 /* this is a very serious error */
634 DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
635 return CURLE_OUT_OF_MEMORY;
638 data->magic = CURLEASY_MAGIC_NUMBER;
640 result = Curl_resolver_init(&data->state.resolver);
642 DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
647 /* We do some initial setup here, all those fields that can't be just 0 */
649 data->state.headerbuff = malloc(HEADERSIZE);
650 if(!data->state.headerbuff) {
651 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
652 result = CURLE_OUT_OF_MEMORY;
655 result = Curl_init_userdefined(&data->set);
657 data->state.headersize=HEADERSIZE;
659 Curl_convert_init(data);
661 /* most recent connection is not yet defined */
662 data->state.lastconnect = NULL;
664 data->progress.flags |= PGRS_HIDE;
665 data->state.current_speed = -1; /* init to negative == impossible */
667 data->wildcard.state = CURLWC_INIT;
668 data->wildcard.filelist = NULL;
669 data->set.fnmatch = ZERO_NULL;
670 data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
672 Curl_http2_init_state(&data->state);
676 Curl_resolver_cleanup(data->state.resolver);
677 free(data->state.headerbuff);
688 CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
692 CURLcode result = CURLE_OK;
694 #ifndef CURL_DISABLE_HTTP
699 case CURLOPT_DNS_CACHE_TIMEOUT:
700 data->set.dns_cache_timeout = va_arg(param, long);
702 case CURLOPT_DNS_USE_GLOBAL_CACHE:
703 /* remember we want this enabled */
704 arg = va_arg(param, long);
705 data->set.global_dns_cache = (0 != arg) ? TRUE : FALSE;
707 case CURLOPT_SSL_CIPHER_LIST:
708 /* set a list of cipher we want to use in the SSL connection */
709 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
710 va_arg(param, char *));
713 case CURLOPT_RANDOM_FILE:
715 * This is the path name to a file that contains random data to seed
716 * the random SSL stuff with. The file is only used for reading.
718 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
719 va_arg(param, char *));
721 case CURLOPT_EGDSOCKET:
723 * The Entropy Gathering Daemon socket pathname
725 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
726 va_arg(param, char *));
728 case CURLOPT_MAXCONNECTS:
730 * Set the absolute number of maximum simultaneous alive connection that
731 * libcurl is allowed to have.
733 data->set.maxconnects = va_arg(param, long);
735 case CURLOPT_FORBID_REUSE:
737 * When this transfer is done, it must not be left to be reused by a
738 * subsequent transfer but shall be closed immediately.
740 data->set.reuse_forbid = (0 != va_arg(param, long)) ? TRUE : FALSE;
742 case CURLOPT_FRESH_CONNECT:
744 * This transfer shall not use a previously cached connection but
745 * should be made with a fresh new connect!
747 data->set.reuse_fresh = (0 != va_arg(param, long)) ? TRUE : FALSE;
749 case CURLOPT_VERBOSE:
751 * Verbose means infof() calls that give a lot of information about
752 * the connection and transfer procedures as well as internal choices.
754 data->set.verbose = (0 != va_arg(param, long)) ? TRUE : FALSE;
758 * Set to include the header in the general data output stream.
760 data->set.include_header = (0 != va_arg(param, long)) ? TRUE : FALSE;
762 case CURLOPT_NOPROGRESS:
764 * Shut off the internal supported progress meter
766 data->set.hide_progress = (0 != va_arg(param, long)) ? TRUE : FALSE;
767 if(data->set.hide_progress)
768 data->progress.flags |= PGRS_HIDE;
770 data->progress.flags &= ~PGRS_HIDE;
774 * Do not include the body part in the output data stream.
776 data->set.opt_no_body = (0 != va_arg(param, long)) ? TRUE : FALSE;
778 case CURLOPT_FAILONERROR:
780 * Don't output the >=400 error code HTML-page, but instead only
783 data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE;
788 * We want to sent data to the remote host. If this is HTTP, that equals
789 * using the PUT request.
791 data->set.upload = (0 != va_arg(param, long)) ? TRUE : FALSE;
792 if(data->set.upload) {
793 /* If this is HTTP, PUT is what's needed to "upload" */
794 data->set.httpreq = HTTPREQ_PUT;
795 data->set.opt_no_body = FALSE; /* this is implied */
798 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
799 then this can be changed to HEAD later on) */
800 data->set.httpreq = HTTPREQ_GET;
802 case CURLOPT_FILETIME:
804 * Try to get the file time of the remote document. The time will
805 * later (possibly) become available using curl_easy_getinfo().
807 data->set.get_filetime = (0 != va_arg(param, long)) ? TRUE : FALSE;
809 case CURLOPT_FTP_CREATE_MISSING_DIRS:
811 * An FTP option that modifies an upload to create missing directories on
814 switch(va_arg(param, long)) {
816 data->set.ftp_create_missing_dirs = 0;
819 data->set.ftp_create_missing_dirs = 1;
822 data->set.ftp_create_missing_dirs = 2;
825 /* reserve other values for future use */
826 result = CURLE_UNKNOWN_OPTION;
830 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
832 * Option that specifies how quickly an server response must be obtained
833 * before it is considered failure. For pingpong protocols.
835 data->set.server_response_timeout = va_arg(param, long) * 1000;
837 case CURLOPT_TFTP_NO_OPTIONS:
839 * Option that prevents libcurl from sending TFTP option requests to the
842 data->set.tftp_no_options = va_arg(param, long) != 0;
844 case CURLOPT_TFTP_BLKSIZE:
846 * TFTP option that specifies the block size to use for data transmission.
848 data->set.tftp_blksize = va_arg(param, long);
850 case CURLOPT_DIRLISTONLY:
852 * An option that changes the command to one that asks for a list
853 * only, no file info details.
855 data->set.ftp_list_only = (0 != va_arg(param, long)) ? TRUE : FALSE;
859 * We want to upload and append to an existing file.
861 data->set.ftp_append = (0 != va_arg(param, long)) ? TRUE : FALSE;
863 case CURLOPT_FTP_FILEMETHOD:
865 * How do access files over FTP.
867 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
871 * Parse the $HOME/.netrc file
873 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
875 case CURLOPT_NETRC_FILE:
877 * Use this file instead of the $HOME/.netrc file
879 result = setstropt(&data->set.str[STRING_NETRC_FILE],
880 va_arg(param, char *));
882 case CURLOPT_TRANSFERTEXT:
884 * This option was previously named 'FTPASCII'. Renamed to work with
885 * more protocols than merely FTP.
887 * Transfer using ASCII (instead of BINARY).
889 data->set.prefer_ascii = (0 != va_arg(param, long)) ? TRUE : FALSE;
891 case CURLOPT_TIMECONDITION:
893 * Set HTTP time condition. This must be one of the defines in the
894 * curl/curl.h header file.
896 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
898 case CURLOPT_TIMEVALUE:
900 * This is the value to compare with the remote document with the
901 * method set with CURLOPT_TIMECONDITION
903 data->set.timevalue = (time_t)va_arg(param, long);
905 case CURLOPT_SSLVERSION:
907 * Set explicit SSL version to try to connect with, as some SSL
908 * implementations are lame.
911 data->set.ssl.version = va_arg(param, long);
913 result = CURLE_UNKNOWN_OPTION;
917 #ifndef CURL_DISABLE_HTTP
918 case CURLOPT_AUTOREFERER:
920 * Switch on automatic referer that gets set if curl follows locations.
922 data->set.http_auto_referer = (0 != va_arg(param, long)) ? TRUE : FALSE;
925 case CURLOPT_ACCEPT_ENCODING:
927 * String to use at the value of Accept-Encoding header.
929 * If the encoding is set to "" we use an Accept-Encoding header that
930 * encompasses all the encodings we support.
931 * If the encoding is set to NULL we don't send an Accept-Encoding header
932 * and ignore an received Content-Encoding header.
935 argptr = va_arg(param, char *);
936 result = setstropt(&data->set.str[STRING_ENCODING],
937 (argptr && !*argptr)?
938 ALL_CONTENT_ENCODINGS: argptr);
941 case CURLOPT_TRANSFER_ENCODING:
942 data->set.http_transfer_encoding = (0 != va_arg(param, long)) ?
946 case CURLOPT_FOLLOWLOCATION:
948 * Follow Location: header hints on a HTTP-server.
950 data->set.http_follow_location = (0 != va_arg(param, long)) ? TRUE : FALSE;
953 case CURLOPT_UNRESTRICTED_AUTH:
955 * Send authentication (user+password) when following locations, even when
958 data->set.http_disable_hostname_check_before_authentication =
959 (0 != va_arg(param, long)) ? TRUE : FALSE;
962 case CURLOPT_MAXREDIRS:
964 * The maximum amount of hops you allow curl to follow Location:
965 * headers. This should mostly be used to detect never-ending loops.
967 data->set.maxredirs = va_arg(param, long);
970 case CURLOPT_POSTREDIR:
973 * Set the behaviour of POST when redirecting
974 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
975 * CURL_REDIR_POST_301 - POST is kept as POST after 301
976 * CURL_REDIR_POST_302 - POST is kept as POST after 302
977 * CURL_REDIR_POST_303 - POST is kept as POST after 303
978 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
979 * other - POST is kept as POST after 301 and 302
981 int postRedir = curlx_sltosi(va_arg(param, long));
982 data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
987 /* Does this option serve a purpose anymore? Yes it does, when
988 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
990 if(va_arg(param, long)) {
991 data->set.httpreq = HTTPREQ_POST;
992 data->set.opt_no_body = FALSE; /* this is implied */
995 data->set.httpreq = HTTPREQ_GET;
998 case CURLOPT_COPYPOSTFIELDS:
1000 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
1001 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
1002 * CURLOPT_COPYPOSTFIELDS and not altered later.
1004 argptr = va_arg(param, char *);
1006 if(!argptr || data->set.postfieldsize == -1)
1007 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
1010 * Check that requested length does not overflow the size_t type.
1013 if((data->set.postfieldsize < 0) ||
1014 ((sizeof(curl_off_t) != sizeof(size_t)) &&
1015 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
1016 result = CURLE_OUT_OF_MEMORY;
1020 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1022 /* Allocate even when size == 0. This satisfies the need of possible
1023 later address compare to detect the COPYPOSTFIELDS mode, and
1024 to mark that postfields is used rather than read function or
1027 p = malloc((size_t)(data->set.postfieldsize?
1028 data->set.postfieldsize:1));
1031 result = CURLE_OUT_OF_MEMORY;
1033 if(data->set.postfieldsize)
1034 memcpy(p, argptr, (size_t)data->set.postfieldsize);
1036 data->set.str[STRING_COPYPOSTFIELDS] = p;
1041 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
1042 data->set.httpreq = HTTPREQ_POST;
1045 case CURLOPT_POSTFIELDS:
1047 * Like above, but use static data instead of copying it.
1049 data->set.postfields = va_arg(param, void *);
1050 /* Release old copied data. */
1051 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1052 data->set.httpreq = HTTPREQ_POST;
1055 case CURLOPT_POSTFIELDSIZE:
1057 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1058 * figure it out. Enables binary posts.
1060 bigsize = va_arg(param, long);
1062 if(data->set.postfieldsize < bigsize &&
1063 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1064 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1065 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1066 data->set.postfields = NULL;
1069 data->set.postfieldsize = bigsize;
1072 case CURLOPT_POSTFIELDSIZE_LARGE:
1074 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1075 * figure it out. Enables binary posts.
1077 bigsize = va_arg(param, curl_off_t);
1079 if(data->set.postfieldsize < bigsize &&
1080 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1081 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1082 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1083 data->set.postfields = NULL;
1086 data->set.postfieldsize = bigsize;
1089 case CURLOPT_HTTPPOST:
1091 * Set to make us do HTTP POST
1093 data->set.httppost = va_arg(param, struct curl_httppost *);
1094 data->set.httpreq = HTTPREQ_POST_FORM;
1095 data->set.opt_no_body = FALSE; /* this is implied */
1098 case CURLOPT_REFERER:
1100 * String to set in the HTTP Referer: field.
1102 if(data->change.referer_alloc) {
1103 Curl_safefree(data->change.referer);
1104 data->change.referer_alloc = FALSE;
1106 result = setstropt(&data->set.str[STRING_SET_REFERER],
1107 va_arg(param, char *));
1108 data->change.referer = data->set.str[STRING_SET_REFERER];
1111 case CURLOPT_USERAGENT:
1113 * String to use in the HTTP User-Agent field
1115 result = setstropt(&data->set.str[STRING_USERAGENT],
1116 va_arg(param, char *));
1119 case CURLOPT_HTTPHEADER:
1121 * Set a list with HTTP headers to use (or replace internals with)
1123 data->set.headers = va_arg(param, struct curl_slist *);
1126 case CURLOPT_PROXYHEADER:
1128 * Set a list with proxy headers to use (or replace internals with)
1130 * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a
1131 * long time we remain doing it this way until CURLOPT_PROXYHEADER is
1132 * used. As soon as this option has been used, if set to anything but
1133 * NULL, custom headers for proxies are only picked from this list.
1135 * Set this option to NULL to restore the previous behavior.
1137 data->set.proxyheaders = va_arg(param, struct curl_slist *);
1140 case CURLOPT_HEADEROPT:
1142 * Set header option.
1144 arg = va_arg(param, long);
1145 data->set.sep_headers = (arg & CURLHEADER_SEPARATE)? TRUE: FALSE;
1148 case CURLOPT_HTTP200ALIASES:
1150 * Set a list of aliases for HTTP 200 in response header
1152 data->set.http200aliases = va_arg(param, struct curl_slist *);
1155 #if !defined(CURL_DISABLE_COOKIES)
1156 case CURLOPT_COOKIE:
1158 * Cookie string to send to the remote server in the request.
1160 result = setstropt(&data->set.str[STRING_COOKIE],
1161 va_arg(param, char *));
1164 case CURLOPT_COOKIEFILE:
1166 * Set cookie file to read and parse. Can be used multiple times.
1168 argptr = (char *)va_arg(param, void *);
1170 struct curl_slist *cl;
1171 /* append the cookie file name to the list of file names, and deal with
1173 cl = curl_slist_append(data->change.cookielist, argptr);
1175 curl_slist_free_all(data->change.cookielist);
1176 data->change.cookielist = NULL;
1177 return CURLE_OUT_OF_MEMORY;
1179 data->change.cookielist = cl; /* store the list for later use */
1183 case CURLOPT_COOKIEJAR:
1185 * Set cookie file name to dump all cookies to when we're done.
1188 struct CookieInfo *newcookies;
1189 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1190 va_arg(param, char *));
1193 * Activate the cookie parser. This may or may not already
1196 newcookies = Curl_cookie_init(data, NULL, data->cookies,
1197 data->set.cookiesession);
1199 result = CURLE_OUT_OF_MEMORY;
1200 data->cookies = newcookies;
1204 case CURLOPT_COOKIESESSION:
1206 * Set this option to TRUE to start a new "cookie session". It will
1207 * prevent the forthcoming read-cookies-from-file actions to accept
1208 * cookies that are marked as being session cookies, as they belong to a
1211 * In the original Netscape cookie spec, "session cookies" are cookies
1212 * with no expire date set. RFC2109 describes the same action if no
1213 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1214 * a 'Discard' action that can enforce the discard even for cookies that
1217 * We run mostly with the original cookie spec, as hardly anyone implements
1220 data->set.cookiesession = (0 != va_arg(param, long)) ? TRUE : FALSE;
1223 case CURLOPT_COOKIELIST:
1224 argptr = va_arg(param, char *);
1229 if(Curl_raw_equal(argptr, "ALL")) {
1230 /* clear all cookies */
1231 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1232 Curl_cookie_clearall(data->cookies);
1233 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1235 else if(Curl_raw_equal(argptr, "SESS")) {
1236 /* clear session cookies */
1237 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1238 Curl_cookie_clearsess(data->cookies);
1239 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1241 else if(Curl_raw_equal(argptr, "FLUSH")) {
1242 /* flush cookies to file, takes care of the locking */
1243 Curl_flush_cookies(data, 0);
1245 else if(Curl_raw_equal(argptr, "RELOAD")) {
1246 /* reload cookies from file */
1247 Curl_cookie_loadfiles(data);
1252 /* if cookie engine was not running, activate it */
1253 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1255 argptr = strdup(argptr);
1256 if(!argptr || !data->cookies) {
1257 result = CURLE_OUT_OF_MEMORY;
1261 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
1263 if(checkprefix("Set-Cookie:", argptr))
1264 /* HTTP Header format line */
1265 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1268 /* Netscape format line */
1269 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1271 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
1277 #endif /* CURL_DISABLE_COOKIES */
1279 case CURLOPT_HTTPGET:
1281 * Set to force us do HTTP GET
1283 if(va_arg(param, long)) {
1284 data->set.httpreq = HTTPREQ_GET;
1285 data->set.upload = FALSE; /* switch off upload */
1286 data->set.opt_no_body = FALSE; /* this is implied */
1290 case CURLOPT_HTTP_VERSION:
1292 * This sets a requested HTTP version to be used. The value is one of
1293 * the listed enums in curl/curl.h.
1295 arg = va_arg(param, long);
1297 if(arg >= CURL_HTTP_VERSION_2)
1298 return CURLE_UNSUPPORTED_PROTOCOL;
1300 data->set.httpversion = arg;
1303 case CURLOPT_HTTPAUTH:
1305 * Set HTTP Authentication type BITMASK.
1310 unsigned long auth = va_arg(param, unsigned long);
1312 if(auth == CURLAUTH_NONE) {
1313 data->set.httpauth = auth;
1317 /* the DIGEST_IE bit is only used to set a special marker, for all the
1318 rest we need to handle it as normal DIGEST */
1319 data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE;
1321 if(auth & CURLAUTH_DIGEST_IE) {
1322 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1323 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1326 /* switch off bits we can't support */
1328 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1329 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1330 #elif !defined(NTLM_WB_ENABLED)
1331 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1334 auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
1338 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1341 while(bitcheck < 31) {
1342 if(auth & (1UL << bitcheck++)) {
1348 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1350 data->set.httpauth = auth;
1354 case CURLOPT_EXPECT_100_TIMEOUT_MS:
1356 * Time to wait for a response to a HTTP request containing an
1357 * Expect: 100-continue header before sending the data anyway.
1359 data->set.expect_100_timeout = va_arg(param, long);
1362 #endif /* CURL_DISABLE_HTTP */
1364 case CURLOPT_CUSTOMREQUEST:
1366 * Set a custom string to use as request
1368 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1369 va_arg(param, char *));
1372 data->set.httpreq = HTTPREQ_CUSTOM;
1373 here, we continue as if we were using the already set type
1374 and this just changes the actual request keyword */
1377 #ifndef CURL_DISABLE_PROXY
1378 case CURLOPT_HTTPPROXYTUNNEL:
1380 * Tunnel operations through the proxy instead of normal proxy use
1382 data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)) ?
1386 case CURLOPT_PROXYPORT:
1388 * Explicitly set HTTP proxy port number.
1390 data->set.proxyport = va_arg(param, long);
1393 case CURLOPT_PROXYAUTH:
1395 * Set HTTP Authentication type BITMASK.
1400 unsigned long auth = va_arg(param, unsigned long);
1402 if(auth == CURLAUTH_NONE) {
1403 data->set.proxyauth = auth;
1407 /* the DIGEST_IE bit is only used to set a special marker, for all the
1408 rest we need to handle it as normal DIGEST */
1409 data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE;
1411 if(auth & CURLAUTH_DIGEST_IE) {
1412 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1413 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1415 /* switch off bits we can't support */
1417 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1418 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1419 #elif !defined(NTLM_WB_ENABLED)
1420 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1423 auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
1427 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1430 while(bitcheck < 31) {
1431 if(auth & (1UL << bitcheck++)) {
1437 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1439 data->set.proxyauth = auth;
1445 * Set proxy server:port to use as HTTP proxy.
1447 * If the proxy is set to "" we explicitly say that we don't want to use a
1448 * proxy (even though there might be environment variables saying so).
1450 * Setting it to NULL, means no proxy but allows the environment variables
1453 result = setstropt(&data->set.str[STRING_PROXY],
1454 va_arg(param, char *));
1457 case CURLOPT_PROXYTYPE:
1459 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1461 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1464 case CURLOPT_PROXY_TRANSFER_MODE:
1466 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1468 switch (va_arg(param, long)) {
1470 data->set.proxy_transfer_mode = FALSE;
1473 data->set.proxy_transfer_mode = TRUE;
1476 /* reserve other values for future use */
1477 result = CURLE_UNKNOWN_OPTION;
1481 #endif /* CURL_DISABLE_PROXY */
1483 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1484 case CURLOPT_SOCKS5_GSSAPI_NEC:
1486 * Set flag for NEC SOCK5 support
1488 data->set.socks5_gssapi_nec = (0 != va_arg(param, long)) ? TRUE : FALSE;
1491 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1492 case CURLOPT_PROXY_SERVICE_NAME:
1494 * Set proxy authentication service name for Kerberos 5 and SPNEGO
1496 result = setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME],
1497 va_arg(param, char *));
1501 #if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \
1503 case CURLOPT_SERVICE_NAME:
1505 * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO
1507 result = setstropt(&data->set.str[STRING_SERVICE_NAME],
1508 va_arg(param, char *));
1513 case CURLOPT_HEADERDATA:
1515 * Custom pointer to pass the header write callback function
1517 data->set.writeheader = (void *)va_arg(param, void *);
1519 case CURLOPT_ERRORBUFFER:
1521 * Error buffer provided by the caller to get the human readable
1524 data->set.errorbuffer = va_arg(param, char *);
1526 case CURLOPT_WRITEDATA:
1528 * FILE pointer to write to. Or possibly
1529 * used as argument to the write callback.
1531 data->set.out = va_arg(param, void *);
1533 case CURLOPT_FTPPORT:
1535 * Use FTP PORT, this also specifies which IP address to use
1537 result = setstropt(&data->set.str[STRING_FTPPORT],
1538 va_arg(param, char *));
1539 data->set.ftp_use_port = (data->set.str[STRING_FTPPORT]) ? TRUE : FALSE;
1542 case CURLOPT_FTP_USE_EPRT:
1543 data->set.ftp_use_eprt = (0 != va_arg(param, long)) ? TRUE : FALSE;
1546 case CURLOPT_FTP_USE_EPSV:
1547 data->set.ftp_use_epsv = (0 != va_arg(param, long)) ? TRUE : FALSE;
1550 case CURLOPT_FTP_USE_PRET:
1551 data->set.ftp_use_pret = (0 != va_arg(param, long)) ? TRUE : FALSE;
1554 case CURLOPT_FTP_SSL_CCC:
1555 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1558 case CURLOPT_FTP_SKIP_PASV_IP:
1560 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1561 * bypass of the IP address in PASV responses.
1563 data->set.ftp_skip_ip = (0 != va_arg(param, long)) ? TRUE : FALSE;
1566 case CURLOPT_READDATA:
1568 * FILE pointer to read the file to be uploaded from. Or possibly
1569 * used as argument to the read callback.
1571 data->set.in_set = va_arg(param, void *);
1573 case CURLOPT_INFILESIZE:
1575 * If known, this should inform curl about the file size of the
1576 * to-be-uploaded file.
1578 data->set.filesize = va_arg(param, long);
1580 case CURLOPT_INFILESIZE_LARGE:
1582 * If known, this should inform curl about the file size of the
1583 * to-be-uploaded file.
1585 data->set.filesize = va_arg(param, curl_off_t);
1587 case CURLOPT_LOW_SPEED_LIMIT:
1589 * The low speed limit that if transfers are below this for
1590 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1592 data->set.low_speed_limit=va_arg(param, long);
1594 case CURLOPT_MAX_SEND_SPEED_LARGE:
1596 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1597 * bytes per second the transfer is throttled..
1599 data->set.max_send_speed=va_arg(param, curl_off_t);
1601 case CURLOPT_MAX_RECV_SPEED_LARGE:
1603 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1604 * second the transfer is throttled..
1606 data->set.max_recv_speed=va_arg(param, curl_off_t);
1608 case CURLOPT_LOW_SPEED_TIME:
1610 * The low speed time that if transfers are below the set
1611 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1613 data->set.low_speed_time=va_arg(param, long);
1619 if(data->change.url_alloc) {
1620 /* the already set URL is allocated, free it first! */
1621 Curl_safefree(data->change.url);
1622 data->change.url_alloc = FALSE;
1624 result = setstropt(&data->set.str[STRING_SET_URL],
1625 va_arg(param, char *));
1626 data->change.url = data->set.str[STRING_SET_URL];
1630 * The port number to use when getting the URL
1632 data->set.use_port = va_arg(param, long);
1634 case CURLOPT_TIMEOUT:
1636 * The maximum time you allow curl to use for a single transfer
1639 data->set.timeout = va_arg(param, long) * 1000L;
1642 case CURLOPT_TIMEOUT_MS:
1643 data->set.timeout = va_arg(param, long);
1646 case CURLOPT_CONNECTTIMEOUT:
1648 * The maximum time you allow curl to use to connect.
1650 data->set.connecttimeout = va_arg(param, long) * 1000L;
1653 case CURLOPT_CONNECTTIMEOUT_MS:
1654 data->set.connecttimeout = va_arg(param, long);
1657 case CURLOPT_ACCEPTTIMEOUT_MS:
1659 * The maximum time you allow curl to wait for server connect
1661 data->set.accepttimeout = va_arg(param, long);
1664 case CURLOPT_USERPWD:
1666 * user:password to use in the operation
1668 result = setstropt_userpwd(va_arg(param, char *),
1669 &data->set.str[STRING_USERNAME],
1670 &data->set.str[STRING_PASSWORD]);
1673 case CURLOPT_USERNAME:
1675 * authentication user name to use in the operation
1677 result = setstropt(&data->set.str[STRING_USERNAME],
1678 va_arg(param, char *));
1681 case CURLOPT_PASSWORD:
1683 * authentication password to use in the operation
1685 result = setstropt(&data->set.str[STRING_PASSWORD],
1686 va_arg(param, char *));
1689 case CURLOPT_LOGIN_OPTIONS:
1691 * authentication options to use in the operation
1693 result = setstropt(&data->set.str[STRING_OPTIONS],
1694 va_arg(param, char *));
1697 case CURLOPT_XOAUTH2_BEARER:
1699 * OAuth 2.0 bearer token to use in the operation
1701 result = setstropt(&data->set.str[STRING_BEARER],
1702 va_arg(param, char *));
1705 case CURLOPT_POSTQUOTE:
1707 * List of RAW FTP commands to use after a transfer
1709 data->set.postquote = va_arg(param, struct curl_slist *);
1711 case CURLOPT_PREQUOTE:
1713 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1715 data->set.prequote = va_arg(param, struct curl_slist *);
1719 * List of RAW FTP commands to use before a transfer
1721 data->set.quote = va_arg(param, struct curl_slist *);
1723 case CURLOPT_RESOLVE:
1725 * List of NAME:[address] names to populate the DNS cache with
1726 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1728 * Names added with this API will remain in the cache until explicitly
1729 * removed or the handle is cleaned up.
1731 * This API can remove any name from the DNS cache, but only entries
1732 * that aren't actually in use right now will be pruned immediately.
1734 data->set.resolve = va_arg(param, struct curl_slist *);
1735 data->change.resolve = data->set.resolve;
1737 case CURLOPT_PROGRESSFUNCTION:
1739 * Progress callback function
1741 data->set.fprogress = va_arg(param, curl_progress_callback);
1742 if(data->set.fprogress)
1743 data->progress.callback = TRUE; /* no longer internal */
1745 data->progress.callback = FALSE; /* NULL enforces internal */
1748 case CURLOPT_XFERINFOFUNCTION:
1750 * Transfer info callback function
1752 data->set.fxferinfo = va_arg(param, curl_xferinfo_callback);
1753 if(data->set.fxferinfo)
1754 data->progress.callback = TRUE; /* no longer internal */
1756 data->progress.callback = FALSE; /* NULL enforces internal */
1760 case CURLOPT_PROGRESSDATA:
1762 * Custom client data to pass to the progress callback
1764 data->set.progress_client = va_arg(param, void *);
1767 #ifndef CURL_DISABLE_PROXY
1768 case CURLOPT_PROXYUSERPWD:
1770 * user:password needed to use the proxy
1772 result = setstropt_userpwd(va_arg(param, char *),
1773 &data->set.str[STRING_PROXYUSERNAME],
1774 &data->set.str[STRING_PROXYPASSWORD]);
1776 case CURLOPT_PROXYUSERNAME:
1778 * authentication user name to use in the operation
1780 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1781 va_arg(param, char *));
1783 case CURLOPT_PROXYPASSWORD:
1785 * authentication password to use in the operation
1787 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1788 va_arg(param, char *));
1790 case CURLOPT_NOPROXY:
1792 * proxy exception list
1794 result = setstropt(&data->set.str[STRING_NOPROXY],
1795 va_arg(param, char *));
1801 * What range of the file you want to transfer
1803 result = setstropt(&data->set.str[STRING_SET_RANGE],
1804 va_arg(param, char *));
1806 case CURLOPT_RESUME_FROM:
1808 * Resume transfer at the give file position
1810 data->set.set_resume_from = va_arg(param, long);
1812 case CURLOPT_RESUME_FROM_LARGE:
1814 * Resume transfer at the give file position
1816 data->set.set_resume_from = va_arg(param, curl_off_t);
1818 case CURLOPT_DEBUGFUNCTION:
1820 * stderr write callback.
1822 data->set.fdebug = va_arg(param, curl_debug_callback);
1824 * if the callback provided is NULL, it'll use the default callback
1827 case CURLOPT_DEBUGDATA:
1829 * Set to a void * that should receive all error writes. This
1830 * defaults to CURLOPT_STDERR for normal operations.
1832 data->set.debugdata = va_arg(param, void *);
1834 case CURLOPT_STDERR:
1836 * Set to a FILE * that should receive all error writes. This
1837 * defaults to stderr for normal operations.
1839 data->set.err = va_arg(param, FILE *);
1841 data->set.err = stderr;
1843 case CURLOPT_HEADERFUNCTION:
1845 * Set header write callback
1847 data->set.fwrite_header = va_arg(param, curl_write_callback);
1849 case CURLOPT_WRITEFUNCTION:
1851 * Set data write callback
1853 data->set.fwrite_func = va_arg(param, curl_write_callback);
1854 if(!data->set.fwrite_func) {
1855 data->set.is_fwrite_set = 0;
1856 /* When set to NULL, reset to our internal default function */
1857 data->set.fwrite_func = (curl_write_callback)fwrite;
1860 data->set.is_fwrite_set = 1;
1862 case CURLOPT_READFUNCTION:
1864 * Read data callback
1866 data->set.fread_func_set = va_arg(param, curl_read_callback);
1867 if(!data->set.fread_func_set) {
1868 data->set.is_fread_set = 0;
1869 /* When set to NULL, reset to our internal default function */
1870 data->set.fread_func_set = (curl_read_callback)fread;
1873 data->set.is_fread_set = 1;
1875 case CURLOPT_SEEKFUNCTION:
1877 * Seek callback. Might be NULL.
1879 data->set.seek_func = va_arg(param, curl_seek_callback);
1881 case CURLOPT_SEEKDATA:
1883 * Seek control callback. Might be NULL.
1885 data->set.seek_client = va_arg(param, void *);
1887 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1889 * "Convert from network encoding" callback
1891 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1893 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1895 * "Convert to network encoding" callback
1897 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1899 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1901 * "Convert from UTF-8 encoding" callback
1903 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1905 case CURLOPT_IOCTLFUNCTION:
1907 * I/O control callback. Might be NULL.
1909 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1911 case CURLOPT_IOCTLDATA:
1913 * I/O control data pointer. Might be NULL.
1915 data->set.ioctl_client = va_arg(param, void *);
1917 case CURLOPT_SSLCERT:
1919 * String that holds file name of the SSL certificate to use
1921 result = setstropt(&data->set.str[STRING_CERT],
1922 va_arg(param, char *));
1924 case CURLOPT_SSLCERTTYPE:
1926 * String that holds file type of the SSL certificate to use
1928 result = setstropt(&data->set.str[STRING_CERT_TYPE],
1929 va_arg(param, char *));
1931 case CURLOPT_SSLKEY:
1933 * String that holds file name of the SSL key to use
1935 result = setstropt(&data->set.str[STRING_KEY],
1936 va_arg(param, char *));
1938 case CURLOPT_SSLKEYTYPE:
1940 * String that holds file type of the SSL key to use
1942 result = setstropt(&data->set.str[STRING_KEY_TYPE],
1943 va_arg(param, char *));
1945 case CURLOPT_KEYPASSWD:
1947 * String that holds the SSL or SSH private key password.
1949 result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1950 va_arg(param, char *));
1952 case CURLOPT_SSLENGINE:
1954 * String that holds the SSL crypto engine.
1956 argptr = va_arg(param, char *);
1957 if(argptr && argptr[0])
1958 result = Curl_ssl_set_engine(data, argptr);
1961 case CURLOPT_SSLENGINE_DEFAULT:
1963 * flag to set engine as default.
1965 result = Curl_ssl_set_engine_default(data);
1969 * Kludgy option to enable CRLF conversions. Subject for removal.
1971 data->set.crlf = (0 != va_arg(param, long)) ? TRUE : FALSE;
1974 case CURLOPT_INTERFACE:
1976 * Set what interface or address/hostname to bind the socket to when
1977 * performing an operation and thus what from-IP your connection will use.
1979 result = setstropt(&data->set.str[STRING_DEVICE],
1980 va_arg(param, char *));
1982 case CURLOPT_LOCALPORT:
1984 * Set what local port to bind the socket to when performing an operation.
1986 data->set.localport = curlx_sltous(va_arg(param, long));
1988 case CURLOPT_LOCALPORTRANGE:
1990 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
1992 data->set.localportrange = curlx_sltosi(va_arg(param, long));
1994 case CURLOPT_KRBLEVEL:
1996 * A string that defines the kerberos security level.
1998 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
1999 va_arg(param, char *));
2000 data->set.krb = (data->set.str[STRING_KRB_LEVEL]) ? TRUE : FALSE;
2002 case CURLOPT_GSSAPI_DELEGATION:
2004 * GSS-API credential delegation
2006 data->set.gssapi_delegation = va_arg(param, long);
2008 case CURLOPT_SSL_VERIFYPEER:
2010 * Enable peer SSL verifying.
2012 data->set.ssl.verifypeer = (0 != va_arg(param, long)) ? TRUE : FALSE;
2014 case CURLOPT_SSL_VERIFYHOST:
2016 * Enable verification of the host name in the peer certificate
2018 arg = va_arg(param, long);
2020 /* Obviously people are not reading documentation and too many thought
2021 this argument took a boolean when it wasn't and misused it. We thus ban
2022 1 as a sensible input and we warn about its use. Then we only have the
2023 2 action internally stored as TRUE. */
2026 failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
2027 return CURLE_BAD_FUNCTION_ARGUMENT;
2030 data->set.ssl.verifyhost = (0 != arg) ? TRUE : FALSE;
2032 case CURLOPT_SSL_VERIFYSTATUS:
2034 * Enable certificate status verifying.
2036 if(!Curl_ssl_cert_status_request()) {
2037 result = CURLE_NOT_BUILT_IN;
2041 data->set.ssl.verifystatus = (0 != va_arg(param, long)) ? TRUE : FALSE;
2043 case CURLOPT_SSL_CTX_FUNCTION:
2044 #ifdef have_curlssl_ssl_ctx
2046 * Set a SSL_CTX callback
2048 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
2050 result = CURLE_NOT_BUILT_IN;
2053 case CURLOPT_SSL_CTX_DATA:
2054 #ifdef have_curlssl_ssl_ctx
2056 * Set a SSL_CTX callback parameter pointer
2058 data->set.ssl.fsslctxp = va_arg(param, void *);
2060 result = CURLE_NOT_BUILT_IN;
2063 case CURLOPT_SSL_FALSESTART:
2065 * Enable TLS false start.
2067 if(!Curl_ssl_false_start()) {
2068 result = CURLE_NOT_BUILT_IN;
2072 data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE;
2074 case CURLOPT_CERTINFO:
2075 #ifdef have_curlssl_certinfo
2076 data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE;
2078 result = CURLE_NOT_BUILT_IN;
2081 case CURLOPT_PINNEDPUBLICKEY:
2082 #ifdef have_curlssl_pinnedpubkey /* only by supported backends */
2084 * Set pinned public key for SSL connection.
2085 * Specify file name of the public key in DER format.
2087 result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY],
2088 va_arg(param, char *));
2090 result = CURLE_NOT_BUILT_IN;
2093 case CURLOPT_CAINFO:
2095 * Set CA info for SSL connection. Specify file name of the CA certificate
2097 result = setstropt(&data->set.str[STRING_SSL_CAFILE],
2098 va_arg(param, char *));
2100 case CURLOPT_CAPATH:
2101 #ifdef have_curlssl_ca_path /* not supported by all backends */
2103 * Set CA path info for SSL connection. Specify directory name of the CA
2104 * certificates which have been prepared using openssl c_rehash utility.
2106 /* This does not work on windows. */
2107 result = setstropt(&data->set.str[STRING_SSL_CAPATH],
2108 va_arg(param, char *));
2110 result = CURLE_NOT_BUILT_IN;
2113 case CURLOPT_CRLFILE:
2115 * Set CRL file info for SSL connection. Specify file name of the CRL
2116 * to check certificates revocation
2118 result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
2119 va_arg(param, char *));
2121 case CURLOPT_ISSUERCERT:
2123 * Set Issuer certificate file
2124 * to check certificates issuer
2126 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
2127 va_arg(param, char *));
2129 case CURLOPT_TELNETOPTIONS:
2131 * Set a linked list of telnet options
2133 data->set.telnet_options = va_arg(param, struct curl_slist *);
2136 case CURLOPT_BUFFERSIZE:
2138 * The application kindly asks for a differently sized receive buffer.
2139 * If it seems reasonable, we'll use it.
2141 data->set.buffer_size = va_arg(param, long);
2143 if((data->set.buffer_size> (BUFSIZE -1)) ||
2144 (data->set.buffer_size < 1))
2145 data->set.buffer_size = 0; /* huge internal default */
2149 case CURLOPT_NOSIGNAL:
2151 * The application asks not to set any signal() or alarm() handlers,
2152 * even when using a timeout.
2154 data->set.no_signal = (0 != va_arg(param, long)) ? TRUE : FALSE;
2159 struct Curl_share *set;
2160 set = va_arg(param, struct Curl_share *);
2162 /* disconnect from old share, if any */
2164 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2166 if(data->dns.hostcachetype == HCACHE_SHARED) {
2167 data->dns.hostcache = NULL;
2168 data->dns.hostcachetype = HCACHE_NONE;
2171 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2172 if(data->share->cookies == data->cookies)
2173 data->cookies = NULL;
2176 if(data->share->sslsession == data->state.session)
2177 data->state.session = NULL;
2179 data->share->dirty--;
2181 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2185 /* use new share if it set */
2189 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2191 data->share->dirty++;
2193 if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) {
2194 /* use shared host cache */
2195 data->dns.hostcache = &data->share->hostcache;
2196 data->dns.hostcachetype = HCACHE_SHARED;
2198 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2199 if(data->share->cookies) {
2200 /* use shared cookie list, first free own one if any */
2201 Curl_cookie_cleanup(data->cookies);
2202 /* enable cookies since we now use a share that uses cookies! */
2203 data->cookies = data->share->cookies;
2205 #endif /* CURL_DISABLE_HTTP */
2206 if(data->share->sslsession) {
2207 data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions;
2208 data->state.session = data->share->sslsession;
2210 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2213 /* check for host cache not needed,
2214 * it will be done by curl_easy_perform */
2218 case CURLOPT_PRIVATE:
2220 * Set private data pointer.
2222 data->set.private_data = va_arg(param, void *);
2225 case CURLOPT_MAXFILESIZE:
2227 * Set the maximum size of a file to download.
2229 data->set.max_filesize = va_arg(param, long);
2233 case CURLOPT_USE_SSL:
2235 * Make transfers attempt to use SSL/TLS.
2237 data->set.use_ssl = (curl_usessl)va_arg(param, long);
2240 case CURLOPT_SSL_OPTIONS:
2241 arg = va_arg(param, long);
2242 data->set.ssl_enable_beast = !!(arg & CURLSSLOPT_ALLOW_BEAST);
2243 data->set.ssl_no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE);
2247 case CURLOPT_FTPSSLAUTH:
2249 * Set a specific auth for FTP-SSL transfers.
2251 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2254 case CURLOPT_IPRESOLVE:
2255 data->set.ipver = va_arg(param, long);
2258 case CURLOPT_MAXFILESIZE_LARGE:
2260 * Set the maximum size of a file to download.
2262 data->set.max_filesize = va_arg(param, curl_off_t);
2265 case CURLOPT_TCP_NODELAY:
2267 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2270 data->set.tcp_nodelay = (0 != va_arg(param, long)) ? TRUE : FALSE;
2273 case CURLOPT_FTP_ACCOUNT:
2274 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2275 va_arg(param, char *));
2278 case CURLOPT_IGNORE_CONTENT_LENGTH:
2279 data->set.ignorecl = (0 != va_arg(param, long)) ? TRUE : FALSE;
2282 case CURLOPT_CONNECT_ONLY:
2284 * No data transfer, set up connection and let application use the socket
2286 data->set.connect_only = (0 != va_arg(param, long)) ? TRUE : FALSE;
2289 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2290 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2291 va_arg(param, char *));
2294 case CURLOPT_SOCKOPTFUNCTION:
2296 * socket callback function: called after socket() but before connect()
2298 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2301 case CURLOPT_SOCKOPTDATA:
2303 * socket callback data pointer. Might be NULL.
2305 data->set.sockopt_client = va_arg(param, void *);
2308 case CURLOPT_OPENSOCKETFUNCTION:
2310 * open/create socket callback function: called instead of socket(),
2313 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2316 case CURLOPT_OPENSOCKETDATA:
2318 * socket callback data pointer. Might be NULL.
2320 data->set.opensocket_client = va_arg(param, void *);
2323 case CURLOPT_CLOSESOCKETFUNCTION:
2325 * close socket callback function: called instead of close()
2326 * when shutting down a connection
2328 data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
2331 case CURLOPT_CLOSESOCKETDATA:
2333 * socket callback data pointer. Might be NULL.
2335 data->set.closesocket_client = va_arg(param, void *);
2338 case CURLOPT_SSL_SESSIONID_CACHE:
2339 data->set.ssl.sessionid = (0 != va_arg(param, long)) ? TRUE : FALSE;
2343 /* we only include SSH options if explicitly built to support SSH */
2344 case CURLOPT_SSH_AUTH_TYPES:
2345 data->set.ssh_auth_types = va_arg(param, long);
2348 case CURLOPT_SSH_PUBLIC_KEYFILE:
2350 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2352 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2353 va_arg(param, char *));
2356 case CURLOPT_SSH_PRIVATE_KEYFILE:
2358 * Use this file instead of the $HOME/.ssh/id_dsa file
2360 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2361 va_arg(param, char *));
2363 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2365 * Option to allow for the MD5 of the host public key to be checked
2366 * for validation purposes.
2368 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2369 va_arg(param, char *));
2371 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2372 case CURLOPT_SSH_KNOWNHOSTS:
2374 * Store the file name to read known hosts from.
2376 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2377 va_arg(param, char *));
2380 case CURLOPT_SSH_KEYFUNCTION:
2381 /* setting to NULL is fine since the ssh.c functions themselves will
2382 then rever to use the internal default */
2383 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2386 case CURLOPT_SSH_KEYDATA:
2388 * Custom client data to pass to the SSH keyfunc callback
2390 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2392 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2394 #endif /* USE_LIBSSH2 */
2396 case CURLOPT_HTTP_TRANSFER_DECODING:
2398 * disable libcurl transfer encoding is used
2400 data->set.http_te_skip = (0 == va_arg(param, long)) ? TRUE : FALSE;
2403 case CURLOPT_HTTP_CONTENT_DECODING:
2405 * raw data passed to the application when content encoding is used
2407 data->set.http_ce_skip = (0 == va_arg(param, long)) ? TRUE : FALSE;
2410 case CURLOPT_NEW_FILE_PERMS:
2412 * Uses these permissions instead of 0644
2414 data->set.new_file_perms = va_arg(param, long);
2417 case CURLOPT_NEW_DIRECTORY_PERMS:
2419 * Uses these permissions instead of 0755
2421 data->set.new_directory_perms = va_arg(param, long);
2424 case CURLOPT_ADDRESS_SCOPE:
2426 * We always get longs when passed plain numericals, but for this value we
2427 * know that an unsigned int will always hold the value so we blindly
2428 * typecast to this type
2430 data->set.scope_id = curlx_sltoui(va_arg(param, long));
2433 case CURLOPT_PROTOCOLS:
2434 /* set the bitmask for the protocols that are allowed to be used for the
2435 transfer, which thus helps the app which takes URLs from users or other
2436 external inputs and want to restrict what protocol(s) to deal
2437 with. Defaults to CURLPROTO_ALL. */
2438 data->set.allowed_protocols = va_arg(param, long);
2441 case CURLOPT_REDIR_PROTOCOLS:
2442 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2443 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2444 to be set in both bitmasks to be allowed to get redirected to. Defaults
2445 to all protocols except FILE and SCP. */
2446 data->set.redir_protocols = va_arg(param, long);
2449 case CURLOPT_DEFAULT_PROTOCOL:
2450 /* Set the protocol to use when the URL doesn't include any protocol */
2451 result = setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL],
2452 va_arg(param, char *));
2455 case CURLOPT_MAIL_FROM:
2456 /* Set the SMTP mail originator */
2457 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2458 va_arg(param, char *));
2461 case CURLOPT_MAIL_AUTH:
2462 /* Set the SMTP auth originator */
2463 result = setstropt(&data->set.str[STRING_MAIL_AUTH],
2464 va_arg(param, char *));
2467 case CURLOPT_MAIL_RCPT:
2468 /* Set the list of mail recipients */
2469 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2472 case CURLOPT_SASL_IR:
2473 /* Enable/disable SASL initial response */
2474 data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
2477 case CURLOPT_RTSP_REQUEST:
2480 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2481 * Would this be better if the RTSPREQ_* were just moved into here?
2483 long curl_rtspreq = va_arg(param, long);
2484 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2485 switch(curl_rtspreq) {
2486 case CURL_RTSPREQ_OPTIONS:
2487 rtspreq = RTSPREQ_OPTIONS;
2490 case CURL_RTSPREQ_DESCRIBE:
2491 rtspreq = RTSPREQ_DESCRIBE;
2494 case CURL_RTSPREQ_ANNOUNCE:
2495 rtspreq = RTSPREQ_ANNOUNCE;
2498 case CURL_RTSPREQ_SETUP:
2499 rtspreq = RTSPREQ_SETUP;
2502 case CURL_RTSPREQ_PLAY:
2503 rtspreq = RTSPREQ_PLAY;
2506 case CURL_RTSPREQ_PAUSE:
2507 rtspreq = RTSPREQ_PAUSE;
2510 case CURL_RTSPREQ_TEARDOWN:
2511 rtspreq = RTSPREQ_TEARDOWN;
2514 case CURL_RTSPREQ_GET_PARAMETER:
2515 rtspreq = RTSPREQ_GET_PARAMETER;
2518 case CURL_RTSPREQ_SET_PARAMETER:
2519 rtspreq = RTSPREQ_SET_PARAMETER;
2522 case CURL_RTSPREQ_RECORD:
2523 rtspreq = RTSPREQ_RECORD;
2526 case CURL_RTSPREQ_RECEIVE:
2527 rtspreq = RTSPREQ_RECEIVE;
2530 rtspreq = RTSPREQ_NONE;
2533 data->set.rtspreq = rtspreq;
2538 case CURLOPT_RTSP_SESSION_ID:
2540 * Set the RTSP Session ID manually. Useful if the application is
2541 * resuming a previously established RTSP session
2543 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2544 va_arg(param, char *));
2547 case CURLOPT_RTSP_STREAM_URI:
2549 * Set the Stream URI for the RTSP request. Unless the request is
2550 * for generic server options, the application will need to set this.
2552 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2553 va_arg(param, char *));
2556 case CURLOPT_RTSP_TRANSPORT:
2558 * The content of the Transport: header for the RTSP request
2560 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2561 va_arg(param, char *));
2564 case CURLOPT_RTSP_CLIENT_CSEQ:
2566 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2567 * application is resuming a previously broken connection. The CSEQ
2568 * will increment from this new number henceforth.
2570 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2573 case CURLOPT_RTSP_SERVER_CSEQ:
2574 /* Same as the above, but for server-initiated requests */
2575 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2578 case CURLOPT_INTERLEAVEDATA:
2579 data->set.rtp_out = va_arg(param, void *);
2581 case CURLOPT_INTERLEAVEFUNCTION:
2582 /* Set the user defined RTP write function */
2583 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2586 case CURLOPT_WILDCARDMATCH:
2587 data->set.wildcardmatch = (0 != va_arg(param, long)) ? TRUE : FALSE;
2589 case CURLOPT_CHUNK_BGN_FUNCTION:
2590 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2592 case CURLOPT_CHUNK_END_FUNCTION:
2593 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2595 case CURLOPT_FNMATCH_FUNCTION:
2596 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2598 case CURLOPT_CHUNK_DATA:
2599 data->wildcard.customptr = va_arg(param, void *);
2601 case CURLOPT_FNMATCH_DATA:
2602 data->set.fnmatch_data = va_arg(param, void *);
2605 case CURLOPT_TLSAUTH_USERNAME:
2606 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
2607 va_arg(param, char *));
2608 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2609 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2611 case CURLOPT_TLSAUTH_PASSWORD:
2612 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
2613 va_arg(param, char *));
2614 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2615 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2617 case CURLOPT_TLSAUTH_TYPE:
2618 if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
2619 data->set.ssl.authtype = CURL_TLSAUTH_SRP;
2621 data->set.ssl.authtype = CURL_TLSAUTH_NONE;
2624 case CURLOPT_DNS_SERVERS:
2625 result = Curl_set_dns_servers(data, va_arg(param, char *));
2627 case CURLOPT_DNS_INTERFACE:
2628 result = Curl_set_dns_interface(data, va_arg(param, char *));
2630 case CURLOPT_DNS_LOCAL_IP4:
2631 result = Curl_set_dns_local_ip4(data, va_arg(param, char *));
2633 case CURLOPT_DNS_LOCAL_IP6:
2634 result = Curl_set_dns_local_ip6(data, va_arg(param, char *));
2637 case CURLOPT_TCP_KEEPALIVE:
2638 data->set.tcp_keepalive = (0 != va_arg(param, long)) ? TRUE : FALSE;
2640 case CURLOPT_TCP_KEEPIDLE:
2641 data->set.tcp_keepidle = va_arg(param, long);
2643 case CURLOPT_TCP_KEEPINTVL:
2644 data->set.tcp_keepintvl = va_arg(param, long);
2646 case CURLOPT_TCP_FASTOPEN:
2647 #if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN)
2648 data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE;
2650 result = CURLE_NOT_BUILT_IN;
2653 case CURLOPT_SSL_ENABLE_NPN:
2654 data->set.ssl_enable_npn = (0 != va_arg(param, long)) ? TRUE : FALSE;
2656 case CURLOPT_SSL_ENABLE_ALPN:
2657 data->set.ssl_enable_alpn = (0 != va_arg(param, long)) ? TRUE : FALSE;
2660 #ifdef USE_UNIX_SOCKETS
2661 case CURLOPT_UNIX_SOCKET_PATH:
2662 result = setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH],
2663 va_arg(param, char *));
2667 case CURLOPT_PATH_AS_IS:
2668 data->set.path_as_is = (0 != va_arg(param, long)) ? TRUE : FALSE;
2670 case CURLOPT_PIPEWAIT:
2671 data->set.pipewait = (0 != va_arg(param, long)) ? TRUE : FALSE;
2673 case CURLOPT_STREAM_WEIGHT:
2675 return CURLE_NOT_BUILT_IN;
2677 arg = va_arg(param, long);
2678 if((arg>=1) && (arg <= 256))
2679 data->set.stream_weight = (int)arg;
2682 case CURLOPT_STREAM_DEPENDS:
2683 case CURLOPT_STREAM_DEPENDS_E:
2686 return CURLE_NOT_BUILT_IN;
2688 struct Curl_easy *dep = va_arg(param, struct Curl_easy *);
2689 if(dep && GOOD_EASY_HANDLE(dep)) {
2690 data->set.stream_depends_on = dep;
2691 data->set.stream_depends_e = (option == CURLOPT_STREAM_DEPENDS_E);
2696 case CURLOPT_CONNECT_TO:
2697 data->set.connect_to = va_arg(param, struct curl_slist *);
2700 /* unknown tag and its companion, just ignore: */
2701 result = CURLE_UNKNOWN_OPTION;
2708 #ifdef USE_RECV_BEFORE_SEND_WORKAROUND
2709 static void conn_reset_postponed_data(struct connectdata *conn, int num)
2711 struct postponed_data * const psnd = &(conn->postponed[num]);
2713 DEBUGASSERT(psnd->allocated_size > 0);
2714 DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
2715 DEBUGASSERT(psnd->recv_size ?
2716 (psnd->recv_processed < psnd->recv_size) :
2717 (psnd->recv_processed == 0));
2718 DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
2720 psnd->buffer = NULL;
2721 psnd->allocated_size = 0;
2722 psnd->recv_size = 0;
2723 psnd->recv_processed = 0;
2725 psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
2726 #endif /* DEBUGBUILD */
2729 DEBUGASSERT (psnd->allocated_size == 0);
2730 DEBUGASSERT (psnd->recv_size == 0);
2731 DEBUGASSERT (psnd->recv_processed == 0);
2732 DEBUGASSERT (psnd->bindsock == CURL_SOCKET_BAD);
2736 static void conn_reset_all_postponed_data(struct connectdata *conn)
2738 conn_reset_postponed_data(conn, 0);
2739 conn_reset_postponed_data(conn, 1);
2741 #else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
2742 /* Use "do-nothing" macros instead of functions when workaround not used */
2743 #define conn_reset_postponed_data(c,n) do {} WHILE_FALSE
2744 #define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
2745 #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
2747 static void conn_free(struct connectdata *conn)
2752 /* possible left-overs from the async name resolvers */
2753 Curl_resolver_cancel(conn);
2755 /* close the SSL stuff before we close any sockets since they will/may
2756 write to the sockets */
2757 Curl_ssl_close(conn, FIRSTSOCKET);
2758 Curl_ssl_close(conn, SECONDARYSOCKET);
2760 /* close possibly still open sockets */
2761 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2762 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2763 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2764 Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
2765 if(CURL_SOCKET_BAD != conn->tempsock[0])
2766 Curl_closesocket(conn, conn->tempsock[0]);
2767 if(CURL_SOCKET_BAD != conn->tempsock[1])
2768 Curl_closesocket(conn, conn->tempsock[1]);
2770 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
2771 defined(NTLM_WB_ENABLED)
2772 Curl_ntlm_wb_cleanup(conn);
2775 Curl_safefree(conn->user);
2776 Curl_safefree(conn->passwd);
2777 Curl_safefree(conn->oauth_bearer);
2778 Curl_safefree(conn->options);
2779 Curl_safefree(conn->proxyuser);
2780 Curl_safefree(conn->proxypasswd);
2781 Curl_safefree(conn->allocptr.proxyuserpwd);
2782 Curl_safefree(conn->allocptr.uagent);
2783 Curl_safefree(conn->allocptr.userpwd);
2784 Curl_safefree(conn->allocptr.accept_encoding);
2785 Curl_safefree(conn->allocptr.te);
2786 Curl_safefree(conn->allocptr.rangeline);
2787 Curl_safefree(conn->allocptr.ref);
2788 Curl_safefree(conn->allocptr.host);
2789 Curl_safefree(conn->allocptr.cookiehost);
2790 Curl_safefree(conn->allocptr.rtsp_transport);
2791 Curl_safefree(conn->trailer);
2792 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2793 Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
2794 Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2795 Curl_safefree(conn->master_buffer);
2797 conn_reset_all_postponed_data(conn);
2799 Curl_llist_destroy(conn->send_pipe, NULL);
2800 Curl_llist_destroy(conn->recv_pipe, NULL);
2802 conn->send_pipe = NULL;
2803 conn->recv_pipe = NULL;
2805 Curl_safefree(conn->localdev);
2806 Curl_free_ssl_config(&conn->ssl_config);
2808 free(conn); /* free all the connection oriented data */
2812 * Disconnects the given connection. Note the connection may not be the
2813 * primary connection, like when freeing room in the connection cache or
2814 * killing of a dead old connection.
2816 * This function MUST NOT reset state in the Curl_easy struct if that
2817 * isn't strictly bound to the life-time of *this* particular connection.
2821 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2823 struct Curl_easy *data;
2825 return CURLE_OK; /* this is closed and fine already */
2829 DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
2834 * If this connection isn't marked to force-close, leave it open if there
2835 * are other users of it
2837 if(!conn->bits.close &&
2838 (conn->send_pipe->size + conn->recv_pipe->size)) {
2839 DEBUGF(infof(data, "Curl_disconnect, usecounter: %d\n",
2840 conn->send_pipe->size + conn->recv_pipe->size));
2844 if(conn->dns_entry != NULL) {
2845 Curl_resolv_unlock(data, conn->dns_entry);
2846 conn->dns_entry = NULL;
2849 Curl_hostcache_prune(data); /* kill old DNS cache entries */
2851 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
2852 /* Cleanup NTLM connection-related data */
2853 Curl_http_ntlm_cleanup(conn);
2856 if(conn->handler->disconnect)
2857 /* This is set if protocol-specific cleanups should be made */
2858 conn->handler->disconnect(conn, dead_connection);
2860 /* unlink ourselves! */
2861 infof(data, "Closing connection %ld\n", conn->connection_id);
2862 Curl_conncache_remove_conn(data->state.conn_cache, conn);
2864 free_fixed_hostname(&conn->host);
2865 free_fixed_hostname(&conn->conn_to_host);
2866 free_fixed_hostname(&conn->proxy);
2868 Curl_ssl_close(conn, FIRSTSOCKET);
2870 /* Indicate to all handles on the pipe that we're dead */
2871 if(Curl_pipeline_wanted(data->multi, CURLPIPE_ANY)) {
2872 signalPipeClose(conn->send_pipe, TRUE);
2873 signalPipeClose(conn->recv_pipe, TRUE);
2882 * This function should return TRUE if the socket is to be assumed to
2883 * be dead. Most commonly this happens when the server has closed the
2884 * connection due to inactivity.
2886 static bool SocketIsDead(curl_socket_t sock)
2889 bool ret_val = TRUE;
2891 sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2900 * IsPipeliningPossible() returns TRUE if the options set would allow
2901 * pipelining/multiplexing and the connection is using a HTTP protocol.
2903 static bool IsPipeliningPossible(const struct Curl_easy *handle,
2904 const struct connectdata *conn)
2906 /* If a HTTP protocol and pipelining is enabled */
2907 if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
2909 if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
2910 (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
2911 (handle->set.httpreq == HTTPREQ_GET ||
2912 handle->set.httpreq == HTTPREQ_HEAD))
2913 /* didn't ask for HTTP/1.0 and a GET or HEAD */
2916 if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
2917 (handle->set.httpversion >= CURL_HTTP_VERSION_2))
2924 int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
2925 struct curl_llist *pipeline)
2928 struct curl_llist_element *curr;
2930 curr = pipeline->head;
2932 if(curr->ptr == handle) {
2933 Curl_llist_remove(pipeline, curr, NULL);
2934 return 1; /* we removed a handle */
2943 #if 0 /* this code is saved here as it is useful for debugging purposes */
2944 static void Curl_printPipeline(struct curl_llist *pipeline)
2946 struct curl_llist_element *curr;
2948 curr = pipeline->head;
2950 struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
2951 infof(data, "Handle in pipeline: %s\n", data->state.path);
2957 static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
2959 struct curl_llist_element *curr = pipeline->head;
2961 return (struct Curl_easy *) curr->ptr;
2967 /* remove the specified connection from all (possible) pipelines and related
2969 void Curl_getoff_all_pipelines(struct Curl_easy *data,
2970 struct connectdata *conn)
2972 bool recv_head = (conn->readchannel_inuse &&
2973 Curl_recvpipe_head(data, conn));
2974 bool send_head = (conn->writechannel_inuse &&
2975 Curl_sendpipe_head(data, conn));
2977 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2978 Curl_pipeline_leave_read(conn);
2979 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2980 Curl_pipeline_leave_write(conn);
2983 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2985 struct curl_llist_element *curr;
2990 curr = pipeline->head;
2992 struct curl_llist_element *next = curr->next;
2993 struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
2995 #ifdef DEBUGBUILD /* debug-only code */
2996 if(data->magic != CURLEASY_MAGIC_NUMBER) {
2998 infof(data, "signalPipeClose() found BAAD easy handle\n");
3003 data->state.pipe_broke = TRUE;
3004 Curl_multi_handlePipeBreak(data);
3005 Curl_llist_remove(pipeline, curr, NULL);
3011 * This function finds the connection in the connection
3012 * cache that has been unused for the longest time.
3014 * Returns the pointer to the oldest idle connection, or NULL if none was
3017 struct connectdata *
3018 Curl_oldest_idle_connection(struct Curl_easy *data)
3020 struct conncache *bc = data->state.conn_cache;
3021 struct curl_hash_iterator iter;
3022 struct curl_llist_element *curr;
3023 struct curl_hash_element *he;
3027 struct connectdata *conn_candidate = NULL;
3028 struct connectbundle *bundle;
3032 Curl_hash_start_iterate(&bc->hash, &iter);
3034 he = Curl_hash_next_element(&iter);
3036 struct connectdata *conn;
3040 curr = bundle->conn_list->head;
3045 /* Set higher score for the age passed since the connection was used */
3046 score = Curl_tvdiff(now, conn->now);
3048 if(score > highscore) {
3050 conn_candidate = conn;
3056 he = Curl_hash_next_element(&iter);
3059 return conn_candidate;
3063 * This function finds the connection in the connection
3064 * bundle that has been unused for the longest time.
3066 * Returns the pointer to the oldest idle connection, or NULL if none was
3069 static struct connectdata *
3070 find_oldest_idle_connection_in_bundle(struct Curl_easy *data,
3071 struct connectbundle *bundle)
3073 struct curl_llist_element *curr;
3077 struct connectdata *conn_candidate = NULL;
3078 struct connectdata *conn;
3084 curr = bundle->conn_list->head;
3089 /* Set higher score for the age passed since the connection was used */
3090 score = Curl_tvdiff(now, conn->now);
3092 if(score > highscore) {
3094 conn_candidate = conn;
3100 return conn_candidate;
3104 * This function checks if given connection is dead and disconnects if so.
3105 * (That also removes it from the connection cache.)
3107 * Returns TRUE if the connection actually was dead and disconnected.
3109 static bool disconnect_if_dead(struct connectdata *conn,
3110 struct Curl_easy *data)
3112 size_t pipeLen = conn->send_pipe->size + conn->recv_pipe->size;
3113 if(!pipeLen && !conn->inuse) {
3114 /* The check for a dead socket makes sense only if there are no
3115 handles in pipeline and the connection isn't already marked in
3118 if(conn->handler->protocol & CURLPROTO_RTSP)
3119 /* RTSP is a special case due to RTP interleaving */
3120 dead = Curl_rtsp_connisdead(conn);
3122 dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
3126 infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
3128 /* disconnect resources */
3129 Curl_disconnect(conn, /* dead_connection */TRUE);
3137 * Wrapper to use disconnect_if_dead() function in Curl_conncache_foreach()
3141 static int call_disconnect_if_dead(struct connectdata *conn,
3144 struct Curl_easy* data = (struct Curl_easy*)param;
3145 disconnect_if_dead(conn, data);
3146 return 0; /* continue iteration */
3150 * This function scans the connection cache for half-open/dead connections,
3151 * closes and removes them.
3152 * The cleanup is done at most once per second.
3154 static void prune_dead_connections(struct Curl_easy *data)
3156 struct timeval now = Curl_tvnow();
3157 long elapsed = Curl_tvdiff(now, data->state.conn_cache->last_cleanup);
3159 if(elapsed >= 1000L) {
3160 Curl_conncache_foreach(data->state.conn_cache, data,
3161 call_disconnect_if_dead);
3162 data->state.conn_cache->last_cleanup = now;
3167 static size_t max_pipeline_length(struct Curl_multi *multi)
3169 return multi ? multi->max_pipeline_length : 0;
3174 * Given one filled in connection struct (named needle), this function should
3175 * detect if there already is one that has all the significant details
3176 * exactly the same and thus should be used instead.
3178 * If there is a match, this function returns TRUE - and has marked the
3179 * connection as 'in-use'. It must later be called with ConnectionDone() to
3180 * return back to 'idle' (unused) state.
3182 * The force_reuse flag is set if the connection must be used, even if
3183 * the pipelining strategy wants to open a new connection instead of reusing.
3186 ConnectionExists(struct Curl_easy *data,
3187 struct connectdata *needle,
3188 struct connectdata **usethis,
3192 struct connectdata *check;
3193 struct connectdata *chosen = 0;
3194 bool foundPendingCandidate = FALSE;
3195 bool canPipeline = IsPipeliningPossible(data, needle);
3196 struct connectbundle *bundle;
3199 bool wantNTLMhttp = ((data->state.authhost.want &
3200 (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
3201 (needle->handler->protocol & PROTO_FAMILY_HTTP));
3202 bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
3203 ((data->state.authproxy.want &
3204 (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
3205 (needle->handler->protocol & PROTO_FAMILY_HTTP)));
3208 *force_reuse = FALSE;
3211 /* We can't pipe if the site is blacklisted */
3212 if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
3213 canPipeline = FALSE;
3216 /* Look up the bundle with all the connections to this
3218 bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
3220 /* Max pipe length is zero (unlimited) for multiplexed connections */
3221 size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
3222 max_pipeline_length(data->multi):0;
3223 size_t best_pipe_len = max_pipe_len;
3224 struct curl_llist_element *curr;
3225 const char *hostname;
3227 if(needle->bits.conn_to_host)
3228 hostname = needle->conn_to_host.name;
3230 hostname = needle->host.name;
3232 infof(data, "Found bundle for host %s: %p [%s]\n",
3233 hostname, (void *)bundle,
3234 (bundle->multiuse== BUNDLE_PIPELINING?
3236 (bundle->multiuse== BUNDLE_MULTIPLEX?
3237 "can multiplex":"serially")));
3239 /* We can't pipe if we don't know anything about the server */
3241 if(bundle->multiuse <= BUNDLE_UNKNOWN) {
3242 if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
3243 infof(data, "Server doesn't support multi-use yet, wait\n");
3245 return FALSE; /* no re-use */
3248 infof(data, "Server doesn't support multi-use (yet)\n");
3249 canPipeline = FALSE;
3251 if((bundle->multiuse == BUNDLE_PIPELINING) &&
3252 !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
3253 /* not asked for, switch off */
3254 infof(data, "Could pipeline, but not asked to!\n");
3255 canPipeline = FALSE;
3257 else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
3258 !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
3259 infof(data, "Could multiplex, but not asked to!\n");
3260 canPipeline = FALSE;
3264 curr = bundle->conn_list->head;
3270 * Note that if we use a HTTP proxy in normal mode (no tunneling), we
3271 * check connections to that proxy and not to the actual remote server.
3276 if(disconnect_if_dead(check, data))
3279 pipeLen = check->send_pipe->size + check->recv_pipe->size;
3283 if(!check->bits.multiplex) {
3284 /* If not multiplexing, make sure the pipe has only GET requests */
3285 struct Curl_easy* sh = gethandleathead(check->send_pipe);
3286 struct Curl_easy* rh = gethandleathead(check->recv_pipe);
3288 if(!IsPipeliningPossible(sh, check))
3292 if(!IsPipeliningPossible(rh, check))
3299 /* can only happen within multi handles, and means that another easy
3300 handle is using this connection */
3304 if(Curl_resolver_asynch()) {
3305 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
3306 completed yet and until then we don't re-use this connection */
3307 if(!check->ip_addr_str[0]) {
3309 "Connection #%ld is still name resolving, can't reuse\n",
3310 check->connection_id);
3315 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
3316 check->bits.close) {
3317 if(!check->bits.close)
3318 foundPendingCandidate = TRUE;
3319 /* Don't pick a connection that hasn't connected yet or that is going
3321 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
3322 check->connection_id);
3324 if(check->recv_pipe->size > 0) {
3326 "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
3327 check->connection_id);
3334 if((needle->handler->flags&PROTOPT_SSL) !=
3335 (check->handler->flags&PROTOPT_SSL))
3336 /* don't do mixed SSL and non-SSL connections */
3337 if(get_protocol_family(check->handler->protocol) !=
3338 needle->handler->protocol || !check->tls_upgraded)
3339 /* except protocols that have been upgraded via TLS */
3342 if(needle->handler->flags&PROTOPT_SSL) {
3343 if((data->set.ssl.verifypeer != check->verifypeer) ||
3344 (data->set.ssl.verifyhost != check->verifyhost))
3348 if(needle->bits.proxy != check->bits.proxy)
3349 /* don't do mixed proxy and non-proxy connections */
3352 if(needle->bits.proxy &&
3353 (needle->proxytype != check->proxytype ||
3354 needle->bits.httpproxy != check->bits.httpproxy ||
3355 needle->bits.tunnel_proxy != check->bits.tunnel_proxy ||
3356 !Curl_raw_equal(needle->proxy.name, check->proxy.name) ||
3357 needle->port != check->port))
3358 /* don't mix connections that use different proxies */
3361 if(needle->bits.conn_to_host != check->bits.conn_to_host)
3362 /* don't mix connections that use the "connect to host" feature and
3363 * connections that don't use this feature */
3366 if(needle->bits.conn_to_port != check->bits.conn_to_port)
3367 /* don't mix connections that use the "connect to port" feature and
3368 * connections that don't use this feature */
3371 if(!canPipeline && check->inuse)
3372 /* this request can't be pipelined but the checked connection is
3373 already in use so we skip it */
3376 if(needle->localdev || needle->localport) {
3377 /* If we are bound to a specific local end (IP+port), we must not
3378 re-use a random other one, although if we didn't ask for a
3379 particular one we can reuse one that was bound.
3381 This comparison is a bit rough and too strict. Since the input
3382 parameters can be specified in numerous ways and still end up the
3383 same it would take a lot of processing to make it really accurate.
3384 Instead, this matching will assume that re-uses of bound connections
3385 will most likely also re-use the exact same binding parameters and
3386 missing out a few edge cases shouldn't hurt anyone very much.
3388 if((check->localport != needle->localport) ||
3389 (check->localportrange != needle->localportrange) ||
3391 !needle->localdev ||
3392 strcmp(check->localdev, needle->localdev))
3396 if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
3397 /* This protocol requires credentials per connection,
3398 so verify that we're using the same name and password as well */
3399 if(!strequal(needle->user, check->user) ||
3400 !strequal(needle->passwd, check->passwd)) {
3401 /* one of them was different */
3406 if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
3407 (needle->bits.httpproxy && needle->bits.tunnel_proxy)) {
3408 /* The requested connection does not use a HTTP proxy or it uses SSL or
3409 it is a non-SSL protocol tunneled over the same HTTP proxy name and
3411 if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
3412 (get_protocol_family(check->handler->protocol) ==
3413 needle->handler->protocol && check->tls_upgraded)) &&
3414 (!needle->bits.conn_to_host || Curl_raw_equal(
3415 needle->conn_to_host.name, check->conn_to_host.name)) &&
3416 (!needle->bits.conn_to_port ||
3417 needle->conn_to_port == check->conn_to_port) &&
3418 Curl_raw_equal(needle->host.name, check->host.name) &&
3419 needle->remote_port == check->remote_port) {
3420 /* The schemes match or the the protocol family is the same and the
3421 previous connection was TLS upgraded, and the hostname and host
3423 if(needle->handler->flags & PROTOPT_SSL) {
3424 /* This is a SSL connection so verify that we're using the same
3425 SSL options as well */
3426 if(!Curl_ssl_config_matches(&needle->ssl_config,
3427 &check->ssl_config)) {
3429 "Connection #%ld has different SSL parameters, "
3431 check->connection_id));
3434 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3435 foundPendingCandidate = TRUE;
3437 "Connection #%ld has not started SSL connect, "
3439 check->connection_id));
3447 /* The requested connection is using the same HTTP proxy in normal
3448 mode (no tunneling) */
3453 #if defined(USE_NTLM)
3454 /* If we are looking for an HTTP+NTLM connection, check if this is
3455 already authenticating with the right credentials. If not, keep
3456 looking so that we can reuse NTLM connections if
3457 possible. (Especially we must not reuse the same connection if
3458 partway through a handshake!) */
3460 if(!strequal(needle->user, check->user) ||
3461 !strequal(needle->passwd, check->passwd))
3464 else if(check->ntlm.state != NTLMSTATE_NONE) {
3465 /* Connection is using NTLM auth but we don't want NTLM */
3469 /* Same for Proxy NTLM authentication */
3470 if(wantProxyNTLMhttp) {
3471 /* Both check->proxyuser and check->proxypasswd can be NULL */
3472 if(!check->proxyuser || !check->proxypasswd)
3475 if(!strequal(needle->proxyuser, check->proxyuser) ||
3476 !strequal(needle->proxypasswd, check->proxypasswd))
3479 else if(check->proxyntlm.state != NTLMSTATE_NONE) {
3480 /* Proxy connection is using NTLM auth but we don't want NTLM */
3484 if(wantNTLMhttp || wantProxyNTLMhttp) {
3485 /* Credentials are already checked, we can use this connection */
3489 (check->ntlm.state != NTLMSTATE_NONE)) ||
3490 (wantProxyNTLMhttp &&
3491 (check->proxyntlm.state != NTLMSTATE_NONE))) {
3492 /* We must use this connection, no other */
3493 *force_reuse = TRUE;
3497 /* Continue look up for a better connection */
3502 /* We can pipeline if we want to. Let's continue looking for
3503 the optimal connection to use, i.e the shortest pipe that is not
3507 /* We have the optimal connection. Let's stop looking. */
3512 /* We can't use the connection if the pipe is full */
3513 if(max_pipe_len && (pipeLen >= max_pipe_len)) {
3514 infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
3518 /* If multiplexed, make sure we don't go over concurrency limit */
3519 if(check->bits.multiplex) {
3520 /* Multiplexed connections can only be HTTP/2 for now */
3521 struct http_conn *httpc = &check->proto.httpc;
3522 if(pipeLen >= httpc->settings.max_concurrent_streams) {
3523 infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
3529 /* We can't use the connection if the pipe is penalized */
3530 if(Curl_pipeline_penalized(data, check)) {
3531 infof(data, "Penalized, skip\n");
3536 if(pipeLen < best_pipe_len) {
3537 /* This connection has a shorter pipe so far. We'll pick this
3538 and continue searching */
3540 best_pipe_len = pipeLen;
3545 /* When not pipelining (== multiplexed), we have a match here! */
3547 infof(data, "Multiplexed connection found!\n");
3552 /* We have found a connection. Let's stop searching. */
3562 return TRUE; /* yes, we found one to use! */
3565 if(foundPendingCandidate && data->set.pipewait) {
3567 "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
3571 return FALSE; /* no matching connecting exists */
3574 /* after a TCP connection to the proxy has been verified, this function does
3575 the next magic step.
3577 Note: this function's sub-functions call failf()
3580 CURLcode Curl_connected_proxy(struct connectdata *conn,
3583 if(!conn->bits.proxy || sockindex)
3584 /* this magic only works for the primary socket as the secondary is used
3585 for FTP only and it has FTP specific magic in ftp.c */
3588 switch(conn->proxytype) {
3589 #ifndef CURL_DISABLE_PROXY
3590 case CURLPROXY_SOCKS5:
3591 case CURLPROXY_SOCKS5_HOSTNAME:
3592 return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3593 conn->bits.conn_to_host ? conn->conn_to_host.name :
3595 conn->bits.conn_to_port ? conn->conn_to_port :
3599 case CURLPROXY_SOCKS4:
3600 return Curl_SOCKS4(conn->proxyuser,
3601 conn->bits.conn_to_host ? conn->conn_to_host.name :
3603 conn->bits.conn_to_port ? conn->conn_to_port :
3605 FIRSTSOCKET, conn, FALSE);
3607 case CURLPROXY_SOCKS4A:
3608 return Curl_SOCKS4(conn->proxyuser,
3609 conn->bits.conn_to_host ? conn->conn_to_host.name :
3611 conn->bits.conn_to_port ? conn->conn_to_port :
3613 FIRSTSOCKET, conn, TRUE);
3615 #endif /* CURL_DISABLE_PROXY */
3616 case CURLPROXY_HTTP:
3617 case CURLPROXY_HTTP_1_0:
3618 /* do nothing here. handled later. */
3622 } /* switch proxytype */
3628 * verboseconnect() displays verbose information after a connect
3630 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3631 void Curl_verboseconnect(struct connectdata *conn)
3633 if(conn->data->set.verbose)
3634 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3635 conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3636 conn->ip_addr_str, conn->port, conn->connection_id);
3640 int Curl_protocol_getsock(struct connectdata *conn,
3641 curl_socket_t *socks,
3644 if(conn->handler->proto_getsock)
3645 return conn->handler->proto_getsock(conn, socks, numsocks);
3646 return GETSOCK_BLANK;
3649 int Curl_doing_getsock(struct connectdata *conn,
3650 curl_socket_t *socks,
3653 if(conn && conn->handler->doing_getsock)
3654 return conn->handler->doing_getsock(conn, socks, numsocks);
3655 return GETSOCK_BLANK;
3659 * We are doing protocol-specific connecting and this is being called over and
3660 * over from the multi interface until the connection phase is done on
3664 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3667 CURLcode result=CURLE_OK;
3669 if(conn && conn->handler->connecting) {
3671 result = conn->handler->connecting(conn, done);
3680 * We are DOING this is being called over and over from the multi interface
3681 * until the DOING phase is done on protocol layer.
3684 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3686 CURLcode result=CURLE_OK;
3688 if(conn && conn->handler->doing) {
3690 result = conn->handler->doing(conn, done);
3699 * We have discovered that the TCP connection has been successful, we can now
3700 * proceed with some action.
3703 CURLcode Curl_protocol_connect(struct connectdata *conn,
3704 bool *protocol_done)
3706 CURLcode result=CURLE_OK;
3708 *protocol_done = FALSE;
3710 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
3711 /* We already are connected, get back. This may happen when the connect
3712 worked fine in the first call, like when we connect to a local server
3713 or proxy. Note that we don't know if the protocol is actually done.
3715 Unless this protocol doesn't have any protocol-connect callback, as
3716 then we know we're done. */
3717 if(!conn->handler->connecting)
3718 *protocol_done = TRUE;
3723 if(!conn->bits.protoconnstart) {
3725 result = Curl_proxy_connect(conn);
3729 if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
3730 (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
3731 /* when using an HTTP tunnel proxy, await complete tunnel establishment
3732 before proceeding further. Return CURLE_OK so we'll be called again */
3735 if(conn->handler->connect_it) {
3736 /* is there a protocol-specific connect() procedure? */
3738 /* Call the protocol-specific connect function */
3739 result = conn->handler->connect_it(conn, protocol_done);
3742 *protocol_done = TRUE;
3744 /* it has started, possibly even completed but that knowledge isn't stored
3747 conn->bits.protoconnstart = TRUE;
3750 return result; /* pass back status */
3754 * Helpers for IDNA convertions.
3756 static bool is_ASCII_name(const char *hostname)
3758 const unsigned char *ch = (const unsigned char*)hostname;
3769 * Check if characters in hostname is allowed in Top Level Domain.
3771 static bool tld_check_name(struct Curl_easy *data,
3772 const char *ace_hostname)
3775 char *uc_name = NULL;
3777 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3778 const char *tld_errmsg = "<no msg>";
3783 /* Convert (and downcase) ACE-name back into locale's character set */
3784 rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3785 if(rc != IDNA_SUCCESS)
3788 /* Warning: err_pos receives "the decoded character offset rather than the
3789 byte position in the string." And as of libidn 1.32 that character offset
3790 is for UTF-8, even if the passed in string is another locale. */
3791 rc = tld_check_lz(uc_name, &err_pos, NULL);
3792 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3793 #ifdef HAVE_TLD_STRERROR
3794 if(rc != TLD_SUCCESS)
3795 tld_errmsg = tld_strerror((Tld_rc)rc);
3797 if(rc != TLD_SUCCESS)
3798 infof(data, "WARNING: TLD check for %s failed; %s\n",
3799 uc_name, tld_errmsg);
3800 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3803 if(rc != TLD_SUCCESS)
3811 * Perform any necessary IDN conversion of hostname
3813 static void fix_hostname(struct Curl_easy *data,
3814 struct connectdata *conn, struct hostname *host)
3821 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3825 /* set the name we use to display the host name */
3826 host->dispname = host->name;
3828 len = strlen(host->name);
3829 if(len && (host->name[len-1] == '.'))
3830 /* strip off a single trailing dot if present, primarily for SNI but
3831 there's no use for it */
3832 host->name[len-1]=0;
3834 /* Check name for non-ASCII and convert hostname to ACE form if we can */
3835 if(!is_ASCII_name(host->name)) {
3837 if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3838 char *ace_hostname = NULL;
3840 int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3841 infof(data, "Input domain encoded as `%s'\n",
3842 stringprep_locale_charset());
3843 if(rc == IDNA_SUCCESS) {
3844 /* tld_check_name() displays a warning if the host name contains
3845 "illegal" characters for this TLD */
3846 (void)tld_check_name(data, ace_hostname);
3848 host->encalloc = ace_hostname;
3849 /* change the name pointer to point to the encoded hostname */
3850 host->name = host->encalloc;
3853 infof(data, "Failed to convert %s to ACE; %s\n", host->name,
3854 Curl_idn_strerror(conn, rc));
3856 #elif defined(USE_WIN32_IDN)
3857 char *ace_hostname = NULL;
3859 if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
3860 host->encalloc = ace_hostname;
3861 /* change the name pointer to point to the encoded hostname */
3862 host->name = host->encalloc;
3865 infof(data, "Failed to convert %s to ACE;\n", host->name);
3867 infof(data, "IDN support not present, can't parse Unicode domains\n");
3873 * Frees data allocated by fix_hostname()
3875 static void free_fixed_hostname(struct hostname *host)
3877 #if defined(USE_LIBIDN)
3878 if(host->encalloc) {
3879 idn_free(host->encalloc); /* must be freed with idn_free() since this was
3880 allocated by libidn */
3881 host->encalloc = NULL;
3883 #elif defined(USE_WIN32_IDN)
3884 free(host->encalloc); /* must be freed withidn_free() since this was
3885 allocated by curl_win32_idn_to_ascii */
3886 host->encalloc = NULL;
3892 static void llist_dtor(void *user, void *element)
3900 * Allocate and initialize a new connectdata object.
3902 static struct connectdata *allocate_conn(struct Curl_easy *data)
3904 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3908 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
3909 already from start to avoid NULL
3910 situations and checks */
3912 /* and we setup a few fields in case we end up actually using this struct */
3914 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3915 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3916 conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
3917 conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
3918 conn->connection_id = -1; /* no ID */
3919 conn->port = -1; /* unknown at this point */
3920 conn->remote_port = -1; /* unknown */
3921 #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
3922 conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
3923 conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
3924 #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
3926 /* Default protocol-independent behavior doesn't support persistent
3927 connections, so we set this to force-close. Protocols that support
3928 this need to set this to FALSE in their "curl_do" functions. */
3929 connclose(conn, "Default to force-close");
3931 /* Store creation time to help future close decision making */
3932 conn->created = Curl_tvnow();
3934 conn->data = data; /* Setup the association between this connection
3935 and the Curl_easy */
3937 conn->proxytype = data->set.proxytype; /* type */
3939 #ifdef CURL_DISABLE_PROXY
3941 conn->bits.proxy = FALSE;
3942 conn->bits.httpproxy = FALSE;
3943 conn->bits.proxy_user_passwd = FALSE;
3944 conn->bits.tunnel_proxy = FALSE;
3946 #else /* CURL_DISABLE_PROXY */
3948 /* note that these two proxy bits are now just on what looks to be
3949 requested, they may be altered down the road */
3950 conn->bits.proxy = (data->set.str[STRING_PROXY] &&
3951 *data->set.str[STRING_PROXY]) ? TRUE : FALSE;
3952 conn->bits.httpproxy = (conn->bits.proxy &&
3953 (conn->proxytype == CURLPROXY_HTTP ||
3954 conn->proxytype == CURLPROXY_HTTP_1_0)) ?
3956 conn->bits.proxy_user_passwd = (data->set.str[STRING_PROXYUSERNAME]) ?
3958 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3960 #endif /* CURL_DISABLE_PROXY */
3962 conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
3963 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3964 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3966 conn->verifypeer = data->set.ssl.verifypeer;
3967 conn->verifyhost = data->set.ssl.verifyhost;
3969 conn->ip_version = data->set.ipver;
3971 #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
3972 defined(NTLM_WB_ENABLED)
3973 conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
3974 conn->ntlm_auth_hlpr_pid = 0;
3975 conn->challenge_header = NULL;
3976 conn->response_header = NULL;
3979 if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
3980 !conn->master_buffer) {
3981 /* Allocate master_buffer to be used for HTTP/1 pipelining */
3982 conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3983 if(!conn->master_buffer)
3987 /* Initialize the pipeline lists */
3988 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3989 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3990 if(!conn->send_pipe || !conn->recv_pipe)
3994 conn->data_prot = PROT_CLEAR;
3997 /* Store the local bind parameters that will be used for this connection */
3998 if(data->set.str[STRING_DEVICE]) {
3999 conn->localdev = strdup(data->set.str[STRING_DEVICE]);
4003 conn->localportrange = data->set.localportrange;
4004 conn->localport = data->set.localport;
4006 /* the close socket stuff needs to be copied to the connection struct as
4007 it may live on without (this specific) Curl_easy */
4008 conn->fclosesocket = data->set.fclosesocket;
4009 conn->closesocket_client = data->set.closesocket_client;
4014 Curl_llist_destroy(conn->send_pipe, NULL);
4015 Curl_llist_destroy(conn->recv_pipe, NULL);
4017 conn->send_pipe = NULL;
4018 conn->recv_pipe = NULL;
4020 free(conn->master_buffer);
4021 free(conn->localdev);
4026 static CURLcode findprotocol(struct Curl_easy *data,
4027 struct connectdata *conn,
4028 const char *protostr)
4030 const struct Curl_handler * const *pp;
4031 const struct Curl_handler *p;
4033 /* Scan protocol handler table and match against 'protostr' to set a few
4034 variables based on the URL. Now that the handler may be changed later
4035 when the protocol specific setup function is called. */
4036 for(pp = protocols; (p = *pp) != NULL; pp++) {
4037 if(Curl_raw_equal(p->scheme, protostr)) {
4038 /* Protocol found in table. Check if allowed */
4039 if(!(data->set.allowed_protocols & p->protocol))
4043 /* it is allowed for "normal" request, now do an extra check if this is
4044 the result of a redirect */
4045 if(data->state.this_is_a_follow &&
4046 !(data->set.redir_protocols & p->protocol))
4050 /* Perform setup complement if some. */
4051 conn->handler = conn->given = p;
4053 /* 'port' and 'remote_port' are set in setup_connection_internals() */
4059 /* The protocol was not found in the table, but we don't have to assign it
4060 to anything since it is already assigned to a dummy-struct in the
4061 create_conn() function when the connectdata struct is allocated. */
4062 failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
4065 return CURLE_UNSUPPORTED_PROTOCOL;
4069 * Parse URL and fill in the relevant members of the connection struct.
4071 static CURLcode parseurlandfillconn(struct Curl_easy *data,
4072 struct connectdata *conn,
4074 char **userp, char **passwdp,
4079 char *path = data->state.path;
4082 char protobuf[16] = "";
4083 const char *protop = "";
4085 bool rebuild_url = FALSE;
4087 *prot_missing = FALSE;
4089 /* We might pass the entire URL into the request so we need to make sure
4090 * there are no bad characters in there.*/
4091 if(strpbrk(data->change.url, "\r\n")) {
4092 failf(data, "Illegal characters found in URL");
4093 return CURLE_URL_MALFORMAT;
4096 /*************************************************************
4099 * We need to parse the url even when using the proxy, because we will need
4100 * the hostname and port in case we are trying to SSL connect through the
4101 * proxy -- and we don't know if we will need to use SSL until we parse the
4103 ************************************************************/
4104 if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
4106 Curl_raw_equal(protobuf, "file")) {
4107 if(path[0] == '/' && path[1] == '/') {
4108 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
4109 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
4110 * file://localhost/<path> is similar to how other schemes treat missing
4111 * hostnames. See RFC 1808. */
4113 /* This cannot be done with strcpy() in a portable manner, since the
4114 memory areas overlap! */
4115 memmove(path, path + 2, strlen(path + 2)+1);
4118 * we deal with file://<host>/<path> differently since it supports no
4119 * hostname other than "localhost" and "127.0.0.1", which is unique among
4120 * the URL protocols specified in RFC 1738
4122 if(path[0] != '/') {
4123 /* the URL included a host name, we ignore host names in file:// URLs
4124 as the standards don't define what to do with them */
4125 char *ptr=strchr(path, '/');
4127 /* there was a slash present
4129 RFC1738 (section 3.1, page 5) says:
4131 The rest of the locator consists of data specific to the scheme,
4132 and is known as the "url-path". It supplies the details of how the
4133 specified resource can be accessed. Note that the "/" between the
4134 host (or port) and the url-path is NOT part of the url-path.
4136 As most agents use file://localhost/foo to get '/foo' although the
4137 slash preceding foo is a separator and not a slash for the path,
4138 a URL as file://localhost//foo must be valid as well, to refer to
4139 the same file with an absolute path.
4142 if(ptr[1] && ('/' == ptr[1]))
4143 /* if there was two slashes, we skip the first one as that is then
4144 used truly as a separator */
4147 /* This cannot be made with strcpy, as the memory chunks overlap! */
4148 memmove(path, ptr, strlen(ptr)+1);
4152 protop = "file"; /* protocol string */
4159 rc = sscanf(data->change.url,
4160 "%15[^\n:]:%3[/]%[^\n/?]%[^\n]",
4161 protobuf, slashbuf, conn->host.name, path);
4163 failf(data, "Bad URL");
4164 return CURLE_URL_MALFORMAT;
4169 * The URL was badly formatted, let's try the browser-style _without_
4170 * protocol specified like 'http://'.
4172 rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
4175 * We couldn't even get this format.
4176 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
4177 * assigned, but the return value is EOF!
4179 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
4180 if(!(rc == -1 && *conn->host.name))
4183 failf(data, "<url> malformed");
4184 return CURLE_URL_MALFORMAT;
4189 * Since there was no protocol part specified in the URL use the
4190 * user-specified default protocol. If we weren't given a default make a
4191 * guess by matching some protocols against the host's outermost
4192 * sub-domain name. Finally if there was no match use HTTP.
4195 protop = data->set.str[STRING_DEFAULT_PROTOCOL];
4197 /* Note: if you add a new protocol, please update the list in
4198 * lib/version.c too! */
4199 if(checkprefix("FTP.", conn->host.name))
4201 else if(checkprefix("DICT.", conn->host.name))
4203 else if(checkprefix("LDAP.", conn->host.name))
4205 else if(checkprefix("IMAP.", conn->host.name))
4207 else if(checkprefix("SMTP.", conn->host.name))
4209 else if(checkprefix("POP3.", conn->host.name))
4215 *prot_missing = TRUE; /* not given in URL */
4218 size_t s = strlen(slashbuf);
4221 infof(data, "Unwillingly accepted illegal URL using %d slash%s!\n",
4224 if(data->change.url_alloc)
4225 free(data->change.url);
4226 /* repair the URL to use two slashes */
4227 data->change.url = aprintf("%s://%s%s",
4228 protobuf, conn->host.name, path);
4229 if(!data->change.url)
4230 return CURLE_OUT_OF_MEMORY;
4231 data->change.url_alloc = TRUE;
4236 /* We search for '?' in the host name (but only on the right side of a
4237 * @-letter to allow ?-letters in username and password) to handle things
4238 * like http://example.com?param= (notice the missing '/').
4240 at = strchr(conn->host.name, '@');
4242 query = strchr(at+1, '?');
4244 query = strchr(conn->host.name, '?');
4247 /* We must insert a slash before the '?'-letter in the URL. If the URL had
4248 a slash after the '?', that is where the path currently begins and the
4249 '?string' is still part of the host name.
4251 We must move the trailing part from the host name and put it first in
4252 the path. And have it all prefixed with a slash.
4255 size_t hostlen = strlen(query);
4256 size_t pathlen = strlen(path);
4258 /* move the existing path plus the zero byte forward, to make room for
4259 the host-name part */
4260 memmove(path+hostlen+1, path, pathlen+1);
4262 /* now copy the trailing host part in front of the existing path */
4263 memcpy(path+1, query, hostlen);
4265 path[0]='/'; /* prepend the missing slash */
4268 *query=0; /* now cut off the hostname at the ? */
4271 /* if there's no path set, use a single slash */
4276 /* If the URL is malformatted (missing a '/' after hostname before path) we
4277 * insert a slash here. The only letter except '/' we accept to start a path
4280 if(path[0] == '?') {
4281 /* We need this function to deal with overlapping memory areas. We know
4282 that the memory area 'path' points to is 'urllen' bytes big and that
4283 is bigger than the path. Use +1 to move the zero byte too. */
4284 memmove(&path[1], path, strlen(path)+1);
4288 else if(!data->set.path_as_is) {
4289 /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
4290 char *newp = Curl_dedotdotify(path);
4292 return CURLE_OUT_OF_MEMORY;
4294 if(strcmp(newp, path)) {
4296 free(data->state.pathbuffer);
4297 data->state.pathbuffer = newp;
4298 data->state.path = newp;
4306 * "rebuild_url" means that one or more URL components have been modified so
4307 * we need to generate an updated full version. We need the corrected URL
4308 * when communicating over HTTP proxy and we don't know at this point if
4309 * we're using a proxy or not.
4314 size_t plen = strlen(path); /* new path, should be 1 byte longer than
4316 size_t urllen = strlen(data->change.url); /* original URL length */
4318 size_t prefixlen = strlen(conn->host.name);
4321 prefixlen += strlen(protop) + strlen("://");
4323 reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */
4325 return CURLE_OUT_OF_MEMORY;
4327 /* copy the prefix */
4328 memcpy(reurl, data->change.url, prefixlen);
4330 /* append the trailing piece + zerobyte */
4331 memcpy(&reurl[prefixlen], path, plen + 1);
4333 /* possible free the old one */
4334 if(data->change.url_alloc) {
4335 Curl_safefree(data->change.url);
4336 data->change.url_alloc = FALSE;
4339 infof(data, "Rebuilt URL to: %s\n", reurl);
4341 data->change.url = reurl;
4342 data->change.url_alloc = TRUE; /* free this later */
4346 * Parse the login details from the URL and strip them out of
4349 result = parse_url_login(data, conn, userp, passwdp, optionsp);
4353 if(conn->host.name[0] == '[') {
4354 /* This looks like an IPv6 address literal. See if there is an address
4355 scope if there is no location header */
4356 char *percent = strchr(conn->host.name, '%');
4358 unsigned int identifier_offset = 3;
4360 unsigned long scope;
4361 if(strncmp("%25", percent, 3) != 0) {
4363 "Please URL encode %% as %%25, see RFC 6874.\n");
4364 identifier_offset = 1;
4366 scope = strtoul(percent + identifier_offset, &endp, 10);
4368 /* The address scope was well formed. Knock it out of the
4370 memmove(percent, endp, strlen(endp)+1);
4371 conn->scope_id = (unsigned int)scope;
4374 /* Zone identifier is not numeric */
4375 #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
4376 char ifname[IFNAMSIZ + 2];
4377 char *square_bracket;
4378 unsigned int scopeidx = 0;
4379 strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
4380 /* Ensure nullbyte termination */
4381 ifname[IFNAMSIZ + 1] = '\0';
4382 square_bracket = strchr(ifname, ']');
4383 if(square_bracket) {
4385 *square_bracket = '\0';
4386 scopeidx = if_nametoindex(ifname);
4388 infof(data, "Invalid network interface: %s; %s\n", ifname,
4393 char *p = percent + identifier_offset + strlen(ifname);
4395 /* Remove zone identifier from hostname */
4396 memmove(percent, p, strlen(p) + 1);
4397 conn->scope_id = scopeidx;
4400 #endif /* HAVE_NET_IF_H && IFNAMSIZ */
4401 infof(data, "Invalid IPv6 address format\n");
4406 if(data->set.scope_id)
4407 /* Override any scope that was set above. */
4408 conn->scope_id = data->set.scope_id;
4410 /* Remove the fragment part of the path. Per RFC 2396, this is always the
4411 last part of the URI. We are looking for the first '#' so that we deal
4412 gracefully with non conformant URI such as http://example.com#foo#bar. */
4413 fragment = strchr(path, '#');
4417 /* we know the path part ended with a fragment, so we know the full URL
4418 string does too and we need to cut it off from there so it isn't used
4420 fragment = strchr(data->change.url, '#');
4426 * So if the URL was A://B/C#D,
4428 * conn->host.name is B
4429 * data->state.path is /C
4432 return findprotocol(data, conn, protop);
4436 * If we're doing a resumed transfer, we need to setup our stuff
4439 static CURLcode setup_range(struct Curl_easy *data)
4441 struct UrlState *s = &data->state;
4442 s->resume_from = data->set.set_resume_from;
4443 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
4444 if(s->rangestringalloc)
4448 s->range = aprintf("%" CURL_FORMAT_CURL_OFF_TU "-", s->resume_from);
4450 s->range = strdup(data->set.str[STRING_SET_RANGE]);
4452 s->rangestringalloc = (s->range) ? TRUE : FALSE;
4455 return CURLE_OUT_OF_MEMORY;
4457 /* tell ourselves to fetch this range */
4458 s->use_range = TRUE; /* enable range download */
4461 s->use_range = FALSE; /* disable range download */
4468 * setup_connection_internals() -
4470 * Setup connection internals specific to the requested protocol in the
4471 * Curl_easy. This is inited and setup before the connection is made but
4472 * is about the particular protocol that is to be used.
4474 * This MUST get called after proxy magic has been figured out.
4476 static CURLcode setup_connection_internals(struct connectdata *conn)
4478 const struct Curl_handler * p;
4480 struct Curl_easy *data = conn->data;
4482 /* in some case in the multi state-machine, we go back to the CONNECT state
4483 and then a second (or third or...) call to this function will be made
4484 without doing a DISCONNECT or DONE in between (since the connection is
4485 yet in place) and therefore this function needs to first make sure
4486 there's no lingering previous data allocated. */
4487 Curl_free_request_state(data);
4489 memset(&data->req, 0, sizeof(struct SingleRequest));
4490 data->req.maxdownload = -1;
4492 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
4494 /* Perform setup complement if some. */
4497 if(p->setup_connection) {
4498 result = (*p->setup_connection)(conn);
4503 p = conn->handler; /* May have changed. */
4507 /* we check for -1 here since if proxy was detected already, this
4508 was very likely already set to the proxy port */
4509 conn->port = p->defport;
4515 * Curl_free_request_state() should free temp data that was allocated in the
4516 * Curl_easy for this single request.
4519 void Curl_free_request_state(struct Curl_easy *data)
4521 Curl_safefree(data->req.protop);
4522 Curl_safefree(data->req.newurl);
4526 #ifndef CURL_DISABLE_PROXY
4527 /****************************************************************
4528 * Checks if the host is in the noproxy list. returns true if it matches
4529 * and therefore the proxy should NOT be used.
4530 ****************************************************************/
4531 static bool check_noproxy(const char* name, const char* no_proxy)
4533 /* no_proxy=domain1.dom,host.domain2.dom
4534 * (a comma-separated list of hosts which should
4535 * not be proxied, or an asterisk to override
4536 * all proxy variables)
4540 const char* separator = ", ";
4541 size_t no_proxy_len;
4545 if(no_proxy && no_proxy[0]) {
4546 if(Curl_raw_equal("*", no_proxy)) {
4550 /* NO_PROXY was specified and it wasn't just an asterisk */
4552 no_proxy_len = strlen(no_proxy);
4553 endptr = strchr(name, ':');
4555 namelen = endptr - name;
4557 namelen = strlen(name);
4559 for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
4560 while(tok_start < no_proxy_len &&
4561 strchr(separator, no_proxy[tok_start]) != NULL) {
4562 /* Look for the beginning of the token. */
4566 if(tok_start == no_proxy_len)
4567 break; /* It was all trailing separator chars, no more tokens. */
4569 for(tok_end = tok_start; tok_end < no_proxy_len &&
4570 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
4571 /* Look for the end of the token. */
4574 /* To match previous behaviour, where it was necessary to specify
4575 * ".local.com" to prevent matching "notlocal.com", we will leave
4578 if(no_proxy[tok_start] == '.')
4581 if((tok_end - tok_start) <= namelen) {
4582 /* Match the last part of the name to the domain we are checking. */
4583 const char *checkn = name + namelen - (tok_end - tok_start);
4584 if(Curl_raw_nequal(no_proxy + tok_start, checkn,
4585 tok_end - tok_start)) {
4586 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
4587 /* We either have an exact match, or the previous character is a .
4588 * so it is within the same domain, so no proxy for this host.
4593 } /* if((tok_end - tok_start) <= namelen) */
4594 } /* for(tok_start = 0; tok_start < no_proxy_len;
4595 tok_start = tok_end + 1) */
4596 } /* NO_PROXY was specified and it wasn't just an asterisk */
4601 /****************************************************************
4602 * Detect what (if any) proxy to use. Remember that this selects a host
4603 * name and is not limited to HTTP proxies only.
4604 * The returned pointer must be freed by the caller (unless NULL)
4605 ****************************************************************/
4606 static char *detect_proxy(struct connectdata *conn)
4610 #ifndef CURL_DISABLE_HTTP
4611 /* If proxy was not specified, we check for default proxy environment
4612 * variables, to enable i.e Lynx compliance:
4614 * http_proxy=http://some.server.dom:port/
4615 * https_proxy=http://some.server.dom:port/
4616 * ftp_proxy=http://some.server.dom:port/
4617 * no_proxy=domain1.dom,host.domain2.dom
4618 * (a comma-separated list of hosts which should
4619 * not be proxied, or an asterisk to override
4620 * all proxy variables)
4621 * all_proxy=http://some.server.dom:port/
4622 * (seems to exist for the CERN www lib. Probably
4623 * the first to check for.)
4625 * For compatibility, the all-uppercase versions of these variables are
4626 * checked if the lowercase versions don't exist.
4628 char *no_proxy=NULL;
4629 char proxy_env[128];
4631 no_proxy=curl_getenv("no_proxy");
4633 no_proxy=curl_getenv("NO_PROXY");
4635 if(!check_noproxy(conn->host.name, no_proxy)) {
4636 /* It was not listed as without proxy */
4637 const char *protop = conn->handler->scheme;
4638 char *envp = proxy_env;
4641 /* Now, build <protocol>_proxy and check for such a one to use */
4643 *envp++ = (char)tolower((int)*protop++);
4646 strcpy(envp, "_proxy");
4648 /* read the protocol proxy: */
4649 prox=curl_getenv(proxy_env);
4652 * We don't try the uppercase version of HTTP_PROXY because of
4655 * When curl is used in a webserver application
4656 * environment (cgi or php), this environment variable can
4657 * be controlled by the web server user by setting the
4658 * http header 'Proxy:' to some value.
4660 * This can cause 'internal' http/ftp requests to be
4661 * arbitrarily redirected by any external attacker.
4663 if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4664 /* There was no lowercase variable, try the uppercase version: */
4665 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4666 prox=curl_getenv(proxy_env);
4670 proxy = prox; /* use this */
4672 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4674 proxy=curl_getenv("ALL_PROXY");
4676 } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4680 #else /* !CURL_DISABLE_HTTP */
4683 #endif /* CURL_DISABLE_HTTP */
4689 * If this is supposed to use a proxy, we need to figure out the proxy
4690 * host name, so that we can re-use an existing connection
4691 * that may exist registered to the same proxy host.
4693 static CURLcode parse_proxy(struct Curl_easy *data,
4694 struct connectdata *conn, char *proxy)
4699 /* We use 'proxyptr' to point to the proxy name from now on... */
4704 /* We do the proxy host string parsing here. We want the host name and the
4705 * port name. Accept a protocol:// prefix
4708 /* Parse the protocol part if present */
4709 endofprot = strstr(proxy, "://");
4711 proxyptr = endofprot+3;
4712 if(checkprefix("socks5h", proxy))
4713 conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
4714 else if(checkprefix("socks5", proxy))
4715 conn->proxytype = CURLPROXY_SOCKS5;
4716 else if(checkprefix("socks4a", proxy))
4717 conn->proxytype = CURLPROXY_SOCKS4A;
4718 else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
4719 conn->proxytype = CURLPROXY_SOCKS4;
4720 else if(checkprefix("http:", proxy))
4721 ; /* leave it as HTTP or HTTP/1.0 */
4723 /* Any other xxx:// reject! */
4724 failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
4725 return CURLE_COULDNT_CONNECT;
4729 proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
4731 /* Is there a username and password given in this proxy url? */
4732 atsign = strchr(proxyptr, '@');
4734 char *proxyuser = NULL;
4735 char *proxypasswd = NULL;
4737 parse_login_details(proxyptr, atsign - proxyptr,
4738 &proxyuser, &proxypasswd, NULL);
4740 /* found user and password, rip them out. note that we are
4741 unescaping them, as there is otherwise no way to have a
4742 username or password with reserved characters like ':' in
4744 Curl_safefree(conn->proxyuser);
4745 if(proxyuser && strlen(proxyuser) < MAX_CURL_USER_LENGTH)
4746 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4748 conn->proxyuser = strdup("");
4750 if(!conn->proxyuser)
4751 result = CURLE_OUT_OF_MEMORY;
4753 Curl_safefree(conn->proxypasswd);
4754 if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
4755 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4757 conn->proxypasswd = strdup("");
4759 if(!conn->proxypasswd)
4760 result = CURLE_OUT_OF_MEMORY;
4764 conn->bits.proxy_user_passwd = TRUE; /* enable it */
4765 atsign++; /* the right side of the @-letter */
4767 proxyptr = atsign; /* now use this instead */
4778 /* start scanning for port number at this point */
4781 /* detect and extract RFC6874-style IPv6-addresses */
4782 if(*proxyptr == '[') {
4783 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4784 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
4787 /* There might be a zone identifier */
4788 if(strncmp("%25", ptr, 3))
4789 infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
4791 /* Allow unreserved characters as defined in RFC 3986 */
4792 while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
4793 (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
4797 /* yeps, it ended nicely with a bracket as well */
4800 infof(data, "Invalid IPv6 address format\n");
4802 /* Note that if this didn't end with a bracket, we still advanced the
4803 * proxyptr first, but I can't see anything wrong with that as no host
4804 * name nor a numeric can legally start with a bracket.
4808 /* Get port number off proxy.server.com:1080 */
4809 prox_portno = strchr(portptr, ':');
4813 *prox_portno = 0x0; /* cut off number from host name */
4815 /* now set the local port number */
4816 port = strtol(prox_portno, &endp, 10);
4817 if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
4818 (port < 0) || (port > 65535)) {
4819 /* meant to detect for example invalid IPv6 numerical addresses without
4820 brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
4821 because we then allow "URL style" with the number followed by a
4822 slash, used in curl test cases already. Space is also an acceptable
4823 terminating symbol. */
4824 infof(data, "No valid port number in proxy string (%s)\n",
4831 if(proxyptr[0]=='/')
4832 /* If the first character in the proxy string is a slash, fail
4833 immediately. The following code will otherwise clear the string which
4834 will lead to code running as if no proxy was set! */
4835 return CURLE_COULDNT_RESOLVE_PROXY;
4837 /* without a port number after the host name, some people seem to use
4838 a slash so we strip everything from the first slash */
4839 atsign = strchr(proxyptr, '/');
4841 *atsign = '\0'; /* cut off path part from host name */
4843 if(data->set.proxyport)
4844 /* None given in the proxy string, then get the default one if it is
4846 conn->port = data->set.proxyport;
4849 /* now, clone the cleaned proxy host name */
4850 conn->proxy.rawalloc = strdup(proxyptr);
4851 conn->proxy.name = conn->proxy.rawalloc;
4853 if(!conn->proxy.rawalloc)
4854 return CURLE_OUT_OF_MEMORY;
4860 * Extract the user and password from the authentication string
4862 static CURLcode parse_proxy_auth(struct Curl_easy *data,
4863 struct connectdata *conn)
4865 char proxyuser[MAX_CURL_USER_LENGTH]="";
4866 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4868 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4869 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4870 MAX_CURL_USER_LENGTH);
4871 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4873 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4874 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4875 MAX_CURL_PASSWORD_LENGTH);
4876 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4879 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4880 if(!conn->proxyuser)
4881 return CURLE_OUT_OF_MEMORY;
4883 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4884 if(!conn->proxypasswd)
4885 return CURLE_OUT_OF_MEMORY;
4889 #endif /* CURL_DISABLE_PROXY */
4894 * Parse the login details (user name, password and options) from the URL and
4895 * strip them out of the host name
4897 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4900 * Outputs: (almost :- all currently undefined)
4901 * conn->bits.user_passwd - non-zero if non-default passwords exist
4902 * user - non-zero length if defined
4903 * passwd - non-zero length if defined
4904 * options - non-zero length if defined
4905 * conn->host.name - remove user name and password
4907 static CURLcode parse_url_login(struct Curl_easy *data,
4908 struct connectdata *conn,
4909 char **user, char **passwd, char **options)
4911 CURLcode result = CURLE_OK;
4913 char *passwdp = NULL;
4914 char *optionsp = NULL;
4916 /* At this point, we're hoping all the other special cases have
4917 * been taken care of, so conn->host.name is at most
4918 * [user[:password][;options]]@]hostname
4920 * We need somewhere to put the embedded details, so do that first.
4923 char *ptr = strchr(conn->host.name, '@');
4924 char *login = conn->host.name;
4926 DEBUGASSERT(!**user);
4927 DEBUGASSERT(!**passwd);
4928 DEBUGASSERT(!**options);
4933 /* We will now try to extract the
4934 * possible login information in a string like:
4935 * ftp://user:password@ftp.my.site:8021/README */
4936 conn->host.name = ++ptr;
4938 /* So the hostname is sane. Only bother interpreting the
4939 * results if we could care. It could still be wasted
4940 * work because it might be overtaken by the programmatically
4941 * set user/passwd, but doing that first adds more cases here :-(
4944 if(data->set.use_netrc == CURL_NETRC_REQUIRED)
4947 /* We could use the login information in the URL so extract it */
4948 result = parse_login_details(login, ptr - login - 1,
4949 &userp, &passwdp, &optionsp);
4956 /* We have a user in the URL */
4957 conn->bits.userpwd_in_url = TRUE;
4958 conn->bits.user_passwd = TRUE; /* enable user+password */
4960 /* Decode the user */
4961 newname = curl_easy_unescape(data, userp, 0, NULL);
4963 result = CURLE_OUT_OF_MEMORY;
4972 /* We have a password in the URL so decode it */
4973 char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
4975 result = CURLE_OUT_OF_MEMORY;
4980 *passwd = newpasswd;
4984 /* We have an options list in the URL so decode it */
4985 char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
4987 result = CURLE_OUT_OF_MEMORY;
4992 *options = newoptions;
5006 * parse_login_details()
5008 * This is used to parse a login string for user name, password and options in
5009 * the following formats:
5013 * user:password;options
5015 * user;options:password
5023 * login [in] - The login string.
5024 * len [in] - The length of the login string.
5025 * userp [in/out] - The address where a pointer to newly allocated memory
5026 * holding the user will be stored upon completion.
5027 * passdwp [in/out] - The address where a pointer to newly allocated memory
5028 * holding the password will be stored upon completion.
5029 * optionsp [in/out] - The address where a pointer to newly allocated memory
5030 * holding the options will be stored upon completion.
5032 * Returns CURLE_OK on success.
5034 static CURLcode parse_login_details(const char *login, const size_t len,
5035 char **userp, char **passwdp,
5038 CURLcode result = CURLE_OK;
5042 const char *psep = NULL;
5043 const char *osep = NULL;
5048 /* Attempt to find the password separator */
5050 psep = strchr(login, ':');
5052 /* Within the constraint of the login string */
5053 if(psep >= login + len)
5057 /* Attempt to find the options separator */
5059 osep = strchr(login, ';');
5061 /* Within the constraint of the login string */
5062 if(osep >= login + len)
5066 /* Calculate the portion lengths */
5068 (size_t)(osep && psep > osep ? osep - login : psep - login) :
5069 (osep ? (size_t)(osep - login) : len));
5071 (osep && osep > psep ? (size_t)(osep - psep) :
5072 (size_t)(login + len - psep)) - 1 : 0);
5074 (psep && psep > osep ? (size_t)(psep - osep) :
5075 (size_t)(login + len - osep)) - 1 : 0);
5077 /* Allocate the user portion buffer */
5079 ubuf = malloc(ulen + 1);
5081 result = CURLE_OUT_OF_MEMORY;
5084 /* Allocate the password portion buffer */
5085 if(!result && passwdp && plen) {
5086 pbuf = malloc(plen + 1);
5089 result = CURLE_OUT_OF_MEMORY;
5093 /* Allocate the options portion buffer */
5094 if(!result && optionsp && olen) {
5095 obuf = malloc(olen + 1);
5099 result = CURLE_OUT_OF_MEMORY;
5104 /* Store the user portion if necessary */
5106 memcpy(ubuf, login, ulen);
5108 Curl_safefree(*userp);
5112 /* Store the password portion if necessary */
5114 memcpy(pbuf, psep + 1, plen);
5116 Curl_safefree(*passwdp);
5120 /* Store the options portion if necessary */
5122 memcpy(obuf, osep + 1, olen);
5124 Curl_safefree(*optionsp);
5132 /*************************************************************
5133 * Figure out the remote port number and fix it in the URL
5135 * No matter if we use a proxy or not, we have to figure out the remote
5136 * port number of various reasons.
5138 * To be able to detect port number flawlessly, we must not confuse them
5139 * IPv6-specified addresses in the [0::1] style. (RFC2732)
5141 * The conn->host.name is currently [user:passwd@]host[:port] where host
5142 * could be a hostname, IPv4 address or IPv6 address.
5144 * The port number embedded in the URL is replaced, if necessary.
5145 *************************************************************/
5146 static CURLcode parse_remote_port(struct Curl_easy *data,
5147 struct connectdata *conn)
5152 /* Note that at this point, the IPv6 address cannot contain any scope
5153 suffix as that has already been removed in the parseurlandfillconn()
5155 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
5157 (']' == endbracket)) {
5158 /* this is a RFC2732-style specified IP-address */
5159 conn->bits.ipv6_ip = TRUE;
5161 conn->host.name++; /* skip over the starting bracket */
5162 portptr = strchr(conn->host.name, ']');
5164 *portptr++ = '\0'; /* zero terminate, killing the bracket */
5166 portptr = NULL; /* no port number available */
5171 struct in6_addr in6;
5172 if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
5173 /* This is a numerical IPv6 address, meaning this is a wrongly formatted
5175 failf(data, "IPv6 numerical address used in URL without brackets");
5176 return CURLE_URL_MALFORMAT;
5180 portptr = strrchr(conn->host.name, ':');
5183 if(data->set.use_port && data->state.allow_port) {
5184 /* if set, we use this and ignore the port possibly given in the URL */
5185 conn->remote_port = (unsigned short)data->set.use_port;
5187 *portptr = '\0'; /* cut off the name there anyway - if there was a port
5188 number - since the port number is to be ignored! */
5189 if(conn->bits.httpproxy) {
5190 /* we need to create new URL with the new port number */
5194 if(conn->bits.type_set)
5195 snprintf(type, sizeof(type), ";type=%c",
5196 data->set.prefer_ascii?'A':
5197 (data->set.ftp_list_only?'D':'I'));
5200 * This synthesized URL isn't always right--suffixes like ;type=A are
5201 * stripped off. It would be better to work directly from the original
5202 * URL and simply replace the port part of it.
5204 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
5205 conn->bits.ipv6_ip?"[":"", conn->host.name,
5206 conn->bits.ipv6_ip?"]":"", conn->remote_port,
5207 data->state.slash_removed?"/":"", data->state.path,
5210 return CURLE_OUT_OF_MEMORY;
5212 if(data->change.url_alloc) {
5213 Curl_safefree(data->change.url);
5214 data->change.url_alloc = FALSE;
5217 data->change.url = url;
5218 data->change.url_alloc = TRUE;
5222 /* no CURLOPT_PORT given, extract the one from the URL */
5227 port=strtol(portptr+1, &rest, 10); /* Port number must be decimal */
5229 if((port < 0) || (port > 0xffff)) {
5230 /* Single unix standard says port numbers are 16 bits long */
5231 failf(data, "Port number out of range");
5232 return CURLE_URL_MALFORMAT;
5235 else if(rest != &portptr[1]) {
5236 *portptr = '\0'; /* cut off the name there */
5237 conn->remote_port = curlx_ultous(port);
5240 /* Browser behavior adaptation. If there's a colon with no digits after,
5241 just cut off the name there which makes us ignore the colon and just
5242 use the default port. Firefox and Chrome both do that. */
5246 /* only if remote_port was not already parsed off the URL we use the
5247 default port number */
5248 if(conn->remote_port < 0)
5249 conn->remote_port = (unsigned short)conn->given->defport;
5255 * Override the login details from the URL with that in the CURLOPT_USERPWD
5256 * option or a .netrc file, if applicable.
5258 static CURLcode override_login(struct Curl_easy *data,
5259 struct connectdata *conn,
5260 char **userp, char **passwdp, char **optionsp)
5262 if(data->set.str[STRING_USERNAME]) {
5264 *userp = strdup(data->set.str[STRING_USERNAME]);
5266 return CURLE_OUT_OF_MEMORY;
5269 if(data->set.str[STRING_PASSWORD]) {
5271 *passwdp = strdup(data->set.str[STRING_PASSWORD]);
5273 return CURLE_OUT_OF_MEMORY;
5276 if(data->set.str[STRING_OPTIONS]) {
5278 *optionsp = strdup(data->set.str[STRING_OPTIONS]);
5280 return CURLE_OUT_OF_MEMORY;
5283 conn->bits.netrc = FALSE;
5284 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
5285 int ret = Curl_parsenetrc(conn->host.name,
5287 data->set.str[STRING_NETRC_FILE]);
5289 infof(data, "Couldn't find host %s in the "
5290 DOT_CHAR "netrc file; using defaults\n",
5294 return CURLE_OUT_OF_MEMORY;
5297 /* set bits.netrc TRUE to remember that we got the name from a .netrc
5298 file, so that it is safe to use even if we followed a Location: to a
5299 different host or similar. */
5300 conn->bits.netrc = TRUE;
5302 conn->bits.user_passwd = TRUE; /* enable user+password */
5310 * Set the login details so they're available in the connection
5312 static CURLcode set_login(struct connectdata *conn,
5313 const char *user, const char *passwd,
5314 const char *options)
5316 CURLcode result = CURLE_OK;
5318 /* If our protocol needs a password and we have none, use the defaults */
5319 if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
5320 /* Store the default user */
5321 conn->user = strdup(CURL_DEFAULT_USER);
5323 /* Store the default password */
5325 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
5327 conn->passwd = NULL;
5329 /* This is the default password, so DON'T set conn->bits.user_passwd */
5332 /* Store the user, zero-length if not set */
5333 conn->user = strdup(user);
5335 /* Store the password (only if user is present), zero-length if not set */
5337 conn->passwd = strdup(passwd);
5339 conn->passwd = NULL;
5342 if(!conn->user || !conn->passwd)
5343 result = CURLE_OUT_OF_MEMORY;
5345 /* Store the options, null if not set */
5346 if(!result && options[0]) {
5347 conn->options = strdup(options);
5350 result = CURLE_OUT_OF_MEMORY;
5357 * Parses a "host:port" string to connect to.
5358 * The hostname and the port may be empty; in this case, NULL is returned for
5359 * the hostname and -1 for the port.
5361 static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
5363 char **hostname_result,
5372 *hostname_result = NULL;
5378 host_dup = strdup(host);
5380 return CURLE_OUT_OF_MEMORY;
5384 /* start scanning for port number at this point */
5387 /* detect and extract RFC6874-style IPv6-addresses */
5388 if(*hostptr == '[') {
5389 char *ptr = ++hostptr; /* advance beyond the initial bracket */
5390 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
5393 /* There might be a zone identifier */
5394 if(strncmp("%25", ptr, 3))
5395 infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
5397 /* Allow unreserved characters as defined in RFC 3986 */
5398 while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
5399 (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
5403 /* yeps, it ended nicely with a bracket as well */
5406 infof(data, "Invalid IPv6 address format\n");
5408 /* Note that if this didn't end with a bracket, we still advanced the
5409 * hostptr first, but I can't see anything wrong with that as no host
5410 * name nor a numeric can legally start with a bracket.
5414 /* Get port number off server.com:1080 */
5415 host_portno = strchr(portptr, ':');
5418 *host_portno = '\0'; /* cut off number from host name */
5421 long portparse = strtol(host_portno, &endp, 10);
5422 if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
5423 infof(data, "No valid port number in connect to host string (%s)\n",
5429 port = (int)portparse; /* we know it will fit */
5433 /* now, clone the cleaned host name */
5435 *hostname_result = strdup(hostptr);
5436 if(!*hostname_result) {
5438 return CURLE_OUT_OF_MEMORY;
5442 *port_result = port;
5449 * Parses one "connect to" string in the form:
5450 * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
5452 static CURLcode parse_connect_to_string(struct Curl_easy *data,
5453 struct connectdata *conn,
5454 const char *conn_to_host,
5458 CURLcode result = CURLE_OK;
5459 const char *ptr = conn_to_host;
5460 int host_match = FALSE;
5461 int port_match = FALSE;
5464 /* an empty hostname always matches */
5469 /* check whether the URL's hostname matches */
5470 size_t hostname_to_match_len;
5471 char *hostname_to_match = aprintf("%s%s%s",
5472 conn->bits.ipv6_ip ? "[" : "",
5474 conn->bits.ipv6_ip ? "]" : "");
5475 if(!hostname_to_match)
5476 return CURLE_OUT_OF_MEMORY;
5477 hostname_to_match_len = strlen(hostname_to_match);
5478 host_match = curl_strnequal(ptr, hostname_to_match, hostname_to_match_len);
5479 free(hostname_to_match);
5480 ptr += hostname_to_match_len;
5482 host_match = host_match && *ptr == ':';
5488 /* an empty port always matches */
5493 /* check whether the URL's port matches */
5494 char *ptr_next = strchr(ptr, ':');
5497 long port_to_match = strtol(ptr, &endp, 10);
5498 if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
5506 if(host_match && port_match) {
5507 /* parse the hostname and port to connect to */
5508 result = parse_connect_to_host_port(data, ptr, host_result, port_result);
5515 * Processes all strings in the "connect to" slist, and uses the "connect
5516 * to host" and "connect to port" of the first string that matches.
5518 static CURLcode parse_connect_to_slist(struct Curl_easy *data,
5519 struct connectdata *conn,
5520 struct curl_slist *conn_to_host)
5522 CURLcode result = CURLE_OK;
5526 while(conn_to_host && !host) {
5527 result = parse_connect_to_string(data, conn, conn_to_host->data,
5534 conn->conn_to_host.rawalloc = host;
5535 conn->conn_to_host.name = host;
5536 conn->bits.conn_to_host = TRUE;
5538 ipv6host = strchr(host, ':') != NULL;
5539 infof(data, "Connecting to hostname: %s%s%s\n",
5540 ipv6host ? "[" : "", host, ipv6host ? "]" : "");
5543 /* no "connect to host" */
5544 conn->bits.conn_to_host = FALSE;
5549 conn->conn_to_port = port;
5550 conn->bits.conn_to_port = TRUE;
5551 infof(data, "Connecting to port: %d\n", port);
5554 /* no "connect to port" */
5555 conn->bits.conn_to_port = FALSE;
5558 conn_to_host = conn_to_host->next;
5564 /*************************************************************
5565 * Resolve the address of the server or proxy
5566 *************************************************************/
5567 static CURLcode resolve_server(struct Curl_easy *data,
5568 struct connectdata *conn,
5571 CURLcode result=CURLE_OK;
5572 long timeout_ms = Curl_timeleft(data, NULL, TRUE);
5574 /*************************************************************
5575 * Resolve the name of the server or proxy
5576 *************************************************************/
5577 if(conn->bits.reuse)
5578 /* We're reusing the connection - no need to resolve anything, and
5579 fix_hostname() was called already in create_conn() for the re-use
5584 /* this is a fresh connect */
5586 struct Curl_dns_entry *hostaddr;
5588 #ifdef USE_UNIX_SOCKETS
5589 if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
5590 /* Unix domain sockets are local. The host gets ignored, just use the
5591 * specified domain socket address. Do not cache "DNS entries". There is
5592 * no DNS involved and we already have the filesystem path available */
5593 const char *path = data->set.str[STRING_UNIX_SOCKET_PATH];
5595 hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
5597 result = CURLE_OUT_OF_MEMORY;
5598 else if((hostaddr->addr = Curl_unix2addr(path)) != NULL)
5601 /* Long paths are not supported for now */
5602 if(strlen(path) >= sizeof(((struct sockaddr_un *)0)->sun_path)) {
5603 failf(data, "Unix socket path too long: '%s'", path);
5604 result = CURLE_COULDNT_RESOLVE_HOST;
5607 result = CURLE_OUT_OF_MEMORY;
5614 if(!conn->proxy.name || !*conn->proxy.name) {
5615 struct hostname *connhost;
5616 if(conn->bits.conn_to_host)
5617 connhost = &conn->conn_to_host;
5619 connhost = &conn->host;
5621 /* If not connecting via a proxy, extract the port from the URL, if it is
5622 * there, thus overriding any defaults that might have been set above. */
5623 if(conn->bits.conn_to_port)
5624 conn->port = conn->conn_to_port;
5626 conn->port = conn->remote_port; /* it is the same port */
5628 /* Resolve target host right on */
5629 rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
5630 &hostaddr, timeout_ms);
5631 if(rc == CURLRESOLV_PENDING)
5634 else if(rc == CURLRESOLV_TIMEDOUT)
5635 result = CURLE_OPERATION_TIMEDOUT;
5637 else if(!hostaddr) {
5638 failf(data, "Couldn't resolve host '%s'", connhost->dispname);
5639 result = CURLE_COULDNT_RESOLVE_HOST;
5640 /* don't return yet, we need to clean up the timeout first */
5644 /* This is a proxy that hasn't been resolved yet. */
5647 rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
5648 &hostaddr, timeout_ms);
5650 if(rc == CURLRESOLV_PENDING)
5653 else if(rc == CURLRESOLV_TIMEDOUT)
5654 result = CURLE_OPERATION_TIMEDOUT;
5656 else if(!hostaddr) {
5657 failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
5658 result = CURLE_COULDNT_RESOLVE_PROXY;
5659 /* don't return yet, we need to clean up the timeout first */
5662 DEBUGASSERT(conn->dns_entry == NULL);
5663 conn->dns_entry = hostaddr;
5670 * Cleanup the connection just allocated before we can move along and use the
5671 * previously existing one. All relevant data is copied over and old_conn is
5672 * ready for freeing once this function returns.
5674 static void reuse_conn(struct connectdata *old_conn,
5675 struct connectdata *conn)
5677 free_fixed_hostname(&old_conn->proxy);
5678 free(old_conn->proxy.rawalloc);
5680 /* free the SSL config struct from this connection struct as this was
5681 allocated in vain and is targeted for destruction */
5682 Curl_free_ssl_config(&old_conn->ssl_config);
5684 conn->data = old_conn->data;
5686 /* get the user+password information from the old_conn struct since it may
5687 * be new for this request even when we re-use an existing connection */
5688 conn->bits.user_passwd = old_conn->bits.user_passwd;
5689 if(conn->bits.user_passwd) {
5690 /* use the new user name and password though */
5691 Curl_safefree(conn->user);
5692 Curl_safefree(conn->passwd);
5693 conn->user = old_conn->user;
5694 conn->passwd = old_conn->passwd;
5695 old_conn->user = NULL;
5696 old_conn->passwd = NULL;
5699 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
5700 if(conn->bits.proxy_user_passwd) {
5701 /* use the new proxy user name and proxy password though */
5702 Curl_safefree(conn->proxyuser);
5703 Curl_safefree(conn->proxypasswd);
5704 conn->proxyuser = old_conn->proxyuser;
5705 conn->proxypasswd = old_conn->proxypasswd;
5706 old_conn->proxyuser = NULL;
5707 old_conn->proxypasswd = NULL;
5710 /* host can change, when doing keepalive with a proxy or if the case is
5711 different this time etc */
5712 free_fixed_hostname(&conn->host);
5713 free_fixed_hostname(&conn->conn_to_host);
5714 Curl_safefree(conn->host.rawalloc);
5715 Curl_safefree(conn->conn_to_host.rawalloc);
5716 conn->host=old_conn->host;
5717 conn->bits.conn_to_host = old_conn->bits.conn_to_host;
5718 conn->conn_to_host = old_conn->conn_to_host;
5719 conn->bits.conn_to_port = old_conn->bits.conn_to_port;
5720 conn->conn_to_port = old_conn->conn_to_port;
5722 /* persist connection info in session handle */
5723 Curl_persistconninfo(conn);
5725 conn_reset_all_postponed_data(old_conn); /* free buffers */
5726 conn_reset_all_postponed_data(conn); /* reset unprocessed data */
5729 conn->bits.reuse = TRUE; /* yes, we're re-using here */
5731 Curl_safefree(old_conn->user);
5732 Curl_safefree(old_conn->passwd);
5733 Curl_safefree(old_conn->proxyuser);
5734 Curl_safefree(old_conn->proxypasswd);
5735 Curl_safefree(old_conn->localdev);
5737 Curl_llist_destroy(old_conn->send_pipe, NULL);
5738 Curl_llist_destroy(old_conn->recv_pipe, NULL);
5740 old_conn->send_pipe = NULL;
5741 old_conn->recv_pipe = NULL;
5743 Curl_safefree(old_conn->master_buffer);
5747 * create_conn() sets up a new connectdata struct, or re-uses an already
5748 * existing one, and resolves host name.
5750 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
5751 * response will be coming asynchronously. If *async is FALSE, the name is
5754 * @param data The sessionhandle pointer
5755 * @param in_connect is set to the next connection data pointer
5756 * @param async is set TRUE when an async DNS resolution is pending
5757 * @see Curl_setup_conn()
5759 * *NOTE* this function assigns the conn->data pointer!
5762 static CURLcode create_conn(struct Curl_easy *data,
5763 struct connectdata **in_connect,
5766 CURLcode result = CURLE_OK;
5767 struct connectdata *conn;
5768 struct connectdata *conn_temp = NULL;
5771 char *passwd = NULL;
5772 char *options = NULL;
5775 bool prot_missing = FALSE;
5776 bool connections_available = TRUE;
5777 bool force_reuse = FALSE;
5778 bool waitpipe = FALSE;
5779 size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
5780 size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
5784 /*************************************************************
5786 *************************************************************/
5788 if(!data->change.url) {
5789 result = CURLE_URL_MALFORMAT;
5793 /* First, split up the current URL in parts so that we can use the
5794 parts for checking against the already present connections. In order
5795 to not have to modify everything at once, we allocate a temporary
5796 connection data struct and fill in for comparison purposes. */
5797 conn = allocate_conn(data);
5800 result = CURLE_OUT_OF_MEMORY;
5804 /* We must set the return variable as soon as possible, so that our
5805 parent can cleanup any possible allocs we may have done before
5809 /* This initing continues below, see the comment "Continue connectdata
5810 * initialization here" */
5812 /***********************************************************
5813 * We need to allocate memory to store the path in. We get the size of the
5814 * full URL to be sure, and we need to make it at least 256 bytes since
5815 * other parts of the code will rely on this fact
5816 ***********************************************************/
5817 #define LEAST_PATH_ALLOC 256
5818 urllen=strlen(data->change.url);
5819 if(urllen < LEAST_PATH_ALLOC)
5820 urllen=LEAST_PATH_ALLOC;
5823 * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
5824 * 1 - an extra terminating zero
5825 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
5828 Curl_safefree(data->state.pathbuffer);
5829 data->state.path = NULL;
5831 data->state.pathbuffer = malloc(urllen+2);
5832 if(NULL == data->state.pathbuffer) {
5833 result = CURLE_OUT_OF_MEMORY; /* really bad error */
5836 data->state.path = data->state.pathbuffer;
5838 conn->host.rawalloc = malloc(urllen+2);
5839 if(NULL == conn->host.rawalloc) {
5840 Curl_safefree(data->state.pathbuffer);
5841 data->state.path = NULL;
5842 result = CURLE_OUT_OF_MEMORY;
5846 conn->host.name = conn->host.rawalloc;
5847 conn->host.name[0] = 0;
5850 passwd = strdup("");
5851 options = strdup("");
5852 if(!user || !passwd || !options) {
5853 result = CURLE_OUT_OF_MEMORY;
5857 result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
5862 /*************************************************************
5863 * No protocol part in URL was used, add it!
5864 *************************************************************/
5866 /* We're guessing prefixes here and if we're told to use a proxy or if
5867 we're gonna follow a Location: later or... then we need the protocol
5868 part added so that we have a valid URL. */
5872 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
5875 result = CURLE_OUT_OF_MEMORY;
5879 /* Change protocol prefix to lower-case */
5880 for(ch_lower = reurl; *ch_lower != ':'; ch_lower++)
5881 *ch_lower = (char)TOLOWER(*ch_lower);
5883 if(data->change.url_alloc) {
5884 Curl_safefree(data->change.url);
5885 data->change.url_alloc = FALSE;
5888 data->change.url = reurl;
5889 data->change.url_alloc = TRUE; /* free this later */
5892 /*************************************************************
5893 * If the protocol can't handle url query strings, then cut
5894 * off the unhandable part
5895 *************************************************************/
5896 if((conn->given->flags&PROTOPT_NOURLQUERY)) {
5897 char *path_q_sep = strchr(conn->data->state.path, '?');
5899 /* according to rfc3986, allow the query (?foo=bar)
5900 also on protocols that can't handle it.
5902 cut the string-part after '?'
5905 /* terminate the string */
5910 if(data->set.str[STRING_BEARER]) {
5911 conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
5912 if(!conn->oauth_bearer) {
5913 result = CURLE_OUT_OF_MEMORY;
5918 #ifndef CURL_DISABLE_PROXY
5919 /*************************************************************
5920 * Extract the user and password from the authentication string
5921 *************************************************************/
5922 if(conn->bits.proxy_user_passwd) {
5923 result = parse_proxy_auth(data, conn);
5928 /*************************************************************
5929 * Detect what (if any) proxy to use
5930 *************************************************************/
5931 if(data->set.str[STRING_PROXY]) {
5932 proxy = strdup(data->set.str[STRING_PROXY]);
5933 /* if global proxy is set, this is it */
5935 failf(data, "memory shortage");
5936 result = CURLE_OUT_OF_MEMORY;
5941 if(data->set.str[STRING_NOPROXY] &&
5942 check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
5943 free(proxy); /* proxy is in exception list */
5947 proxy = detect_proxy(conn);
5949 #ifdef USE_UNIX_SOCKETS
5950 if(proxy && data->set.str[STRING_UNIX_SOCKET_PATH]) {
5951 free(proxy); /* Unix domain sockets cannot be proxied, so disable it */
5956 if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
5957 free(proxy); /* Don't bother with an empty proxy string or if the
5958 protocol doesn't work with network */
5962 /***********************************************************************
5963 * If this is supposed to use a proxy, we need to figure out the proxy host
5964 * name, proxy type and port number, so that we can re-use an existing
5965 * connection that may exist registered to the same proxy host.
5966 ***********************************************************************/
5968 result = parse_proxy(data, conn, proxy);
5970 free(proxy); /* parse_proxy copies the proxy string */
5976 if((conn->proxytype == CURLPROXY_HTTP) ||
5977 (conn->proxytype == CURLPROXY_HTTP_1_0)) {
5978 #ifdef CURL_DISABLE_HTTP
5979 /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
5980 result = CURLE_UNSUPPORTED_PROTOCOL;
5983 /* force this connection's protocol to become HTTP if not already
5984 compatible - if it isn't tunneling through */
5985 if(!(conn->handler->protocol & PROTO_FAMILY_HTTP) &&
5986 !conn->bits.tunnel_proxy)
5987 conn->handler = &Curl_handler_http;
5989 conn->bits.httpproxy = TRUE;
5993 conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
5994 conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
5996 conn->bits.proxy = TRUE;
5999 /* we aren't using the proxy after all... */
6000 conn->bits.proxy = FALSE;
6001 conn->bits.httpproxy = FALSE;
6002 conn->bits.proxy_user_passwd = FALSE;
6003 conn->bits.tunnel_proxy = FALSE;
6006 #endif /* CURL_DISABLE_PROXY */
6008 /*************************************************************
6009 * If the protocol is using SSL and HTTP proxy is used, we set
6010 * the tunnel_proxy bit.
6011 *************************************************************/
6012 if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
6013 conn->bits.tunnel_proxy = TRUE;
6015 /*************************************************************
6016 * Figure out the remote port number and fix it in the URL
6017 *************************************************************/
6018 result = parse_remote_port(data, conn);
6022 /* Check for overridden login details and set them accordingly so they
6023 they are known when protocol->setup_connection is called! */
6024 result = override_login(data, conn, &user, &passwd, &options);
6027 result = set_login(conn, user, passwd, options);
6031 /*************************************************************
6032 * Process the "connect to" linked list of hostname/port mappings.
6033 * Do this after the remote port number has been fixed in the URL.
6034 *************************************************************/
6035 result = parse_connect_to_slist(data, conn, data->set.connect_to);
6039 /*************************************************************
6040 * IDN-fix the hostnames
6041 *************************************************************/
6042 fix_hostname(data, conn, &conn->host);
6043 if(conn->bits.conn_to_host)
6044 fix_hostname(data, conn, &conn->conn_to_host);
6045 if(conn->proxy.name && *conn->proxy.name)
6046 fix_hostname(data, conn, &conn->proxy);
6048 /*************************************************************
6049 * Check whether the host and the "connect to host" are equal.
6050 * Do this after the hostnames have been IDN-fixed .
6051 *************************************************************/
6052 if(conn->bits.conn_to_host &&
6053 Curl_raw_equal(conn->conn_to_host.name, conn->host.name)) {
6054 conn->bits.conn_to_host = FALSE;
6057 /*************************************************************
6058 * Check whether the port and the "connect to port" are equal.
6059 * Do this after the remote port number has been fixed in the URL.
6060 *************************************************************/
6061 if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
6062 conn->bits.conn_to_port = FALSE;
6065 /*************************************************************
6066 * If the "connect to" feature is used with an HTTP proxy,
6067 * we set the tunnel_proxy bit.
6068 *************************************************************/
6069 if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
6070 conn->bits.httpproxy)
6071 conn->bits.tunnel_proxy = TRUE;
6073 /*************************************************************
6074 * Setup internals depending on protocol. Needs to be done after
6075 * we figured out what/if proxy to use.
6076 *************************************************************/
6077 result = setup_connection_internals(conn);
6081 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
6082 conn->send[FIRSTSOCKET] = Curl_send_plain;
6083 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
6084 conn->send[SECONDARYSOCKET] = Curl_send_plain;
6086 conn->bits.tcp_fastopen = data->set.tcp_fastopen;
6088 /***********************************************************************
6089 * file: is a special case in that it doesn't need a network connection
6090 ***********************************************************************/
6091 #ifndef CURL_DISABLE_FILE
6092 if(conn->handler->flags & PROTOPT_NONETWORK) {
6094 /* this is supposed to be the connect function so we better at least check
6095 that the file is present here! */
6096 DEBUGASSERT(conn->handler->connect_it);
6097 result = conn->handler->connect_it(conn, &done);
6099 /* Setup a "faked" transfer that'll do nothing */
6102 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
6104 Curl_conncache_add_conn(data->state.conn_cache, conn);
6107 * Setup whatever necessary for a resumed transfer
6109 result = setup_range(data);
6111 DEBUGASSERT(conn->handler->done);
6112 /* we ignore the return code for the protocol-specific DONE */
6113 (void)conn->handler->done(conn, result, FALSE);
6117 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
6118 -1, NULL); /* no upload */
6121 /* since we skip do_init() */
6122 Curl_init_do(data, conn);
6128 /* Get a cloned copy of the SSL config situation stored in the
6129 connection struct. But to get this going nicely, we must first make
6130 sure that the strings in the master copy are pointing to the correct
6131 strings in the session handle strings array!
6133 Keep in mind that the pointers in the master copy are pointing to strings
6134 that will be freed as part of the Curl_easy struct, but all cloned
6135 copies will be separately allocated.
6137 data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
6138 data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
6139 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
6140 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
6141 data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
6142 data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
6143 data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
6144 data->set.ssl.clientcert = data->set.str[STRING_CERT];
6146 data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
6147 data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
6150 if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config)) {
6151 result = CURLE_OUT_OF_MEMORY;
6155 prune_dead_connections(data);
6157 /*************************************************************
6158 * Check the current list of connections to see if we can
6159 * re-use an already existing one or if we have to create a
6161 *************************************************************/
6163 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
6164 we only acknowledge this option if this is not a re-used connection
6165 already (which happens due to follow-location or during a HTTP
6166 authentication phase). */
6167 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
6170 reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
6172 /* If we found a reusable connection, we may still want to
6173 open a new connection if we are pipelining. */
6174 if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
6175 size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
6177 infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
6178 conn_temp->connection_id, pipelen);
6180 if(conn_temp->bundle->num_connections < max_host_connections &&
6181 data->state.conn_cache->num_connections < max_total_connections) {
6182 /* We want a new connection anyway */
6185 infof(data, "We can reuse, but we want a new connection anyway\n");
6192 * We already have a connection for this, we got the former connection
6193 * in the conn_temp variable and thus we need to cleanup the one we
6194 * just allocated before we can move along and use the previously
6197 conn_temp->inuse = TRUE; /* mark this as being in use so that no other
6198 handle in a multi stack may nick it */
6199 reuse_conn(conn, conn_temp);
6200 free(conn); /* we don't need this anymore */
6204 infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
6205 conn->connection_id,
6206 conn->bits.proxy?"proxy":"host",
6207 conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
6210 /* We have decided that we want a new connection. However, we may not
6211 be able to do that if we have reached the limit of how many
6212 connections we are allowed to open. */
6213 struct connectbundle *bundle = NULL;
6215 if(conn->handler->flags & PROTOPT_ALPN_NPN) {
6216 /* The protocol wants it, so set the bits if enabled in the easy handle
6218 if(data->set.ssl_enable_alpn)
6219 conn->bits.tls_enable_alpn = TRUE;
6220 if(data->set.ssl_enable_npn)
6221 conn->bits.tls_enable_npn = TRUE;
6225 /* There is a connection that *might* become usable for pipelining
6226 "soon", and we wait for that */
6227 connections_available = FALSE;
6229 bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache);
6231 if(max_host_connections > 0 && bundle &&
6232 (bundle->num_connections >= max_host_connections)) {
6233 struct connectdata *conn_candidate;
6235 /* The bundle is full. Let's see if we can kill a connection. */
6236 conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
6238 if(conn_candidate) {
6239 /* Set the connection's owner correctly, then kill it */
6240 conn_candidate->data = data;
6241 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
6244 infof(data, "No more connections allowed to host: %d\n",
6245 max_host_connections);
6246 connections_available = FALSE;
6250 if(connections_available &&
6251 (max_total_connections > 0) &&
6252 (data->state.conn_cache->num_connections >= max_total_connections)) {
6253 struct connectdata *conn_candidate;
6255 /* The cache is full. Let's see if we can kill a connection. */
6256 conn_candidate = Curl_oldest_idle_connection(data);
6258 if(conn_candidate) {
6259 /* Set the connection's owner correctly, then kill it */
6260 conn_candidate->data = data;
6261 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
6264 infof(data, "No connections available in cache\n");
6265 connections_available = FALSE;
6269 if(!connections_available) {
6270 infof(data, "No connections available.\n");
6275 result = CURLE_NO_CONNECTION_AVAILABLE;
6280 * This is a brand new connection, so let's store it in the connection
6283 Curl_conncache_add_conn(data->state.conn_cache, conn);
6286 #if defined(USE_NTLM)
6287 /* If NTLM is requested in a part of this connection, make sure we don't
6288 assume the state is fine as this is a fresh connection and NTLM is
6289 connection based. */
6290 if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
6291 data->state.authhost.done) {
6292 infof(data, "NTLM picked AND auth done set, clear picked!\n");
6293 data->state.authhost.picked = CURLAUTH_NONE;
6294 data->state.authhost.done = FALSE;
6297 if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
6298 data->state.authproxy.done) {
6299 infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
6300 data->state.authproxy.picked = CURLAUTH_NONE;
6301 data->state.authproxy.done = FALSE;
6306 /* Mark the connection as used */
6309 /* Setup and init stuff before DO starts, in preparing for the transfer. */
6310 Curl_init_do(data, conn);
6313 * Setup whatever necessary for a resumed transfer
6315 result = setup_range(data);
6319 /* Continue connectdata initialization here. */
6322 * Inherit the proper values from the urldata struct AFTER we have arranged
6323 * the persistent connection stuff
6325 conn->seek_func = data->set.seek_func;
6326 conn->seek_client = data->set.seek_client;
6328 /*************************************************************
6329 * Resolve the address of the server or proxy
6330 *************************************************************/
6331 result = resolve_server(data, conn, async);
6342 /* Curl_setup_conn() is called after the name resolve initiated in
6343 * create_conn() is all done.
6345 * Curl_setup_conn() also handles reused connections
6347 * conn->data MUST already have been setup fine (in create_conn)
6350 CURLcode Curl_setup_conn(struct connectdata *conn,
6351 bool *protocol_done)
6353 CURLcode result = CURLE_OK;
6354 struct Curl_easy *data = conn->data;
6356 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
6358 if(conn->handler->flags & PROTOPT_NONETWORK) {
6359 /* nothing to setup when not using a network */
6360 *protocol_done = TRUE;
6363 *protocol_done = FALSE; /* default to not done */
6365 /* set proxy_connect_closed to false unconditionally already here since it
6366 is used strictly to provide extra information to a parent function in the
6367 case of proxy CONNECT failures and we must make sure we don't have it
6368 lingering set from a previous invoke */
6369 conn->bits.proxy_connect_closed = FALSE;
6372 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
6373 * basically anything through a http proxy we can't limit this based on
6376 if(data->set.str[STRING_USERAGENT]) {
6377 Curl_safefree(conn->allocptr.uagent);
6378 conn->allocptr.uagent =
6379 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
6380 if(!conn->allocptr.uagent)
6381 return CURLE_OUT_OF_MEMORY;
6384 data->req.headerbytecount = 0;
6386 #ifdef CURL_DO_LINEEND_CONV
6387 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
6388 #endif /* CURL_DO_LINEEND_CONV */
6390 /* set start time here for timeout purposes in the connect procedure, it
6391 is later set again for the progress meter purpose */
6392 conn->now = Curl_tvnow();
6394 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
6395 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
6396 result = Curl_connecthost(conn, conn->dns_entry);
6401 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
6402 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
6403 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
6404 *protocol_done = TRUE;
6405 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
6406 Curl_verboseconnect(conn);
6409 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
6410 set this here perhaps a second time */
6414 * This check is quite a hack. We're calling _fsetmode to fix the problem
6415 * with fwrite converting newline characters (you get mangled text files,
6416 * and corrupted binary files when you download to stdout and redirect it to
6420 if((data->set.out)->_handle == NULL) {
6421 _fsetmode(stdout, "b");
6428 CURLcode Curl_connect(struct Curl_easy *data,
6429 struct connectdata **in_connect,
6431 bool *protocol_done)
6435 *asyncp = FALSE; /* assume synchronous resolves by default */
6437 /* call the stuff that needs to be called */
6438 result = create_conn(data, in_connect, asyncp);
6442 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
6444 *protocol_done = TRUE;
6446 /* DNS resolution is done: that's either because this is a reused
6447 connection, in which case DNS was unnecessary, or because DNS
6448 really did finish already (synch resolver/fast async resolve) */
6449 result = Curl_setup_conn(*in_connect, protocol_done);
6453 if(result == CURLE_NO_CONNECTION_AVAILABLE) {
6458 if(result && *in_connect) {
6459 /* We're not allowed to return failure with memory left allocated
6460 in the connectdata struct, free those here */
6461 Curl_disconnect(*in_connect, FALSE); /* close the connection */
6462 *in_connect = NULL; /* return a NULL */
6469 * Curl_init_do() inits the readwrite session. This is inited each time (in
6470 * the DO function before the protocol-specific DO functions are invoked) for
6471 * a transfer, sometimes multiple times on the same Curl_easy. Make sure
6472 * nothing in here depends on stuff that are setup dynamically for the
6475 * Allow this function to get called with 'conn' set to NULL.
6478 CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
6480 struct SingleRequest *k = &data->req;
6483 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
6486 data->state.done = FALSE; /* *_done() is not called yet */
6487 data->state.expect100header = FALSE;
6489 if(data->set.opt_no_body)
6490 /* in HTTP lingo, no body means using the HEAD request... */
6491 data->set.httpreq = HTTPREQ_HEAD;
6492 else if(HTTPREQ_HEAD == data->set.httpreq)
6493 /* ... but if unset there really is no perfect method that is the
6494 "opposite" of HEAD but in reality most people probably think GET
6495 then. The important thing is that we can't let it remain HEAD if the
6496 opt_no_body is set FALSE since then we'll behave wrong when getting
6498 data->set.httpreq = HTTPREQ_GET;
6500 k->start = Curl_tvnow(); /* start time */
6501 k->now = k->start; /* current time is now */
6502 k->header = TRUE; /* assume header */
6506 k->buf = data->state.buffer;
6507 k->uploadbuf = data->state.uploadbuffer;
6508 k->hbufp = data->state.headerbuff;
6509 k->ignorebody=FALSE;
6511 Curl_speedinit(data);
6513 Curl_pgrsSetUploadCounter(data, 0);
6514 Curl_pgrsSetDownloadCounter(data, 0);
6520 * get_protocol_family()
6522 * This is used to return the protocol family for a given protocol.
6526 * protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
6528 * Returns the family as a single bit protocol identifier.
6531 unsigned int get_protocol_family(unsigned int protocol)
6533 unsigned int family;
6536 case CURLPROTO_HTTP:
6537 case CURLPROTO_HTTPS:
6538 family = CURLPROTO_HTTP;
6542 case CURLPROTO_FTPS:
6543 family = CURLPROTO_FTP;
6547 family = CURLPROTO_SCP;
6550 case CURLPROTO_SFTP:
6551 family = CURLPROTO_SFTP;
6554 case CURLPROTO_TELNET:
6555 family = CURLPROTO_TELNET;
6558 case CURLPROTO_LDAP:
6559 case CURLPROTO_LDAPS:
6560 family = CURLPROTO_LDAP;
6563 case CURLPROTO_DICT:
6564 family = CURLPROTO_DICT;
6567 case CURLPROTO_FILE:
6568 family = CURLPROTO_FILE;
6571 case CURLPROTO_TFTP:
6572 family = CURLPROTO_TFTP;
6575 case CURLPROTO_IMAP:
6576 case CURLPROTO_IMAPS:
6577 family = CURLPROTO_IMAP;
6580 case CURLPROTO_POP3:
6581 case CURLPROTO_POP3S:
6582 family = CURLPROTO_POP3;
6585 case CURLPROTO_SMTP:
6586 case CURLPROTO_SMTPS:
6587 family = CURLPROTO_SMTP;
6590 case CURLPROTO_RTSP:
6591 family = CURLPROTO_RTSP;
6594 case CURLPROTO_RTMP:
6595 case CURLPROTO_RTMPS:
6596 family = CURLPROTO_RTMP;
6599 case CURLPROTO_RTMPT:
6600 case CURLPROTO_RTMPTS:
6601 family = CURLPROTO_RTMPT;
6604 case CURLPROTO_RTMPE:
6605 family = CURLPROTO_RTMPE;
6608 case CURLPROTO_RTMPTE:
6609 family = CURLPROTO_RTMPTE;
6612 case CURLPROTO_GOPHER:
6613 family = CURLPROTO_GOPHER;
6617 case CURLPROTO_SMBS:
6618 family = CURLPROTO_SMB;