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 **user_storage,
301 char **pwd_storage, char **options_storage)
303 CURLcode result = CURLE_OK;
305 char *passwdp = NULL;
306 char *optionsp = NULL;
309 /* we treat a NULL passed in as a hint to clear existing info */
311 Curl_safefree(*user_storage);
312 *user_storage = (char *) NULL;
316 Curl_safefree(*pwd_storage);
317 *pwd_storage = (char *) NULL;
320 if(options_storage) {
321 Curl_safefree(*options_storage);
322 *options_storage = (char *) NULL;
328 /* Parse the login details */
329 result = parse_login_details(option, strlen(option),
330 (user_storage ? &userp : NULL),
331 (pwd_storage ? &passwdp : NULL),
332 (options_storage ? &optionsp : NULL));
334 /* store username part of option */
336 setstropt(user_storage, userp);
338 /* store password part of option */
340 setstropt(pwd_storage, passwdp);
342 /* store options part of option */
344 setstropt(options_storage, optionsp);
350 CURLcode Curl_dupset(struct SessionHandle * dst, struct SessionHandle * src)
352 CURLcode r = CURLE_OK;
355 /* Copy src->set into dst->set first, then deal with the strings
359 /* clear all string pointers first */
360 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
362 /* duplicate all strings */
363 for(i=(enum dupstring)0; i< STRING_LAST; i++) {
364 r = setstropt(&dst->set.str[i], src->set.str[i]);
369 /* If a failure occurred, freeing has to be performed externally. */
374 * This is the internal function curl_easy_cleanup() calls. This should
375 * cleanup and free all resources associated with this sessionhandle.
377 * NOTE: if we ever add something that attempts to write to a socket or
378 * similar here, we must ignore SIGPIPE first. It is currently only done
379 * when curl_easy_perform() is invoked.
382 CURLcode Curl_close(struct SessionHandle *data)
384 struct Curl_multi *m;
389 Curl_expire(data, 0); /* shut off timers */
394 /* This handle is still part of a multi handle, take care of this first
395 and detach this handle from there. */
396 curl_multi_remove_handle(data->multi, data);
399 /* when curl_easy_perform() is used, it creates its own multi handle to
400 use and this is the one */
401 curl_multi_cleanup(data->multi_easy);
403 /* Destroy the timeout list that is held in the easy handle. It is
404 /normally/ done by curl_multi_remove_handle() but this is "just in
406 if(data->state.timeoutlist) {
407 Curl_llist_destroy(data->state.timeoutlist, NULL);
408 data->state.timeoutlist = NULL;
411 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
412 the multi handle, since that function uses the magic
415 if(data->state.rangestringalloc)
416 free(data->state.range);
418 /* Free the pathbuffer */
419 Curl_safefree(data->state.pathbuffer);
420 data->state.path = NULL;
422 Curl_safefree(data->state.proto.generic);
424 /* Close down all open SSL info and sessions */
425 Curl_ssl_close_all(data);
426 Curl_safefree(data->state.first_host);
427 Curl_safefree(data->state.scratch);
428 Curl_ssl_free_certinfo(data);
430 if(data->change.referer_alloc) {
431 Curl_safefree(data->change.referer);
432 data->change.referer_alloc = FALSE;
434 data->change.referer = NULL;
436 if(data->change.url_alloc) {
437 Curl_safefree(data->change.url);
438 data->change.url_alloc = FALSE;
440 data->change.url = NULL;
442 Curl_safefree(data->state.headerbuff);
444 Curl_flush_cookies(data, 1);
446 Curl_digest_cleanup(data);
448 Curl_safefree(data->info.contenttype);
449 Curl_safefree(data->info.wouldredirect);
451 /* this destroys the channel and we cannot use it anymore after this */
452 Curl_resolver_cleanup(data->state.resolver);
454 Curl_convert_close(data);
456 /* No longer a dirty share, if it exists */
458 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
459 data->share->dirty--;
460 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
469 * Initialize the UserDefined fields within a SessionHandle.
470 * This may be safely called on a new or existing SessionHandle.
472 CURLcode Curl_init_userdefined(struct UserDefined *set)
474 CURLcode res = CURLE_OK;
476 set->out = stdout; /* default output to stdout */
477 set->in = stdin; /* default input from stdin */
478 set->err = stderr; /* default stderr to stderr */
480 /* use fwrite as default function to store output */
481 set->fwrite_func = (curl_write_callback)fwrite;
483 /* use fread as default function to read input */
484 set->fread_func = (curl_read_callback)fread;
485 set->is_fread_set = 0;
486 set->is_fwrite_set = 0;
488 set->seek_func = ZERO_NULL;
489 set->seek_client = ZERO_NULL;
491 /* conversion callbacks for non-ASCII hosts */
492 set->convfromnetwork = ZERO_NULL;
493 set->convtonetwork = ZERO_NULL;
494 set->convfromutf8 = ZERO_NULL;
496 set->infilesize = -1; /* we don't know any size */
497 set->postfieldsize = -1; /* unknown size */
498 set->maxredirs = -1; /* allow any amount by default */
500 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
501 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
502 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
503 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
504 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
505 set->ftp_filemethod = FTPFILE_MULTICWD;
507 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
509 /* Set the default size of the SSL session ID cache */
510 set->ssl.max_ssl_sessions = 5;
512 set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
513 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
514 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
515 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
517 /* make libcurl quiet by default: */
518 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
521 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
522 * switched off unless wanted.
524 set->ssl.verifypeer = TRUE;
525 set->ssl.verifyhost = TRUE;
527 set->ssl.authtype = CURL_TLSAUTH_NONE;
529 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
531 set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
533 set->new_file_perms = 0644; /* Default permissions */
534 set->new_directory_perms = 0755; /* Default permissions */
536 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
537 define since we internally only use the lower 16 bits for the passed
538 in bitmask to not conflict with the private bits */
539 set->allowed_protocols = CURLPROTO_ALL;
540 set->redir_protocols =
541 CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
543 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
545 * disallow unprotected protection negotiation NEC reference implementation
546 * seem not to follow rfc1961 section 4.3/4.4
548 set->socks5_gssapi_nec = FALSE;
549 /* set default gssapi service name */
550 res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
551 (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
556 /* This is our preferred CA cert bundle/path since install time */
557 #if defined(CURL_CA_BUNDLE)
558 res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
559 #elif defined(CURL_CA_PATH)
560 res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
563 set->wildcardmatch = FALSE;
564 set->chunk_bgn = ZERO_NULL;
565 set->chunk_end = ZERO_NULL;
567 /* tcp keepalives are disabled by default, but provide reasonable values for
568 * the interval and idle times.
570 set->tcp_keepalive = FALSE;
571 set->tcp_keepintvl = 60;
572 set->tcp_keepidle = 60;
580 * @param curl is a pointer to a sessionhandle pointer that gets set by this
585 CURLcode Curl_open(struct SessionHandle **curl)
587 CURLcode res = CURLE_OK;
588 struct SessionHandle *data;
591 /* Very simple start-up: alloc the struct, init it with zeroes and return */
592 data = calloc(1, sizeof(struct SessionHandle));
594 /* this is a very serious error */
595 DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
596 return CURLE_OUT_OF_MEMORY;
599 data->magic = CURLEASY_MAGIC_NUMBER;
601 status = Curl_resolver_init(&data->state.resolver);
603 DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
608 /* We do some initial setup here, all those fields that can't be just 0 */
610 data->state.headerbuff = malloc(HEADERSIZE);
611 if(!data->state.headerbuff) {
612 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
613 res = CURLE_OUT_OF_MEMORY;
616 Curl_easy_initHandleData(data);
617 res = Curl_init_userdefined(&data->set);
619 data->state.headersize=HEADERSIZE;
621 Curl_convert_init(data);
623 /* most recent connection is not yet defined */
624 data->state.lastconnect = NULL;
626 data->progress.flags |= PGRS_HIDE;
627 data->state.current_speed = -1; /* init to negative == impossible */
629 data->wildcard.state = CURLWC_INIT;
630 data->wildcard.filelist = NULL;
631 data->set.fnmatch = ZERO_NULL;
632 data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
636 Curl_resolver_cleanup(data->state.resolver);
637 if(data->state.headerbuff)
638 free(data->state.headerbuff);
649 CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
653 CURLcode result = CURLE_OK;
655 #ifndef CURL_DISABLE_HTTP
660 case CURLOPT_DNS_CACHE_TIMEOUT:
661 data->set.dns_cache_timeout = va_arg(param, long);
663 case CURLOPT_DNS_USE_GLOBAL_CACHE:
664 /* remember we want this enabled */
665 arg = va_arg(param, long);
666 data->set.global_dns_cache = (0 != arg)?TRUE:FALSE;
668 case CURLOPT_SSL_CIPHER_LIST:
669 /* set a list of cipher we want to use in the SSL connection */
670 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
671 va_arg(param, char *));
674 case CURLOPT_RANDOM_FILE:
676 * This is the path name to a file that contains random data to seed
677 * the random SSL stuff with. The file is only used for reading.
679 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
680 va_arg(param, char *));
682 case CURLOPT_EGDSOCKET:
684 * The Entropy Gathering Daemon socket pathname
686 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
687 va_arg(param, char *));
689 case CURLOPT_MAXCONNECTS:
691 * Set the absolute number of maximum simultaneous alive connection that
692 * libcurl is allowed to have.
694 data->set.maxconnects = va_arg(param, long);
696 case CURLOPT_FORBID_REUSE:
698 * When this transfer is done, it must not be left to be reused by a
699 * subsequent transfer but shall be closed immediately.
701 data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE;
703 case CURLOPT_FRESH_CONNECT:
705 * This transfer shall not use a previously cached connection but
706 * should be made with a fresh new connect!
708 data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE;
710 case CURLOPT_VERBOSE:
712 * Verbose means infof() calls that give a lot of information about
713 * the connection and transfer procedures as well as internal choices.
715 data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE;
719 * Set to include the header in the general data output stream.
721 data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE;
723 case CURLOPT_NOPROGRESS:
725 * Shut off the internal supported progress meter
727 data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE;
728 if(data->set.hide_progress)
729 data->progress.flags |= PGRS_HIDE;
731 data->progress.flags &= ~PGRS_HIDE;
735 * Do not include the body part in the output data stream.
737 data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE;
739 case CURLOPT_FAILONERROR:
741 * Don't output the >=300 error code HTML-page, but instead only
744 data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE;
749 * We want to sent data to the remote host. If this is HTTP, that equals
750 * using the PUT request.
752 data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE;
753 if(data->set.upload) {
754 /* If this is HTTP, PUT is what's needed to "upload" */
755 data->set.httpreq = HTTPREQ_PUT;
756 data->set.opt_no_body = FALSE; /* this is implied */
759 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
760 then this can be changed to HEAD later on) */
761 data->set.httpreq = HTTPREQ_GET;
763 case CURLOPT_FILETIME:
765 * Try to get the file time of the remote document. The time will
766 * later (possibly) become available using curl_easy_getinfo().
768 data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE;
770 case CURLOPT_FTP_CREATE_MISSING_DIRS:
772 * An FTP option that modifies an upload to create missing directories on
775 switch(va_arg(param, long)) {
777 data->set.ftp_create_missing_dirs = 0;
780 data->set.ftp_create_missing_dirs = 1;
783 data->set.ftp_create_missing_dirs = 2;
786 /* reserve other values for future use */
787 result = CURLE_UNKNOWN_OPTION;
791 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
793 * Option that specifies how quickly an server response must be obtained
794 * before it is considered failure. For pingpong protocols.
796 data->set.server_response_timeout = va_arg( param , long ) * 1000;
798 case CURLOPT_TFTP_BLKSIZE:
800 * TFTP option that specifies the block size to use for data transmission
802 data->set.tftp_blksize = va_arg(param, long);
804 case CURLOPT_DIRLISTONLY:
806 * An option that changes the command to one that asks for a list
807 * only, no file info details.
809 data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE;
813 * We want to upload and append to an existing file.
815 data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE;
817 case CURLOPT_FTP_FILEMETHOD:
819 * How do access files over FTP.
821 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
825 * Parse the $HOME/.netrc file
827 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
829 case CURLOPT_NETRC_FILE:
831 * Use this file instead of the $HOME/.netrc file
833 result = setstropt(&data->set.str[STRING_NETRC_FILE],
834 va_arg(param, char *));
836 case CURLOPT_TRANSFERTEXT:
838 * This option was previously named 'FTPASCII'. Renamed to work with
839 * more protocols than merely FTP.
841 * Transfer using ASCII (instead of BINARY).
843 data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE;
845 case CURLOPT_TIMECONDITION:
847 * Set HTTP time condition. This must be one of the defines in the
848 * curl/curl.h header file.
850 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
852 case CURLOPT_TIMEVALUE:
854 * This is the value to compare with the remote document with the
855 * method set with CURLOPT_TIMECONDITION
857 data->set.timevalue = (time_t)va_arg(param, long);
859 case CURLOPT_SSLVERSION:
861 * Set explicit SSL version to try to connect with, as some SSL
862 * implementations are lame.
864 data->set.ssl.version = va_arg(param, long);
867 #ifndef CURL_DISABLE_HTTP
868 case CURLOPT_AUTOREFERER:
870 * Switch on automatic referer that gets set if curl follows locations.
872 data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE;
875 case CURLOPT_ACCEPT_ENCODING:
877 * String to use at the value of Accept-Encoding header.
879 * If the encoding is set to "" we use an Accept-Encoding header that
880 * encompasses all the encodings we support.
881 * If the encoding is set to NULL we don't send an Accept-Encoding header
882 * and ignore an received Content-Encoding header.
885 argptr = va_arg(param, char *);
886 result = setstropt(&data->set.str[STRING_ENCODING],
887 (argptr && !*argptr)?
888 (char *) ALL_CONTENT_ENCODINGS: argptr);
891 case CURLOPT_TRANSFER_ENCODING:
892 data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE;
895 case CURLOPT_FOLLOWLOCATION:
897 * Follow Location: header hints on a HTTP-server.
899 data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE;
902 case CURLOPT_UNRESTRICTED_AUTH:
904 * Send authentication (user+password) when following locations, even when
907 data->set.http_disable_hostname_check_before_authentication =
908 (0 != va_arg(param, long))?TRUE:FALSE;
911 case CURLOPT_MAXREDIRS:
913 * The maximum amount of hops you allow curl to follow Location:
914 * headers. This should mostly be used to detect never-ending loops.
916 data->set.maxredirs = va_arg(param, long);
919 case CURLOPT_POSTREDIR:
922 * Set the behaviour of POST when redirecting
923 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
924 * CURL_REDIR_POST_301 - POST is kept as POST after 301
925 * CURL_REDIR_POST_302 - POST is kept as POST after 302
926 * CURL_REDIR_POST_303 - POST is kept as POST after 303
927 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
928 * other - POST is kept as POST after 301 and 302
930 int postRedir = curlx_sltosi(va_arg(param, long));
931 data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
936 /* Does this option serve a purpose anymore? Yes it does, when
937 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
939 if(va_arg(param, long)) {
940 data->set.httpreq = HTTPREQ_POST;
941 data->set.opt_no_body = FALSE; /* this is implied */
944 data->set.httpreq = HTTPREQ_GET;
947 case CURLOPT_COPYPOSTFIELDS:
949 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
950 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
951 * CURLOPT_COPYPOSTFIELDS and not altered later.
953 argptr = va_arg(param, char *);
955 if(!argptr || data->set.postfieldsize == -1)
956 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
959 * Check that requested length does not overflow the size_t type.
962 if((data->set.postfieldsize < 0) ||
963 ((sizeof(curl_off_t) != sizeof(size_t)) &&
964 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
965 result = CURLE_OUT_OF_MEMORY;
969 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
971 /* Allocate even when size == 0. This satisfies the need of possible
972 later address compare to detect the COPYPOSTFIELDS mode, and
973 to mark that postfields is used rather than read function or
976 p = malloc((size_t)(data->set.postfieldsize?
977 data->set.postfieldsize:1));
980 result = CURLE_OUT_OF_MEMORY;
982 if(data->set.postfieldsize)
983 memcpy(p, argptr, (size_t)data->set.postfieldsize);
985 data->set.str[STRING_COPYPOSTFIELDS] = p;
990 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
991 data->set.httpreq = HTTPREQ_POST;
994 case CURLOPT_POSTFIELDS:
996 * Like above, but use static data instead of copying it.
998 data->set.postfields = va_arg(param, void *);
999 /* Release old copied data. */
1000 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1001 data->set.httpreq = HTTPREQ_POST;
1004 case CURLOPT_POSTFIELDSIZE:
1006 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1007 * figure it out. Enables binary posts.
1009 bigsize = va_arg(param, long);
1011 if(data->set.postfieldsize < bigsize &&
1012 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1013 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1014 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1015 data->set.postfields = NULL;
1018 data->set.postfieldsize = bigsize;
1021 case CURLOPT_POSTFIELDSIZE_LARGE:
1023 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1024 * figure it out. Enables binary posts.
1026 bigsize = va_arg(param, curl_off_t);
1028 if(data->set.postfieldsize < bigsize &&
1029 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1030 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1031 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1032 data->set.postfields = NULL;
1035 data->set.postfieldsize = bigsize;
1038 case CURLOPT_HTTPPOST:
1040 * Set to make us do HTTP POST
1042 data->set.httppost = va_arg(param, struct curl_httppost *);
1043 data->set.httpreq = HTTPREQ_POST_FORM;
1044 data->set.opt_no_body = FALSE; /* this is implied */
1047 case CURLOPT_REFERER:
1049 * String to set in the HTTP Referer: field.
1051 if(data->change.referer_alloc) {
1052 Curl_safefree(data->change.referer);
1053 data->change.referer_alloc = FALSE;
1055 result = setstropt(&data->set.str[STRING_SET_REFERER],
1056 va_arg(param, char *));
1057 data->change.referer = data->set.str[STRING_SET_REFERER];
1060 case CURLOPT_USERAGENT:
1062 * String to use in the HTTP User-Agent field
1064 result = setstropt(&data->set.str[STRING_USERAGENT],
1065 va_arg(param, char *));
1068 case CURLOPT_HTTPHEADER:
1070 * Set a list with HTTP headers to use (or replace internals with)
1072 data->set.headers = va_arg(param, struct curl_slist *);
1075 case CURLOPT_HTTP200ALIASES:
1077 * Set a list of aliases for HTTP 200 in response header
1079 data->set.http200aliases = va_arg(param, struct curl_slist *);
1082 #if !defined(CURL_DISABLE_COOKIES)
1083 case CURLOPT_COOKIE:
1085 * Cookie string to send to the remote server in the request.
1087 result = setstropt(&data->set.str[STRING_COOKIE],
1088 va_arg(param, char *));
1091 case CURLOPT_COOKIEFILE:
1093 * Set cookie file to read and parse. Can be used multiple times.
1095 argptr = (char *)va_arg(param, void *);
1097 struct curl_slist *cl;
1098 /* append the cookie file name to the list of file names, and deal with
1100 cl = curl_slist_append(data->change.cookielist, argptr);
1102 curl_slist_free_all(data->change.cookielist);
1103 data->change.cookielist = NULL;
1104 return CURLE_OUT_OF_MEMORY;
1106 data->change.cookielist = cl; /* store the list for later use */
1110 case CURLOPT_COOKIEJAR:
1112 * Set cookie file name to dump all cookies to when we're done.
1114 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1115 va_arg(param, char *));
1118 * Activate the cookie parser. This may or may not already
1121 data->cookies = Curl_cookie_init(data, NULL, data->cookies,
1122 data->set.cookiesession);
1125 case CURLOPT_COOKIESESSION:
1127 * Set this option to TRUE to start a new "cookie session". It will
1128 * prevent the forthcoming read-cookies-from-file actions to accept
1129 * cookies that are marked as being session cookies, as they belong to a
1132 * In the original Netscape cookie spec, "session cookies" are cookies
1133 * with no expire date set. RFC2109 describes the same action if no
1134 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1135 * a 'Discard' action that can enforce the discard even for cookies that
1138 * We run mostly with the original cookie spec, as hardly anyone implements
1141 data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE;
1144 case CURLOPT_COOKIELIST:
1145 argptr = va_arg(param, char *);
1150 if(Curl_raw_equal(argptr, "ALL")) {
1151 /* clear all cookies */
1152 Curl_cookie_clearall(data->cookies);
1155 else if(Curl_raw_equal(argptr, "SESS")) {
1156 /* clear session cookies */
1157 Curl_cookie_clearsess(data->cookies);
1160 else if(Curl_raw_equal(argptr, "FLUSH")) {
1161 /* flush cookies to file */
1162 Curl_flush_cookies(data, 0);
1167 /* if cookie engine was not running, activate it */
1168 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1170 argptr = strdup(argptr);
1172 result = CURLE_OUT_OF_MEMORY;
1176 if(checkprefix("Set-Cookie:", argptr))
1177 /* HTTP Header format line */
1178 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1181 /* Netscape format line */
1182 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1186 #endif /* CURL_DISABLE_COOKIES */
1188 case CURLOPT_HTTPGET:
1190 * Set to force us do HTTP GET
1192 if(va_arg(param, long)) {
1193 data->set.httpreq = HTTPREQ_GET;
1194 data->set.upload = FALSE; /* switch off upload */
1195 data->set.opt_no_body = FALSE; /* this is implied */
1199 case CURLOPT_HTTP_VERSION:
1201 * This sets a requested HTTP version to be used. The value is one of
1202 * the listed enums in curl/curl.h.
1204 data->set.httpversion = va_arg(param, long);
1207 case CURLOPT_HTTPAUTH:
1209 * Set HTTP Authentication type BITMASK.
1214 unsigned long auth = va_arg(param, unsigned long);
1216 if(auth == CURLAUTH_NONE) {
1217 data->set.httpauth = auth;
1221 /* the DIGEST_IE bit is only used to set a special marker, for all the
1222 rest we need to handle it as normal DIGEST */
1223 data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
1225 if(auth & CURLAUTH_DIGEST_IE) {
1226 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1227 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1230 /* switch off bits we can't support */
1232 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1233 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1234 #elif !defined(NTLM_WB_ENABLED)
1235 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1237 #ifndef USE_HTTP_NEGOTIATE
1238 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
1242 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1245 while(bitcheck < 31) {
1246 if(auth & (1UL << bitcheck++)) {
1252 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1254 data->set.httpauth = auth;
1258 #endif /* CURL_DISABLE_HTTP */
1260 case CURLOPT_CUSTOMREQUEST:
1262 * Set a custom string to use as request
1264 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1265 va_arg(param, char *));
1268 data->set.httpreq = HTTPREQ_CUSTOM;
1269 here, we continue as if we were using the already set type
1270 and this just changes the actual request keyword */
1273 #ifndef CURL_DISABLE_PROXY
1274 case CURLOPT_HTTPPROXYTUNNEL:
1276 * Tunnel operations through the proxy instead of normal proxy use
1278 data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE;
1281 case CURLOPT_PROXYPORT:
1283 * Explicitly set HTTP proxy port number.
1285 data->set.proxyport = va_arg(param, long);
1288 case CURLOPT_PROXYAUTH:
1290 * Set HTTP Authentication type BITMASK.
1295 unsigned long auth = va_arg(param, unsigned long);
1297 if(auth == CURLAUTH_NONE) {
1298 data->set.proxyauth = auth;
1302 /* the DIGEST_IE bit is only used to set a special marker, for all the
1303 rest we need to handle it as normal DIGEST */
1304 data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
1306 if(auth & CURLAUTH_DIGEST_IE) {
1307 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1308 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1310 /* switch off bits we can't support */
1312 auth &= ~CURLAUTH_NTLM; /* no NTLM support */
1313 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1314 #elif !defined(NTLM_WB_ENABLED)
1315 auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
1317 #ifndef USE_HTTP_NEGOTIATE
1318 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
1322 /* check if any auth bit lower than CURLAUTH_ONLY is still set */
1325 while(bitcheck < 31) {
1326 if(auth & (1UL << bitcheck++)) {
1332 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1334 data->set.proxyauth = auth;
1340 * Set proxy server:port to use as HTTP proxy.
1342 * If the proxy is set to "" we explicitly say that we don't want to use a
1343 * proxy (even though there might be environment variables saying so).
1345 * Setting it to NULL, means no proxy but allows the environment variables
1348 result = setstropt(&data->set.str[STRING_PROXY],
1349 va_arg(param, char *));
1352 case CURLOPT_PROXYTYPE:
1354 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1356 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1359 case CURLOPT_PROXY_TRANSFER_MODE:
1361 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1363 switch (va_arg(param, long)) {
1365 data->set.proxy_transfer_mode = FALSE;
1368 data->set.proxy_transfer_mode = TRUE;
1371 /* reserve other values for future use */
1372 result = CURLE_UNKNOWN_OPTION;
1376 #endif /* CURL_DISABLE_PROXY */
1378 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1379 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1381 * Set gssapi service name
1383 result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
1384 va_arg(param, char *));
1387 case CURLOPT_SOCKS5_GSSAPI_NEC:
1389 * set flag for nec socks5 support
1391 data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE;
1395 case CURLOPT_WRITEHEADER:
1397 * Custom pointer to pass the header write callback function
1399 data->set.writeheader = (void *)va_arg(param, void *);
1401 case CURLOPT_ERRORBUFFER:
1403 * Error buffer provided by the caller to get the human readable
1406 data->set.errorbuffer = va_arg(param, char *);
1410 * FILE pointer to write to. Or possibly
1411 * used as argument to the write callback.
1413 data->set.out = va_arg(param, void *);
1415 case CURLOPT_FTPPORT:
1417 * Use FTP PORT, this also specifies which IP address to use
1419 result = setstropt(&data->set.str[STRING_FTPPORT],
1420 va_arg(param, char *));
1421 data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ?
1425 case CURLOPT_FTP_USE_EPRT:
1426 data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE;
1429 case CURLOPT_FTP_USE_EPSV:
1430 data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE;
1433 case CURLOPT_FTP_USE_PRET:
1434 data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE;
1437 case CURLOPT_FTP_SSL_CCC:
1438 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1441 case CURLOPT_FTP_SKIP_PASV_IP:
1443 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1444 * bypass of the IP address in PASV responses.
1446 data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE;
1449 case CURLOPT_INFILE:
1451 * FILE pointer to read the file to be uploaded from. Or possibly
1452 * used as argument to the read callback.
1454 data->set.in = va_arg(param, void *);
1456 case CURLOPT_INFILESIZE:
1458 * If known, this should inform curl about the file size of the
1459 * to-be-uploaded file.
1461 data->set.infilesize = va_arg(param, long);
1463 case CURLOPT_INFILESIZE_LARGE:
1465 * If known, this should inform curl about the file size of the
1466 * to-be-uploaded file.
1468 data->set.infilesize = va_arg(param, curl_off_t);
1470 case CURLOPT_LOW_SPEED_LIMIT:
1472 * The low speed limit that if transfers are below this for
1473 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1475 data->set.low_speed_limit=va_arg(param, long);
1477 case CURLOPT_MAX_SEND_SPEED_LARGE:
1479 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1480 * bytes per second the transfer is throttled..
1482 data->set.max_send_speed=va_arg(param, curl_off_t);
1484 case CURLOPT_MAX_RECV_SPEED_LARGE:
1486 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1487 * second the transfer is throttled..
1489 data->set.max_recv_speed=va_arg(param, curl_off_t);
1491 case CURLOPT_LOW_SPEED_TIME:
1493 * The low speed time that if transfers are below the set
1494 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1496 data->set.low_speed_time=va_arg(param, long);
1502 if(data->change.url_alloc) {
1503 /* the already set URL is allocated, free it first! */
1504 Curl_safefree(data->change.url);
1505 data->change.url_alloc = FALSE;
1507 result = setstropt(&data->set.str[STRING_SET_URL],
1508 va_arg(param, char *));
1509 data->change.url = data->set.str[STRING_SET_URL];
1513 * The port number to use when getting the URL
1515 data->set.use_port = va_arg(param, long);
1517 case CURLOPT_TIMEOUT:
1519 * The maximum time you allow curl to use for a single transfer
1522 data->set.timeout = va_arg(param, long) * 1000L;
1525 case CURLOPT_TIMEOUT_MS:
1526 data->set.timeout = va_arg(param, long);
1529 case CURLOPT_CONNECTTIMEOUT:
1531 * The maximum time you allow curl to use to connect.
1533 data->set.connecttimeout = va_arg(param, long) * 1000L;
1536 case CURLOPT_CONNECTTIMEOUT_MS:
1537 data->set.connecttimeout = va_arg(param, long);
1540 case CURLOPT_ACCEPTTIMEOUT_MS:
1542 * The maximum time you allow curl to wait for server connect
1544 data->set.accepttimeout = va_arg(param, long);
1547 case CURLOPT_USERPWD:
1549 * user:password;options to use in the operation
1551 result = setstropt_userpwd(va_arg(param, char *),
1552 &data->set.str[STRING_USERNAME],
1553 &data->set.str[STRING_PASSWORD],
1554 &data->set.str[STRING_OPTIONS]);
1556 case CURLOPT_USERNAME:
1558 * authentication user name to use in the operation
1560 result = setstropt(&data->set.str[STRING_USERNAME],
1561 va_arg(param, char *));
1563 case CURLOPT_PASSWORD:
1565 * authentication password to use in the operation
1567 result = setstropt(&data->set.str[STRING_PASSWORD],
1568 va_arg(param, char *));
1570 case CURLOPT_POSTQUOTE:
1572 * List of RAW FTP commands to use after a transfer
1574 data->set.postquote = va_arg(param, struct curl_slist *);
1576 case CURLOPT_PREQUOTE:
1578 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1580 data->set.prequote = va_arg(param, struct curl_slist *);
1584 * List of RAW FTP commands to use before a transfer
1586 data->set.quote = va_arg(param, struct curl_slist *);
1588 case CURLOPT_RESOLVE:
1590 * List of NAME:[address] names to populate the DNS cache with
1591 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1593 * Names added with this API will remain in the cache until explicitly
1594 * removed or the handle is cleaned up.
1596 * This API can remove any name from the DNS cache, but only entries
1597 * that aren't actually in use right now will be pruned immediately.
1599 data->set.resolve = va_arg(param, struct curl_slist *);
1600 data->change.resolve = data->set.resolve;
1602 case CURLOPT_PROGRESSFUNCTION:
1604 * Progress callback function
1606 data->set.fprogress = va_arg(param, curl_progress_callback);
1607 if(data->set.fprogress)
1608 data->progress.callback = TRUE; /* no longer internal */
1610 data->progress.callback = FALSE; /* NULL enforces internal */
1613 case CURLOPT_PROGRESSDATA:
1615 * Custom client data to pass to the progress callback
1617 data->set.progress_client = va_arg(param, void *);
1620 #ifndef CURL_DISABLE_PROXY
1621 case CURLOPT_PROXYUSERPWD:
1623 * user:password needed to use the proxy
1625 result = setstropt_userpwd(va_arg(param, char *),
1626 &data->set.str[STRING_PROXYUSERNAME],
1627 &data->set.str[STRING_PROXYPASSWORD], NULL);
1629 case CURLOPT_PROXYUSERNAME:
1631 * authentication user name to use in the operation
1633 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1634 va_arg(param, char *));
1636 case CURLOPT_PROXYPASSWORD:
1638 * authentication password to use in the operation
1640 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1641 va_arg(param, char *));
1643 case CURLOPT_NOPROXY:
1645 * proxy exception list
1647 result = setstropt(&data->set.str[STRING_NOPROXY],
1648 va_arg(param, char *));
1654 * What range of the file you want to transfer
1656 result = setstropt(&data->set.str[STRING_SET_RANGE],
1657 va_arg(param, char *));
1659 case CURLOPT_RESUME_FROM:
1661 * Resume transfer at the give file position
1663 data->set.set_resume_from = va_arg(param, long);
1665 case CURLOPT_RESUME_FROM_LARGE:
1667 * Resume transfer at the give file position
1669 data->set.set_resume_from = va_arg(param, curl_off_t);
1671 case CURLOPT_DEBUGFUNCTION:
1673 * stderr write callback.
1675 data->set.fdebug = va_arg(param, curl_debug_callback);
1677 * if the callback provided is NULL, it'll use the default callback
1680 case CURLOPT_DEBUGDATA:
1682 * Set to a void * that should receive all error writes. This
1683 * defaults to CURLOPT_STDERR for normal operations.
1685 data->set.debugdata = va_arg(param, void *);
1687 case CURLOPT_STDERR:
1689 * Set to a FILE * that should receive all error writes. This
1690 * defaults to stderr for normal operations.
1692 data->set.err = va_arg(param, FILE *);
1694 data->set.err = stderr;
1696 case CURLOPT_HEADERFUNCTION:
1698 * Set header write callback
1700 data->set.fwrite_header = va_arg(param, curl_write_callback);
1702 case CURLOPT_WRITEFUNCTION:
1704 * Set data write callback
1706 data->set.fwrite_func = va_arg(param, curl_write_callback);
1707 if(!data->set.fwrite_func) {
1708 data->set.is_fwrite_set = 0;
1709 /* When set to NULL, reset to our internal default function */
1710 data->set.fwrite_func = (curl_write_callback)fwrite;
1713 data->set.is_fwrite_set = 1;
1715 case CURLOPT_READFUNCTION:
1717 * Read data callback
1719 data->set.fread_func = va_arg(param, curl_read_callback);
1720 if(!data->set.fread_func) {
1721 data->set.is_fread_set = 0;
1722 /* When set to NULL, reset to our internal default function */
1723 data->set.fread_func = (curl_read_callback)fread;
1726 data->set.is_fread_set = 1;
1728 case CURLOPT_SEEKFUNCTION:
1730 * Seek callback. Might be NULL.
1732 data->set.seek_func = va_arg(param, curl_seek_callback);
1734 case CURLOPT_SEEKDATA:
1736 * Seek control callback. Might be NULL.
1738 data->set.seek_client = va_arg(param, void *);
1740 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1742 * "Convert from network encoding" callback
1744 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1746 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1748 * "Convert to network encoding" callback
1750 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1752 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1754 * "Convert from UTF-8 encoding" callback
1756 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1758 case CURLOPT_IOCTLFUNCTION:
1760 * I/O control callback. Might be NULL.
1762 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1764 case CURLOPT_IOCTLDATA:
1766 * I/O control data pointer. Might be NULL.
1768 data->set.ioctl_client = va_arg(param, void *);
1770 case CURLOPT_SSLCERT:
1772 * String that holds file name of the SSL certificate to use
1774 result = setstropt(&data->set.str[STRING_CERT],
1775 va_arg(param, char *));
1777 case CURLOPT_SSLCERTTYPE:
1779 * String that holds file type of the SSL certificate to use
1781 result = setstropt(&data->set.str[STRING_CERT_TYPE],
1782 va_arg(param, char *));
1784 case CURLOPT_SSLKEY:
1786 * String that holds file name of the SSL key to use
1788 result = setstropt(&data->set.str[STRING_KEY],
1789 va_arg(param, char *));
1791 case CURLOPT_SSLKEYTYPE:
1793 * String that holds file type of the SSL key to use
1795 result = setstropt(&data->set.str[STRING_KEY_TYPE],
1796 va_arg(param, char *));
1798 case CURLOPT_KEYPASSWD:
1800 * String that holds the SSL or SSH private key password.
1802 result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1803 va_arg(param, char *));
1805 case CURLOPT_SSLENGINE:
1807 * String that holds the SSL crypto engine.
1809 argptr = va_arg(param, char *);
1810 if(argptr && argptr[0])
1811 result = Curl_ssl_set_engine(data, argptr);
1814 case CURLOPT_SSLENGINE_DEFAULT:
1816 * flag to set engine as default.
1818 result = Curl_ssl_set_engine_default(data);
1822 * Kludgy option to enable CRLF conversions. Subject for removal.
1824 data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE;
1827 case CURLOPT_INTERFACE:
1829 * Set what interface or address/hostname to bind the socket to when
1830 * performing an operation and thus what from-IP your connection will use.
1832 result = setstropt(&data->set.str[STRING_DEVICE],
1833 va_arg(param, char *));
1835 case CURLOPT_LOCALPORT:
1837 * Set what local port to bind the socket to when performing an operation.
1839 data->set.localport = curlx_sltous(va_arg(param, long));
1841 case CURLOPT_LOCALPORTRANGE:
1843 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
1845 data->set.localportrange = curlx_sltosi(va_arg(param, long));
1847 case CURLOPT_KRBLEVEL:
1849 * A string that defines the kerberos security level.
1851 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
1852 va_arg(param, char *));
1853 data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE;
1855 case CURLOPT_GSSAPI_DELEGATION:
1857 * GSSAPI credential delegation
1859 data->set.gssapi_delegation = va_arg(param, long);
1861 case CURLOPT_SSL_VERIFYPEER:
1863 * Enable peer SSL verifying.
1865 data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE;
1867 case CURLOPT_SSL_VERIFYHOST:
1869 * Enable verification of the host name in the peer certificate
1871 arg = va_arg(param, long);
1873 /* Obviously people are not reading documentation and too many thought
1874 this argument took a boolean when it wasn't and misused it. We thus ban
1875 1 as a sensible input and we warn about its use. Then we only have the
1876 2 action internally stored as TRUE. */
1879 failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
1880 return CURLE_BAD_FUNCTION_ARGUMENT;
1883 data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE;
1886 /* since these two options are only possible to use on an OpenSSL-
1887 powered libcurl we #ifdef them on this condition so that libcurls
1888 built against other SSL libs will return a proper error when trying
1889 to set this option! */
1890 case CURLOPT_SSL_CTX_FUNCTION:
1892 * Set a SSL_CTX callback
1894 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
1896 case CURLOPT_SSL_CTX_DATA:
1898 * Set a SSL_CTX callback parameter pointer
1900 data->set.ssl.fsslctxp = va_arg(param, void *);
1902 case CURLOPT_CERTINFO:
1903 data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE;
1906 case CURLOPT_CAINFO:
1908 * Set CA info for SSL connection. Specify file name of the CA certificate
1910 result = setstropt(&data->set.str[STRING_SSL_CAFILE],
1911 va_arg(param, char *));
1913 case CURLOPT_CAPATH:
1915 * Set CA path info for SSL connection. Specify directory name of the CA
1916 * certificates which have been prepared using openssl c_rehash utility.
1918 /* This does not work on windows. */
1919 result = setstropt(&data->set.str[STRING_SSL_CAPATH],
1920 va_arg(param, char *));
1922 case CURLOPT_CRLFILE:
1924 * Set CRL file info for SSL connection. Specify file name of the CRL
1925 * to check certificates revocation
1927 result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
1928 va_arg(param, char *));
1930 case CURLOPT_ISSUERCERT:
1932 * Set Issuer certificate file
1933 * to check certificates issuer
1935 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
1936 va_arg(param, char *));
1938 case CURLOPT_TELNETOPTIONS:
1940 * Set a linked list of telnet options
1942 data->set.telnet_options = va_arg(param, struct curl_slist *);
1945 case CURLOPT_BUFFERSIZE:
1947 * The application kindly asks for a differently sized receive buffer.
1948 * If it seems reasonable, we'll use it.
1950 data->set.buffer_size = va_arg(param, long);
1952 if((data->set.buffer_size> (BUFSIZE -1 )) ||
1953 (data->set.buffer_size < 1))
1954 data->set.buffer_size = 0; /* huge internal default */
1958 case CURLOPT_NOSIGNAL:
1960 * The application asks not to set any signal() or alarm() handlers,
1961 * even when using a timeout.
1963 data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE;
1968 struct Curl_share *set;
1969 set = va_arg(param, struct Curl_share *);
1971 /* disconnect from old share, if any */
1973 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
1975 if(data->dns.hostcachetype == HCACHE_SHARED) {
1976 data->dns.hostcache = NULL;
1977 data->dns.hostcachetype = HCACHE_NONE;
1980 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
1981 if(data->share->cookies == data->cookies)
1982 data->cookies = NULL;
1985 if(data->share->sslsession == data->state.session)
1986 data->state.session = NULL;
1988 data->share->dirty--;
1990 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
1994 /* use new share if it set */
1998 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2000 data->share->dirty++;
2002 if(data->share->hostcache) {
2003 /* use shared host cache */
2004 data->dns.hostcache = data->share->hostcache;
2005 data->dns.hostcachetype = HCACHE_SHARED;
2007 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2008 if(data->share->cookies) {
2009 /* use shared cookie list, first free own one if any */
2011 Curl_cookie_cleanup(data->cookies);
2012 /* enable cookies since we now use a share that uses cookies! */
2013 data->cookies = data->share->cookies;
2015 #endif /* CURL_DISABLE_HTTP */
2016 if(data->share->sslsession) {
2017 data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions;
2018 data->state.session = data->share->sslsession;
2020 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2023 /* check for host cache not needed,
2024 * it will be done by curl_easy_perform */
2028 case CURLOPT_PRIVATE:
2030 * Set private data pointer.
2032 data->set.private_data = va_arg(param, void *);
2035 case CURLOPT_MAXFILESIZE:
2037 * Set the maximum size of a file to download.
2039 data->set.max_filesize = va_arg(param, long);
2043 case CURLOPT_USE_SSL:
2045 * Make transfers attempt to use SSL/TLS.
2047 data->set.use_ssl = (curl_usessl)va_arg(param, long);
2050 case CURLOPT_SSL_OPTIONS:
2051 arg = va_arg(param, long);
2052 data->set.ssl_enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE;
2056 case CURLOPT_FTPSSLAUTH:
2058 * Set a specific auth for FTP-SSL transfers.
2060 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2063 case CURLOPT_IPRESOLVE:
2064 data->set.ipver = va_arg(param, long);
2067 case CURLOPT_MAXFILESIZE_LARGE:
2069 * Set the maximum size of a file to download.
2071 data->set.max_filesize = va_arg(param, curl_off_t);
2074 case CURLOPT_TCP_NODELAY:
2076 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2079 data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE;
2082 case CURLOPT_FTP_ACCOUNT:
2083 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2084 va_arg(param, char *));
2087 case CURLOPT_IGNORE_CONTENT_LENGTH:
2088 data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE;
2091 case CURLOPT_CONNECT_ONLY:
2093 * No data transfer, set up connection and let application use the socket
2095 data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE;
2098 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2099 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2100 va_arg(param, char *));
2103 case CURLOPT_SOCKOPTFUNCTION:
2105 * socket callback function: called after socket() but before connect()
2107 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2110 case CURLOPT_SOCKOPTDATA:
2112 * socket callback data pointer. Might be NULL.
2114 data->set.sockopt_client = va_arg(param, void *);
2117 case CURLOPT_OPENSOCKETFUNCTION:
2119 * open/create socket callback function: called instead of socket(),
2122 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2125 case CURLOPT_OPENSOCKETDATA:
2127 * socket callback data pointer. Might be NULL.
2129 data->set.opensocket_client = va_arg(param, void *);
2132 case CURLOPT_CLOSESOCKETFUNCTION:
2134 * close socket callback function: called instead of close()
2135 * when shutting down a connection
2137 data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
2140 case CURLOPT_CLOSESOCKETDATA:
2142 * socket callback data pointer. Might be NULL.
2144 data->set.closesocket_client = va_arg(param, void *);
2147 case CURLOPT_SSL_SESSIONID_CACHE:
2148 data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE;
2152 /* we only include SSH options if explicitly built to support SSH */
2153 case CURLOPT_SSH_AUTH_TYPES:
2154 data->set.ssh_auth_types = va_arg(param, long);
2157 case CURLOPT_SSH_PUBLIC_KEYFILE:
2159 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2161 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2162 va_arg(param, char *));
2165 case CURLOPT_SSH_PRIVATE_KEYFILE:
2167 * Use this file instead of the $HOME/.ssh/id_dsa file
2169 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2170 va_arg(param, char *));
2172 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2174 * Option to allow for the MD5 of the host public key to be checked
2175 * for validation purposes.
2177 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2178 va_arg(param, char *));
2180 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2181 case CURLOPT_SSH_KNOWNHOSTS:
2183 * Store the file name to read known hosts from.
2185 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2186 va_arg(param, char *));
2189 case CURLOPT_SSH_KEYFUNCTION:
2190 /* setting to NULL is fine since the ssh.c functions themselves will
2191 then rever to use the internal default */
2192 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2195 case CURLOPT_SSH_KEYDATA:
2197 * Custom client data to pass to the SSH keyfunc callback
2199 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2201 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2203 #endif /* USE_LIBSSH2 */
2205 case CURLOPT_HTTP_TRANSFER_DECODING:
2207 * disable libcurl transfer encoding is used
2209 data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE;
2212 case CURLOPT_HTTP_CONTENT_DECODING:
2214 * raw data passed to the application when content encoding is used
2216 data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE;
2219 case CURLOPT_NEW_FILE_PERMS:
2221 * Uses these permissions instead of 0644
2223 data->set.new_file_perms = va_arg(param, long);
2226 case CURLOPT_NEW_DIRECTORY_PERMS:
2228 * Uses these permissions instead of 0755
2230 data->set.new_directory_perms = va_arg(param, long);
2233 case CURLOPT_ADDRESS_SCOPE:
2235 * We always get longs when passed plain numericals, but for this value we
2236 * know that an unsigned int will always hold the value so we blindly
2237 * typecast to this type
2239 data->set.scope = curlx_sltoui(va_arg(param, long));
2242 case CURLOPT_PROTOCOLS:
2243 /* set the bitmask for the protocols that are allowed to be used for the
2244 transfer, which thus helps the app which takes URLs from users or other
2245 external inputs and want to restrict what protocol(s) to deal
2246 with. Defaults to CURLPROTO_ALL. */
2247 data->set.allowed_protocols = va_arg(param, long);
2250 case CURLOPT_REDIR_PROTOCOLS:
2251 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2252 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2253 to be set in both bitmasks to be allowed to get redirected to. Defaults
2254 to all protocols except FILE and SCP. */
2255 data->set.redir_protocols = va_arg(param, long);
2258 case CURLOPT_MAIL_FROM:
2259 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2260 va_arg(param, char *));
2263 case CURLOPT_MAIL_AUTH:
2264 result = setstropt(&data->set.str[STRING_MAIL_AUTH],
2265 va_arg(param, char *));
2268 case CURLOPT_MAIL_RCPT:
2269 /* get a list of mail recipients */
2270 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2273 case CURLOPT_RTSP_REQUEST:
2276 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2277 * Would this be better if the RTSPREQ_* were just moved into here?
2279 long curl_rtspreq = va_arg(param, long);
2280 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2281 switch(curl_rtspreq) {
2282 case CURL_RTSPREQ_OPTIONS:
2283 rtspreq = RTSPREQ_OPTIONS;
2286 case CURL_RTSPREQ_DESCRIBE:
2287 rtspreq = RTSPREQ_DESCRIBE;
2290 case CURL_RTSPREQ_ANNOUNCE:
2291 rtspreq = RTSPREQ_ANNOUNCE;
2294 case CURL_RTSPREQ_SETUP:
2295 rtspreq = RTSPREQ_SETUP;
2298 case CURL_RTSPREQ_PLAY:
2299 rtspreq = RTSPREQ_PLAY;
2302 case CURL_RTSPREQ_PAUSE:
2303 rtspreq = RTSPREQ_PAUSE;
2306 case CURL_RTSPREQ_TEARDOWN:
2307 rtspreq = RTSPREQ_TEARDOWN;
2310 case CURL_RTSPREQ_GET_PARAMETER:
2311 rtspreq = RTSPREQ_GET_PARAMETER;
2314 case CURL_RTSPREQ_SET_PARAMETER:
2315 rtspreq = RTSPREQ_SET_PARAMETER;
2318 case CURL_RTSPREQ_RECORD:
2319 rtspreq = RTSPREQ_RECORD;
2322 case CURL_RTSPREQ_RECEIVE:
2323 rtspreq = RTSPREQ_RECEIVE;
2326 rtspreq = RTSPREQ_NONE;
2329 data->set.rtspreq = rtspreq;
2334 case CURLOPT_RTSP_SESSION_ID:
2336 * Set the RTSP Session ID manually. Useful if the application is
2337 * resuming a previously established RTSP session
2339 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2340 va_arg(param, char *));
2343 case CURLOPT_RTSP_STREAM_URI:
2345 * Set the Stream URI for the RTSP request. Unless the request is
2346 * for generic server options, the application will need to set this.
2348 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2349 va_arg(param, char *));
2352 case CURLOPT_RTSP_TRANSPORT:
2354 * The content of the Transport: header for the RTSP request
2356 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2357 va_arg(param, char *));
2360 case CURLOPT_RTSP_CLIENT_CSEQ:
2362 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2363 * application is resuming a previously broken connection. The CSEQ
2364 * will increment from this new number henceforth.
2366 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2369 case CURLOPT_RTSP_SERVER_CSEQ:
2370 /* Same as the above, but for server-initiated requests */
2371 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2374 case CURLOPT_INTERLEAVEDATA:
2375 data->set.rtp_out = va_arg(param, void *);
2377 case CURLOPT_INTERLEAVEFUNCTION:
2378 /* Set the user defined RTP write function */
2379 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2382 case CURLOPT_WILDCARDMATCH:
2383 data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE;
2385 case CURLOPT_CHUNK_BGN_FUNCTION:
2386 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2388 case CURLOPT_CHUNK_END_FUNCTION:
2389 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2391 case CURLOPT_FNMATCH_FUNCTION:
2392 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2394 case CURLOPT_CHUNK_DATA:
2395 data->wildcard.customptr = va_arg(param, void *);
2397 case CURLOPT_FNMATCH_DATA:
2398 data->set.fnmatch_data = va_arg(param, void *);
2401 case CURLOPT_TLSAUTH_USERNAME:
2402 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
2403 va_arg(param, char *));
2404 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2405 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2407 case CURLOPT_TLSAUTH_PASSWORD:
2408 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
2409 va_arg(param, char *));
2410 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2411 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2413 case CURLOPT_TLSAUTH_TYPE:
2414 if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
2415 data->set.ssl.authtype = CURL_TLSAUTH_SRP;
2417 data->set.ssl.authtype = CURL_TLSAUTH_NONE;
2420 case CURLOPT_DNS_SERVERS:
2421 result = Curl_set_dns_servers(data, va_arg(param, char *));
2424 case CURLOPT_TCP_KEEPALIVE:
2425 data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE;
2427 case CURLOPT_TCP_KEEPIDLE:
2428 data->set.tcp_keepidle = va_arg(param, long);
2430 case CURLOPT_TCP_KEEPINTVL:
2431 data->set.tcp_keepintvl = va_arg(param, long);
2435 /* unknown tag and its companion, just ignore: */
2436 result = CURLE_UNKNOWN_OPTION;
2443 static void conn_free(struct connectdata *conn)
2448 /* possible left-overs from the async name resolvers */
2449 Curl_resolver_cancel(conn);
2451 /* close the SSL stuff before we close any sockets since they will/may
2452 write to the sockets */
2453 Curl_ssl_close(conn, FIRSTSOCKET);
2454 Curl_ssl_close(conn, SECONDARYSOCKET);
2456 /* close possibly still open sockets */
2457 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2458 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2459 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2460 Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
2462 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
2463 Curl_ntlm_wb_cleanup(conn);
2466 Curl_safefree(conn->user);
2467 Curl_safefree(conn->passwd);
2468 Curl_safefree(conn->options);
2469 Curl_safefree(conn->proxyuser);
2470 Curl_safefree(conn->proxypasswd);
2471 Curl_safefree(conn->allocptr.proxyuserpwd);
2472 Curl_safefree(conn->allocptr.uagent);
2473 Curl_safefree(conn->allocptr.userpwd);
2474 Curl_safefree(conn->allocptr.accept_encoding);
2475 Curl_safefree(conn->allocptr.te);
2476 Curl_safefree(conn->allocptr.rangeline);
2477 Curl_safefree(conn->allocptr.ref);
2478 Curl_safefree(conn->allocptr.host);
2479 Curl_safefree(conn->allocptr.cookiehost);
2480 Curl_safefree(conn->allocptr.rtsp_transport);
2481 Curl_safefree(conn->trailer);
2482 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2483 Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2484 Curl_safefree(conn->master_buffer);
2486 Curl_llist_destroy(conn->send_pipe, NULL);
2487 Curl_llist_destroy(conn->recv_pipe, NULL);
2489 conn->send_pipe = NULL;
2490 conn->recv_pipe = NULL;
2492 Curl_safefree(conn->localdev);
2493 Curl_free_ssl_config(&conn->ssl_config);
2495 free(conn); /* free all the connection oriented data */
2498 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2500 struct SessionHandle *data;
2502 return CURLE_OK; /* this is closed and fine already */
2506 DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
2510 if(conn->dns_entry != NULL) {
2511 Curl_resolv_unlock(data, conn->dns_entry);
2512 conn->dns_entry = NULL;
2515 Curl_hostcache_prune(data); /* kill old DNS cache entries */
2518 int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
2519 int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
2521 /* Authentication data is a mix of connection-related and sessionhandle-
2522 related stuff. NTLM is connection-related so when we close the shop
2526 data->state.authhost.done = FALSE;
2527 data->state.authhost.picked =
2528 data->state.authhost.want;
2531 if(has_proxy_ntlm) {
2532 data->state.authproxy.done = FALSE;
2533 data->state.authproxy.picked =
2534 data->state.authproxy.want;
2537 if(has_host_ntlm || has_proxy_ntlm)
2538 data->state.authproblem = FALSE;
2541 /* Cleanup NTLM connection-related data */
2542 Curl_http_ntlm_cleanup(conn);
2544 /* Cleanup possible redirect junk */
2545 if(data->req.newurl) {
2546 free(data->req.newurl);
2547 data->req.newurl = NULL;
2550 if(conn->handler->disconnect)
2551 /* This is set if protocol-specific cleanups should be made */
2552 conn->handler->disconnect(conn, dead_connection);
2554 /* unlink ourselves! */
2555 infof(data, "Closing connection %d\n", conn->connection_id);
2556 Curl_conncache_remove_conn(data->state.conn_cache, conn);
2558 #if defined(USE_LIBIDN)
2559 if(conn->host.encalloc)
2560 idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
2561 with idn_free() since this was allocated
2563 if(conn->proxy.encalloc)
2564 idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
2565 freed with idn_free() since this was
2566 allocated by libidn */
2567 #elif defined(USE_WIN32_IDN)
2568 free(conn->host.encalloc); /* encoded host name buffer, must be freed with
2569 idn_free() since this was allocated by
2570 curl_win32_idn_to_ascii */
2571 if(conn->proxy.encalloc)
2572 free(conn->proxy.encalloc); /* encoded proxy name buffer, must be freed
2573 with idn_free() since this was allocated by
2574 curl_win32_idn_to_ascii */
2577 Curl_ssl_close(conn, FIRSTSOCKET);
2579 /* Indicate to all handles on the pipe that we're dead */
2580 if(Curl_multi_pipeline_enabled(data->multi)) {
2581 signalPipeClose(conn->send_pipe, TRUE);
2582 signalPipeClose(conn->recv_pipe, TRUE);
2586 data->state.current_conn = NULL;
2587 Curl_speedinit(data);
2593 * This function should return TRUE if the socket is to be assumed to
2594 * be dead. Most commonly this happens when the server has closed the
2595 * connection due to inactivity.
2597 static bool SocketIsDead(curl_socket_t sock)
2600 bool ret_val = TRUE;
2602 sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2610 static bool IsPipeliningPossible(const struct SessionHandle *handle,
2611 const struct connectdata *conn)
2613 if((conn->handler->protocol & CURLPROTO_HTTP) &&
2614 Curl_multi_pipeline_enabled(handle->multi) &&
2615 (handle->set.httpreq == HTTPREQ_GET ||
2616 handle->set.httpreq == HTTPREQ_HEAD) &&
2617 handle->set.httpversion != CURL_HTTP_VERSION_1_0)
2623 bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
2625 return Curl_multi_pipeline_enabled(handle->multi);
2628 CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
2629 struct curl_llist *pipeline)
2631 if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
2632 return CURLE_OUT_OF_MEMORY;
2633 infof(data, "Curl_addHandleToPipeline: length: %d\n", pipeline->size);
2637 int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
2638 struct curl_llist *pipeline)
2640 struct curl_llist_element *curr;
2642 curr = pipeline->head;
2644 if(curr->ptr == handle) {
2645 Curl_llist_remove(pipeline, curr, NULL);
2646 return 1; /* we removed a handle */
2654 #if 0 /* this code is saved here as it is useful for debugging purposes */
2655 static void Curl_printPipeline(struct curl_llist *pipeline)
2657 struct curl_llist_element *curr;
2659 curr = pipeline->head;
2661 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2662 infof(data, "Handle in pipeline: %s\n", data->state.path);
2668 static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
2670 struct curl_llist_element *curr = pipeline->head;
2672 return (struct SessionHandle *) curr->ptr;
2678 /* remove the specified connection from all (possible) pipelines and related
2680 void Curl_getoff_all_pipelines(struct SessionHandle *data,
2681 struct connectdata *conn)
2683 bool recv_head = (conn->readchannel_inuse &&
2684 (gethandleathead(conn->recv_pipe) == data)) ? TRUE : FALSE;
2686 bool send_head = (conn->writechannel_inuse &&
2687 (gethandleathead(conn->send_pipe) == data)) ? TRUE : FALSE;
2689 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2690 conn->readchannel_inuse = FALSE;
2691 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2692 conn->writechannel_inuse = FALSE;
2695 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2697 struct curl_llist_element *curr;
2702 curr = pipeline->head;
2704 struct curl_llist_element *next = curr->next;
2705 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2707 #ifdef DEBUGBUILD /* debug-only code */
2708 if(data->magic != CURLEASY_MAGIC_NUMBER) {
2710 infof(data, "signalPipeClose() found BAAD easy handle\n");
2715 data->state.pipe_broke = TRUE;
2716 Curl_multi_handlePipeBreak(data);
2717 Curl_llist_remove(pipeline, curr, NULL);
2723 * This function finds the connection in the connection
2724 * cache that has been unused for the longest time.
2726 * Returns the pointer to the oldest idle connection, or NULL if none was
2729 static struct connectdata *
2730 find_oldest_idle_connection(struct SessionHandle *data)
2732 struct conncache *bc = data->state.conn_cache;
2733 struct curl_hash_iterator iter;
2734 struct curl_llist_element *curr;
2735 struct curl_hash_element *he;
2739 struct connectdata *conn_candidate = NULL;
2740 struct connectbundle *bundle;
2744 Curl_hash_start_iterate(bc->hash, &iter);
2746 he = Curl_hash_next_element(&iter);
2748 struct connectdata *conn;
2752 curr = bundle->conn_list->head;
2757 /* Set higher score for the age passed since the connection was used */
2758 score = Curl_tvdiff(now, conn->now);
2760 if(score > highscore) {
2762 conn_candidate = conn;
2768 he = Curl_hash_next_element(&iter);
2771 return conn_candidate;
2775 * This function finds the connection in the connection
2776 * bundle that has been unused for the longest time.
2778 * Returns the pointer to the oldest idle connection, or NULL if none was
2781 static struct connectdata *
2782 find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
2783 struct connectbundle *bundle)
2785 struct curl_llist_element *curr;
2789 struct connectdata *conn_candidate = NULL;
2790 struct connectdata *conn;
2796 curr = bundle->conn_list->head;
2801 /* Set higher score for the age passed since the connection was used */
2802 score = Curl_tvdiff(now, conn->now);
2804 if(score > highscore) {
2806 conn_candidate = conn;
2812 return conn_candidate;
2816 * Given one filled in connection struct (named needle), this function should
2817 * detect if there already is one that has all the significant details
2818 * exactly the same and thus should be used instead.
2820 * If there is a match, this function returns TRUE - and has marked the
2821 * connection as 'in-use'. It must later be called with ConnectionDone() to
2822 * return back to 'idle' (unused) state.
2824 * The force_reuse flag is set if the connection must be used, even if
2825 * the pipelining strategy wants to open a new connection instead of reusing.
2828 ConnectionExists(struct SessionHandle *data,
2829 struct connectdata *needle,
2830 struct connectdata **usethis,
2833 struct connectdata *check;
2834 struct connectdata *chosen = 0;
2835 bool canPipeline = IsPipeliningPossible(data, needle);
2836 bool wantNTLM = (data->state.authhost.want==CURLAUTH_NTLM) ||
2837 (data->state.authhost.want==CURLAUTH_NTLM_WB) ? TRUE : FALSE;
2838 struct connectbundle *bundle;
2840 *force_reuse = FALSE;
2842 /* We can't pipe if the site is blacklisted */
2843 if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
2844 canPipeline = FALSE;
2847 /* Look up the bundle with all the connections to this
2849 bundle = Curl_conncache_find_bundle(data->state.conn_cache,
2852 size_t max_pipe_len = Curl_multi_max_pipeline_length(data->multi);
2853 size_t best_pipe_len = max_pipe_len;
2854 struct curl_llist_element *curr;
2856 infof(data, "Found bundle for host %s: %p\n", needle->host.name, bundle);
2858 /* We can't pipe if we don't know anything about the server */
2859 if(canPipeline && !bundle->server_supports_pipelining) {
2860 infof(data, "Server doesn't support pipelining\n");
2861 canPipeline = FALSE;
2864 curr = bundle->conn_list->head;
2867 bool credentialsMatch = FALSE;
2871 * Note that if we use a HTTP proxy, we check connections to that
2872 * proxy and not to the actual remote server.
2877 pipeLen = check->send_pipe->size + check->recv_pipe->size;
2879 if(!pipeLen && !check->inuse) {
2880 /* The check for a dead socket makes sense only if there are no
2881 handles in pipeline and the connection isn't already marked in
2884 if(check->handler->protocol & CURLPROTO_RTSP)
2885 /* RTSP is a special case due to RTP interleaving */
2886 dead = Curl_rtsp_connisdead(check);
2888 dead = SocketIsDead(check->sock[FIRSTSOCKET]);
2892 infof(data, "Connection %d seems to be dead!\n",
2893 check->connection_id);
2895 /* disconnect resources */
2896 Curl_disconnect(check, /* dead_connection */ TRUE);
2902 /* Make sure the pipe has only GET requests */
2903 struct SessionHandle* sh = gethandleathead(check->send_pipe);
2904 struct SessionHandle* rh = gethandleathead(check->recv_pipe);
2906 if(!IsPipeliningPossible(sh, check))
2910 if(!IsPipeliningPossible(rh, check))
2916 /* can only happen within multi handles, and means that another easy
2917 handle is using this connection */
2921 if(Curl_resolver_asynch()) {
2922 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
2923 completed yet and until then we don't re-use this connection */
2924 if(!check->ip_addr_str[0]) {
2926 "Connection #%ld is still name resolving, can't reuse\n",
2927 check->connection_id);
2932 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
2933 check->bits.close) {
2934 /* Don't pick a connection that hasn't connected yet or that is going
2936 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
2937 check->connection_id);
2939 if(check->recv_pipe->size > 0) {
2941 "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
2942 check->connection_id);
2949 if((needle->handler->flags&PROTOPT_SSL) !=
2950 (check->handler->flags&PROTOPT_SSL))
2951 /* don't do mixed SSL and non-SSL connections */
2952 if(!(needle->handler->protocol & check->handler->protocol))
2953 /* except protocols that have been upgraded via TLS */
2956 if(needle->handler->flags&PROTOPT_SSL) {
2957 if((data->set.ssl.verifypeer != check->verifypeer) ||
2958 (data->set.ssl.verifyhost != check->verifyhost))
2962 if(needle->bits.proxy != check->bits.proxy)
2963 /* don't do mixed proxy and non-proxy connections */
2966 if(!canPipeline && check->inuse)
2967 /* this request can't be pipelined but the checked connection is
2968 already in use so we skip it */
2971 if(needle->localdev || needle->localport) {
2972 /* If we are bound to a specific local end (IP+port), we must not
2973 re-use a random other one, although if we didn't ask for a
2974 particular one we can reuse one that was bound.
2976 This comparison is a bit rough and too strict. Since the input
2977 parameters can be specified in numerous ways and still end up the
2978 same it would take a lot of processing to make it really accurate.
2979 Instead, this matching will assume that re-uses of bound connections
2980 will most likely also re-use the exact same binding parameters and
2981 missing out a few edge cases shouldn't hurt anyone very much.
2983 if((check->localport != needle->localport) ||
2984 (check->localportrange != needle->localportrange) ||
2986 !needle->localdev ||
2987 strcmp(check->localdev, needle->localdev))
2991 if((needle->handler->protocol & CURLPROTO_FTP) ||
2992 ((needle->handler->protocol & CURLPROTO_HTTP) && wantNTLM)) {
2993 /* This is FTP or HTTP+NTLM, verify that we're using the same name
2994 and password as well */
2995 if(!strequal(needle->user, check->user) ||
2996 !strequal(needle->passwd, check->passwd)) {
2997 /* one of them was different */
3000 credentialsMatch = TRUE;
3003 if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
3004 (needle->bits.httpproxy && check->bits.httpproxy &&
3005 needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
3006 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3007 (needle->port == check->port))) {
3008 /* The requested connection does not use a HTTP proxy or it uses SSL or
3009 it is a non-SSL protocol tunneled over the same http proxy name and
3010 port number or it is a non-SSL protocol which is allowed to be
3013 if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
3014 needle->handler->protocol & check->handler->protocol) &&
3015 Curl_raw_equal(needle->host.name, check->host.name) &&
3016 needle->remote_port == check->remote_port) {
3017 if(needle->handler->flags & PROTOPT_SSL) {
3018 /* This is a SSL connection so verify that we're using the same
3019 SSL options as well */
3020 if(!Curl_ssl_config_matches(&needle->ssl_config,
3021 &check->ssl_config)) {
3023 "Connection #%ld has different SSL parameters, "
3025 check->connection_id));
3028 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3030 "Connection #%ld has not started SSL connect, "
3032 check->connection_id));
3039 else { /* The requested needle connection is using a proxy,
3040 is the checked one using the same host, port and type? */
3041 if(check->bits.proxy &&
3042 (needle->proxytype == check->proxytype) &&
3043 (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
3044 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3045 needle->port == check->port) {
3046 /* This is the same proxy connection, use it! */
3052 /* If we are looking for an NTLM connection, check if this is already
3053 authenticating with the right credentials. If not, keep looking so
3054 that we can reuse NTLM connections if possible. (Especially we
3055 must not reuse the same connection if partway through
3058 if(credentialsMatch && check->ntlm.state != NTLMSTATE_NONE) {
3061 /* We must use this connection, no other */
3062 *force_reuse = TRUE;
3070 /* We can pipeline if we want to. Let's continue looking for
3071 the optimal connection to use, i.e the shortest pipe that is not
3075 /* We have the optimal connection. Let's stop looking. */
3080 /* We can't use the connection if the pipe is full */
3081 if(pipeLen >= max_pipe_len)
3084 /* We can't use the connection if the pipe is penalized */
3085 if(Curl_pipeline_penalized(data, check))
3088 if(pipeLen < best_pipe_len) {
3089 /* This connection has a shorter pipe so far. We'll pick this
3090 and continue searching */
3092 best_pipe_len = pipeLen;
3097 /* We have found a connection. Let's stop searching. */
3107 return TRUE; /* yes, we found one to use! */
3110 return FALSE; /* no matching connecting exists */
3113 /* Mark the connection as 'idle', or close it if the cache is full.
3114 Returns TRUE if the connection is kept, or FALSE if it was closed. */
3116 ConnectionDone(struct SessionHandle *data, struct connectdata *conn)
3118 /* data->multi->maxconnects can be negative, deal with it. */
3119 size_t maxconnects =
3120 (data->multi->maxconnects < 0) ? 0 : data->multi->maxconnects;
3121 struct connectdata *conn_candidate = NULL;
3123 /* Mark the current connection as 'unused' */
3124 conn->inuse = FALSE;
3126 if(maxconnects > 0 &&
3127 data->state.conn_cache->num_connections > maxconnects) {
3128 infof(data, "Connection cache is full, closing the oldest one.\n");
3130 conn_candidate = find_oldest_idle_connection(data);
3132 if(conn_candidate) {
3133 /* Set the connection's owner correctly */
3134 conn_candidate->data = data;
3136 /* the winner gets the honour of being disconnected */
3137 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
3141 return (conn_candidate == conn) ? FALSE : TRUE;
3145 * The given input connection struct pointer is to be stored in the connection
3146 * cache. If the cache is already full, least interesting existing connection
3147 * (if any) gets closed.
3149 * The given connection should be unique. That must've been checked prior to
3152 static CURLcode ConnectionStore(struct SessionHandle *data,
3153 struct connectdata *conn)
3155 static int connection_id_counter = 0;
3159 /* Assign a number to the connection for easier tracking in the log
3161 conn->connection_id = connection_id_counter++;
3163 result = Curl_conncache_add_conn(data->state.conn_cache, conn);
3164 if(result != CURLE_OK)
3165 conn->connection_id = -1;
3170 /* after a TCP connection to the proxy has been verified, this function does
3171 the next magic step.
3173 Note: this function's sub-functions call failf()
3176 CURLcode Curl_connected_proxy(struct connectdata *conn)
3178 if(!conn->bits.proxy)
3181 switch(conn->proxytype) {
3182 #ifndef CURL_DISABLE_PROXY
3183 case CURLPROXY_SOCKS5:
3184 case CURLPROXY_SOCKS5_HOSTNAME:
3185 return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3186 conn->host.name, conn->remote_port,
3189 case CURLPROXY_SOCKS4:
3190 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3191 conn->remote_port, FIRSTSOCKET, conn, FALSE);
3193 case CURLPROXY_SOCKS4A:
3194 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3195 conn->remote_port, FIRSTSOCKET, conn, TRUE);
3197 #endif /* CURL_DISABLE_PROXY */
3198 case CURLPROXY_HTTP:
3199 case CURLPROXY_HTTP_1_0:
3200 /* do nothing here. handled later. */
3204 } /* switch proxytype */
3209 static CURLcode ConnectPlease(struct SessionHandle *data,
3210 struct connectdata *conn,
3214 Curl_addrinfo *addr;
3215 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3216 char *hostname = conn->bits.proxy?conn->proxy.name:conn->host.name;
3218 infof(data, "About to connect() to %s%s port %ld (#%ld)\n",
3219 conn->bits.proxy?"proxy ":"",
3220 hostname, conn->port, conn->connection_id);
3225 /*************************************************************
3226 * Connect to server/proxy
3227 *************************************************************/
3228 result= Curl_connecthost(conn,
3230 &conn->sock[FIRSTSOCKET],
3233 if(CURLE_OK == result) {
3234 /* All is cool, we store the current information */
3235 conn->ip_addr = addr;
3238 result = Curl_connected_proxy(conn);
3240 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
3241 Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
3247 *connected = FALSE; /* mark it as not connected */
3253 * verboseconnect() displays verbose information after a connect
3255 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3256 void Curl_verboseconnect(struct connectdata *conn)
3258 if(conn->data->set.verbose)
3259 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3260 conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3261 conn->ip_addr_str, conn->port, conn->connection_id);
3265 int Curl_protocol_getsock(struct connectdata *conn,
3266 curl_socket_t *socks,
3269 if(conn->handler->proto_getsock)
3270 return conn->handler->proto_getsock(conn, socks, numsocks);
3271 return GETSOCK_BLANK;
3274 int Curl_doing_getsock(struct connectdata *conn,
3275 curl_socket_t *socks,
3278 if(conn && conn->handler->doing_getsock)
3279 return conn->handler->doing_getsock(conn, socks, numsocks);
3280 return GETSOCK_BLANK;
3284 * We are doing protocol-specific connecting and this is being called over and
3285 * over from the multi interface until the connection phase is done on
3289 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3292 CURLcode result=CURLE_OK;
3294 if(conn && conn->handler->connecting) {
3296 result = conn->handler->connecting(conn, done);
3305 * We are DOING this is being called over and over from the multi interface
3306 * until the DOING phase is done on protocol layer.
3309 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3311 CURLcode result=CURLE_OK;
3313 if(conn && conn->handler->doing) {
3315 result = conn->handler->doing(conn, done);
3324 * We have discovered that the TCP connection has been successful, we can now
3325 * proceed with some action.
3328 CURLcode Curl_protocol_connect(struct connectdata *conn,
3329 bool *protocol_done)
3331 CURLcode result=CURLE_OK;
3333 *protocol_done = FALSE;
3335 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
3336 /* We already are connected, get back. This may happen when the connect
3337 worked fine in the first call, like when we connect to a local server
3338 or proxy. Note that we don't know if the protocol is actually done.
3340 Unless this protocol doesn't have any protocol-connect callback, as
3341 then we know we're done. */
3342 if(!conn->handler->connecting)
3343 *protocol_done = TRUE;
3348 if(!conn->bits.protoconnstart) {
3350 result = Curl_proxy_connect(conn);
3354 if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
3355 (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
3356 /* when using an HTTP tunnel proxy, await complete tunnel establishment
3357 before proceeding further. Return CURLE_OK so we'll be called again */
3360 if(conn->handler->connect_it) {
3361 /* is there a protocol-specific connect() procedure? */
3363 /* Call the protocol-specific connect function */
3364 result = conn->handler->connect_it(conn, protocol_done);
3367 *protocol_done = TRUE;
3369 /* it has started, possibly even completed but that knowledge isn't stored
3372 conn->bits.protoconnstart = TRUE;
3375 return result; /* pass back status */
3379 * Helpers for IDNA convertions.
3381 static bool is_ASCII_name(const char *hostname)
3383 const unsigned char *ch = (const unsigned char*)hostname;
3394 * Check if characters in hostname is allowed in Top Level Domain.
3396 static bool tld_check_name(struct SessionHandle *data,
3397 const char *ace_hostname)
3400 char *uc_name = NULL;
3402 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3403 const char *tld_errmsg = "<no msg>";
3408 /* Convert (and downcase) ACE-name back into locale's character set */
3409 rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3410 if(rc != IDNA_SUCCESS)
3413 rc = tld_check_lz(uc_name, &err_pos, NULL);
3414 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3415 #ifdef HAVE_TLD_STRERROR
3416 if(rc != TLD_SUCCESS)
3417 tld_errmsg = tld_strerror((Tld_rc)rc);
3419 if(rc == TLD_INVALID)
3420 infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
3421 tld_errmsg, err_pos, uc_name[err_pos],
3422 uc_name[err_pos] & 255);
3423 else if(rc != TLD_SUCCESS)
3424 infof(data, "WARNING: TLD check for %s failed; %s\n",
3425 uc_name, tld_errmsg);
3426 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3429 if(rc != TLD_SUCCESS)
3437 * Perform any necessary IDN conversion of hostname
3439 static void fix_hostname(struct SessionHandle *data,
3440 struct connectdata *conn, struct hostname *host)
3445 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3449 /* set the name we use to display the host name */
3450 host->dispname = host->name;
3451 if(!is_ASCII_name(host->name)) {
3453 /*************************************************************
3454 * Check name for non-ASCII and convert hostname to ACE form.
3455 *************************************************************/
3456 if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3457 char *ace_hostname = NULL;
3458 int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3459 infof (data, "Input domain encoded as `%s'\n",
3460 stringprep_locale_charset ());
3461 if(rc != IDNA_SUCCESS)
3462 infof(data, "Failed to convert %s to ACE; %s\n",
3463 host->name, Curl_idn_strerror(conn,rc));
3465 /* tld_check_name() displays a warning if the host name contains
3466 "illegal" characters for this TLD */
3467 (void)tld_check_name(data, ace_hostname);
3469 host->encalloc = ace_hostname;
3470 /* change the name pointer to point to the encoded hostname */
3471 host->name = host->encalloc;
3474 #elif defined(USE_WIN32_IDN)
3475 /*************************************************************
3476 * Check name for non-ASCII and convert hostname to ACE form.
3477 *************************************************************/
3478 char *ace_hostname = NULL;
3479 int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname);
3481 infof(data, "Failed to convert %s to ACE;\n",
3484 host->encalloc = ace_hostname;
3485 /* change the name pointer to point to the encoded hostname */
3486 host->name = host->encalloc;
3489 infof(data, "IDN support not present, can't parse Unicode domains\n");
3494 static void llist_dtor(void *user, void *element)
3502 * Allocate and initialize a new connectdata object.
3504 static struct connectdata *allocate_conn(struct SessionHandle *data)
3506 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3510 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
3511 already from start to avoid NULL
3512 situations and checks */
3514 /* and we setup a few fields in case we end up actually using this struct */
3516 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3517 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3518 conn->connection_id = -1; /* no ID */
3519 conn->port = -1; /* unknown at this point */
3521 /* Default protocol-independent behavior doesn't support persistent
3522 connections, so we set this to force-close. Protocols that support
3523 this need to set this to FALSE in their "curl_do" functions. */
3524 conn->bits.close = TRUE;
3526 /* Store creation time to help future close decision making */
3527 conn->created = Curl_tvnow();
3529 conn->data = data; /* Setup the association between this connection
3530 and the SessionHandle */
3532 conn->proxytype = data->set.proxytype; /* type */
3534 #ifdef CURL_DISABLE_PROXY
3536 conn->bits.proxy = FALSE;
3537 conn->bits.httpproxy = FALSE;
3538 conn->bits.proxy_user_passwd = FALSE;
3539 conn->bits.tunnel_proxy = FALSE;
3541 #else /* CURL_DISABLE_PROXY */
3543 /* note that these two proxy bits are now just on what looks to be
3544 requested, they may be altered down the road */
3545 conn->bits.proxy = (data->set.str[STRING_PROXY] &&
3546 *data->set.str[STRING_PROXY])?TRUE:FALSE;
3547 conn->bits.httpproxy = (conn->bits.proxy &&
3548 (conn->proxytype == CURLPROXY_HTTP ||
3549 conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE;
3550 conn->bits.proxy_user_passwd =
3551 (NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE;
3552 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3554 #endif /* CURL_DISABLE_PROXY */
3556 conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE;
3557 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3558 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3560 conn->verifypeer = data->set.ssl.verifypeer;
3561 conn->verifyhost = data->set.ssl.verifyhost;
3563 conn->ip_version = data->set.ipver;
3565 #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
3566 conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
3567 conn->ntlm_auth_hlpr_pid = 0;
3568 conn->challenge_header = NULL;
3569 conn->response_header = NULL;
3572 if(Curl_multi_pipeline_enabled(data->multi) &&
3573 !conn->master_buffer) {
3574 /* Allocate master_buffer to be used for pipelining */
3575 conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3576 if(!conn->master_buffer)
3580 /* Initialize the pipeline lists */
3581 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3582 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3583 if(!conn->send_pipe || !conn->recv_pipe)
3586 #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI)
3587 conn->data_prot = PROT_CLEAR;
3590 /* Store the local bind parameters that will be used for this connection */
3591 if(data->set.str[STRING_DEVICE]) {
3592 conn->localdev = strdup(data->set.str[STRING_DEVICE]);
3596 conn->localportrange = data->set.localportrange;
3597 conn->localport = data->set.localport;
3599 /* the close socket stuff needs to be copied to the connection struct as
3600 it may live on without (this specific) SessionHandle */
3601 conn->fclosesocket = data->set.fclosesocket;
3602 conn->closesocket_client = data->set.closesocket_client;
3607 Curl_llist_destroy(conn->send_pipe, NULL);
3608 Curl_llist_destroy(conn->recv_pipe, NULL);
3610 conn->send_pipe = NULL;
3611 conn->recv_pipe = NULL;
3613 Curl_safefree(conn->master_buffer);
3614 Curl_safefree(conn->localdev);
3615 Curl_safefree(conn);
3619 static CURLcode findprotocol(struct SessionHandle *data,
3620 struct connectdata *conn,
3621 const char *protostr)
3623 const struct Curl_handler * const *pp;
3624 const struct Curl_handler *p;
3626 /* Scan protocol handler table and match against 'protostr' to set a few
3627 variables based on the URL. Now that the handler may be changed later
3628 when the protocol specific setup function is called. */
3629 for(pp = protocols; (p = *pp) != NULL; pp++) {
3630 if(Curl_raw_equal(p->scheme, protostr)) {
3631 /* Protocol found in table. Check if allowed */
3632 if(!(data->set.allowed_protocols & p->protocol))
3636 /* it is allowed for "normal" request, now do an extra check if this is
3637 the result of a redirect */
3638 if(data->state.this_is_a_follow &&
3639 !(data->set.redir_protocols & p->protocol))
3643 /* Perform setup complement if some. */
3644 conn->handler = conn->given = p;
3646 /* 'port' and 'remote_port' are set in setup_connection_internals() */
3652 /* The protocol was not found in the table, but we don't have to assign it
3653 to anything since it is already assigned to a dummy-struct in the
3654 create_conn() function when the connectdata struct is allocated. */
3655 failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
3658 return CURLE_UNSUPPORTED_PROTOCOL;
3662 * Parse URL and fill in the relevant members of the connection struct.
3664 static CURLcode parseurlandfillconn(struct SessionHandle *data,
3665 struct connectdata *conn,
3667 char *user, char *passwd, char *options)
3671 char *path = data->state.path;
3677 bool fix_slash = FALSE;
3679 *prot_missing = FALSE;
3681 /*************************************************************
3684 * We need to parse the url even when using the proxy, because we will need
3685 * the hostname and port in case we are trying to SSL connect through the
3686 * proxy -- and we don't know if we will need to use SSL until we parse the
3688 ************************************************************/
3689 if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
3691 Curl_raw_equal(protobuf, "file")) {
3692 if(path[0] == '/' && path[1] == '/') {
3693 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
3694 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
3695 * file://localhost/<path> is similar to how other schemes treat missing
3696 * hostnames. See RFC 1808. */
3698 /* This cannot be done with strcpy() in a portable manner, since the
3699 memory areas overlap! */
3700 memmove(path, path + 2, strlen(path + 2)+1);
3703 * we deal with file://<host>/<path> differently since it supports no
3704 * hostname other than "localhost" and "127.0.0.1", which is unique among
3705 * the URL protocols specified in RFC 1738
3707 if(path[0] != '/') {
3708 /* the URL included a host name, we ignore host names in file:// URLs
3709 as the standards don't define what to do with them */
3710 char *ptr=strchr(path, '/');
3712 /* there was a slash present
3714 RFC1738 (section 3.1, page 5) says:
3716 The rest of the locator consists of data specific to the scheme,
3717 and is known as the "url-path". It supplies the details of how the
3718 specified resource can be accessed. Note that the "/" between the
3719 host (or port) and the url-path is NOT part of the url-path.
3721 As most agents use file://localhost/foo to get '/foo' although the
3722 slash preceding foo is a separator and not a slash for the path,
3723 a URL as file://localhost//foo must be valid as well, to refer to
3724 the same file with an absolute path.
3727 if(ptr[1] && ('/' == ptr[1]))
3728 /* if there was two slashes, we skip the first one as that is then
3729 used truly as a separator */
3732 /* This cannot be made with strcpy, as the memory chunks overlap! */
3733 memmove(path, ptr, strlen(ptr)+1);
3737 protop = "file"; /* protocol string */
3743 if(2 > sscanf(data->change.url,
3744 "%15[^\n:]://%[^\n/?]%[^\n]",
3746 conn->host.name, path)) {
3749 * The URL was badly formatted, let's try the browser-style _without_
3750 * protocol specified like 'http://'.
3752 rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
3755 * We couldn't even get this format.
3756 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
3757 * assigned, but the return value is EOF!
3759 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
3760 if(!(rc == -1 && *conn->host.name))
3763 failf(data, "<url> malformed");
3764 return CURLE_URL_MALFORMAT;
3769 * Since there was no protocol part specified, we guess what protocol it
3770 * is based on the first letters of the server name.
3773 /* Note: if you add a new protocol, please update the list in
3774 * lib/version.c too! */
3776 if(checkprefix("FTP.", conn->host.name))
3778 else if(checkprefix("DICT.", conn->host.name))
3780 else if(checkprefix("LDAP.", conn->host.name))
3782 else if(checkprefix("IMAP.", conn->host.name))
3788 *prot_missing = TRUE; /* not given in URL */
3794 /* We search for '?' in the host name (but only on the right side of a
3795 * @-letter to allow ?-letters in username and password) to handle things
3796 * like http://example.com?param= (notice the missing '/').
3798 at = strchr(conn->host.name, '@');
3800 query = strchr(at+1, '?');
3802 query = strchr(conn->host.name, '?');
3805 /* We must insert a slash before the '?'-letter in the URL. If the URL had
3806 a slash after the '?', that is where the path currently begins and the
3807 '?string' is still part of the host name.
3809 We must move the trailing part from the host name and put it first in
3810 the path. And have it all prefixed with a slash.
3813 size_t hostlen = strlen(query);
3814 size_t pathlen = strlen(path);
3816 /* move the existing path plus the zero byte forward, to make room for
3817 the host-name part */
3818 memmove(path+hostlen+1, path, pathlen+1);
3820 /* now copy the trailing host part in front of the existing path */
3821 memcpy(path+1, query, hostlen);
3823 path[0]='/'; /* prepend the missing slash */
3826 *query=0; /* now cut off the hostname at the ? */
3829 /* if there's no path set, use a single slash */
3834 /* If the URL is malformatted (missing a '/' after hostname before path) we
3835 * insert a slash here. The only letter except '/' we accept to start a path
3838 if(path[0] == '?') {
3839 /* We need this function to deal with overlapping memory areas. We know
3840 that the memory area 'path' points to is 'urllen' bytes big and that
3841 is bigger than the path. Use +1 to move the zero byte too. */
3842 memmove(&path[1], path, strlen(path)+1);
3849 * "fix_slash" means that the URL was malformatted so we need to generate an
3850 * updated version with the new slash inserted at the right place! We need
3851 * the corrected URL when communicating over HTTP proxy and we don't know at
3852 * this point if we're using a proxy or not.
3857 size_t plen = strlen(path); /* new path, should be 1 byte longer than
3859 size_t urllen = strlen(data->change.url); /* original URL length */
3861 reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */
3863 return CURLE_OUT_OF_MEMORY;
3865 /* copy the prefix */
3866 memcpy(reurl, data->change.url, urllen - (plen-1));
3868 /* append the trailing piece + zerobyte */
3869 memcpy(&reurl[urllen - (plen-1)], path, plen + 1);
3871 /* possible free the old one */
3872 if(data->change.url_alloc) {
3873 Curl_safefree(data->change.url);
3874 data->change.url_alloc = FALSE;
3877 data->change.url = reurl;
3878 data->change.url_alloc = TRUE; /* free this later */
3882 * Parse the login details from the URL and strip them out of
3885 result = parse_url_login(data, conn, user, passwd, options);
3886 if(result != CURLE_OK)
3889 if(conn->host.name[0] == '[') {
3890 /* This looks like an IPv6 address literal. See if there is an address
3892 char *percent = strstr (conn->host.name, "%25");
3895 unsigned long scope = strtoul (percent + 3, &endp, 10);
3897 /* The address scope was well formed. Knock it out of the
3899 memmove(percent, endp, strlen(endp)+1);
3900 if(!data->state.this_is_a_follow)
3901 /* Don't honour a scope given in a Location: header */
3902 conn->scope = (unsigned int)scope;
3905 infof(data, "Invalid IPv6 address format\n");
3910 /* Override any scope that was set above. */
3911 conn->scope = data->set.scope;
3913 /* Remove the fragment part of the path. Per RFC 2396, this is always the
3914 last part of the URI. We are looking for the first '#' so that we deal
3915 gracefully with non conformant URI such as http://example.com#foo#bar. */
3916 fragment = strchr(path, '#');
3920 /* we know the path part ended with a fragment, so we know the full URL
3921 string does too and we need to cut it off from there so it isn't used
3923 fragment = strchr(data->change.url, '#');
3929 * So if the URL was A://B/C#D,
3931 * conn->host.name is B
3932 * data->state.path is /C
3935 return findprotocol(data, conn, protop);
3939 * If we're doing a resumed transfer, we need to setup our stuff
3942 static CURLcode setup_range(struct SessionHandle *data)
3944 struct UrlState *s = &data->state;
3945 s->resume_from = data->set.set_resume_from;
3946 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
3947 if(s->rangestringalloc)
3951 s->range = aprintf("%" FORMAT_OFF_TU "-", s->resume_from);
3953 s->range = strdup(data->set.str[STRING_SET_RANGE]);
3955 s->rangestringalloc = (s->range)?TRUE:FALSE;
3958 return CURLE_OUT_OF_MEMORY;
3960 /* tell ourselves to fetch this range */
3961 s->use_range = TRUE; /* enable range download */
3964 s->use_range = FALSE; /* disable range download */
3970 /***************************************************************
3971 * Setup connection internals specific to the requested protocol.
3972 * This MUST get called after proxy magic has been figured out.
3973 ***************************************************************/
3974 static CURLcode setup_connection_internals(struct connectdata *conn)
3976 const struct Curl_handler * p;
3979 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
3981 /* Scan protocol handler table. */
3983 /* Perform setup complement if some. */
3986 if(p->setup_connection) {
3987 result = (*p->setup_connection)(conn);
3989 if(result != CURLE_OK)
3992 p = conn->handler; /* May have changed. */
3996 /* we check for -1 here since if proxy was detected already, this
3997 was very likely already set to the proxy port */
3998 conn->port = p->defport;
3999 conn->remote_port = (unsigned short)conn->given->defport;
4004 #ifndef CURL_DISABLE_PROXY
4005 /****************************************************************
4006 * Checks if the host is in the noproxy list. returns true if it matches
4007 * and therefore the proxy should NOT be used.
4008 ****************************************************************/
4009 static bool check_noproxy(const char* name, const char* no_proxy)
4011 /* no_proxy=domain1.dom,host.domain2.dom
4012 * (a comma-separated list of hosts which should
4013 * not be proxied, or an asterisk to override
4014 * all proxy variables)
4018 const char* separator = ", ";
4019 size_t no_proxy_len;
4023 if(no_proxy && no_proxy[0]) {
4024 if(Curl_raw_equal("*", no_proxy)) {
4028 /* NO_PROXY was specified and it wasn't just an asterisk */
4030 no_proxy_len = strlen(no_proxy);
4031 endptr = strchr(name, ':');
4033 namelen = endptr - name;
4035 namelen = strlen(name);
4037 for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
4038 while(tok_start < no_proxy_len &&
4039 strchr(separator, no_proxy[tok_start]) != NULL) {
4040 /* Look for the beginning of the token. */
4044 if(tok_start == no_proxy_len)
4045 break; /* It was all trailing separator chars, no more tokens. */
4047 for(tok_end = tok_start; tok_end < no_proxy_len &&
4048 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
4049 /* Look for the end of the token. */
4052 /* To match previous behaviour, where it was necessary to specify
4053 * ".local.com" to prevent matching "notlocal.com", we will leave
4056 if(no_proxy[tok_start] == '.')
4059 if((tok_end - tok_start) <= namelen) {
4060 /* Match the last part of the name to the domain we are checking. */
4061 const char *checkn = name + namelen - (tok_end - tok_start);
4062 if(Curl_raw_nequal(no_proxy + tok_start, checkn,
4063 tok_end - tok_start)) {
4064 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
4065 /* We either have an exact match, or the previous character is a .
4066 * so it is within the same domain, so no proxy for this host.
4071 } /* if((tok_end - tok_start) <= namelen) */
4072 } /* for(tok_start = 0; tok_start < no_proxy_len;
4073 tok_start = tok_end + 1) */
4074 } /* NO_PROXY was specified and it wasn't just an asterisk */
4079 /****************************************************************
4080 * Detect what (if any) proxy to use. Remember that this selects a host
4081 * name and is not limited to HTTP proxies only.
4082 * The returned pointer must be freed by the caller (unless NULL)
4083 ****************************************************************/
4084 static char *detect_proxy(struct connectdata *conn)
4088 #ifndef CURL_DISABLE_HTTP
4089 /* If proxy was not specified, we check for default proxy environment
4090 * variables, to enable i.e Lynx compliance:
4092 * http_proxy=http://some.server.dom:port/
4093 * https_proxy=http://some.server.dom:port/
4094 * ftp_proxy=http://some.server.dom:port/
4095 * no_proxy=domain1.dom,host.domain2.dom
4096 * (a comma-separated list of hosts which should
4097 * not be proxied, or an asterisk to override
4098 * all proxy variables)
4099 * all_proxy=http://some.server.dom:port/
4100 * (seems to exist for the CERN www lib. Probably
4101 * the first to check for.)
4103 * For compatibility, the all-uppercase versions of these variables are
4104 * checked if the lowercase versions don't exist.
4106 char *no_proxy=NULL;
4107 char proxy_env[128];
4109 no_proxy=curl_getenv("no_proxy");
4111 no_proxy=curl_getenv("NO_PROXY");
4113 if(!check_noproxy(conn->host.name, no_proxy)) {
4114 /* It was not listed as without proxy */
4115 const char *protop = conn->handler->scheme;
4116 char *envp = proxy_env;
4119 /* Now, build <protocol>_proxy and check for such a one to use */
4121 *envp++ = (char)tolower((int)*protop++);
4124 strcpy(envp, "_proxy");
4126 /* read the protocol proxy: */
4127 prox=curl_getenv(proxy_env);
4130 * We don't try the uppercase version of HTTP_PROXY because of
4133 * When curl is used in a webserver application
4134 * environment (cgi or php), this environment variable can
4135 * be controlled by the web server user by setting the
4136 * http header 'Proxy:' to some value.
4138 * This can cause 'internal' http/ftp requests to be
4139 * arbitrarily redirected by any external attacker.
4141 if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4142 /* There was no lowercase variable, try the uppercase version: */
4143 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4144 prox=curl_getenv(proxy_env);
4147 if(prox && *prox) { /* don't count "" strings */
4148 proxy = prox; /* use this */
4151 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4153 proxy=curl_getenv("ALL_PROXY");
4155 } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4160 #else /* !CURL_DISABLE_HTTP */
4163 #endif /* CURL_DISABLE_HTTP */
4169 * If this is supposed to use a proxy, we need to figure out the proxy
4170 * host name, so that we can re-use an existing connection
4171 * that may exist registered to the same proxy host.
4172 * proxy will be freed before this function returns.
4174 static CURLcode parse_proxy(struct SessionHandle *data,
4175 struct connectdata *conn, char *proxy)
4180 /* We use 'proxyptr' to point to the proxy name from now on... */
4185 /* We do the proxy host string parsing here. We want the host name and the
4186 * port name. Accept a protocol:// prefix
4189 /* Parse the protocol part if present */
4190 endofprot = strstr(proxy, "://");
4192 proxyptr = endofprot+3;
4193 if(checkprefix("socks5h", proxy))
4194 conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
4195 else if(checkprefix("socks5", proxy))
4196 conn->proxytype = CURLPROXY_SOCKS5;
4197 else if(checkprefix("socks4a", proxy))
4198 conn->proxytype = CURLPROXY_SOCKS4A;
4199 else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
4200 conn->proxytype = CURLPROXY_SOCKS4;
4201 /* Any other xxx:// : change to http proxy */
4204 proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
4206 /* Is there a username and password given in this proxy url? */
4207 atsign = strchr(proxyptr, '@');
4209 char proxyuser[MAX_CURL_USER_LENGTH];
4210 char proxypasswd[MAX_CURL_PASSWORD_LENGTH];
4213 if(1 <= sscanf(proxyptr,
4214 "%" MAX_CURL_USER_LENGTH_TXT"[^:@]:"
4215 "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4216 proxyuser, proxypasswd)) {
4217 CURLcode res = CURLE_OK;
4219 /* found user and password, rip them out. note that we are
4220 unescaping them, as there is otherwise no way to have a
4221 username or password with reserved characters like ':' in
4223 Curl_safefree(conn->proxyuser);
4224 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4226 if(!conn->proxyuser)
4227 res = CURLE_OUT_OF_MEMORY;
4229 Curl_safefree(conn->proxypasswd);
4230 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4232 if(!conn->proxypasswd)
4233 res = CURLE_OUT_OF_MEMORY;
4236 if(CURLE_OK == res) {
4237 conn->bits.proxy_user_passwd = TRUE; /* enable it */
4238 atsign++; /* the right side of the @-letter */
4241 proxyptr = atsign; /* now use this instead */
4243 res = CURLE_OUT_OF_MEMORY;
4251 /* start scanning for port number at this point */
4254 /* detect and extract RFC2732-style IPv6-addresses */
4255 if(*proxyptr == '[') {
4256 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4257 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
4261 /* yeps, it ended nicely with a bracket as well */
4264 infof(data, "Invalid IPv6 address format\n");
4266 /* Note that if this didn't end with a bracket, we still advanced the
4267 * proxyptr first, but I can't see anything wrong with that as no host
4268 * name nor a numeric can legally start with a bracket.
4272 /* Get port number off proxy.server.com:1080 */
4273 prox_portno = strchr(portptr, ':');
4275 *prox_portno = 0x0; /* cut off number from host name */
4277 /* now set the local port number */
4278 conn->port = strtol(prox_portno, NULL, 10);
4281 if(proxyptr[0]=='/')
4282 /* If the first character in the proxy string is a slash, fail
4283 immediately. The following code will otherwise clear the string which
4284 will lead to code running as if no proxy was set! */
4285 return CURLE_COULDNT_RESOLVE_PROXY;
4287 /* without a port number after the host name, some people seem to use
4288 a slash so we strip everything from the first slash */
4289 atsign = strchr(proxyptr, '/');
4291 *atsign = 0x0; /* cut off path part from host name */
4293 if(data->set.proxyport)
4294 /* None given in the proxy string, then get the default one if it is
4296 conn->port = data->set.proxyport;
4299 /* now, clone the cleaned proxy host name */
4300 conn->proxy.rawalloc = strdup(proxyptr);
4301 conn->proxy.name = conn->proxy.rawalloc;
4303 if(!conn->proxy.rawalloc)
4304 return CURLE_OUT_OF_MEMORY;
4310 * Extract the user and password from the authentication string
4312 static CURLcode parse_proxy_auth(struct SessionHandle *data,
4313 struct connectdata *conn)
4315 char proxyuser[MAX_CURL_USER_LENGTH]="";
4316 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4318 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4319 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4320 MAX_CURL_USER_LENGTH);
4321 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4323 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4324 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4325 MAX_CURL_PASSWORD_LENGTH);
4326 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4329 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4330 if(!conn->proxyuser)
4331 return CURLE_OUT_OF_MEMORY;
4333 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4334 if(!conn->proxypasswd)
4335 return CURLE_OUT_OF_MEMORY;
4339 #endif /* CURL_DISABLE_PROXY */
4344 * Parse the login details (user name, password and options) from the URL and
4345 * strip them out of the host name
4347 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4350 * Outputs: (almost :- all currently undefined)
4351 * conn->bits.user_passwd - non-zero if non-default passwords exist
4352 * user - non-zero length if defined
4353 * passwd - non-zero length if defined
4354 * options - non-zero length if defined
4355 * conn->host.name - remove user name and password
4357 static CURLcode parse_url_login(struct SessionHandle *data,
4358 struct connectdata *conn,
4359 char *user, char *passwd, char *options)
4361 CURLcode result = CURLE_OK;
4363 char *passwdp = NULL;
4364 char *optionsp = NULL;
4366 /* At this point, we're hoping all the other special cases have
4367 * been taken care of, so conn->host.name is at most
4368 * [user[:password][;options]]@]hostname
4370 * We need somewhere to put the embedded details, so do that first.
4373 char *ptr = strchr(conn->host.name, '@');
4374 char *login = conn->host.name;
4376 user[0] = 0; /* to make everything well-defined */
4380 /* We will now try to extract the
4381 * possible login information in a string like:
4382 * ftp://user:password@ftp.my.site:8021/README */
4384 /* There's login information to the left of the @ */
4386 conn->host.name = ++ptr;
4388 /* So the hostname is sane. Only bother interpreting the
4389 * results if we could care. It could still be wasted
4390 * work because it might be overtaken by the programmatically
4391 * set user/passwd, but doing that first adds more cases here :-(
4394 if(data->set.use_netrc != CURL_NETRC_REQUIRED) {
4395 /* We could use the login information in the URL so extract it */
4396 result = parse_login_details(login, ptr - login - 1,
4397 &userp, &passwdp, &optionsp);
4402 /* We have a user in the URL */
4403 conn->bits.userpwd_in_url = TRUE;
4404 conn->bits.user_passwd = TRUE; /* enable user+password */
4406 /* Decode the user */
4407 newname = curl_easy_unescape(data, userp, 0, NULL);
4409 return CURLE_OUT_OF_MEMORY;
4411 if(strlen(newname) < MAX_CURL_USER_LENGTH)
4412 strcpy(user, newname);
4418 /* We have a password in the URL so decode it */
4419 char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
4421 return CURLE_OUT_OF_MEMORY;
4423 if(strlen(newpasswd) < MAX_CURL_PASSWORD_LENGTH)
4424 strcpy(passwd, newpasswd);
4430 /* We have an options list in the URL so decode it */
4431 char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
4433 return CURLE_OUT_OF_MEMORY;
4435 if(strlen(newoptions) < MAX_CURL_OPTIONS_LENGTH)
4436 strcpy(options, newoptions);
4442 Curl_safefree(userp);
4443 Curl_safefree(passwdp);
4444 Curl_safefree(optionsp);
4452 * parse_login_details()
4454 * This is used to parse a login string for user name, password and options in
4455 * the following formats:
4459 * user:password;options
4461 * user;options:password
4469 * login [in] - The login string.
4470 * len [in] - The length of the login string.
4471 * userp [in/out] - The address where a pointer to newly allocated memory
4472 * holding the user will be stored upon completion.
4473 * passdwp [in/out] - The address where a pointer to newly allocated memory
4474 * holding the password will be stored upon completion.
4475 * optionsp [in/out] - The address where a pointer to newly allocated memory
4476 * holding the options will be stored upon completion.
4478 * Returns CURLE_OK on success.
4480 static CURLcode parse_login_details(const char *login, const size_t len,
4481 char **userp, char **passwdp,
4484 CURLcode result = CURLE_OK;
4488 const char *psep = NULL;
4489 const char *osep = NULL;
4494 /* Attempt to find the password separator */
4496 psep = strchr(login, ':');
4498 /* Within the constraint of the login string */
4499 if(psep >= login + len)
4503 /* Attempt to find the options separator */
4505 osep = strchr(login, ';');
4507 /* Within the constraint of the login string */
4508 if(osep >= login + len)
4512 /* Calculate the portion lengths */
4514 (size_t)(osep && psep > osep ? osep - login : psep - login) :
4515 (osep ? (size_t)(osep - login) : len));
4517 (osep && osep > psep ? (size_t)(osep - psep) :
4518 (size_t)(login + len - psep)) - 1 : 0);
4520 (psep && psep > osep ? (size_t)(psep - osep) :
4521 (size_t)(login + len - osep)) - 1 : 0);
4523 /* Allocate the user portion temporary buffer */
4525 utemp = malloc(ulen + 1);
4527 result = CURLE_OUT_OF_MEMORY;
4530 /* Allocate the password portion temporary buffer */
4531 if(!result && passwdp && plen) {
4532 ptemp = malloc(plen + 1);
4534 result = CURLE_OUT_OF_MEMORY;
4537 /* Allocate the options portion temporary buffer */
4538 if(!result && optionsp && olen) {
4539 otemp = malloc(olen + 1);
4541 result = CURLE_OUT_OF_MEMORY;
4545 /* Copy the user portion if necessary */
4547 memcpy(utemp, login, ulen);
4549 Curl_safefree(*userp);
4553 /* Copy the password portion if necessary */
4555 memcpy(ptemp, psep + 1, plen);
4557 Curl_safefree(*passwdp);
4561 /* Copy the options portion if necessary */
4563 memcpy(otemp, osep + 1, olen);
4565 Curl_safefree(*optionsp);
4573 /*************************************************************
4574 * Figure out the remote port number and fix it in the URL
4576 * No matter if we use a proxy or not, we have to figure out the remote
4577 * port number of various reasons.
4579 * To be able to detect port number flawlessly, we must not confuse them
4580 * IPv6-specified addresses in the [0::1] style. (RFC2732)
4582 * The conn->host.name is currently [user:passwd@]host[:port] where host
4583 * could be a hostname, IPv4 address or IPv6 address.
4585 * The port number embedded in the URL is replaced, if necessary.
4586 *************************************************************/
4587 static CURLcode parse_remote_port(struct SessionHandle *data,
4588 struct connectdata *conn)
4593 /* Note that at this point, the IPv6 address cannot contain any scope
4594 suffix as that has already been removed in the parseurlandfillconn()
4596 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
4598 (']' == endbracket)) {
4599 /* this is a RFC2732-style specified IP-address */
4600 conn->bits.ipv6_ip = TRUE;
4602 conn->host.name++; /* skip over the starting bracket */
4603 portptr = strchr(conn->host.name, ']');
4605 *portptr++ = '\0'; /* zero terminate, killing the bracket */
4607 portptr = NULL; /* no port number available */
4612 struct in6_addr in6;
4613 if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
4614 /* This is a numerical IPv6 address, meaning this is a wrongly formatted
4616 failf(data, "IPv6 numerical address used in URL without brackets");
4617 return CURLE_URL_MALFORMAT;
4621 portptr = strrchr(conn->host.name, ':');
4624 if(data->set.use_port && data->state.allow_port) {
4625 /* if set, we use this and ignore the port possibly given in the URL */
4626 conn->remote_port = (unsigned short)data->set.use_port;
4628 *portptr = '\0'; /* cut off the name there anyway - if there was a port
4629 number - since the port number is to be ignored! */
4630 if(conn->bits.httpproxy) {
4631 /* we need to create new URL with the new port number */
4635 if(conn->bits.type_set)
4636 snprintf(type, sizeof(type), ";type=%c",
4637 data->set.prefer_ascii?'A':
4638 (data->set.ftp_list_only?'D':'I'));
4641 * This synthesized URL isn't always right--suffixes like ;type=A are
4642 * stripped off. It would be better to work directly from the original
4643 * URL and simply replace the port part of it.
4645 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
4646 conn->bits.ipv6_ip?"[":"", conn->host.name,
4647 conn->bits.ipv6_ip?"]":"", conn->remote_port,
4648 data->state.slash_removed?"/":"", data->state.path,
4651 return CURLE_OUT_OF_MEMORY;
4653 if(data->change.url_alloc) {
4654 Curl_safefree(data->change.url);
4655 data->change.url_alloc = FALSE;
4658 data->change.url = url;
4659 data->change.url_alloc = TRUE;
4663 /* no CURLOPT_PORT given, extract the one from the URL */
4668 port=strtoul(portptr+1, &rest, 10); /* Port number must be decimal */
4670 if(rest != (portptr+1) && *rest == '\0') {
4671 /* The colon really did have only digits after it,
4672 * so it is either a port number or a mistake */
4674 if(port > 0xffff) { /* Single unix standard says port numbers are
4676 failf(data, "Port number too large: %lu", port);
4677 return CURLE_URL_MALFORMAT;
4680 *portptr = '\0'; /* cut off the name there */
4681 conn->remote_port = curlx_ultous(port);
4684 /* Browser behavior adaptation. If there's a colon with no digits after,
4685 just cut off the name there which makes us ignore the colon and just
4686 use the default port. Firefox and Chrome both do that. */
4693 * Override a user name and password from the URL with that in the
4694 * CURLOPT_USERPWD option or a .netrc file, if applicable.
4696 static void override_userpass(struct SessionHandle *data,
4697 struct connectdata *conn,
4698 char *user, char *passwd)
4700 if(data->set.str[STRING_USERNAME] != NULL) {
4701 strncpy(user, data->set.str[STRING_USERNAME], MAX_CURL_USER_LENGTH);
4702 user[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4704 if(data->set.str[STRING_PASSWORD] != NULL) {
4705 strncpy(passwd, data->set.str[STRING_PASSWORD], MAX_CURL_PASSWORD_LENGTH);
4706 passwd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4709 conn->bits.netrc = FALSE;
4710 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
4711 if(Curl_parsenetrc(conn->host.name,
4713 data->set.str[STRING_NETRC_FILE])) {
4714 infof(data, "Couldn't find host %s in the "
4715 DOT_CHAR "netrc file; using defaults\n",
4719 /* set bits.netrc TRUE to remember that we got the name from a .netrc
4720 file, so that it is safe to use even if we followed a Location: to a
4721 different host or similar. */
4722 conn->bits.netrc = TRUE;
4724 conn->bits.user_passwd = TRUE; /* enable user+password */
4730 * Set password so it's available in the connection.
4732 static CURLcode set_login(struct connectdata *conn,
4733 const char *user, const char *passwd,
4734 const char *options)
4736 CURLcode result = CURLE_OK;
4738 /* If our protocol needs a password and we have none, use the defaults */
4739 if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
4740 /* Store the default user */
4741 conn->user = strdup(CURL_DEFAULT_USER);
4743 /* Store the default password */
4745 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
4747 conn->passwd = NULL;
4749 /* This is the default password, so DON'T set conn->bits.user_passwd */
4752 /* Store the user, zero-length if not set */
4753 conn->user = strdup(user);
4755 /* Store the password (only if user is present), zero-length if not set */
4757 conn->passwd = strdup(passwd);
4759 conn->passwd = NULL;
4762 if(!conn->user || !conn->passwd)
4763 result = CURLE_OUT_OF_MEMORY;
4765 /* Store the options, null if not set */
4766 if(!result && options[0]) {
4767 conn->options = strdup(options);
4770 result = CURLE_OUT_OF_MEMORY;
4776 /*************************************************************
4777 * Resolve the address of the server or proxy
4778 *************************************************************/
4779 static CURLcode resolve_server(struct SessionHandle *data,
4780 struct connectdata *conn,
4783 CURLcode result=CURLE_OK;
4784 long timeout_ms = Curl_timeleft(data, NULL, TRUE);
4786 /*************************************************************
4787 * Resolve the name of the server or proxy
4788 *************************************************************/
4789 if(conn->bits.reuse)
4790 /* We're reusing the connection - no need to resolve anything, and
4791 fix_hostname() was called already in create_conn() for the re-use
4796 /* this is a fresh connect */
4798 struct Curl_dns_entry *hostaddr;
4800 /* set a pointer to the hostname we display */
4801 fix_hostname(data, conn, &conn->host);
4803 if(!conn->proxy.name || !*conn->proxy.name) {
4804 /* If not connecting via a proxy, extract the port from the URL, if it is
4805 * there, thus overriding any defaults that might have been set above. */
4806 conn->port = conn->remote_port; /* it is the same port */
4808 /* Resolve target host right on */
4809 rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
4810 &hostaddr, timeout_ms);
4811 if(rc == CURLRESOLV_PENDING)
4814 else if(rc == CURLRESOLV_TIMEDOUT)
4815 result = CURLE_OPERATION_TIMEDOUT;
4817 else if(!hostaddr) {
4818 failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
4819 result = CURLE_COULDNT_RESOLVE_HOST;
4820 /* don't return yet, we need to clean up the timeout first */
4824 /* This is a proxy that hasn't been resolved yet. */
4826 /* IDN-fix the proxy name */
4827 fix_hostname(data, conn, &conn->proxy);
4830 rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
4831 &hostaddr, timeout_ms);
4833 if(rc == CURLRESOLV_PENDING)
4836 else if(rc == CURLRESOLV_TIMEDOUT)
4837 result = CURLE_OPERATION_TIMEDOUT;
4839 else if(!hostaddr) {
4840 failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
4841 result = CURLE_COULDNT_RESOLVE_PROXY;
4842 /* don't return yet, we need to clean up the timeout first */
4845 DEBUGASSERT(conn->dns_entry == NULL);
4846 conn->dns_entry = hostaddr;
4853 * Cleanup the connection just allocated before we can move along and use the
4854 * previously existing one. All relevant data is copied over and old_conn is
4855 * ready for freeing once this function returns.
4857 static void reuse_conn(struct connectdata *old_conn,
4858 struct connectdata *conn)
4860 if(old_conn->proxy.rawalloc)
4861 free(old_conn->proxy.rawalloc);
4863 /* free the SSL config struct from this connection struct as this was
4864 allocated in vain and is targeted for destruction */
4865 Curl_free_ssl_config(&old_conn->ssl_config);
4867 conn->data = old_conn->data;
4869 /* get the user+password information from the old_conn struct since it may
4870 * be new for this request even when we re-use an existing connection */
4871 conn->bits.user_passwd = old_conn->bits.user_passwd;
4872 if(conn->bits.user_passwd) {
4873 /* use the new user name and password though */
4874 Curl_safefree(conn->user);
4875 Curl_safefree(conn->passwd);
4876 conn->user = old_conn->user;
4877 conn->passwd = old_conn->passwd;
4878 old_conn->user = NULL;
4879 old_conn->passwd = NULL;
4882 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
4883 if(conn->bits.proxy_user_passwd) {
4884 /* use the new proxy user name and proxy password though */
4885 Curl_safefree(conn->proxyuser);
4886 Curl_safefree(conn->proxypasswd);
4887 conn->proxyuser = old_conn->proxyuser;
4888 conn->proxypasswd = old_conn->proxypasswd;
4889 old_conn->proxyuser = NULL;
4890 old_conn->proxypasswd = NULL;
4893 /* host can change, when doing keepalive with a proxy or if the case is
4894 different this time etc */
4895 Curl_safefree(conn->host.rawalloc);
4896 conn->host=old_conn->host;
4898 /* persist connection info in session handle */
4899 Curl_persistconninfo(conn);
4902 conn->bits.reuse = TRUE; /* yes, we're re-using here */
4904 Curl_safefree(old_conn->user);
4905 Curl_safefree(old_conn->passwd);
4906 Curl_safefree(old_conn->proxyuser);
4907 Curl_safefree(old_conn->proxypasswd);
4908 Curl_safefree(old_conn->localdev);
4910 Curl_llist_destroy(old_conn->send_pipe, NULL);
4911 Curl_llist_destroy(old_conn->recv_pipe, NULL);
4913 old_conn->send_pipe = NULL;
4914 old_conn->recv_pipe = NULL;
4916 Curl_safefree(old_conn->master_buffer);
4920 * create_conn() sets up a new connectdata struct, or re-uses an already
4921 * existing one, and resolves host name.
4923 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
4924 * response will be coming asynchronously. If *async is FALSE, the name is
4927 * @param data The sessionhandle pointer
4928 * @param in_connect is set to the next connection data pointer
4929 * @param async is set TRUE when an async DNS resolution is pending
4930 * @see Curl_setup_conn()
4932 * *NOTE* this function assigns the conn->data pointer!
4935 static CURLcode create_conn(struct SessionHandle *data,
4936 struct connectdata **in_connect,
4939 CURLcode result = CURLE_OK;
4940 struct connectdata *conn;
4941 struct connectdata *conn_temp = NULL;
4943 char user[MAX_CURL_USER_LENGTH];
4944 char passwd[MAX_CURL_PASSWORD_LENGTH];
4945 char options[MAX_CURL_OPTIONS_LENGTH];
4948 bool prot_missing = FALSE;
4949 bool no_connections_available = FALSE;
4951 size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
4952 size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
4956 /*************************************************************
4958 *************************************************************/
4960 if(!data->change.url)
4961 return CURLE_URL_MALFORMAT;
4963 /* First, split up the current URL in parts so that we can use the
4964 parts for checking against the already present connections. In order
4965 to not have to modify everything at once, we allocate a temporary
4966 connection data struct and fill in for comparison purposes. */
4967 conn = allocate_conn(data);
4970 return CURLE_OUT_OF_MEMORY;
4972 /* We must set the return variable as soon as possible, so that our
4973 parent can cleanup any possible allocs we may have done before
4977 /* This initing continues below, see the comment "Continue connectdata
4978 * initialization here" */
4980 /***********************************************************
4981 * We need to allocate memory to store the path in. We get the size of the
4982 * full URL to be sure, and we need to make it at least 256 bytes since
4983 * other parts of the code will rely on this fact
4984 ***********************************************************/
4985 #define LEAST_PATH_ALLOC 256
4986 urllen=strlen(data->change.url);
4987 if(urllen < LEAST_PATH_ALLOC)
4988 urllen=LEAST_PATH_ALLOC;
4991 * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
4992 * 1 - an extra terminating zero
4993 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
4996 Curl_safefree(data->state.pathbuffer);
4997 data->state.path = NULL;
4999 data->state.pathbuffer = malloc(urllen+2);
5000 if(NULL == data->state.pathbuffer)
5001 return CURLE_OUT_OF_MEMORY; /* really bad error */
5002 data->state.path = data->state.pathbuffer;
5004 conn->host.rawalloc = malloc(urllen+2);
5005 if(NULL == conn->host.rawalloc) {
5006 Curl_safefree(data->state.pathbuffer);
5007 data->state.path = NULL;
5008 return CURLE_OUT_OF_MEMORY;
5011 conn->host.name = conn->host.rawalloc;
5012 conn->host.name[0] = 0;
5014 result = parseurlandfillconn(data, conn, &prot_missing, user, passwd,
5016 if(result != CURLE_OK)
5019 /*************************************************************
5020 * No protocol part in URL was used, add it!
5021 *************************************************************/
5023 /* We're guessing prefixes here and if we're told to use a proxy or if
5024 we're gonna follow a Location: later or... then we need the protocol
5025 part added so that we have a valid URL. */
5028 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
5031 Curl_safefree(proxy);
5032 return CURLE_OUT_OF_MEMORY;
5035 if(data->change.url_alloc) {
5036 Curl_safefree(data->change.url);
5037 data->change.url_alloc = FALSE;
5040 data->change.url = reurl;
5041 data->change.url_alloc = TRUE; /* free this later */
5044 /*************************************************************
5045 * If the protocol can't handle url query strings, then cut
5046 * of the unhandable part
5047 *************************************************************/
5048 if((conn->given->flags&PROTOPT_NOURLQUERY)) {
5049 char *path_q_sep = strchr(conn->data->state.path, '?');
5051 /* according to rfc3986, allow the query (?foo=bar)
5052 also on protocols that can't handle it.
5054 cut the string-part after '?'
5057 /* terminate the string */
5062 #ifndef CURL_DISABLE_PROXY
5063 /*************************************************************
5064 * Extract the user and password from the authentication string
5065 *************************************************************/
5066 if(conn->bits.proxy_user_passwd) {
5067 result = parse_proxy_auth(data, conn);
5068 if(result != CURLE_OK)
5072 /*************************************************************
5073 * Detect what (if any) proxy to use
5074 *************************************************************/
5075 if(data->set.str[STRING_PROXY]) {
5076 proxy = strdup(data->set.str[STRING_PROXY]);
5077 /* if global proxy is set, this is it */
5079 failf(data, "memory shortage");
5080 return CURLE_OUT_OF_MEMORY;
5084 if(data->set.str[STRING_NOPROXY] &&
5085 check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
5087 free(proxy); /* proxy is in exception list */
5092 proxy = detect_proxy(conn);
5094 if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
5095 free(proxy); /* Don't bother with an empty proxy string or if the
5096 protocol doesn't work with network */
5100 /***********************************************************************
5101 * If this is supposed to use a proxy, we need to figure out the proxy host
5102 * name, proxy type and port number, so that we can re-use an existing
5103 * connection that may exist registered to the same proxy host.
5104 ***********************************************************************/
5106 result = parse_proxy(data, conn, proxy);
5108 free(proxy); /* parse_proxy copies the proxy string */
5113 if((conn->proxytype == CURLPROXY_HTTP) ||
5114 (conn->proxytype == CURLPROXY_HTTP_1_0)) {
5115 #ifdef CURL_DISABLE_HTTP
5116 /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
5117 return CURLE_UNSUPPORTED_PROTOCOL;
5119 /* force this connection's protocol to become HTTP if not already
5120 compatible - if it isn't tunneling through */
5121 if(!(conn->handler->protocol & CURLPROTO_HTTP) &&
5122 !conn->bits.tunnel_proxy)
5123 conn->handler = &Curl_handler_http;
5125 conn->bits.httpproxy = TRUE;
5129 conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
5130 conn->bits.proxy = TRUE;
5133 /* we aren't using the proxy after all... */
5134 conn->bits.proxy = FALSE;
5135 conn->bits.httpproxy = FALSE;
5136 conn->bits.proxy_user_passwd = FALSE;
5137 conn->bits.tunnel_proxy = FALSE;
5140 #endif /* CURL_DISABLE_PROXY */
5142 /*************************************************************
5143 * Setup internals depending on protocol. Needs to be done after
5144 * we figured out what/if proxy to use.
5145 *************************************************************/
5146 result = setup_connection_internals(conn);
5147 if(result != CURLE_OK) {
5148 Curl_safefree(proxy);
5152 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
5153 conn->send[FIRSTSOCKET] = Curl_send_plain;
5154 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
5155 conn->send[SECONDARYSOCKET] = Curl_send_plain;
5157 /***********************************************************************
5158 * file: is a special case in that it doesn't need a network connection
5159 ***********************************************************************/
5160 #ifndef CURL_DISABLE_FILE
5161 if(conn->handler->flags & PROTOPT_NONETWORK) {
5163 /* this is supposed to be the connect function so we better at least check
5164 that the file is present here! */
5165 DEBUGASSERT(conn->handler->connect_it);
5166 result = conn->handler->connect_it(conn, &done);
5168 /* Setup a "faked" transfer that'll do nothing */
5169 if(CURLE_OK == result) {
5171 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
5173 ConnectionStore(data, conn);
5176 * Setup whatever necessary for a resumed transfer
5178 result = setup_range(data);
5180 DEBUGASSERT(conn->handler->done);
5181 /* we ignore the return code for the protocol-specific DONE */
5182 (void)conn->handler->done(conn, result, FALSE);
5186 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
5187 -1, NULL); /* no upload */
5194 /*************************************************************
5195 * If the protocol is using SSL and HTTP proxy is used, we set
5196 * the tunnel_proxy bit.
5197 *************************************************************/
5198 if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
5199 conn->bits.tunnel_proxy = TRUE;
5201 /*************************************************************
5202 * Figure out the remote port number and fix it in the URL
5203 *************************************************************/
5204 result = parse_remote_port(data, conn);
5205 if(result != CURLE_OK)
5208 /*************************************************************
5209 * Check for an overridden user name and password, then set it
5211 *************************************************************/
5212 override_userpass(data, conn, user, passwd);
5213 result = set_login(conn, user, passwd, options);
5214 if(result != CURLE_OK)
5217 /* Get a cloned copy of the SSL config situation stored in the
5218 connection struct. But to get this going nicely, we must first make
5219 sure that the strings in the master copy are pointing to the correct
5220 strings in the session handle strings array!
5222 Keep in mind that the pointers in the master copy are pointing to strings
5223 that will be freed as part of the SessionHandle struct, but all cloned
5224 copies will be separately allocated.
5226 data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
5227 data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
5228 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
5229 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
5230 data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
5231 data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
5232 data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
5234 data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
5235 data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
5238 if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
5239 return CURLE_OUT_OF_MEMORY;
5241 /*************************************************************
5242 * Check the current list of connections to see if we can
5243 * re-use an already existing one or if we have to create a
5245 *************************************************************/
5247 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
5248 we only acknowledge this option if this is not a re-used connection
5249 already (which happens due to follow-location or during a HTTP
5250 authentication phase). */
5251 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
5254 reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse);
5256 /* If we found a reusable connection, we may still want to
5257 open a new connection if we are pipelining. */
5258 if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
5259 size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
5261 infof(data, "Found connection %d, with requests in the pipe (%d)\n",
5262 conn_temp->connection_id, pipelen);
5264 if(conn_temp->bundle->num_connections < max_host_connections &&
5265 data->state.conn_cache->num_connections < max_total_connections) {
5266 /* We want a new connection anyway */
5269 infof(data, "We can reuse, but we want a new connection anyway\n");
5276 * We already have a connection for this, we got the former connection
5277 * in the conn_temp variable and thus we need to cleanup the one we
5278 * just allocated before we can move along and use the previously
5281 conn_temp->inuse = TRUE; /* mark this as being in use so that no other
5282 handle in a multi stack may nick it */
5283 reuse_conn(conn, conn_temp);
5284 free(conn); /* we don't need this anymore */
5288 /* set a pointer to the hostname we display */
5289 fix_hostname(data, conn, &conn->host);
5291 infof(data, "Re-using existing connection! (#%ld) with host %s\n",
5292 conn->connection_id,
5293 conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
5296 /* We have decided that we want a new connection. However, we may not
5297 be able to do that if we have reached the limit of how many
5298 connections we are allowed to open. */
5299 struct connectbundle *bundle;
5301 bundle = Curl_conncache_find_bundle(data->state.conn_cache,
5303 if(max_host_connections > 0 && bundle &&
5304 (bundle->num_connections >= max_host_connections)) {
5305 struct connectdata *conn_candidate;
5307 /* The bundle is full. Let's see if we can kill a connection. */
5308 conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
5310 if(conn_candidate) {
5311 /* Set the connection's owner correctly, then kill it */
5312 conn_candidate->data = data;
5313 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
5316 no_connections_available = TRUE;
5319 if(max_total_connections > 0 &&
5320 (data->state.conn_cache->num_connections >= max_total_connections)) {
5321 struct connectdata *conn_candidate;
5323 /* The cache is full. Let's see if we can kill a connection. */
5324 conn_candidate = find_oldest_idle_connection(data);
5326 if(conn_candidate) {
5327 /* Set the connection's owner correctly, then kill it */
5328 conn_candidate->data = data;
5329 (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
5332 no_connections_available = TRUE;
5336 if(no_connections_available) {
5337 infof(data, "No connections available.\n");
5342 return CURLE_NO_CONNECTION_AVAILABLE;
5346 * This is a brand new connection, so let's store it in the connection
5349 ConnectionStore(data, conn);
5353 /* Mark the connection as used */
5356 /* Setup and init stuff before DO starts, in preparing for the transfer. */
5360 * Setup whatever necessary for a resumed transfer
5362 result = setup_range(data);
5366 /* Continue connectdata initialization here. */
5369 * Inherit the proper values from the urldata struct AFTER we have arranged
5370 * the persistent connection stuff
5372 conn->fread_func = data->set.fread_func;
5373 conn->fread_in = data->set.in;
5374 conn->seek_func = data->set.seek_func;
5375 conn->seek_client = data->set.seek_client;
5377 /*************************************************************
5378 * Resolve the address of the server or proxy
5379 *************************************************************/
5380 result = resolve_server(data, conn, async);
5385 /* Curl_setup_conn() is called after the name resolve initiated in
5386 * create_conn() is all done.
5388 * Curl_setup_conn() also handles reused connections
5390 * conn->data MUST already have been setup fine (in create_conn)
5393 CURLcode Curl_setup_conn(struct connectdata *conn,
5394 bool *protocol_done)
5396 CURLcode result = CURLE_OK;
5397 struct SessionHandle *data = conn->data;
5399 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
5401 if(conn->handler->flags & PROTOPT_NONETWORK) {
5402 /* nothing to setup when not using a network */
5403 *protocol_done = TRUE;
5406 *protocol_done = FALSE; /* default to not done */
5408 /* set proxy_connect_closed to false unconditionally already here since it
5409 is used strictly to provide extra information to a parent function in the
5410 case of proxy CONNECT failures and we must make sure we don't have it
5411 lingering set from a previous invoke */
5412 conn->bits.proxy_connect_closed = FALSE;
5415 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
5416 * basically anything through a http proxy we can't limit this based on
5419 if(data->set.str[STRING_USERAGENT]) {
5420 Curl_safefree(conn->allocptr.uagent);
5421 conn->allocptr.uagent =
5422 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
5423 if(!conn->allocptr.uagent)
5424 return CURLE_OUT_OF_MEMORY;
5427 data->req.headerbytecount = 0;
5429 #ifdef CURL_DO_LINEEND_CONV
5430 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
5431 #endif /* CURL_DO_LINEEND_CONV */
5433 /* set start time here for timeout purposes in the connect procedure, it
5434 is later set again for the progress meter purpose */
5435 conn->now = Curl_tvnow();
5438 /* loop for CURL_SERVER_CLOSED_CONNECTION */
5440 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
5441 /* Try to connect only if not already connected */
5442 bool connected = FALSE;
5444 result = ConnectPlease(data, conn, &connected);
5446 if(result && !conn->ip_addr) {
5447 /* transport connection failure not related with authentication */
5448 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
5453 result = Curl_protocol_connect(conn, protocol_done);
5454 if(CURLE_OK == result)
5455 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
5458 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
5460 /* if the connection was closed by the server while exchanging
5461 authentication informations, retry with the new set
5462 authentication information */
5463 if(conn->bits.proxy_connect_closed) {
5464 /* reset the error buffer */
5465 if(data->set.errorbuffer)
5466 data->set.errorbuffer[0] = '\0';
5467 data->state.errorbuf = FALSE;
5471 if(CURLE_OK != result)
5475 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
5476 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
5477 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
5478 *protocol_done = TRUE;
5479 Curl_verboseconnect(conn);
5480 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
5482 /* Stop the loop now */
5486 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
5487 set this here perhaps a second time */
5491 * This check is quite a hack. We're calling _fsetmode to fix the problem
5492 * with fwrite converting newline characters (you get mangled text files,
5493 * and corrupted binary files when you download to stdout and redirect it to
5497 if((data->set.out)->_handle == NULL) {
5498 _fsetmode(stdout, "b");
5505 CURLcode Curl_connect(struct SessionHandle *data,
5506 struct connectdata **in_connect,
5508 bool *protocol_done)
5512 *asyncp = FALSE; /* assume synchronous resolves by default */
5514 /* call the stuff that needs to be called */
5515 code = create_conn(data, in_connect, asyncp);
5517 if(CURLE_OK == code) {
5519 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
5521 *protocol_done = TRUE;
5523 /* DNS resolution is done: that's either because this is a reused
5524 connection, in which case DNS was unnecessary, or because DNS
5525 really did finish already (synch resolver/fast async resolve) */
5526 code = Curl_setup_conn(*in_connect, protocol_done);
5530 if(code == CURLE_NO_CONNECTION_AVAILABLE) {
5535 if(code && *in_connect) {
5536 /* We're not allowed to return failure with memory left allocated
5537 in the connectdata struct, free those here */
5538 Curl_disconnect(*in_connect, FALSE); /* close the connection */
5539 *in_connect = NULL; /* return a NULL */
5545 CURLcode Curl_done(struct connectdata **connp,
5546 CURLcode status, /* an error if this is called after an
5547 error was detected */
5551 struct connectdata *conn;
5552 struct SessionHandle *data;
5554 DEBUGASSERT(*connp);
5560 /* Stop if Curl_done() has already been called */
5563 Curl_getoff_all_pipelines(data, conn);
5565 if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
5566 !data->set.reuse_forbid &&
5568 /* Stop if pipeline is not empty and we do not have to close
5572 conn->bits.done = TRUE; /* called just now! */
5574 /* Cleanup possible redirect junk */
5575 if(data->req.newurl) {
5576 free(data->req.newurl);
5577 data->req.newurl = NULL;
5579 if(data->req.location) {
5580 free(data->req.location);
5581 data->req.location = NULL;
5584 Curl_resolver_cancel(conn);
5586 if(conn->dns_entry) {
5587 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
5588 conn->dns_entry = NULL;
5591 if(status == CURLE_ABORTED_BY_CALLBACK)
5592 /* When we're aborted due to a callback return code it basically have to
5593 be counted as premature as there is trouble ahead if we don't. We have
5594 many callbacks and protocols work differently, we could potentially do
5595 this more fine-grained in the future. */
5598 /* this calls the protocol-specific function pointer previously set */
5599 if(conn->handler->done)
5600 result = conn->handler->done(conn, status, premature);
5604 if(Curl_pgrsDone(conn) && !result)
5605 result = CURLE_ABORTED_BY_CALLBACK;
5607 /* if the transfer was completed in a paused state there can be buffered
5608 data left to write and then kill */
5609 if(data->state.tempwrite) {
5610 free(data->state.tempwrite);
5611 data->state.tempwrite = NULL;
5614 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
5615 forced us to close this no matter what we think.
5617 if conn->bits.close is TRUE, it means that the connection should be
5618 closed in spite of all our efforts to be nice, due to protocol
5619 restrictions in our or the server's end
5621 if premature is TRUE, it means this connection was said to be DONE before
5622 the entire request operation is complete and thus we can't know in what
5623 state it is for re-using, so we're forced to close it. In a perfect world
5624 we can add code that keep track of if we really must close it here or not,
5625 but currently we have no such detail knowledge.
5627 if(data->set.reuse_forbid || conn->bits.close || premature) {
5628 CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
5630 /* If we had an error already, make sure we return that one. But
5631 if we got a new error, return that. */
5636 /* the connection is no longer in use */
5637 if(ConnectionDone(data, conn)) {
5638 /* remember the most recently used connection */
5639 data->state.lastconnect = conn;
5641 infof(data, "Connection #%ld to host %s left intact\n",
5642 conn->connection_id,
5643 conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
5646 data->state.lastconnect = NULL;
5649 *connp = NULL; /* to make the caller of this function better detect that
5650 this was either closed or handed over to the connection
5651 cache here, and therefore cannot be used from this point on
5658 * do_init() inits the readwrite session. This is inited each time (in the DO
5659 * function before the protocol-specific DO functions are invoked) for a
5660 * transfer, sometimes multiple times on the same SessionHandle. Make sure
5661 * nothing in here depends on stuff that are setup dynamically for the
5665 static CURLcode do_init(struct connectdata *conn)
5667 struct SessionHandle *data = conn->data;
5668 struct SingleRequest *k = &data->req;
5670 conn->bits.done = FALSE; /* Curl_done() is not called yet */
5671 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
5672 data->state.expect100header = FALSE;
5674 if(data->set.opt_no_body)
5675 /* in HTTP lingo, no body means using the HEAD request... */
5676 data->set.httpreq = HTTPREQ_HEAD;
5677 else if(HTTPREQ_HEAD == data->set.httpreq)
5678 /* ... but if unset there really is no perfect method that is the
5679 "opposite" of HEAD but in reality most people probably think GET
5680 then. The important thing is that we can't let it remain HEAD if the
5681 opt_no_body is set FALSE since then we'll behave wrong when getting
5683 data->set.httpreq = HTTPREQ_GET;
5685 /* NB: the content encoding software depends on this initialization */
5686 Curl_easy_initHandleData(data);
5688 k->start = Curl_tvnow(); /* start time */
5689 k->now = k->start; /* current time is now */
5690 k->header = TRUE; /* assume header */
5694 k->buf = data->state.buffer;
5695 k->uploadbuf = data->state.uploadbuffer;
5696 k->hbufp = data->state.headerbuff;
5697 k->ignorebody=FALSE;
5699 Curl_speedinit(data);
5701 Curl_pgrsSetUploadCounter(data, 0);
5702 Curl_pgrsSetDownloadCounter(data, 0);
5708 * do_complete is called when the DO actions are complete.
5710 * We init chunking and trailer bits to their default values here immediately
5711 * before receiving any header data for the current request in the pipeline.
5713 static void do_complete(struct connectdata *conn)
5715 conn->data->req.chunk=FALSE;
5716 conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
5717 conn->sockfd:conn->writesockfd)+1;
5718 Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
5721 CURLcode Curl_do(struct connectdata **connp, bool *done)
5723 CURLcode result=CURLE_OK;
5724 struct connectdata *conn = *connp;
5725 struct SessionHandle *data = conn->data;
5727 if(conn->handler->do_it) {
5728 /* generic protocol-specific function pointer set in curl_connect() */
5729 result = conn->handler->do_it(conn, done);
5731 /* This was formerly done in transfer.c, but we better do it here */
5732 if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
5734 * If the connection is using an easy handle, call reconnect
5735 * to re-establish the connection. Otherwise, let the multi logic
5736 * figure out how to re-establish the connection.
5739 result = Curl_reconnect_request(connp);
5741 if(result == CURLE_OK) {
5742 /* ... finally back to actually retry the DO phase */
5743 conn = *connp; /* re-assign conn since Curl_reconnect_request
5744 creates a new connection */
5745 result = conn->handler->do_it(conn, done);
5752 if((result == CURLE_OK) && *done)
5753 /* do_complete must be called after the protocol-specific DO function */
5760 * Curl_do_more() is called during the DO_MORE multi state. It is basically a
5761 * second stage DO state which (wrongly) was introduced to support FTP's
5762 * second connection.
5764 * TODO: A future libcurl should be able to work away this state.
5768 CURLcode Curl_do_more(struct connectdata *conn, bool *completed)
5770 CURLcode result=CURLE_OK;
5774 if(conn->handler->do_more)
5775 result = conn->handler->do_more(conn, completed);
5777 if(!result && *completed)
5778 /* do_complete must be called after the protocol-specific DO function */
5784 /* Called on connect, and if there's already a protocol-specific struct
5785 allocated for a different connection, this frees it that it can be setup
5786 properly later on. */
5787 void Curl_reset_reqproto(struct connectdata *conn)
5789 struct SessionHandle *data = conn->data;
5790 if(data->state.proto.generic && data->state.current_conn != conn) {
5791 free(data->state.proto.generic);
5792 data->state.proto.generic = NULL;
5794 data->state.current_conn = conn;