1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, 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 http://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>
51 #error "We can't compile without socket() support!"
61 #include <stringprep.h>
62 #ifdef HAVE_IDN_FREE_H
65 /* prototype from idn-free.h, not provided by libidn 0.4.5's make install! */
66 void idn_free (void *ptr);
69 /* if idn_free() was not found in this version of libidn use free() instead */
70 #define idn_free(x) (free)(x)
72 #elif defined(USE_WIN32_IDN)
73 /* prototype for curl_win32_idn_to_ascii() */
74 int curl_win32_idn_to_ascii(const char *in, char **out);
75 #endif /* USE_LIBIDN */
92 #include "content_encoding.h"
93 #include "http_digest.h"
94 #include "http_negotiate.h"
98 #include "speedcheck.h"
100 #include "warnless.h"
101 #include "non-ascii.h"
102 #include "inet_pton.h"
104 /* And now for the protocols */
111 #include "curl_ldap.h"
116 #include "inet_ntop.h"
117 #include "curl_ntlm.h"
118 #include "curl_ntlm_wb.h"
120 #include "curl_rtmp.h"
122 #include "http_proxy.h"
124 #include "conncache.h"
125 #include "multihandle.h"
126 #include "pipeline.h"
128 #define _MPRINTF_REPLACE /* use our functions only */
129 #include <curl/mprintf.h>
131 #include "curl_memory.h"
132 /* The last #include file should be: */
133 #include "memdebug.h"
135 /* Local static prototypes */
136 static struct connectdata *
137 find_oldest_idle_connection(struct SessionHandle *data);
138 static struct connectdata *
139 find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
140 struct connectbundle *bundle);
141 static void conn_free(struct connectdata *conn);
142 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
143 static CURLcode do_init(struct connectdata *conn);
144 static CURLcode parse_url_login(struct SessionHandle *data,
145 struct connectdata *conn,
146 char *user, char *passwd, char *options);
147 static CURLcode parse_login_details(const char *login, const size_t len,
148 char **userptr, char **passwdptr,
154 static const struct Curl_handler * const protocols[] = {
156 #ifndef CURL_DISABLE_HTTP
160 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
164 #ifndef CURL_DISABLE_FTP
168 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
172 #ifndef CURL_DISABLE_TELNET
173 &Curl_handler_telnet,
176 #ifndef CURL_DISABLE_DICT
180 #ifndef CURL_DISABLE_LDAP
182 #if !defined(CURL_DISABLE_LDAPS) && \
183 ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
184 (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
189 #ifndef CURL_DISABLE_FILE
193 #ifndef CURL_DISABLE_TFTP
202 #ifndef CURL_DISABLE_IMAP
209 #ifndef CURL_DISABLE_POP3
216 #ifndef CURL_DISABLE_SMTP
223 #ifndef CURL_DISABLE_RTSP
227 #ifndef CURL_DISABLE_GOPHER
228 &Curl_handler_gopher,
235 &Curl_handler_rtmpte,
237 &Curl_handler_rtmpts,
240 (struct Curl_handler *) NULL
244 * Dummy handler for undefined protocol schemes.
247 static const struct Curl_handler Curl_handler_dummy = {
248 "<no protocol>", /* scheme */
249 ZERO_NULL, /* setup_connection */
250 ZERO_NULL, /* do_it */
251 ZERO_NULL, /* done */
252 ZERO_NULL, /* do_more */
253 ZERO_NULL, /* connect_it */
254 ZERO_NULL, /* connecting */
255 ZERO_NULL, /* doing */
256 ZERO_NULL, /* proto_getsock */
257 ZERO_NULL, /* doing_getsock */
258 ZERO_NULL, /* domore_getsock */
259 ZERO_NULL, /* perform_getsock */
260 ZERO_NULL, /* disconnect */
261 ZERO_NULL, /* readwrite */
264 PROTOPT_NONE /* flags */
267 void Curl_freeset(struct SessionHandle *data)
269 /* Free all dynamic strings stored in the data->set substructure. */
271 for(i=(enum dupstring)0; i < STRING_LAST; i++)
272 Curl_safefree(data->set.str[i]);
274 if(data->change.referer_alloc) {
275 Curl_safefree(data->change.referer);
276 data->change.referer_alloc = FALSE;
278 data->change.referer = NULL;
281 static CURLcode setstropt(char **charp, char *s)
283 /* Release the previous storage at `charp' and replace by a dynamic storage
284 copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
286 Curl_safefree(*charp);
292 return CURLE_OUT_OF_MEMORY;
300 static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp,
303 CURLcode result = CURLE_OK;
306 char *options = NULL;
308 /* Parse the login details if specified. It not then we treat NULL as a hint
309 to clear the existing data */
311 result = parse_login_details(option, strlen(option),
312 (userp ? &user : NULL),
313 (passwdp ? &passwd : NULL),
314 (optionsp ? &options : NULL));
318 /* Store the username part of option if required */
320 Curl_safefree(*userp);
324 /* Store the password part of option if required */
326 Curl_safefree(*passwdp);
330 /* Store the options part of option if required */
332 Curl_safefree(*optionsp);
340 CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src)
342 CURLcode r = CURLE_OK;
345 /* Copy src->set into dst->set first, then deal with the strings
349 /* clear all string pointers first */
350 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
352 /* duplicate all strings */
353 for(i=(enum dupstring)0; i< STRING_LAST; i++) {
354 r = setstropt(&dst->set.str[i], src->set.str[i]);
359 /* If a failure occurred, freeing has to be performed externally. */
364 * This is the internal function curl_easy_cleanup() calls. This should
365 * cleanup and free all resources associated with this sessionhandle.
367 * NOTE: if we ever add something that attempts to write to a socket or
368 * similar here, we must ignore SIGPIPE first. It is currently only done
369 * when curl_easy_perform() is invoked.
372 CURLcode Curl_close(struct SessionHandle *data)
374 struct Curl_multi *m;
379 Curl_expire(data, 0); /* shut off timers */
384 /* This handle is still part of a multi handle, take care of this first
385 and detach this handle from there. */
386 curl_multi_remove_handle(data->multi, data);
389 /* when curl_easy_perform() is used, it creates its own multi handle to
390 use and this is the one */
391 curl_multi_cleanup(data->multi_easy);
393 /* Destroy the timeout list that is held in the easy handle. It is
394 /normally/ done by curl_multi_remove_handle() but this is "just in
396 if(data->state.timeoutlist) {
397 Curl_llist_destroy(data->state.timeoutlist, NULL);
398 data->state.timeoutlist = NULL;
401 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
402 the multi handle, since that function uses the magic
405 if(data->state.rangestringalloc)
406 free(data->state.range);
408 /* Free the pathbuffer */
409 Curl_safefree(data->state.pathbuffer);
410 data->state.path = NULL;
412 Curl_safefree(data->state.proto.generic);
414 /* Close down all open SSL info and sessions */
415 Curl_ssl_close_all(data);
416 Curl_safefree(data->state.first_host);
417 Curl_safefree(data->state.scratch);
418 Curl_ssl_free_certinfo(data);
420 if(data->change.referer_alloc) {
421 Curl_safefree(data->change.referer);
422 data->change.referer_alloc = FALSE;
424 data->change.referer = NULL;
426 if(data->change.url_alloc) {
427 Curl_safefree(data->change.url);
428 data->change.url_alloc = FALSE;
430 data->change.url = NULL;
432 Curl_safefree(data->state.headerbuff);
434 Curl_flush_cookies(data, 1);
436 Curl_digest_cleanup(data);
438 Curl_safefree(data->info.contenttype);
439 Curl_safefree(data->info.wouldredirect);
441 /* this destroys the channel and we cannot use it anymore after this */
442 Curl_resolver_cleanup(data->state.resolver);
444 Curl_convert_close(data);
446 /* No longer a dirty share, if it exists */
448 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
449 data->share->dirty--;
450 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
459 * Initialize the UserDefined fields within a SessionHandle.
460 * This may be safely called on a new or existing SessionHandle.
462 CURLcode Curl_init_userdefined(struct UserDefined *set)
464 CURLcode res = CURLE_OK;
466 set->out = stdout; /* default output to stdout */
467 set->in = stdin; /* default input from stdin */
468 set->err = stderr; /* default stderr to stderr */
470 /* use fwrite as default function to store output */
471 set->fwrite_func = (curl_write_callback)fwrite;
473 /* use fread as default function to read input */
474 set->fread_func = (curl_read_callback)fread;
475 set->is_fread_set = 0;
476 set->is_fwrite_set = 0;
478 set->seek_func = ZERO_NULL;
479 set->seek_client = ZERO_NULL;
481 /* conversion callbacks for non-ASCII hosts */
482 set->convfromnetwork = ZERO_NULL;
483 set->convtonetwork = ZERO_NULL;
484 set->convfromutf8 = ZERO_NULL;
486 set->infilesize = -1; /* we don't know any size */
487 set->postfieldsize = -1; /* unknown size */
488 set->maxredirs = -1; /* allow any amount by default */
490 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
491 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
492 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
493 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
494 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
495 set->ftp_filemethod = FTPFILE_MULTICWD;
497 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
499 /* Set the default size of the SSL session ID cache */
500 set->ssl.max_ssl_sessions = 5;
502 set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
503 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
504 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
505 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
507 /* make libcurl quiet by default: */
508 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
511 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
512 * switched off unless wanted.
514 set->ssl.verifypeer = TRUE;
515 set->ssl.verifyhost = TRUE;
517 set->ssl.authtype = CURL_TLSAUTH_NONE;
519 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
521 set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
523 set->new_file_perms = 0644; /* Default permissions */
524 set->new_directory_perms = 0755; /* Default permissions */
526 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
527 define since we internally only use the lower 16 bits for the passed
528 in bitmask to not conflict with the private bits */
529 set->allowed_protocols = CURLPROTO_ALL;
530 set->redir_protocols =
531 CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
533 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
535 * disallow unprotected protection negotiation NEC reference implementation
536 * seem not to follow rfc1961 section 4.3/4.4
538 set->socks5_gssapi_nec = FALSE;
539 /* set default gssapi service name */
540 res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
541 (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
546 /* This is our preferred CA cert bundle/path since install time */
547 #if defined(CURL_CA_BUNDLE)
548 res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
549 #elif defined(CURL_CA_PATH)
550 res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
553 set->wildcardmatch = FALSE;
554 set->chunk_bgn = ZERO_NULL;
555 set->chunk_end = ZERO_NULL;
557 /* tcp keepalives are disabled by default, but provide reasonable values for
558 * the interval and idle times.
560 set->tcp_keepalive = FALSE;
561 set->tcp_keepintvl = 60;
562 set->tcp_keepidle = 60;
570 * @param curl is a pointer to a sessionhandle pointer that gets set by this
575 CURLcode Curl_open(struct SessionHandle **curl)
577 CURLcode res = CURLE_OK;
578 struct SessionHandle *data;
581 /* Very simple start-up: alloc the struct, init it with zeroes and return */
582 data = calloc(1, sizeof(struct SessionHandle));
584 /* this is a very serious error */
585 DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
586 return CURLE_OUT_OF_MEMORY;
589 data->magic = CURLEASY_MAGIC_NUMBER;
591 status = Curl_resolver_init(&data->state.resolver);
593 DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
598 /* We do some initial setup here, all those fields that can't be just 0 */
600 data->state.headerbuff = malloc(HEADERSIZE);
601 if(!data->state.headerbuff) {
602 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
603 res = CURLE_OUT_OF_MEMORY;
606 Curl_easy_initHandleData(data);
607 res = Curl_init_userdefined(&data->set);
609 data->state.headersize=HEADERSIZE;
611 Curl_convert_init(data);
613 /* most recent connection is not yet defined */
614 data->state.lastconnect = NULL;
616 data->progress.flags |= PGRS_HIDE;
617 data->state.current_speed = -1; /* init to negative == impossible */
619 data->wildcard.state = CURLWC_INIT;
620 data->wildcard.filelist = NULL;
621 data->set.fnmatch = ZERO_NULL;
622 data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
626 Curl_resolver_cleanup(data->state.resolver);
627 if(data->state.headerbuff)
628 free(data->state.headerbuff);
639 CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
643 CURLcode result = CURLE_OK;
645 #ifndef CURL_DISABLE_HTTP
650 case CURLOPT_DNS_CACHE_TIMEOUT:
651 data->set.dns_cache_timeout = va_arg(param, long);
653 case CURLOPT_DNS_USE_GLOBAL_CACHE:
654 /* remember we want this enabled */
655 arg = va_arg(param, long);
656 data->set.global_dns_cache = (0 != arg)?TRUE:FALSE;
658 case CURLOPT_SSL_CIPHER_LIST:
659 /* set a list of cipher we want to use in the SSL connection */
660 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
661 va_arg(param, char *));
664 case CURLOPT_RANDOM_FILE:
666 * This is the path name to a file that contains random data to seed
667 * the random SSL stuff with. The file is only used for reading.
669 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
670 va_arg(param, char *));
672 case CURLOPT_EGDSOCKET:
674 * The Entropy Gathering Daemon socket pathname
676 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
677 va_arg(param, char *));
679 case CURLOPT_MAXCONNECTS:
681 * Set the absolute number of maximum simultaneous alive connection that
682 * libcurl is allowed to have.
684 data->set.maxconnects = va_arg(param, long);
686 case CURLOPT_FORBID_REUSE:
688 * When this transfer is done, it must not be left to be reused by a
689 * subsequent transfer but shall be closed immediately.
691 data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE;
693 case CURLOPT_FRESH_CONNECT:
695 * This transfer shall not use a previously cached connection but
696 * should be made with a fresh new connect!
698 data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE;
700 case CURLOPT_VERBOSE:
702 * Verbose means infof() calls that give a lot of information about
703 * the connection and transfer procedures as well as internal choices.
705 data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE;
709 * Set to include the header in the general data output stream.
711 data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE;
713 case CURLOPT_NOPROGRESS:
715 * Shut off the internal supported progress meter
717 data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE;
718 if(data->set.hide_progress)
719 data->progress.flags |= PGRS_HIDE;
721 data->progress.flags &= ~PGRS_HIDE;
725 * Do not include the body part in the output data stream.
727 data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE;
729 case CURLOPT_FAILONERROR:
731 * Don't output the >=300 error code HTML-page, but instead only
734 data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE;
739 * We want to sent data to the remote host. If this is HTTP, that equals
740 * using the PUT request.
742 data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE;
743 if(data->set.upload) {
744 /* If this is HTTP, PUT is what's needed to "upload" */
745 data->set.httpreq = HTTPREQ_PUT;
746 data->set.opt_no_body = FALSE; /* this is implied */
749 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
750 then this can be changed to HEAD later on) */
751 data->set.httpreq = HTTPREQ_GET;
753 case CURLOPT_FILETIME:
755 * Try to get the file time of the remote document. The time will
756 * later (possibly) become available using curl_easy_getinfo().
758 data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE;
760 case CURLOPT_FTP_CREATE_MISSING_DIRS:
762 * An FTP option that modifies an upload to create missing directories on
765 switch(va_arg(param, long)) {
767 data->set.ftp_create_missing_dirs = 0;
770 data->set.ftp_create_missing_dirs = 1;
773 data->set.ftp_create_missing_dirs = 2;
776 /* reserve other values for future use */
777 result = CURLE_UNKNOWN_OPTION;
781 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
783 * Option that specifies how quickly an server response must be obtained
784 * before it is considered failure. For pingpong protocols.
786 data->set.server_response_timeout = va_arg( param , long ) * 1000;
788 case CURLOPT_TFTP_BLKSIZE:
790 * TFTP option that specifies the block size to use for data transmission
792 data->set.tftp_blksize = va_arg(param, long);
794 case CURLOPT_DIRLISTONLY:
796 * An option that changes the command to one that asks for a list
797 * only, no file info details.
799 data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE;
803 * We want to upload and append to an existing file.
805 data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE;
807 case CURLOPT_FTP_FILEMETHOD:
809 * How do access files over FTP.
811 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
815 * Parse the $HOME/.netrc file
817 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
819 case CURLOPT_NETRC_FILE:
821 * Use this file instead of the $HOME/.netrc file
823 result = setstropt(&data->set.str[STRING_NETRC_FILE],
824 va_arg(param, char *));
826 case CURLOPT_TRANSFERTEXT:
828 * This option was previously named 'FTPASCII'. Renamed to work with
829 * more protocols than merely FTP.
831 * Transfer using ASCII (instead of BINARY).
833 data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE;
835 case CURLOPT_TIMECONDITION:
837 * Set HTTP time condition. This must be one of the defines in the
838 * curl/curl.h header file.
840 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
842 case CURLOPT_TIMEVALUE:
844 * This is the value to compare with the remote document with the
845 * method set with CURLOPT_TIMECONDITION
847 data->set.timevalue = (time_t)va_arg(param, long);
849 case CURLOPT_SSLVERSION:
851 * Set explicit SSL version to try to connect with, as some SSL
852 * implementations are lame.
854 data->set.ssl.version = va_arg(param, long);
857 #ifndef CURL_DISABLE_HTTP
858 case CURLOPT_AUTOREFERER:
860 * Switch on automatic referer that gets set if curl follows locations.
862 data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE;
865 case CURLOPT_ACCEPT_ENCODING:
867 * String to use at the value of Accept-Encoding header.
869 * If the encoding is set to "" we use an Accept-Encoding header that
870 * encompasses all the encodings we support.
871 * If the encoding is set to NULL we don't send an Accept-Encoding header
872 * and ignore an received Content-Encoding header.
875 argptr = va_arg(param, char *);
876 result = setstropt(&data->set.str[STRING_ENCODING],
877 (argptr && !*argptr)?
878 (char *) ALL_CONTENT_ENCODINGS: argptr);
881 case CURLOPT_TRANSFER_ENCODING:
882 data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE;
885 case CURLOPT_FOLLOWLOCATION:
887 * Follow Location: header hints on a HTTP-server.
889 data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE;
892 case CURLOPT_UNRESTRICTED_AUTH:
894 * Send authentication (user+password) when following locations, even when
897 data->set.http_disable_hostname_check_before_authentication =
898 (0 != va_arg(param, long))?TRUE:FALSE;
901 case CURLOPT_MAXREDIRS:
903 * The maximum amount of hops you allow curl to follow Location:
904 * headers. This should mostly be used to detect never-ending loops.
906 data->set.maxredirs = va_arg(param, long);
909 case CURLOPT_POSTREDIR:
912 * Set the behaviour of POST when redirecting
913 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
914 * CURL_REDIR_POST_301 - POST is kept as POST after 301
915 * CURL_REDIR_POST_302 - POST is kept as POST after 302
916 * CURL_REDIR_POST_303 - POST is kept as POST after 303
917 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
918 * other - POST is kept as POST after 301 and 302
920 int postRedir = curlx_sltosi(va_arg(param, long));
921 data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
926 /* Does this option serve a purpose anymore? Yes it does, when
927 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
929 if(va_arg(param, long)) {
930 data->set.httpreq = HTTPREQ_POST;
931 data->set.opt_no_body = FALSE; /* this is implied */
934 data->set.httpreq = HTTPREQ_GET;
937 case CURLOPT_COPYPOSTFIELDS:
939 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
940 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
941 * CURLOPT_COPYPOSTFIELDS and not altered later.
943 argptr = va_arg(param, char *);
945 if(!argptr || data->set.postfieldsize == -1)
946 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
949 * Check that requested length does not overflow the size_t type.
952 if((data->set.postfieldsize < 0) ||
953 ((sizeof(curl_off_t) != sizeof(size_t)) &&
954 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
955 result = CURLE_OUT_OF_MEMORY;
959 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
961 /* Allocate even when size == 0. This satisfies the need of possible
962 later address compare to detect the COPYPOSTFIELDS mode, and
963 to mark that postfields is used rather than read function or
966 p = malloc((size_t)(data->set.postfieldsize?
967 data->set.postfieldsize:1));
970 result = CURLE_OUT_OF_MEMORY;
972 if(data->set.postfieldsize)
973 memcpy(p, argptr, (size_t)data->set.postfieldsize);
975 data->set.str[STRING_COPYPOSTFIELDS] = p;
980 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
981 data->set.httpreq = HTTPREQ_POST;
984 case CURLOPT_POSTFIELDS:
986 * Like above, but use static data instead of copying it.
988 data->set.postfields = va_arg(param, void *);
989 /* Release old copied data. */
990 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
991 data->set.httpreq = HTTPREQ_POST;
994 case CURLOPT_POSTFIELDSIZE:
996 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
997 * figure it out. Enables binary posts.
999 bigsize = va_arg(param, long);
1001 if(data->set.postfieldsize < bigsize &&
1002 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1003 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1004 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1005 data->set.postfields = NULL;
1008 data->set.postfieldsize = bigsize;
1011 case CURLOPT_POSTFIELDSIZE_LARGE:
1013 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1014 * figure it out. Enables binary posts.
1016 bigsize = va_arg(param, curl_off_t);
1018 if(data->set.postfieldsize < bigsize &&
1019 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1020 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1021 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1022 data->set.postfields = NULL;
1025 data->set.postfieldsize = bigsize;
1028 case CURLOPT_HTTPPOST:
1030 * Set to make us do HTTP POST
1032 data->set.httppost = va_arg(param, struct curl_httppost *);
1033 data->set.httpreq = HTTPREQ_POST_FORM;
1034 data->set.opt_no_body = FALSE; /* this is implied */
1037 case CURLOPT_REFERER:
1039 * String to set in the HTTP Referer: field.
1041 if(data->change.referer_alloc) {
1042 Curl_safefree(data->change.referer);
1043 data->change.referer_alloc = FALSE;
1045 result = setstropt(&data->set.str[STRING_SET_REFERER],
1046 va_arg(param, char *));
1047 data->change.referer = data->set.str[STRING_SET_REFERER];
1050 case CURLOPT_USERAGENT:
1052 * String to use in the HTTP User-Agent field
1054 result = setstropt(&data->set.str[STRING_USERAGENT],
1055 va_arg(param, char *));
1058 case CURLOPT_HTTPHEADER:
1060 * Set a list with HTTP headers to use (or replace internals with)
1062 data->set.headers = va_arg(param, struct curl_slist *);
1065 case CURLOPT_HTTP200ALIASES:
1067 * Set a list of aliases for HTTP 200 in response header
1069 data->set.http200aliases = va_arg(param, struct curl_slist *);
1072 #if !defined(CURL_DISABLE_COOKIES)
1073 case CURLOPT_COOKIE:
1075 * Cookie string to send to the remote server in the request.
1077 result = setstropt(&data->set.str[STRING_COOKIE],
1078 va_arg(param, char *));
1081 case CURLOPT_COOKIEFILE:
1083 * Set cookie file to read and parse. Can be used multiple times.
1085 argptr = (char *)va_arg(param, void *);
1087 struct curl_slist *cl;
1088 /* append the cookie file name to the list of file names, and deal with
1090 cl = curl_slist_append(data->change.cookielist, argptr);
1092 curl_slist_free_all(data->change.cookielist);
1093 data->change.cookielist = NULL;
1094 return CURLE_OUT_OF_MEMORY;
1096 data->change.cookielist = cl; /* store the list for later use */
1100 case CURLOPT_COOKIEJAR:
1102 * Set cookie file name to dump all cookies to when we're done.
1104 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1105 va_arg(param, char *));
1108 * Activate the cookie parser. This may or may not already
1111 data->cookies = Curl_cookie_init(data, NULL, data->cookies,
1112 data->set.cookiesession);
1115 case CURLOPT_COOKIESESSION:
1117 * Set this option to TRUE to start a new "cookie session". It will
1118 * prevent the forthcoming read-cookies-from-file actions to accept
1119 * cookies that are marked as being session cookies, as they belong to a
1122 * In the original Netscape cookie spec, "session cookies" are cookies
1123 * with no expire date set. RFC2109 describes the same action if no
1124 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1125 * a 'Discard' action that can enforce the discard even for cookies that
1128 * We run mostly with the original cookie spec, as hardly anyone implements
1131 data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE;
1134 case CURLOPT_COOKIELIST:
1135 argptr = va_arg(param, char *);
1140 if(Curl_raw_equal(argptr, "ALL")) {
1141 /* clear all cookies */
1142 Curl_cookie_clearall(data->cookies);
1145 else if(Curl_raw_equal(argptr, "SESS")) {
1146 /* clear session cookies */
1147 Curl_cookie_clearsess(data->cookies);
1150 else if(Curl_raw_equal(argptr, "FLUSH")) {
1151 /* flush cookies to file */
1152 Curl_flush_cookies(data, 0);
1157 /* if cookie engine was not running, activate it */
1158 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1160 argptr = strdup(argptr);
1162 result = CURLE_OUT_OF_MEMORY;
1166 if(checkprefix("Set-Cookie:", argptr))
1167 /* HTTP Header format line */
1168 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1171 /* Netscape format line */
1172 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1176 #endif /* CURL_DISABLE_COOKIES */
1178 case CURLOPT_HTTPGET:
1180 * Set to force us do HTTP GET
1182 if(va_arg(param, long)) {
1183 data->set.httpreq = HTTPREQ_GET;
1184 data->set.upload = FALSE; /* switch off upload */
1185 data->set.opt_no_body = FALSE; /* this is implied */
1189 case CURLOPT_HTTP_VERSION:
1191 * This sets a requested HTTP version to be used. The value is one of
1192 * the listed enums in curl/curl.h.
1194 data->set.httpversion = va_arg(param, long);
1197 case CURLOPT_HTTPAUTH:
1199 * Set HTTP Authentication type BITMASK.
1204 unsigned long auth = va_arg(param, unsigned long);
1206 if(auth == CURLAUTH_NONE) {
1207 data->set.httpauth = auth;
1211 /* the DIGEST_IE bit is only used to set a special marker, for all the
1212 rest we need to handle it as normal DIGEST */
1213 data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
1215 if(auth & CURLAUTH_DIGEST_IE) {
1216 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1217 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1220 /* switch off bits we can't support */
1222 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1223 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1224 #elif !defined(NTLM_WB_ENABLED)
1225 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1227 #ifndef USE_HTTP_NEGOTIATE
1228 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
1232 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1235 while(bitcheck < 31) {
1236 if(auth & (1UL << bitcheck++)) {
1242 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1244 data->set.httpauth = auth;
1248 #endif /* CURL_DISABLE_HTTP */
1250 case CURLOPT_CUSTOMREQUEST:
1252 * Set a custom string to use as request
1254 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1255 va_arg(param, char *));
1258 data->set.httpreq = HTTPREQ_CUSTOM;
1259 here, we continue as if we were using the already set type
1260 and this just changes the actual request keyword */
1263 #ifndef CURL_DISABLE_PROXY
1264 case CURLOPT_HTTPPROXYTUNNEL:
1266 * Tunnel operations through the proxy instead of normal proxy use
1268 data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE;
1271 case CURLOPT_PROXYPORT:
1273 * Explicitly set HTTP proxy port number.
1275 data->set.proxyport = va_arg(param, long);
1278 case CURLOPT_PROXYAUTH:
1280 * Set HTTP Authentication type BITMASK.
1285 unsigned long auth = va_arg(param, unsigned long);
1287 if(auth == CURLAUTH_NONE) {
1288 data->set.proxyauth = auth;
1292 /* the DIGEST_IE bit is only used to set a special marker, for all the
1293 rest we need to handle it as normal DIGEST */
1294 data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
1296 if(auth & CURLAUTH_DIGEST_IE) {
1297 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1298 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1300 /* switch off bits we can't support */
1302 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1303 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1304 #elif !defined(NTLM_WB_ENABLED)
1305 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1307 #ifndef USE_HTTP_NEGOTIATE
1308 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
1312 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1315 while(bitcheck < 31) {
1316 if(auth & (1UL << bitcheck++)) {
1322 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1324 data->set.proxyauth = auth;
1330 * Set proxy server:port to use as HTTP proxy.
1332 * If the proxy is set to "" we explicitly say that we don't want to use a
1333 * proxy (even though there might be environment variables saying so).
1335 * Setting it to NULL, means no proxy but allows the environment variables
1338 result = setstropt(&data->set.str[STRING_PROXY],
1339 va_arg(param, char *));
1342 case CURLOPT_PROXYTYPE:
1344 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1346 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1349 case CURLOPT_PROXY_TRANSFER_MODE:
1351 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1353 switch (va_arg(param, long)) {
1355 data->set.proxy_transfer_mode = FALSE;
1358 data->set.proxy_transfer_mode = TRUE;
1361 /* reserve other values for future use */
1362 result = CURLE_UNKNOWN_OPTION;
1366 #endif /* CURL_DISABLE_PROXY */
1368 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1369 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1371 * Set gssapi service name
1373 result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
1374 va_arg(param, char *));
1377 case CURLOPT_SOCKS5_GSSAPI_NEC:
1379 * set flag for nec socks5 support
1381 data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE;
1385 case CURLOPT_WRITEHEADER:
1387 * Custom pointer to pass the header write callback function
1389 data->set.writeheader = (void *)va_arg(param, void *);
1391 case CURLOPT_ERRORBUFFER:
1393 * Error buffer provided by the caller to get the human readable
1396 data->set.errorbuffer = va_arg(param, char *);
1400 * FILE pointer to write to. Or possibly
1401 * used as argument to the write callback.
1403 data->set.out = va_arg(param, void *);
1405 case CURLOPT_FTPPORT:
1407 * Use FTP PORT, this also specifies which IP address to use
1409 result = setstropt(&data->set.str[STRING_FTPPORT],
1410 va_arg(param, char *));
1411 data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ?
1415 case CURLOPT_FTP_USE_EPRT:
1416 data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE;
1419 case CURLOPT_FTP_USE_EPSV:
1420 data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE;
1423 case CURLOPT_FTP_USE_PRET:
1424 data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE;
1427 case CURLOPT_FTP_SSL_CCC:
1428 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1431 case CURLOPT_FTP_SKIP_PASV_IP:
1433 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1434 * bypass of the IP address in PASV responses.
1436 data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE;
1439 case CURLOPT_INFILE:
1441 * FILE pointer to read the file to be uploaded from. Or possibly
1442 * used as argument to the read callback.
1444 data->set.in = va_arg(param, void *);
1446 case CURLOPT_INFILESIZE:
1448 * If known, this should inform curl about the file size of the
1449 * to-be-uploaded file.
1451 data->set.infilesize = va_arg(param, long);
1453 case CURLOPT_INFILESIZE_LARGE:
1455 * If known, this should inform curl about the file size of the
1456 * to-be-uploaded file.
1458 data->set.infilesize = va_arg(param, curl_off_t);
1460 case CURLOPT_LOW_SPEED_LIMIT:
1462 * The low speed limit that if transfers are below this for
1463 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1465 data->set.low_speed_limit=va_arg(param, long);
1467 case CURLOPT_MAX_SEND_SPEED_LARGE:
1469 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1470 * bytes per second the transfer is throttled..
1472 data->set.max_send_speed=va_arg(param, curl_off_t);
1474 case CURLOPT_MAX_RECV_SPEED_LARGE:
1476 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1477 * second the transfer is throttled..
1479 data->set.max_recv_speed=va_arg(param, curl_off_t);
1481 case CURLOPT_LOW_SPEED_TIME:
1483 * The low speed time that if transfers are below the set
1484 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1486 data->set.low_speed_time=va_arg(param, long);
1492 if(data->change.url_alloc) {
1493 /* the already set URL is allocated, free it first! */
1494 Curl_safefree(data->change.url);
1495 data->change.url_alloc = FALSE;
1497 result = setstropt(&data->set.str[STRING_SET_URL],
1498 va_arg(param, char *));
1499 data->change.url = data->set.str[STRING_SET_URL];
1503 * The port number to use when getting the URL
1505 data->set.use_port = va_arg(param, long);
1507 case CURLOPT_TIMEOUT:
1509 * The maximum time you allow curl to use for a single transfer
1512 data->set.timeout = va_arg(param, long) * 1000L;
1515 case CURLOPT_TIMEOUT_MS:
1516 data->set.timeout = va_arg(param, long);
1519 case CURLOPT_CONNECTTIMEOUT:
1521 * The maximum time you allow curl to use to connect.
1523 data->set.connecttimeout = va_arg(param, long) * 1000L;
1526 case CURLOPT_CONNECTTIMEOUT_MS:
1527 data->set.connecttimeout = va_arg(param, long);
1530 case CURLOPT_ACCEPTTIMEOUT_MS:
1532 * The maximum time you allow curl to wait for server connect
1534 data->set.accepttimeout = va_arg(param, long);
1537 case CURLOPT_USERPWD:
1539 * user:password;options to use in the operation
1541 result = setstropt_userpwd(va_arg(param, char *),
1542 &data->set.str[STRING_USERNAME],
1543 &data->set.str[STRING_PASSWORD],
1544 &data->set.str[STRING_OPTIONS]);
1546 case CURLOPT_USERNAME:
1548 * authentication user name to use in the operation
1550 result = setstropt(&data->set.str[STRING_USERNAME],
1551 va_arg(param, char *));
1553 case CURLOPT_PASSWORD:
1555 * authentication password to use in the operation
1557 result = setstropt(&data->set.str[STRING_PASSWORD],
1558 va_arg(param, char *));
1560 case CURLOPT_POSTQUOTE:
1562 * List of RAW FTP commands to use after a transfer
1564 data->set.postquote = va_arg(param, struct curl_slist *);
1566 case CURLOPT_PREQUOTE:
1568 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1570 data->set.prequote = va_arg(param, struct curl_slist *);
1574 * List of RAW FTP commands to use before a transfer
1576 data->set.quote = va_arg(param, struct curl_slist *);
1578 case CURLOPT_RESOLVE:
1580 * List of NAME:[address] names to populate the DNS cache with
1581 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1583 * Names added with this API will remain in the cache until explicitly
1584 * removed or the handle is cleaned up.
1586 * This API can remove any name from the DNS cache, but only entries
1587 * that aren't actually in use right now will be pruned immediately.
1589 data->set.resolve = va_arg(param, struct curl_slist *);
1590 data->change.resolve = data->set.resolve;
1592 case CURLOPT_PROGRESSFUNCTION:
1594 * Progress callback function
1596 data->set.fprogress = va_arg(param, curl_progress_callback);
1597 if(data->set.fprogress)
1598 data->progress.callback = TRUE; /* no longer internal */
1600 data->progress.callback = FALSE; /* NULL enforces internal */
1603 case CURLOPT_PROGRESSDATA:
1605 * Custom client data to pass to the progress callback
1607 data->set.progress_client = va_arg(param, void *);
1610 #ifndef CURL_DISABLE_PROXY
1611 case CURLOPT_PROXYUSERPWD:
1613 * user:password needed to use the proxy
1615 result = setstropt_userpwd(va_arg(param, char *),
1616 &data->set.str[STRING_PROXYUSERNAME],
1617 &data->set.str[STRING_PROXYPASSWORD], NULL);
1619 case CURLOPT_PROXYUSERNAME:
1621 * authentication user name to use in the operation
1623 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1624 va_arg(param, char *));
1626 case CURLOPT_PROXYPASSWORD:
1628 * authentication password to use in the operation
1630 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1631 va_arg(param, char *));
1633 case CURLOPT_NOPROXY:
1635 * proxy exception list
1637 result = setstropt(&data->set.str[STRING_NOPROXY],
1638 va_arg(param, char *));
1644 * What range of the file you want to transfer
1646 result = setstropt(&data->set.str[STRING_SET_RANGE],
1647 va_arg(param, char *));
1649 case CURLOPT_RESUME_FROM:
1651 * Resume transfer at the give file position
1653 data->set.set_resume_from = va_arg(param, long);
1655 case CURLOPT_RESUME_FROM_LARGE:
1657 * Resume transfer at the give file position
1659 data->set.set_resume_from = va_arg(param, curl_off_t);
1661 case CURLOPT_DEBUGFUNCTION:
1663 * stderr write callback.
1665 data->set.fdebug = va_arg(param, curl_debug_callback);
1667 * if the callback provided is NULL, it'll use the default callback
1670 case CURLOPT_DEBUGDATA:
1672 * Set to a void * that should receive all error writes. This
1673 * defaults to CURLOPT_STDERR for normal operations.
1675 data->set.debugdata = va_arg(param, void *);
1677 case CURLOPT_STDERR:
1679 * Set to a FILE * that should receive all error writes. This
1680 * defaults to stderr for normal operations.
1682 data->set.err = va_arg(param, FILE *);
1684 data->set.err = stderr;
1686 case CURLOPT_HEADERFUNCTION:
1688 * Set header write callback
1690 data->set.fwrite_header = va_arg(param, curl_write_callback);
1692 case CURLOPT_WRITEFUNCTION:
1694 * Set data write callback
1696 data->set.fwrite_func = va_arg(param, curl_write_callback);
1697 if(!data->set.fwrite_func) {
1698 data->set.is_fwrite_set = 0;
1699 /* When set to NULL, reset to our internal default function */
1700 data->set.fwrite_func = (curl_write_callback)fwrite;
1703 data->set.is_fwrite_set = 1;
1705 case CURLOPT_READFUNCTION:
1707 * Read data callback
1709 data->set.fread_func = va_arg(param, curl_read_callback);
1710 if(!data->set.fread_func) {
1711 data->set.is_fread_set = 0;
1712 /* When set to NULL, reset to our internal default function */
1713 data->set.fread_func = (curl_read_callback)fread;
1716 data->set.is_fread_set = 1;
1718 case CURLOPT_SEEKFUNCTION:
1720 * Seek callback. Might be NULL.
1722 data->set.seek_func = va_arg(param, curl_seek_callback);
1724 case CURLOPT_SEEKDATA:
1726 * Seek control callback. Might be NULL.
1728 data->set.seek_client = va_arg(param, void *);
1730 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1732 * "Convert from network encoding" callback
1734 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1736 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1738 * "Convert to network encoding" callback
1740 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1742 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1744 * "Convert from UTF-8 encoding" callback
1746 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1748 case CURLOPT_IOCTLFUNCTION:
1750 * I/O control callback. Might be NULL.
1752 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1754 case CURLOPT_IOCTLDATA:
1756 * I/O control data pointer. Might be NULL.
1758 data->set.ioctl_client = va_arg(param, void *);
1760 case CURLOPT_SSLCERT:
1762 * String that holds file name of the SSL certificate to use
1764 result = setstropt(&data->set.str[STRING_CERT],
1765 va_arg(param, char *));
1767 case CURLOPT_SSLCERTTYPE:
1769 * String that holds file type of the SSL certificate to use
1771 result = setstropt(&data->set.str[STRING_CERT_TYPE],
1772 va_arg(param, char *));
1774 case CURLOPT_SSLKEY:
1776 * String that holds file name of the SSL key to use
1778 result = setstropt(&data->set.str[STRING_KEY],
1779 va_arg(param, char *));
1781 case CURLOPT_SSLKEYTYPE:
1783 * String that holds file type of the SSL key to use
1785 result = setstropt(&data->set.str[STRING_KEY_TYPE],
1786 va_arg(param, char *));
1788 case CURLOPT_KEYPASSWD:
1790 * String that holds the SSL or SSH private key password.
1792 result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1793 va_arg(param, char *));
1795 case CURLOPT_SSLENGINE:
1797 * String that holds the SSL crypto engine.
1799 argptr = va_arg(param, char *);
1800 if(argptr && argptr[0])
1801 result = Curl_ssl_set_engine(data, argptr);
1804 case CURLOPT_SSLENGINE_DEFAULT:
1806 * flag to set engine as default.
1808 result = Curl_ssl_set_engine_default(data);
1812 * Kludgy option to enable CRLF conversions. Subject for removal.
1814 data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE;
1817 case CURLOPT_INTERFACE:
1819 * Set what interface or address/hostname to bind the socket to when
1820 * performing an operation and thus what from-IP your connection will use.
1822 result = setstropt(&data->set.str[STRING_DEVICE],
1823 va_arg(param, char *));
1825 case CURLOPT_LOCALPORT:
1827 * Set what local port to bind the socket to when performing an operation.
1829 data->set.localport = curlx_sltous(va_arg(param, long));
1831 case CURLOPT_LOCALPORTRANGE:
1833 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
1835 data->set.localportrange = curlx_sltosi(va_arg(param, long));
1837 case CURLOPT_KRBLEVEL:
1839 * A string that defines the kerberos security level.
1841 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
1842 va_arg(param, char *));
1843 data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE;
1845 case CURLOPT_GSSAPI_DELEGATION:
1847 * GSSAPI credential delegation
1849 data->set.gssapi_delegation = va_arg(param, long);
1851 case CURLOPT_SSL_VERIFYPEER:
1853 * Enable peer SSL verifying.
1855 data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE;
1857 case CURLOPT_SSL_VERIFYHOST:
1859 * Enable verification of the host name in the peer certificate
1861 arg = va_arg(param, long);
1863 /* Obviously people are not reading documentation and too many thought
1864 this argument took a boolean when it wasn't and misused it. We thus ban
1865 1 as a sensible input and we warn about its use. Then we only have the
1866 2 action internally stored as TRUE. */
1869 failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
1870 return CURLE_BAD_FUNCTION_ARGUMENT;
1873 data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE;
1876 /* since these two options are only possible to use on an OpenSSL-
1877 powered libcurl we #ifdef them on this condition so that libcurls
1878 built against other SSL libs will return a proper error when trying
1879 to set this option! */
1880 case CURLOPT_SSL_CTX_FUNCTION:
1882 * Set a SSL_CTX callback
1884 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
1886 case CURLOPT_SSL_CTX_DATA:
1888 * Set a SSL_CTX callback parameter pointer
1890 data->set.ssl.fsslctxp = va_arg(param, void *);
1892 case CURLOPT_CERTINFO:
1893 data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE;
1896 case CURLOPT_CAINFO:
1898 * Set CA info for SSL connection. Specify file name of the CA certificate
1900 result = setstropt(&data->set.str[STRING_SSL_CAFILE],
1901 va_arg(param, char *));
1903 case CURLOPT_CAPATH:
1905 * Set CA path info for SSL connection. Specify directory name of the CA
1906 * certificates which have been prepared using openssl c_rehash utility.
1908 /* This does not work on windows. */
1909 result = setstropt(&data->set.str[STRING_SSL_CAPATH],
1910 va_arg(param, char *));
1912 case CURLOPT_CRLFILE:
1914 * Set CRL file info for SSL connection. Specify file name of the CRL
1915 * to check certificates revocation
1917 result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
1918 va_arg(param, char *));
1920 case CURLOPT_ISSUERCERT:
1922 * Set Issuer certificate file
1923 * to check certificates issuer
1925 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
1926 va_arg(param, char *));
1928 case CURLOPT_TELNETOPTIONS:
1930 * Set a linked list of telnet options
1932 data->set.telnet_options = va_arg(param, struct curl_slist *);
1935 case CURLOPT_BUFFERSIZE:
1937 * The application kindly asks for a differently sized receive buffer.
1938 * If it seems reasonable, we'll use it.
1940 data->set.buffer_size = va_arg(param, long);
1942 if((data->set.buffer_size> (BUFSIZE -1 )) ||
1943 (data->set.buffer_size < 1))
1944 data->set.buffer_size = 0; /* huge internal default */
1948 case CURLOPT_NOSIGNAL:
1950 * The application asks not to set any signal() or alarm() handlers,
1951 * even when using a timeout.
1953 data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE;
1958 struct Curl_share *set;
1959 set = va_arg(param, struct Curl_share *);
1961 /* disconnect from old share, if any */
1963 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
1965 if(data->dns.hostcachetype == HCACHE_SHARED) {
1966 data->dns.hostcache = NULL;
1967 data->dns.hostcachetype = HCACHE_NONE;
1970 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
1971 if(data->share->cookies == data->cookies)
1972 data->cookies = NULL;
1975 if(data->share->sslsession == data->state.session)
1976 data->state.session = NULL;
1978 data->share->dirty--;
1980 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
1984 /* use new share if it set */
1988 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
1990 data->share->dirty++;
1992 if(data->share->hostcache) {
1993 /* use shared host cache */
1994 data->dns.hostcache = data->share->hostcache;
1995 data->dns.hostcachetype = HCACHE_SHARED;
1997 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
1998 if(data->share->cookies) {
1999 /* use shared cookie list, first free own one if any */
2001 Curl_cookie_cleanup(data->cookies);
2002 /* enable cookies since we now use a share that uses cookies! */
2003 data->cookies = data->share->cookies;
2005 #endif /* CURL_DISABLE_HTTP */
2006 if(data->share->sslsession) {
2007 data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions;
2008 data->state.session = data->share->sslsession;
2010 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2013 /* check for host cache not needed,
2014 * it will be done by curl_easy_perform */
2018 case CURLOPT_PRIVATE:
2020 * Set private data pointer.
2022 data->set.private_data = va_arg(param, void *);
2025 case CURLOPT_MAXFILESIZE:
2027 * Set the maximum size of a file to download.
2029 data->set.max_filesize = va_arg(param, long);
2033 case CURLOPT_USE_SSL:
2035 * Make transfers attempt to use SSL/TLS.
2037 data->set.use_ssl = (curl_usessl)va_arg(param, long);
2040 case CURLOPT_SSL_OPTIONS:
2041 arg = va_arg(param, long);
2042 data->set.ssl_enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE;
2046 case CURLOPT_FTPSSLAUTH:
2048 * Set a specific auth for FTP-SSL transfers.
2050 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2053 case CURLOPT_IPRESOLVE:
2054 data->set.ipver = va_arg(param, long);
2057 case CURLOPT_MAXFILESIZE_LARGE:
2059 * Set the maximum size of a file to download.
2061 data->set.max_filesize = va_arg(param, curl_off_t);
2064 case CURLOPT_TCP_NODELAY:
2066 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2069 data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE;
2072 case CURLOPT_FTP_ACCOUNT:
2073 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2074 va_arg(param, char *));
2077 case CURLOPT_IGNORE_CONTENT_LENGTH:
2078 data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE;
2081 case CURLOPT_CONNECT_ONLY:
2083 * No data transfer, set up connection and let application use the socket
2085 data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE;
2088 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2089 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2090 va_arg(param, char *));
2093 case CURLOPT_SOCKOPTFUNCTION:
2095 * socket callback function: called after socket() but before connect()
2097 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2100 case CURLOPT_SOCKOPTDATA:
2102 * socket callback data pointer. Might be NULL.
2104 data->set.sockopt_client = va_arg(param, void *);
2107 case CURLOPT_OPENSOCKETFUNCTION:
2109 * open/create socket callback function: called instead of socket(),
2112 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2115 case CURLOPT_OPENSOCKETDATA:
2117 * socket callback data pointer. Might be NULL.
2119 data->set.opensocket_client = va_arg(param, void *);
2122 case CURLOPT_CLOSESOCKETFUNCTION:
2124 * close socket callback function: called instead of close()
2125 * when shutting down a connection
2127 data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
2130 case CURLOPT_CLOSESOCKETDATA:
2132 * socket callback data pointer. Might be NULL.
2134 data->set.closesocket_client = va_arg(param, void *);
2137 case CURLOPT_SSL_SESSIONID_CACHE:
2138 data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE;
2142 /* we only include SSH options if explicitly built to support SSH */
2143 case CURLOPT_SSH_AUTH_TYPES:
2144 data->set.ssh_auth_types = va_arg(param, long);
2147 case CURLOPT_SSH_PUBLIC_KEYFILE:
2149 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2151 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2152 va_arg(param, char *));
2155 case CURLOPT_SSH_PRIVATE_KEYFILE:
2157 * Use this file instead of the $HOME/.ssh/id_dsa file
2159 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2160 va_arg(param, char *));
2162 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2164 * Option to allow for the MD5 of the host public key to be checked
2165 * for validation purposes.
2167 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2168 va_arg(param, char *));
2170 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2171 case CURLOPT_SSH_KNOWNHOSTS:
2173 * Store the file name to read known hosts from.
2175 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2176 va_arg(param, char *));
2179 case CURLOPT_SSH_KEYFUNCTION:
2180 /* setting to NULL is fine since the ssh.c functions themselves will
2181 then rever to use the internal default */
2182 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2185 case CURLOPT_SSH_KEYDATA:
2187 * Custom client data to pass to the SSH keyfunc callback
2189 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2191 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2193 #endif /* USE_LIBSSH2 */
2195 case CURLOPT_HTTP_TRANSFER_DECODING:
2197 * disable libcurl transfer encoding is used
2199 data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE;
2202 case CURLOPT_HTTP_CONTENT_DECODING:
2204 * raw data passed to the application when content encoding is used
2206 data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE;
2209 case CURLOPT_NEW_FILE_PERMS:
2211 * Uses these permissions instead of 0644
2213 data->set.new_file_perms = va_arg(param, long);
2216 case CURLOPT_NEW_DIRECTORY_PERMS:
2218 * Uses these permissions instead of 0755
2220 data->set.new_directory_perms = va_arg(param, long);
2223 case CURLOPT_ADDRESS_SCOPE:
2225 * We always get longs when passed plain numericals, but for this value we
2226 * know that an unsigned int will always hold the value so we blindly
2227 * typecast to this type
2229 data->set.scope = curlx_sltoui(va_arg(param, long));
2232 case CURLOPT_PROTOCOLS:
2233 /* set the bitmask for the protocols that are allowed to be used for the
2234 transfer, which thus helps the app which takes URLs from users or other
2235 external inputs and want to restrict what protocol(s) to deal
2236 with. Defaults to CURLPROTO_ALL. */
2237 data->set.allowed_protocols = va_arg(param, long);
2240 case CURLOPT_REDIR_PROTOCOLS:
2241 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2242 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2243 to be set in both bitmasks to be allowed to get redirected to. Defaults
2244 to all protocols except FILE and SCP. */
2245 data->set.redir_protocols = va_arg(param, long);
2248 case CURLOPT_MAIL_FROM:
2249 /* Set the SMTP mail originator */
2250 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2251 va_arg(param, char *));
2254 case CURLOPT_MAIL_AUTH:
2255 /* Set the SMTP auth originator */
2256 result = setstropt(&data->set.str[STRING_MAIL_AUTH],
2257 va_arg(param, char *));
2260 case CURLOPT_MAIL_RCPT:
2261 /* Set the list of mail recipients */
2262 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2265 case CURLOPT_SASL_IR:
2266 /* Enable/disable SASL initial response */
2267 data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
2270 case CURLOPT_RTSP_REQUEST:
2273 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2274 * Would this be better if the RTSPREQ_* were just moved into here?
2276 long curl_rtspreq = va_arg(param, long);
2277 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2278 switch(curl_rtspreq) {
2279 case CURL_RTSPREQ_OPTIONS:
2280 rtspreq = RTSPREQ_OPTIONS;
2283 case CURL_RTSPREQ_DESCRIBE:
2284 rtspreq = RTSPREQ_DESCRIBE;
2287 case CURL_RTSPREQ_ANNOUNCE:
2288 rtspreq = RTSPREQ_ANNOUNCE;
2291 case CURL_RTSPREQ_SETUP:
2292 rtspreq = RTSPREQ_SETUP;
2295 case CURL_RTSPREQ_PLAY:
2296 rtspreq = RTSPREQ_PLAY;
2299 case CURL_RTSPREQ_PAUSE:
2300 rtspreq = RTSPREQ_PAUSE;
2303 case CURL_RTSPREQ_TEARDOWN:
2304 rtspreq = RTSPREQ_TEARDOWN;
2307 case CURL_RTSPREQ_GET_PARAMETER:
2308 rtspreq = RTSPREQ_GET_PARAMETER;
2311 case CURL_RTSPREQ_SET_PARAMETER:
2312 rtspreq = RTSPREQ_SET_PARAMETER;
2315 case CURL_RTSPREQ_RECORD:
2316 rtspreq = RTSPREQ_RECORD;
2319 case CURL_RTSPREQ_RECEIVE:
2320 rtspreq = RTSPREQ_RECEIVE;
2323 rtspreq = RTSPREQ_NONE;
2326 data->set.rtspreq = rtspreq;
2331 case CURLOPT_RTSP_SESSION_ID:
2333 * Set the RTSP Session ID manually. Useful if the application is
2334 * resuming a previously established RTSP session
2336 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2337 va_arg(param, char *));
2340 case CURLOPT_RTSP_STREAM_URI:
2342 * Set the Stream URI for the RTSP request. Unless the request is
2343 * for generic server options, the application will need to set this.
2345 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2346 va_arg(param, char *));
2349 case CURLOPT_RTSP_TRANSPORT:
2351 * The content of the Transport: header for the RTSP request
2353 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2354 va_arg(param, char *));
2357 case CURLOPT_RTSP_CLIENT_CSEQ:
2359 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2360 * application is resuming a previously broken connection. The CSEQ
2361 * will increment from this new number henceforth.
2363 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2366 case CURLOPT_RTSP_SERVER_CSEQ:
2367 /* Same as the above, but for server-initiated requests */
2368 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2371 case CURLOPT_INTERLEAVEDATA:
2372 data->set.rtp_out = va_arg(param, void *);
2374 case CURLOPT_INTERLEAVEFUNCTION:
2375 /* Set the user defined RTP write function */
2376 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2379 case CURLOPT_WILDCARDMATCH:
2380 data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE;
2382 case CURLOPT_CHUNK_BGN_FUNCTION:
2383 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2385 case CURLOPT_CHUNK_END_FUNCTION:
2386 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2388 case CURLOPT_FNMATCH_FUNCTION:
2389 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2391 case CURLOPT_CHUNK_DATA:
2392 data->wildcard.customptr = va_arg(param, void *);
2394 case CURLOPT_FNMATCH_DATA:
2395 data->set.fnmatch_data = va_arg(param, void *);
2398 case CURLOPT_TLSAUTH_USERNAME:
2399 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
2400 va_arg(param, char *));
2401 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2402 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2404 case CURLOPT_TLSAUTH_PASSWORD:
2405 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
2406 va_arg(param, char *));
2407 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2408 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2410 case CURLOPT_TLSAUTH_TYPE:
2411 if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
2412 data->set.ssl.authtype = CURL_TLSAUTH_SRP;
2414 data->set.ssl.authtype = CURL_TLSAUTH_NONE;
2417 case CURLOPT_DNS_SERVERS:
2418 result = Curl_set_dns_servers(data, va_arg(param, char *));
2421 case CURLOPT_TCP_KEEPALIVE:
2422 data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE;
2424 case CURLOPT_TCP_KEEPIDLE:
2425 data->set.tcp_keepidle = va_arg(param, long);
2427 case CURLOPT_TCP_KEEPINTVL:
2428 data->set.tcp_keepintvl = va_arg(param, long);
2432 /* unknown tag and its companion, just ignore: */
2433 result = CURLE_UNKNOWN_OPTION;
2440 static void conn_free(struct connectdata *conn)
2445 /* possible left-overs from the async name resolvers */
2446 Curl_resolver_cancel(conn);
2448 /* close the SSL stuff before we close any sockets since they will/may
2449 write to the sockets */
2450 Curl_ssl_close(conn, FIRSTSOCKET);
2451 Curl_ssl_close(conn, SECONDARYSOCKET);
2453 /* close possibly still open sockets */
2454 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2455 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2456 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2457 Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
2459 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
2460 Curl_ntlm_wb_cleanup(conn);
2463 Curl_safefree(conn->user);
2464 Curl_safefree(conn->passwd);
2465 Curl_safefree(conn->options);
2466 Curl_safefree(conn->proxyuser);
2467 Curl_safefree(conn->proxypasswd);
2468 Curl_safefree(conn->allocptr.proxyuserpwd);
2469 Curl_safefree(conn->allocptr.uagent);
2470 Curl_safefree(conn->allocptr.userpwd);
2471 Curl_safefree(conn->allocptr.accept_encoding);
2472 Curl_safefree(conn->allocptr.te);
2473 Curl_safefree(conn->allocptr.rangeline);
2474 Curl_safefree(conn->allocptr.ref);
2475 Curl_safefree(conn->allocptr.host);
2476 Curl_safefree(conn->allocptr.cookiehost);
2477 Curl_safefree(conn->allocptr.rtsp_transport);
2478 Curl_safefree(conn->trailer);
2479 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2480 Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2481 Curl_safefree(conn->master_buffer);
2483 Curl_llist_destroy(conn->send_pipe, NULL);
2484 Curl_llist_destroy(conn->recv_pipe, NULL);
2486 conn->send_pipe = NULL;
2487 conn->recv_pipe = NULL;
2489 Curl_safefree(conn->localdev);
2490 Curl_free_ssl_config(&conn->ssl_config);
2492 free(conn); /* free all the connection oriented data */
2495 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2497 struct SessionHandle *data;
2499 return CURLE_OK; /* this is closed and fine already */
2503 DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
2507 if(conn->dns_entry != NULL) {
2508 Curl_resolv_unlock(data, conn->dns_entry);
2509 conn->dns_entry = NULL;
2512 Curl_hostcache_prune(data); /* kill old DNS cache entries */
2515 int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
2516 int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
2518 /* Authentication data is a mix of connection-related and sessionhandle-
2519 related stuff. NTLM is connection-related so when we close the shop
2523 data->state.authhost.done = FALSE;
2524 data->state.authhost.picked =
2525 data->state.authhost.want;
2528 if(has_proxy_ntlm) {
2529 data->state.authproxy.done = FALSE;
2530 data->state.authproxy.picked =
2531 data->state.authproxy.want;
2534 if(has_host_ntlm || has_proxy_ntlm)
2535 data->state.authproblem = FALSE;
2538 /* Cleanup NTLM connection-related data */
2539 Curl_http_ntlm_cleanup(conn);
2541 /* Cleanup possible redirect junk */
2542 if(data->req.newurl) {
2543 free(data->req.newurl);
2544 data->req.newurl = NULL;
2547 if(conn->handler->disconnect)
2548 /* This is set if protocol-specific cleanups should be made */
2549 conn->handler->disconnect(conn, dead_connection);
2551 /* unlink ourselves! */
2552 infof(data, "Closing connection %d\n", conn->connection_id);
2553 Curl_conncache_remove_conn(data->state.conn_cache, conn);
2555 #if defined(USE_LIBIDN)
2556 if(conn->host.encalloc)
2557 idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
2558 with idn_free() since this was allocated
2560 if(conn->proxy.encalloc)
2561 idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
2562 freed with idn_free() since this was
2563 allocated by libidn */
2564 #elif defined(USE_WIN32_IDN)
2565 free(conn->host.encalloc); /* encoded host name buffer, must be freed with
2566 idn_free() since this was allocated by
2567 curl_win32_idn_to_ascii */
2568 if(conn->proxy.encalloc)
2569 free(conn->proxy.encalloc); /* encoded proxy name buffer, must be freed
2570 with idn_free() since this was allocated by
2571 curl_win32_idn_to_ascii */
2574 Curl_ssl_close(conn, FIRSTSOCKET);
2576 /* Indicate to all handles on the pipe that we're dead */
2577 if(Curl_multi_pipeline_enabled(data->multi)) {
2578 signalPipeClose(conn->send_pipe, TRUE);
2579 signalPipeClose(conn->recv_pipe, TRUE);
2583 data->state.current_conn = NULL;
2584 Curl_speedinit(data);
2590 * This function should return TRUE if the socket is to be assumed to
2591 * be dead. Most commonly this happens when the server has closed the
2592 * connection due to inactivity.
2594 static bool SocketIsDead(curl_socket_t sock)
2597 bool ret_val = TRUE;
2599 sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2607 static bool IsPipeliningPossible(const struct SessionHandle *handle,
2608 const struct connectdata *conn)
2610 if((conn->handler->protocol & CURLPROTO_HTTP) &&
2611 Curl_multi_pipeline_enabled(handle->multi) &&
2612 (handle->set.httpreq == HTTPREQ_GET ||
2613 handle->set.httpreq == HTTPREQ_HEAD) &&
2614 handle->set.httpversion != CURL_HTTP_VERSION_1_0)
2620 bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
2622 return Curl_multi_pipeline_enabled(handle->multi);
2625 CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
2626 struct curl_llist *pipeline)
2628 if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
2629 return CURLE_OUT_OF_MEMORY;
2630 infof(data, "Curl_addHandleToPipeline: length: %d\n", pipeline->size);
2634 int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
2635 struct curl_llist *pipeline)
2637 struct curl_llist_element *curr;
2639 curr = pipeline->head;
2641 if(curr->ptr == handle) {
2642 Curl_llist_remove(pipeline, curr, NULL);
2643 return 1; /* we removed a handle */
2651 #if 0 /* this code is saved here as it is useful for debugging purposes */
2652 static void Curl_printPipeline(struct curl_llist *pipeline)
2654 struct curl_llist_element *curr;
2656 curr = pipeline->head;
2658 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2659 infof(data, "Handle in pipeline: %s\n", data->state.path);
2665 static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
2667 struct curl_llist_element *curr = pipeline->head;
2669 return (struct SessionHandle *) curr->ptr;
2675 /* remove the specified connection from all (possible) pipelines and related
2677 void Curl_getoff_all_pipelines(struct SessionHandle *data,
2678 struct connectdata *conn)
2680 bool recv_head = (conn->readchannel_inuse &&
2681 (gethandleathead(conn->recv_pipe) == data)) ? TRUE : FALSE;
2683 bool send_head = (conn->writechannel_inuse &&
2684 (gethandleathead(conn->send_pipe) == data)) ? TRUE : FALSE;
2686 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2687 conn->readchannel_inuse = FALSE;
2688 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2689 conn->writechannel_inuse = FALSE;
2692 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2694 struct curl_llist_element *curr;
2699 curr = pipeline->head;
2701 struct curl_llist_element *next = curr->next;
2702 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2704 #ifdef DEBUGBUILD /* debug-only code */
2705 if(data->magic != CURLEASY_MAGIC_NUMBER) {
2707 infof(data, "signalPipeClose() found BAAD easy handle\n");
2712 data->state.pipe_broke = TRUE;
2713 Curl_multi_handlePipeBreak(data);
2714 Curl_llist_remove(pipeline, curr, NULL);
2720 * This function finds the connection in the connection
2721 * cache that has been unused for the longest time.
2723 * Returns the pointer to the oldest idle connection, or NULL if none was
2726 static struct connectdata *
2727 find_oldest_idle_connection(struct SessionHandle *data)
2729 struct conncache *bc = data->state.conn_cache;
2730 struct curl_hash_iterator iter;
2731 struct curl_llist_element *curr;
2732 struct curl_hash_element *he;
2736 struct connectdata *conn_candidate = NULL;
2737 struct connectbundle *bundle;
2741 Curl_hash_start_iterate(bc->hash, &iter);
2743 he = Curl_hash_next_element(&iter);
2745 struct connectdata *conn;
2749 curr = bundle->conn_list->head;
2754 /* Set higher score for the age passed since the connection was used */
2755 score = Curl_tvdiff(now, conn->now);
2757 if(score > highscore) {
2759 conn_candidate = conn;
2765 he = Curl_hash_next_element(&iter);
2768 return conn_candidate;
2772 * This function finds the connection in the connection
2773 * bundle that has been unused for the longest time.
2775 * Returns the pointer to the oldest idle connection, or NULL if none was
2778 static struct connectdata *
2779 find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
2780 struct connectbundle *bundle)
2782 struct curl_llist_element *curr;
2786 struct connectdata *conn_candidate = NULL;
2787 struct connectdata *conn;
2793 curr = bundle->conn_list->head;
2798 /* Set higher score for the age passed since the connection was used */
2799 score = Curl_tvdiff(now, conn->now);
2801 if(score > highscore) {
2803 conn_candidate = conn;
2809 return conn_candidate;
2813 * Given one filled in connection struct (named needle), this function should
2814 * detect if there already is one that has all the significant details
2815 * exactly the same and thus should be used instead.
2817 * If there is a match, this function returns TRUE - and has marked the
2818 * connection as 'in-use'. It must later be called with ConnectionDone() to
2819 * return back to 'idle' (unused) state.
2821 * The force_reuse flag is set if the connection must be used, even if
2822 * the pipelining strategy wants to open a new connection instead of reusing.
2825 ConnectionExists(struct SessionHandle *data,
2826 struct connectdata *needle,
2827 struct connectdata **usethis,
2830 struct connectdata *check;
2831 struct connectdata *chosen = 0;
2832 bool canPipeline = IsPipeliningPossible(data, needle);
2833 bool wantNTLM = (data->state.authhost.want==CURLAUTH_NTLM) ||
2834 (data->state.authhost.want==CURLAUTH_NTLM_WB) ? TRUE : FALSE;
2835 struct connectbundle *bundle;
2837 *force_reuse = FALSE;
2839 /* We can't pipe if the site is blacklisted */
2840 if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
2841 canPipeline = FALSE;
2844 /* Look up the bundle with all the connections to this
2846 bundle = Curl_conncache_find_bundle(data->state.conn_cache,
2849 size_t max_pipe_len = Curl_multi_max_pipeline_length(data->multi);
2850 size_t best_pipe_len = max_pipe_len;
2851 struct curl_llist_element *curr;
2853 infof(data, "Found bundle for host %s: %p\n", needle->host.name, bundle);
2855 /* We can't pipe if we don't know anything about the server */
2856 if(canPipeline && !bundle->server_supports_pipelining) {
2857 infof(data, "Server doesn't support pipelining\n");
2858 canPipeline = FALSE;
2861 curr = bundle->conn_list->head;
2864 bool credentialsMatch = FALSE;
2868 * Note that if we use a HTTP proxy, we check connections to that
2869 * proxy and not to the actual remote server.
2874 pipeLen = check->send_pipe->size + check->recv_pipe->size;
2876 if(!pipeLen && !check->inuse) {
2877 /* The check for a dead socket makes sense only if there are no
2878 handles in pipeline and the connection isn't already marked in
2881 if(check->handler->protocol & CURLPROTO_RTSP)
2882 /* RTSP is a special case due to RTP interleaving */
2883 dead = Curl_rtsp_connisdead(check);
2885 dead = SocketIsDead(check->sock[FIRSTSOCKET]);
2889 infof(data, "Connection %d seems to be dead!\n",
2890 check->connection_id);
2892 /* disconnect resources */
2893 Curl_disconnect(check, /* dead_connection */ TRUE);
2899 /* Make sure the pipe has only GET requests */
2900 struct SessionHandle* sh = gethandleathead(check->send_pipe);
2901 struct SessionHandle* rh = gethandleathead(check->recv_pipe);
2903 if(!IsPipeliningPossible(sh, check))
2907 if(!IsPipeliningPossible(rh, check))
2913 /* can only happen within multi handles, and means that another easy
2914 handle is using this connection */
2918 if(Curl_resolver_asynch()) {
2919 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
2920 completed yet and until then we don't re-use this connection */
2921 if(!check->ip_addr_str[0]) {
2923 "Connection #%ld is still name resolving, can't reuse\n",
2924 check->connection_id);
2929 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
2930 check->bits.close) {
2931 /* Don't pick a connection that hasn't connected yet or that is going
2933 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
2934 check->connection_id);
2936 if(check->recv_pipe->size > 0) {
2938 "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
2939 check->connection_id);
2946 if((needle->handler->flags&PROTOPT_SSL) !=
2947 (check->handler->flags&PROTOPT_SSL))
2948 /* don't do mixed SSL and non-SSL connections */
2949 if(!(needle->handler->protocol & check->handler->protocol))
2950 /* except protocols that have been upgraded via TLS */
2953 if(needle->handler->flags&PROTOPT_SSL) {
2954 if((data->set.ssl.verifypeer != check->verifypeer) ||
2955 (data->set.ssl.verifyhost != check->verifyhost))
2959 if(needle->bits.proxy != check->bits.proxy)
2960 /* don't do mixed proxy and non-proxy connections */
2963 if(!canPipeline && check->inuse)
2964 /* this request can't be pipelined but the checked connection is
2965 already in use so we skip it */
2968 if(needle->localdev || needle->localport) {
2969 /* If we are bound to a specific local end (IP+port), we must not
2970 re-use a random other one, although if we didn't ask for a
2971 particular one we can reuse one that was bound.
2973 This comparison is a bit rough and too strict. Since the input
2974 parameters can be specified in numerous ways and still end up the
2975 same it would take a lot of processing to make it really accurate.
2976 Instead, this matching will assume that re-uses of bound connections
2977 will most likely also re-use the exact same binding parameters and
2978 missing out a few edge cases shouldn't hurt anyone very much.
2980 if((check->localport != needle->localport) ||
2981 (check->localportrange != needle->localportrange) ||
2983 !needle->localdev ||
2984 strcmp(check->localdev, needle->localdev))
2988 if((needle->handler->protocol & CURLPROTO_FTP) ||
2989 ((needle->handler->protocol & CURLPROTO_HTTP) && wantNTLM)) {
2990 /* This is FTP or HTTP+NTLM, verify that we're using the same name
2991 and password as well */
2992 if(!strequal(needle->user, check->user) ||
2993 !strequal(needle->passwd, check->passwd)) {
2994 /* one of them was different */
2997 credentialsMatch = TRUE;
3000 if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
3001 (needle->bits.httpproxy && check->bits.httpproxy &&
3002 needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
3003 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3004 (needle->port == check->port))) {
3005 /* The requested connection does not use a HTTP proxy or it uses SSL or
3006 it is a non-SSL protocol tunneled over the same http proxy name and
3007 port number or it is a non-SSL protocol which is allowed to be
3010 if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
3011 needle->handler->protocol & check->handler->protocol) &&
3012 Curl_raw_equal(needle->host.name, check->host.name) &&
3013 needle->remote_port == check->remote_port) {
3014 if(needle->handler->flags & PROTOPT_SSL) {
3015 /* This is a SSL connection so verify that we're using the same
3016 SSL options as well */
3017 if(!Curl_ssl_config_matches(&needle->ssl_config,
3018 &check->ssl_config)) {
3020 "Connection #%ld has different SSL parameters, "
3022 check->connection_id));
3025 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3027 "Connection #%ld has not started SSL connect, "
3029 check->connection_id));
3036 else { /* The requested needle connection is using a proxy,
3037 is the checked one using the same host, port and type? */
3038 if(check->bits.proxy &&
3039 (needle->proxytype == check->proxytype) &&
3040 (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
3041 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3042 needle->port == check->port) {
3043 /* This is the same proxy connection, use it! */
3049 /* If we are looking for an NTLM connection, check if this is already
3050 authenticating with the right credentials. If not, keep looking so
3051 that we can reuse NTLM connections if possible. (Especially we
3052 must not reuse the same connection if partway through
3055 if(credentialsMatch && check->ntlm.state != NTLMSTATE_NONE) {
3058 /* We must use this connection, no other */
3059 *force_reuse = TRUE;
3067 /* We can pipeline if we want to. Let's continue looking for
3068 the optimal connection to use, i.e the shortest pipe that is not
3072 /* We have the optimal connection. Let's stop looking. */
3077 /* We can't use the connection if the pipe is full */
3078 if(pipeLen >= max_pipe_len)
3081 /* We can't use the connection if the pipe is penalized */
3082 if(Curl_pipeline_penalized(data, check))
3085 if(pipeLen < best_pipe_len) {
3086 /* This connection has a shorter pipe so far. We'll pick this
3087 and continue searching */
3089 best_pipe_len = pipeLen;
3094 /* We have found a connection. Let's stop searching. */
3104 return TRUE; /* yes, we found one to use! */
3107 return FALSE; /* no matching connecting exists */
3110 /* Mark the connection as 'idle', or close it if the cache is full.
3111 Returns TRUE if the connection is kept, or FALSE if it was closed. */
3113 ConnectionDone(struct SessionHandle *data, struct connectdata *conn)
3115 /* data->multi->maxconnects can be negative, deal with it. */
3116 size_t maxconnects =
3117 (data->multi->maxconnects < 0) ? 0 : data->multi->maxconnects;
3118 struct connectdata *conn_candidate = NULL;
3120 /* Mark the current connection as 'unused' */
3121 conn->inuse = FALSE;
3123 if(maxconnects > 0 &&
3124 data->state.conn_cache->num_connections > maxconnects) {
3125 infof(data, "Connection cache is full, closing the oldest one.\n");
3127 conn_candidate = find_oldest_idle_connection(data);
3129 if(conn_candidate) {
3130 /* Set the connection's owner correctly */
3131 conn_candidate->data = data;
3133 /* the winner gets the honour of being disconnected */
3134 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
3138 return (conn_candidate == conn) ? FALSE : TRUE;
3142 * The given input connection struct pointer is to be stored in the connection
3143 * cache. If the cache is already full, least interesting existing connection
3144 * (if any) gets closed.
3146 * The given connection should be unique. That must've been checked prior to
3149 static CURLcode ConnectionStore(struct SessionHandle *data,
3150 struct connectdata *conn)
3152 static int connection_id_counter = 0;
3156 /* Assign a number to the connection for easier tracking in the log
3158 conn->connection_id = connection_id_counter++;
3160 result = Curl_conncache_add_conn(data->state.conn_cache, conn);
3161 if(result != CURLE_OK)
3162 conn->connection_id = -1;
3167 /* after a TCP connection to the proxy has been verified, this function does
3168 the next magic step.
3170 Note: this function's sub-functions call failf()
3173 CURLcode Curl_connected_proxy(struct connectdata *conn)
3175 if(!conn->bits.proxy)
3178 switch(conn->proxytype) {
3179 #ifndef CURL_DISABLE_PROXY
3180 case CURLPROXY_SOCKS5:
3181 case CURLPROXY_SOCKS5_HOSTNAME:
3182 return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3183 conn->host.name, conn->remote_port,
3186 case CURLPROXY_SOCKS4:
3187 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3188 conn->remote_port, FIRSTSOCKET, conn, FALSE);
3190 case CURLPROXY_SOCKS4A:
3191 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3192 conn->remote_port, FIRSTSOCKET, conn, TRUE);
3194 #endif /* CURL_DISABLE_PROXY */
3195 case CURLPROXY_HTTP:
3196 case CURLPROXY_HTTP_1_0:
3197 /* do nothing here. handled later. */
3201 } /* switch proxytype */
3206 static CURLcode ConnectPlease(struct SessionHandle *data,
3207 struct connectdata *conn,
3211 Curl_addrinfo *addr;
3212 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3213 char *hostname = conn->bits.proxy?conn->proxy.name:conn->host.name;
3215 infof(data, "About to connect() to %s%s port %ld (#%ld)\n",
3216 conn->bits.proxy?"proxy ":"",
3217 hostname, conn->port, conn->connection_id);
3222 /*************************************************************
3223 * Connect to server/proxy
3224 *************************************************************/
3225 result= Curl_connecthost(conn,
3227 &conn->sock[FIRSTSOCKET],
3230 if(CURLE_OK == result) {
3231 /* All is cool, we store the current information */
3232 conn->ip_addr = addr;
3235 result = Curl_connected_proxy(conn);
3237 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
3238 Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
3244 *connected = FALSE; /* mark it as not connected */
3250 * verboseconnect() displays verbose information after a connect
3252 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3253 void Curl_verboseconnect(struct connectdata *conn)
3255 if(conn->data->set.verbose)
3256 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3257 conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3258 conn->ip_addr_str, conn->port, conn->connection_id);
3262 int Curl_protocol_getsock(struct connectdata *conn,
3263 curl_socket_t *socks,
3266 if(conn->handler->proto_getsock)
3267 return conn->handler->proto_getsock(conn, socks, numsocks);
3268 return GETSOCK_BLANK;
3271 int Curl_doing_getsock(struct connectdata *conn,
3272 curl_socket_t *socks,
3275 if(conn && conn->handler->doing_getsock)
3276 return conn->handler->doing_getsock(conn, socks, numsocks);
3277 return GETSOCK_BLANK;
3281 * We are doing protocol-specific connecting and this is being called over and
3282 * over from the multi interface until the connection phase is done on
3286 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3289 CURLcode result=CURLE_OK;
3291 if(conn && conn->handler->connecting) {
3293 result = conn->handler->connecting(conn, done);
3302 * We are DOING this is being called over and over from the multi interface
3303 * until the DOING phase is done on protocol layer.
3306 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3308 CURLcode result=CURLE_OK;
3310 if(conn && conn->handler->doing) {
3312 result = conn->handler->doing(conn, done);
3321 * We have discovered that the TCP connection has been successful, we can now
3322 * proceed with some action.
3325 CURLcode Curl_protocol_connect(struct connectdata *conn,
3326 bool *protocol_done)
3328 CURLcode result=CURLE_OK;
3330 *protocol_done = FALSE;
3332 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
3333 /* We already are connected, get back. This may happen when the connect
3334 worked fine in the first call, like when we connect to a local server
3335 or proxy. Note that we don't know if the protocol is actually done.
3337 Unless this protocol doesn't have any protocol-connect callback, as
3338 then we know we're done. */
3339 if(!conn->handler->connecting)
3340 *protocol_done = TRUE;
3345 if(!conn->bits.protoconnstart) {
3347 result = Curl_proxy_connect(conn);
3351 if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
3352 (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
3353 /* when using an HTTP tunnel proxy, await complete tunnel establishment
3354 before proceeding further. Return CURLE_OK so we'll be called again */
3357 if(conn->handler->connect_it) {
3358 /* is there a protocol-specific connect() procedure? */
3360 /* Call the protocol-specific connect function */
3361 result = conn->handler->connect_it(conn, protocol_done);
3364 *protocol_done = TRUE;
3366 /* it has started, possibly even completed but that knowledge isn't stored
3369 conn->bits.protoconnstart = TRUE;
3372 return result; /* pass back status */
3376 * Helpers for IDNA convertions.
3378 static bool is_ASCII_name(const char *hostname)
3380 const unsigned char *ch = (const unsigned char*)hostname;
3391 * Check if characters in hostname is allowed in Top Level Domain.
3393 static bool tld_check_name(struct SessionHandle *data,
3394 const char *ace_hostname)
3397 char *uc_name = NULL;
3399 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3400 const char *tld_errmsg = "<no msg>";
3405 /* Convert (and downcase) ACE-name back into locale's character set */
3406 rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3407 if(rc != IDNA_SUCCESS)
3410 rc = tld_check_lz(uc_name, &err_pos, NULL);
3411 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3412 #ifdef HAVE_TLD_STRERROR
3413 if(rc != TLD_SUCCESS)
3414 tld_errmsg = tld_strerror((Tld_rc)rc);
3416 if(rc == TLD_INVALID)
3417 infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
3418 tld_errmsg, err_pos, uc_name[err_pos],
3419 uc_name[err_pos] & 255);
3420 else if(rc != TLD_SUCCESS)
3421 infof(data, "WARNING: TLD check for %s failed; %s\n",
3422 uc_name, tld_errmsg);
3423 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3426 if(rc != TLD_SUCCESS)
3434 * Perform any necessary IDN conversion of hostname
3436 static void fix_hostname(struct SessionHandle *data,
3437 struct connectdata *conn, struct hostname *host)
3442 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3446 /* set the name we use to display the host name */
3447 host->dispname = host->name;
3448 if(!is_ASCII_name(host->name)) {
3450 /*************************************************************
3451 * Check name for non-ASCII and convert hostname to ACE form.
3452 *************************************************************/
3453 if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3454 char *ace_hostname = NULL;
3455 int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3456 infof (data, "Input domain encoded as `%s'\n",
3457 stringprep_locale_charset ());
3458 if(rc != IDNA_SUCCESS)
3459 infof(data, "Failed to convert %s to ACE; %s\n",
3460 host->name, Curl_idn_strerror(conn,rc));
3462 /* tld_check_name() displays a warning if the host name contains
3463 "illegal" characters for this TLD */
3464 (void)tld_check_name(data, ace_hostname);
3466 host->encalloc = ace_hostname;
3467 /* change the name pointer to point to the encoded hostname */
3468 host->name = host->encalloc;
3471 #elif defined(USE_WIN32_IDN)
3472 /*************************************************************
3473 * Check name for non-ASCII and convert hostname to ACE form.
3474 *************************************************************/
3475 char *ace_hostname = NULL;
3476 int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname);
3478 infof(data, "Failed to convert %s to ACE;\n",
3481 host->encalloc = ace_hostname;
3482 /* change the name pointer to point to the encoded hostname */
3483 host->name = host->encalloc;
3486 infof(data, "IDN support not present, can't parse Unicode domains\n");
3491 static void llist_dtor(void *user, void *element)
3499 * Allocate and initialize a new connectdata object.
3501 static struct connectdata *allocate_conn(struct SessionHandle *data)
3503 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3507 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
3508 already from start to avoid NULL
3509 situations and checks */
3511 /* and we setup a few fields in case we end up actually using this struct */
3513 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3514 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3515 conn->connection_id = -1; /* no ID */
3516 conn->port = -1; /* unknown at this point */
3518 /* Default protocol-independent behavior doesn't support persistent
3519 connections, so we set this to force-close. Protocols that support
3520 this need to set this to FALSE in their "curl_do" functions. */
3521 conn->bits.close = TRUE;
3523 /* Store creation time to help future close decision making */
3524 conn->created = Curl_tvnow();
3526 conn->data = data; /* Setup the association between this connection
3527 and the SessionHandle */
3529 conn->proxytype = data->set.proxytype; /* type */
3531 #ifdef CURL_DISABLE_PROXY
3533 conn->bits.proxy = FALSE;
3534 conn->bits.httpproxy = FALSE;
3535 conn->bits.proxy_user_passwd = FALSE;
3536 conn->bits.tunnel_proxy = FALSE;
3538 #else /* CURL_DISABLE_PROXY */
3540 /* note that these two proxy bits are now just on what looks to be
3541 requested, they may be altered down the road */
3542 conn->bits.proxy = (data->set.str[STRING_PROXY] &&
3543 *data->set.str[STRING_PROXY])?TRUE:FALSE;
3544 conn->bits.httpproxy = (conn->bits.proxy &&
3545 (conn->proxytype == CURLPROXY_HTTP ||
3546 conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE;
3547 conn->bits.proxy_user_passwd =
3548 (NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE;
3549 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3551 #endif /* CURL_DISABLE_PROXY */
3553 conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE;
3554 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3555 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3557 conn->verifypeer = data->set.ssl.verifypeer;
3558 conn->verifyhost = data->set.ssl.verifyhost;
3560 conn->ip_version = data->set.ipver;
3562 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
3563 conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
3564 conn->ntlm_auth_hlpr_pid = 0;
3565 conn->challenge_header = NULL;
3566 conn->response_header = NULL;
3569 if(Curl_multi_pipeline_enabled(data->multi) &&
3570 !conn->master_buffer) {
3571 /* Allocate master_buffer to be used for pipelining */
3572 conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3573 if(!conn->master_buffer)
3577 /* Initialize the pipeline lists */
3578 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3579 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3580 if(!conn->send_pipe || !conn->recv_pipe)
3583 #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI)
3584 conn->data_prot = PROT_CLEAR;
3587 /* Store the local bind parameters that will be used for this connection */
3588 if(data->set.str[STRING_DEVICE]) {
3589 conn->localdev = strdup(data->set.str[STRING_DEVICE]);
3593 conn->localportrange = data->set.localportrange;
3594 conn->localport = data->set.localport;
3596 /* the close socket stuff needs to be copied to the connection struct as
3597 it may live on without (this specific) SessionHandle */
3598 conn->fclosesocket = data->set.fclosesocket;
3599 conn->closesocket_client = data->set.closesocket_client;
3604 Curl_llist_destroy(conn->send_pipe, NULL);
3605 Curl_llist_destroy(conn->recv_pipe, NULL);
3607 conn->send_pipe = NULL;
3608 conn->recv_pipe = NULL;
3610 Curl_safefree(conn->master_buffer);
3611 Curl_safefree(conn->localdev);
3612 Curl_safefree(conn);
3616 static CURLcode findprotocol(struct SessionHandle *data,
3617 struct connectdata *conn,
3618 const char *protostr)
3620 const struct Curl_handler * const *pp;
3621 const struct Curl_handler *p;
3623 /* Scan protocol handler table and match against 'protostr' to set a few
3624 variables based on the URL. Now that the handler may be changed later
3625 when the protocol specific setup function is called. */
3626 for(pp = protocols; (p = *pp) != NULL; pp++) {
3627 if(Curl_raw_equal(p->scheme, protostr)) {
3628 /* Protocol found in table. Check if allowed */
3629 if(!(data->set.allowed_protocols & p->protocol))
3633 /* it is allowed for "normal" request, now do an extra check if this is
3634 the result of a redirect */
3635 if(data->state.this_is_a_follow &&
3636 !(data->set.redir_protocols & p->protocol))
3640 /* Perform setup complement if some. */
3641 conn->handler = conn->given = p;
3643 /* 'port' and 'remote_port' are set in setup_connection_internals() */
3649 /* The protocol was not found in the table, but we don't have to assign it
3650 to anything since it is already assigned to a dummy-struct in the
3651 create_conn() function when the connectdata struct is allocated. */
3652 failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
3655 return CURLE_UNSUPPORTED_PROTOCOL;
3659 * Parse URL and fill in the relevant members of the connection struct.
3661 static CURLcode parseurlandfillconn(struct SessionHandle *data,
3662 struct connectdata *conn,
3664 char *user, char *passwd, char *options)
3668 char *path = data->state.path;
3674 bool fix_slash = FALSE;
3676 *prot_missing = FALSE;
3678 /*************************************************************
3681 * We need to parse the url even when using the proxy, because we will need
3682 * the hostname and port in case we are trying to SSL connect through the
3683 * proxy -- and we don't know if we will need to use SSL until we parse the
3685 ************************************************************/
3686 if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
3688 Curl_raw_equal(protobuf, "file")) {
3689 if(path[0] == '/' && path[1] == '/') {
3690 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
3691 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
3692 * file://localhost/<path> is similar to how other schemes treat missing
3693 * hostnames. See RFC 1808. */
3695 /* This cannot be done with strcpy() in a portable manner, since the
3696 memory areas overlap! */
3697 memmove(path, path + 2, strlen(path + 2)+1);
3700 * we deal with file://<host>/<path> differently since it supports no
3701 * hostname other than "localhost" and "127.0.0.1", which is unique among
3702 * the URL protocols specified in RFC 1738
3704 if(path[0] != '/') {
3705 /* the URL included a host name, we ignore host names in file:// URLs
3706 as the standards don't define what to do with them */
3707 char *ptr=strchr(path, '/');
3709 /* there was a slash present
3711 RFC1738 (section 3.1, page 5) says:
3713 The rest of the locator consists of data specific to the scheme,
3714 and is known as the "url-path". It supplies the details of how the
3715 specified resource can be accessed. Note that the "/" between the
3716 host (or port) and the url-path is NOT part of the url-path.
3718 As most agents use file://localhost/foo to get '/foo' although the
3719 slash preceding foo is a separator and not a slash for the path,
3720 a URL as file://localhost//foo must be valid as well, to refer to
3721 the same file with an absolute path.
3724 if(ptr[1] && ('/' == ptr[1]))
3725 /* if there was two slashes, we skip the first one as that is then
3726 used truly as a separator */
3729 /* This cannot be made with strcpy, as the memory chunks overlap! */
3730 memmove(path, ptr, strlen(ptr)+1);
3734 protop = "file"; /* protocol string */
3740 if(2 > sscanf(data->change.url,
3741 "%15[^\n:]://%[^\n/?]%[^\n]",
3743 conn->host.name, path)) {
3746 * The URL was badly formatted, let's try the browser-style _without_
3747 * protocol specified like 'http://'.
3749 rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
3752 * We couldn't even get this format.
3753 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
3754 * assigned, but the return value is EOF!
3756 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
3757 if(!(rc == -1 && *conn->host.name))
3760 failf(data, "<url> malformed");
3761 return CURLE_URL_MALFORMAT;
3766 * Since there was no protocol part specified, we guess what protocol it
3767 * is based on the first letters of the server name.
3770 /* Note: if you add a new protocol, please update the list in
3771 * lib/version.c too! */
3773 if(checkprefix("FTP.", conn->host.name))
3775 else if(checkprefix("DICT.", conn->host.name))
3777 else if(checkprefix("LDAP.", conn->host.name))
3779 else if(checkprefix("IMAP.", conn->host.name))
3781 else if(checkprefix("SMTP.", conn->host.name))
3783 else if(checkprefix("POP3.", conn->host.name))
3789 *prot_missing = TRUE; /* not given in URL */
3795 /* We search for '?' in the host name (but only on the right side of a
3796 * @-letter to allow ?-letters in username and password) to handle things
3797 * like http://example.com?param= (notice the missing '/').
3799 at = strchr(conn->host.name, '@');
3801 query = strchr(at+1, '?');
3803 query = strchr(conn->host.name, '?');
3806 /* We must insert a slash before the '?'-letter in the URL. If the URL had
3807 a slash after the '?', that is where the path currently begins and the
3808 '?string' is still part of the host name.
3810 We must move the trailing part from the host name and put it first in
3811 the path. And have it all prefixed with a slash.
3814 size_t hostlen = strlen(query);
3815 size_t pathlen = strlen(path);
3817 /* move the existing path plus the zero byte forward, to make room for
3818 the host-name part */
3819 memmove(path+hostlen+1, path, pathlen+1);
3821 /* now copy the trailing host part in front of the existing path */
3822 memcpy(path+1, query, hostlen);
3824 path[0]='/'; /* prepend the missing slash */
3827 *query=0; /* now cut off the hostname at the ? */
3830 /* if there's no path set, use a single slash */
3835 /* If the URL is malformatted (missing a '/' after hostname before path) we
3836 * insert a slash here. The only letter except '/' we accept to start a path
3839 if(path[0] == '?') {
3840 /* We need this function to deal with overlapping memory areas. We know
3841 that the memory area 'path' points to is 'urllen' bytes big and that
3842 is bigger than the path. Use +1 to move the zero byte too. */
3843 memmove(&path[1], path, strlen(path)+1);
3850 * "fix_slash" means that the URL was malformatted so we need to generate an
3851 * updated version with the new slash inserted at the right place! We need
3852 * the corrected URL when communicating over HTTP proxy and we don't know at
3853 * this point if we're using a proxy or not.
3858 size_t plen = strlen(path); /* new path, should be 1 byte longer than
3860 size_t urllen = strlen(data->change.url); /* original URL length */
3862 reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */
3864 return CURLE_OUT_OF_MEMORY;
3866 /* copy the prefix */
3867 memcpy(reurl, data->change.url, urllen - (plen-1));
3869 /* append the trailing piece + zerobyte */
3870 memcpy(&reurl[urllen - (plen-1)], path, plen + 1);
3872 /* possible free the old one */
3873 if(data->change.url_alloc) {
3874 Curl_safefree(data->change.url);
3875 data->change.url_alloc = FALSE;
3878 data->change.url = reurl;
3879 data->change.url_alloc = TRUE; /* free this later */
3883 * Parse the login details from the URL and strip them out of
3886 result = parse_url_login(data, conn, user, passwd, options);
3887 if(result != CURLE_OK)
3890 if(conn->host.name[0] == '[') {
3891 /* This looks like an IPv6 address literal. See if there is an address
3893 char *percent = strstr (conn->host.name, "%25");
3896 unsigned long scope = strtoul (percent + 3, &endp, 10);
3898 /* The address scope was well formed. Knock it out of the
3900 memmove(percent, endp, strlen(endp)+1);
3901 if(!data->state.this_is_a_follow)
3902 /* Don't honour a scope given in a Location: header */
3903 conn->scope = (unsigned int)scope;
3906 infof(data, "Invalid IPv6 address format\n");
3911 /* Override any scope that was set above. */
3912 conn->scope = data->set.scope;
3914 /* Remove the fragment part of the path. Per RFC 2396, this is always the
3915 last part of the URI. We are looking for the first '#' so that we deal
3916 gracefully with non conformant URI such as http://example.com#foo#bar. */
3917 fragment = strchr(path, '#');
3921 /* we know the path part ended with a fragment, so we know the full URL
3922 string does too and we need to cut it off from there so it isn't used
3924 fragment = strchr(data->change.url, '#');
3930 * So if the URL was A://B/C#D,
3932 * conn->host.name is B
3933 * data->state.path is /C
3936 return findprotocol(data, conn, protop);
3940 * If we're doing a resumed transfer, we need to setup our stuff
3943 static CURLcode setup_range(struct SessionHandle *data)
3945 struct UrlState *s = &data->state;
3946 s->resume_from = data->set.set_resume_from;
3947 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
3948 if(s->rangestringalloc)
3952 s->range = aprintf("%" FORMAT_OFF_TU "-", s->resume_from);
3954 s->range = strdup(data->set.str[STRING_SET_RANGE]);
3956 s->rangestringalloc = (s->range)?TRUE:FALSE;
3959 return CURLE_OUT_OF_MEMORY;
3961 /* tell ourselves to fetch this range */
3962 s->use_range = TRUE; /* enable range download */
3965 s->use_range = FALSE; /* disable range download */
3971 /***************************************************************
3972 * Setup connection internals specific to the requested protocol.
3973 * This MUST get called after proxy magic has been figured out.
3974 ***************************************************************/
3975 static CURLcode setup_connection_internals(struct connectdata *conn)
3977 const struct Curl_handler * p;
3980 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
3982 /* Scan protocol handler table. */
3984 /* Perform setup complement if some. */
3987 if(p->setup_connection) {
3988 result = (*p->setup_connection)(conn);
3990 if(result != CURLE_OK)
3993 p = conn->handler; /* May have changed. */
3997 /* we check for -1 here since if proxy was detected already, this
3998 was very likely already set to the proxy port */
3999 conn->port = p->defport;
4000 conn->remote_port = (unsigned short)conn->given->defport;
4005 #ifndef CURL_DISABLE_PROXY
4006 /****************************************************************
4007 * Checks if the host is in the noproxy list. returns true if it matches
4008 * and therefore the proxy should NOT be used.
4009 ****************************************************************/
4010 static bool check_noproxy(const char* name, const char* no_proxy)
4012 /* no_proxy=domain1.dom,host.domain2.dom
4013 * (a comma-separated list of hosts which should
4014 * not be proxied, or an asterisk to override
4015 * all proxy variables)
4019 const char* separator = ", ";
4020 size_t no_proxy_len;
4024 if(no_proxy && no_proxy[0]) {
4025 if(Curl_raw_equal("*", no_proxy)) {
4029 /* NO_PROXY was specified and it wasn't just an asterisk */
4031 no_proxy_len = strlen(no_proxy);
4032 endptr = strchr(name, ':');
4034 namelen = endptr - name;
4036 namelen = strlen(name);
4038 for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
4039 while(tok_start < no_proxy_len &&
4040 strchr(separator, no_proxy[tok_start]) != NULL) {
4041 /* Look for the beginning of the token. */
4045 if(tok_start == no_proxy_len)
4046 break; /* It was all trailing separator chars, no more tokens. */
4048 for(tok_end = tok_start; tok_end < no_proxy_len &&
4049 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
4050 /* Look for the end of the token. */
4053 /* To match previous behaviour, where it was necessary to specify
4054 * ".local.com" to prevent matching "notlocal.com", we will leave
4057 if(no_proxy[tok_start] == '.')
4060 if((tok_end - tok_start) <= namelen) {
4061 /* Match the last part of the name to the domain we are checking. */
4062 const char *checkn = name + namelen - (tok_end - tok_start);
4063 if(Curl_raw_nequal(no_proxy + tok_start, checkn,
4064 tok_end - tok_start)) {
4065 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
4066 /* We either have an exact match, or the previous character is a .
4067 * so it is within the same domain, so no proxy for this host.
4072 } /* if((tok_end - tok_start) <= namelen) */
4073 } /* for(tok_start = 0; tok_start < no_proxy_len;
4074 tok_start = tok_end + 1) */
4075 } /* NO_PROXY was specified and it wasn't just an asterisk */
4080 /****************************************************************
4081 * Detect what (if any) proxy to use. Remember that this selects a host
4082 * name and is not limited to HTTP proxies only.
4083 * The returned pointer must be freed by the caller (unless NULL)
4084 ****************************************************************/
4085 static char *detect_proxy(struct connectdata *conn)
4089 #ifndef CURL_DISABLE_HTTP
4090 /* If proxy was not specified, we check for default proxy environment
4091 * variables, to enable i.e Lynx compliance:
4093 * http_proxy=http://some.server.dom:port/
4094 * https_proxy=http://some.server.dom:port/
4095 * ftp_proxy=http://some.server.dom:port/
4096 * no_proxy=domain1.dom,host.domain2.dom
4097 * (a comma-separated list of hosts which should
4098 * not be proxied, or an asterisk to override
4099 * all proxy variables)
4100 * all_proxy=http://some.server.dom:port/
4101 * (seems to exist for the CERN www lib. Probably
4102 * the first to check for.)
4104 * For compatibility, the all-uppercase versions of these variables are
4105 * checked if the lowercase versions don't exist.
4107 char *no_proxy=NULL;
4108 char proxy_env[128];
4110 no_proxy=curl_getenv("no_proxy");
4112 no_proxy=curl_getenv("NO_PROXY");
4114 if(!check_noproxy(conn->host.name, no_proxy)) {
4115 /* It was not listed as without proxy */
4116 const char *protop = conn->handler->scheme;
4117 char *envp = proxy_env;
4120 /* Now, build <protocol>_proxy and check for such a one to use */
4122 *envp++ = (char)tolower((int)*protop++);
4125 strcpy(envp, "_proxy");
4127 /* read the protocol proxy: */
4128 prox=curl_getenv(proxy_env);
4131 * We don't try the uppercase version of HTTP_PROXY because of
4134 * When curl is used in a webserver application
4135 * environment (cgi or php), this environment variable can
4136 * be controlled by the web server user by setting the
4137 * http header 'Proxy:' to some value.
4139 * This can cause 'internal' http/ftp requests to be
4140 * arbitrarily redirected by any external attacker.
4142 if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4143 /* There was no lowercase variable, try the uppercase version: */
4144 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4145 prox=curl_getenv(proxy_env);
4148 if(prox && *prox) { /* don't count "" strings */
4149 proxy = prox; /* use this */
4152 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4154 proxy=curl_getenv("ALL_PROXY");
4156 } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4161 #else /* !CURL_DISABLE_HTTP */
4164 #endif /* CURL_DISABLE_HTTP */
4170 * If this is supposed to use a proxy, we need to figure out the proxy
4171 * host name, so that we can re-use an existing connection
4172 * that may exist registered to the same proxy host.
4173 * proxy will be freed before this function returns.
4175 static CURLcode parse_proxy(struct SessionHandle *data,
4176 struct connectdata *conn, char *proxy)
4181 /* We use 'proxyptr' to point to the proxy name from now on... */
4186 /* We do the proxy host string parsing here. We want the host name and the
4187 * port name. Accept a protocol:// prefix
4190 /* Parse the protocol part if present */
4191 endofprot = strstr(proxy, "://");
4193 proxyptr = endofprot+3;
4194 if(checkprefix("socks5h", proxy))
4195 conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
4196 else if(checkprefix("socks5", proxy))
4197 conn->proxytype = CURLPROXY_SOCKS5;
4198 else if(checkprefix("socks4a", proxy))
4199 conn->proxytype = CURLPROXY_SOCKS4A;
4200 else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
4201 conn->proxytype = CURLPROXY_SOCKS4;
4202 /* Any other xxx:// : change to http proxy */
4205 proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
4207 /* Is there a username and password given in this proxy url? */
4208 atsign = strchr(proxyptr, '@');
4210 CURLcode res = CURLE_OK;
4211 char *proxyuser = NULL;
4212 char *proxypasswd = NULL;
4214 res = parse_login_details(proxyptr, atsign - proxyptr,
4215 &proxyuser, &proxypasswd, NULL);
4217 /* found user and password, rip them out. note that we are
4218 unescaping them, as there is otherwise no way to have a
4219 username or password with reserved characters like ':' in
4221 Curl_safefree(conn->proxyuser);
4222 if(proxyuser && strlen(proxyuser) < MAX_CURL_USER_LENGTH)
4223 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4225 conn->proxyuser = strdup("");
4227 if(!conn->proxyuser)
4228 res = CURLE_OUT_OF_MEMORY;
4230 Curl_safefree(conn->proxypasswd);
4231 if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
4232 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4234 conn->proxypasswd = strdup("");
4236 if(!conn->proxypasswd)
4237 res = CURLE_OUT_OF_MEMORY;
4241 conn->bits.proxy_user_passwd = TRUE; /* enable it */
4242 atsign++; /* the right side of the @-letter */
4245 proxyptr = atsign; /* now use this instead */
4247 res = CURLE_OUT_OF_MEMORY;
4251 Curl_safefree(proxyuser);
4252 Curl_safefree(proxypasswd);
4258 /* start scanning for port number at this point */
4261 /* detect and extract RFC2732-style IPv6-addresses */
4262 if(*proxyptr == '[') {
4263 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4264 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
4268 /* yeps, it ended nicely with a bracket as well */
4271 infof(data, "Invalid IPv6 address format\n");
4273 /* Note that if this didn't end with a bracket, we still advanced the
4274 * proxyptr first, but I can't see anything wrong with that as no host
4275 * name nor a numeric can legally start with a bracket.
4279 /* Get port number off proxy.server.com:1080 */
4280 prox_portno = strchr(portptr, ':');
4282 *prox_portno = 0x0; /* cut off number from host name */
4284 /* now set the local port number */
4285 conn->port = strtol(prox_portno, NULL, 10);
4288 if(proxyptr[0]=='/')
4289 /* If the first character in the proxy string is a slash, fail
4290 immediately. The following code will otherwise clear the string which
4291 will lead to code running as if no proxy was set! */
4292 return CURLE_COULDNT_RESOLVE_PROXY;
4294 /* without a port number after the host name, some people seem to use
4295 a slash so we strip everything from the first slash */
4296 atsign = strchr(proxyptr, '/');
4298 *atsign = 0x0; /* cut off path part from host name */
4300 if(data->set.proxyport)
4301 /* None given in the proxy string, then get the default one if it is
4303 conn->port = data->set.proxyport;
4306 /* now, clone the cleaned proxy host name */
4307 conn->proxy.rawalloc = strdup(proxyptr);
4308 conn->proxy.name = conn->proxy.rawalloc;
4310 if(!conn->proxy.rawalloc)
4311 return CURLE_OUT_OF_MEMORY;
4317 * Extract the user and password from the authentication string
4319 static CURLcode parse_proxy_auth(struct SessionHandle *data,
4320 struct connectdata *conn)
4322 char proxyuser[MAX_CURL_USER_LENGTH]="";
4323 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4325 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4326 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4327 MAX_CURL_USER_LENGTH);
4328 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4330 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4331 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4332 MAX_CURL_PASSWORD_LENGTH);
4333 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4336 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4337 if(!conn->proxyuser)
4338 return CURLE_OUT_OF_MEMORY;
4340 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4341 if(!conn->proxypasswd)
4342 return CURLE_OUT_OF_MEMORY;
4346 #endif /* CURL_DISABLE_PROXY */
4351 * Parse the login details (user name, password and options) from the URL and
4352 * strip them out of the host name
4354 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4357 * Outputs: (almost :- all currently undefined)
4358 * conn->bits.user_passwd - non-zero if non-default passwords exist
4359 * user - non-zero length if defined
4360 * passwd - non-zero length if defined
4361 * options - non-zero length if defined
4362 * conn->host.name - remove user name and password
4364 static CURLcode parse_url_login(struct SessionHandle *data,
4365 struct connectdata *conn,
4366 char *user, char *passwd, char *options)
4368 CURLcode result = CURLE_OK;
4370 char *passwdp = NULL;
4371 char *optionsp = NULL;
4373 /* At this point, we're hoping all the other special cases have
4374 * been taken care of, so conn->host.name is at most
4375 * [user[:password][;options]]@]hostname
4377 * We need somewhere to put the embedded details, so do that first.
4380 char *ptr = strchr(conn->host.name, '@');
4381 char *login = conn->host.name;
4383 user[0] = 0; /* to make everything well-defined */
4387 /* We will now try to extract the
4388 * possible login information in a string like:
4389 * ftp://user:password@ftp.my.site:8021/README */
4391 /* There's login information to the left of the @ */
4393 conn->host.name = ++ptr;
4395 /* So the hostname is sane. Only bother interpreting the
4396 * results if we could care. It could still be wasted
4397 * work because it might be overtaken by the programmatically
4398 * set user/passwd, but doing that first adds more cases here :-(
4401 if(data->set.use_netrc != CURL_NETRC_REQUIRED) {
4402 /* We could use the login information in the URL so extract it */
4403 result = parse_login_details(login, ptr - login - 1,
4404 &userp, &passwdp, &optionsp);
4409 /* We have a user in the URL */
4410 conn->bits.userpwd_in_url = TRUE;
4411 conn->bits.user_passwd = TRUE; /* enable user+password */
4413 /* Decode the user */
4414 newname = curl_easy_unescape(data, userp, 0, NULL);
4416 return CURLE_OUT_OF_MEMORY;
4418 if(strlen(newname) < MAX_CURL_USER_LENGTH)
4419 strcpy(user, newname);
4425 /* We have a password in the URL so decode it */
4426 char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
4428 return CURLE_OUT_OF_MEMORY;
4430 if(strlen(newpasswd) < MAX_CURL_PASSWORD_LENGTH)
4431 strcpy(passwd, newpasswd);
4437 /* We have an options list in the URL so decode it */
4438 char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
4440 return CURLE_OUT_OF_MEMORY;
4442 if(strlen(newoptions) < MAX_CURL_OPTIONS_LENGTH)
4443 strcpy(options, newoptions);
4449 Curl_safefree(userp);
4450 Curl_safefree(passwdp);
4451 Curl_safefree(optionsp);
4459 * parse_login_details()
4461 * This is used to parse a login string for user name, password and options in
4462 * the following formats:
4466 * user:password;options
4468 * user;options:password
4476 * login [in] - The login string.
4477 * len [in] - The length of the login string.
4478 * userp [in/out] - The address where a pointer to newly allocated memory
4479 * holding the user will be stored upon completion.
4480 * passdwp [in/out] - The address where a pointer to newly allocated memory
4481 * holding the password will be stored upon completion.
4482 * optionsp [in/out] - The address where a pointer to newly allocated memory
4483 * holding the options will be stored upon completion.
4485 * Returns CURLE_OK on success.
4487 static CURLcode parse_login_details(const char *login, const size_t len,
4488 char **userp, char **passwdp,
4491 CURLcode result = CURLE_OK;
4495 const char *psep = NULL;
4496 const char *osep = NULL;
4501 /* Attempt to find the password separator */
4503 psep = strchr(login, ':');
4505 /* Within the constraint of the login string */
4506 if(psep >= login + len)
4510 /* Attempt to find the options separator */
4512 osep = strchr(login, ';');
4514 /* Within the constraint of the login string */
4515 if(osep >= login + len)
4519 /* Calculate the portion lengths */
4521 (size_t)(osep && psep > osep ? osep - login : psep - login) :
4522 (osep ? (size_t)(osep - login) : len));
4524 (osep && osep > psep ? (size_t)(osep - psep) :
4525 (size_t)(login + len - psep)) - 1 : 0);
4527 (psep && psep > osep ? (size_t)(psep - osep) :
4528 (size_t)(login + len - osep)) - 1 : 0);
4530 /* Allocate the user portion buffer */
4532 ubuf = malloc(ulen + 1);
4534 result = CURLE_OUT_OF_MEMORY;
4537 /* Allocate the password portion buffer */
4538 if(!result && passwdp && plen) {
4539 pbuf = malloc(plen + 1);
4541 result = CURLE_OUT_OF_MEMORY;
4544 /* Allocate the options portion buffer */
4545 if(!result && optionsp && olen) {
4546 obuf = malloc(olen + 1);
4548 result = CURLE_OUT_OF_MEMORY;
4552 /* Store the user portion if necessary */
4554 memcpy(ubuf, login, ulen);
4556 Curl_safefree(*userp);
4560 /* Store the password portion if necessary */
4562 memcpy(pbuf, psep + 1, plen);
4564 Curl_safefree(*passwdp);
4568 /* Store the options portion if necessary */
4570 memcpy(obuf, osep + 1, olen);
4572 Curl_safefree(*optionsp);
4580 /*************************************************************
4581 * Figure out the remote port number and fix it in the URL
4583 * No matter if we use a proxy or not, we have to figure out the remote
4584 * port number of various reasons.
4586 * To be able to detect port number flawlessly, we must not confuse them
4587 * IPv6-specified addresses in the [0::1] style. (RFC2732)
4589 * The conn->host.name is currently [user:passwd@]host[:port] where host
4590 * could be a hostname, IPv4 address or IPv6 address.
4592 * The port number embedded in the URL is replaced, if necessary.
4593 *************************************************************/
4594 static CURLcode parse_remote_port(struct SessionHandle *data,
4595 struct connectdata *conn)
4600 /* Note that at this point, the IPv6 address cannot contain any scope
4601 suffix as that has already been removed in the parseurlandfillconn()
4603 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
4605 (']' == endbracket)) {
4606 /* this is a RFC2732-style specified IP-address */
4607 conn->bits.ipv6_ip = TRUE;
4609 conn->host.name++; /* skip over the starting bracket */
4610 portptr = strchr(conn->host.name, ']');
4612 *portptr++ = '\0'; /* zero terminate, killing the bracket */
4614 portptr = NULL; /* no port number available */
4619 struct in6_addr in6;
4620 if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
4621 /* This is a numerical IPv6 address, meaning this is a wrongly formatted
4623 failf(data, "IPv6 numerical address used in URL without brackets");
4624 return CURLE_URL_MALFORMAT;
4628 portptr = strrchr(conn->host.name, ':');
4631 if(data->set.use_port && data->state.allow_port) {
4632 /* if set, we use this and ignore the port possibly given in the URL */
4633 conn->remote_port = (unsigned short)data->set.use_port;
4635 *portptr = '\0'; /* cut off the name there anyway - if there was a port
4636 number - since the port number is to be ignored! */
4637 if(conn->bits.httpproxy) {
4638 /* we need to create new URL with the new port number */
4642 if(conn->bits.type_set)
4643 snprintf(type, sizeof(type), ";type=%c",
4644 data->set.prefer_ascii?'A':
4645 (data->set.ftp_list_only?'D':'I'));
4648 * This synthesized URL isn't always right--suffixes like ;type=A are
4649 * stripped off. It would be better to work directly from the original
4650 * URL and simply replace the port part of it.
4652 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
4653 conn->bits.ipv6_ip?"[":"", conn->host.name,
4654 conn->bits.ipv6_ip?"]":"", conn->remote_port,
4655 data->state.slash_removed?"/":"", data->state.path,
4658 return CURLE_OUT_OF_MEMORY;
4660 if(data->change.url_alloc) {
4661 Curl_safefree(data->change.url);
4662 data->change.url_alloc = FALSE;
4665 data->change.url = url;
4666 data->change.url_alloc = TRUE;
4670 /* no CURLOPT_PORT given, extract the one from the URL */
4675 port=strtoul(portptr+1, &rest, 10); /* Port number must be decimal */
4677 if(rest != (portptr+1) && *rest == '\0') {
4678 /* The colon really did have only digits after it,
4679 * so it is either a port number or a mistake */
4681 if(port > 0xffff) { /* Single unix standard says port numbers are
4683 failf(data, "Port number too large: %lu", port);
4684 return CURLE_URL_MALFORMAT;
4687 *portptr = '\0'; /* cut off the name there */
4688 conn->remote_port = curlx_ultous(port);
4691 /* Browser behavior adaptation. If there's a colon with no digits after,
4692 just cut off the name there which makes us ignore the colon and just
4693 use the default port. Firefox and Chrome both do that. */
4700 * Override the login details from the URL with that in the CURLOPT_USERPWD
4701 * option or a .netrc file, if applicable.
4703 static void override_login(struct SessionHandle *data,
4704 struct connectdata *conn,
4705 char *user, char *passwd, char *options)
4707 if(data->set.str[STRING_USERNAME]) {
4708 strncpy(user, data->set.str[STRING_USERNAME], MAX_CURL_USER_LENGTH);
4709 user[MAX_CURL_USER_LENGTH - 1] = '\0'; /* To be on safe side */
4712 if(data->set.str[STRING_PASSWORD]) {
4713 strncpy(passwd, data->set.str[STRING_PASSWORD], MAX_CURL_PASSWORD_LENGTH);
4714 passwd[MAX_CURL_PASSWORD_LENGTH - 1] = '\0'; /* To be on safe side */
4717 if(data->set.str[STRING_OPTIONS]) {
4718 strncpy(options, data->set.str[STRING_OPTIONS], MAX_CURL_OPTIONS_LENGTH);
4719 options[MAX_CURL_OPTIONS_LENGTH - 1] = '\0'; /* To be on safe side */
4722 conn->bits.netrc = FALSE;
4723 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
4724 if(Curl_parsenetrc(conn->host.name,
4726 data->set.str[STRING_NETRC_FILE])) {
4727 infof(data, "Couldn't find host %s in the "
4728 DOT_CHAR "netrc file; using defaults\n",
4732 /* set bits.netrc TRUE to remember that we got the name from a .netrc
4733 file, so that it is safe to use even if we followed a Location: to a
4734 different host or similar. */
4735 conn->bits.netrc = TRUE;
4737 conn->bits.user_passwd = TRUE; /* enable user+password */
4743 * Set password so it's available in the connection.
4745 static CURLcode set_login(struct connectdata *conn,
4746 const char *user, const char *passwd,
4747 const char *options)
4749 CURLcode result = CURLE_OK;
4751 /* If our protocol needs a password and we have none, use the defaults */
4752 if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
4753 /* Store the default user */
4754 conn->user = strdup(CURL_DEFAULT_USER);
4756 /* Store the default password */
4758 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
4760 conn->passwd = NULL;
4762 /* This is the default password, so DON'T set conn->bits.user_passwd */
4765 /* Store the user, zero-length if not set */
4766 conn->user = strdup(user);
4768 /* Store the password (only if user is present), zero-length if not set */
4770 conn->passwd = strdup(passwd);
4772 conn->passwd = NULL;
4775 if(!conn->user || !conn->passwd)
4776 result = CURLE_OUT_OF_MEMORY;
4778 /* Store the options, null if not set */
4779 if(!result && options[0]) {
4780 conn->options = strdup(options);
4783 result = CURLE_OUT_OF_MEMORY;
4789 /*************************************************************
4790 * Resolve the address of the server or proxy
4791 *************************************************************/
4792 static CURLcode resolve_server(struct SessionHandle *data,
4793 struct connectdata *conn,
4796 CURLcode result=CURLE_OK;
4797 long timeout_ms = Curl_timeleft(data, NULL, TRUE);
4799 /*************************************************************
4800 * Resolve the name of the server or proxy
4801 *************************************************************/
4802 if(conn->bits.reuse)
4803 /* We're reusing the connection - no need to resolve anything, and
4804 fix_hostname() was called already in create_conn() for the re-use
4809 /* this is a fresh connect */
4811 struct Curl_dns_entry *hostaddr;
4813 /* set a pointer to the hostname we display */
4814 fix_hostname(data, conn, &conn->host);
4816 if(!conn->proxy.name || !*conn->proxy.name) {
4817 /* If not connecting via a proxy, extract the port from the URL, if it is
4818 * there, thus overriding any defaults that might have been set above. */
4819 conn->port = conn->remote_port; /* it is the same port */
4821 /* Resolve target host right on */
4822 rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
4823 &hostaddr, timeout_ms);
4824 if(rc == CURLRESOLV_PENDING)
4827 else if(rc == CURLRESOLV_TIMEDOUT)
4828 result = CURLE_OPERATION_TIMEDOUT;
4830 else if(!hostaddr) {
4831 failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
4832 result = CURLE_COULDNT_RESOLVE_HOST;
4833 /* don't return yet, we need to clean up the timeout first */
4837 /* This is a proxy that hasn't been resolved yet. */
4839 /* IDN-fix the proxy name */
4840 fix_hostname(data, conn, &conn->proxy);
4843 rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
4844 &hostaddr, timeout_ms);
4846 if(rc == CURLRESOLV_PENDING)
4849 else if(rc == CURLRESOLV_TIMEDOUT)
4850 result = CURLE_OPERATION_TIMEDOUT;
4852 else if(!hostaddr) {
4853 failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
4854 result = CURLE_COULDNT_RESOLVE_PROXY;
4855 /* don't return yet, we need to clean up the timeout first */
4858 DEBUGASSERT(conn->dns_entry == NULL);
4859 conn->dns_entry = hostaddr;
4866 * Cleanup the connection just allocated before we can move along and use the
4867 * previously existing one. All relevant data is copied over and old_conn is
4868 * ready for freeing once this function returns.
4870 static void reuse_conn(struct connectdata *old_conn,
4871 struct connectdata *conn)
4873 if(old_conn->proxy.rawalloc)
4874 free(old_conn->proxy.rawalloc);
4876 /* free the SSL config struct from this connection struct as this was
4877 allocated in vain and is targeted for destruction */
4878 Curl_free_ssl_config(&old_conn->ssl_config);
4880 conn->data = old_conn->data;
4882 /* get the user+password information from the old_conn struct since it may
4883 * be new for this request even when we re-use an existing connection */
4884 conn->bits.user_passwd = old_conn->bits.user_passwd;
4885 if(conn->bits.user_passwd) {
4886 /* use the new user name and password though */
4887 Curl_safefree(conn->user);
4888 Curl_safefree(conn->passwd);
4889 conn->user = old_conn->user;
4890 conn->passwd = old_conn->passwd;
4891 old_conn->user = NULL;
4892 old_conn->passwd = NULL;
4895 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
4896 if(conn->bits.proxy_user_passwd) {
4897 /* use the new proxy user name and proxy password though */
4898 Curl_safefree(conn->proxyuser);
4899 Curl_safefree(conn->proxypasswd);
4900 conn->proxyuser = old_conn->proxyuser;
4901 conn->proxypasswd = old_conn->proxypasswd;
4902 old_conn->proxyuser = NULL;
4903 old_conn->proxypasswd = NULL;
4906 /* host can change, when doing keepalive with a proxy or if the case is
4907 different this time etc */
4908 Curl_safefree(conn->host.rawalloc);
4909 conn->host=old_conn->host;
4911 /* persist connection info in session handle */
4912 Curl_persistconninfo(conn);
4915 conn->bits.reuse = TRUE; /* yes, we're re-using here */
4917 Curl_safefree(old_conn->user);
4918 Curl_safefree(old_conn->passwd);
4919 Curl_safefree(old_conn->proxyuser);
4920 Curl_safefree(old_conn->proxypasswd);
4921 Curl_safefree(old_conn->localdev);
4923 Curl_llist_destroy(old_conn->send_pipe, NULL);
4924 Curl_llist_destroy(old_conn->recv_pipe, NULL);
4926 old_conn->send_pipe = NULL;
4927 old_conn->recv_pipe = NULL;
4929 Curl_safefree(old_conn->master_buffer);
4933 * create_conn() sets up a new connectdata struct, or re-uses an already
4934 * existing one, and resolves host name.
4936 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
4937 * response will be coming asynchronously. If *async is FALSE, the name is
4940 * @param data The sessionhandle pointer
4941 * @param in_connect is set to the next connection data pointer
4942 * @param async is set TRUE when an async DNS resolution is pending
4943 * @see Curl_setup_conn()
4945 * *NOTE* this function assigns the conn->data pointer!
4948 static CURLcode create_conn(struct SessionHandle *data,
4949 struct connectdata **in_connect,
4952 CURLcode result = CURLE_OK;
4953 struct connectdata *conn;
4954 struct connectdata *conn_temp = NULL;
4956 char user[MAX_CURL_USER_LENGTH];
4957 char passwd[MAX_CURL_PASSWORD_LENGTH];
4958 char options[MAX_CURL_OPTIONS_LENGTH];
4961 bool prot_missing = FALSE;
4962 bool no_connections_available = FALSE;
4964 size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
4965 size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
4969 /*************************************************************
4971 *************************************************************/
4973 if(!data->change.url)
4974 return CURLE_URL_MALFORMAT;
4976 /* First, split up the current URL in parts so that we can use the
4977 parts for checking against the already present connections. In order
4978 to not have to modify everything at once, we allocate a temporary
4979 connection data struct and fill in for comparison purposes. */
4980 conn = allocate_conn(data);
4983 return CURLE_OUT_OF_MEMORY;
4985 /* We must set the return variable as soon as possible, so that our
4986 parent can cleanup any possible allocs we may have done before
4990 /* This initing continues below, see the comment "Continue connectdata
4991 * initialization here" */
4993 /***********************************************************
4994 * We need to allocate memory to store the path in. We get the size of the
4995 * full URL to be sure, and we need to make it at least 256 bytes since
4996 * other parts of the code will rely on this fact
4997 ***********************************************************/
4998 #define LEAST_PATH_ALLOC 256
4999 urllen=strlen(data->change.url);
5000 if(urllen < LEAST_PATH_ALLOC)
5001 urllen=LEAST_PATH_ALLOC;
5004 * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
5005 * 1 - an extra terminating zero
5006 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
5009 Curl_safefree(data->state.pathbuffer);
5010 data->state.path = NULL;
5012 data->state.pathbuffer = malloc(urllen+2);
5013 if(NULL == data->state.pathbuffer)
5014 return CURLE_OUT_OF_MEMORY; /* really bad error */
5015 data->state.path = data->state.pathbuffer;
5017 conn->host.rawalloc = malloc(urllen+2);
5018 if(NULL == conn->host.rawalloc) {
5019 Curl_safefree(data->state.pathbuffer);
5020 data->state.path = NULL;
5021 return CURLE_OUT_OF_MEMORY;
5024 conn->host.name = conn->host.rawalloc;
5025 conn->host.name[0] = 0;
5027 result = parseurlandfillconn(data, conn, &prot_missing, user, passwd,
5029 if(result != CURLE_OK)
5032 /*************************************************************
5033 * No protocol part in URL was used, add it!
5034 *************************************************************/
5036 /* We're guessing prefixes here and if we're told to use a proxy or if
5037 we're gonna follow a Location: later or... then we need the protocol
5038 part added so that we have a valid URL. */
5041 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
5044 Curl_safefree(proxy);
5045 return CURLE_OUT_OF_MEMORY;
5048 if(data->change.url_alloc) {
5049 Curl_safefree(data->change.url);
5050 data->change.url_alloc = FALSE;
5053 data->change.url = reurl;
5054 data->change.url_alloc = TRUE; /* free this later */
5057 /*************************************************************
5058 * If the protocol can't handle url query strings, then cut
5059 * of the unhandable part
5060 *************************************************************/
5061 if((conn->given->flags&PROTOPT_NOURLQUERY)) {
5062 char *path_q_sep = strchr(conn->data->state.path, '?');
5064 /* according to rfc3986, allow the query (?foo=bar)
5065 also on protocols that can't handle it.
5067 cut the string-part after '?'
5070 /* terminate the string */
5075 #ifndef CURL_DISABLE_PROXY
5076 /*************************************************************
5077 * Extract the user and password from the authentication string
5078 *************************************************************/
5079 if(conn->bits.proxy_user_passwd) {
5080 result = parse_proxy_auth(data, conn);
5081 if(result != CURLE_OK)
5085 /*************************************************************
5086 * Detect what (if any) proxy to use
5087 *************************************************************/
5088 if(data->set.str[STRING_PROXY]) {
5089 proxy = strdup(data->set.str[STRING_PROXY]);
5090 /* if global proxy is set, this is it */
5092 failf(data, "memory shortage");
5093 return CURLE_OUT_OF_MEMORY;
5097 if(data->set.str[STRING_NOPROXY] &&
5098 check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
5100 free(proxy); /* proxy is in exception list */
5105 proxy = detect_proxy(conn);
5107 if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
5108 free(proxy); /* Don't bother with an empty proxy string or if the
5109 protocol doesn't work with network */
5113 /***********************************************************************
5114 * If this is supposed to use a proxy, we need to figure out the proxy host
5115 * name, proxy type and port number, so that we can re-use an existing
5116 * connection that may exist registered to the same proxy host.
5117 ***********************************************************************/
5119 result = parse_proxy(data, conn, proxy);
5121 free(proxy); /* parse_proxy copies the proxy string */
5126 if((conn->proxytype == CURLPROXY_HTTP) ||
5127 (conn->proxytype == CURLPROXY_HTTP_1_0)) {
5128 #ifdef CURL_DISABLE_HTTP
5129 /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
5130 return CURLE_UNSUPPORTED_PROTOCOL;
5132 /* force this connection's protocol to become HTTP if not already
5133 compatible - if it isn't tunneling through */
5134 if(!(conn->handler->protocol & CURLPROTO_HTTP) &&
5135 !conn->bits.tunnel_proxy)
5136 conn->handler = &Curl_handler_http;
5138 conn->bits.httpproxy = TRUE;
5142 conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
5143 conn->bits.proxy = TRUE;
5146 /* we aren't using the proxy after all... */
5147 conn->bits.proxy = FALSE;
5148 conn->bits.httpproxy = FALSE;
5149 conn->bits.proxy_user_passwd = FALSE;
5150 conn->bits.tunnel_proxy = FALSE;
5153 #endif /* CURL_DISABLE_PROXY */
5155 /*************************************************************
5156 * Setup internals depending on protocol. Needs to be done after
5157 * we figured out what/if proxy to use.
5158 *************************************************************/
5159 result = setup_connection_internals(conn);
5160 if(result != CURLE_OK) {
5161 Curl_safefree(proxy);
5165 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
5166 conn->send[FIRSTSOCKET] = Curl_send_plain;
5167 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
5168 conn->send[SECONDARYSOCKET] = Curl_send_plain;
5170 /***********************************************************************
5171 * file: is a special case in that it doesn't need a network connection
5172 ***********************************************************************/
5173 #ifndef CURL_DISABLE_FILE
5174 if(conn->handler->flags & PROTOPT_NONETWORK) {
5176 /* this is supposed to be the connect function so we better at least check
5177 that the file is present here! */
5178 DEBUGASSERT(conn->handler->connect_it);
5179 result = conn->handler->connect_it(conn, &done);
5181 /* Setup a "faked" transfer that'll do nothing */
5182 if(CURLE_OK == result) {
5184 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
5186 ConnectionStore(data, conn);
5189 * Setup whatever necessary for a resumed transfer
5191 result = setup_range(data);
5193 DEBUGASSERT(conn->handler->done);
5194 /* we ignore the return code for the protocol-specific DONE */
5195 (void)conn->handler->done(conn, result, FALSE);
5199 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
5200 -1, NULL); /* no upload */
5203 /* since we skip do_init() */
5204 Curl_speedinit(data);
5210 /*************************************************************
5211 * If the protocol is using SSL and HTTP proxy is used, we set
5212 * the tunnel_proxy bit.
5213 *************************************************************/
5214 if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
5215 conn->bits.tunnel_proxy = TRUE;
5217 /*************************************************************
5218 * Figure out the remote port number and fix it in the URL
5219 *************************************************************/
5220 result = parse_remote_port(data, conn);
5221 if(result != CURLE_OK)
5224 /* Check for overridden login details and set them accordingly */
5225 override_login(data, conn, user, passwd, options);
5226 result = set_login(conn, user, passwd, options);
5227 if(result != CURLE_OK)
5230 /* Get a cloned copy of the SSL config situation stored in the
5231 connection struct. But to get this going nicely, we must first make
5232 sure that the strings in the master copy are pointing to the correct
5233 strings in the session handle strings array!
5235 Keep in mind that the pointers in the master copy are pointing to strings
5236 that will be freed as part of the SessionHandle struct, but all cloned
5237 copies will be separately allocated.
5239 data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
5240 data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
5241 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
5242 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
5243 data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
5244 data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
5245 data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
5247 data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
5248 data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
5251 if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
5252 return CURLE_OUT_OF_MEMORY;
5254 /*************************************************************
5255 * Check the current list of connections to see if we can
5256 * re-use an already existing one or if we have to create a
5258 *************************************************************/
5260 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
5261 we only acknowledge this option if this is not a re-used connection
5262 already (which happens due to follow-location or during a HTTP
5263 authentication phase). */
5264 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
5267 reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse);
5269 /* If we found a reusable connection, we may still want to
5270 open a new connection if we are pipelining. */
5271 if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
5272 size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
5274 infof(data, "Found connection %d, with requests in the pipe (%d)\n",
5275 conn_temp->connection_id, pipelen);
5277 if(conn_temp->bundle->num_connections < max_host_connections &&
5278 data->state.conn_cache->num_connections < max_total_connections) {
5279 /* We want a new connection anyway */
5282 infof(data, "We can reuse, but we want a new connection anyway\n");
5289 * We already have a connection for this, we got the former connection
5290 * in the conn_temp variable and thus we need to cleanup the one we
5291 * just allocated before we can move along and use the previously
5294 conn_temp->inuse = TRUE; /* mark this as being in use so that no other
5295 handle in a multi stack may nick it */
5296 reuse_conn(conn, conn_temp);
5297 free(conn); /* we don't need this anymore */
5301 /* set a pointer to the hostname we display */
5302 fix_hostname(data, conn, &conn->host);
5304 infof(data, "Re-using existing connection! (#%ld) with host %s\n",
5305 conn->connection_id,
5306 conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
5309 /* We have decided that we want a new connection. However, we may not
5310 be able to do that if we have reached the limit of how many
5311 connections we are allowed to open. */
5312 struct connectbundle *bundle;
5314 bundle = Curl_conncache_find_bundle(data->state.conn_cache,
5316 if(max_host_connections > 0 && bundle &&
5317 (bundle->num_connections >= max_host_connections)) {
5318 struct connectdata *conn_candidate;
5320 /* The bundle is full. Let's see if we can kill a connection. */
5321 conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
5323 if(conn_candidate) {
5324 /* Set the connection's owner correctly, then kill it */
5325 conn_candidate->data = data;
5326 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
5329 no_connections_available = TRUE;
5332 if(max_total_connections > 0 &&
5333 (data->state.conn_cache->num_connections >= max_total_connections)) {
5334 struct connectdata *conn_candidate;
5336 /* The cache is full. Let's see if we can kill a connection. */
5337 conn_candidate = find_oldest_idle_connection(data);
5339 if(conn_candidate) {
5340 /* Set the connection's owner correctly, then kill it */
5341 conn_candidate->data = data;
5342 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
5345 no_connections_available = TRUE;
5349 if(no_connections_available) {
5350 infof(data, "No connections available.\n");
5355 return CURLE_NO_CONNECTION_AVAILABLE;
5359 * This is a brand new connection, so let's store it in the connection
5362 ConnectionStore(data, conn);
5366 /* Mark the connection as used */
5369 /* Setup and init stuff before DO starts, in preparing for the transfer. */
5373 * Setup whatever necessary for a resumed transfer
5375 result = setup_range(data);
5379 /* Continue connectdata initialization here. */
5382 * Inherit the proper values from the urldata struct AFTER we have arranged
5383 * the persistent connection stuff
5385 conn->fread_func = data->set.fread_func;
5386 conn->fread_in = data->set.in;
5387 conn->seek_func = data->set.seek_func;
5388 conn->seek_client = data->set.seek_client;
5390 /*************************************************************
5391 * Resolve the address of the server or proxy
5392 *************************************************************/
5393 result = resolve_server(data, conn, async);
5398 /* Curl_setup_conn() is called after the name resolve initiated in
5399 * create_conn() is all done.
5401 * Curl_setup_conn() also handles reused connections
5403 * conn->data MUST already have been setup fine (in create_conn)
5406 CURLcode Curl_setup_conn(struct connectdata *conn,
5407 bool *protocol_done)
5409 CURLcode result = CURLE_OK;
5410 struct SessionHandle *data = conn->data;
5412 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
5414 if(conn->handler->flags & PROTOPT_NONETWORK) {
5415 /* nothing to setup when not using a network */
5416 *protocol_done = TRUE;
5419 *protocol_done = FALSE; /* default to not done */
5421 /* set proxy_connect_closed to false unconditionally already here since it
5422 is used strictly to provide extra information to a parent function in the
5423 case of proxy CONNECT failures and we must make sure we don't have it
5424 lingering set from a previous invoke */
5425 conn->bits.proxy_connect_closed = FALSE;
5428 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
5429 * basically anything through a http proxy we can't limit this based on
5432 if(data->set.str[STRING_USERAGENT]) {
5433 Curl_safefree(conn->allocptr.uagent);
5434 conn->allocptr.uagent =
5435 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
5436 if(!conn->allocptr.uagent)
5437 return CURLE_OUT_OF_MEMORY;
5440 data->req.headerbytecount = 0;
5442 #ifdef CURL_DO_LINEEND_CONV
5443 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
5444 #endif /* CURL_DO_LINEEND_CONV */
5446 /* set start time here for timeout purposes in the connect procedure, it
5447 is later set again for the progress meter purpose */
5448 conn->now = Curl_tvnow();
5451 /* loop for CURL_SERVER_CLOSED_CONNECTION */
5453 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
5454 /* Try to connect only if not already connected */
5455 bool connected = FALSE;
5457 result = ConnectPlease(data, conn, &connected);
5459 if(result && !conn->ip_addr) {
5460 /* transport connection failure not related with authentication */
5461 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
5466 result = Curl_protocol_connect(conn, protocol_done);
5467 if(CURLE_OK == result)
5468 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
5471 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
5473 /* if the connection was closed by the server while exchanging
5474 authentication informations, retry with the new set
5475 authentication information */
5476 if(conn->bits.proxy_connect_closed) {
5477 /* reset the error buffer */
5478 if(data->set.errorbuffer)
5479 data->set.errorbuffer[0] = '\0';
5480 data->state.errorbuf = FALSE;
5484 if(CURLE_OK != result)
5488 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
5489 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
5490 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
5491 *protocol_done = TRUE;
5492 Curl_verboseconnect(conn);
5493 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
5495 /* Stop the loop now */
5499 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
5500 set this here perhaps a second time */
5504 * This check is quite a hack. We're calling _fsetmode to fix the problem
5505 * with fwrite converting newline characters (you get mangled text files,
5506 * and corrupted binary files when you download to stdout and redirect it to
5510 if((data->set.out)->_handle == NULL) {
5511 _fsetmode(stdout, "b");
5518 CURLcode Curl_connect(struct SessionHandle *data,
5519 struct connectdata **in_connect,
5521 bool *protocol_done)
5525 *asyncp = FALSE; /* assume synchronous resolves by default */
5527 /* call the stuff that needs to be called */
5528 code = create_conn(data, in_connect, asyncp);
5530 if(CURLE_OK == code) {
5532 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
5534 *protocol_done = TRUE;
5536 /* DNS resolution is done: that's either because this is a reused
5537 connection, in which case DNS was unnecessary, or because DNS
5538 really did finish already (synch resolver/fast async resolve) */
5539 code = Curl_setup_conn(*in_connect, protocol_done);
5543 if(code == CURLE_NO_CONNECTION_AVAILABLE) {
5548 if(code && *in_connect) {
5549 /* We're not allowed to return failure with memory left allocated
5550 in the connectdata struct, free those here */
5551 Curl_disconnect(*in_connect, FALSE); /* close the connection */
5552 *in_connect = NULL; /* return a NULL */
5558 CURLcode Curl_done(struct connectdata **connp,
5559 CURLcode status, /* an error if this is called after an
5560 error was detected */
5564 struct connectdata *conn;
5565 struct SessionHandle *data;
5567 DEBUGASSERT(*connp);
5573 /* Stop if Curl_done() has already been called */
5576 Curl_getoff_all_pipelines(data, conn);
5578 if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
5579 !data->set.reuse_forbid &&
5581 /* Stop if pipeline is not empty and we do not have to close
5585 conn->bits.done = TRUE; /* called just now! */
5587 /* Cleanup possible redirect junk */
5588 if(data->req.newurl) {
5589 free(data->req.newurl);
5590 data->req.newurl = NULL;
5592 if(data->req.location) {
5593 free(data->req.location);
5594 data->req.location = NULL;
5597 Curl_resolver_cancel(conn);
5599 if(conn->dns_entry) {
5600 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
5601 conn->dns_entry = NULL;
5604 if(status == CURLE_ABORTED_BY_CALLBACK)
5605 /* When we're aborted due to a callback return code it basically have to
5606 be counted as premature as there is trouble ahead if we don't. We have
5607 many callbacks and protocols work differently, we could potentially do
5608 this more fine-grained in the future. */
5611 /* this calls the protocol-specific function pointer previously set */
5612 if(conn->handler->done)
5613 result = conn->handler->done(conn, status, premature);
5617 if(Curl_pgrsDone(conn) && !result)
5618 result = CURLE_ABORTED_BY_CALLBACK;
5620 /* if the transfer was completed in a paused state there can be buffered
5621 data left to write and then kill */
5622 if(data->state.tempwrite) {
5623 free(data->state.tempwrite);
5624 data->state.tempwrite = NULL;
5627 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
5628 forced us to close this no matter what we think.
5630 if conn->bits.close is TRUE, it means that the connection should be
5631 closed in spite of all our efforts to be nice, due to protocol
5632 restrictions in our or the server's end
5634 if premature is TRUE, it means this connection was said to be DONE before
5635 the entire request operation is complete and thus we can't know in what
5636 state it is for re-using, so we're forced to close it. In a perfect world
5637 we can add code that keep track of if we really must close it here or not,
5638 but currently we have no such detail knowledge.
5640 if(data->set.reuse_forbid || conn->bits.close || premature) {
5641 CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
5643 /* If we had an error already, make sure we return that one. But
5644 if we got a new error, return that. */
5649 /* the connection is no longer in use */
5650 if(ConnectionDone(data, conn)) {
5651 /* remember the most recently used connection */
5652 data->state.lastconnect = conn;
5654 infof(data, "Connection #%ld to host %s left intact\n",
5655 conn->connection_id,
5656 conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
5659 data->state.lastconnect = NULL;
5662 *connp = NULL; /* to make the caller of this function better detect that
5663 this was either closed or handed over to the connection
5664 cache here, and therefore cannot be used from this point on
5671 * do_init() inits the readwrite session. This is inited each time (in the DO
5672 * function before the protocol-specific DO functions are invoked) for a
5673 * transfer, sometimes multiple times on the same SessionHandle. Make sure
5674 * nothing in here depends on stuff that are setup dynamically for the
5678 static CURLcode do_init(struct connectdata *conn)
5680 struct SessionHandle *data = conn->data;
5681 struct SingleRequest *k = &data->req;
5683 conn->bits.done = FALSE; /* Curl_done() is not called yet */
5684 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
5685 data->state.expect100header = FALSE;
5687 if(data->set.opt_no_body)
5688 /* in HTTP lingo, no body means using the HEAD request... */
5689 data->set.httpreq = HTTPREQ_HEAD;
5690 else if(HTTPREQ_HEAD == data->set.httpreq)
5691 /* ... but if unset there really is no perfect method that is the
5692 "opposite" of HEAD but in reality most people probably think GET
5693 then. The important thing is that we can't let it remain HEAD if the
5694 opt_no_body is set FALSE since then we'll behave wrong when getting
5696 data->set.httpreq = HTTPREQ_GET;
5698 /* NB: the content encoding software depends on this initialization */
5699 Curl_easy_initHandleData(data);
5701 k->start = Curl_tvnow(); /* start time */
5702 k->now = k->start; /* current time is now */
5703 k->header = TRUE; /* assume header */
5707 k->buf = data->state.buffer;
5708 k->uploadbuf = data->state.uploadbuffer;
5709 k->hbufp = data->state.headerbuff;
5710 k->ignorebody=FALSE;
5712 Curl_speedinit(data);
5714 Curl_pgrsSetUploadCounter(data, 0);
5715 Curl_pgrsSetDownloadCounter(data, 0);
5721 * do_complete is called when the DO actions are complete.
5723 * We init chunking and trailer bits to their default values here immediately
5724 * before receiving any header data for the current request in the pipeline.
5726 static void do_complete(struct connectdata *conn)
5728 conn->data->req.chunk=FALSE;
5729 conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
5730 conn->sockfd:conn->writesockfd)+1;
5731 Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
5734 CURLcode Curl_do(struct connectdata **connp, bool *done)
5736 CURLcode result=CURLE_OK;
5737 struct connectdata *conn = *connp;
5738 struct SessionHandle *data = conn->data;
5740 if(conn->handler->do_it) {
5741 /* generic protocol-specific function pointer set in curl_connect() */
5742 result = conn->handler->do_it(conn, done);
5744 /* This was formerly done in transfer.c, but we better do it here */
5745 if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
5747 * If the connection is using an easy handle, call reconnect
5748 * to re-establish the connection. Otherwise, let the multi logic
5749 * figure out how to re-establish the connection.
5752 result = Curl_reconnect_request(connp);
5754 if(result == CURLE_OK) {
5755 /* ... finally back to actually retry the DO phase */
5756 conn = *connp; /* re-assign conn since Curl_reconnect_request
5757 creates a new connection */
5758 result = conn->handler->do_it(conn, done);
5765 if((result == CURLE_OK) && *done)
5766 /* do_complete must be called after the protocol-specific DO function */
5773 * Curl_do_more() is called during the DO_MORE multi state. It is basically a
5774 * second stage DO state which (wrongly) was introduced to support FTP's
5775 * second connection.
5777 * TODO: A future libcurl should be able to work away this state.
5781 CURLcode Curl_do_more(struct connectdata *conn, bool *completed)
5783 CURLcode result=CURLE_OK;
5787 if(conn->handler->do_more)
5788 result = conn->handler->do_more(conn, completed);
5790 if(!result && *completed)
5791 /* do_complete must be called after the protocol-specific DO function */
5797 /* Called on connect, and if there's already a protocol-specific struct
5798 allocated for a different connection, this frees it that it can be setup
5799 properly later on. */
5800 void Curl_reset_reqproto(struct connectdata *conn)
5802 struct SessionHandle *data = conn->data;
5803 if(data->state.proto.generic && data->state.current_conn != conn) {
5804 free(data->state.proto.generic);
5805 data->state.proto.generic = NULL;
5807 data->state.current_conn = conn;