1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2011, 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 ***************************************************************************/
25 #ifdef HAVE_SYS_SOCKET_H
26 #include <sys/socket.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
37 #ifdef HAVE_ARPA_INET_H
38 #include <arpa/inet.h>
43 #ifdef HAVE_SYS_IOCTL_H
44 #include <sys/ioctl.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
57 #error "We can't compile without socket() support!"
67 #include <stringprep.h>
68 #ifdef HAVE_IDN_FREE_H
71 /* prototype from idn-free.h, not provided by libidn 0.4.5's make install! */
72 void idn_free (void *ptr);
75 /* if idn_free() was not found in this version of libidn use free() instead */
76 #define idn_free(x) (free)(x)
78 #elif defined(USE_WIN32_IDN)
79 /* prototype for curl_win32_idn_to_ascii() */
80 int curl_win32_idn_to_ascii(const char *in, char **out);
81 #endif /* USE_LIBIDN */
98 #include "content_encoding.h"
99 #include "http_digest.h"
100 #include "http_negotiate.h"
104 #include "speedcheck.h"
106 #include "warnless.h"
107 #include "non-ascii.h"
109 /* And now for the protocols */
116 #include "curl_ldap.h"
121 #include "inet_ntop.h"
122 #include "http_ntlm.h"
124 #include "curl_rtmp.h"
127 #define _MPRINTF_REPLACE /* use our functions only */
128 #include <curl/mprintf.h>
130 #include "curl_memory.h"
131 /* The last #include file should be: */
132 #include "memdebug.h"
134 /* Local static prototypes */
135 static long ConnectionKillOne(struct SessionHandle *data);
136 static void conn_free(struct connectdata *conn);
137 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
143 static const struct Curl_handler * const protocols[] = {
145 #ifndef CURL_DISABLE_HTTP
149 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
153 #ifndef CURL_DISABLE_FTP
157 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
161 #ifndef CURL_DISABLE_TELNET
162 &Curl_handler_telnet,
165 #ifndef CURL_DISABLE_DICT
169 #ifndef CURL_DISABLE_LDAP
171 #if !defined(CURL_DISABLE_LDAPS) && \
172 ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
173 (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
178 #ifndef CURL_DISABLE_FILE
182 #ifndef CURL_DISABLE_TFTP
191 #ifndef CURL_DISABLE_IMAP
198 #ifndef CURL_DISABLE_POP3
205 #ifndef CURL_DISABLE_SMTP
212 #ifndef CURL_DISABLE_RTSP
216 #ifndef CURL_DISABLE_GOPHER
217 &Curl_handler_gopher,
224 &Curl_handler_rtmpte,
226 &Curl_handler_rtmpts,
229 (struct Curl_handler *) NULL
233 * Dummy handler for undefined protocol schemes.
236 static const struct Curl_handler Curl_handler_dummy = {
237 "<no protocol>", /* scheme */
238 ZERO_NULL, /* setup_connection */
239 ZERO_NULL, /* do_it */
240 ZERO_NULL, /* done */
241 ZERO_NULL, /* do_more */
242 ZERO_NULL, /* connect_it */
243 ZERO_NULL, /* connecting */
244 ZERO_NULL, /* doing */
245 ZERO_NULL, /* proto_getsock */
246 ZERO_NULL, /* doing_getsock */
247 ZERO_NULL, /* perform_getsock */
248 ZERO_NULL, /* disconnect */
249 ZERO_NULL, /* readwrite */
252 PROTOPT_NONE /* flags */
255 void Curl_safefree(void *ptr)
261 static void close_connections(struct SessionHandle *data)
263 /* Loop through all open connections and kill them one by one */
266 i = ConnectionKillOne(data);
270 void Curl_freeset(struct SessionHandle * data)
272 /* Free all dynamic strings stored in the data->set substructure. */
274 for(i=(enum dupstring)0; i < STRING_LAST; i++)
275 Curl_safefree(data->set.str[i]);
278 static CURLcode setstropt(char **charp, char * s)
280 /* Release the previous storage at `charp' and replace by a dynamic storage
281 copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
285 *charp = (char *) NULL;
292 return CURLE_OUT_OF_MEMORY;
300 static CURLcode setstropt_userpwd(char *option, char **user_storage,
304 CURLcode result = CURLE_OK;
307 /* we treat a NULL passed in as a hint to clear existing info */
308 Curl_safefree(*user_storage);
309 *user_storage = (char *) NULL;
310 Curl_safefree(*pwd_storage);
311 *pwd_storage = (char *) NULL;
315 separator = strchr(option, ':');
316 if(separator != NULL) {
318 /* store username part of option */
320 size_t username_len = (size_t)(separator-option);
321 p = malloc(username_len+1);
323 result = CURLE_OUT_OF_MEMORY;
325 memcpy(p, option, username_len);
326 p[username_len] = '\0';
327 Curl_safefree(*user_storage);
331 /* store password part of option */
332 if(result == CURLE_OK)
333 result = setstropt(pwd_storage, separator+1);
336 result = setstropt(user_storage, option);
341 CURLcode Curl_dupset(struct SessionHandle * dst, struct SessionHandle * src)
343 CURLcode r = CURLE_OK;
346 /* Copy src->set into dst->set first, then deal with the strings
350 /* clear all string pointers first */
351 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
353 /* duplicate all strings */
354 for(i=(enum dupstring)0; i< STRING_LAST; i++) {
355 r = setstropt(&dst->set.str[i], src->set.str[i]);
360 /* If a failure occurred, freeing has to be performed externally. */
365 * This is the internal function curl_easy_cleanup() calls. This should
366 * cleanup and free all resources associated with this sessionhandle.
368 * NOTE: if we ever add something that attempts to write to a socket or
369 * similar here, we must ignore SIGPIPE first. It is currently only done
370 * when curl_easy_perform() is invoked.
373 CURLcode Curl_close(struct SessionHandle *data)
375 struct Curl_multi *m = data->multi;
378 /* only for debugging, scan through all connections and see if there's a
379 pipe reference still identifying this handle */
381 if(data->state.connc && data->state.connc->type == CONNCACHE_MULTI) {
382 struct conncache *c = data->state.connc;
384 struct curl_llist *pipeline;
385 struct curl_llist_element *curr;
386 struct connectdata *connptr;
388 for(i=0; i< c->num; i++) {
389 connptr = c->connects[i];
393 pipeline = connptr->send_pipe;
395 for(curr = pipeline->head; curr; curr=curr->next) {
396 if(data == (struct SessionHandle *) curr->ptr) {
398 "problem we %p are still in send pipe for %p done %d\n",
399 data, connptr, (int)connptr->bits.done);
403 pipeline = connptr->recv_pipe;
405 for(curr = pipeline->head; curr; curr=curr->next) {
406 if(data == (struct SessionHandle *) curr->ptr) {
408 "problem we %p are still in recv pipe for %p done %d\n",
409 data, connptr, (int)connptr->bits.done);
413 pipeline = connptr->done_pipe;
415 for(curr = pipeline->head; curr; curr=curr->next) {
416 if(data == (struct SessionHandle *) curr->ptr) {
418 "problem we %p are still in done pipe for %p done %d\n",
419 data, connptr, (int)connptr->bits.done);
423 pipeline = connptr->pend_pipe;
425 for(curr = pipeline->head; curr; curr=curr->next) {
426 if(data == (struct SessionHandle *) curr->ptr) {
428 "problem we %p are still in pend pipe for %p done %d\n",
429 data, connptr, (int)connptr->bits.done);
437 Curl_expire(data, 0); /* shut off timers */
440 /* This handle is still part of a multi handle, take care of this first
441 and detach this handle from there. */
442 curl_multi_remove_handle(data->multi, data);
444 /* Destroy the timeout list that is held in the easy handle. It is
445 /normally/ done by curl_multi_remove_handle() but this is "just in
447 if(data->state.timeoutlist) {
448 Curl_llist_destroy(data->state.timeoutlist, NULL);
449 data->state.timeoutlist = NULL;
452 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
453 the multi handle, since that function uses the magic
456 if(data->state.connc) {
458 if(data->state.connc->type == CONNCACHE_PRIVATE) {
459 /* close all connections still alive that are in the private connection
460 cache, as we no longer have the pointer left to the shared one. */
461 close_connections(data);
463 /* free the connection cache if allocated privately */
464 Curl_rm_connc(data->state.connc);
468 if(data->state.shared_conn) {
469 /* marked to be used by a pending connection so we can't kill this handle
471 data->state.closed = TRUE;
475 if(data->dns.hostcachetype == HCACHE_PRIVATE) {
476 Curl_hash_destroy(data->dns.hostcache);
477 data->dns.hostcachetype = HCACHE_NONE;
478 data->dns.hostcache = NULL;
481 if(data->state.rangestringalloc)
482 free(data->state.range);
484 /* Free the pathbuffer */
485 Curl_safefree(data->state.pathbuffer);
486 Curl_safefree(data->state.proto.generic);
488 /* Close down all open SSL info and sessions */
489 Curl_ssl_close_all(data);
490 Curl_safefree(data->state.first_host);
491 Curl_safefree(data->state.scratch);
492 Curl_ssl_free_certinfo(data);
494 if(data->change.referer_alloc)
495 free(data->change.referer);
497 if(data->change.url_alloc)
498 free(data->change.url);
500 Curl_safefree(data->state.headerbuff);
502 Curl_flush_cookies(data, 1);
504 Curl_digest_cleanup(data);
506 Curl_safefree(data->info.contenttype);
507 Curl_safefree(data->info.wouldredirect);
509 /* this destroys the channel and we cannot use it anymore after this */
510 Curl_resolver_cleanup(data->state.resolver);
512 Curl_convert_close(data);
514 /* No longer a dirty share, if it exists */
516 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
517 data->share->dirty--;
518 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
526 /* create a connection cache of a private or multi type */
527 struct conncache *Curl_mk_connc(int type,
528 long amount) /* set -1 to use default */
530 /* It is subject for debate how many default connections to have for a multi
531 connection cache... */
535 long max_amount = (long)(((size_t)INT_MAX) / sizeof(struct connectdata *));
537 if(type == CONNCACHE_PRIVATE) {
538 default_amount = (amount < 1L) ? 5L : amount;
541 default_amount = (amount < 1L) ? 10L : amount;
544 if(default_amount > max_amount)
545 default_amount = max_amount;
547 c = calloc(1, sizeof(struct conncache));
551 c->connects = calloc((size_t)default_amount, sizeof(struct connectdata *));
557 c->num = default_amount;
562 /* Change number of entries of a connection cache */
563 CURLcode Curl_ch_connc(struct SessionHandle *data,
568 struct connectdata **newptr;
569 long max_amount = (long)(((size_t)INT_MAX) / sizeof(struct connectdata *));
572 newamount = 1; /* we better have at least one entry */
575 /* we get a NULL pointer passed in as connection cache, which means that
576 there is no cache created for this SessionHandle just yet, we create a
577 brand new with the requested size.
579 data->state.connc = Curl_mk_connc(CONNCACHE_PRIVATE, newamount);
580 if(!data->state.connc)
581 return CURLE_OUT_OF_MEMORY;
585 if(newamount < c->num) {
586 /* Since this number is *decreased* from the existing number, we must
587 close the possibly open connections that live on the indexes that
590 NOTE: for conncache_multi cases we must make sure that we only
591 close handles not in use.
593 for(i=newamount; i< c->num; i++)
594 Curl_disconnect(c->connects[i], /* dead_connection */ FALSE);
596 /* If the most recent connection is no longer valid, mark it
598 if(data->state.lastconnect <= newamount)
599 data->state.lastconnect = -1;
602 if(newamount > max_amount)
603 newamount = max_amount;
604 newptr = realloc(c->connects, sizeof(struct connectdata *) * newamount);
606 /* we closed a few connections in vain, but so what? */
607 return CURLE_OUT_OF_MEMORY;
609 /* nullify the newly added pointers */
610 for(i=c->num; i<newamount; i++)
613 c->connects = newptr;
616 /* we no longer support less than 1 as size for the connection cache, and
617 I'm not sure it ever worked to set it to zero */
621 /* Free a connection cache. This is called from Curl_close() and
622 curl_multi_cleanup(). */
623 void Curl_rm_connc(struct conncache *c)
627 for(i = 0; i < c->num; ++i)
628 conn_free(c->connects[i]);
637 * Initialize the UserDefined fields within a SessionHandle.
638 * This may be safely called on a new or existing SessionHandle.
640 CURLcode Curl_init_userdefined(struct UserDefined *set)
642 CURLcode res = CURLE_OK;
644 set->out = stdout; /* default output to stdout */
645 set->in = stdin; /* default input from stdin */
646 set->err = stderr; /* default stderr to stderr */
648 /* use fwrite as default function to store output */
649 set->fwrite_func = (curl_write_callback)fwrite;
651 /* use fread as default function to read input */
652 set->fread_func = (curl_read_callback)fread;
653 set->is_fread_set = 0;
654 set->is_fwrite_set = 0;
656 set->seek_func = ZERO_NULL;
657 set->seek_client = ZERO_NULL;
659 /* conversion callbacks for non-ASCII hosts */
660 set->convfromnetwork = ZERO_NULL;
661 set->convtonetwork = ZERO_NULL;
662 set->convfromutf8 = ZERO_NULL;
664 set->infilesize = -1; /* we don't know any size */
665 set->postfieldsize = -1; /* unknown size */
666 set->maxredirs = -1; /* allow any amount by default */
668 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
669 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
670 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
671 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
672 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
673 set->ftp_filemethod = FTPFILE_MULTICWD;
675 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
677 /* Set the default size of the SSL session ID cache */
678 set->ssl.numsessions = 5;
680 set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
681 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
682 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
683 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
685 /* make libcurl quiet by default: */
686 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
689 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
690 * switched off unless wanted.
692 set->ssl.verifypeer = TRUE;
693 set->ssl.verifyhost = 2;
695 set->ssl.authtype = CURL_TLSAUTH_NONE;
697 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
699 set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
701 set->new_file_perms = 0644; /* Default permissions */
702 set->new_directory_perms = 0755; /* Default permissions */
704 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
705 define since we internally only use the lower 16 bits for the passed
706 in bitmask to not conflict with the private bits */
707 set->allowed_protocols = CURLPROTO_ALL;
708 set->redir_protocols =
709 CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
711 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
713 * disallow unprotected protection negotiation NEC reference implementation
714 * seem not to follow rfc1961 section 4.3/4.4
716 set->socks5_gssapi_nec = FALSE;
717 /* set default gssapi service name */
718 res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
719 (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
724 /* This is our preferred CA cert bundle/path since install time */
725 #if defined(CURL_CA_BUNDLE)
726 res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
727 #elif defined(CURL_CA_PATH)
728 res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
731 set->wildcardmatch = FALSE;
732 set->chunk_bgn = ZERO_NULL;
733 set->chunk_end = ZERO_NULL;
741 * @param curl is a pointer to a sessionhandle pointer that gets set by this
746 CURLcode Curl_open(struct SessionHandle **curl)
748 CURLcode res = CURLE_OK;
749 struct SessionHandle *data;
752 /* Very simple start-up: alloc the struct, init it with zeroes and return */
753 data = calloc(1, sizeof(struct SessionHandle));
755 /* this is a very serious error */
756 DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
757 return CURLE_OUT_OF_MEMORY;
760 data->magic = CURLEASY_MAGIC_NUMBER;
762 status = Curl_resolver_init(&data->state.resolver);
764 DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
769 /* We do some initial setup here, all those fields that can't be just 0 */
771 data->state.headerbuff = malloc(HEADERSIZE);
772 if(!data->state.headerbuff) {
773 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
774 res = CURLE_OUT_OF_MEMORY;
777 Curl_easy_initHandleData(data);
778 res = Curl_init_userdefined(&data->set);
780 data->state.headersize=HEADERSIZE;
782 Curl_convert_init(data);
784 /* most recent connection is not yet defined */
785 data->state.lastconnect = -1;
787 data->progress.flags |= PGRS_HIDE;
788 data->state.current_speed = -1; /* init to negative == impossible */
790 data->wildcard.state = CURLWC_INIT;
791 data->wildcard.filelist = NULL;
792 data->set.fnmatch = ZERO_NULL;
793 /* This no longer creates a connection cache here. It is instead made on
794 the first call to curl_easy_perform() or when the handle is added to a
799 Curl_resolver_cleanup(data->state.resolver);
800 if(data->state.headerbuff)
801 free(data->state.headerbuff);
812 CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
816 CURLcode result = CURLE_OK;
817 #ifndef CURL_DISABLE_HTTP
822 case CURLOPT_DNS_CACHE_TIMEOUT:
823 data->set.dns_cache_timeout = va_arg(param, long);
825 case CURLOPT_DNS_USE_GLOBAL_CACHE:
827 /* remember we want this enabled */
828 long use_cache = va_arg(param, long);
829 data->set.global_dns_cache = (bool)(0 != use_cache);
832 case CURLOPT_SSL_CIPHER_LIST:
833 /* set a list of cipher we want to use in the SSL connection */
834 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
835 va_arg(param, char *));
838 case CURLOPT_RANDOM_FILE:
840 * This is the path name to a file that contains random data to seed
841 * the random SSL stuff with. The file is only used for reading.
843 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
844 va_arg(param, char *));
846 case CURLOPT_EGDSOCKET:
848 * The Entropy Gathering Daemon socket pathname
850 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
851 va_arg(param, char *));
853 case CURLOPT_MAXCONNECTS:
855 * Set the absolute number of maximum simultaneous alive connection that
856 * libcurl is allowed to have.
858 result = Curl_ch_connc(data, data->state.connc, va_arg(param, long));
860 case CURLOPT_FORBID_REUSE:
862 * When this transfer is done, it must not be left to be reused by a
863 * subsequent transfer but shall be closed immediately.
865 data->set.reuse_forbid = (bool)(0 != va_arg(param, long));
867 case CURLOPT_FRESH_CONNECT:
869 * This transfer shall not use a previously cached connection but
870 * should be made with a fresh new connect!
872 data->set.reuse_fresh = (bool)(0 != va_arg(param, long));
874 case CURLOPT_VERBOSE:
876 * Verbose means infof() calls that give a lot of information about
877 * the connection and transfer procedures as well as internal choices.
879 data->set.verbose = (bool)(0 != va_arg(param, long));
883 * Set to include the header in the general data output stream.
885 data->set.include_header = (bool)(0 != va_arg(param, long));
887 case CURLOPT_NOPROGRESS:
889 * Shut off the internal supported progress meter
891 data->set.hide_progress = (bool)(0 != va_arg(param, long));
892 if(data->set.hide_progress)
893 data->progress.flags |= PGRS_HIDE;
895 data->progress.flags &= ~PGRS_HIDE;
899 * Do not include the body part in the output data stream.
901 data->set.opt_no_body = (bool)(0 != va_arg(param, long));
903 case CURLOPT_FAILONERROR:
905 * Don't output the >=300 error code HTML-page, but instead only
908 data->set.http_fail_on_error = (bool)(0 != va_arg(param, long));
913 * We want to sent data to the remote host. If this is HTTP, that equals
914 * using the PUT request.
916 data->set.upload = (bool)(0 != va_arg(param, long));
917 if(data->set.upload) {
918 /* If this is HTTP, PUT is what's needed to "upload" */
919 data->set.httpreq = HTTPREQ_PUT;
920 data->set.opt_no_body = FALSE; /* this is implied */
923 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
924 then this can be changed to HEAD later on) */
925 data->set.httpreq = HTTPREQ_GET;
927 case CURLOPT_FILETIME:
929 * Try to get the file time of the remote document. The time will
930 * later (possibly) become available using curl_easy_getinfo().
932 data->set.get_filetime = (bool)(0 != va_arg(param, long));
934 case CURLOPT_FTP_CREATE_MISSING_DIRS:
936 * An FTP option that modifies an upload to create missing directories on
939 switch(va_arg(param, long)) {
941 data->set.ftp_create_missing_dirs = 0;
944 data->set.ftp_create_missing_dirs = 1;
947 data->set.ftp_create_missing_dirs = 2;
950 /* reserve other values for future use */
951 result = CURLE_UNKNOWN_OPTION;
955 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
957 * Option that specifies how quickly an server response must be obtained
958 * before it is considered failure. For pingpong protocols.
960 data->set.server_response_timeout = va_arg( param , long ) * 1000;
962 case CURLOPT_TFTP_BLKSIZE:
964 * TFTP option that specifies the block size to use for data transmission
966 data->set.tftp_blksize = va_arg(param, long);
968 case CURLOPT_DIRLISTONLY:
970 * An option that changes the command to one that asks for a list
971 * only, no file info details.
973 data->set.ftp_list_only = (bool)(0 != va_arg(param, long));
977 * We want to upload and append to an existing file.
979 data->set.ftp_append = (bool)(0 != va_arg(param, long));
981 case CURLOPT_FTP_FILEMETHOD:
983 * How do access files over FTP.
985 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
989 * Parse the $HOME/.netrc file
991 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
993 case CURLOPT_NETRC_FILE:
995 * Use this file instead of the $HOME/.netrc file
997 result = setstropt(&data->set.str[STRING_NETRC_FILE],
998 va_arg(param, char *));
1000 case CURLOPT_TRANSFERTEXT:
1002 * This option was previously named 'FTPASCII'. Renamed to work with
1003 * more protocols than merely FTP.
1005 * Transfer using ASCII (instead of BINARY).
1007 data->set.prefer_ascii = (bool)(0 != va_arg(param, long));
1009 case CURLOPT_TIMECONDITION:
1011 * Set HTTP time condition. This must be one of the defines in the
1012 * curl/curl.h header file.
1014 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
1016 case CURLOPT_TIMEVALUE:
1018 * This is the value to compare with the remote document with the
1019 * method set with CURLOPT_TIMECONDITION
1021 data->set.timevalue = (time_t)va_arg(param, long);
1023 case CURLOPT_SSLVERSION:
1025 * Set explicit SSL version to try to connect with, as some SSL
1026 * implementations are lame.
1028 data->set.ssl.version = va_arg(param, long);
1031 #ifndef CURL_DISABLE_HTTP
1032 case CURLOPT_AUTOREFERER:
1034 * Switch on automatic referer that gets set if curl follows locations.
1036 data->set.http_auto_referer = (bool)(0 != va_arg(param, long));
1039 case CURLOPT_ACCEPT_ENCODING:
1041 * String to use at the value of Accept-Encoding header.
1043 * If the encoding is set to "" we use an Accept-Encoding header that
1044 * encompasses all the encodings we support.
1045 * If the encoding is set to NULL we don't send an Accept-Encoding header
1046 * and ignore an received Content-Encoding header.
1049 argptr = va_arg(param, char *);
1050 result = setstropt(&data->set.str[STRING_ENCODING],
1051 (argptr && !*argptr)?
1052 (char *) ALL_CONTENT_ENCODINGS: argptr);
1055 case CURLOPT_TRANSFER_ENCODING:
1056 data->set.http_transfer_encoding = (bool)(0 != va_arg(param, long));
1059 case CURLOPT_FOLLOWLOCATION:
1061 * Follow Location: header hints on a HTTP-server.
1063 data->set.http_follow_location = (bool)(0 != va_arg(param, long));
1066 case CURLOPT_UNRESTRICTED_AUTH:
1068 * Send authentication (user+password) when following locations, even when
1071 data->set.http_disable_hostname_check_before_authentication =
1072 (bool)(0 != va_arg(param, long));
1075 case CURLOPT_MAXREDIRS:
1077 * The maximum amount of hops you allow curl to follow Location:
1078 * headers. This should mostly be used to detect never-ending loops.
1080 data->set.maxredirs = va_arg(param, long);
1083 case CURLOPT_POSTREDIR:
1086 * Set the behaviour of POST when redirecting
1087 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
1088 * CURL_REDIR_POST_301 - POST is kept as POST after 301
1089 * CURL_REDIR_POST_302 - POST is kept as POST after 302
1090 * CURL_REDIR_POST_ALL - POST is kept as POST after 301 and 302
1091 * other - POST is kept as POST after 301 and 302
1093 long postRedir = va_arg(param, long);
1094 data->set.post301 = (bool)((postRedir & CURL_REDIR_POST_301)?TRUE:FALSE);
1095 data->set.post302 = (bool)((postRedir & CURL_REDIR_POST_302)?TRUE:FALSE);
1100 /* Does this option serve a purpose anymore? Yes it does, when
1101 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
1103 if(va_arg(param, long)) {
1104 data->set.httpreq = HTTPREQ_POST;
1105 data->set.opt_no_body = FALSE; /* this is implied */
1108 data->set.httpreq = HTTPREQ_GET;
1111 case CURLOPT_COPYPOSTFIELDS:
1113 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
1114 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
1115 * CURLOPT_COPYPOSTFIELDS and not altered later.
1117 argptr = va_arg(param, char *);
1119 if(!argptr || data->set.postfieldsize == -1)
1120 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
1123 * Check that requested length does not overflow the size_t type.
1126 if((data->set.postfieldsize < 0) ||
1127 ((sizeof(curl_off_t) != sizeof(size_t)) &&
1128 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
1129 result = CURLE_OUT_OF_MEMORY;
1133 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1135 /* Allocate even when size == 0. This satisfies the need of possible
1136 later address compare to detect the COPYPOSTFIELDS mode, and
1137 to mark that postfields is used rather than read function or
1140 p = malloc((size_t)(data->set.postfieldsize?
1141 data->set.postfieldsize:1));
1144 result = CURLE_OUT_OF_MEMORY;
1146 if(data->set.postfieldsize)
1147 memcpy(p, argptr, (size_t)data->set.postfieldsize);
1149 data->set.str[STRING_COPYPOSTFIELDS] = p;
1154 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
1155 data->set.httpreq = HTTPREQ_POST;
1158 case CURLOPT_POSTFIELDS:
1160 * Like above, but use static data instead of copying it.
1162 data->set.postfields = va_arg(param, void *);
1163 /* Release old copied data. */
1164 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1165 data->set.httpreq = HTTPREQ_POST;
1168 case CURLOPT_POSTFIELDSIZE:
1170 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1171 * figure it out. Enables binary posts.
1173 bigsize = va_arg(param, long);
1175 if(data->set.postfieldsize < bigsize &&
1176 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1177 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1178 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1179 data->set.postfields = NULL;
1182 data->set.postfieldsize = bigsize;
1185 case CURLOPT_POSTFIELDSIZE_LARGE:
1187 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1188 * figure it out. Enables binary posts.
1190 bigsize = va_arg(param, curl_off_t);
1192 if(data->set.postfieldsize < bigsize &&
1193 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1194 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1195 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1196 data->set.postfields = NULL;
1199 data->set.postfieldsize = bigsize;
1202 case CURLOPT_HTTPPOST:
1204 * Set to make us do HTTP POST
1206 data->set.httppost = va_arg(param, struct curl_httppost *);
1207 data->set.httpreq = HTTPREQ_POST_FORM;
1208 data->set.opt_no_body = FALSE; /* this is implied */
1211 case CURLOPT_REFERER:
1213 * String to set in the HTTP Referer: field.
1215 if(data->change.referer_alloc) {
1216 free(data->change.referer);
1217 data->change.referer_alloc = FALSE;
1219 result = setstropt(&data->set.str[STRING_SET_REFERER],
1220 va_arg(param, char *));
1221 data->change.referer = data->set.str[STRING_SET_REFERER];
1224 case CURLOPT_USERAGENT:
1226 * String to use in the HTTP User-Agent field
1228 result = setstropt(&data->set.str[STRING_USERAGENT],
1229 va_arg(param, char *));
1232 case CURLOPT_HTTPHEADER:
1234 * Set a list with HTTP headers to use (or replace internals with)
1236 data->set.headers = va_arg(param, struct curl_slist *);
1239 case CURLOPT_HTTP200ALIASES:
1241 * Set a list of aliases for HTTP 200 in response header
1243 data->set.http200aliases = va_arg(param, struct curl_slist *);
1246 #if !defined(CURL_DISABLE_COOKIES)
1247 case CURLOPT_COOKIE:
1249 * Cookie string to send to the remote server in the request.
1251 result = setstropt(&data->set.str[STRING_COOKIE],
1252 va_arg(param, char *));
1255 case CURLOPT_COOKIEFILE:
1257 * Set cookie file to read and parse. Can be used multiple times.
1259 argptr = (char *)va_arg(param, void *);
1261 struct curl_slist *cl;
1262 /* append the cookie file name to the list of file names, and deal with
1264 cl = curl_slist_append(data->change.cookielist, argptr);
1267 return CURLE_OUT_OF_MEMORY;
1269 data->change.cookielist = cl; /* store the list for later use */
1273 case CURLOPT_COOKIEJAR:
1275 * Set cookie file name to dump all cookies to when we're done.
1277 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1278 va_arg(param, char *));
1281 * Activate the cookie parser. This may or may not already
1284 data->cookies = Curl_cookie_init(data, NULL, data->cookies,
1285 data->set.cookiesession);
1288 case CURLOPT_COOKIESESSION:
1290 * Set this option to TRUE to start a new "cookie session". It will
1291 * prevent the forthcoming read-cookies-from-file actions to accept
1292 * cookies that are marked as being session cookies, as they belong to a
1295 * In the original Netscape cookie spec, "session cookies" are cookies
1296 * with no expire date set. RFC2109 describes the same action if no
1297 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1298 * a 'Discard' action that can enforce the discard even for cookies that
1301 * We run mostly with the original cookie spec, as hardly anyone implements
1304 data->set.cookiesession = (bool)(0 != va_arg(param, long));
1307 case CURLOPT_COOKIELIST:
1308 argptr = va_arg(param, char *);
1313 if(Curl_raw_equal(argptr, "ALL")) {
1314 /* clear all cookies */
1315 Curl_cookie_clearall(data->cookies);
1318 else if(Curl_raw_equal(argptr, "SESS")) {
1319 /* clear session cookies */
1320 Curl_cookie_clearsess(data->cookies);
1323 else if(Curl_raw_equal(argptr, "FLUSH")) {
1324 /* flush cookies to file */
1325 Curl_flush_cookies(data, 0);
1330 /* if cookie engine was not running, activate it */
1331 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1333 argptr = strdup(argptr);
1335 result = CURLE_OUT_OF_MEMORY;
1339 if(checkprefix("Set-Cookie:", argptr))
1340 /* HTTP Header format line */
1341 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1344 /* Netscape format line */
1345 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1349 #endif /* CURL_DISABLE_COOKIES */
1351 case CURLOPT_HTTPGET:
1353 * Set to force us do HTTP GET
1355 if(va_arg(param, long)) {
1356 data->set.httpreq = HTTPREQ_GET;
1357 data->set.upload = FALSE; /* switch off upload */
1358 data->set.opt_no_body = FALSE; /* this is implied */
1362 case CURLOPT_HTTP_VERSION:
1364 * This sets a requested HTTP version to be used. The value is one of
1365 * the listed enums in curl/curl.h.
1367 data->set.httpversion = va_arg(param, long);
1370 case CURLOPT_HTTPAUTH:
1372 * Set HTTP Authentication type BITMASK.
1375 long auth = va_arg(param, long);
1377 /* the DIGEST_IE bit is only used to set a special marker, for all the
1378 rest we need to handle it as normal DIGEST */
1379 data->state.authhost.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE)?
1382 if(auth & CURLAUTH_DIGEST_IE) {
1383 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1384 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1387 /* switch off bits we can't support */
1389 auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
1391 #ifndef WINBIND_NTLM_AUTH_ENABLED
1392 auth &= ~CURLAUTH_NTLM_WB;
1394 #ifndef USE_HTTP_NEGOTIATE
1395 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
1399 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1401 data->set.httpauth = auth;
1405 #endif /* CURL_DISABLE_HTTP */
1407 case CURLOPT_CUSTOMREQUEST:
1409 * Set a custom string to use as request
1411 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1412 va_arg(param, char *));
1415 data->set.httpreq = HTTPREQ_CUSTOM;
1416 here, we continue as if we were using the already set type
1417 and this just changes the actual request keyword */
1420 #ifndef CURL_DISABLE_PROXY
1421 case CURLOPT_HTTPPROXYTUNNEL:
1423 * Tunnel operations through the proxy instead of normal proxy use
1425 data->set.tunnel_thru_httpproxy = (bool)(0 != va_arg(param, long));
1428 case CURLOPT_PROXYPORT:
1430 * Explicitly set HTTP proxy port number.
1432 data->set.proxyport = va_arg(param, long);
1435 case CURLOPT_PROXYAUTH:
1437 * Set HTTP Authentication type BITMASK.
1440 long auth = va_arg(param, long);
1442 /* the DIGEST_IE bit is only used to set a special marker, for all the
1443 rest we need to handle it as normal DIGEST */
1444 data->state.authproxy.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE)?
1447 if(auth & CURLAUTH_DIGEST_IE) {
1448 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1449 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1451 /* switch off bits we can't support */
1453 auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
1455 #ifndef WINBIND_NTLM_AUTH_ENABLED
1456 auth &= ~CURLAUTH_NTLM_WB;
1458 #ifndef USE_HTTP_NEGOTIATE
1459 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
1463 return CURLE_NOT_BUILT_IN; /* no supported types left! */
1465 data->set.proxyauth = auth;
1471 * Set proxy server:port to use as HTTP proxy.
1473 * If the proxy is set to "" we explicitly say that we don't want to use a
1474 * proxy (even though there might be environment variables saying so).
1476 * Setting it to NULL, means no proxy but allows the environment variables
1479 result = setstropt(&data->set.str[STRING_PROXY],
1480 va_arg(param, char *));
1483 case CURLOPT_PROXYTYPE:
1485 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1487 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1490 case CURLOPT_PROXY_TRANSFER_MODE:
1492 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1494 switch (va_arg(param, long)) {
1496 data->set.proxy_transfer_mode = FALSE;
1499 data->set.proxy_transfer_mode = TRUE;
1502 /* reserve other values for future use */
1503 result = CURLE_UNKNOWN_OPTION;
1507 #endif /* CURL_DISABLE_PROXY */
1509 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1510 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1512 * Set gssapi service name
1514 result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
1515 va_arg(param, char *));
1518 case CURLOPT_SOCKS5_GSSAPI_NEC:
1520 * set flag for nec socks5 support
1522 data->set.socks5_gssapi_nec = (bool)(0 != va_arg(param, long));
1526 case CURLOPT_WRITEHEADER:
1528 * Custom pointer to pass the header write callback function
1530 data->set.writeheader = (void *)va_arg(param, void *);
1532 case CURLOPT_ERRORBUFFER:
1534 * Error buffer provided by the caller to get the human readable
1537 data->set.errorbuffer = va_arg(param, char *);
1541 * FILE pointer to write to or include in the data write callback
1543 data->set.out = va_arg(param, FILE *);
1545 case CURLOPT_FTPPORT:
1547 * Use FTP PORT, this also specifies which IP address to use
1549 result = setstropt(&data->set.str[STRING_FTPPORT],
1550 va_arg(param, char *));
1551 data->set.ftp_use_port = (bool)(NULL != data->set.str[STRING_FTPPORT]);
1554 case CURLOPT_FTP_USE_EPRT:
1555 data->set.ftp_use_eprt = (bool)(0 != va_arg(param, long));
1558 case CURLOPT_FTP_USE_EPSV:
1559 data->set.ftp_use_epsv = (bool)(0 != va_arg(param, long));
1562 case CURLOPT_FTP_USE_PRET:
1563 data->set.ftp_use_pret = (bool)(0 != va_arg(param, long));
1566 case CURLOPT_FTP_SSL_CCC:
1567 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1570 case CURLOPT_FTP_SKIP_PASV_IP:
1572 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1573 * bypass of the IP address in PASV responses.
1575 data->set.ftp_skip_ip = (bool)(0 != va_arg(param, long));
1578 case CURLOPT_INFILE:
1580 * FILE pointer to read the file to be uploaded from. Or possibly
1581 * used as argument to the read callback.
1583 data->set.in = va_arg(param, FILE *);
1585 case CURLOPT_INFILESIZE:
1587 * If known, this should inform curl about the file size of the
1588 * to-be-uploaded file.
1590 data->set.infilesize = va_arg(param, long);
1592 case CURLOPT_INFILESIZE_LARGE:
1594 * If known, this should inform curl about the file size of the
1595 * to-be-uploaded file.
1597 data->set.infilesize = va_arg(param, curl_off_t);
1599 case CURLOPT_LOW_SPEED_LIMIT:
1601 * The low speed limit that if transfers are below this for
1602 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1604 data->set.low_speed_limit=va_arg(param, long);
1606 case CURLOPT_MAX_SEND_SPEED_LARGE:
1608 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1609 * bytes per second the transfer is throttled..
1611 data->set.max_send_speed=va_arg(param, curl_off_t);
1613 case CURLOPT_MAX_RECV_SPEED_LARGE:
1615 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1616 * second the transfer is throttled..
1618 data->set.max_recv_speed=va_arg(param, curl_off_t);
1620 case CURLOPT_LOW_SPEED_TIME:
1622 * The low speed time that if transfers are below the set
1623 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1625 data->set.low_speed_time=va_arg(param, long);
1631 if(data->change.url_alloc) {
1632 /* the already set URL is allocated, free it first! */
1633 free(data->change.url);
1634 data->change.url_alloc=FALSE;
1636 result = setstropt(&data->set.str[STRING_SET_URL],
1637 va_arg(param, char *));
1638 data->change.url = data->set.str[STRING_SET_URL];
1642 * The port number to use when getting the URL
1644 data->set.use_port = va_arg(param, long);
1646 case CURLOPT_TIMEOUT:
1648 * The maximum time you allow curl to use for a single transfer
1651 data->set.timeout = va_arg(param, long) * 1000L;
1654 case CURLOPT_TIMEOUT_MS:
1655 data->set.timeout = va_arg(param, long);
1658 case CURLOPT_CONNECTTIMEOUT:
1660 * The maximum time you allow curl to use to connect.
1662 data->set.connecttimeout = va_arg(param, long) * 1000L;
1665 case CURLOPT_CONNECTTIMEOUT_MS:
1666 data->set.connecttimeout = va_arg(param, long);
1669 case CURLOPT_USERPWD:
1671 * user:password to use in the operation
1673 result = setstropt_userpwd(va_arg(param, char *),
1674 &data->set.str[STRING_USERNAME],
1675 &data->set.str[STRING_PASSWORD]);
1677 case CURLOPT_USERNAME:
1679 * authentication user name to use in the operation
1681 result = setstropt(&data->set.str[STRING_USERNAME],
1682 va_arg(param, char *));
1684 case CURLOPT_PASSWORD:
1686 * authentication password to use in the operation
1688 result = setstropt(&data->set.str[STRING_PASSWORD],
1689 va_arg(param, char *));
1691 case CURLOPT_POSTQUOTE:
1693 * List of RAW FTP commands to use after a transfer
1695 data->set.postquote = va_arg(param, struct curl_slist *);
1697 case CURLOPT_PREQUOTE:
1699 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1701 data->set.prequote = va_arg(param, struct curl_slist *);
1705 * List of RAW FTP commands to use before a transfer
1707 data->set.quote = va_arg(param, struct curl_slist *);
1709 case CURLOPT_RESOLVE:
1711 * List of NAME:[address] names to populate the DNS cache with
1712 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1714 * Names added with this API will remain in the cache until explicitly
1715 * removed or the handle is cleaned up.
1717 * This API can remove any name from the DNS cache, but only entries
1718 * that aren't actually in use right now will be pruned immediately.
1720 data->set.resolve = va_arg(param, struct curl_slist *);
1721 data->change.resolve = data->set.resolve;
1723 case CURLOPT_PROGRESSFUNCTION:
1725 * Progress callback function
1727 data->set.fprogress = va_arg(param, curl_progress_callback);
1728 if(data->set.fprogress)
1729 data->progress.callback = TRUE; /* no longer internal */
1731 data->progress.callback = FALSE; /* NULL enforces internal */
1734 case CURLOPT_PROGRESSDATA:
1736 * Custom client data to pass to the progress callback
1738 data->set.progress_client = va_arg(param, void *);
1741 #ifndef CURL_DISABLE_PROXY
1742 case CURLOPT_PROXYUSERPWD:
1744 * user:password needed to use the proxy
1746 result = setstropt_userpwd(va_arg(param, char *),
1747 &data->set.str[STRING_PROXYUSERNAME],
1748 &data->set.str[STRING_PROXYPASSWORD]);
1750 case CURLOPT_PROXYUSERNAME:
1752 * authentication user name to use in the operation
1754 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1755 va_arg(param, char *));
1757 case CURLOPT_PROXYPASSWORD:
1759 * authentication password to use in the operation
1761 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1762 va_arg(param, char *));
1764 case CURLOPT_NOPROXY:
1766 * proxy exception list
1768 result = setstropt(&data->set.str[STRING_NOPROXY],
1769 va_arg(param, char *));
1775 * What range of the file you want to transfer
1777 result = setstropt(&data->set.str[STRING_SET_RANGE],
1778 va_arg(param, char *));
1780 case CURLOPT_RESUME_FROM:
1782 * Resume transfer at the give file position
1784 data->set.set_resume_from = va_arg(param, long);
1786 case CURLOPT_RESUME_FROM_LARGE:
1788 * Resume transfer at the give file position
1790 data->set.set_resume_from = va_arg(param, curl_off_t);
1792 case CURLOPT_DEBUGFUNCTION:
1794 * stderr write callback.
1796 data->set.fdebug = va_arg(param, curl_debug_callback);
1798 * if the callback provided is NULL, it'll use the default callback
1801 case CURLOPT_DEBUGDATA:
1803 * Set to a void * that should receive all error writes. This
1804 * defaults to CURLOPT_STDERR for normal operations.
1806 data->set.debugdata = va_arg(param, void *);
1808 case CURLOPT_STDERR:
1810 * Set to a FILE * that should receive all error writes. This
1811 * defaults to stderr for normal operations.
1813 data->set.err = va_arg(param, FILE *);
1815 data->set.err = stderr;
1817 case CURLOPT_HEADERFUNCTION:
1819 * Set header write callback
1821 data->set.fwrite_header = va_arg(param, curl_write_callback);
1823 case CURLOPT_WRITEFUNCTION:
1825 * Set data write callback
1827 data->set.fwrite_func = va_arg(param, curl_write_callback);
1828 if(!data->set.fwrite_func) {
1829 data->set.is_fwrite_set = 0;
1830 /* When set to NULL, reset to our internal default function */
1831 data->set.fwrite_func = (curl_write_callback)fwrite;
1834 data->set.is_fwrite_set = 1;
1836 case CURLOPT_READFUNCTION:
1838 * Read data callback
1840 data->set.fread_func = va_arg(param, curl_read_callback);
1841 if(!data->set.fread_func) {
1842 data->set.is_fread_set = 0;
1843 /* When set to NULL, reset to our internal default function */
1844 data->set.fread_func = (curl_read_callback)fread;
1847 data->set.is_fread_set = 1;
1849 case CURLOPT_SEEKFUNCTION:
1851 * Seek callback. Might be NULL.
1853 data->set.seek_func = va_arg(param, curl_seek_callback);
1855 case CURLOPT_SEEKDATA:
1857 * Seek control callback. Might be NULL.
1859 data->set.seek_client = va_arg(param, void *);
1861 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1863 * "Convert from network encoding" callback
1865 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1867 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1869 * "Convert to network encoding" callback
1871 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1873 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1875 * "Convert from UTF-8 encoding" callback
1877 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1879 case CURLOPT_IOCTLFUNCTION:
1881 * I/O control callback. Might be NULL.
1883 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1885 case CURLOPT_IOCTLDATA:
1887 * I/O control data pointer. Might be NULL.
1889 data->set.ioctl_client = va_arg(param, void *);
1891 case CURLOPT_SSLCERT:
1893 * String that holds file name of the SSL certificate to use
1895 result = setstropt(&data->set.str[STRING_CERT],
1896 va_arg(param, char *));
1898 case CURLOPT_SSLCERTTYPE:
1900 * String that holds file type of the SSL certificate to use
1902 result = setstropt(&data->set.str[STRING_CERT_TYPE],
1903 va_arg(param, char *));
1905 case CURLOPT_SSLKEY:
1907 * String that holds file name of the SSL key to use
1909 result = setstropt(&data->set.str[STRING_KEY],
1910 va_arg(param, char *));
1912 case CURLOPT_SSLKEYTYPE:
1914 * String that holds file type of the SSL key to use
1916 result = setstropt(&data->set.str[STRING_KEY_TYPE],
1917 va_arg(param, char *));
1919 case CURLOPT_KEYPASSWD:
1921 * String that holds the SSL or SSH private key password.
1923 result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1924 va_arg(param, char *));
1926 case CURLOPT_SSLENGINE:
1928 * String that holds the SSL crypto engine.
1930 argptr = va_arg(param, char *);
1931 if(argptr && argptr[0])
1932 result = Curl_ssl_set_engine(data, argptr);
1935 case CURLOPT_SSLENGINE_DEFAULT:
1937 * flag to set engine as default.
1939 result = Curl_ssl_set_engine_default(data);
1943 * Kludgy option to enable CRLF conversions. Subject for removal.
1945 data->set.crlf = (bool)(0 != va_arg(param, long));
1948 case CURLOPT_INTERFACE:
1950 * Set what interface or address/hostname to bind the socket to when
1951 * performing an operation and thus what from-IP your connection will use.
1953 result = setstropt(&data->set.str[STRING_DEVICE],
1954 va_arg(param, char *));
1956 case CURLOPT_LOCALPORT:
1958 * Set what local port to bind the socket to when performing an operation.
1960 data->set.localport = curlx_sltous(va_arg(param, long));
1962 case CURLOPT_LOCALPORTRANGE:
1964 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
1966 data->set.localportrange = curlx_sltosi(va_arg(param, long));
1968 case CURLOPT_KRBLEVEL:
1970 * A string that defines the kerberos security level.
1972 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
1973 va_arg(param, char *));
1974 data->set.krb = (bool)(NULL != data->set.str[STRING_KRB_LEVEL]);
1976 case CURLOPT_GSSAPI_DELEGATION:
1978 * GSSAPI credential delegation
1980 data->set.gssapi_delegation = va_arg(param, long);
1982 case CURLOPT_SSL_VERIFYPEER:
1984 * Enable peer SSL verifying.
1986 data->set.ssl.verifypeer = va_arg(param, long);
1988 case CURLOPT_SSL_VERIFYHOST:
1990 * Enable verification of the CN contained in the peer certificate
1992 data->set.ssl.verifyhost = va_arg(param, long);
1995 /* since these two options are only possible to use on an OpenSSL-
1996 powered libcurl we #ifdef them on this condition so that libcurls
1997 built against other SSL libs will return a proper error when trying
1998 to set this option! */
1999 case CURLOPT_SSL_CTX_FUNCTION:
2001 * Set a SSL_CTX callback
2003 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
2005 case CURLOPT_SSL_CTX_DATA:
2007 * Set a SSL_CTX callback parameter pointer
2009 data->set.ssl.fsslctxp = va_arg(param, void *);
2011 case CURLOPT_CERTINFO:
2012 data->set.ssl.certinfo = (bool)(0 != va_arg(param, long));
2015 case CURLOPT_CAINFO:
2017 * Set CA info for SSL connection. Specify file name of the CA certificate
2019 result = setstropt(&data->set.str[STRING_SSL_CAFILE],
2020 va_arg(param, char *));
2022 case CURLOPT_CAPATH:
2024 * Set CA path info for SSL connection. Specify directory name of the CA
2025 * certificates which have been prepared using openssl c_rehash utility.
2027 /* This does not work on windows. */
2028 result = setstropt(&data->set.str[STRING_SSL_CAPATH],
2029 va_arg(param, char *));
2031 case CURLOPT_CRLFILE:
2033 * Set CRL file info for SSL connection. Specify file name of the CRL
2034 * to check certificates revocation
2036 result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
2037 va_arg(param, char *));
2039 case CURLOPT_ISSUERCERT:
2041 * Set Issuer certificate file
2042 * to check certificates issuer
2044 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
2045 va_arg(param, char *));
2047 case CURLOPT_TELNETOPTIONS:
2049 * Set a linked list of telnet options
2051 data->set.telnet_options = va_arg(param, struct curl_slist *);
2054 case CURLOPT_BUFFERSIZE:
2056 * The application kindly asks for a differently sized receive buffer.
2057 * If it seems reasonable, we'll use it.
2059 data->set.buffer_size = va_arg(param, long);
2061 if((data->set.buffer_size> (BUFSIZE -1 )) ||
2062 (data->set.buffer_size < 1))
2063 data->set.buffer_size = 0; /* huge internal default */
2067 case CURLOPT_NOSIGNAL:
2069 * The application asks not to set any signal() or alarm() handlers,
2070 * even when using a timeout.
2072 data->set.no_signal = (bool)(0 != va_arg(param, long));
2077 struct Curl_share *set;
2078 set = va_arg(param, struct Curl_share *);
2080 /* disconnect from old share, if any */
2082 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2084 if(data->dns.hostcachetype == HCACHE_SHARED) {
2085 data->dns.hostcache = NULL;
2086 data->dns.hostcachetype = HCACHE_NONE;
2089 if(data->share->cookies == data->cookies)
2090 data->cookies = NULL;
2092 data->share->dirty--;
2094 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2098 /* use new share if it set */
2102 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2104 data->share->dirty++;
2106 if(data->share->hostcache) {
2107 /* use shared host cache, first free the private one if any */
2108 if(data->dns.hostcachetype == HCACHE_PRIVATE)
2109 Curl_hash_destroy(data->dns.hostcache);
2111 data->dns.hostcache = data->share->hostcache;
2112 data->dns.hostcachetype = HCACHE_SHARED;
2114 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2115 if(data->share->cookies) {
2116 /* use shared cookie list, first free own one if any */
2118 Curl_cookie_cleanup(data->cookies);
2119 /* enable cookies since we now use a share that uses cookies! */
2120 data->cookies = data->share->cookies;
2122 #endif /* CURL_DISABLE_HTTP */
2123 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2126 /* check for host cache not needed,
2127 * it will be done by curl_easy_perform */
2131 case CURLOPT_PRIVATE:
2133 * Set private data pointer.
2135 data->set.private_data = va_arg(param, void *);
2138 case CURLOPT_MAXFILESIZE:
2140 * Set the maximum size of a file to download.
2142 data->set.max_filesize = va_arg(param, long);
2146 case CURLOPT_USE_SSL:
2148 * Make transfers attempt to use SSL/TLS.
2150 data->set.ftp_ssl = (curl_usessl)va_arg(param, long);
2153 case CURLOPT_FTPSSLAUTH:
2155 * Set a specific auth for FTP-SSL transfers.
2157 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2160 case CURLOPT_IPRESOLVE:
2161 data->set.ipver = va_arg(param, long);
2164 case CURLOPT_MAXFILESIZE_LARGE:
2166 * Set the maximum size of a file to download.
2168 data->set.max_filesize = va_arg(param, curl_off_t);
2171 case CURLOPT_TCP_NODELAY:
2173 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2176 data->set.tcp_nodelay = (bool)(0 != va_arg(param, long));
2179 case CURLOPT_FTP_ACCOUNT:
2180 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2181 va_arg(param, char *));
2184 case CURLOPT_IGNORE_CONTENT_LENGTH:
2185 data->set.ignorecl = (bool)(0 != va_arg(param, long));
2188 case CURLOPT_CONNECT_ONLY:
2190 * No data transfer, set up connection and let application use the socket
2192 data->set.connect_only = (bool)(0 != va_arg(param, long));
2195 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2196 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2197 va_arg(param, char *));
2200 case CURLOPT_SOCKOPTFUNCTION:
2202 * socket callback function: called after socket() but before connect()
2204 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2207 case CURLOPT_SOCKOPTDATA:
2209 * socket callback data pointer. Might be NULL.
2211 data->set.sockopt_client = va_arg(param, void *);
2214 case CURLOPT_OPENSOCKETFUNCTION:
2216 * open/create socket callback function: called instead of socket(),
2219 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2222 case CURLOPT_OPENSOCKETDATA:
2224 * socket callback data pointer. Might be NULL.
2226 data->set.opensocket_client = va_arg(param, void *);
2229 case CURLOPT_CLOSESOCKETFUNCTION:
2231 * close socket callback function: called instead of close()
2232 * when shutting down a connection
2234 data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
2237 case CURLOPT_CLOSESOCKETDATA:
2239 * socket callback data pointer. Might be NULL.
2241 data->set.closesocket_client = va_arg(param, void *);
2244 case CURLOPT_SSL_SESSIONID_CACHE:
2245 data->set.ssl.sessionid = (bool)(0 != va_arg(param, long));
2249 /* we only include SSH options if explicitly built to support SSH */
2250 case CURLOPT_SSH_AUTH_TYPES:
2251 data->set.ssh_auth_types = va_arg(param, long);
2254 case CURLOPT_SSH_PUBLIC_KEYFILE:
2256 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2258 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2259 va_arg(param, char *));
2262 case CURLOPT_SSH_PRIVATE_KEYFILE:
2264 * Use this file instead of the $HOME/.ssh/id_dsa file
2266 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2267 va_arg(param, char *));
2269 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2271 * Option to allow for the MD5 of the host public key to be checked
2272 * for validation purposes.
2274 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2275 va_arg(param, char *));
2277 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2278 case CURLOPT_SSH_KNOWNHOSTS:
2280 * Store the file name to read known hosts from.
2282 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2283 va_arg(param, char *));
2286 case CURLOPT_SSH_KEYFUNCTION:
2287 /* setting to NULL is fine since the ssh.c functions themselves will
2288 then rever to use the internal default */
2289 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2292 case CURLOPT_SSH_KEYDATA:
2294 * Custom client data to pass to the SSH keyfunc callback
2296 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2298 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2300 #endif /* USE_LIBSSH2 */
2302 case CURLOPT_HTTP_TRANSFER_DECODING:
2304 * disable libcurl transfer encoding is used
2306 data->set.http_te_skip = (bool)(0 == va_arg(param, long));
2309 case CURLOPT_HTTP_CONTENT_DECODING:
2311 * raw data passed to the application when content encoding is used
2313 data->set.http_ce_skip = (bool)(0 == va_arg(param, long));
2316 case CURLOPT_NEW_FILE_PERMS:
2318 * Uses these permissions instead of 0644
2320 data->set.new_file_perms = va_arg(param, long);
2323 case CURLOPT_NEW_DIRECTORY_PERMS:
2325 * Uses these permissions instead of 0755
2327 data->set.new_directory_perms = va_arg(param, long);
2330 case CURLOPT_ADDRESS_SCOPE:
2332 * We always get longs when passed plain numericals, but for this value we
2333 * know that an unsigned int will always hold the value so we blindly
2334 * typecast to this type
2336 data->set.scope = curlx_sltoui(va_arg(param, long));
2339 case CURLOPT_PROTOCOLS:
2340 /* set the bitmask for the protocols that are allowed to be used for the
2341 transfer, which thus helps the app which takes URLs from users or other
2342 external inputs and want to restrict what protocol(s) to deal
2343 with. Defaults to CURLPROTO_ALL. */
2344 data->set.allowed_protocols = va_arg(param, long);
2347 case CURLOPT_REDIR_PROTOCOLS:
2348 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2349 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2350 to be set in both bitmasks to be allowed to get redirected to. Defaults
2351 to all protocols except FILE and SCP. */
2352 data->set.redir_protocols = va_arg(param, long);
2355 case CURLOPT_MAIL_FROM:
2356 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2357 va_arg(param, char *));
2360 case CURLOPT_MAIL_RCPT:
2361 /* get a list of mail recipients */
2362 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2365 case CURLOPT_RTSP_REQUEST:
2368 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2369 * Would this be better if the RTSPREQ_* were just moved into here?
2371 long curl_rtspreq = va_arg(param, long);
2372 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2373 switch(curl_rtspreq) {
2374 case CURL_RTSPREQ_OPTIONS:
2375 rtspreq = RTSPREQ_OPTIONS;
2378 case CURL_RTSPREQ_DESCRIBE:
2379 rtspreq = RTSPREQ_DESCRIBE;
2382 case CURL_RTSPREQ_ANNOUNCE:
2383 rtspreq = RTSPREQ_ANNOUNCE;
2386 case CURL_RTSPREQ_SETUP:
2387 rtspreq = RTSPREQ_SETUP;
2390 case CURL_RTSPREQ_PLAY:
2391 rtspreq = RTSPREQ_PLAY;
2394 case CURL_RTSPREQ_PAUSE:
2395 rtspreq = RTSPREQ_PAUSE;
2398 case CURL_RTSPREQ_TEARDOWN:
2399 rtspreq = RTSPREQ_TEARDOWN;
2402 case CURL_RTSPREQ_GET_PARAMETER:
2403 rtspreq = RTSPREQ_GET_PARAMETER;
2406 case CURL_RTSPREQ_SET_PARAMETER:
2407 rtspreq = RTSPREQ_SET_PARAMETER;
2410 case CURL_RTSPREQ_RECORD:
2411 rtspreq = RTSPREQ_RECORD;
2414 case CURL_RTSPREQ_RECEIVE:
2415 rtspreq = RTSPREQ_RECEIVE;
2418 rtspreq = RTSPREQ_NONE;
2421 data->set.rtspreq = rtspreq;
2426 case CURLOPT_RTSP_SESSION_ID:
2428 * Set the RTSP Session ID manually. Useful if the application is
2429 * resuming a previously established RTSP session
2431 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2432 va_arg(param, char *));
2435 case CURLOPT_RTSP_STREAM_URI:
2437 * Set the Stream URI for the RTSP request. Unless the request is
2438 * for generic server options, the application will need to set this.
2440 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2441 va_arg(param, char *));
2444 case CURLOPT_RTSP_TRANSPORT:
2446 * The content of the Transport: header for the RTSP request
2448 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2449 va_arg(param, char *));
2452 case CURLOPT_RTSP_CLIENT_CSEQ:
2454 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2455 * application is resuming a previously broken connection. The CSEQ
2456 * will increment from this new number henceforth.
2458 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2461 case CURLOPT_RTSP_SERVER_CSEQ:
2462 /* Same as the above, but for server-initiated requests */
2463 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2466 case CURLOPT_INTERLEAVEDATA:
2467 data->set.rtp_out = va_arg(param, void *);
2469 case CURLOPT_INTERLEAVEFUNCTION:
2470 /* Set the user defined RTP write function */
2471 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2474 case CURLOPT_WILDCARDMATCH:
2475 data->set.wildcardmatch = (bool)(0 != va_arg(param, long));
2477 case CURLOPT_CHUNK_BGN_FUNCTION:
2478 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2480 case CURLOPT_CHUNK_END_FUNCTION:
2481 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2483 case CURLOPT_FNMATCH_FUNCTION:
2484 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2486 case CURLOPT_CHUNK_DATA:
2487 data->wildcard.customptr = va_arg(param, void *);
2489 case CURLOPT_FNMATCH_DATA:
2490 data->set.fnmatch_data = va_arg(param, void *);
2493 case CURLOPT_TLSAUTH_USERNAME:
2494 result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
2495 va_arg(param, char *));
2496 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2497 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2499 case CURLOPT_TLSAUTH_PASSWORD:
2500 result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
2501 va_arg(param, char *));
2502 if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
2503 data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
2505 case CURLOPT_TLSAUTH_TYPE:
2506 if(strncmp((char *)va_arg(param, char *), "SRP", strlen("SRP")) == 0)
2507 data->set.ssl.authtype = CURL_TLSAUTH_SRP;
2509 data->set.ssl.authtype = CURL_TLSAUTH_NONE;
2513 /* unknown tag and its companion, just ignore: */
2514 result = CURLE_UNKNOWN_OPTION;
2521 static void conn_free(struct connectdata *conn)
2526 /* possible left-overs from the async name resolvers */
2527 Curl_resolver_cancel(conn);
2529 /* close the SSL stuff before we close any sockets since they will/may
2530 write to the sockets */
2531 Curl_ssl_close(conn, FIRSTSOCKET);
2532 Curl_ssl_close(conn, SECONDARYSOCKET);
2534 /* close possibly still open sockets */
2535 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2536 Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
2537 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2538 Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
2540 Curl_safefree(conn->user);
2541 Curl_safefree(conn->passwd);
2542 Curl_safefree(conn->proxyuser);
2543 Curl_safefree(conn->proxypasswd);
2544 Curl_safefree(conn->allocptr.proxyuserpwd);
2545 Curl_safefree(conn->allocptr.uagent);
2546 Curl_safefree(conn->allocptr.userpwd);
2547 Curl_safefree(conn->allocptr.accept_encoding);
2548 Curl_safefree(conn->allocptr.te);
2549 Curl_safefree(conn->allocptr.rangeline);
2550 Curl_safefree(conn->allocptr.ref);
2551 Curl_safefree(conn->allocptr.host);
2552 Curl_safefree(conn->allocptr.cookiehost);
2553 Curl_safefree(conn->allocptr.rtsp_transport);
2554 Curl_safefree(conn->trailer);
2555 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2556 Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2557 Curl_safefree(conn->master_buffer);
2559 Curl_llist_destroy(conn->send_pipe, NULL);
2560 Curl_llist_destroy(conn->recv_pipe, NULL);
2561 Curl_llist_destroy(conn->pend_pipe, NULL);
2562 Curl_llist_destroy(conn->done_pipe, NULL);
2564 Curl_safefree(conn->localdev);
2565 Curl_free_ssl_config(&conn->ssl_config);
2567 free(conn); /* free all the connection oriented data */
2570 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2572 struct SessionHandle *data;
2574 return CURLE_OK; /* this is closed and fine already */
2578 DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
2582 if(conn->dns_entry != NULL) {
2583 Curl_resolv_unlock(data, conn->dns_entry);
2584 conn->dns_entry = NULL;
2587 #if defined(DEBUGBUILD) && defined(AGGRESIVE_TEST)
2588 /* scan for DNS cache entries still marked as in use */
2589 Curl_hash_apply(data->hostcache,
2590 NULL, Curl_scan_cache_used);
2593 Curl_hostcache_prune(data); /* kill old DNS cache entries */
2596 int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
2597 int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
2599 /* Authentication data is a mix of connection-related and sessionhandle-
2600 related stuff. NTLM is connection-related so when we close the shop
2604 data->state.authhost.done = FALSE;
2605 data->state.authhost.picked =
2606 data->state.authhost.want;
2609 if(has_proxy_ntlm) {
2610 data->state.authproxy.done = FALSE;
2611 data->state.authproxy.picked =
2612 data->state.authproxy.want;
2615 if(has_host_ntlm || has_proxy_ntlm) {
2616 data->state.authproblem = FALSE;
2618 Curl_http_ntlm_cleanup(conn);
2622 /* Cleanup possible redirect junk */
2623 if(data->req.newurl) {
2624 free(data->req.newurl);
2625 data->req.newurl = NULL;
2628 if(conn->handler->disconnect)
2629 /* This is set if protocol-specific cleanups should be made */
2630 conn->handler->disconnect(conn, dead_connection);
2632 if(-1 != conn->connectindex) {
2633 /* unlink ourselves! */
2634 infof(data, "Closing connection #%ld\n", conn->connectindex);
2635 if(data->state.connc)
2636 /* only clear the table entry if we still know in which cache we
2638 data->state.connc->connects[conn->connectindex] = NULL;
2641 #if defined(USE_LIBIDN)
2642 if(conn->host.encalloc)
2643 idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
2644 with idn_free() since this was allocated
2646 if(conn->proxy.encalloc)
2647 idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
2648 freed with idn_free() since this was
2649 allocated by libidn */
2650 #elif defined(USE_WIN32_IDN)
2651 free(conn->host.encalloc); /* encoded host name buffer, must be freed with
2652 idn_free() since this was allocated by
2653 curl_win32_idn_to_ascii */
2654 if(conn->proxy.encalloc)
2655 free(conn->proxy.encalloc); /* encoded proxy name buffer, must be freed
2656 with idn_free() since this was allocated by
2657 curl_win32_idn_to_ascii */
2660 Curl_ssl_close(conn, FIRSTSOCKET);
2662 /* Indicate to all handles on the pipe that we're dead */
2663 if(Curl_isPipeliningEnabled(data)) {
2664 signalPipeClose(conn->send_pipe, TRUE);
2665 signalPipeClose(conn->recv_pipe, TRUE);
2666 signalPipeClose(conn->pend_pipe, TRUE);
2667 signalPipeClose(conn->done_pipe, FALSE);
2671 data->state.current_conn = NULL;
2672 Curl_speedinit(data);
2678 * This function should return TRUE if the socket is to be assumed to
2679 * be dead. Most commonly this happens when the server has closed the
2680 * connection due to inactivity.
2682 static bool SocketIsDead(curl_socket_t sock)
2685 bool ret_val = TRUE;
2687 sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2695 static bool IsPipeliningPossible(const struct SessionHandle *handle,
2696 const struct connectdata *conn)
2698 if((conn->handler->protocol & CURLPROTO_HTTP) &&
2699 handle->multi && Curl_multi_canPipeline(handle->multi) &&
2700 (handle->set.httpreq == HTTPREQ_GET ||
2701 handle->set.httpreq == HTTPREQ_HEAD) &&
2702 handle->set.httpversion != CURL_HTTP_VERSION_1_0)
2708 bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
2710 if(handle->multi && Curl_multi_canPipeline(handle->multi))
2716 CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
2717 struct curl_llist *pipeline)
2719 if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
2720 return CURLE_OUT_OF_MEMORY;
2724 int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
2725 struct curl_llist *pipeline)
2727 struct curl_llist_element *curr;
2729 curr = pipeline->head;
2731 if(curr->ptr == handle) {
2732 Curl_llist_remove(pipeline, curr, NULL);
2733 return 1; /* we removed a handle */
2741 #if 0 /* this code is saved here as it is useful for debugging purposes */
2742 static void Curl_printPipeline(struct curl_llist *pipeline)
2744 struct curl_llist_element *curr;
2746 curr = pipeline->head;
2748 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2749 infof(data, "Handle in pipeline: %s\n", data->state.path);
2755 static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
2757 struct curl_llist_element *curr = pipeline->head;
2759 return (struct SessionHandle *) curr->ptr;
2765 /* remove the specified connection from all (possible) pipelines and related
2767 void Curl_getoff_all_pipelines(struct SessionHandle *data,
2768 struct connectdata *conn)
2770 bool recv_head = (bool)(conn->readchannel_inuse &&
2771 (gethandleathead(conn->recv_pipe) == data));
2773 bool send_head = (bool)(conn->writechannel_inuse &&
2774 (gethandleathead(conn->send_pipe) == data));
2776 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2777 conn->readchannel_inuse = FALSE;
2778 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2779 conn->writechannel_inuse = FALSE;
2780 Curl_removeHandleFromPipeline(data, conn->pend_pipe);
2781 Curl_removeHandleFromPipeline(data, conn->done_pipe);
2784 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2786 struct curl_llist_element *curr;
2791 curr = pipeline->head;
2793 struct curl_llist_element *next = curr->next;
2794 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2796 #ifdef DEBUGBUILD /* debug-only code */
2797 if(data->magic != CURLEASY_MAGIC_NUMBER) {
2799 infof(data, "signalPipeClose() found BAAD easy handle\n");
2804 data->state.pipe_broke = TRUE;
2805 Curl_multi_handlePipeBreak(data);
2806 Curl_llist_remove(pipeline, curr, NULL);
2813 * Given one filled in connection struct (named needle), this function should
2814 * detect if there already is one that has all the significant details
2815 * exactly the same and thus should be used instead.
2817 * If there is a match, this function returns TRUE - and has marked the
2818 * connection as 'in-use'. It must later be called with ConnectionDone() to
2819 * return back to 'idle' (unused) state.
2822 ConnectionExists(struct SessionHandle *data,
2823 struct connectdata *needle,
2824 struct connectdata **usethis)
2827 struct connectdata *check;
2828 bool canPipeline = IsPipeliningPossible(data, needle);
2830 for(i=0; i< data->state.connc->num; i++) {
2834 * Note that if we use a HTTP proxy, we check connections to that
2835 * proxy and not to the actual remote server.
2837 check = data->state.connc->connects[i];
2839 /* NULL pointer means not filled-in entry */
2842 pipeLen = check->send_pipe->size + check->recv_pipe->size;
2844 if(check->connectindex == -1) {
2845 check->connectindex = i; /* Set this appropriately since it might have
2846 been set to -1 when the easy was removed
2850 if(!pipeLen && !check->inuse) {
2851 /* The check for a dead socket makes sense only if there are no
2852 handles in pipeline and the connection isn't already marked in
2855 if(check->handler->protocol & CURLPROTO_RTSP)
2856 /* RTSP is a special case due to RTP interleaving */
2857 dead = Curl_rtsp_connisdead(check);
2859 dead = SocketIsDead(check->sock[FIRSTSOCKET]);
2863 infof(data, "Connection #%ld seems to be dead!\n", i);
2865 /* disconnect resources */
2866 Curl_disconnect(check, /* dead_connection */ TRUE);
2867 data->state.connc->connects[i]=NULL; /* nothing here */
2874 /* Make sure the pipe has only GET requests */
2875 struct SessionHandle* sh = gethandleathead(check->send_pipe);
2876 struct SessionHandle* rh = gethandleathead(check->recv_pipe);
2878 if(!IsPipeliningPossible(sh, check))
2882 if(!IsPipeliningPossible(rh, check))
2887 if(pipeLen > MAX_PIPELINE_LENGTH) {
2888 infof(data, "BAD! Connection #%ld has too big pipeline!\n",
2889 check->connectindex);
2895 /* can only happen within multi handles, and means that another easy
2896 handle is using this connection */
2900 if(Curl_resolver_asynch()) {
2901 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
2902 completed yet and until then we don't re-use this connection */
2903 if(!check->ip_addr_str[0]) {
2905 "Connection #%ld hasn't finished name resolve, can't reuse\n",
2906 check->connectindex);
2911 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) || check->bits.close) {
2912 /* Don't pick a connection that hasn't connected yet or that is going
2914 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
2915 check->connectindex);
2917 if(check->recv_pipe->size > 0) {
2918 infof(data, "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
2919 check->connectindex);
2926 if((needle->handler->flags&PROTOPT_SSL) !=
2927 (check->handler->flags&PROTOPT_SSL))
2928 /* don't do mixed SSL and non-SSL connections */
2931 if(needle->handler->flags&PROTOPT_SSL) {
2932 if((data->set.ssl.verifypeer != check->verifypeer) ||
2933 (data->set.ssl.verifyhost != check->verifyhost))
2937 if(needle->bits.proxy != check->bits.proxy)
2938 /* don't do mixed proxy and non-proxy connections */
2941 if(!canPipeline && check->inuse)
2942 /* this request can't be pipelined but the checked connection is already
2943 in use so we skip it */
2946 if(needle->localdev || needle->localport) {
2947 /* If we are bound to a specific local end (IP+port), we must not re-use
2948 a random other one, although if we didn't ask for a particular one we
2949 can reuse one that was bound.
2951 This comparison is a bit rough and too strict. Since the input
2952 parameters can be specified in numerous ways and still end up the
2953 same it would take a lot of processing to make it really accurate.
2954 Instead, this matching will assume that re-uses of bound connections
2955 will most likely also re-use the exact same binding parameters and
2956 missing out a few edge cases shouldn't hurt anyone very much.
2958 if((check->localport != needle->localport) ||
2959 (check->localportrange != needle->localportrange) ||
2961 !needle->localdev ||
2962 strcmp(check->localdev, needle->localdev))
2966 if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
2967 (needle->bits.httpproxy && check->bits.httpproxy &&
2968 needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
2969 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
2970 (needle->port == check->port))) {
2971 /* The requested connection does not use a HTTP proxy or it uses SSL or
2972 it is a non-SSL protocol tunneled over the same http proxy name and
2975 if(Curl_raw_equal(needle->handler->scheme, check->handler->scheme) &&
2976 Curl_raw_equal(needle->host.name, check->host.name) &&
2977 (needle->remote_port == check->remote_port) ) {
2978 if(needle->handler->flags & PROTOPT_SSL) {
2979 /* This is SSL, verify that we're using the same
2980 ssl options as well */
2981 if(!Curl_ssl_config_matches(&needle->ssl_config,
2982 &check->ssl_config)) {
2984 "Connection #%ld has different SSL parameters, "
2986 check->connectindex));
2989 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
2991 "Connection #%ld has not started ssl connect, "
2993 check->connectindex));
2997 if((needle->handler->protocol & CURLPROTO_FTP) ||
2998 ((needle->handler->protocol & CURLPROTO_HTTP) &&
2999 ((data->state.authhost.want==CURLAUTH_NTLM) ||
3000 (data->state.authhost.want==CURLAUTH_NTLM_WB)))) {
3001 /* This is FTP or HTTP+NTLM, verify that we're using the same name
3002 and password as well */
3003 if(!strequal(needle->user, check->user) ||
3004 !strequal(needle->passwd, check->passwd)) {
3005 /* one of them was different */
3012 else { /* The requested needle connection is using a proxy,
3013 is the checked one using the same host, port and type? */
3014 if(check->bits.proxy &&
3015 (needle->proxytype == check->proxytype) &&
3016 (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
3017 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3018 needle->port == check->port) {
3019 /* This is the same proxy connection, use it! */
3025 check->inuse = TRUE; /* mark this as being in use so that no other
3026 handle in a multi stack may nick it */
3029 return TRUE; /* yes, we found one to use! */
3033 return FALSE; /* no matching connecting exists */
3039 * This function kills and removes an existing connection in the connection
3040 * cache. The connection that has been unused for the longest time.
3042 * Returns -1 if it can't find any unused connection to kill.
3045 ConnectionKillOne(struct SessionHandle *data)
3048 struct connectdata *conn;
3056 for(i=0; data->state.connc && (i< data->state.connc->num); i++) {
3057 conn = data->state.connc->connects[i];
3059 if(!conn || conn->inuse)
3062 /* Set higher score for the age passed since the connection was used */
3063 score = Curl_tvdiff(now, conn->now);
3065 if(score > highscore) {
3070 if(connindex >= 0) {
3071 /* Set the connection's owner correctly */
3072 conn = data->state.connc->connects[connindex];
3075 /* the winner gets the honour of being disconnected */
3076 (void)Curl_disconnect(conn, /* dead_connection */ FALSE);
3078 /* clean the array entry */
3079 data->state.connc->connects[connindex] = NULL;
3082 return connindex; /* return the available index or -1 */
3085 /* this connection can now be marked 'idle' */
3087 ConnectionDone(struct connectdata *conn)
3089 conn->inuse = FALSE;
3093 * The given input connection struct pointer is to be stored in the connection
3094 * cache. If the cache is already full, least interesting existing connection
3095 * (if any) gets closed.
3097 * The given connection should be unique. That must've been checked prior to
3100 static void ConnectionStore(struct SessionHandle *data,
3101 struct connectdata *conn)
3104 for(i=0; i< data->state.connc->num; i++) {
3105 if(!data->state.connc->connects[i])
3108 if(i == data->state.connc->num) {
3109 /* there was no room available, kill one */
3110 i = ConnectionKillOne(data);
3112 infof(data, "Connection (#%ld) was killed to make room (holds %ld)\n",
3113 i, data->state.connc->num);
3115 infof(data, "This connection did not fit in the connection cache\n");
3118 conn->connectindex = i; /* Make the child know where the pointer to this
3119 particular data is stored. But note that this -1
3120 if this is not within the cache and this is
3121 probably not checked for everywhere (yet). */
3124 /* Only do this if a true index was returned, if -1 was returned there
3125 is no room in the cache for an unknown reason and we cannot store
3128 TODO: make sure we really can work with more handles than positions in
3129 the cache, or possibly we should (allow to automatically) resize the
3130 connection cache when we add more easy handles to a multi handle!
3132 data->state.connc->connects[i] = conn; /* fill in this */
3137 /* after a TCP connection to the proxy has been verified, this function does
3138 the next magic step.
3140 Note: this function's sub-functions call failf()
3143 CURLcode Curl_connected_proxy(struct connectdata *conn)
3145 switch(conn->proxytype) {
3146 #ifndef CURL_DISABLE_PROXY
3147 case CURLPROXY_SOCKS5:
3148 case CURLPROXY_SOCKS5_HOSTNAME:
3149 return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3150 conn->host.name, conn->remote_port,
3153 case CURLPROXY_SOCKS4:
3154 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3155 conn->remote_port, FIRSTSOCKET, conn, FALSE);
3157 case CURLPROXY_SOCKS4A:
3158 return Curl_SOCKS4(conn->proxyuser, conn->host.name,
3159 conn->remote_port, FIRSTSOCKET, conn, TRUE);
3161 #endif /* CURL_DISABLE_PROXY */
3162 case CURLPROXY_HTTP:
3163 case CURLPROXY_HTTP_1_0:
3164 /* do nothing here. handled later. */
3168 } /* switch proxytype */
3173 static CURLcode ConnectPlease(struct SessionHandle *data,
3174 struct connectdata *conn,
3178 Curl_addrinfo *addr;
3179 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3180 char *hostname = conn->bits.proxy?conn->proxy.name:conn->host.name;
3182 infof(data, "About to connect() to %s%s port %ld (#%ld)\n",
3183 conn->bits.proxy?"proxy ":"",
3184 hostname, conn->port, conn->connectindex);
3189 /*************************************************************
3190 * Connect to server/proxy
3191 *************************************************************/
3192 result= Curl_connecthost(conn,
3194 &conn->sock[FIRSTSOCKET],
3197 if(CURLE_OK == result) {
3198 /* All is cool, we store the current information */
3199 conn->ip_addr = addr;
3202 result = Curl_connected_proxy(conn);
3204 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
3205 Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
3211 *connected = FALSE; /* mark it as not connected */
3217 * verboseconnect() displays verbose information after a connect
3219 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3220 void Curl_verboseconnect(struct connectdata *conn)
3222 if(conn->data->set.verbose)
3223 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3224 conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3225 conn->ip_addr_str, conn->port, conn->connectindex);
3229 int Curl_protocol_getsock(struct connectdata *conn,
3230 curl_socket_t *socks,
3233 if(conn->handler->proto_getsock)
3234 return conn->handler->proto_getsock(conn, socks, numsocks);
3235 return GETSOCK_BLANK;
3238 int Curl_doing_getsock(struct connectdata *conn,
3239 curl_socket_t *socks,
3242 if(conn && conn->handler->doing_getsock)
3243 return conn->handler->doing_getsock(conn, socks, numsocks);
3244 return GETSOCK_BLANK;
3248 * We are doing protocol-specific connecting and this is being called over and
3249 * over from the multi interface until the connection phase is done on
3253 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3256 CURLcode result=CURLE_OK;
3258 if(conn && conn->handler->connecting) {
3260 result = conn->handler->connecting(conn, done);
3269 * We are DOING this is being called over and over from the multi interface
3270 * until the DOING phase is done on protocol layer.
3273 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3275 CURLcode result=CURLE_OK;
3277 if(conn && conn->handler->doing) {
3279 result = conn->handler->doing(conn, done);
3288 * We have discovered that the TCP connection has been successful, we can now
3289 * proceed with some action.
3292 CURLcode Curl_protocol_connect(struct connectdata *conn,
3293 bool *protocol_done)
3295 CURLcode result=CURLE_OK;
3296 struct SessionHandle *data = conn->data;
3298 *protocol_done = FALSE;
3300 if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
3301 /* We already are connected, get back. This may happen when the connect
3302 worked fine in the first call, like when we connect to a local server
3303 or proxy. Note that we don't know if the protocol is actually done.
3305 Unless this protocol doesn't have any protocol-connect callback, as
3306 then we know we're done. */
3307 if(!conn->handler->connecting)
3308 *protocol_done = TRUE;
3313 if(!conn->bits.tcpconnect[FIRSTSOCKET]) {
3315 Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
3316 Curl_verboseconnect(conn);
3319 if(!conn->bits.protoconnstart) {
3320 if(conn->handler->connect_it) {
3321 /* is there a protocol-specific connect() procedure? */
3323 /* Set start time here for timeout purposes in the connect procedure, it
3324 is later set again for the progress meter purpose */
3325 conn->now = Curl_tvnow();
3327 /* Call the protocol-specific connect function */
3328 result = conn->handler->connect_it(conn, protocol_done);
3331 *protocol_done = TRUE;
3333 /* it has started, possibly even completed but that knowledge isn't stored
3336 conn->bits.protoconnstart = TRUE;
3339 return result; /* pass back status */
3343 * Helpers for IDNA convertions.
3345 static bool is_ASCII_name(const char *hostname)
3347 const unsigned char *ch = (const unsigned char*)hostname;
3358 * Check if characters in hostname is allowed in Top Level Domain.
3360 static bool tld_check_name(struct SessionHandle *data,
3361 const char *ace_hostname)
3364 char *uc_name = NULL;
3366 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3367 const char *tld_errmsg = "<no msg>";
3372 /* Convert (and downcase) ACE-name back into locale's character set */
3373 rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3374 if(rc != IDNA_SUCCESS)
3377 rc = tld_check_lz(uc_name, &err_pos, NULL);
3378 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3379 #ifdef HAVE_TLD_STRERROR
3380 if(rc != TLD_SUCCESS)
3381 tld_errmsg = tld_strerror((Tld_rc)rc);
3383 if(rc == TLD_INVALID)
3384 infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
3385 tld_errmsg, err_pos, uc_name[err_pos],
3386 uc_name[err_pos] & 255);
3387 else if(rc != TLD_SUCCESS)
3388 infof(data, "WARNING: TLD check for %s failed; %s\n",
3389 uc_name, tld_errmsg);
3390 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3393 if(rc != TLD_SUCCESS)
3401 * Perform any necessary IDN conversion of hostname
3403 static void fix_hostname(struct SessionHandle *data,
3404 struct connectdata *conn, struct hostname *host)
3409 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3413 /* set the name we use to display the host name */
3414 host->dispname = host->name;
3415 if(!is_ASCII_name(host->name)) {
3417 /*************************************************************
3418 * Check name for non-ASCII and convert hostname to ACE form.
3419 *************************************************************/
3420 if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3421 char *ace_hostname = NULL;
3422 int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3423 infof (data, "Input domain encoded as `%s'\n",
3424 stringprep_locale_charset ());
3425 if(rc != IDNA_SUCCESS)
3426 infof(data, "Failed to convert %s to ACE; %s\n",
3427 host->name, Curl_idn_strerror(conn,rc));
3429 /* tld_check_name() displays a warning if the host name contains
3430 "illegal" characters for this TLD */
3431 (void)tld_check_name(data, ace_hostname);
3433 host->encalloc = ace_hostname;
3434 /* change the name pointer to point to the encoded hostname */
3435 host->name = host->encalloc;
3438 #elif defined(USE_WIN32_IDN)
3439 /*************************************************************
3440 * Check name for non-ASCII and convert hostname to ACE form.
3441 *************************************************************/
3442 char *ace_hostname = NULL;
3443 int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname);
3445 infof(data, "Failed to convert %s to ACE;\n",
3448 host->encalloc = ace_hostname;
3449 /* change the name pointer to point to the encoded hostname */
3450 host->name = host->encalloc;
3453 infof (data, "IDN support not present, can't parse Unicode domains");
3458 static void llist_dtor(void *user, void *element)
3466 * Allocate and initialize a new connectdata object.
3468 static struct connectdata *allocate_conn(struct SessionHandle *data)
3470 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3474 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
3475 already from start to avoid NULL
3476 situations and checks */
3478 /* and we setup a few fields in case we end up actually using this struct */
3480 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3481 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3482 conn->connectindex = -1; /* no index */
3483 conn->port = -1; /* unknown at this point */
3485 /* Default protocol-independent behavior doesn't support persistent
3486 connections, so we set this to force-close. Protocols that support
3487 this need to set this to FALSE in their "curl_do" functions. */
3488 conn->bits.close = TRUE;
3490 /* Store creation time to help future close decision making */
3491 conn->created = Curl_tvnow();
3493 conn->data = data; /* Setup the association between this connection
3494 and the SessionHandle */
3496 conn->proxytype = data->set.proxytype; /* type */
3498 #ifdef CURL_DISABLE_PROXY
3500 conn->bits.proxy = FALSE;
3501 conn->bits.httpproxy = FALSE;
3502 conn->bits.proxy_user_passwd = FALSE;
3503 conn->bits.tunnel_proxy = FALSE;
3505 #else /* CURL_DISABLE_PROXY */
3507 /* note that these two proxy bits are now just on what looks to be
3508 requested, they may be altered down the road */
3509 conn->bits.proxy = (bool)(data->set.str[STRING_PROXY] &&
3510 *data->set.str[STRING_PROXY]);
3511 conn->bits.httpproxy = (bool)(conn->bits.proxy &&
3512 (conn->proxytype == CURLPROXY_HTTP ||
3513 conn->proxytype == CURLPROXY_HTTP_1_0));
3514 conn->bits.proxy_user_passwd =
3515 (bool)(NULL != data->set.str[STRING_PROXYUSERNAME]);
3516 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3518 #endif /* CURL_DISABLE_PROXY */
3520 conn->bits.user_passwd = (bool)(NULL != data->set.str[STRING_USERNAME]);
3521 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3522 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3524 conn->verifypeer = data->set.ssl.verifypeer;
3525 conn->verifyhost = data->set.ssl.verifyhost;
3527 conn->ip_version = data->set.ipver;
3529 #ifdef WINBIND_NTLM_AUTH_ENABLED
3530 conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
3531 conn->ntlm_auth_hlpr_pid = 0;
3532 conn->challenge_header = NULL;
3533 conn->response_header = NULL;
3536 if(data->multi && Curl_multi_canPipeline(data->multi) &&
3537 !conn->master_buffer) {
3538 /* Allocate master_buffer to be used for pipelining */
3539 conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3540 if(!conn->master_buffer)
3544 /* Initialize the pipeline lists */
3545 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3546 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3547 conn->pend_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3548 conn->done_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3549 if(!conn->send_pipe || !conn->recv_pipe || !conn->pend_pipe ||
3553 #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI)
3554 conn->data_prot = PROT_CLEAR;
3557 /* Store the local bind parameters that will be used for this connection */
3558 if(data->set.str[STRING_DEVICE]) {
3559 conn->localdev = strdup(data->set.str[STRING_DEVICE]);
3563 conn->localportrange = data->set.localportrange;
3564 conn->localport = data->set.localport;
3566 /* the close socket stuff needs to be copied to the connection struct as
3567 it may live on without (this specific) SessionHandle */
3568 conn->fclosesocket = data->set.fclosesocket;
3569 conn->closesocket_client = data->set.closesocket_client;
3574 Curl_llist_destroy(conn->send_pipe, NULL);
3575 Curl_llist_destroy(conn->recv_pipe, NULL);
3576 Curl_llist_destroy(conn->pend_pipe, NULL);
3577 Curl_llist_destroy(conn->done_pipe, NULL);
3578 Curl_safefree(conn->master_buffer);
3579 Curl_safefree(conn->localdev);
3580 Curl_safefree(conn);
3584 static CURLcode findprotocol(struct SessionHandle *data,
3585 struct connectdata *conn,
3586 const char *protostr)
3588 const struct Curl_handler * const *pp;
3589 const struct Curl_handler *p;
3591 /* Scan protocol handler table and match against 'protostr' to set a few
3592 variables based on the URL. Now that the handler may be changed later
3593 when the protocol specific setup function is called. */
3594 for(pp = protocols; (p = *pp) != NULL; pp++) {
3595 if(Curl_raw_equal(p->scheme, protostr)) {
3596 /* Protocol found in table. Check if allowed */
3597 if(!(data->set.allowed_protocols & p->protocol))
3601 /* it is allowed for "normal" request, now do an extra check if this is
3602 the result of a redirect */
3603 if(data->state.this_is_a_follow &&
3604 !(data->set.redir_protocols & p->protocol))
3608 /* Perform setup complement if some. */
3609 conn->handler = conn->given = p;
3611 /* 'port' and 'remote_port' are set in setup_connection_internals() */
3617 /* The protocol was not found in the table, but we don't have to assign it
3618 to anything since it is already assigned to a dummy-struct in the
3619 create_conn() function when the connectdata struct is allocated. */
3620 failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
3623 return CURLE_UNSUPPORTED_PROTOCOL;
3627 * Parse URL and fill in the relevant members of the connection struct.
3629 static CURLcode parseurlandfillconn(struct SessionHandle *data,
3630 struct connectdata *conn,
3635 char *path = data->state.path;
3641 *prot_missing = FALSE;
3643 /*************************************************************
3646 * We need to parse the url even when using the proxy, because we will need
3647 * the hostname and port in case we are trying to SSL connect through the
3648 * proxy -- and we don't know if we will need to use SSL until we parse the
3650 ************************************************************/
3651 if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
3653 Curl_raw_equal(protobuf, "file")) {
3654 if(path[0] == '/' && path[1] == '/') {
3655 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
3656 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
3657 * file://localhost/<path> is similar to how other schemes treat missing
3658 * hostnames. See RFC 1808. */
3660 /* This cannot be done with strcpy() in a portable manner, since the
3661 memory areas overlap! */
3662 memmove(path, path + 2, strlen(path + 2)+1);
3665 * we deal with file://<host>/<path> differently since it supports no
3666 * hostname other than "localhost" and "127.0.0.1", which is unique among
3667 * the URL protocols specified in RFC 1738
3669 if(path[0] != '/') {
3670 /* the URL included a host name, we ignore host names in file:// URLs
3671 as the standards don't define what to do with them */
3672 char *ptr=strchr(path, '/');
3674 /* there was a slash present
3676 RFC1738 (section 3.1, page 5) says:
3678 The rest of the locator consists of data specific to the scheme,
3679 and is known as the "url-path". It supplies the details of how the
3680 specified resource can be accessed. Note that the "/" between the
3681 host (or port) and the url-path is NOT part of the url-path.
3683 As most agents use file://localhost/foo to get '/foo' although the
3684 slash preceding foo is a separator and not a slash for the path,
3685 a URL as file://localhost//foo must be valid as well, to refer to
3686 the same file with an absolute path.
3689 if(ptr[1] && ('/' == ptr[1]))
3690 /* if there was two slashes, we skip the first one as that is then
3691 used truly as a separator */
3694 /* This cannot be made with strcpy, as the memory chunks overlap! */
3695 memmove(path, ptr, strlen(ptr)+1);
3699 protop = "file"; /* protocol string */
3705 if(2 > sscanf(data->change.url,
3706 "%15[^\n:]://%[^\n/?]%[^\n]",
3708 conn->host.name, path)) {
3711 * The URL was badly formatted, let's try the browser-style _without_
3712 * protocol specified like 'http://'.
3714 rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
3717 * We couldn't even get this format.
3718 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
3719 * assigned, but the return value is EOF!
3721 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
3722 if(!(rc == -1 && *conn->host.name))
3725 failf(data, "<url> malformed");
3726 return CURLE_URL_MALFORMAT;
3731 * Since there was no protocol part specified, we guess what protocol it
3732 * is based on the first letters of the server name.
3735 /* Note: if you add a new protocol, please update the list in
3736 * lib/version.c too! */
3738 if(checkprefix("FTP.", conn->host.name))
3740 else if(checkprefix("DICT.", conn->host.name))
3742 else if(checkprefix("LDAP.", conn->host.name))
3744 else if(checkprefix("IMAP.", conn->host.name))
3750 *prot_missing = TRUE; /* not given in URL */
3756 /* We search for '?' in the host name (but only on the right side of a
3757 * @-letter to allow ?-letters in username and password) to handle things
3758 * like http://example.com?param= (notice the missing '/').
3760 at = strchr(conn->host.name, '@');
3762 query = strchr(at+1, '?');
3764 query = strchr(conn->host.name, '?');
3767 /* We must insert a slash before the '?'-letter in the URL. If the URL had
3768 a slash after the '?', that is where the path currently begins and the
3769 '?string' is still part of the host name.
3771 We must move the trailing part from the host name and put it first in
3772 the path. And have it all prefixed with a slash.
3775 size_t hostlen = strlen(query);
3776 size_t pathlen = strlen(path);
3778 /* move the existing path plus the zero byte forward, to make room for
3779 the host-name part */
3780 memmove(path+hostlen+1, path, pathlen+1);
3782 /* now copy the trailing host part in front of the existing path */
3783 memcpy(path+1, query, hostlen);
3785 path[0]='/'; /* prepend the missing slash */
3787 *query=0; /* now cut off the hostname at the ? */
3790 /* if there's no path set, use a single slash */
3794 /* If the URL is malformatted (missing a '/' after hostname before path) we
3795 * insert a slash here. The only letter except '/' we accept to start a path
3798 if(path[0] == '?') {
3799 /* We need this function to deal with overlapping memory areas. We know
3800 that the memory area 'path' points to is 'urllen' bytes big and that
3801 is bigger than the path. Use +1 to move the zero byte too. */
3802 memmove(&path[1], path, strlen(path)+1);
3806 if(conn->host.name[0] == '[') {
3807 /* This looks like an IPv6 address literal. See if there is an address
3809 char *percent = strstr (conn->host.name, "%25");
3812 unsigned long scope = strtoul (percent + 3, &endp, 10);
3814 /* The address scope was well formed. Knock it out of the
3816 memmove(percent, endp, strlen(endp)+1);
3817 if(!data->state.this_is_a_follow)
3818 /* Don't honour a scope given in a Location: header */
3819 conn->scope = (unsigned int)scope;
3822 infof(data, "Invalid IPv6 address format\n");
3827 /* Override any scope that was set above. */
3828 conn->scope = data->set.scope;
3830 /* Remove the fragment part of the path. Per RFC 2396, this is always the
3831 last part of the URI. We are looking for the first '#' so that we deal
3832 gracefully with non conformant URI such as http://example.com#foo#bar. */
3833 fragment = strchr(path, '#');
3838 * So if the URL was A://B/C#D,
3840 * conn->host.name is B
3841 * data->state.path is /C
3844 return findprotocol(data, conn, protop);
3848 * If we're doing a resumed transfer, we need to setup our stuff
3851 static CURLcode setup_range(struct SessionHandle *data)
3853 struct UrlState *s = &data->state;
3854 s->resume_from = data->set.set_resume_from;
3855 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
3856 if(s->rangestringalloc)
3860 s->range = aprintf("%" FORMAT_OFF_TU "-", s->resume_from);
3862 s->range = strdup(data->set.str[STRING_SET_RANGE]);
3864 s->rangestringalloc = (bool)(s->range?TRUE:FALSE);
3867 return CURLE_OUT_OF_MEMORY;
3869 /* tell ourselves to fetch this range */
3870 s->use_range = TRUE; /* enable range download */
3873 s->use_range = FALSE; /* disable range download */
3879 /***************************************************************
3880 * Setup connection internals specific to the requested protocol.
3881 * This MUST get called after proxy magic has been figured out.
3882 ***************************************************************/
3883 static CURLcode setup_connection_internals(struct connectdata *conn)
3885 const struct Curl_handler * p;
3888 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
3890 /* Scan protocol handler table. */
3892 /* Perform setup complement if some. */
3895 if(p->setup_connection) {
3896 result = (*p->setup_connection)(conn);
3898 if(result != CURLE_OK)
3901 p = conn->handler; /* May have changed. */
3905 /* we check for -1 here since if proxy was detected already, this
3906 was very likely already set to the proxy port */
3907 conn->port = p->defport;
3908 conn->remote_port = (unsigned short)conn->given->defport;
3913 #ifndef CURL_DISABLE_PROXY
3914 /****************************************************************
3915 * Checks if the host is in the noproxy list. returns true if it matches
3916 * and therefore the proxy should NOT be used.
3917 ****************************************************************/
3918 static bool check_noproxy(const char* name, const char* no_proxy)
3920 /* no_proxy=domain1.dom,host.domain2.dom
3921 * (a comma-separated list of hosts which should
3922 * not be proxied, or an asterisk to override
3923 * all proxy variables)
3927 const char* separator = ", ";
3928 size_t no_proxy_len;
3932 if(no_proxy && no_proxy[0]) {
3933 if(Curl_raw_equal("*", no_proxy)) {
3937 /* NO_PROXY was specified and it wasn't just an asterisk */
3939 no_proxy_len = strlen(no_proxy);
3940 endptr = strchr(name, ':');
3942 namelen = endptr - name;
3944 namelen = strlen(name);
3946 for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
3947 while(tok_start < no_proxy_len &&
3948 strchr(separator, no_proxy[tok_start]) != NULL) {
3949 /* Look for the beginning of the token. */
3953 if(tok_start == no_proxy_len)
3954 break; /* It was all trailing separator chars, no more tokens. */
3956 for(tok_end = tok_start; tok_end < no_proxy_len &&
3957 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
3958 /* Look for the end of the token. */
3961 /* To match previous behaviour, where it was necessary to specify
3962 * ".local.com" to prevent matching "notlocal.com", we will leave
3965 if(no_proxy[tok_start] == '.')
3968 if((tok_end - tok_start) <= namelen) {
3969 /* Match the last part of the name to the domain we are checking. */
3970 const char *checkn = name + namelen - (tok_end - tok_start);
3971 if(Curl_raw_nequal(no_proxy + tok_start, checkn,
3972 tok_end - tok_start)) {
3973 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
3974 /* We either have an exact match, or the previous character is a .
3975 * so it is within the same domain, so no proxy for this host.
3980 } /* if((tok_end - tok_start) <= namelen) */
3981 } /* for(tok_start = 0; tok_start < no_proxy_len;
3982 tok_start = tok_end + 1) */
3983 } /* NO_PROXY was specified and it wasn't just an asterisk */
3988 /****************************************************************
3989 * Detect what (if any) proxy to use. Remember that this selects a host
3990 * name and is not limited to HTTP proxies only.
3991 * The returned pointer must be freed by the caller (unless NULL)
3992 ****************************************************************/
3993 static char *detect_proxy(struct connectdata *conn)
3997 #ifndef CURL_DISABLE_HTTP
3998 /* If proxy was not specified, we check for default proxy environment
3999 * variables, to enable i.e Lynx compliance:
4001 * http_proxy=http://some.server.dom:port/
4002 * https_proxy=http://some.server.dom:port/
4003 * ftp_proxy=http://some.server.dom:port/
4004 * no_proxy=domain1.dom,host.domain2.dom
4005 * (a comma-separated list of hosts which should
4006 * not be proxied, or an asterisk to override
4007 * all proxy variables)
4008 * all_proxy=http://some.server.dom:port/
4009 * (seems to exist for the CERN www lib. Probably
4010 * the first to check for.)
4012 * For compatibility, the all-uppercase versions of these variables are
4013 * checked if the lowercase versions don't exist.
4015 char *no_proxy=NULL;
4016 char proxy_env[128];
4018 no_proxy=curl_getenv("no_proxy");
4020 no_proxy=curl_getenv("NO_PROXY");
4022 if(!check_noproxy(conn->host.name, no_proxy)) {
4023 /* It was not listed as without proxy */
4024 const char *protop = conn->handler->scheme;
4025 char *envp = proxy_env;
4028 /* Now, build <protocol>_proxy and check for such a one to use */
4030 *envp++ = (char)tolower((int)*protop++);
4033 strcpy(envp, "_proxy");
4035 /* read the protocol proxy: */
4036 prox=curl_getenv(proxy_env);
4039 * We don't try the uppercase version of HTTP_PROXY because of
4042 * When curl is used in a webserver application
4043 * environment (cgi or php), this environment variable can
4044 * be controlled by the web server user by setting the
4045 * http header 'Proxy:' to some value.
4047 * This can cause 'internal' http/ftp requests to be
4048 * arbitrarily redirected by any external attacker.
4050 if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4051 /* There was no lowercase variable, try the uppercase version: */
4052 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4053 prox=curl_getenv(proxy_env);
4056 if(prox && *prox) { /* don't count "" strings */
4057 proxy = prox; /* use this */
4060 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4062 proxy=curl_getenv("ALL_PROXY");
4064 } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4069 #else /* !CURL_DISABLE_HTTP */
4072 #endif /* CURL_DISABLE_HTTP */
4078 * If this is supposed to use a proxy, we need to figure out the proxy
4079 * host name, so that we can re-use an existing connection
4080 * that may exist registered to the same proxy host.
4081 * proxy will be freed before this function returns.
4083 static CURLcode parse_proxy(struct SessionHandle *data,
4084 struct connectdata *conn, char *proxy)
4089 /* We use 'proxyptr' to point to the proxy name from now on... */
4094 /* We do the proxy host string parsing here. We want the host name and the
4095 * port name. Accept a protocol:// prefix
4098 /* Parse the protocol part if present */
4099 endofprot = strstr(proxy, "://");
4101 proxyptr = endofprot+3;
4102 if(checkprefix("socks5h", proxy))
4103 conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
4104 else if(checkprefix("socks5", proxy))
4105 conn->proxytype = CURLPROXY_SOCKS5;
4106 else if(checkprefix("socks4a", proxy))
4107 conn->proxytype = CURLPROXY_SOCKS4A;
4108 else if(checkprefix("socks4", proxy))
4109 conn->proxytype = CURLPROXY_SOCKS4;
4110 /* Any other xxx:// : change to http proxy */
4113 proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
4115 /* Is there a username and password given in this proxy url? */
4116 atsign = strchr(proxyptr, '@');
4118 char proxyuser[MAX_CURL_USER_LENGTH];
4119 char proxypasswd[MAX_CURL_PASSWORD_LENGTH];
4122 if(1 <= sscanf(proxyptr,
4123 "%" MAX_CURL_USER_LENGTH_TXT"[^:@]:"
4124 "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4125 proxyuser, proxypasswd)) {
4126 CURLcode res = CURLE_OK;
4128 /* found user and password, rip them out. note that we are
4129 unescaping them, as there is otherwise no way to have a
4130 username or password with reserved characters like ':' in
4132 Curl_safefree(conn->proxyuser);
4133 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4135 if(!conn->proxyuser)
4136 res = CURLE_OUT_OF_MEMORY;
4138 Curl_safefree(conn->proxypasswd);
4139 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4141 if(!conn->proxypasswd)
4142 res = CURLE_OUT_OF_MEMORY;
4145 if(CURLE_OK == res) {
4146 conn->bits.proxy_user_passwd = TRUE; /* enable it */
4147 atsign = strdup(atsign+1); /* the right side of the @-letter */
4150 free(proxy); /* free the former proxy string */
4151 proxy = proxyptr = atsign; /* now use this instead */
4154 res = CURLE_OUT_OF_MEMORY;
4158 free(proxy); /* free the allocated proxy string */
4164 /* start scanning for port number at this point */
4167 /* detect and extract RFC2732-style IPv6-addresses */
4168 if(*proxyptr == '[') {
4169 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4170 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
4174 /* yeps, it ended nicely with a bracket as well */
4177 infof(data, "Invalid IPv6 address format\n");
4179 /* Note that if this didn't end with a bracket, we still advanced the
4180 * proxyptr first, but I can't see anything wrong with that as no host
4181 * name nor a numeric can legally start with a bracket.
4185 /* Get port number off proxy.server.com:1080 */
4186 prox_portno = strchr(portptr, ':');
4188 *prox_portno = 0x0; /* cut off number from host name */
4190 /* now set the local port number */
4191 conn->port = strtol(prox_portno, NULL, 10);
4194 /* without a port number after the host name, some people seem to use
4195 a slash so we strip everything from the first slash */
4196 atsign = strchr(proxyptr, '/');
4198 *atsign = 0x0; /* cut off path part from host name */
4200 if(data->set.proxyport)
4201 /* None given in the proxy string, then get the default one if it is
4203 conn->port = data->set.proxyport;
4206 /* now, clone the cleaned proxy host name */
4207 conn->proxy.rawalloc = strdup(proxyptr);
4208 conn->proxy.name = conn->proxy.rawalloc;
4211 if(!conn->proxy.rawalloc)
4212 return CURLE_OUT_OF_MEMORY;
4218 * Extract the user and password from the authentication string
4220 static CURLcode parse_proxy_auth(struct SessionHandle *data,
4221 struct connectdata *conn)
4223 char proxyuser[MAX_CURL_USER_LENGTH]="";
4224 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4226 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4227 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4228 MAX_CURL_USER_LENGTH);
4229 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4231 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4232 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4233 MAX_CURL_PASSWORD_LENGTH);
4234 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4237 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4238 if(!conn->proxyuser)
4239 return CURLE_OUT_OF_MEMORY;
4241 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4242 if(!conn->proxypasswd)
4243 return CURLE_OUT_OF_MEMORY;
4247 #endif /* CURL_DISABLE_PROXY */
4251 * Parse a user name and password in the URL and strip it out of the host name
4253 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4256 * Outputs: (almost :- all currently undefined)
4257 * conn->bits.user_passwd - non-zero if non-default passwords exist
4258 * user - non-zero length if defined
4260 * conn->host.name - remove user name and password
4262 static CURLcode parse_url_userpass(struct SessionHandle *data,
4263 struct connectdata *conn,
4264 char *user, char *passwd)
4266 /* At this point, we're hoping all the other special cases have
4267 * been taken care of, so conn->host.name is at most
4268 * [user[:password]]@]hostname
4270 * We need somewhere to put the embedded details, so do that first.
4273 char *ptr=strchr(conn->host.name, '@');
4274 char *userpass = conn->host.name;
4276 user[0] =0; /* to make everything well-defined */
4279 /* We will now try to extract the
4280 * possible user+password pair in a string like:
4281 * ftp://user:password@ftp.my.site:8021/README */
4283 /* there's a user+password given here, to the left of the @ */
4285 conn->host.name = ++ptr;
4287 /* So the hostname is sane. Only bother interpreting the
4288 * results if we could care. It could still be wasted
4289 * work because it might be overtaken by the programmatically
4290 * set user/passwd, but doing that first adds more cases here :-(
4293 conn->bits.userpwd_in_url = TRUE;
4294 if(data->set.use_netrc != CURL_NETRC_REQUIRED) {
4295 /* We could use the one in the URL */
4297 conn->bits.user_passwd = TRUE; /* enable user+password */
4299 if(*userpass != ':') {
4300 /* the name is given, get user+password */
4301 sscanf(userpass, "%" MAX_CURL_USER_LENGTH_TXT "[^:@]:"
4302 "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4306 /* no name given, get the password only */
4307 sscanf(userpass, ":%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]", passwd);
4310 char *newname=curl_easy_unescape(data, user, 0, NULL);
4312 return CURLE_OUT_OF_MEMORY;
4313 if(strlen(newname) < MAX_CURL_USER_LENGTH)
4314 strcpy(user, newname);
4316 /* if the new name is longer than accepted, then just use
4317 the unconverted name, it'll be wrong but what the heck */
4321 /* we have a password found in the URL, decode it! */
4322 char *newpasswd=curl_easy_unescape(data, passwd, 0, NULL);
4324 return CURLE_OUT_OF_MEMORY;
4325 if(strlen(newpasswd) < MAX_CURL_PASSWORD_LENGTH)
4326 strcpy(passwd, newpasswd);
4335 /*************************************************************
4336 * Figure out the remote port number and fix it in the URL
4338 * No matter if we use a proxy or not, we have to figure out the remote
4339 * port number of various reasons.
4341 * To be able to detect port number flawlessly, we must not confuse them
4342 * IPv6-specified addresses in the [0::1] style. (RFC2732)
4344 * The conn->host.name is currently [user:passwd@]host[:port] where host
4345 * could be a hostname, IPv4 address or IPv6 address.
4347 * The port number embedded in the URL is replaced, if necessary.
4348 *************************************************************/
4349 static CURLcode parse_remote_port(struct SessionHandle *data,
4350 struct connectdata *conn)
4355 /* Note that at this point, the IPv6 address cannot contain any scope
4356 suffix as that has already been removed in the parseurlandfillconn()
4358 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
4360 (']' == endbracket)) {
4361 /* this is a RFC2732-style specified IP-address */
4362 conn->bits.ipv6_ip = TRUE;
4364 conn->host.name++; /* skip over the starting bracket */
4365 portptr = strchr(conn->host.name, ']');
4367 *portptr++ = '\0'; /* zero terminate, killing the bracket */
4369 portptr = NULL; /* no port number available */
4373 portptr = strrchr(conn->host.name, ':');
4375 if(data->set.use_port && data->state.allow_port) {
4376 /* if set, we use this and ignore the port possibly given in the URL */
4377 conn->remote_port = (unsigned short)data->set.use_port;
4379 *portptr = '\0'; /* cut off the name there anyway - if there was a port
4380 number - since the port number is to be ignored! */
4381 if(conn->bits.httpproxy) {
4382 /* we need to create new URL with the new port number */
4386 if(conn->bits.type_set)
4387 snprintf(type, sizeof(type), ";type=%c",
4388 data->set.prefer_ascii?'A':
4389 (data->set.ftp_list_only?'D':'I'));
4392 * This synthesized URL isn't always right--suffixes like ;type=A are
4393 * stripped off. It would be better to work directly from the original
4394 * URL and simply replace the port part of it.
4396 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
4397 conn->bits.ipv6_ip?"[":"", conn->host.name,
4398 conn->bits.ipv6_ip?"]":"", conn->remote_port,
4399 data->state.slash_removed?"/":"", data->state.path,
4402 return CURLE_OUT_OF_MEMORY;
4404 if(data->change.url_alloc)
4405 free(data->change.url);
4407 data->change.url = url;
4408 data->change.url_alloc = TRUE;
4412 /* no CURLOPT_PORT given, extract the one from the URL */
4417 port=strtoul(portptr+1, &rest, 10); /* Port number must be decimal */
4419 if(rest != (portptr+1) && *rest == '\0') {
4420 /* The colon really did have only digits after it,
4421 * so it is either a port number or a mistake */
4423 if(port > 0xffff) { /* Single unix standard says port numbers are
4425 failf(data, "Port number too large: %lu", port);
4426 return CURLE_URL_MALFORMAT;
4429 *portptr = '\0'; /* cut off the name there */
4430 conn->remote_port = curlx_ultous(port);
4433 /* Browser behavior adaptation. If there's a colon with no digits after,
4434 just cut off the name there which makes us ignore the colon and just
4435 use the default port. Firefox and Chrome both do that. */
4442 * Override a user name and password from the URL with that in the
4443 * CURLOPT_USERPWD option or a .netrc file, if applicable.
4445 static void override_userpass(struct SessionHandle *data,
4446 struct connectdata *conn,
4447 char *user, char *passwd)
4449 if(data->set.str[STRING_USERNAME] != NULL) {
4450 strncpy(user, data->set.str[STRING_USERNAME], MAX_CURL_USER_LENGTH);
4451 user[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4453 if(data->set.str[STRING_PASSWORD] != NULL) {
4454 strncpy(passwd, data->set.str[STRING_PASSWORD], MAX_CURL_PASSWORD_LENGTH);
4455 passwd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4458 conn->bits.netrc = FALSE;
4459 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
4460 if(Curl_parsenetrc(conn->host.name,
4462 data->set.str[STRING_NETRC_FILE])) {
4463 infof(data, "Couldn't find host %s in the "
4464 DOT_CHAR "netrc file; using defaults\n",
4468 /* set bits.netrc TRUE to remember that we got the name from a .netrc
4469 file, so that it is safe to use even if we followed a Location: to a
4470 different host or similar. */
4471 conn->bits.netrc = TRUE;
4473 conn->bits.user_passwd = TRUE; /* enable user+password */
4479 * Set password so it's available in the connection.
4481 static CURLcode set_userpass(struct connectdata *conn,
4482 const char *user, const char *passwd)
4484 /* If our protocol needs a password and we have none, use the defaults */
4485 if((conn->handler->flags & PROTOPT_NEEDSPWD) &&
4486 !conn->bits.user_passwd) {
4488 conn->user = strdup(CURL_DEFAULT_USER);
4490 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
4492 conn->passwd = NULL;
4493 /* This is the default password, so DON'T set conn->bits.user_passwd */
4496 /* store user + password, zero-length if not set */
4497 conn->user = strdup(user);
4499 conn->passwd = strdup(passwd);
4501 conn->passwd = NULL;
4503 if(!conn->user || !conn->passwd)
4504 return CURLE_OUT_OF_MEMORY;
4509 /*************************************************************
4510 * Resolve the address of the server or proxy
4511 *************************************************************/
4512 static CURLcode resolve_server(struct SessionHandle *data,
4513 struct connectdata *conn,
4516 CURLcode result=CURLE_OK;
4517 long timeout_ms = Curl_timeleft(data, NULL, TRUE);
4519 /*************************************************************
4520 * Resolve the name of the server or proxy
4521 *************************************************************/
4522 if(conn->bits.reuse) {
4523 /* We're reusing the connection - no need to resolve anything */
4526 if(conn->bits.proxy)
4527 fix_hostname(data, conn, &conn->host);
4530 /* this is a fresh connect */
4532 struct Curl_dns_entry *hostaddr;
4534 /* set a pointer to the hostname we display */
4535 fix_hostname(data, conn, &conn->host);
4537 if(!conn->proxy.name || !*conn->proxy.name) {
4538 /* If not connecting via a proxy, extract the port from the URL, if it is
4539 * there, thus overriding any defaults that might have been set above. */
4540 conn->port = conn->remote_port; /* it is the same port */
4542 /* Resolve target host right on */
4543 rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
4544 &hostaddr, timeout_ms);
4545 if(rc == CURLRESOLV_PENDING)
4548 else if(rc == CURLRESOLV_TIMEDOUT)
4549 result = CURLE_OPERATION_TIMEDOUT;
4551 else if(!hostaddr) {
4552 failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
4553 result = CURLE_COULDNT_RESOLVE_HOST;
4554 /* don't return yet, we need to clean up the timeout first */
4558 /* This is a proxy that hasn't been resolved yet. */
4560 /* IDN-fix the proxy name */
4561 fix_hostname(data, conn, &conn->proxy);
4564 rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
4565 &hostaddr, timeout_ms);
4567 if(rc == CURLRESOLV_PENDING)
4570 else if(rc == CURLRESOLV_TIMEDOUT)
4571 result = CURLE_OPERATION_TIMEDOUT;
4573 else if(!hostaddr) {
4574 failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
4575 result = CURLE_COULDNT_RESOLVE_PROXY;
4576 /* don't return yet, we need to clean up the timeout first */
4579 DEBUGASSERT(conn->dns_entry == NULL);
4580 conn->dns_entry = hostaddr;
4587 * Cleanup the connection just allocated before we can move along and use the
4588 * previously existing one. All relevant data is copied over and old_conn is
4589 * ready for freeing once this function returns.
4591 static void reuse_conn(struct connectdata *old_conn,
4592 struct connectdata *conn)
4594 if(old_conn->proxy.rawalloc)
4595 free(old_conn->proxy.rawalloc);
4597 /* free the SSL config struct from this connection struct as this was
4598 allocated in vain and is targeted for destruction */
4599 Curl_free_ssl_config(&old_conn->ssl_config);
4601 conn->data = old_conn->data;
4603 /* get the user+password information from the old_conn struct since it may
4604 * be new for this request even when we re-use an existing connection */
4605 conn->bits.user_passwd = old_conn->bits.user_passwd;
4606 if(conn->bits.user_passwd) {
4607 /* use the new user name and password though */
4608 Curl_safefree(conn->user);
4609 Curl_safefree(conn->passwd);
4610 conn->user = old_conn->user;
4611 conn->passwd = old_conn->passwd;
4612 old_conn->user = NULL;
4613 old_conn->passwd = NULL;
4616 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
4617 if(conn->bits.proxy_user_passwd) {
4618 /* use the new proxy user name and proxy password though */
4619 Curl_safefree(conn->proxyuser);
4620 Curl_safefree(conn->proxypasswd);
4621 conn->proxyuser = old_conn->proxyuser;
4622 conn->proxypasswd = old_conn->proxypasswd;
4623 old_conn->proxyuser = NULL;
4624 old_conn->proxypasswd = NULL;
4627 /* host can change, when doing keepalive with a proxy ! */
4628 if(conn->bits.proxy) {
4629 free(conn->host.rawalloc);
4630 conn->host=old_conn->host;
4633 free(old_conn->host.rawalloc); /* free the newly allocated name buffer */
4635 /* persist connection info in session handle */
4636 Curl_persistconninfo(conn);
4639 conn->bits.reuse = TRUE; /* yes, we're re-using here */
4641 Curl_safefree(old_conn->user);
4642 Curl_safefree(old_conn->passwd);
4643 Curl_safefree(old_conn->proxyuser);
4644 Curl_safefree(old_conn->proxypasswd);
4645 Curl_llist_destroy(old_conn->send_pipe, NULL);
4646 Curl_llist_destroy(old_conn->recv_pipe, NULL);
4647 Curl_llist_destroy(old_conn->pend_pipe, NULL);
4648 Curl_llist_destroy(old_conn->done_pipe, NULL);
4649 Curl_safefree(old_conn->master_buffer);
4653 * create_conn() sets up a new connectdata struct, or re-uses an already
4654 * existing one, and resolves host name.
4656 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
4657 * response will be coming asynchronously. If *async is FALSE, the name is
4660 * @param data The sessionhandle pointer
4661 * @param in_connect is set to the next connection data pointer
4662 * @param async is set TRUE when an async DNS resolution is pending
4663 * @see Curl_setup_conn()
4665 * *NOTE* this function assigns the conn->data pointer!
4668 static CURLcode create_conn(struct SessionHandle *data,
4669 struct connectdata **in_connect,
4672 CURLcode result=CURLE_OK;
4673 struct connectdata *conn;
4674 struct connectdata *conn_temp = NULL;
4676 char user[MAX_CURL_USER_LENGTH];
4677 char passwd[MAX_CURL_PASSWORD_LENGTH];
4680 bool prot_missing = FALSE;
4684 /*************************************************************
4686 *************************************************************/
4688 if(!data->change.url)
4689 return CURLE_URL_MALFORMAT;
4691 /* First, split up the current URL in parts so that we can use the
4692 parts for checking against the already present connections. In order
4693 to not have to modify everything at once, we allocate a temporary
4694 connection data struct and fill in for comparison purposes. */
4695 conn = allocate_conn(data);
4698 return CURLE_OUT_OF_MEMORY;
4700 /* We must set the return variable as soon as possible, so that our
4701 parent can cleanup any possible allocs we may have done before
4705 /* This initing continues below, see the comment "Continue connectdata
4706 * initialization here" */
4708 /***********************************************************
4709 * We need to allocate memory to store the path in. We get the size of the
4710 * full URL to be sure, and we need to make it at least 256 bytes since
4711 * other parts of the code will rely on this fact
4712 ***********************************************************/
4713 #define LEAST_PATH_ALLOC 256
4714 urllen=strlen(data->change.url);
4715 if(urllen < LEAST_PATH_ALLOC)
4716 urllen=LEAST_PATH_ALLOC;
4719 * We malloc() the buffers below urllen+2 to make room for to possibilities:
4720 * 1 - an extra terminating zero
4721 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
4724 Curl_safefree(data->state.pathbuffer);
4725 data->state.pathbuffer = malloc(urllen+2);
4726 if(NULL == data->state.pathbuffer)
4727 return CURLE_OUT_OF_MEMORY; /* really bad error */
4728 data->state.path = data->state.pathbuffer;
4730 conn->host.rawalloc = malloc(urllen+2);
4731 if(NULL == conn->host.rawalloc)
4732 return CURLE_OUT_OF_MEMORY;
4734 conn->host.name = conn->host.rawalloc;
4735 conn->host.name[0] = 0;
4737 result = parseurlandfillconn(data, conn, &prot_missing);
4738 if(result != CURLE_OK)
4741 /*************************************************************
4742 * No protocol part in URL was used, add it!
4743 *************************************************************/
4745 /* We're guessing prefixes here and if we're told to use a proxy or if
4746 we're gonna follow a Location: later or... then we need the protocol
4747 part added so that we have a valid URL. */
4750 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
4753 Curl_safefree(proxy);
4754 return CURLE_OUT_OF_MEMORY;
4757 data->change.url = reurl;
4758 data->change.url_alloc = TRUE; /* free this later */
4761 /*************************************************************
4762 * Parse a user name and password in the URL and strip it out
4764 *************************************************************/
4765 result = parse_url_userpass(data, conn, user, passwd);
4766 if(result != CURLE_OK)
4769 #ifndef CURL_DISABLE_PROXY
4770 /*************************************************************
4771 * Extract the user and password from the authentication string
4772 *************************************************************/
4773 if(conn->bits.proxy_user_passwd) {
4774 result = parse_proxy_auth(data, conn);
4775 if(result != CURLE_OK)
4779 /*************************************************************
4780 * Detect what (if any) proxy to use
4781 *************************************************************/
4782 if(data->set.str[STRING_PROXY]) {
4783 proxy = strdup(data->set.str[STRING_PROXY]);
4784 /* if global proxy is set, this is it */
4786 failf(data, "memory shortage");
4787 return CURLE_OUT_OF_MEMORY;
4791 if(data->set.str[STRING_NOPROXY] &&
4792 check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
4794 free(proxy); /* proxy is in exception list */
4799 proxy = detect_proxy(conn);
4801 if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
4802 free(proxy); /* Don't bother with an empty proxy string or if the
4803 protocol doesn't work with network */
4807 /***********************************************************************
4808 * If this is supposed to use a proxy, we need to figure out the proxy host
4809 * name, proxy type and port number, so that we can re-use an existing
4810 * connection that may exist registered to the same proxy host.
4811 ***********************************************************************/
4813 result = parse_proxy(data, conn, proxy);
4815 /* parse_proxy has freed the proxy string, so don't try to use it again */
4816 if(result != CURLE_OK)
4819 if((conn->proxytype == CURLPROXY_HTTP) ||
4820 (conn->proxytype == CURLPROXY_HTTP_1_0)) {
4821 #ifdef CURL_DISABLE_HTTP
4822 /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
4823 return CURLE_UNSUPPORTED_PROTOCOL;
4825 /* force this connection's protocol to become HTTP if not already
4827 if(!(conn->handler->protocol & CURLPROTO_HTTP))
4828 conn->handler = &Curl_handler_http;
4830 conn->bits.httpproxy = TRUE;
4834 conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
4835 conn->bits.proxy = TRUE;
4838 /* we aren't using the proxy after all... */
4839 conn->bits.proxy = FALSE;
4840 conn->bits.httpproxy = FALSE;
4841 conn->bits.proxy_user_passwd = FALSE;
4842 conn->bits.tunnel_proxy = FALSE;
4845 #endif /* CURL_DISABLE_PROXY */
4847 /*************************************************************
4848 * Setup internals depending on protocol. Needs to be done after
4849 * we figured out what/if proxy to use.
4850 *************************************************************/
4851 result = setup_connection_internals(conn);
4852 if(result != CURLE_OK) {
4853 Curl_safefree(proxy);
4857 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
4858 conn->send[FIRSTSOCKET] = Curl_send_plain;
4859 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
4860 conn->send[SECONDARYSOCKET] = Curl_send_plain;
4862 /***********************************************************************
4863 * file: is a special case in that it doesn't need a network connection
4864 ***********************************************************************/
4865 #ifndef CURL_DISABLE_FILE
4866 if(conn->handler->flags & PROTOPT_NONETWORK) {
4868 /* this is supposed to be the connect function so we better at least check
4869 that the file is present here! */
4870 DEBUGASSERT(conn->handler->connect_it);
4871 result = conn->handler->connect_it(conn, &done);
4873 /* Setup a "faked" transfer that'll do nothing */
4874 if(CURLE_OK == result) {
4876 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
4878 ConnectionStore(data, conn);
4881 * Setup whatever necessary for a resumed transfer
4883 result = setup_range(data);
4885 DEBUGASSERT(conn->handler->done);
4886 /* we ignore the return code for the protocol-specific DONE */
4887 (void)conn->handler->done(conn, result, FALSE);
4891 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
4892 -1, NULL); /* no upload */
4899 /*************************************************************
4900 * If the protocol is using SSL and HTTP proxy is used, we set
4901 * the tunnel_proxy bit.
4902 *************************************************************/
4903 if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
4904 conn->bits.tunnel_proxy = TRUE;
4906 /*************************************************************
4907 * Figure out the remote port number and fix it in the URL
4908 *************************************************************/
4909 result = parse_remote_port(data, conn);
4910 if(result != CURLE_OK)
4913 /*************************************************************
4914 * Check for an overridden user name and password, then set it
4916 *************************************************************/
4917 override_userpass(data, conn, user, passwd);
4918 result = set_userpass(conn, user, passwd);
4919 if(result != CURLE_OK)
4922 /* Get a cloned copy of the SSL config situation stored in the
4923 connection struct. But to get this going nicely, we must first make
4924 sure that the strings in the master copy are pointing to the correct
4925 strings in the session handle strings array!
4927 Keep in mind that the pointers in the master copy are pointing to strings
4928 that will be freed as part of the SessionHandle struct, but all cloned
4929 copies will be separately allocated.
4931 data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
4932 data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
4933 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
4934 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
4935 data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
4936 data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
4937 data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
4939 data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
4940 data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
4943 if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
4944 return CURLE_OUT_OF_MEMORY;
4946 /*************************************************************
4947 * Check the current list of connections to see if we can
4948 * re-use an already existing one or if we have to create a
4950 *************************************************************/
4952 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
4953 we only acknowledge this option if this is not a re-used connection
4954 already (which happens due to follow-location or during a HTTP
4955 authentication phase). */
4956 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
4959 reuse = ConnectionExists(data, conn, &conn_temp);
4963 * We already have a connection for this, we got the former connection
4964 * in the conn_temp variable and thus we need to cleanup the one we
4965 * just allocated before we can move along and use the previously
4968 reuse_conn(conn, conn_temp);
4969 free(conn); /* we don't need this anymore */
4972 infof(data, "Re-using existing connection! (#%ld) with host %s\n",
4974 conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
4978 * This is a brand new connection, so let's store it in the connection
4981 ConnectionStore(data, conn);
4985 * Setup whatever necessary for a resumed transfer
4987 result = setup_range(data);
4991 /* Continue connectdata initialization here. */
4994 * Inherit the proper values from the urldata struct AFTER we have arranged
4995 * the persistent connection stuff
4997 conn->fread_func = data->set.fread_func;
4998 conn->fread_in = data->set.in;
4999 conn->seek_func = data->set.seek_func;
5000 conn->seek_client = data->set.seek_client;
5002 /*************************************************************
5003 * Resolve the address of the server or proxy
5004 *************************************************************/
5005 result = resolve_server(data, conn, async);
5010 /* Curl_setup_conn() is called after the name resolve initiated in
5011 * create_conn() is all done.
5013 * Curl_setup_conn() also handles reused connections
5015 * conn->data MUST already have been setup fine (in create_conn)
5018 CURLcode Curl_setup_conn(struct connectdata *conn,
5019 bool *protocol_done)
5021 CURLcode result=CURLE_OK;
5022 struct SessionHandle *data = conn->data;
5024 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
5026 if(conn->handler->flags & PROTOPT_NONETWORK) {
5027 /* nothing to setup when not using a network */
5028 *protocol_done = TRUE;
5031 *protocol_done = FALSE; /* default to not done */
5033 /* set proxy_connect_closed to false unconditionally already here since it
5034 is used strictly to provide extra information to a parent function in the
5035 case of proxy CONNECT failures and we must make sure we don't have it
5036 lingering set from a previous invoke */
5037 conn->bits.proxy_connect_closed = FALSE;
5040 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
5041 * basically anything through a http proxy we can't limit this based on
5044 if(data->set.str[STRING_USERAGENT]) {
5045 Curl_safefree(conn->allocptr.uagent);
5046 conn->allocptr.uagent =
5047 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
5048 if(!conn->allocptr.uagent)
5049 return CURLE_OUT_OF_MEMORY;
5052 data->req.headerbytecount = 0;
5054 #ifdef CURL_DO_LINEEND_CONV
5055 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
5056 #endif /* CURL_DO_LINEEND_CONV */
5059 /* loop for CURL_SERVER_CLOSED_CONNECTION */
5061 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
5062 /* Try to connect only if not already connected */
5063 bool connected = FALSE;
5065 result = ConnectPlease(data, conn, &connected);
5068 result = Curl_protocol_connect(conn, protocol_done);
5069 if(CURLE_OK == result)
5070 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
5073 conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
5075 /* if the connection was closed by the server while exchanging
5076 authentication informations, retry with the new set
5077 authentication information */
5078 if(conn->bits.proxy_connect_closed) {
5079 /* reset the error buffer */
5080 if(data->set.errorbuffer)
5081 data->set.errorbuffer[0] = '\0';
5082 data->state.errorbuf = FALSE;
5086 if(CURLE_OK != result)
5090 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
5091 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
5092 conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
5093 *protocol_done = TRUE;
5094 Curl_verboseconnect(conn);
5095 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
5097 /* Stop the loop now */
5101 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
5102 set this here perhaps a second time */
5106 * This check is quite a hack. We're calling _fsetmode to fix the problem
5107 * with fwrite converting newline characters (you get mangled text files,
5108 * and corrupted binary files when you download to stdout and redirect it to
5112 if((data->set.out)->_handle == NULL) {
5113 _fsetmode(stdout, "b");
5120 CURLcode Curl_connect(struct SessionHandle *data,
5121 struct connectdata **in_connect,
5123 bool *protocol_done)
5127 *asyncp = FALSE; /* assume synchronous resolves by default */
5129 /* call the stuff that needs to be called */
5130 code = create_conn(data, in_connect, asyncp);
5132 if(CURLE_OK == code) {
5134 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
5136 *protocol_done = TRUE;
5138 /* DNS resolution is done: that's either because this is a reused
5139 connection, in which case DNS was unnecessary, or because DNS
5140 really did finish already (synch resolver/fast async resolve) */
5141 code = Curl_setup_conn(*in_connect, protocol_done);
5145 if(code && *in_connect) {
5146 /* We're not allowed to return failure with memory left allocated
5147 in the connectdata struct, free those here */
5148 Curl_disconnect(*in_connect, FALSE); /* close the connection */
5149 *in_connect = NULL; /* return a NULL */
5155 CURLcode Curl_done(struct connectdata **connp,
5156 CURLcode status, /* an error if this is called after an
5157 error was detected */
5161 struct connectdata *conn;
5162 struct SessionHandle *data;
5164 DEBUGASSERT(*connp);
5170 /* Stop if Curl_done() has already been called */
5173 Curl_getoff_all_pipelines(data, conn);
5175 if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
5176 !data->set.reuse_forbid &&
5178 /* Stop if pipeline is not empty and we do not have to close
5182 conn->bits.done = TRUE; /* called just now! */
5184 /* Cleanup possible redirect junk */
5185 if(data->req.newurl) {
5186 free(data->req.newurl);
5187 data->req.newurl = NULL;
5189 if(data->req.location) {
5190 free(data->req.location);
5191 data->req.location = NULL;
5194 Curl_resolver_cancel(conn);
5196 if(conn->dns_entry) {
5197 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
5198 conn->dns_entry = NULL;
5201 /* this calls the protocol-specific function pointer previously set */
5202 if(conn->handler->done)
5203 result = conn->handler->done(conn, status, premature);
5207 Curl_pgrsDone(conn); /* done with the operation */
5209 /* if the transfer was completed in a paused state there can be buffered
5210 data left to write and then kill */
5211 if(data->state.tempwrite) {
5212 free(data->state.tempwrite);
5213 data->state.tempwrite = NULL;
5216 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
5217 forced us to close this no matter what we think.
5219 if conn->bits.close is TRUE, it means that the connection should be
5220 closed in spite of all our efforts to be nice, due to protocol
5221 restrictions in our or the server's end
5223 if premature is TRUE, it means this connection was said to be DONE before
5224 the entire request operation is complete and thus we can't know in what
5225 state it is for re-using, so we're forced to close it. In a perfect world
5226 we can add code that keep track of if we really must close it here or not,
5227 but currently we have no such detail knowledge.
5229 connectindex == -1 here means that the connection has no spot in the
5230 connection cache and thus we must disconnect it here.
5232 if(data->set.reuse_forbid || conn->bits.close || premature ||
5233 (-1 == conn->connectindex)) {
5234 CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
5236 /* If we had an error already, make sure we return that one. But
5237 if we got a new error, return that. */
5242 ConnectionDone(conn); /* the connection is no longer in use */
5244 /* remember the most recently used connection */
5245 data->state.lastconnect = conn->connectindex;
5247 infof(data, "Connection #%ld to host %s left intact\n",
5249 conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
5252 *connp = NULL; /* to make the caller of this function better detect that
5253 this was either closed or handed over to the connection
5254 cache here, and therefore cannot be used from this point on
5261 * do_init() inits the readwrite session. This is inited each time (in the DO
5262 * function before the protocol-specific DO functions are invoked) for a
5263 * transfer, sometimes multiple times on the same SessionHandle. Make sure
5264 * nothing in here depends on stuff that are setup dynamically for the
5268 static CURLcode do_init(struct connectdata *conn)
5270 struct SessionHandle *data = conn->data;
5271 struct SingleRequest *k = &data->req;
5273 conn->bits.done = FALSE; /* Curl_done() is not called yet */
5274 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
5275 data->state.expect100header = FALSE;
5277 if(data->set.opt_no_body)
5278 /* in HTTP lingo, no body means using the HEAD request... */
5279 data->set.httpreq = HTTPREQ_HEAD;
5280 else if(HTTPREQ_HEAD == data->set.httpreq)
5281 /* ... but if unset there really is no perfect method that is the
5282 "opposite" of HEAD but in reality most people probably think GET
5283 then. The important thing is that we can't let it remain HEAD if the
5284 opt_no_body is set FALSE since then we'll behave wrong when getting
5286 data->set.httpreq = HTTPREQ_GET;
5288 /* NB: the content encoding software depends on this initialization */
5289 Curl_easy_initHandleData(data);
5291 k->start = Curl_tvnow(); /* start time */
5292 k->now = k->start; /* current time is now */
5293 k->header = TRUE; /* assume header */
5297 k->buf = data->state.buffer;
5298 k->uploadbuf = data->state.uploadbuffer;
5299 k->hbufp = data->state.headerbuff;
5300 k->ignorebody=FALSE;
5302 Curl_pgrsTime(data, TIMER_PRETRANSFER);
5303 Curl_speedinit(data);
5305 Curl_pgrsSetUploadCounter(data, 0);
5306 Curl_pgrsSetDownloadCounter(data, 0);
5312 * do_complete is called when the DO actions are complete.
5314 * We init chunking and trailer bits to their default values here immediately
5315 * before receiving any header data for the current request in the pipeline.
5317 static void do_complete(struct connectdata *conn)
5319 conn->data->req.chunk=FALSE;
5320 conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
5321 conn->sockfd:conn->writesockfd)+1;
5324 CURLcode Curl_do(struct connectdata **connp, bool *done)
5326 CURLcode result=CURLE_OK;
5327 struct connectdata *conn = *connp;
5328 struct SessionHandle *data = conn->data;
5330 /* setup and init stuff before DO starts, in preparing for the transfer */
5333 if(conn->handler->do_it) {
5334 /* generic protocol-specific function pointer set in curl_connect() */
5335 result = conn->handler->do_it(conn, done);
5337 /* This was formerly done in transfer.c, but we better do it here */
5338 if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
5340 * If the connection is using an easy handle, call reconnect
5341 * to re-establish the connection. Otherwise, let the multi logic
5342 * figure out how to re-establish the connection.
5345 result = Curl_reconnect_request(connp);
5347 if(result == CURLE_OK) {
5348 /* ... finally back to actually retry the DO phase */
5349 conn = *connp; /* re-assign conn since Curl_reconnect_request
5350 creates a new connection */
5351 result = conn->handler->do_it(conn, done);
5358 if((result == CURLE_OK) && *done)
5359 /* do_complete must be called after the protocol-specific DO function */
5365 CURLcode Curl_do_more(struct connectdata *conn)
5367 CURLcode result=CURLE_OK;
5369 if(conn->handler->do_more)
5370 result = conn->handler->do_more(conn);
5372 if(result == CURLE_OK)
5373 /* do_complete must be called after the protocol-specific DO function */
5379 /* Called on connect, and if there's already a protocol-specific struct
5380 allocated for a different connection, this frees it that it can be setup
5381 properly later on. */
5382 void Curl_reset_reqproto(struct connectdata *conn)
5384 struct SessionHandle *data = conn->data;
5385 if(data->state.proto.generic && data->state.current_conn != conn) {
5386 free(data->state.proto.generic);
5387 data->state.proto.generic = NULL;
5389 data->state.current_conn = conn;