1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 /* -- WIN32 approved -- */
38 #ifdef HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
44 #ifdef HAVE_SYS_TIME_H
53 #ifdef HAVE_ARPA_INET_H
54 #include <arpa/inet.h>
59 #ifdef HAVE_SYS_IOCTL_H
60 #include <sys/ioctl.h>
63 #ifdef HAVE_SYS_PARAM_H
64 #include <sys/param.h>
73 #error "We can't compile without socket() support!"
85 #include <stringprep.h>
86 #ifdef HAVE_IDN_FREE_H
89 void idn_free (void *ptr); /* prototype from idn-free.h, not provided by
90 libidn 0.4.5's make install! */
93 /* if idn_free() was not found in this version of libidn, use plain free()
95 #define idn_free(x) (free)(x)
97 #endif /* USE_LIBIDN */
102 #include "formdata.h"
105 #include "transfer.h"
107 #include "progress.h"
109 #include "strequal.h"
110 #include "strerror.h"
114 #include "content_encoding.h"
115 #include "http_digest.h"
116 #include "http_negotiate.h"
120 #include "speedcheck.h"
122 #include "warnless.h"
124 /* And now for the protocols */
131 #include "curl_ldap.h"
136 #include "inet_ntop.h"
137 #include "http_ntlm.h"
140 #include "curl_rtmp.h"
143 #define _MPRINTF_REPLACE /* use our functions only */
144 #include <curl/mprintf.h>
146 #include "curl_memory.h"
147 /* The last #include file should be: */
148 #include "memdebug.h"
150 /* Local static prototypes */
151 static long ConnectionKillOne(struct SessionHandle *data);
152 static void conn_free(struct connectdata *conn);
153 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
159 static const struct Curl_handler * const protocols[] = {
161 #ifndef CURL_DISABLE_HTTP
165 #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
169 #ifndef CURL_DISABLE_FTP
173 #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
177 #ifndef CURL_DISABLE_TELNET
178 &Curl_handler_telnet,
181 #ifndef CURL_DISABLE_DICT
185 #ifndef CURL_DISABLE_LDAP
187 #if (defined(USE_OPENLDAP) && defined(USE_SSL)) || \
188 (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))
193 #ifndef CURL_DISABLE_FILE
197 #ifndef CURL_DISABLE_TFTP
206 #ifndef CURL_DISABLE_IMAP
213 #ifndef CURL_DISABLE_POP3
220 #ifndef CURL_DISABLE_SMTP
227 #ifndef CURL_DISABLE_RTSP
231 #ifndef CURL_DISABLE_GOPHER
232 &Curl_handler_gopher,
239 &Curl_handler_rtmpte,
241 &Curl_handler_rtmpts,
244 (struct Curl_handler *) NULL
248 * Dummy handler for undefined protocol schemes.
251 static const struct Curl_handler Curl_handler_dummy = {
252 "<no protocol>", /* scheme */
253 ZERO_NULL, /* setup_connection */
254 ZERO_NULL, /* do_it */
255 ZERO_NULL, /* done */
256 ZERO_NULL, /* do_more */
257 ZERO_NULL, /* connect_it */
258 ZERO_NULL, /* connecting */
259 ZERO_NULL, /* doing */
260 ZERO_NULL, /* proto_getsock */
261 ZERO_NULL, /* doing_getsock */
262 ZERO_NULL, /* perform_getsock */
263 ZERO_NULL, /* disconnect */
268 void Curl_safefree(void *ptr)
274 static void close_connections(struct SessionHandle *data)
276 /* Loop through all open connections and kill them one by one */
279 i = ConnectionKillOne(data);
283 void Curl_freeset(struct SessionHandle * data)
285 /* Free all dynamic strings stored in the data->set substructure. */
287 for(i=(enum dupstring)0; i < STRING_LAST; i++)
288 Curl_safefree(data->set.str[i]);
291 static CURLcode setstropt(char **charp, char * s)
293 /* Release the previous storage at `charp' and replace by a dynamic storage
294 copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
298 *charp = (char *) NULL;
305 return CURLE_OUT_OF_MEMORY;
313 static CURLcode setstropt_userpwd(char *option, char **user_storage,
317 CURLcode result = CURLE_OK;
320 /* we treat a NULL passed in as a hint to clear existing info */
321 Curl_safefree(*user_storage);
322 *user_storage = (char *) NULL;
323 Curl_safefree(*pwd_storage);
324 *pwd_storage = (char *) NULL;
328 separator = strchr(option, ':');
329 if (separator != NULL) {
331 /* store username part of option */
333 size_t username_len = (size_t)(separator-option);
334 p = malloc(username_len+1);
336 result = CURLE_OUT_OF_MEMORY;
338 memcpy(p, option, username_len);
339 p[username_len] = '\0';
340 Curl_safefree(*user_storage);
344 /* store password part of option */
345 if (result == CURLE_OK) {
346 result = setstropt(pwd_storage, separator+1);
350 result = setstropt(user_storage, option);
355 CURLcode Curl_dupset(struct SessionHandle * dst, struct SessionHandle * src)
357 CURLcode r = CURLE_OK;
360 /* Copy src->set into dst->set first, then deal with the strings
364 /* clear all string pointers first */
365 memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
367 /* duplicate all strings */
368 for(i=(enum dupstring)0; i< STRING_LAST; i++) {
369 r = setstropt(&dst->set.str[i], src->set.str[i]);
374 /* If a failure occurred, freeing has to be performed externally. */
378 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
379 static void flush_cookies(struct SessionHandle *data, int cleanup)
381 if(data->set.str[STRING_COOKIEJAR]) {
382 if(data->change.cookielist) {
383 /* If there is a list of cookie files to read, do it first so that
384 we have all the told files read before we write the new jar.
385 Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */
386 Curl_cookie_loadfiles(data);
389 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
391 /* if we have a destination file for all the cookies to get dumped to */
392 if(Curl_cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR]))
393 infof(data, "WARNING: failed to save cookies in %s\n",
394 data->set.str[STRING_COOKIEJAR]);
397 if(cleanup && data->change.cookielist)
398 /* since nothing is written, we can just free the list of cookie file
400 curl_slist_free_all(data->change.cookielist); /* clean up list */
401 Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
404 if(cleanup && (!data->share || (data->cookies != data->share->cookies))) {
405 Curl_cookie_cleanup(data->cookies);
407 Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
412 * This is the internal function curl_easy_cleanup() calls. This should
413 * cleanup and free all resources associated with this sessionhandle.
415 * NOTE: if we ever add something that attempts to write to a socket or
416 * similar here, we must ignore SIGPIPE first. It is currently only done
417 * when curl_easy_perform() is invoked.
420 CURLcode Curl_close(struct SessionHandle *data)
422 struct Curl_multi *m = data->multi;
425 /* only for debugging, scan through all connections and see if there's a
426 pipe reference still identifying this handle */
428 if(data->state.connc && data->state.connc->type == CONNCACHE_MULTI) {
429 struct conncache *c = data->state.connc;
431 struct curl_llist *pipeline;
432 struct curl_llist_element *curr;
433 struct connectdata *connptr;
435 for(i=0; i< c->num; i++) {
436 connptr = c->connects[i];
440 pipeline = connptr->send_pipe;
442 for (curr = pipeline->head; curr; curr=curr->next) {
443 if(data == (struct SessionHandle *) curr->ptr) {
445 "problem we %p are still in send pipe for %p done %d\n",
446 data, connptr, (int)connptr->bits.done);
450 pipeline = connptr->recv_pipe;
452 for (curr = pipeline->head; curr; curr=curr->next) {
453 if(data == (struct SessionHandle *) curr->ptr) {
455 "problem we %p are still in recv pipe for %p done %d\n",
456 data, connptr, (int)connptr->bits.done);
460 pipeline = connptr->done_pipe;
462 for (curr = pipeline->head; curr; curr=curr->next) {
463 if(data == (struct SessionHandle *) curr->ptr) {
465 "problem we %p are still in done pipe for %p done %d\n",
466 data, connptr, (int)connptr->bits.done);
470 pipeline = connptr->pend_pipe;
472 for (curr = pipeline->head; curr; curr=curr->next) {
473 if(data == (struct SessionHandle *) curr->ptr) {
475 "problem we %p are still in pend pipe for %p done %d\n",
476 data, connptr, (int)connptr->bits.done);
484 Curl_expire(data, 0); /* shut off timers */
487 /* This handle is still part of a multi handle, take care of this first
488 and detach this handle from there. */
489 curl_multi_remove_handle(data->multi, data);
491 /* Destroy the timeout list that is held in the easy handle. It is
492 /normally/ done by curl_multi_remove_handle() but this is "just in
494 if(data->state.timeoutlist) {
495 Curl_llist_destroy(data->state.timeoutlist, NULL);
496 data->state.timeoutlist = NULL;
499 data->magic = 0; /* force a clear AFTER the possibly enforced removal from
500 the multi handle, since that function uses the magic
503 if(data->state.connc) {
505 if(data->state.connc->type == CONNCACHE_PRIVATE) {
506 /* close all connections still alive that are in the private connection
507 cache, as we no longer have the pointer left to the shared one. */
508 close_connections(data);
510 /* free the connection cache if allocated privately */
511 Curl_rm_connc(data->state.connc);
515 if(data->state.shared_conn) {
516 /* marked to be used by a pending connection so we can't kill this handle
518 data->state.closed = TRUE;
522 if(data->dns.hostcachetype == HCACHE_PRIVATE) {
523 Curl_hash_destroy(data->dns.hostcache);
524 data->dns.hostcachetype = HCACHE_NONE;
525 data->dns.hostcache = NULL;
528 if(data->state.rangestringalloc)
529 free(data->state.range);
531 /* Free the pathbuffer */
532 Curl_safefree(data->state.pathbuffer);
533 Curl_safefree(data->state.proto.generic);
535 /* Close down all open SSL info and sessions */
536 Curl_ssl_close_all(data);
537 Curl_safefree(data->state.first_host);
538 Curl_safefree(data->state.scratch);
539 Curl_ssl_free_certinfo(data);
541 if(data->change.referer_alloc)
542 free(data->change.referer);
544 if(data->change.url_alloc)
545 free(data->change.url);
547 Curl_safefree(data->state.headerbuff);
549 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
550 flush_cookies(data, 1);
553 Curl_digest_cleanup(data);
555 Curl_safefree(data->info.contenttype);
556 Curl_safefree(data->info.wouldredirect);
558 /* this destroys the channel and we cannot use it anymore after this */
559 ares_destroy(data->state.areschannel);
561 #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
562 /* close iconv conversion descriptors */
563 if(data->inbound_cd != (iconv_t)-1) {
564 iconv_close(data->inbound_cd);
566 if(data->outbound_cd != (iconv_t)-1) {
567 iconv_close(data->outbound_cd);
569 if(data->utf8_cd != (iconv_t)-1) {
570 iconv_close(data->utf8_cd);
572 #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
574 /* No longer a dirty share, if it exists */
576 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
577 data->share->dirty--;
578 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
586 /* create a connection cache of a private or multi type */
587 struct conncache *Curl_mk_connc(int type,
588 long amount) /* set -1 to use default */
590 /* It is subject for debate how many default connections to have for a multi
591 connection cache... */
595 long max_amount = (long)(((size_t)INT_MAX) / sizeof(struct connectdata *));
597 if(type == CONNCACHE_PRIVATE) {
598 default_amount = (amount < 1L) ? 5L : amount;
601 default_amount = (amount < 1L) ? 10L : amount;
604 if(default_amount > max_amount)
605 default_amount = max_amount;
607 c = calloc(1, sizeof(struct conncache));
611 c->connects = calloc((size_t)default_amount, sizeof(struct connectdata *));
617 c->num = default_amount;
622 /* Change number of entries of a connection cache */
623 CURLcode Curl_ch_connc(struct SessionHandle *data,
628 struct connectdata **newptr;
629 long max_amount = (long)(((size_t)INT_MAX) / sizeof(struct connectdata *));
632 newamount = 1; /* we better have at least one entry */
635 /* we get a NULL pointer passed in as connection cache, which means that
636 there is no cache created for this SessionHandle just yet, we create a
637 brand new with the requested size.
639 data->state.connc = Curl_mk_connc(CONNCACHE_PRIVATE, newamount);
640 if(!data->state.connc)
641 return CURLE_OUT_OF_MEMORY;
645 if(newamount < c->num) {
646 /* Since this number is *decreased* from the existing number, we must
647 close the possibly open connections that live on the indexes that
650 NOTE: for conncache_multi cases we must make sure that we only
651 close handles not in use.
653 for(i=newamount; i< c->num; i++)
654 Curl_disconnect(c->connects[i], /* dead_connection */ FALSE);
656 /* If the most recent connection is no longer valid, mark it
658 if(data->state.lastconnect <= newamount)
659 data->state.lastconnect = -1;
662 if(newamount > max_amount)
663 newamount = max_amount;
664 newptr = realloc(c->connects, sizeof(struct connectdata *) * newamount);
666 /* we closed a few connections in vain, but so what? */
667 return CURLE_OUT_OF_MEMORY;
669 /* nullify the newly added pointers */
670 for(i=c->num; i<newamount; i++)
673 c->connects = newptr;
676 /* we no longer support less than 1 as size for the connection cache, and
677 I'm not sure it ever worked to set it to zero */
681 /* Free a connection cache. This is called from Curl_close() and
682 curl_multi_cleanup(). */
683 void Curl_rm_connc(struct conncache *c)
687 for(i = 0; i < c->num; ++i)
688 conn_free(c->connects[i]);
697 * Initialize the UserDefined fields within a SessionHandle.
698 * This may be safely called on a new or existing SessionHandle.
700 CURLcode Curl_init_userdefined(struct UserDefined *set)
702 CURLcode res = CURLE_OK;
704 set->out = stdout; /* default output to stdout */
705 set->in = stdin; /* default input from stdin */
706 set->err = stderr; /* default stderr to stderr */
708 /* use fwrite as default function to store output */
709 set->fwrite_func = (curl_write_callback)fwrite;
711 /* use fread as default function to read input */
712 set->fread_func = (curl_read_callback)fread;
713 set->is_fread_set = 0;
714 set->is_fwrite_set = 0;
716 set->seek_func = ZERO_NULL;
717 set->seek_client = ZERO_NULL;
719 /* conversion callbacks for non-ASCII hosts */
720 set->convfromnetwork = ZERO_NULL;
721 set->convtonetwork = ZERO_NULL;
722 set->convfromutf8 = ZERO_NULL;
724 set->infilesize = -1; /* we don't know any size */
725 set->postfieldsize = -1; /* unknown size */
726 set->maxredirs = -1; /* allow any amount by default */
728 set->httpreq = HTTPREQ_GET; /* Default HTTP request */
729 set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
730 set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
731 set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
732 set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
733 set->ftp_filemethod = FTPFILE_MULTICWD;
735 set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
737 /* Set the default size of the SSL session ID cache */
738 set->ssl.numsessions = 5;
740 set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
741 set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
742 set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
743 set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
745 /* make libcurl quiet by default: */
746 set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
749 * libcurl 7.10 introduced SSL verification *by default*! This needs to be
750 * switched off unless wanted.
752 set->ssl.verifypeer = TRUE;
753 set->ssl.verifyhost = 2;
754 set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
756 set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
758 set->new_file_perms = 0644; /* Default permissions */
759 set->new_directory_perms = 0755; /* Default permissions */
761 /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
762 define since we internally only use the lower 16 bits for the passed
763 in bitmask to not conflict with the private bits */
764 set->allowed_protocols = PROT_EXTMASK;
765 set->redir_protocols =
766 PROT_EXTMASK & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
768 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
770 * disallow unprotected protection negotiation NEC reference implementation
771 * seem not to follow rfc1961 section 4.3/4.4
773 set->socks5_gssapi_nec = FALSE;
774 /* set default gssapi service name */
775 res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
776 (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
781 /* This is our preferred CA cert bundle/path since install time */
782 #if defined(CURL_CA_BUNDLE)
783 res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
784 #elif defined(CURL_CA_PATH)
785 res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
788 set->wildcardmatch = FALSE;
789 set->chunk_bgn = ZERO_NULL;
790 set->chunk_end = ZERO_NULL;
798 * @param curl is a pointer to a sessionhandle pointer that gets set by this
803 CURLcode Curl_open(struct SessionHandle **curl)
805 CURLcode res = CURLE_OK;
806 struct SessionHandle *data;
811 /* Very simple start-up: alloc the struct, init it with zeroes and return */
812 data = calloc(1, sizeof(struct SessionHandle));
814 /* this is a very serious error */
815 DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
816 return CURLE_OUT_OF_MEMORY;
819 data->magic = CURLEASY_MAGIC_NUMBER;
822 if((status = ares_init(&data->state.areschannel)) != ARES_SUCCESS) {
823 DEBUGF(fprintf(stderr, "Error: ares_init failed\n"));
825 if(status == ARES_ENOMEM)
826 return CURLE_OUT_OF_MEMORY;
828 return CURLE_FAILED_INIT;
830 /* make sure that all other returns from this function should destroy the
831 ares channel before returning error! */
834 /* We do some initial setup here, all those fields that can't be just 0 */
836 data->state.headerbuff = malloc(HEADERSIZE);
837 if(!data->state.headerbuff) {
838 DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
839 res = CURLE_OUT_OF_MEMORY;
842 Curl_easy_initHandleData(data);
843 res = Curl_init_userdefined(&data->set);
845 data->state.headersize=HEADERSIZE;
847 #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
848 /* conversion descriptors for iconv calls */
849 data->outbound_cd = (iconv_t)-1;
850 data->inbound_cd = (iconv_t)-1;
851 data->utf8_cd = (iconv_t)-1;
852 #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
854 /* most recent connection is not yet defined */
855 data->state.lastconnect = -1;
857 data->progress.flags |= PGRS_HIDE;
858 data->state.current_speed = -1; /* init to negative == impossible */
860 data->wildcard.state = CURLWC_INIT;
861 data->wildcard.filelist = NULL;
862 data->set.fnmatch = ZERO_NULL;
863 /* This no longer creates a connection cache here. It is instead made on
864 the first call to curl_easy_perform() or when the handle is added to a
869 ares_destroy(data->state.areschannel);
870 if(data->state.headerbuff)
871 free(data->state.headerbuff);
882 CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
886 CURLcode result = CURLE_OK;
887 #ifndef CURL_DISABLE_HTTP
892 case CURLOPT_DNS_CACHE_TIMEOUT:
893 data->set.dns_cache_timeout = va_arg(param, long);
895 case CURLOPT_DNS_USE_GLOBAL_CACHE:
897 /* remember we want this enabled */
898 long use_cache = va_arg(param, long);
899 data->set.global_dns_cache = (bool)(0 != use_cache);
902 case CURLOPT_SSL_CIPHER_LIST:
903 /* set a list of cipher we want to use in the SSL connection */
904 result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
905 va_arg(param, char *));
908 case CURLOPT_RANDOM_FILE:
910 * This is the path name to a file that contains random data to seed
911 * the random SSL stuff with. The file is only used for reading.
913 result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
914 va_arg(param, char *));
916 case CURLOPT_EGDSOCKET:
918 * The Entropy Gathering Daemon socket pathname
920 result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
921 va_arg(param, char *));
923 case CURLOPT_MAXCONNECTS:
925 * Set the absolute number of maximum simultaneous alive connection that
926 * libcurl is allowed to have.
928 result = Curl_ch_connc(data, data->state.connc, va_arg(param, long));
930 case CURLOPT_FORBID_REUSE:
932 * When this transfer is done, it must not be left to be reused by a
933 * subsequent transfer but shall be closed immediately.
935 data->set.reuse_forbid = (bool)(0 != va_arg(param, long));
937 case CURLOPT_FRESH_CONNECT:
939 * This transfer shall not use a previously cached connection but
940 * should be made with a fresh new connect!
942 data->set.reuse_fresh = (bool)(0 != va_arg(param, long));
944 case CURLOPT_VERBOSE:
946 * Verbose means infof() calls that give a lot of information about
947 * the connection and transfer procedures as well as internal choices.
949 data->set.verbose = (bool)(0 != va_arg(param, long));
953 * Set to include the header in the general data output stream.
955 data->set.include_header = (bool)(0 != va_arg(param, long));
957 case CURLOPT_NOPROGRESS:
959 * Shut off the internal supported progress meter
961 data->set.hide_progress = (bool)(0 != va_arg(param, long));
962 if(data->set.hide_progress)
963 data->progress.flags |= PGRS_HIDE;
965 data->progress.flags &= ~PGRS_HIDE;
969 * Do not include the body part in the output data stream.
971 data->set.opt_no_body = (bool)(0 != va_arg(param, long));
973 case CURLOPT_FAILONERROR:
975 * Don't output the >=300 error code HTML-page, but instead only
978 data->set.http_fail_on_error = (bool)(0 != va_arg(param, long));
983 * We want to sent data to the remote host. If this is HTTP, that equals
984 * using the PUT request.
986 data->set.upload = (bool)(0 != va_arg(param, long));
987 if(data->set.upload) {
988 /* If this is HTTP, PUT is what's needed to "upload" */
989 data->set.httpreq = HTTPREQ_PUT;
990 data->set.opt_no_body = FALSE; /* this is implied */
993 /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
994 then this can be changed to HEAD later on) */
995 data->set.httpreq = HTTPREQ_GET;
997 case CURLOPT_FILETIME:
999 * Try to get the file time of the remote document. The time will
1000 * later (possibly) become available using curl_easy_getinfo().
1002 data->set.get_filetime = (bool)(0 != va_arg(param, long));
1004 case CURLOPT_FTP_CREATE_MISSING_DIRS:
1006 * An FTP option that modifies an upload to create missing directories on
1009 switch(va_arg(param, long)) {
1011 data->set.ftp_create_missing_dirs = 0;
1014 data->set.ftp_create_missing_dirs = 1;
1017 data->set.ftp_create_missing_dirs = 2;
1020 /* reserve other values for future use */
1021 result = CURLE_FAILED_INIT;
1025 case CURLOPT_SERVER_RESPONSE_TIMEOUT:
1027 * Option that specifies how quickly an server response must be obtained
1028 * before it is considered failure. For pingpong protocols.
1030 data->set.server_response_timeout = va_arg( param , long ) * 1000;
1032 case CURLOPT_TFTP_BLKSIZE:
1034 * TFTP option that specifies the block size to use for data transmission
1036 data->set.tftp_blksize = va_arg(param, long);
1038 case CURLOPT_DIRLISTONLY:
1040 * An option that changes the command to one that asks for a list
1041 * only, no file info details.
1043 data->set.ftp_list_only = (bool)(0 != va_arg(param, long));
1045 case CURLOPT_APPEND:
1047 * We want to upload and append to an existing file.
1049 data->set.ftp_append = (bool)(0 != va_arg(param, long));
1051 case CURLOPT_FTP_FILEMETHOD:
1053 * How do access files over FTP.
1055 data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
1059 * Parse the $HOME/.netrc file
1061 data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
1063 case CURLOPT_NETRC_FILE:
1065 * Use this file instead of the $HOME/.netrc file
1067 result = setstropt(&data->set.str[STRING_NETRC_FILE],
1068 va_arg(param, char *));
1070 case CURLOPT_TRANSFERTEXT:
1072 * This option was previously named 'FTPASCII'. Renamed to work with
1073 * more protocols than merely FTP.
1075 * Transfer using ASCII (instead of BINARY).
1077 data->set.prefer_ascii = (bool)(0 != va_arg(param, long));
1079 case CURLOPT_TIMECONDITION:
1081 * Set HTTP time condition. This must be one of the defines in the
1082 * curl/curl.h header file.
1084 data->set.timecondition = (curl_TimeCond)va_arg(param, long);
1086 case CURLOPT_TIMEVALUE:
1088 * This is the value to compare with the remote document with the
1089 * method set with CURLOPT_TIMECONDITION
1091 data->set.timevalue = (time_t)va_arg(param, long);
1093 case CURLOPT_SSLVERSION:
1095 * Set explicit SSL version to try to connect with, as some SSL
1096 * implementations are lame.
1098 data->set.ssl.version = va_arg(param, long);
1101 #ifndef CURL_DISABLE_HTTP
1102 case CURLOPT_AUTOREFERER:
1104 * Switch on automatic referer that gets set if curl follows locations.
1106 data->set.http_auto_referer = (bool)(0 != va_arg(param, long));
1109 case CURLOPT_ENCODING:
1111 * String to use at the value of Accept-Encoding header.
1113 * If the encoding is set to "" we use an Accept-Encoding header that
1114 * encompasses all the encodings we support.
1115 * If the encoding is set to NULL we don't send an Accept-Encoding header
1116 * and ignore an received Content-Encoding header.
1119 argptr = va_arg(param, char *);
1120 result = setstropt(&data->set.str[STRING_ENCODING],
1121 (argptr && !*argptr)?
1122 (char *) ALL_CONTENT_ENCODINGS: argptr);
1125 case CURLOPT_FOLLOWLOCATION:
1127 * Follow Location: header hints on a HTTP-server.
1129 data->set.http_follow_location = (bool)(0 != va_arg(param, long));
1132 case CURLOPT_UNRESTRICTED_AUTH:
1134 * Send authentication (user+password) when following locations, even when
1137 data->set.http_disable_hostname_check_before_authentication =
1138 (bool)(0 != va_arg(param, long));
1141 case CURLOPT_MAXREDIRS:
1143 * The maximum amount of hops you allow curl to follow Location:
1144 * headers. This should mostly be used to detect never-ending loops.
1146 data->set.maxredirs = va_arg(param, long);
1149 case CURLOPT_POSTREDIR:
1152 * Set the behaviour of POST when redirecting
1153 * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
1154 * CURL_REDIR_POST_301 - POST is kept as POST after 301
1155 * CURL_REDIR_POST_302 - POST is kept as POST after 302
1156 * CURL_REDIR_POST_ALL - POST is kept as POST after 301 and 302
1157 * other - POST is kept as POST after 301 and 302
1159 long postRedir = va_arg(param, long);
1160 data->set.post301 = (bool)((postRedir & CURL_REDIR_POST_301)?TRUE:FALSE);
1161 data->set.post302 = (bool)((postRedir & CURL_REDIR_POST_302)?TRUE:FALSE);
1166 /* Does this option serve a purpose anymore? Yes it does, when
1167 CURLOPT_POSTFIELDS isn't used and the POST data is read off the
1169 if(va_arg(param, long)) {
1170 data->set.httpreq = HTTPREQ_POST;
1171 data->set.opt_no_body = FALSE; /* this is implied */
1174 data->set.httpreq = HTTPREQ_GET;
1177 case CURLOPT_COPYPOSTFIELDS:
1179 * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
1180 * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
1181 * CURLOPT_COPYPOSTFIELDS and not altered later.
1183 argptr = va_arg(param, char *);
1185 if(!argptr || data->set.postfieldsize == -1)
1186 result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
1189 * Check that requested length does not overflow the size_t type.
1192 if((data->set.postfieldsize < 0) ||
1193 ((sizeof(curl_off_t) != sizeof(size_t)) &&
1194 (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
1195 result = CURLE_OUT_OF_MEMORY;
1199 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1201 /* Allocate even when size == 0. This satisfies the need of possible
1202 later address compare to detect the COPYPOSTFIELDS mode, and
1203 to mark that postfields is used rather than read function or
1206 p = malloc((size_t)(data->set.postfieldsize?
1207 data->set.postfieldsize:1));
1210 result = CURLE_OUT_OF_MEMORY;
1212 if(data->set.postfieldsize)
1213 memcpy(p, argptr, (size_t)data->set.postfieldsize);
1215 data->set.str[STRING_COPYPOSTFIELDS] = p;
1220 data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
1221 data->set.httpreq = HTTPREQ_POST;
1224 case CURLOPT_POSTFIELDS:
1226 * Like above, but use static data instead of copying it.
1228 data->set.postfields = va_arg(param, void *);
1229 /* Release old copied data. */
1230 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1231 data->set.httpreq = HTTPREQ_POST;
1234 case CURLOPT_POSTFIELDSIZE:
1236 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1237 * figure it out. Enables binary posts.
1239 bigsize = va_arg(param, long);
1241 if(data->set.postfieldsize < bigsize &&
1242 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1243 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1244 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1245 data->set.postfields = NULL;
1248 data->set.postfieldsize = bigsize;
1251 case CURLOPT_POSTFIELDSIZE_LARGE:
1253 * The size of the POSTFIELD data to prevent libcurl to do strlen() to
1254 * figure it out. Enables binary posts.
1256 bigsize = va_arg(param, curl_off_t);
1258 if(data->set.postfieldsize < bigsize &&
1259 data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
1260 /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
1261 (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
1262 data->set.postfields = NULL;
1265 data->set.postfieldsize = bigsize;
1268 case CURLOPT_HTTPPOST:
1270 * Set to make us do HTTP POST
1272 data->set.httppost = va_arg(param, struct curl_httppost *);
1273 data->set.httpreq = HTTPREQ_POST_FORM;
1274 data->set.opt_no_body = FALSE; /* this is implied */
1277 case CURLOPT_REFERER:
1279 * String to set in the HTTP Referer: field.
1281 if(data->change.referer_alloc) {
1282 free(data->change.referer);
1283 data->change.referer_alloc = FALSE;
1285 result = setstropt(&data->set.str[STRING_SET_REFERER],
1286 va_arg(param, char *));
1287 data->change.referer = data->set.str[STRING_SET_REFERER];
1290 case CURLOPT_USERAGENT:
1292 * String to use in the HTTP User-Agent field
1294 result = setstropt(&data->set.str[STRING_USERAGENT],
1295 va_arg(param, char *));
1298 case CURLOPT_HTTPHEADER:
1300 * Set a list with HTTP headers to use (or replace internals with)
1302 data->set.headers = va_arg(param, struct curl_slist *);
1305 case CURLOPT_HTTP200ALIASES:
1307 * Set a list of aliases for HTTP 200 in response header
1309 data->set.http200aliases = va_arg(param, struct curl_slist *);
1312 #if !defined(CURL_DISABLE_COOKIES)
1313 case CURLOPT_COOKIE:
1315 * Cookie string to send to the remote server in the request.
1317 result = setstropt(&data->set.str[STRING_COOKIE],
1318 va_arg(param, char *));
1321 case CURLOPT_COOKIEFILE:
1323 * Set cookie file to read and parse. Can be used multiple times.
1325 argptr = (char *)va_arg(param, void *);
1327 struct curl_slist *cl;
1328 /* append the cookie file name to the list of file names, and deal with
1330 cl = curl_slist_append(data->change.cookielist, argptr);
1333 return CURLE_OUT_OF_MEMORY;
1335 data->change.cookielist = cl; /* store the list for later use */
1339 case CURLOPT_COOKIEJAR:
1341 * Set cookie file name to dump all cookies to when we're done.
1343 result = setstropt(&data->set.str[STRING_COOKIEJAR],
1344 va_arg(param, char *));
1347 * Activate the cookie parser. This may or may not already
1350 data->cookies = Curl_cookie_init(data, NULL, data->cookies,
1351 data->set.cookiesession);
1354 case CURLOPT_COOKIESESSION:
1356 * Set this option to TRUE to start a new "cookie session". It will
1357 * prevent the forthcoming read-cookies-from-file actions to accept
1358 * cookies that are marked as being session cookies, as they belong to a
1361 * In the original Netscape cookie spec, "session cookies" are cookies
1362 * with no expire date set. RFC2109 describes the same action if no
1363 * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
1364 * a 'Discard' action that can enforce the discard even for cookies that
1367 * We run mostly with the original cookie spec, as hardly anyone implements
1370 data->set.cookiesession = (bool)(0 != va_arg(param, long));
1373 case CURLOPT_COOKIELIST:
1374 argptr = va_arg(param, char *);
1379 if(Curl_raw_equal(argptr, "ALL")) {
1380 /* clear all cookies */
1381 Curl_cookie_clearall(data->cookies);
1384 else if(Curl_raw_equal(argptr, "SESS")) {
1385 /* clear session cookies */
1386 Curl_cookie_clearsess(data->cookies);
1389 else if(Curl_raw_equal(argptr, "FLUSH")) {
1390 /* flush cookies to file */
1391 flush_cookies(data, 0);
1396 /* if cookie engine was not running, activate it */
1397 data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
1399 argptr = strdup(argptr);
1401 result = CURLE_OUT_OF_MEMORY;
1405 if(checkprefix("Set-Cookie:", argptr))
1406 /* HTTP Header format line */
1407 Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
1410 /* Netscape format line */
1411 Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
1415 #endif /* CURL_DISABLE_COOKIES */
1417 case CURLOPT_HTTPGET:
1419 * Set to force us do HTTP GET
1421 if(va_arg(param, long)) {
1422 data->set.httpreq = HTTPREQ_GET;
1423 data->set.upload = FALSE; /* switch off upload */
1424 data->set.opt_no_body = FALSE; /* this is implied */
1428 case CURLOPT_HTTP_VERSION:
1430 * This sets a requested HTTP version to be used. The value is one of
1431 * the listed enums in curl/curl.h.
1433 data->set.httpversion = va_arg(param, long);
1436 case CURLOPT_HTTPAUTH:
1438 * Set HTTP Authentication type BITMASK.
1441 long auth = va_arg(param, long);
1443 /* the DIGEST_IE bit is only used to set a special marker, for all the
1444 rest we need to handle it as normal DIGEST */
1445 data->state.authhost.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE)?
1448 if(auth & CURLAUTH_DIGEST_IE) {
1449 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1450 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1453 /* switch off bits we can't support */
1455 auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
1458 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI */
1461 return CURLE_FAILED_INIT; /* no supported types left! */
1463 data->set.httpauth = auth;
1467 #endif /* CURL_DISABLE_HTTP */
1469 case CURLOPT_CUSTOMREQUEST:
1471 * Set a custom string to use as request
1473 result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
1474 va_arg(param, char *));
1477 data->set.httpreq = HTTPREQ_CUSTOM;
1478 here, we continue as if we were using the already set type
1479 and this just changes the actual request keyword */
1482 #ifndef CURL_DISABLE_PROXY
1483 case CURLOPT_HTTPPROXYTUNNEL:
1485 * Tunnel operations through the proxy instead of normal proxy use
1487 data->set.tunnel_thru_httpproxy = (bool)(0 != va_arg(param, long));
1490 case CURLOPT_PROXYPORT:
1492 * Explicitly set HTTP proxy port number.
1494 data->set.proxyport = va_arg(param, long);
1497 case CURLOPT_PROXYAUTH:
1499 * Set HTTP Authentication type BITMASK.
1502 long auth = va_arg(param, long);
1504 /* the DIGEST_IE bit is only used to set a special marker, for all the
1505 rest we need to handle it as normal DIGEST */
1506 data->state.authproxy.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE)?
1509 if(auth & CURLAUTH_DIGEST_IE) {
1510 auth |= CURLAUTH_DIGEST; /* set standard digest bit */
1511 auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
1513 /* switch off bits we can't support */
1515 auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
1518 auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI */
1521 return CURLE_FAILED_INIT; /* no supported types left! */
1523 data->set.proxyauth = auth;
1529 * Set proxy server:port to use as HTTP proxy.
1531 * If the proxy is set to "" we explicitly say that we don't want to use a
1532 * proxy (even though there might be environment variables saying so).
1534 * Setting it to NULL, means no proxy but allows the environment variables
1537 result = setstropt(&data->set.str[STRING_PROXY],
1538 va_arg(param, char *));
1541 case CURLOPT_PROXYTYPE:
1543 * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
1545 data->set.proxytype = (curl_proxytype)va_arg(param, long);
1548 case CURLOPT_PROXY_TRANSFER_MODE:
1550 * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
1552 switch (va_arg(param, long)) {
1554 data->set.proxy_transfer_mode = FALSE;
1557 data->set.proxy_transfer_mode = TRUE;
1560 /* reserve other values for future use */
1561 result = CURLE_FAILED_INIT;
1565 #endif /* CURL_DISABLE_PROXY */
1567 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1568 case CURLOPT_SOCKS5_GSSAPI_SERVICE:
1570 * Set gssapi service name
1572 result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
1573 va_arg(param, char *));
1576 case CURLOPT_SOCKS5_GSSAPI_NEC:
1578 * set flag for nec socks5 support
1580 data->set.socks5_gssapi_nec = (bool)(0 != va_arg(param, long));
1584 case CURLOPT_WRITEHEADER:
1586 * Custom pointer to pass the header write callback function
1588 data->set.writeheader = (void *)va_arg(param, void *);
1590 case CURLOPT_ERRORBUFFER:
1592 * Error buffer provided by the caller to get the human readable
1595 data->set.errorbuffer = va_arg(param, char *);
1599 * FILE pointer to write to or include in the data write callback
1601 data->set.out = va_arg(param, FILE *);
1603 case CURLOPT_FTPPORT:
1605 * Use FTP PORT, this also specifies which IP address to use
1607 result = setstropt(&data->set.str[STRING_FTPPORT],
1608 va_arg(param, char *));
1609 data->set.ftp_use_port = (bool)(NULL != data->set.str[STRING_FTPPORT]);
1612 case CURLOPT_FTP_USE_EPRT:
1613 data->set.ftp_use_eprt = (bool)(0 != va_arg(param, long));
1616 case CURLOPT_FTP_USE_EPSV:
1617 data->set.ftp_use_epsv = (bool)(0 != va_arg(param, long));
1620 case CURLOPT_FTP_USE_PRET:
1621 data->set.ftp_use_pret = (bool)(0 != va_arg(param, long));
1624 case CURLOPT_FTP_SSL_CCC:
1625 data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
1628 case CURLOPT_FTP_SKIP_PASV_IP:
1630 * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
1631 * bypass of the IP address in PASV responses.
1633 data->set.ftp_skip_ip = (bool)(0 != va_arg(param, long));
1636 case CURLOPT_INFILE:
1638 * FILE pointer to read the file to be uploaded from. Or possibly
1639 * used as argument to the read callback.
1641 data->set.in = va_arg(param, FILE *);
1643 case CURLOPT_INFILESIZE:
1645 * If known, this should inform curl about the file size of the
1646 * to-be-uploaded file.
1648 data->set.infilesize = va_arg(param, long);
1650 case CURLOPT_INFILESIZE_LARGE:
1652 * If known, this should inform curl about the file size of the
1653 * to-be-uploaded file.
1655 data->set.infilesize = va_arg(param, curl_off_t);
1657 case CURLOPT_LOW_SPEED_LIMIT:
1659 * The low speed limit that if transfers are below this for
1660 * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
1662 data->set.low_speed_limit=va_arg(param, long);
1664 case CURLOPT_MAX_SEND_SPEED_LARGE:
1666 * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
1667 * bytes per second the transfer is throttled..
1669 data->set.max_send_speed=va_arg(param, curl_off_t);
1671 case CURLOPT_MAX_RECV_SPEED_LARGE:
1673 * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
1674 * second the transfer is throttled..
1676 data->set.max_recv_speed=va_arg(param, curl_off_t);
1678 case CURLOPT_LOW_SPEED_TIME:
1680 * The low speed time that if transfers are below the set
1681 * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
1683 data->set.low_speed_time=va_arg(param, long);
1689 if(data->change.url_alloc) {
1690 /* the already set URL is allocated, free it first! */
1691 free(data->change.url);
1692 data->change.url_alloc=FALSE;
1694 result = setstropt(&data->set.str[STRING_SET_URL],
1695 va_arg(param, char *));
1696 data->change.url = data->set.str[STRING_SET_URL];
1700 * The port number to use when getting the URL
1702 data->set.use_port = va_arg(param, long);
1704 case CURLOPT_TIMEOUT:
1706 * The maximum time you allow curl to use for a single transfer
1709 data->set.timeout = va_arg(param, long) * 1000L;
1712 case CURLOPT_TIMEOUT_MS:
1713 data->set.timeout = va_arg(param, long);
1716 case CURLOPT_CONNECTTIMEOUT:
1718 * The maximum time you allow curl to use to connect.
1720 data->set.connecttimeout = va_arg(param, long) * 1000L;
1723 case CURLOPT_CONNECTTIMEOUT_MS:
1724 data->set.connecttimeout = va_arg(param, long);
1727 case CURLOPT_USERPWD:
1729 * user:password to use in the operation
1731 result = setstropt_userpwd(va_arg(param, char *),
1732 &data->set.str[STRING_USERNAME],
1733 &data->set.str[STRING_PASSWORD]);
1735 case CURLOPT_USERNAME:
1737 * authentication user name to use in the operation
1739 result = setstropt(&data->set.str[STRING_USERNAME],
1740 va_arg(param, char *));
1742 case CURLOPT_PASSWORD:
1744 * authentication password to use in the operation
1746 result = setstropt(&data->set.str[STRING_PASSWORD],
1747 va_arg(param, char *));
1749 case CURLOPT_POSTQUOTE:
1751 * List of RAW FTP commands to use after a transfer
1753 data->set.postquote = va_arg(param, struct curl_slist *);
1755 case CURLOPT_PREQUOTE:
1757 * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
1759 data->set.prequote = va_arg(param, struct curl_slist *);
1763 * List of RAW FTP commands to use before a transfer
1765 data->set.quote = va_arg(param, struct curl_slist *);
1767 case CURLOPT_RESOLVE:
1769 * List of NAME:[address] names to populate the DNS cache with
1770 * Prefix the NAME with dash (-) to _remove_ the name from the cache.
1772 * Names added with this API will remain in the cache until explicitly
1773 * removed or the handle is cleaned up.
1775 * This API can remove any name from the DNS cache, but only entries
1776 * that aren't actually in use right now will be pruned immediately.
1778 data->set.resolve = va_arg(param, struct curl_slist *);
1779 data->change.resolve = data->set.resolve;
1781 case CURLOPT_PROGRESSFUNCTION:
1783 * Progress callback function
1785 data->set.fprogress = va_arg(param, curl_progress_callback);
1786 if(data->set.fprogress)
1787 data->progress.callback = TRUE; /* no longer internal */
1789 data->progress.callback = FALSE; /* NULL enforces internal */
1792 case CURLOPT_PROGRESSDATA:
1794 * Custom client data to pass to the progress callback
1796 data->set.progress_client = va_arg(param, void *);
1799 #ifndef CURL_DISABLE_PROXY
1800 case CURLOPT_PROXYUSERPWD:
1802 * user:password needed to use the proxy
1804 result = setstropt_userpwd(va_arg(param, char *),
1805 &data->set.str[STRING_PROXYUSERNAME],
1806 &data->set.str[STRING_PROXYPASSWORD]);
1808 case CURLOPT_PROXYUSERNAME:
1810 * authentication user name to use in the operation
1812 result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
1813 va_arg(param, char *));
1815 case CURLOPT_PROXYPASSWORD:
1817 * authentication password to use in the operation
1819 result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
1820 va_arg(param, char *));
1822 case CURLOPT_NOPROXY:
1824 * proxy exception list
1826 result = setstropt(&data->set.str[STRING_NOPROXY],
1827 va_arg(param, char *));
1833 * What range of the file you want to transfer
1835 result = setstropt(&data->set.str[STRING_SET_RANGE],
1836 va_arg(param, char *));
1838 case CURLOPT_RESUME_FROM:
1840 * Resume transfer at the give file position
1842 data->set.set_resume_from = va_arg(param, long);
1844 case CURLOPT_RESUME_FROM_LARGE:
1846 * Resume transfer at the give file position
1848 data->set.set_resume_from = va_arg(param, curl_off_t);
1850 case CURLOPT_DEBUGFUNCTION:
1852 * stderr write callback.
1854 data->set.fdebug = va_arg(param, curl_debug_callback);
1856 * if the callback provided is NULL, it'll use the default callback
1859 case CURLOPT_DEBUGDATA:
1861 * Set to a void * that should receive all error writes. This
1862 * defaults to CURLOPT_STDERR for normal operations.
1864 data->set.debugdata = va_arg(param, void *);
1866 case CURLOPT_STDERR:
1868 * Set to a FILE * that should receive all error writes. This
1869 * defaults to stderr for normal operations.
1871 data->set.err = va_arg(param, FILE *);
1873 data->set.err = stderr;
1875 case CURLOPT_HEADERFUNCTION:
1877 * Set header write callback
1879 data->set.fwrite_header = va_arg(param, curl_write_callback);
1881 case CURLOPT_WRITEFUNCTION:
1883 * Set data write callback
1885 data->set.fwrite_func = va_arg(param, curl_write_callback);
1886 if(!data->set.fwrite_func) {
1887 data->set.is_fwrite_set = 0;
1888 /* When set to NULL, reset to our internal default function */
1889 data->set.fwrite_func = (curl_write_callback)fwrite;
1892 data->set.is_fwrite_set = 1;
1894 case CURLOPT_READFUNCTION:
1896 * Read data callback
1898 data->set.fread_func = va_arg(param, curl_read_callback);
1899 if(!data->set.fread_func) {
1900 data->set.is_fread_set = 0;
1901 /* When set to NULL, reset to our internal default function */
1902 data->set.fread_func = (curl_read_callback)fread;
1905 data->set.is_fread_set = 1;
1907 case CURLOPT_SEEKFUNCTION:
1909 * Seek callback. Might be NULL.
1911 data->set.seek_func = va_arg(param, curl_seek_callback);
1913 case CURLOPT_SEEKDATA:
1915 * Seek control callback. Might be NULL.
1917 data->set.seek_client = va_arg(param, void *);
1919 case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
1921 * "Convert from network encoding" callback
1923 data->set.convfromnetwork = va_arg(param, curl_conv_callback);
1925 case CURLOPT_CONV_TO_NETWORK_FUNCTION:
1927 * "Convert to network encoding" callback
1929 data->set.convtonetwork = va_arg(param, curl_conv_callback);
1931 case CURLOPT_CONV_FROM_UTF8_FUNCTION:
1933 * "Convert from UTF-8 encoding" callback
1935 data->set.convfromutf8 = va_arg(param, curl_conv_callback);
1937 case CURLOPT_IOCTLFUNCTION:
1939 * I/O control callback. Might be NULL.
1941 data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
1943 case CURLOPT_IOCTLDATA:
1945 * I/O control data pointer. Might be NULL.
1947 data->set.ioctl_client = va_arg(param, void *);
1949 case CURLOPT_SSLCERT:
1951 * String that holds file name of the SSL certificate to use
1953 result = setstropt(&data->set.str[STRING_CERT],
1954 va_arg(param, char *));
1956 case CURLOPT_SSLCERTTYPE:
1958 * String that holds file type of the SSL certificate to use
1960 result = setstropt(&data->set.str[STRING_CERT_TYPE],
1961 va_arg(param, char *));
1963 case CURLOPT_SSLKEY:
1965 * String that holds file name of the SSL key to use
1967 result = setstropt(&data->set.str[STRING_KEY],
1968 va_arg(param, char *));
1970 case CURLOPT_SSLKEYTYPE:
1972 * String that holds file type of the SSL key to use
1974 result = setstropt(&data->set.str[STRING_KEY_TYPE],
1975 va_arg(param, char *));
1977 case CURLOPT_KEYPASSWD:
1979 * String that holds the SSL or SSH private key password.
1981 result = setstropt(&data->set.str[STRING_KEY_PASSWD],
1982 va_arg(param, char *));
1984 case CURLOPT_SSLENGINE:
1986 * String that holds the SSL crypto engine.
1988 argptr = va_arg(param, char *);
1989 if(argptr && argptr[0])
1990 result = Curl_ssl_set_engine(data, argptr);
1993 case CURLOPT_SSLENGINE_DEFAULT:
1995 * flag to set engine as default.
1997 result = Curl_ssl_set_engine_default(data);
2001 * Kludgy option to enable CRLF conversions. Subject for removal.
2003 data->set.crlf = (bool)(0 != va_arg(param, long));
2006 case CURLOPT_INTERFACE:
2008 * Set what interface or address/hostname to bind the socket to when
2009 * performing an operation and thus what from-IP your connection will use.
2011 result = setstropt(&data->set.str[STRING_DEVICE],
2012 va_arg(param, char *));
2014 case CURLOPT_LOCALPORT:
2016 * Set what local port to bind the socket to when performing an operation.
2018 data->set.localport = curlx_sltous(va_arg(param, long));
2020 case CURLOPT_LOCALPORTRANGE:
2022 * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
2024 data->set.localportrange = curlx_sltosi(va_arg(param, long));
2026 case CURLOPT_KRBLEVEL:
2028 * A string that defines the kerberos security level.
2030 result = setstropt(&data->set.str[STRING_KRB_LEVEL],
2031 va_arg(param, char *));
2032 data->set.krb = (bool)(NULL != data->set.str[STRING_KRB_LEVEL]);
2034 case CURLOPT_SSL_VERIFYPEER:
2036 * Enable peer SSL verifying.
2038 data->set.ssl.verifypeer = va_arg(param, long);
2040 case CURLOPT_SSL_VERIFYHOST:
2042 * Enable verification of the CN contained in the peer certificate
2044 data->set.ssl.verifyhost = va_arg(param, long);
2047 /* since these two options are only possible to use on an OpenSSL-
2048 powered libcurl we #ifdef them on this condition so that libcurls
2049 built against other SSL libs will return a proper error when trying
2050 to set this option! */
2051 case CURLOPT_SSL_CTX_FUNCTION:
2053 * Set a SSL_CTX callback
2055 data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
2057 case CURLOPT_SSL_CTX_DATA:
2059 * Set a SSL_CTX callback parameter pointer
2061 data->set.ssl.fsslctxp = va_arg(param, void *);
2063 case CURLOPT_CERTINFO:
2064 data->set.ssl.certinfo = (bool)(0 != va_arg(param, long));
2067 case CURLOPT_CAINFO:
2069 * Set CA info for SSL connection. Specify file name of the CA certificate
2071 result = setstropt(&data->set.str[STRING_SSL_CAFILE],
2072 va_arg(param, char *));
2074 case CURLOPT_CAPATH:
2076 * Set CA path info for SSL connection. Specify directory name of the CA
2077 * certificates which have been prepared using openssl c_rehash utility.
2079 /* This does not work on windows. */
2080 result = setstropt(&data->set.str[STRING_SSL_CAPATH],
2081 va_arg(param, char *));
2083 case CURLOPT_CRLFILE:
2085 * Set CRL file info for SSL connection. Specify file name of the CRL
2086 * to check certificates revocation
2088 result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
2089 va_arg(param, char *));
2091 case CURLOPT_ISSUERCERT:
2093 * Set Issuer certificate file
2094 * to check certificates issuer
2096 result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
2097 va_arg(param, char *));
2099 case CURLOPT_TELNETOPTIONS:
2101 * Set a linked list of telnet options
2103 data->set.telnet_options = va_arg(param, struct curl_slist *);
2106 case CURLOPT_BUFFERSIZE:
2108 * The application kindly asks for a differently sized receive buffer.
2109 * If it seems reasonable, we'll use it.
2111 data->set.buffer_size = va_arg(param, long);
2113 if((data->set.buffer_size> (BUFSIZE -1 )) ||
2114 (data->set.buffer_size < 1))
2115 data->set.buffer_size = 0; /* huge internal default */
2119 case CURLOPT_NOSIGNAL:
2121 * The application asks not to set any signal() or alarm() handlers,
2122 * even when using a timeout.
2124 data->set.no_signal = (bool)(0 != va_arg(param, long));
2129 struct Curl_share *set;
2130 set = va_arg(param, struct Curl_share *);
2132 /* disconnect from old share, if any */
2134 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2136 if(data->dns.hostcachetype == HCACHE_SHARED) {
2137 data->dns.hostcache = NULL;
2138 data->dns.hostcachetype = HCACHE_NONE;
2141 if(data->share->cookies == data->cookies)
2142 data->cookies = NULL;
2144 data->share->dirty--;
2146 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2150 /* use new share if it set */
2154 Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
2156 data->share->dirty++;
2158 if(data->share->hostcache) {
2159 /* use shared host cache, first free the private one if any */
2160 if(data->dns.hostcachetype == HCACHE_PRIVATE)
2161 Curl_hash_destroy(data->dns.hostcache);
2163 data->dns.hostcache = data->share->hostcache;
2164 data->dns.hostcachetype = HCACHE_SHARED;
2166 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
2167 if(data->share->cookies) {
2168 /* use shared cookie list, first free own one if any */
2170 Curl_cookie_cleanup(data->cookies);
2171 /* enable cookies since we now use a share that uses cookies! */
2172 data->cookies = data->share->cookies;
2174 #endif /* CURL_DISABLE_HTTP */
2175 Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
2178 /* check for host cache not needed,
2179 * it will be done by curl_easy_perform */
2183 case CURLOPT_PRIVATE:
2185 * Set private data pointer.
2187 data->set.private_data = va_arg(param, void *);
2190 case CURLOPT_MAXFILESIZE:
2192 * Set the maximum size of a file to download.
2194 data->set.max_filesize = va_arg(param, long);
2198 case CURLOPT_USE_SSL:
2200 * Make transfers attempt to use SSL/TLS.
2202 data->set.ftp_ssl = (curl_usessl)va_arg(param, long);
2205 case CURLOPT_FTPSSLAUTH:
2207 * Set a specific auth for FTP-SSL transfers.
2209 data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
2212 case CURLOPT_IPRESOLVE:
2213 data->set.ipver = va_arg(param, long);
2216 case CURLOPT_MAXFILESIZE_LARGE:
2218 * Set the maximum size of a file to download.
2220 data->set.max_filesize = va_arg(param, curl_off_t);
2223 case CURLOPT_TCP_NODELAY:
2225 * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
2228 data->set.tcp_nodelay = (bool)(0 != va_arg(param, long));
2231 case CURLOPT_FTP_ACCOUNT:
2232 result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
2233 va_arg(param, char *));
2236 case CURLOPT_IGNORE_CONTENT_LENGTH:
2237 data->set.ignorecl = (bool)(0 != va_arg(param, long));
2240 case CURLOPT_CONNECT_ONLY:
2242 * No data transfer, set up connection and let application use the socket
2244 data->set.connect_only = (bool)(0 != va_arg(param, long));
2247 case CURLOPT_FTP_ALTERNATIVE_TO_USER:
2248 result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
2249 va_arg(param, char *));
2252 case CURLOPT_SOCKOPTFUNCTION:
2254 * socket callback function: called after socket() but before connect()
2256 data->set.fsockopt = va_arg(param, curl_sockopt_callback);
2259 case CURLOPT_SOCKOPTDATA:
2261 * socket callback data pointer. Might be NULL.
2263 data->set.sockopt_client = va_arg(param, void *);
2266 case CURLOPT_OPENSOCKETFUNCTION:
2268 * open/create socket callback function: called instead of socket(),
2271 data->set.fopensocket = va_arg(param, curl_opensocket_callback);
2274 case CURLOPT_OPENSOCKETDATA:
2276 * socket callback data pointer. Might be NULL.
2278 data->set.opensocket_client = va_arg(param, void *);
2281 case CURLOPT_SSL_SESSIONID_CACHE:
2282 data->set.ssl.sessionid = (bool)(0 != va_arg(param, long));
2286 /* we only include SSH options if explicitly built to support SSH */
2287 case CURLOPT_SSH_AUTH_TYPES:
2288 data->set.ssh_auth_types = va_arg(param, long);
2291 case CURLOPT_SSH_PUBLIC_KEYFILE:
2293 * Use this file instead of the $HOME/.ssh/id_dsa.pub file
2295 result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
2296 va_arg(param, char *));
2299 case CURLOPT_SSH_PRIVATE_KEYFILE:
2301 * Use this file instead of the $HOME/.ssh/id_dsa file
2303 result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
2304 va_arg(param, char *));
2306 case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
2308 * Option to allow for the MD5 of the host public key to be checked
2309 * for validation purposes.
2311 result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
2312 va_arg(param, char *));
2314 #ifdef HAVE_LIBSSH2_KNOWNHOST_API
2315 case CURLOPT_SSH_KNOWNHOSTS:
2317 * Store the file name to read known hosts from.
2319 result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
2320 va_arg(param, char *));
2323 case CURLOPT_SSH_KEYFUNCTION:
2324 /* setting to NULL is fine since the ssh.c functions themselves will
2325 then rever to use the internal default */
2326 data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
2329 case CURLOPT_SSH_KEYDATA:
2331 * Custom client data to pass to the SSH keyfunc callback
2333 data->set.ssh_keyfunc_userp = va_arg(param, void *);
2335 #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
2337 #endif /* USE_LIBSSH2 */
2339 case CURLOPT_HTTP_TRANSFER_DECODING:
2341 * disable libcurl transfer encoding is used
2343 data->set.http_te_skip = (bool)(0 == va_arg(param, long));
2346 case CURLOPT_HTTP_CONTENT_DECODING:
2348 * raw data passed to the application when content encoding is used
2350 data->set.http_ce_skip = (bool)(0 == va_arg(param, long));
2353 case CURLOPT_NEW_FILE_PERMS:
2355 * Uses these permissions instead of 0644
2357 data->set.new_file_perms = va_arg(param, long);
2360 case CURLOPT_NEW_DIRECTORY_PERMS:
2362 * Uses these permissions instead of 0755
2364 data->set.new_directory_perms = va_arg(param, long);
2367 case CURLOPT_ADDRESS_SCOPE:
2369 * We always get longs when passed plain numericals, but for this value we
2370 * know that an unsigned int will always hold the value so we blindly
2371 * typecast to this type
2373 data->set.scope = curlx_sltoui(va_arg(param, long));
2376 case CURLOPT_PROTOCOLS:
2377 /* set the bitmask for the protocols that are allowed to be used for the
2378 transfer, which thus helps the app which takes URLs from users or other
2379 external inputs and want to restrict what protocol(s) to deal
2380 with. Defaults to CURLPROTO_ALL. */
2381 data->set.allowed_protocols = va_arg(param, long) & PROT_EXTMASK;
2384 case CURLOPT_REDIR_PROTOCOLS:
2385 /* set the bitmask for the protocols that libcurl is allowed to follow to,
2386 as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
2387 to be set in both bitmasks to be allowed to get redirected to. Defaults
2388 to all protocols except FILE and SCP. */
2389 data->set.redir_protocols = va_arg(param, long) & PROT_EXTMASK;
2392 case CURLOPT_MAIL_FROM:
2393 result = setstropt(&data->set.str[STRING_MAIL_FROM],
2394 va_arg(param, char *));
2397 case CURLOPT_MAIL_RCPT:
2398 /* get a list of mail recipients */
2399 data->set.mail_rcpt = va_arg(param, struct curl_slist *);
2402 case CURLOPT_RTSP_REQUEST:
2405 * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
2406 * Would this be better if the RTSPREQ_* were just moved into here?
2408 long curl_rtspreq = va_arg(param, long);
2409 Curl_RtspReq rtspreq = RTSPREQ_NONE;
2410 switch(curl_rtspreq) {
2411 case CURL_RTSPREQ_OPTIONS:
2412 rtspreq = RTSPREQ_OPTIONS;
2415 case CURL_RTSPREQ_DESCRIBE:
2416 rtspreq = RTSPREQ_DESCRIBE;
2419 case CURL_RTSPREQ_ANNOUNCE:
2420 rtspreq = RTSPREQ_ANNOUNCE;
2423 case CURL_RTSPREQ_SETUP:
2424 rtspreq = RTSPREQ_SETUP;
2427 case CURL_RTSPREQ_PLAY:
2428 rtspreq = RTSPREQ_PLAY;
2431 case CURL_RTSPREQ_PAUSE:
2432 rtspreq = RTSPREQ_PAUSE;
2435 case CURL_RTSPREQ_TEARDOWN:
2436 rtspreq = RTSPREQ_TEARDOWN;
2439 case CURL_RTSPREQ_GET_PARAMETER:
2440 rtspreq = RTSPREQ_GET_PARAMETER;
2443 case CURL_RTSPREQ_SET_PARAMETER:
2444 rtspreq = RTSPREQ_SET_PARAMETER;
2447 case CURL_RTSPREQ_RECORD:
2448 rtspreq = RTSPREQ_RECORD;
2451 case CURL_RTSPREQ_RECEIVE:
2452 rtspreq = RTSPREQ_RECEIVE;
2455 rtspreq = RTSPREQ_NONE;
2458 data->set.rtspreq = rtspreq;
2463 case CURLOPT_RTSP_SESSION_ID:
2465 * Set the RTSP Session ID manually. Useful if the application is
2466 * resuming a previously established RTSP session
2468 result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
2469 va_arg(param, char *));
2472 case CURLOPT_RTSP_STREAM_URI:
2474 * Set the Stream URI for the RTSP request. Unless the request is
2475 * for generic server options, the application will need to set this.
2477 result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
2478 va_arg(param, char *));
2481 case CURLOPT_RTSP_TRANSPORT:
2483 * The content of the Transport: header for the RTSP request
2485 result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
2486 va_arg(param, char *));
2489 case CURLOPT_RTSP_CLIENT_CSEQ:
2491 * Set the CSEQ number to issue for the next RTSP request. Useful if the
2492 * application is resuming a previously broken connection. The CSEQ
2493 * will increment from this new number henceforth.
2495 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2498 case CURLOPT_RTSP_SERVER_CSEQ:
2499 /* Same as the above, but for server-initiated requests */
2500 data->state.rtsp_next_client_CSeq = va_arg(param, long);
2503 case CURLOPT_INTERLEAVEDATA:
2504 data->set.rtp_out = va_arg(param, void *);
2506 case CURLOPT_INTERLEAVEFUNCTION:
2507 /* Set the user defined RTP write function */
2508 data->set.fwrite_rtp = va_arg(param, curl_write_callback);
2511 case CURLOPT_WILDCARDMATCH:
2512 data->set.wildcardmatch = (bool)(0 != va_arg(param, long));
2514 case CURLOPT_CHUNK_BGN_FUNCTION:
2515 data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
2517 case CURLOPT_CHUNK_END_FUNCTION:
2518 data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
2520 case CURLOPT_FNMATCH_FUNCTION:
2521 data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
2523 case CURLOPT_CHUNK_DATA:
2524 data->wildcard.customptr = va_arg(param, void *);
2526 case CURLOPT_FNMATCH_DATA:
2527 data->set.fnmatch_data = va_arg(param, void *);
2530 /* unknown tag and its companion, just ignore: */
2531 result = CURLE_FAILED_INIT; /* correct this */
2538 static void conn_free(struct connectdata *conn)
2543 /* close the SSL stuff before we close any sockets since they will/may
2544 write to the sockets */
2545 Curl_ssl_close(conn, FIRSTSOCKET);
2546 Curl_ssl_close(conn, SECONDARYSOCKET);
2548 /* close possibly still open sockets */
2549 if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
2550 sclose(conn->sock[SECONDARYSOCKET]);
2551 if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
2552 sclose(conn->sock[FIRSTSOCKET]);
2554 Curl_safefree(conn->user);
2555 Curl_safefree(conn->passwd);
2556 Curl_safefree(conn->proxyuser);
2557 Curl_safefree(conn->proxypasswd);
2558 Curl_safefree(conn->allocptr.proxyuserpwd);
2559 Curl_safefree(conn->allocptr.uagent);
2560 Curl_safefree(conn->allocptr.userpwd);
2561 Curl_safefree(conn->allocptr.accept_encoding);
2562 Curl_safefree(conn->allocptr.rangeline);
2563 Curl_safefree(conn->allocptr.ref);
2564 Curl_safefree(conn->allocptr.host);
2565 Curl_safefree(conn->allocptr.cookiehost);
2566 Curl_safefree(conn->allocptr.rtsp_transport);
2567 Curl_safefree(conn->trailer);
2568 Curl_safefree(conn->host.rawalloc); /* host name buffer */
2569 Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
2570 Curl_safefree(conn->master_buffer);
2572 Curl_llist_destroy(conn->send_pipe, NULL);
2573 Curl_llist_destroy(conn->recv_pipe, NULL);
2574 Curl_llist_destroy(conn->pend_pipe, NULL);
2575 Curl_llist_destroy(conn->done_pipe, NULL);
2577 /* possible left-overs from the async name resolvers */
2578 #if defined(CURLRES_THREADED)
2579 Curl_destroy_thread_data(&conn->async);
2580 #elif defined(CURLRES_ASYNCH)
2581 Curl_safefree(conn->async.hostname);
2582 Curl_safefree(conn->async.os_specific);
2585 Curl_free_ssl_config(&conn->ssl_config);
2587 free(conn); /* free all the connection oriented data */
2590 CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
2592 struct SessionHandle *data;
2594 return CURLE_OK; /* this is closed and fine already */
2598 DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
2602 if(conn->dns_entry != NULL) {
2603 Curl_resolv_unlock(data, conn->dns_entry);
2604 conn->dns_entry = NULL;
2607 #if defined(DEBUGBUILD) && defined(AGGRESIVE_TEST)
2608 /* scan for DNS cache entries still marked as in use */
2609 Curl_hash_apply(data->hostcache,
2610 NULL, Curl_scan_cache_used);
2613 Curl_hostcache_prune(data); /* kill old DNS cache entries */
2616 int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
2617 int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
2619 /* Authentication data is a mix of connection-related and sessionhandle-
2620 related stuff. NTLM is connection-related so when we close the shop
2623 if (has_host_ntlm) {
2624 data->state.authhost.done = FALSE;
2625 data->state.authhost.picked =
2626 data->state.authhost.want;
2629 if (has_proxy_ntlm) {
2630 data->state.authproxy.done = FALSE;
2631 data->state.authproxy.picked =
2632 data->state.authproxy.want;
2635 if (has_host_ntlm || has_proxy_ntlm) {
2636 data->state.authproblem = FALSE;
2638 Curl_ntlm_cleanup(conn);
2642 /* Cleanup possible redirect junk */
2643 if(data->req.newurl) {
2644 free(data->req.newurl);
2645 data->req.newurl = NULL;
2648 if(conn->handler->disconnect)
2649 /* This is set if protocol-specific cleanups should be made */
2650 conn->handler->disconnect(conn, dead_connection);
2652 if(-1 != conn->connectindex) {
2653 /* unlink ourselves! */
2654 infof(data, "Closing connection #%ld\n", conn->connectindex);
2655 if(data->state.connc)
2656 /* only clear the table entry if we still know in which cache we
2658 data->state.connc->connects[conn->connectindex] = NULL;
2662 if(conn->host.encalloc)
2663 idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
2664 with idn_free() since this was allocated
2666 if(conn->proxy.encalloc)
2667 idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
2668 freed with idn_free() since this was
2669 allocated by libidn */
2672 Curl_ssl_close(conn, FIRSTSOCKET);
2674 /* Indicate to all handles on the pipe that we're dead */
2675 if(Curl_isPipeliningEnabled(data)) {
2676 signalPipeClose(conn->send_pipe, TRUE);
2677 signalPipeClose(conn->recv_pipe, TRUE);
2678 signalPipeClose(conn->pend_pipe, TRUE);
2679 signalPipeClose(conn->done_pipe, FALSE);
2683 data->state.current_conn = NULL;
2689 * This function should return TRUE if the socket is to be assumed to
2690 * be dead. Most commonly this happens when the server has closed the
2691 * connection due to inactivity.
2693 static bool SocketIsDead(curl_socket_t sock)
2696 bool ret_val = TRUE;
2698 sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
2706 #ifndef CURL_DISABLE_RTSP
2708 * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
2709 * want to block the application forever while receiving a stream. Therefore,
2710 * we cannot assume that an RTSP socket is dead just because it is readable.
2712 * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
2713 * and distinguish between closed and data.
2715 static bool RTSPConnIsDead(struct connectdata *check)
2718 bool ret_val = TRUE;
2720 sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
2725 else if (sval & CURL_CSELECT_ERR) {
2726 /* socket is in an error state */
2729 else if (sval & CURL_CSELECT_IN) {
2730 /* readable with no error. could be closed or could be alive */
2731 curl_socket_t connectinfo =
2732 Curl_getconnectinfo(check->data, &check);
2733 if(connectinfo != CURL_SOCKET_BAD)
2739 #endif /* CURL_DISABLE_RTSP */
2741 static bool IsPipeliningPossible(const struct SessionHandle *handle,
2742 const struct connectdata *conn)
2744 if((conn->handler->protocol & PROT_HTTP) &&
2745 handle->multi && Curl_multi_canPipeline(handle->multi) &&
2746 (handle->set.httpreq == HTTPREQ_GET ||
2747 handle->set.httpreq == HTTPREQ_HEAD) &&
2748 handle->set.httpversion != CURL_HTTP_VERSION_1_0)
2754 bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
2756 if(handle->multi && Curl_multi_canPipeline(handle->multi))
2762 CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
2763 struct curl_llist *pipeline)
2765 if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
2766 return CURLE_OUT_OF_MEMORY;
2770 int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
2771 struct curl_llist *pipeline)
2773 struct curl_llist_element *curr;
2775 curr = pipeline->head;
2777 if(curr->ptr == handle) {
2778 Curl_llist_remove(pipeline, curr, NULL);
2779 return 1; /* we removed a handle */
2787 #if 0 /* this code is saved here as it is useful for debugging purposes */
2788 static void Curl_printPipeline(struct curl_llist *pipeline)
2790 struct curl_llist_element *curr;
2792 curr = pipeline->head;
2794 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2795 infof(data, "Handle in pipeline: %s\n", data->state.path);
2801 static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
2803 struct curl_llist_element *curr = pipeline->head;
2805 return (struct SessionHandle *) curr->ptr;
2811 /* remove the specified connection from all (possible) pipelines and related
2813 void Curl_getoff_all_pipelines(struct SessionHandle *data,
2814 struct connectdata *conn)
2816 bool recv_head = (bool)(conn->readchannel_inuse &&
2817 (gethandleathead(conn->recv_pipe) == data));
2819 bool send_head = (bool)(conn->writechannel_inuse &&
2820 (gethandleathead(conn->send_pipe) == data));
2822 if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
2823 conn->readchannel_inuse = FALSE;
2824 if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
2825 conn->writechannel_inuse = FALSE;
2826 Curl_removeHandleFromPipeline(data, conn->pend_pipe);
2827 Curl_removeHandleFromPipeline(data, conn->done_pipe);
2830 static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
2832 struct curl_llist_element *curr;
2837 curr = pipeline->head;
2839 struct curl_llist_element *next = curr->next;
2840 struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
2842 #ifdef DEBUGBUILD /* debug-only code */
2843 if(data->magic != CURLEASY_MAGIC_NUMBER) {
2845 infof(data, "signalPipeClose() found BAAD easy handle\n");
2850 data->state.pipe_broke = TRUE;
2851 Curl_multi_handlePipeBreak(data);
2852 Curl_llist_remove(pipeline, curr, NULL);
2859 * Given one filled in connection struct (named needle), this function should
2860 * detect if there already is one that has all the significant details
2861 * exactly the same and thus should be used instead.
2863 * If there is a match, this function returns TRUE - and has marked the
2864 * connection as 'in-use'. It must later be called with ConnectionDone() to
2865 * return back to 'idle' (unused) state.
2868 ConnectionExists(struct SessionHandle *data,
2869 struct connectdata *needle,
2870 struct connectdata **usethis)
2873 struct connectdata *check;
2874 bool canPipeline = IsPipeliningPossible(data, needle);
2876 for(i=0; i< data->state.connc->num; i++) {
2880 * Note that if we use a HTTP proxy, we check connections to that
2881 * proxy and not to the actual remote server.
2883 check = data->state.connc->connects[i];
2885 /* NULL pointer means not filled-in entry */
2888 pipeLen = check->send_pipe->size + check->recv_pipe->size;
2890 if(check->connectindex == -1) {
2891 check->connectindex = i; /* Set this appropriately since it might have
2892 been set to -1 when the easy was removed
2896 if(!pipeLen && !check->inuse) {
2897 /* The check for a dead socket makes sense only if there are no
2898 handles in pipeline and the connection isn't already marked in
2901 #ifndef CURL_DISABLE_RTSP
2902 if(check->protocol & PROT_RTSP)
2903 /* RTSP is a special case due to RTP interleaving */
2904 dead = RTSPConnIsDead(check);
2906 #endif /*CURL_DISABLE_RTSP*/
2907 dead = SocketIsDead(check->sock[FIRSTSOCKET]);
2911 infof(data, "Connection #%ld seems to be dead!\n", i);
2913 /* disconnect resources */
2914 Curl_disconnect(check, /* dead_connection */ TRUE);
2915 data->state.connc->connects[i]=NULL; /* nothing here */
2922 /* Make sure the pipe has only GET requests */
2923 struct SessionHandle* sh = gethandleathead(check->send_pipe);
2924 struct SessionHandle* rh = gethandleathead(check->recv_pipe);
2926 if(!IsPipeliningPossible(sh, check))
2930 if(!IsPipeliningPossible(rh, check))
2935 if(pipeLen > MAX_PIPELINE_LENGTH) {
2936 infof(data, "BAD! Connection #%ld has too big pipeline!\n",
2937 check->connectindex);
2943 /* can only happen within multi handles, and means that another easy
2944 handle is using this connection */
2948 #ifdef CURLRES_ASYNCH
2949 /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
2950 completed yet and until then we don't re-use this connection */
2951 if(!check->ip_addr_str[0]) {
2953 "Connection #%ld hasn't finished name resolve, can't reuse\n",
2954 check->connectindex);
2959 if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) || check->bits.close) {
2960 /* Don't pick a connection that hasn't connected yet or that is going
2962 infof(data, "Connection #%ld isn't open enough, can't reuse\n",
2963 check->connectindex);
2965 if(check->recv_pipe->size > 0) {
2966 infof(data, "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
2967 check->connectindex);
2974 if((needle->protocol&PROT_SSL) != (check->protocol&PROT_SSL))
2975 /* don't do mixed SSL and non-SSL connections */
2978 if(needle->protocol&PROT_SSL) {
2979 if((data->set.ssl.verifypeer != check->verifypeer) ||
2980 (data->set.ssl.verifyhost != check->verifyhost))
2984 if(needle->bits.proxy != check->bits.proxy)
2985 /* don't do mixed proxy and non-proxy connections */
2988 if(!canPipeline && check->inuse)
2989 /* this request can't be pipelined but the checked connection is already
2990 in use so we skip it */
2993 if(!needle->bits.httpproxy || needle->protocol&PROT_SSL ||
2994 (needle->bits.httpproxy && check->bits.httpproxy &&
2995 needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
2996 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
2997 (needle->port == check->port))) {
2998 /* The requested connection does not use a HTTP proxy or it uses SSL or
2999 it is a non-SSL protocol tunneled over the same http proxy name and
3002 if(Curl_raw_equal(needle->handler->scheme, check->handler->scheme) &&
3003 Curl_raw_equal(needle->host.name, check->host.name) &&
3004 (needle->remote_port == check->remote_port) ) {
3005 if(needle->protocol & PROT_SSL) {
3006 /* This is SSL, verify that we're using the same
3007 ssl options as well */
3008 if(!Curl_ssl_config_matches(&needle->ssl_config,
3009 &check->ssl_config)) {
3011 "Connection #%ld has different SSL parameters, "
3013 check->connectindex));
3016 else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
3018 "Connection #%ld has not started ssl connect, "
3020 check->connectindex));
3024 if((needle->protocol & PROT_FTP) ||
3025 ((needle->protocol & PROT_HTTP) &&
3026 (data->state.authhost.want==CURLAUTH_NTLM))) {
3027 /* This is FTP or HTTP+NTLM, verify that we're using the same name
3028 and password as well */
3029 if(!strequal(needle->user, check->user) ||
3030 !strequal(needle->passwd, check->passwd)) {
3031 /* one of them was different */
3038 else { /* The requested needle connection is using a proxy,
3039 is the checked one using the same host, port and type? */
3040 if(check->bits.proxy &&
3041 (needle->proxytype == check->proxytype) &&
3042 (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
3043 Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
3044 needle->port == check->port) {
3045 /* This is the same proxy connection, use it! */
3051 check->inuse = TRUE; /* mark this as being in use so that no other
3052 handle in a multi stack may nick it */
3055 return TRUE; /* yes, we found one to use! */
3059 return FALSE; /* no matching connecting exists */
3065 * This function frees/closes a connection in the connection cache. This
3066 * should take the previously set policy into account when deciding which
3067 * of the connections to kill.
3070 ConnectionKillOne(struct SessionHandle *data)
3073 struct connectdata *conn;
3081 for(i=0; data->state.connc && (i< data->state.connc->num); i++) {
3082 conn = data->state.connc->connects[i];
3084 if(!conn || conn->inuse)
3087 /* Set higher score for the age passed since the connection was used */
3088 score = Curl_tvdiff(now, conn->now);
3090 if(score > highscore) {
3095 if(connindex >= 0) {
3096 /* Set the connection's owner correctly */
3097 conn = data->state.connc->connects[connindex];
3100 /* the winner gets the honour of being disconnected */
3101 (void)Curl_disconnect(conn, /* dead_connection */ FALSE);
3103 /* clean the array entry */
3104 data->state.connc->connects[connindex] = NULL;
3107 return connindex; /* return the available index or -1 */
3110 /* this connection can now be marked 'idle' */
3112 ConnectionDone(struct connectdata *conn)
3114 conn->inuse = FALSE;
3118 * The given input connection struct pointer is to be stored. If the "cache"
3119 * is already full, we must clean out the most suitable using the previously
3122 * The given connection should be unique. That must've been checked prior to
3126 ConnectionStore(struct SessionHandle *data,
3127 struct connectdata *conn)
3130 for(i=0; i< data->state.connc->num; i++) {
3131 if(!data->state.connc->connects[i])
3134 if(i == data->state.connc->num) {
3135 /* there was no room available, kill one */
3136 i = ConnectionKillOne(data);
3138 infof(data, "Connection (#%ld) was killed to make room (holds %ld)\n",
3139 i, data->state.connc->num);
3141 infof(data, "This connection did not fit in the connection cache\n");
3144 conn->connectindex = i; /* Make the child know where the pointer to this
3145 particular data is stored. But note that this -1
3146 if this is not within the cache and this is
3147 probably not checked for everywhere (yet). */
3150 /* Only do this if a true index was returned, if -1 was returned there
3151 is no room in the cache for an unknown reason and we cannot store
3154 TODO: make sure we really can work with more handles than positions in
3155 the cache, or possibly we should (allow to automatically) resize the
3156 connection cache when we add more easy handles to a multi handle!
3158 data->state.connc->connects[i] = conn; /* fill in this */
3165 /* after a TCP connection to the proxy has been verified, this function does
3166 the next magic step.
3168 Note: this function's sub-functions call failf()
3171 CURLcode Curl_connected_proxy(struct connectdata *conn)
3173 CURLcode result = CURLE_OK;
3174 struct SessionHandle *data = conn->data;
3176 switch(data->set.proxytype) {
3177 #ifndef CURL_DISABLE_PROXY
3178 case CURLPROXY_SOCKS5:
3179 case CURLPROXY_SOCKS5_HOSTNAME:
3180 result = Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
3181 conn->host.name, conn->remote_port,
3184 case CURLPROXY_SOCKS4:
3185 result = Curl_SOCKS4(conn->proxyuser, conn->host.name,
3186 conn->remote_port, FIRSTSOCKET, conn, FALSE);
3188 case CURLPROXY_SOCKS4A:
3189 result = Curl_SOCKS4(conn->proxyuser, conn->host.name,
3190 conn->remote_port, FIRSTSOCKET, conn, TRUE);
3192 #endif /* CURL_DISABLE_PROXY */
3193 case CURLPROXY_HTTP:
3194 case CURLPROXY_HTTP_1_0:
3195 /* do nothing here. handled later. */
3199 } /* switch proxytype */
3204 static CURLcode ConnectPlease(struct SessionHandle *data,
3205 struct connectdata *conn,
3209 Curl_addrinfo *addr;
3210 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3211 char *hostname = conn->bits.proxy?conn->proxy.name:conn->host.name;
3213 infof(data, "About to connect() to %s%s port %ld (#%ld)\n",
3214 conn->bits.proxy?"proxy ":"",
3215 hostname, conn->port, conn->connectindex);
3220 /*************************************************************
3221 * Connect to server/proxy
3222 *************************************************************/
3223 result= Curl_connecthost(conn,
3225 &conn->sock[FIRSTSOCKET],
3228 if(CURLE_OK == result) {
3229 /* All is cool, we store the current information */
3230 conn->ip_addr = addr;
3233 result = Curl_connected_proxy(conn);
3237 *connected = FALSE; /* mark it as not connected */
3243 * verboseconnect() displays verbose information after a connect
3245 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3246 void Curl_verboseconnect(struct connectdata *conn)
3248 if(conn->data->set.verbose)
3249 infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
3250 conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
3251 conn->ip_addr_str, conn->port, conn->connectindex);
3255 int Curl_protocol_getsock(struct connectdata *conn,
3256 curl_socket_t *socks,
3259 if(conn->handler->proto_getsock)
3260 return conn->handler->proto_getsock(conn, socks, numsocks);
3261 return GETSOCK_BLANK;
3264 int Curl_doing_getsock(struct connectdata *conn,
3265 curl_socket_t *socks,
3268 if(conn && conn->handler->doing_getsock)
3269 return conn->handler->doing_getsock(conn, socks, numsocks);
3270 return GETSOCK_BLANK;
3274 * We are doing protocol-specific connecting and this is being called over and
3275 * over from the multi interface until the connection phase is done on
3279 CURLcode Curl_protocol_connecting(struct connectdata *conn,
3282 CURLcode result=CURLE_OK;
3284 if(conn && conn->handler->connecting) {
3286 result = conn->handler->connecting(conn, done);
3295 * We are DOING this is being called over and over from the multi interface
3296 * until the DOING phase is done on protocol layer.
3299 CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
3301 CURLcode result=CURLE_OK;
3303 if(conn && conn->handler->doing) {
3305 result = conn->handler->doing(conn, done);
3314 * We have discovered that the TCP connection has been successful, we can now
3315 * proceed with some action.
3318 CURLcode Curl_protocol_connect(struct connectdata *conn,
3319 bool *protocol_done)
3321 CURLcode result=CURLE_OK;
3322 struct SessionHandle *data = conn->data;
3324 *protocol_done = FALSE;
3326 if(conn->bits.tcpconnect && conn->bits.protoconnstart) {
3327 /* We already are connected, get back. This may happen when the connect
3328 worked fine in the first call, like when we connect to a local server
3329 or proxy. Note that we don't know if the protocol is actually done.
3331 Unless this protocol doesn't have any protocol-connect callback, as
3332 then we know we're done. */
3333 if(!conn->handler->connecting)
3334 *protocol_done = TRUE;
3339 if(!conn->bits.tcpconnect) {
3341 Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
3342 Curl_verboseconnect(conn);
3345 if(!conn->bits.protoconnstart) {
3346 if(conn->handler->connect_it) {
3347 /* is there a protocol-specific connect() procedure? */
3349 /* Set start time here for timeout purposes in the connect procedure, it
3350 is later set again for the progress meter purpose */
3351 conn->now = Curl_tvnow();
3353 /* Call the protocol-specific connect function */
3354 result = conn->handler->connect_it(conn, protocol_done);
3357 *protocol_done = TRUE;
3359 /* it has started, possibly even completed but that knowledge isn't stored
3362 conn->bits.protoconnstart = TRUE;
3365 return result; /* pass back status */
3369 * Helpers for IDNA convertions.
3372 static bool is_ASCII_name(const char *hostname)
3374 const unsigned char *ch = (const unsigned char*)hostname;
3384 * Check if characters in hostname is allowed in Top Level Domain.
3386 static bool tld_check_name(struct SessionHandle *data,
3387 const char *ace_hostname)
3390 char *uc_name = NULL;
3392 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3393 const char *tld_errmsg = "<no msg>";
3398 /* Convert (and downcase) ACE-name back into locale's character set */
3399 rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
3400 if(rc != IDNA_SUCCESS)
3403 rc = tld_check_lz(uc_name, &err_pos, NULL);
3404 #ifndef CURL_DISABLE_VERBOSE_STRINGS
3405 #ifdef HAVE_TLD_STRERROR
3406 if(rc != TLD_SUCCESS)
3407 tld_errmsg = tld_strerror((Tld_rc)rc);
3409 if(rc == TLD_INVALID)
3410 infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
3411 tld_errmsg, err_pos, uc_name[err_pos],
3412 uc_name[err_pos] & 255);
3413 else if(rc != TLD_SUCCESS)
3414 infof(data, "WARNING: TLD check for %s failed; %s\n",
3415 uc_name, tld_errmsg);
3416 #endif /* CURL_DISABLE_VERBOSE_STRINGS */
3419 if(rc != TLD_SUCCESS)
3427 * Perform any necessary IDN conversion of hostname
3429 static void fix_hostname(struct SessionHandle *data,
3430 struct connectdata *conn, struct hostname *host)
3435 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
3439 /* set the name we use to display the host name */
3440 host->dispname = host->name;
3443 /*************************************************************
3444 * Check name for non-ASCII and convert hostname to ACE form.
3445 *************************************************************/
3446 if(!is_ASCII_name(host->name) &&
3447 stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
3448 char *ace_hostname = NULL;
3449 int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
3450 infof (data, "Input domain encoded as `%s'\n",
3451 stringprep_locale_charset ());
3452 if(rc != IDNA_SUCCESS)
3453 infof(data, "Failed to convert %s to ACE; %s\n",
3454 host->name, Curl_idn_strerror(conn,rc));
3456 /* tld_check_name() displays a warning if the host name contains
3457 "illegal" characters for this TLD */
3458 (void)tld_check_name(data, ace_hostname);
3460 host->encalloc = ace_hostname;
3461 /* change the name pointer to point to the encoded hostname */
3462 host->name = host->encalloc;
3468 static void llist_dtor(void *user, void *element)
3476 * Allocate and initialize a new connectdata object.
3478 static struct connectdata *allocate_conn(struct SessionHandle *data)
3480 struct connectdata *conn = calloc(1, sizeof(struct connectdata));
3484 conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
3485 already from start to avoid NULL
3486 situations and checks */
3488 /* and we setup a few fields in case we end up actually using this struct */
3490 conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3491 conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
3492 conn->connectindex = -1; /* no index */
3493 conn->port = -1; /* unknown at this point */
3495 /* Default protocol-independent behavior doesn't support persistent
3496 connections, so we set this to force-close. Protocols that support
3497 this need to set this to FALSE in their "curl_do" functions. */
3498 conn->bits.close = TRUE;
3500 /* Store creation time to help future close decision making */
3501 conn->created = Curl_tvnow();
3503 conn->data = data; /* Setup the association between this connection
3504 and the SessionHandle */
3506 conn->proxytype = data->set.proxytype; /* type */
3508 #ifdef CURL_DISABLE_PROXY
3510 conn->bits.proxy = FALSE;
3511 conn->bits.httpproxy = FALSE;
3512 conn->bits.proxy_user_passwd = FALSE;
3513 conn->bits.tunnel_proxy = FALSE;
3515 #else /* CURL_DISABLE_PROXY */
3517 conn->bits.proxy = (bool)(data->set.str[STRING_PROXY] &&
3518 *data->set.str[STRING_PROXY]);
3519 conn->bits.httpproxy = (bool)(conn->bits.proxy &&
3520 (conn->proxytype == CURLPROXY_HTTP ||
3521 conn->proxytype == CURLPROXY_HTTP_1_0));
3522 conn->bits.proxy_user_passwd =
3523 (bool)(NULL != data->set.str[STRING_PROXYUSERNAME]);
3524 conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
3526 #endif /* CURL_DISABLE_PROXY */
3528 conn->bits.user_passwd = (bool)(NULL != data->set.str[STRING_USERNAME]);
3529 conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
3530 conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
3532 conn->verifypeer = data->set.ssl.verifypeer;
3533 conn->verifyhost = data->set.ssl.verifyhost;
3535 conn->ip_version = data->set.ipver;
3537 if(data->multi && Curl_multi_canPipeline(data->multi) &&
3538 !conn->master_buffer) {
3539 /* Allocate master_buffer to be used for pipelining */
3540 conn->master_buffer = calloc(BUFSIZE, sizeof (char));
3541 if(!conn->master_buffer)
3545 /* Initialize the pipeline lists */
3546 conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3547 conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3548 conn->pend_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3549 conn->done_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
3550 if(!conn->send_pipe || !conn->recv_pipe || !conn->pend_pipe ||
3554 #if defined(HAVE_KRB4) || defined(HAVE_GSSAPI)
3555 conn->data_prot = PROT_CLEAR;
3560 Curl_llist_destroy(conn->send_pipe, NULL);
3561 Curl_llist_destroy(conn->recv_pipe, NULL);
3562 Curl_llist_destroy(conn->pend_pipe, NULL);
3563 Curl_llist_destroy(conn->done_pipe, NULL);
3564 Curl_safefree(conn->master_buffer);
3565 Curl_safefree(conn);
3569 static CURLcode findprotocol(struct SessionHandle *data,
3570 struct connectdata *conn,
3571 const char *protostr)
3573 const struct Curl_handler * const *pp;
3574 const struct Curl_handler *p;
3576 /* Scan protocol handler table and match against 'protostr' to set a few
3577 variables based on the URL. Now that the handler may be changed later
3578 when the protocol specific setup function is called. */
3579 for (pp = protocols; (p = *pp) != NULL; pp++) {
3580 if(Curl_raw_equal(p->scheme, protostr)) {
3581 /* Protocol found in table. Check if allowed */
3582 if(!(data->set.allowed_protocols & p->protocol))
3586 /* it is allowed for "normal" request, now do an extra check if this is
3587 the result of a redirect */
3588 if(data->state.this_is_a_follow &&
3589 !(data->set.redir_protocols & p->protocol))
3593 /* Perform setup complement if some. */
3595 conn->protocol |= p->protocol;
3597 /* 'port' and 'remote_port' are set in setup_connection_internals() */
3603 /* The protocol was not found in the table, but we don't have to assign it
3604 to anything since it is already assigned to a dummy-struct in the
3605 create_conn() function when the connectdata struct is allocated. */
3606 failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
3609 return CURLE_UNSUPPORTED_PROTOCOL;
3613 * Parse URL and fill in the relevant members of the connection struct.
3615 static CURLcode parseurlandfillconn(struct SessionHandle *data,
3616 struct connectdata *conn,
3621 char *path = data->state.path;
3627 *prot_missing = FALSE;
3629 /*************************************************************
3632 * We need to parse the url even when using the proxy, because we will need
3633 * the hostname and port in case we are trying to SSL connect through the
3634 * proxy -- and we don't know if we will need to use SSL until we parse the
3636 ************************************************************/
3637 if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
3639 Curl_raw_equal(protobuf, "file")) {
3640 if(path[0] == '/' && path[1] == '/') {
3641 /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
3642 * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
3643 * file://localhost/<path> is similar to how other schemes treat missing
3644 * hostnames. See RFC 1808. */
3646 /* This cannot be done with strcpy() in a portable manner, since the
3647 memory areas overlap! */
3648 memmove(path, path + 2, strlen(path + 2)+1);
3651 * we deal with file://<host>/<path> differently since it supports no
3652 * hostname other than "localhost" and "127.0.0.1", which is unique among
3653 * the URL protocols specified in RFC 1738
3655 if(path[0] != '/') {
3656 /* the URL included a host name, we ignore host names in file:// URLs
3657 as the standards don't define what to do with them */
3658 char *ptr=strchr(path, '/');
3660 /* there was a slash present
3662 RFC1738 (section 3.1, page 5) says:
3664 The rest of the locator consists of data specific to the scheme,
3665 and is known as the "url-path". It supplies the details of how the
3666 specified resource can be accessed. Note that the "/" between the
3667 host (or port) and the url-path is NOT part of the url-path.
3669 As most agents use file://localhost/foo to get '/foo' although the
3670 slash preceding foo is a separator and not a slash for the path,
3671 a URL as file://localhost//foo must be valid as well, to refer to
3672 the same file with an absolute path.
3675 if(ptr[1] && ('/' == ptr[1]))
3676 /* if there was two slashes, we skip the first one as that is then
3677 used truly as a separator */
3680 /* This cannot be made with strcpy, as the memory chunks overlap! */
3681 memmove(path, ptr, strlen(ptr)+1);
3685 protop = "file"; /* protocol string */
3691 if(2 > sscanf(data->change.url,
3692 "%15[^\n:]://%[^\n/?]%[^\n]",
3694 conn->host.name, path)) {
3697 * The URL was badly formatted, let's try the browser-style _without_
3698 * protocol specified like 'http://'.
3700 rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
3703 * We couldn't even get this format.
3704 * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
3705 * assigned, but the return value is EOF!
3707 #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
3708 if (!(rc == -1 && *conn->host.name))
3711 failf(data, "<url> malformed");
3712 return CURLE_URL_MALFORMAT;
3717 * Since there was no protocol part specified, we guess what protocol it
3718 * is based on the first letters of the server name.
3721 /* Note: if you add a new protocol, please update the list in
3722 * lib/version.c too! */
3724 if(checkprefix("FTP.", conn->host.name))
3726 else if(checkprefix("DICT.", conn->host.name))
3728 else if(checkprefix("LDAP.", conn->host.name))
3730 else if(checkprefix("IMAP.", conn->host.name))
3736 *prot_missing = TRUE; /* not given in URL */
3742 /* We search for '?' in the host name (but only on the right side of a
3743 * @-letter to allow ?-letters in username and password) to handle things
3744 * like http://example.com?param= (notice the missing '/').
3746 at = strchr(conn->host.name, '@');
3748 query = strchr(at+1, '?');
3750 query = strchr(conn->host.name, '?');
3753 /* We must insert a slash before the '?'-letter in the URL. If the URL had
3754 a slash after the '?', that is where the path currently begins and the
3755 '?string' is still part of the host name.
3757 We must move the trailing part from the host name and put it first in
3758 the path. And have it all prefixed with a slash.
3761 size_t hostlen = strlen(query);
3762 size_t pathlen = strlen(path);
3764 /* move the existing path plus the zero byte forward, to make room for
3765 the host-name part */
3766 memmove(path+hostlen+1, path, pathlen+1);
3768 /* now copy the trailing host part in front of the existing path */
3769 memcpy(path+1, query, hostlen);
3771 path[0]='/'; /* prepend the missing slash */
3773 *query=0; /* now cut off the hostname at the ? */
3776 /* if there's no path set, use a single slash */
3780 /* If the URL is malformatted (missing a '/' after hostname before path) we
3781 * insert a slash here. The only letter except '/' we accept to start a path
3784 if(path[0] == '?') {
3785 /* We need this function to deal with overlapping memory areas. We know
3786 that the memory area 'path' points to is 'urllen' bytes big and that
3787 is bigger than the path. Use +1 to move the zero byte too. */
3788 memmove(&path[1], path, strlen(path)+1);
3792 if (conn->host.name[0] == '[') {
3793 /* This looks like an IPv6 address literal. See if there is an address
3795 char *percent = strstr (conn->host.name, "%25");
3798 unsigned long scope = strtoul (percent + 3, &endp, 10);
3800 /* The address scope was well formed. Knock it out of the
3802 memmove(percent, endp, strlen(endp)+1);
3803 if (!data->state.this_is_a_follow)
3804 /* Don't honour a scope given in a Location: header */
3805 conn->scope = (unsigned int)scope;
3807 infof(data, "Invalid IPv6 address format\n");
3812 /* Override any scope that was set above. */
3813 conn->scope = data->set.scope;
3815 /* Remove the fragment part of the path. Per RFC 2396, this is always the
3816 last part of the URI. We are looking for the first '#' so that we deal
3817 gracefully with non conformant URI such as http://example.com#foo#bar. */
3818 fragment = strchr(path, '#');
3823 * So if the URL was A://B/C#D,
3825 * conn->host.name is B
3826 * data->state.path is /C
3829 return findprotocol(data, conn, protop);
3833 * If we're doing a resumed transfer, we need to setup our stuff
3836 static CURLcode setup_range(struct SessionHandle *data)
3838 struct UrlState *s = &data->state;
3839 s->resume_from = data->set.set_resume_from;
3840 if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
3841 if(s->rangestringalloc)
3845 s->range = aprintf("%" FORMAT_OFF_TU "-", s->resume_from);
3847 s->range = strdup(data->set.str[STRING_SET_RANGE]);
3849 s->rangestringalloc = (bool)(s->range?TRUE:FALSE);
3852 return CURLE_OUT_OF_MEMORY;
3854 /* tell ourselves to fetch this range */
3855 s->use_range = TRUE; /* enable range download */
3858 s->use_range = FALSE; /* disable range download */
3864 /***************************************************************
3865 * Setup connection internals specific to the requested protocol.
3866 * This MUST get called after proxy magic has been figured out.
3867 ***************************************************************/
3868 static CURLcode setup_connection_internals(struct connectdata *conn)
3870 const struct Curl_handler * p;
3873 conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
3875 /* Scan protocol handler table. */
3877 /* Perform setup complement if some. */
3880 if(p->setup_connection) {
3881 result = (*p->setup_connection)(conn);
3883 if(result != CURLE_OK)
3886 p = conn->handler; /* May have changed. */
3890 /* we check for -1 here since if proxy was detected already, this
3891 was very likely already set to the proxy port */
3892 conn->port = p->defport;
3893 conn->remote_port = (unsigned short)p->defport;
3894 conn->protocol |= p->protocol;
3899 #ifndef CURL_DISABLE_PROXY
3900 /****************************************************************
3901 * Checks if the host is in the noproxy list. returns true if it matches
3902 * and therefore the proxy should NOT be used.
3903 ****************************************************************/
3904 static bool check_noproxy(const char* name, const char* no_proxy)
3906 /* no_proxy=domain1.dom,host.domain2.dom
3907 * (a comma-separated list of hosts which should
3908 * not be proxied, or an asterisk to override
3909 * all proxy variables)
3913 const char* separator = ", ";
3914 size_t no_proxy_len;
3918 if(no_proxy && no_proxy[0]) {
3919 if(Curl_raw_equal("*", no_proxy)) {
3923 /* NO_PROXY was specified and it wasn't just an asterisk */
3925 no_proxy_len = strlen(no_proxy);
3926 endptr = strchr(name, ':');
3928 namelen = endptr - name;
3930 namelen = strlen(name);
3932 for (tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
3933 while (tok_start < no_proxy_len &&
3934 strchr(separator, no_proxy[tok_start]) != NULL) {
3935 /* Look for the beginning of the token. */
3939 if(tok_start == no_proxy_len)
3940 break; /* It was all trailing separator chars, no more tokens. */
3942 for (tok_end = tok_start; tok_end < no_proxy_len &&
3943 strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end) {
3944 /* Look for the end of the token. */
3947 /* To match previous behaviour, where it was necessary to specify
3948 * ".local.com" to prevent matching "notlocal.com", we will leave
3951 if(no_proxy[tok_start] == '.')
3954 if((tok_end - tok_start) <= namelen) {
3955 /* Match the last part of the name to the domain we are checking. */
3956 const char *checkn = name + namelen - (tok_end - tok_start);
3957 if(Curl_raw_nequal(no_proxy + tok_start, checkn,
3958 tok_end - tok_start)) {
3959 if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
3960 /* We either have an exact match, or the previous character is a .
3961 * so it is within the same domain, so no proxy for this host.
3966 } /* if((tok_end - tok_start) <= namelen) */
3967 } /* for (tok_start = 0; tok_start < no_proxy_len;
3968 tok_start = tok_end + 1) */
3969 } /* NO_PROXY was specified and it wasn't just an asterisk */
3974 /****************************************************************
3975 * Detect what (if any) proxy to use. Remember that this selects a host
3976 * name and is not limited to HTTP proxies only.
3977 * The returned pointer must be freed by the caller (unless NULL)
3978 ****************************************************************/
3979 static char *detect_proxy(struct connectdata *conn)
3983 #ifndef CURL_DISABLE_HTTP
3984 /* If proxy was not specified, we check for default proxy environment
3985 * variables, to enable i.e Lynx compliance:
3987 * http_proxy=http://some.server.dom:port/
3988 * https_proxy=http://some.server.dom:port/
3989 * ftp_proxy=http://some.server.dom:port/
3990 * no_proxy=domain1.dom,host.domain2.dom
3991 * (a comma-separated list of hosts which should
3992 * not be proxied, or an asterisk to override
3993 * all proxy variables)
3994 * all_proxy=http://some.server.dom:port/
3995 * (seems to exist for the CERN www lib. Probably
3996 * the first to check for.)
3998 * For compatibility, the all-uppercase versions of these variables are
3999 * checked if the lowercase versions don't exist.
4001 char *no_proxy=NULL;
4002 char proxy_env[128];
4004 no_proxy=curl_getenv("no_proxy");
4006 no_proxy=curl_getenv("NO_PROXY");
4008 if(!check_noproxy(conn->host.name, no_proxy)) {
4009 /* It was not listed as without proxy */
4010 const char *protop = conn->handler->scheme;
4011 char *envp = proxy_env;
4014 /* Now, build <protocol>_proxy and check for such a one to use */
4016 *envp++ = (char)tolower((int)*protop++);
4019 strcpy(envp, "_proxy");
4021 /* read the protocol proxy: */
4022 prox=curl_getenv(proxy_env);
4025 * We don't try the uppercase version of HTTP_PROXY because of
4028 * When curl is used in a webserver application
4029 * environment (cgi or php), this environment variable can
4030 * be controlled by the web server user by setting the
4031 * http header 'Proxy:' to some value.
4033 * This can cause 'internal' http/ftp requests to be
4034 * arbitrarily redirected by any external attacker.
4036 if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
4037 /* There was no lowercase variable, try the uppercase version: */
4038 Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
4039 prox=curl_getenv(proxy_env);
4042 if(prox && *prox) { /* don't count "" strings */
4043 proxy = prox; /* use this */
4046 proxy = curl_getenv("all_proxy"); /* default proxy to use */
4048 proxy=curl_getenv("ALL_PROXY");
4050 } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
4055 #else /* !CURL_DISABLE_HTTP */
4058 #endif /* CURL_DISABLE_HTTP */
4064 * If this is supposed to use a proxy, we need to figure out the proxy
4065 * host name, so that we can re-use an existing connection
4066 * that may exist registered to the same proxy host.
4067 * proxy will be freed before this function returns.
4069 static CURLcode parse_proxy(struct SessionHandle *data,
4070 struct connectdata *conn, char *proxy)
4075 /* We use 'proxyptr' to point to the proxy name from now on... */
4080 /* We do the proxy host string parsing here. We want the host name and the
4081 * port name. Accept a protocol:// prefix, even though it should just be
4085 /* Skip the protocol part if present */
4086 endofprot = strstr(proxy, "://");
4088 proxyptr = endofprot+3;
4092 /* Is there a username and password given in this proxy url? */
4093 atsign = strchr(proxyptr, '@');
4095 char proxyuser[MAX_CURL_USER_LENGTH];
4096 char proxypasswd[MAX_CURL_PASSWORD_LENGTH];
4099 if(1 <= sscanf(proxyptr,
4100 "%" MAX_CURL_USER_LENGTH_TXT"[^:@]:"
4101 "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4102 proxyuser, proxypasswd)) {
4103 CURLcode res = CURLE_OK;
4105 /* found user and password, rip them out. note that we are
4106 unescaping them, as there is otherwise no way to have a
4107 username or password with reserved characters like ':' in
4109 Curl_safefree(conn->proxyuser);
4110 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4112 if(!conn->proxyuser)
4113 res = CURLE_OUT_OF_MEMORY;
4115 Curl_safefree(conn->proxypasswd);
4116 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4118 if(!conn->proxypasswd)
4119 res = CURLE_OUT_OF_MEMORY;
4122 if(CURLE_OK == res) {
4123 conn->bits.proxy_user_passwd = TRUE; /* enable it */
4124 atsign = strdup(atsign+1); /* the right side of the @-letter */
4127 free(proxy); /* free the former proxy string */
4128 proxy = proxyptr = atsign; /* now use this instead */
4131 res = CURLE_OUT_OF_MEMORY;
4135 free(proxy); /* free the allocated proxy string */
4141 /* start scanning for port number at this point */
4144 /* detect and extract RFC2732-style IPv6-addresses */
4145 if(*proxyptr == '[') {
4146 char *ptr = ++proxyptr; /* advance beyond the initial bracket */
4147 while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
4151 /* yeps, it ended nicely with a bracket as well */
4154 infof(data, "Invalid IPv6 address format\n");
4156 /* Note that if this didn't end with a bracket, we still advanced the
4157 * proxyptr first, but I can't see anything wrong with that as no host
4158 * name nor a numeric can legally start with a bracket.
4162 /* Get port number off proxy.server.com:1080 */
4163 prox_portno = strchr(portptr, ':');
4165 *prox_portno = 0x0; /* cut off number from host name */
4167 /* now set the local port number */
4168 conn->port = strtol(prox_portno, NULL, 10);
4171 /* without a port number after the host name, some people seem to use
4172 a slash so we strip everything from the first slash */
4173 atsign = strchr(proxyptr, '/');
4175 *atsign = 0x0; /* cut off path part from host name */
4177 if(data->set.proxyport)
4178 /* None given in the proxy string, then get the default one if it is
4180 conn->port = data->set.proxyport;
4183 /* now, clone the cleaned proxy host name */
4184 conn->proxy.rawalloc = strdup(proxyptr);
4185 conn->proxy.name = conn->proxy.rawalloc;
4188 if(!conn->proxy.rawalloc)
4189 return CURLE_OUT_OF_MEMORY;
4195 * Extract the user and password from the authentication string
4197 static CURLcode parse_proxy_auth(struct SessionHandle *data,
4198 struct connectdata *conn)
4200 char proxyuser[MAX_CURL_USER_LENGTH]="";
4201 char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
4203 if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
4204 strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
4205 MAX_CURL_USER_LENGTH);
4206 proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4208 if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
4209 strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
4210 MAX_CURL_PASSWORD_LENGTH);
4211 proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4214 conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
4215 if(!conn->proxyuser)
4216 return CURLE_OUT_OF_MEMORY;
4218 conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
4219 if(!conn->proxypasswd)
4220 return CURLE_OUT_OF_MEMORY;
4224 #endif /* CURL_DISABLE_PROXY */
4228 * Parse a user name and password in the URL and strip it out of the host name
4230 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
4233 * Outputs: (almost :- all currently undefined)
4234 * conn->bits.user_passwd - non-zero if non-default passwords exist
4235 * user - non-zero length if defined
4237 * conn->host.name - remove user name and password
4239 static CURLcode parse_url_userpass(struct SessionHandle *data,
4240 struct connectdata *conn,
4241 char *user, char *passwd)
4243 /* At this point, we're hoping all the other special cases have
4244 * been taken care of, so conn->host.name is at most
4245 * [user[:password]]@]hostname
4247 * We need somewhere to put the embedded details, so do that first.
4250 char *ptr=strchr(conn->host.name, '@');
4251 char *userpass = conn->host.name;
4253 user[0] =0; /* to make everything well-defined */
4256 /* We will now try to extract the
4257 * possible user+password pair in a string like:
4258 * ftp://user:password@ftp.my.site:8021/README */
4260 /* there's a user+password given here, to the left of the @ */
4262 conn->host.name = ++ptr;
4264 /* So the hostname is sane. Only bother interpreting the
4265 * results if we could care. It could still be wasted
4266 * work because it might be overtaken by the programmatically
4267 * set user/passwd, but doing that first adds more cases here :-(
4270 conn->bits.userpwd_in_url = TRUE;
4271 if(data->set.use_netrc != CURL_NETRC_REQUIRED) {
4272 /* We could use the one in the URL */
4274 conn->bits.user_passwd = TRUE; /* enable user+password */
4276 if(*userpass != ':') {
4277 /* the name is given, get user+password */
4278 sscanf(userpass, "%" MAX_CURL_USER_LENGTH_TXT "[^:@]:"
4279 "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
4283 /* no name given, get the password only */
4284 sscanf(userpass, ":%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]", passwd);
4287 char *newname=curl_easy_unescape(data, user, 0, NULL);
4289 return CURLE_OUT_OF_MEMORY;
4290 if(strlen(newname) < MAX_CURL_USER_LENGTH)
4291 strcpy(user, newname);
4293 /* if the new name is longer than accepted, then just use
4294 the unconverted name, it'll be wrong but what the heck */
4298 /* we have a password found in the URL, decode it! */
4299 char *newpasswd=curl_easy_unescape(data, passwd, 0, NULL);
4301 return CURLE_OUT_OF_MEMORY;
4302 if(strlen(newpasswd) < MAX_CURL_PASSWORD_LENGTH)
4303 strcpy(passwd, newpasswd);
4312 /*************************************************************
4313 * Figure out the remote port number and fix it in the URL
4315 * No matter if we use a proxy or not, we have to figure out the remote
4316 * port number of various reasons.
4318 * To be able to detect port number flawlessly, we must not confuse them
4319 * IPv6-specified addresses in the [0::1] style. (RFC2732)
4321 * The conn->host.name is currently [user:passwd@]host[:port] where host
4322 * could be a hostname, IPv4 address or IPv6 address.
4324 * The port number embedded in the URL is replaced, if necessary.
4325 *************************************************************/
4326 static CURLcode parse_remote_port(struct SessionHandle *data,
4327 struct connectdata *conn)
4332 /* Note that at this point, the IPv6 address cannot contain any scope
4333 suffix as that has already been removed in the parseurlandfillconn()
4335 if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
4337 (']' == endbracket)) {
4338 /* this is a RFC2732-style specified IP-address */
4339 conn->bits.ipv6_ip = TRUE;
4341 conn->host.name++; /* skip over the starting bracket */
4342 portptr = strchr(conn->host.name, ']');
4344 *portptr++ = '\0'; /* zero terminate, killing the bracket */
4346 portptr = NULL; /* no port number available */
4350 portptr = strrchr(conn->host.name, ':');
4352 if(data->set.use_port && data->state.allow_port) {
4353 /* if set, we use this and ignore the port possibly given in the URL */
4354 conn->remote_port = (unsigned short)data->set.use_port;
4356 *portptr = '\0'; /* cut off the name there anyway - if there was a port
4357 number - since the port number is to be ignored! */
4358 if(conn->bits.httpproxy) {
4359 /* we need to create new URL with the new port number */
4363 if(conn->bits.type_set)
4364 snprintf(type, sizeof(type), ";type=%c",
4365 data->set.prefer_ascii?'A':
4366 (data->set.ftp_list_only?'D':'I'));
4369 * This synthesized URL isn't always right--suffixes like ;type=A are
4370 * stripped off. It would be better to work directly from the original
4371 * URL and simply replace the port part of it.
4373 url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->handler->scheme,
4374 conn->bits.ipv6_ip?"[":"", conn->host.name,
4375 conn->bits.ipv6_ip?"]":"", conn->remote_port,
4376 data->state.slash_removed?"/":"", data->state.path,
4379 return CURLE_OUT_OF_MEMORY;
4381 if(data->change.url_alloc)
4382 free(data->change.url);
4384 data->change.url = url;
4385 data->change.url_alloc = TRUE;
4389 /* no CURLOPT_PORT given, extract the one from the URL */
4394 port=strtoul(portptr+1, &rest, 10); /* Port number must be decimal */
4396 if(rest != (portptr+1) && *rest == '\0') {
4397 /* The colon really did have only digits after it,
4398 * so it is either a port number or a mistake */
4400 if(port > 0xffff) { /* Single unix standard says port numbers are
4402 failf(data, "Port number too large: %lu", port);
4403 return CURLE_URL_MALFORMAT;
4406 *portptr = '\0'; /* cut off the name there */
4407 conn->remote_port = curlx_ultous(port);
4410 /* Browser behavior adaptation. If there's a colon with no digits after,
4411 just cut off the name there which makes us ignore the colon and just
4412 use the default port. Firefox and Chrome both do that. */
4419 * Override a user name and password from the URL with that in the
4420 * CURLOPT_USERPWD option or a .netrc file, if applicable.
4422 static void override_userpass(struct SessionHandle *data,
4423 struct connectdata *conn,
4424 char *user, char *passwd)
4426 if(data->set.str[STRING_USERNAME] != NULL) {
4427 strncpy(user, data->set.str[STRING_USERNAME], MAX_CURL_USER_LENGTH);
4428 user[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
4430 if(data->set.str[STRING_PASSWORD] != NULL) {
4431 strncpy(passwd, data->set.str[STRING_PASSWORD], MAX_CURL_PASSWORD_LENGTH);
4432 passwd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
4435 conn->bits.netrc = FALSE;
4436 if(data->set.use_netrc != CURL_NETRC_IGNORED) {
4437 if(Curl_parsenetrc(conn->host.name,
4439 data->set.str[STRING_NETRC_FILE])) {
4440 infof(data, "Couldn't find host %s in the "
4441 DOT_CHAR "netrc file; using defaults\n",
4445 /* set bits.netrc TRUE to remember that we got the name from a .netrc
4446 file, so that it is safe to use even if we followed a Location: to a
4447 different host or similar. */
4448 conn->bits.netrc = TRUE;
4450 conn->bits.user_passwd = TRUE; /* enable user+password */
4456 * Set password so it's available in the connection.
4458 static CURLcode set_userpass(struct connectdata *conn,
4459 const char *user, const char *passwd)
4461 /* If our protocol needs a password and we have none, use the defaults */
4462 if( (conn->protocol & (PROT_FTP|PROT_IMAP)) &&
4463 !conn->bits.user_passwd) {
4465 conn->user = strdup(CURL_DEFAULT_USER);
4467 conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
4469 conn->passwd = NULL;
4470 /* This is the default password, so DON'T set conn->bits.user_passwd */
4473 /* store user + password, zero-length if not set */
4474 conn->user = strdup(user);
4476 conn->passwd = strdup(passwd);
4478 conn->passwd = NULL;
4480 if(!conn->user || !conn->passwd)
4481 return CURLE_OUT_OF_MEMORY;
4486 /*************************************************************
4487 * Resolve the address of the server or proxy
4488 *************************************************************/
4489 static CURLcode resolve_server(struct SessionHandle *data,
4490 struct connectdata *conn,
4493 CURLcode result=CURLE_OK;
4494 long timeout_ms = Curl_timeleft(conn, NULL, TRUE);
4496 /*************************************************************
4497 * Resolve the name of the server or proxy
4498 *************************************************************/
4499 if(conn->bits.reuse) {
4500 /* We're reusing the connection - no need to resolve anything */
4503 if(conn->bits.proxy)
4504 fix_hostname(data, conn, &conn->host);
4507 /* this is a fresh connect */
4509 struct Curl_dns_entry *hostaddr;
4511 /* set a pointer to the hostname we display */
4512 fix_hostname(data, conn, &conn->host);
4514 if(!conn->proxy.name || !*conn->proxy.name) {
4515 /* If not connecting via a proxy, extract the port from the URL, if it is
4516 * there, thus overriding any defaults that might have been set above. */
4517 conn->port = conn->remote_port; /* it is the same port */
4519 /* Resolve target host right on */
4520 rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
4521 &hostaddr, timeout_ms);
4522 if(rc == CURLRESOLV_PENDING)
4525 else if (rc == CURLRESOLV_TIMEDOUT)
4526 result = CURLE_OPERATION_TIMEDOUT;
4528 else if(!hostaddr) {
4529 failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
4530 result = CURLE_COULDNT_RESOLVE_HOST;
4531 /* don't return yet, we need to clean up the timeout first */
4535 /* This is a proxy that hasn't been resolved yet. */
4537 /* IDN-fix the proxy name */
4538 fix_hostname(data, conn, &conn->proxy);
4541 rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
4542 &hostaddr, timeout_ms);
4544 if(rc == CURLRESOLV_PENDING)
4547 else if (rc == CURLRESOLV_TIMEDOUT)
4548 result = CURLE_OPERATION_TIMEDOUT;
4550 else if(!hostaddr) {
4551 failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
4552 result = CURLE_COULDNT_RESOLVE_PROXY;
4553 /* don't return yet, we need to clean up the timeout first */
4556 DEBUGASSERT(conn->dns_entry == NULL);
4557 conn->dns_entry = hostaddr;
4564 * Cleanup the connection just allocated before we can move along and use the
4565 * previously existing one. All relevant data is copied over and old_conn is
4566 * ready for freeing once this function returns.
4568 static void reuse_conn(struct connectdata *old_conn,
4569 struct connectdata *conn)
4571 if(old_conn->proxy.rawalloc)
4572 free(old_conn->proxy.rawalloc);
4574 /* free the SSL config struct from this connection struct as this was
4575 allocated in vain and is targeted for destruction */
4576 Curl_free_ssl_config(&old_conn->ssl_config);
4578 conn->data = old_conn->data;
4580 /* get the user+password information from the old_conn struct since it may
4581 * be new for this request even when we re-use an existing connection */
4582 conn->bits.user_passwd = old_conn->bits.user_passwd;
4583 if(conn->bits.user_passwd) {
4584 /* use the new user name and password though */
4585 Curl_safefree(conn->user);
4586 Curl_safefree(conn->passwd);
4587 conn->user = old_conn->user;
4588 conn->passwd = old_conn->passwd;
4589 old_conn->user = NULL;
4590 old_conn->passwd = NULL;
4593 conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
4594 if(conn->bits.proxy_user_passwd) {
4595 /* use the new proxy user name and proxy password though */
4596 Curl_safefree(conn->proxyuser);
4597 Curl_safefree(conn->proxypasswd);
4598 conn->proxyuser = old_conn->proxyuser;
4599 conn->proxypasswd = old_conn->proxypasswd;
4600 old_conn->proxyuser = NULL;
4601 old_conn->proxypasswd = NULL;
4604 /* host can change, when doing keepalive with a proxy ! */
4605 if(conn->bits.proxy) {
4606 free(conn->host.rawalloc);
4607 conn->host=old_conn->host;
4610 free(old_conn->host.rawalloc); /* free the newly allocated name buffer */
4612 /* persist connection info in session handle */
4613 Curl_persistconninfo(conn);
4616 conn->bits.reuse = TRUE; /* yes, we're re-using here */
4618 Curl_safefree(old_conn->user);
4619 Curl_safefree(old_conn->passwd);
4620 Curl_safefree(old_conn->proxyuser);
4621 Curl_safefree(old_conn->proxypasswd);
4622 Curl_llist_destroy(old_conn->send_pipe, NULL);
4623 Curl_llist_destroy(old_conn->recv_pipe, NULL);
4624 Curl_llist_destroy(old_conn->pend_pipe, NULL);
4625 Curl_llist_destroy(old_conn->done_pipe, NULL);
4626 Curl_safefree(old_conn->master_buffer);
4630 * create_conn() sets up a new connectdata struct, or re-uses an already
4631 * existing one, and resolves host name.
4633 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
4634 * response will be coming asynchronously. If *async is FALSE, the name is
4637 * @param data The sessionhandle pointer
4638 * @param in_connect is set to the next connection data pointer
4639 * @param async is set TRUE when an async DNS resolution is pending
4642 * *NOTE* this function assigns the conn->data pointer!
4645 static CURLcode create_conn(struct SessionHandle *data,
4646 struct connectdata **in_connect,
4649 CURLcode result=CURLE_OK;
4650 struct connectdata *conn;
4651 struct connectdata *conn_temp = NULL;
4653 char user[MAX_CURL_USER_LENGTH];
4654 char passwd[MAX_CURL_PASSWORD_LENGTH];
4657 bool prot_missing = FALSE;
4661 /*************************************************************
4663 *************************************************************/
4665 if(!data->change.url)
4666 return CURLE_URL_MALFORMAT;
4668 /* First, split up the current URL in parts so that we can use the
4669 parts for checking against the already present connections. In order
4670 to not have to modify everything at once, we allocate a temporary
4671 connection data struct and fill in for comparison purposes. */
4672 conn = allocate_conn(data);
4675 return CURLE_OUT_OF_MEMORY;
4677 /* We must set the return variable as soon as possible, so that our
4678 parent can cleanup any possible allocs we may have done before
4682 /* This initing continues below, see the comment "Continue connectdata
4683 * initialization here" */
4685 /***********************************************************
4686 * We need to allocate memory to store the path in. We get the size of the
4687 * full URL to be sure, and we need to make it at least 256 bytes since
4688 * other parts of the code will rely on this fact
4689 ***********************************************************/
4690 #define LEAST_PATH_ALLOC 256
4691 urllen=strlen(data->change.url);
4692 if(urllen < LEAST_PATH_ALLOC)
4693 urllen=LEAST_PATH_ALLOC;
4696 * We malloc() the buffers below urllen+2 to make room for to possibilities:
4697 * 1 - an extra terminating zero
4698 * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
4701 Curl_safefree(data->state.pathbuffer);
4702 data->state.pathbuffer = malloc(urllen+2);
4703 if(NULL == data->state.pathbuffer)
4704 return CURLE_OUT_OF_MEMORY; /* really bad error */
4705 data->state.path = data->state.pathbuffer;
4707 conn->host.rawalloc = malloc(urllen+2);
4708 if(NULL == conn->host.rawalloc)
4709 return CURLE_OUT_OF_MEMORY;
4711 conn->host.name = conn->host.rawalloc;
4712 conn->host.name[0] = 0;
4714 result = parseurlandfillconn(data, conn, &prot_missing);
4715 if(result != CURLE_OK) {
4719 /*************************************************************
4720 * No protocol part in URL was used, add it!
4721 *************************************************************/
4723 /* We're guessing prefixes here and if we're told to use a proxy or if
4724 we're gonna follow a Location: later or... then we need the protocol
4725 part added so that we have a valid URL. */
4728 reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
4731 Curl_safefree(proxy);
4732 return CURLE_OUT_OF_MEMORY;
4735 data->change.url = reurl;
4736 data->change.url_alloc = TRUE; /* free this later */
4739 /*************************************************************
4740 * Parse a user name and password in the URL and strip it out
4742 *************************************************************/
4743 result = parse_url_userpass(data, conn, user, passwd);
4744 if(result != CURLE_OK)
4747 #ifndef CURL_DISABLE_PROXY
4748 /*************************************************************
4749 * Extract the user and password from the authentication string
4750 *************************************************************/
4751 if(conn->bits.proxy_user_passwd) {
4752 result = parse_proxy_auth(data, conn);
4753 if(result != CURLE_OK)
4757 /*************************************************************
4758 * Detect what (if any) proxy to use
4759 *************************************************************/
4760 if(data->set.str[STRING_PROXY]) {
4761 proxy = strdup(data->set.str[STRING_PROXY]);
4762 /* if global proxy is set, this is it */
4764 failf(data, "memory shortage");
4765 return CURLE_OUT_OF_MEMORY;
4769 if(data->set.str[STRING_NOPROXY] &&
4770 check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
4772 free(proxy); /* proxy is in exception list */
4777 proxy = detect_proxy(conn);
4779 if(proxy && !*proxy) {
4780 free(proxy); /* Don't bother with an empty proxy string */
4783 /* proxy must be freed later unless NULL */
4785 long bits = conn->protocol & (PROT_HTTPS|PROT_SSL);
4787 if((conn->proxytype == CURLPROXY_HTTP) ||
4788 (conn->proxytype == CURLPROXY_HTTP_1_0)) {
4789 /* force this connection's protocol to become HTTP */
4790 conn->protocol = PROT_HTTP | bits;
4791 conn->bits.httpproxy = TRUE;
4793 conn->bits.proxy = TRUE;
4796 /* we aren't using the proxy after all... */
4797 conn->bits.proxy = FALSE;
4798 conn->bits.httpproxy = FALSE;
4799 conn->bits.proxy_user_passwd = FALSE;
4800 conn->bits.tunnel_proxy = FALSE;
4803 /***********************************************************************
4804 * If this is supposed to use a proxy, we need to figure out the proxy
4805 * host name, so that we can re-use an existing connection
4806 * that may exist registered to the same proxy host.
4807 ***********************************************************************/
4809 result = parse_proxy(data, conn, proxy);
4810 /* parse_proxy has freed the proxy string, so don't try to use it again */
4812 if(result != CURLE_OK)
4815 #endif /* CURL_DISABLE_PROXY */
4817 /*************************************************************
4818 * Setup internals depending on protocol. Needs to be done after
4819 * we figured out what/if proxy to use.
4820 *************************************************************/
4821 result = setup_connection_internals(conn);
4822 if(result != CURLE_OK) {
4823 Curl_safefree(proxy);
4827 conn->recv[FIRSTSOCKET] = Curl_recv_plain;
4828 conn->send[FIRSTSOCKET] = Curl_send_plain;
4829 conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
4830 conn->send[SECONDARYSOCKET] = Curl_send_plain;
4832 /***********************************************************************
4833 * file: is a special case in that it doesn't need a network connection
4834 ***********************************************************************/
4835 #ifndef CURL_DISABLE_FILE
4836 if(conn->protocol & PROT_FILE) {
4838 /* this is supposed to be the connect function so we better at least check
4839 that the file is present here! */
4840 DEBUGASSERT(conn->handler->connect_it);
4841 result = conn->handler->connect_it(conn, &done);
4843 /* Setup a "faked" transfer that'll do nothing */
4844 if(CURLE_OK == result) {
4846 conn->bits.tcpconnect = TRUE; /* we are "connected */
4848 ConnectionStore(data, conn);
4851 * Setup whatever necessary for a resumed transfer
4853 result = setup_range(data);
4855 DEBUGASSERT(conn->handler->done);
4856 /* we ignore the return code for the protocol-specific DONE */
4857 (void)conn->handler->done(conn, result, FALSE);
4861 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
4862 -1, NULL); /* no upload */
4869 /*************************************************************
4870 * If the protocol is using SSL and HTTP proxy is used, we set
4871 * the tunnel_proxy bit.
4872 *************************************************************/
4873 if((conn->protocol&PROT_SSL) && conn->bits.httpproxy)
4874 conn->bits.tunnel_proxy = TRUE;
4876 /*************************************************************
4877 * Figure out the remote port number and fix it in the URL
4878 *************************************************************/
4879 result = parse_remote_port(data, conn);
4880 if(result != CURLE_OK)
4883 /*************************************************************
4884 * Check for an overridden user name and password, then set it
4886 *************************************************************/
4887 override_userpass(data, conn, user, passwd);
4888 result = set_userpass(conn, user, passwd);
4889 if(result != CURLE_OK)
4892 /* Get a cloned copy of the SSL config situation stored in the
4893 connection struct. But to get this going nicely, we must first make
4894 sure that the strings in the master copy are pointing to the correct
4895 strings in the session handle strings array!
4897 Keep in mind that the pointers in the master copy are pointing to strings
4898 that will be freed as part of the SessionHandle struct, but all cloned
4899 copies will be separately allocated.
4901 data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
4902 data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
4903 data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
4904 data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
4905 data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
4906 data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
4907 data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
4909 if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
4910 return CURLE_OUT_OF_MEMORY;
4912 /*************************************************************
4913 * Check the current list of connections to see if we can
4914 * re-use an already existing one or if we have to create a
4916 *************************************************************/
4918 /* reuse_fresh is TRUE if we are told to use a new connection by force, but
4919 we only acknowledge this option if this is not a re-used connection
4920 already (which happens due to follow-location or during a HTTP
4921 authentication phase). */
4922 if(data->set.reuse_fresh && !data->state.this_is_a_follow)
4925 reuse = ConnectionExists(data, conn, &conn_temp);
4929 * We already have a connection for this, we got the former connection
4930 * in the conn_temp variable and thus we need to cleanup the one we
4931 * just allocated before we can move along and use the previously
4934 reuse_conn(conn, conn_temp);
4935 free(conn); /* we don't need this anymore */
4938 infof(data, "Re-using existing connection! (#%ld) with host %s\n",
4940 conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
4944 * This is a brand new connection, so let's store it in the connection
4947 ConnectionStore(data, conn);
4951 * Setup whatever necessary for a resumed transfer
4953 result = setup_range(data);
4957 /* Continue connectdata initialization here. */
4960 * Inherit the proper values from the urldata struct AFTER we have arranged
4961 * the persistent connection stuff
4963 conn->fread_func = data->set.fread_func;
4964 conn->fread_in = data->set.in;
4965 conn->seek_func = data->set.seek_func;
4966 conn->seek_client = data->set.seek_client;
4968 /*************************************************************
4969 * Resolve the address of the server or proxy
4970 *************************************************************/
4971 result = resolve_server(data, conn, async);
4976 /* setup_conn() is called after the name resolve initiated in
4977 * create_conn() is all done.
4979 * setup_conn() also handles reused connections
4981 * conn->data MUST already have been setup fine (in create_conn)
4984 static CURLcode setup_conn(struct connectdata *conn,
4985 bool *protocol_done)
4987 CURLcode result=CURLE_OK;
4988 struct SessionHandle *data = conn->data;
4990 Curl_pgrsTime(data, TIMER_NAMELOOKUP);
4992 if(conn->protocol & PROT_FILE) {
4993 /* There's nothing in this function to setup if we're only doing
4994 a file:// transfer */
4995 *protocol_done = TRUE;
4998 *protocol_done = FALSE; /* default to not done */
5000 /* set proxy_connect_closed to false unconditionally already here since it
5001 is used strictly to provide extra information to a parent function in the
5002 case of proxy CONNECT failures and we must make sure we don't have it
5003 lingering set from a previous invoke */
5004 conn->bits.proxy_connect_closed = FALSE;
5007 * Set user-agent. Used for HTTP, but since we can attempt to tunnel
5008 * basically anything through a http proxy we can't limit this based on
5011 if(data->set.str[STRING_USERAGENT]) {
5012 Curl_safefree(conn->allocptr.uagent);
5013 conn->allocptr.uagent =
5014 aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
5015 if(!conn->allocptr.uagent)
5016 return CURLE_OUT_OF_MEMORY;
5019 data->req.headerbytecount = 0;
5021 #ifdef CURL_DO_LINEEND_CONV
5022 data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
5023 #endif /* CURL_DO_LINEEND_CONV */
5026 /* loop for CURL_SERVER_CLOSED_CONNECTION */
5028 if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
5029 /* Try to connect only if not already connected */
5030 bool connected = FALSE;
5032 result = ConnectPlease(data, conn, &connected);
5035 result = Curl_protocol_connect(conn, protocol_done);
5036 if(CURLE_OK == result)
5037 conn->bits.tcpconnect = TRUE;
5040 conn->bits.tcpconnect = FALSE;
5042 /* if the connection was closed by the server while exchanging
5043 authentication informations, retry with the new set
5044 authentication information */
5045 if(conn->bits.proxy_connect_closed) {
5046 /* reset the error buffer */
5047 if(data->set.errorbuffer)
5048 data->set.errorbuffer[0] = '\0';
5049 data->state.errorbuf = FALSE;
5053 if(CURLE_OK != result)
5057 Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
5058 Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
5059 conn->bits.tcpconnect = TRUE;
5060 *protocol_done = TRUE;
5061 Curl_verboseconnect(conn);
5062 Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
5064 /* Stop the loop now */
5068 conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
5069 set this here perhaps a second time */
5073 * This check is quite a hack. We're calling _fsetmode to fix the problem
5074 * with fwrite converting newline characters (you get mangled text files,
5075 * and corrupted binary files when you download to stdout and redirect it to
5079 if((data->set.out)->_handle == NULL) {
5080 _fsetmode(stdout, "b");
5087 CURLcode Curl_connect(struct SessionHandle *data,
5088 struct connectdata **in_connect,
5090 bool *protocol_done)
5094 *asyncp = FALSE; /* assume synchronous resolves by default */
5096 /* call the stuff that needs to be called */
5097 code = create_conn(data, in_connect, asyncp);
5099 if(CURLE_OK == code) {
5101 if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
5103 *protocol_done = TRUE;
5104 else if (!*asyncp) {
5105 /* DNS resolution is done: that's either because this is a reused
5106 connection, in which case DNS was unnecessary, or because DNS
5107 really did finish already (synch resolver/fast async resolve) */
5108 code = setup_conn(*in_connect, protocol_done);
5112 if(code && *in_connect) {
5113 /* We're not allowed to return failure with memory left allocated
5114 in the connectdata struct, free those here */
5115 Curl_disconnect(*in_connect, FALSE); /* close the connection */
5116 *in_connect = NULL; /* return a NULL */
5122 /* Call this function after Curl_connect() has returned async=TRUE and
5123 then a successful name resolve has been received.
5125 Note: this function disconnects and frees the conn data in case of
5127 CURLcode Curl_async_resolved(struct connectdata *conn,
5128 bool *protocol_done)
5130 #ifdef CURLRES_ASYNCH
5133 if(conn->async.dns) {
5134 conn->dns_entry = conn->async.dns;
5135 conn->async.dns = NULL;
5138 code = setup_conn(conn, protocol_done);
5141 /* We're not allowed to return failure with memory left allocated
5142 in the connectdata struct, free those here */
5143 Curl_disconnect(conn, FALSE); /* close the connection */
5148 (void)protocol_done;
5154 CURLcode Curl_done(struct connectdata **connp,
5155 CURLcode status, /* an error if this is called after an
5156 error was detected */
5160 struct connectdata *conn;
5161 struct SessionHandle *data;
5163 DEBUGASSERT(*connp);
5169 /* Stop if Curl_done() has already been called */
5172 Curl_getoff_all_pipelines(data, conn);
5174 if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
5175 !data->set.reuse_forbid &&
5177 /* Stop if pipeline is not empty and we do not have to close
5181 conn->bits.done = TRUE; /* called just now! */
5183 /* Cleanup possible redirect junk */
5184 if(data->req.newurl) {
5185 free(data->req.newurl);
5186 data->req.newurl = NULL;
5188 if(data->req.location) {
5189 free(data->req.location);
5190 data->req.location = NULL;
5193 if(conn->dns_entry) {
5194 Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
5195 conn->dns_entry = NULL;
5198 /* this calls the protocol-specific function pointer previously set */
5199 if(conn->handler->done)
5200 result = conn->handler->done(conn, status, premature);
5204 Curl_pgrsDone(conn); /* done with the operation */
5206 /* if the transfer was completed in a paused state there can be buffered
5207 data left to write and then kill */
5208 if(data->state.tempwrite) {
5209 free(data->state.tempwrite);
5210 data->state.tempwrite = NULL;
5213 /* for ares-using, make sure all possible outstanding requests are properly
5214 cancelled before we proceed */
5215 ares_cancel(data->state.areschannel);
5217 /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
5218 forced us to close this no matter what we think.
5220 if conn->bits.close is TRUE, it means that the connection should be
5221 closed in spite of all our efforts to be nice, due to protocol
5222 restrictions in our or the server's end
5224 if premature is TRUE, it means this connection was said to be DONE before
5225 the entire request operation is complete and thus we can't know in what
5226 state it is for re-using, so we're forced to close it. In a perfect world
5227 we can add code that keep track of if we really must close it here or not,
5228 but currently we have no such detail knowledge.
5230 connectindex == -1 here means that the connection has no spot in the
5231 connection cache and thus we must disconnect it here.
5233 if(data->set.reuse_forbid || conn->bits.close || premature ||
5234 (-1 == conn->connectindex)) {
5235 CURLcode res2 = Curl_disconnect(conn, FALSE); /* close the connection */
5237 /* If we had an error already, make sure we return that one. But
5238 if we got a new error, return that. */
5243 ConnectionDone(conn); /* the connection is no longer in use */
5245 /* remember the most recently used connection */
5246 data->state.lastconnect = conn->connectindex;
5248 infof(data, "Connection #%ld to host %s left intact\n",
5250 conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
5253 *connp = NULL; /* to make the caller of this function better detect that
5254 this was either closed or handed over to the connection
5255 cache here, and therefore cannot be used from this point on
5262 * do_init() inits the readwrite session. This is inited each time (in the DO
5263 * function before the protocol-specific DO functions are invoked) for a
5264 * transfer, sometimes multiple times on the same SessionHandle. Make sure
5265 * nothing in here depends on stuff that are setup dynamically for the
5269 static CURLcode do_init(struct connectdata *conn)
5271 struct SessionHandle *data = conn->data;
5272 struct SingleRequest *k = &data->req;
5274 conn->bits.done = FALSE; /* Curl_done() is not called yet */
5275 conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
5276 data->state.expect100header = FALSE;
5278 if(data->set.opt_no_body)
5279 /* in HTTP lingo, no body means using the HEAD request... */
5280 data->set.httpreq = HTTPREQ_HEAD;
5281 else if(HTTPREQ_HEAD == data->set.httpreq)
5282 /* ... but if unset there really is no perfect method that is the
5283 "opposite" of HEAD but in reality most people probably think GET
5284 then. The important thing is that we can't let it remain HEAD if the
5285 opt_no_body is set FALSE since then we'll behave wrong when getting
5287 data->set.httpreq = HTTPREQ_GET;
5289 /* NB: the content encoding software depends on this initialization */
5290 Curl_easy_initHandleData(data);
5292 k->start = Curl_tvnow(); /* start time */
5293 k->now = k->start; /* current time is now */
5294 k->header = TRUE; /* assume header */
5298 k->buf = data->state.buffer;
5299 k->uploadbuf = data->state.uploadbuffer;
5300 k->hbufp = data->state.headerbuff;
5301 k->ignorebody=FALSE;
5303 Curl_pgrsTime(data, TIMER_PRETRANSFER);
5304 Curl_speedinit(data);
5306 Curl_pgrsSetUploadCounter(data, 0);
5307 Curl_pgrsSetDownloadCounter(data, 0);
5313 * do_complete is called when the DO actions are complete.
5315 * We init chunking and trailer bits to their default values here immediately
5316 * before receiving any header data for the current request in the pipeline.
5318 static void do_complete(struct connectdata *conn)
5320 conn->data->req.chunk=FALSE;
5321 conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
5322 conn->sockfd:conn->writesockfd)+1;
5325 CURLcode Curl_do(struct connectdata **connp, bool *done)
5327 CURLcode result=CURLE_OK;
5328 struct connectdata *conn = *connp;
5329 struct SessionHandle *data = conn->data;
5331 /* setup and init stuff before DO starts, in preparing for the transfer */
5334 if(conn->handler->do_it) {
5335 /* generic protocol-specific function pointer set in curl_connect() */
5336 result = conn->handler->do_it(conn, done);
5338 /* This was formerly done in transfer.c, but we better do it here */
5339 if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
5341 * If the connection is using an easy handle, call reconnect
5342 * to re-establish the connection. Otherwise, let the multi logic
5343 * figure out how to re-establish the connection.
5346 result = Curl_reconnect_request(connp);
5348 if(result == CURLE_OK) {
5349 /* ... finally back to actually retry the DO phase */
5350 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;