1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2012, 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 ***************************************************************************/
24 #include <curl/curl.h>
36 #elif defined(HAVE_SYS_UTIME_H)
37 # include <sys/utime.h>
44 #ifdef HAVE_NETINET_TCP_H
45 # include <netinet/tcp.h>
50 #define ENABLE_CURLX_PRINTF
51 /* use our own printf() functions */
54 #include "tool_binmode.h"
55 #include "tool_cfgable.h"
56 #include "tool_cb_dbg.h"
57 #include "tool_cb_hdr.h"
58 #include "tool_cb_prg.h"
59 #include "tool_cb_rea.h"
60 #include "tool_cb_see.h"
61 #include "tool_cb_wrt.h"
62 #include "tool_dirhie.h"
63 #include "tool_doswin.h"
64 #include "tool_easysrc.h"
65 #include "tool_getparam.h"
66 #include "tool_helpers.h"
67 #include "tool_homedir.h"
68 #include "tool_libinfo.h"
69 #include "tool_main.h"
70 #include "tool_msgs.h"
71 #include "tool_operate.h"
72 #include "tool_operhlp.h"
73 #include "tool_parsecfg.h"
74 #include "tool_setopt.h"
75 #include "tool_sleep.h"
76 #include "tool_urlglob.h"
77 #include "tool_util.h"
78 #include "tool_writeenv.h"
79 #include "tool_writeout.h"
80 #include "tool_xattr.h"
82 #include "memdebug.h" /* keep this as LAST include */
84 #define CURLseparator "--_curl_--"
87 /* since O_BINARY as used in bitmasks, setting it to zero makes it usable in
88 source code but yet it doesn't ruin anything */
92 #define CURL_CA_CERT_ERRORMSG1 \
93 "More details here: http://curl.haxx.se/docs/sslcerts.html\n\n" \
94 "curl performs SSL certificate verification by default, " \
95 "using a \"bundle\"\n" \
96 " of Certificate Authority (CA) public keys (CA certs). If the default\n" \
97 " bundle file isn't adequate, you can specify an alternate file\n" \
98 " using the --cacert option.\n"
100 #define CURL_CA_CERT_ERRORMSG2 \
101 "If this HTTPS server uses a certificate signed by a CA represented in\n" \
102 " the bundle, the certificate verification probably failed due to a\n" \
103 " problem with the certificate (it might be expired, or the name might\n" \
104 " not match the domain name in the URL).\n" \
105 "If you'd like to turn off curl's verification of the certificate, use\n" \
106 " the -k (or --insecure) option.\n"
108 static int is_fatal_error(int code)
111 /* TODO: Should CURLE_SSL_CACERT be included as critical error ? */
112 case CURLE_FAILED_INIT:
113 case CURLE_OUT_OF_MEMORY:
114 case CURLE_UNKNOWN_OPTION:
115 case CURLE_FUNCTION_NOT_FOUND:
116 case CURLE_BAD_FUNCTION_ARGUMENT:
122 /* no error or not critical */
126 int operate(struct Configurable *config, int argc, argv_item_t argv[])
128 char errorbuffer[CURL_ERROR_SIZE];
129 struct ProgressData progressbar;
130 struct getout *urlnode;
132 struct OutStruct heads;
135 char *httpgetfields = NULL;
141 errorbuffer[0] = '\0';
142 /* default headers output stream is stdout */
143 memset(&heads, 0, sizeof(struct OutStruct));
144 heads.stream = stdout;
145 heads.config = config;
147 memory_tracking_init();
150 ** Initialize curl library - do not call any libcurl functions before
151 ** this point. Note that the memory_tracking_init() magic above is an
152 ** exception, but then that's not part of the official public API.
154 if(main_init() != CURLE_OK) {
155 helpf(config->errors, "error initializing curl library\n");
156 return CURLE_FAILED_INIT;
159 /* Get libcurl info right away */
160 if(get_libcurl_info() != CURLE_OK) {
161 helpf(config->errors, "error retrieving curl library information\n");
163 return CURLE_FAILED_INIT;
166 /* Get a curl handle to use for all forthcoming curl transfers */
167 curl = curl_easy_init();
169 helpf(config->errors, "error initializing curl easy handle\n");
171 return CURLE_FAILED_INIT;
176 ** Beyond this point no return'ing from this function allowed.
177 ** Jump to label 'quit_curl' in order to abandon this function
178 ** from outside of nested loops further down below.
181 /* setup proper locale from environment */
182 #ifdef HAVE_SETLOCALE
183 setlocale(LC_ALL, "");
187 config->postfieldsize = -1;
188 config->showerror = -1; /* will show errors */
189 config->use_httpget = FALSE;
190 config->create_dirs = FALSE;
191 config->maxredirs = DEFAULT_MAXREDIRS;
192 config->proto = CURLPROTO_ALL; /* FIXME: better to read from library */
193 config->proto_present = FALSE;
194 config->proto_redir =
195 CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
196 config->proto_redir_present = FALSE;
199 (!curlx_strnequal("--", argv[1], 2) && (argv[1][0] == '-')) &&
200 strchr(argv[1], 'q')) {
202 * The first flag, that is not a verbose name, but a shortname
203 * and it includes the 'q' flag!
208 parseconfig(NULL, config); /* ignore possible failure */
211 if((argc < 2) && !config->url_list) {
212 helpf(config->errors, NULL);
213 res = CURLE_FAILED_INIT;
218 for(i = 1, stillflags = TRUE; i < argc; i++) {
220 ('-' == argv[i][0])) {
223 char *origopt = argv[i];
225 char *flag = argv[i];
227 if(curlx_strequal("--", argv[i]))
228 /* this indicates the end of the flags and thus enables the
229 following (URL) argument to start with -. */
232 nextarg = (i < (argc-1)) ? argv[i+1] : NULL;
234 res = getparameter(flag, nextarg, &passarg, config);
236 int retval = CURLE_OK;
237 if(res != PARAM_HELP_REQUESTED) {
238 const char *reason = param2text(res);
239 helpf(config->errors, "option %s: %s\n", origopt, reason);
240 retval = CURLE_FAILED_INIT;
246 if(passarg) /* we're supposed to skip this */
252 /* just add the URL please */
253 res = getparameter((char *)"--url", argv[i], &used, config);
259 if((!config->url_list || !config->url_list->url) && !config->list_engines) {
260 helpf(config->errors, "no URL specified!\n");
261 res = CURLE_FAILED_INIT;
265 if(!config->useragent)
266 config->useragent = my_useragent();
267 if(!config->useragent) {
268 helpf(config->errors, "out of memory\n");
269 res = CURLE_OUT_OF_MEMORY;
273 /* On WIN32 we can't set the path to curl-ca-bundle.crt
274 * at compile time. So we look here for the file in two ways:
275 * 1: look at the environment variable CURL_CA_BUNDLE for a path
276 * 2: if #1 isn't found, use the windows API function SearchPath()
277 * to find it along the app's path (includes app's dir and CWD)
279 * We support the environment variable thing for non-Windows platforms
280 * too. Just for the sake of it.
282 if(!config->cacert &&
284 !config->insecure_ok) {
286 env = curlx_getenv("CURL_CA_BUNDLE");
288 config->cacert = strdup(env);
289 if(!config->cacert) {
291 helpf(config->errors, "out of memory\n");
292 res = CURLE_OUT_OF_MEMORY;
297 env = curlx_getenv("SSL_CERT_DIR");
299 config->capath = strdup(env);
300 if(!config->capath) {
302 helpf(config->errors, "out of memory\n");
303 res = CURLE_OUT_OF_MEMORY;
308 env = curlx_getenv("SSL_CERT_FILE");
310 config->cacert = strdup(env);
311 if(!config->cacert) {
313 helpf(config->errors, "out of memory\n");
314 res = CURLE_OUT_OF_MEMORY;
325 res = FindWin32CACert(config, "curl-ca-bundle.crt");
332 if(config->postfields) {
333 if(config->use_httpget) {
334 /* Use the postfields data for a http get */
335 httpgetfields = strdup(config->postfields);
336 Curl_safefree(config->postfields);
338 helpf(config->errors, "out of memory\n");
339 res = CURLE_OUT_OF_MEMORY;
342 if(SetHTTPrequest(config,
343 (config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
350 if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq)) {
357 #ifndef CURL_DISABLE_LIBCURL_OPTION
358 res = easysrc_init();
360 helpf(config->errors, "out of memory\n");
365 if(config->list_engines) {
366 struct curl_slist *engines = NULL;
367 curl_easy_getinfo(curl, CURLINFO_SSL_ENGINES, &engines);
368 list_engines(engines);
369 curl_slist_free_all(engines);
374 /* Single header file for all URLs */
375 if(config->headerfile) {
376 /* open file for output: */
377 if(!curlx_strequal(config->headerfile, "-")) {
378 FILE *newfile = fopen(config->headerfile, "wb");
380 warnf(config, "Failed to open %s\n", config->headerfile);
381 res = CURLE_WRITE_ERROR;
385 heads.filename = config->headerfile;
386 heads.s_isreg = TRUE;
387 heads.fopened = TRUE;
388 heads.stream = newfile;
394 ** Nested loops start here.
397 /* loop through the list of given URLs */
399 for(urlnode = config->url_list; urlnode; urlnode = urlnode->next) {
401 int up; /* upload file counter within a single upload glob */
402 char *infiles; /* might be a glob pattern */
411 /* urlnode->url is the full URL (it might be NULL) */
414 /* This node has no URL. Free node data without destroying the
415 node itself nor modifying next pointer and continue to next */
416 Curl_safefree(urlnode->outfile);
417 Curl_safefree(urlnode->infile);
419 continue; /* next URL please */
422 /* save outfile pattern before expansion */
423 if(urlnode->outfile) {
424 outfiles = strdup(urlnode->outfile);
426 helpf(config->errors, "out of memory\n");
427 res = CURLE_OUT_OF_MEMORY;
432 infiles = urlnode->infile;
434 if(!config->globoff && infiles) {
435 /* Unless explicitly shut off */
436 res = glob_url(&inglob, infiles, &infilenum,
437 config->showerror?config->errors:NULL);
439 Curl_safefree(outfiles);
444 /* Here's the loop for uploading multiple files within the same
445 single globbed string. If no upload, we enter the loop once anyway. */
446 for(up = 0 ; up < infilenum; up++) {
448 char *uploadfile; /* a single file, never a glob */
462 res = glob_next_url(&uploadfile, inglob);
463 if(res == CURLE_OUT_OF_MEMORY)
464 helpf(config->errors, "out of memory\n");
467 uploadfile = strdup(infiles);
469 helpf(config->errors, "out of memory\n");
470 res = CURLE_OUT_OF_MEMORY;
479 if(!config->globoff) {
480 /* Unless explicitly shut off, we expand '{...}' and '[...]'
481 expressions and return total number of URLs in pattern set */
482 res = glob_url(&urls, urlnode->url, &urlnum,
483 config->showerror?config->errors:NULL);
485 Curl_safefree(uploadfile);
490 urlnum = 1; /* without globbing, this is a single URL */
492 /* if multiple files extracted to stdout, insert separators! */
493 separator= ((!outfiles || curlx_strequal(outfiles, "-")) && urlnum > 1);
495 /* Here's looping around each globbed URL */
496 for(i = 0 ; i < urlnum; i++) {
501 struct OutStruct outs;
502 struct InStruct input;
503 struct timeval retrystart;
504 curl_off_t uploadfilesize;
505 long retry_numretries;
506 long retry_sleep_default;
513 uploadfilesize = -1; /* -1 means unknown */
515 /* default output stream is stdout */
516 memset(&outs, 0, sizeof(struct OutStruct));
517 outs.stream = stdout;
518 outs.config = config;
521 res = glob_next_url(&this_url, urls);
526 this_url = strdup(urlnode->url);
528 res = CURLE_OUT_OF_MEMORY;
538 outfile = strdup(outfiles);
540 res = CURLE_OUT_OF_MEMORY;
545 if((urlnode->flags&GETOUT_USEREMOTE) ||
546 (outfile && !curlx_strequal("-", outfile)) ) {
549 * We have specified a file name to store the result in, or we have
550 * decided we want to use the remote file name.
554 /* extract the file name from the URL */
555 res = get_url_file_name(&outfile, this_url);
558 if((!outfile || !*outfile) && !config->content_disposition) {
559 helpf(config->errors, "Remote file name has no length!\n");
560 res = CURLE_WRITE_ERROR;
563 #if defined(MSDOS) || defined(WIN32)
564 /* For DOS and WIN32, we do some major replacing of
565 bad characters in the file name before using it */
566 outfile = sanitize_dos_name(outfile);
568 res = CURLE_OUT_OF_MEMORY;
571 #endif /* MSDOS || WIN32 */
574 /* fill '#1' ... '#9' terms from URL pattern */
575 char *storefile = outfile;
576 res = glob_match_url(&outfile, storefile, urls);
577 Curl_safefree(storefile);
580 warnf(config, "bad output glob!\n");
585 /* Create the directory hierarchy, if not pre-existent to a multiple
588 if(config->create_dirs) {
589 res = create_dir_hierarchy(outfile, config->errors);
590 /* create_dir_hierarchy shows error upon CURLE_WRITE_ERROR */
591 if(res == CURLE_WRITE_ERROR)
598 if((urlnode->flags & GETOUT_USEREMOTE)
599 && config->content_disposition) {
600 /* Our header callback MIGHT set the filename */
601 DEBUGASSERT(!outs.filename);
604 if(config->resume_from_current) {
605 /* We're told to continue from where we are now. Get the size
606 of the file as it is now and open it for append instead */
607 struct_stat fileinfo;
608 /* VMS -- Danger, the filesize is only valid for stream files */
609 if(0 == stat(outfile, &fileinfo))
610 /* set offset to current file size: */
611 config->resume_from = fileinfo.st_size;
613 /* let offset be 0 */
614 config->resume_from = 0;
617 if(config->resume_from) {
618 /* open file for output: */
619 FILE *file = fopen(outfile, config->resume_from?"ab":"wb");
621 helpf(config->errors, "Can't open '%s'!\n", outfile);
622 res = CURLE_WRITE_ERROR;
627 outs.init = config->resume_from;
630 outs.stream = NULL; /* open when needed */
632 outs.filename = outfile;
636 if(uploadfile && !stdin_upload(uploadfile)) {
638 * We have specified a file to upload and it isn't "-".
640 struct_stat fileinfo;
642 this_url = add_file_name_to_url(curl, this_url, uploadfile);
644 res = CURLE_OUT_OF_MEMORY;
649 * Reading binary from files can be a problem... Only FIXED, VAR
650 * etc WITHOUT implied CC will work Others need a \n appended to a
653 * - Stat gives a size but this is UNRELIABLE in VMS As a f.e. a
654 * fixed file with implied CC needs to have a byte added for every
655 * record processed, this can by derived from Filesize & recordsize
656 * for VARiable record files the records need to be counted! for
657 * every record add 1 for linefeed and subtract 2 for the record
658 * header for VARIABLE header files only the bare record data needs
659 * to be considered with one appended if implied CC
662 infd = open(uploadfile, O_RDONLY | O_BINARY);
663 if((infd == -1) || fstat(infd, &fileinfo)) {
664 helpf(config->errors, "Can't open '%s'!\n", uploadfile);
669 res = CURLE_READ_ERROR;
674 /* we ignore file size for char/block devices, sockets, etc. */
675 if(S_ISREG(fileinfo.st_mode))
676 uploadfilesize = fileinfo.st_size;
679 else if(uploadfile && stdin_upload(uploadfile)) {
680 /* count to see if there are more than one auth bit set
681 in the authtype field */
684 while(bitcheck < 32) {
685 if(config->authtype & (1 << bitcheck++)) {
688 /* more than one, we're done! */
695 * If the user has also selected --anyauth or --proxy-anyauth
696 * we should warn him/her.
698 if(config->proxyanyauth || (authbits>1)) {
700 "Using --anyauth or --proxy-anyauth with upload from stdin"
701 " involves a big risk of it not working. Use a temporary"
702 " file or a fixed auth type instead!\n");
705 DEBUGASSERT(infdopen == FALSE);
706 DEBUGASSERT(infd == STDIN_FILENO);
709 if(curlx_strequal(uploadfile, ".")) {
710 if(curlx_nonblock((curl_socket_t)infd, TRUE) < 0)
712 "fcntl failed on fd=%d: %s\n", infd, strerror(errno));
716 if(uploadfile && config->resume_from_current)
717 config->resume_from = -1; /* -1 will then force get-it-yourself */
719 if(output_expected(this_url, uploadfile)
720 && outs.stream && isatty(fileno(outs.stream)))
721 /* we send the output to a tty, therefore we switch off the progress
723 config->noprogress = config->isatty = TRUE;
725 if(urlnum > 1 && !(config->mute)) {
726 fprintf(config->errors, "\n[%d/%d]: %s --> %s\n",
727 i+1, urlnum, this_url, outfile ? outfile : "<stdout>");
729 printf("%s%s\n", CURLseparator, this_url);
733 /* Find out whether the url contains a file name */
734 const char *pc = strstr(this_url, "://");
741 pc = strrchr(pc, '/'); /* check for a slash */
744 /* there is a slash present in the URL */
747 /* Ouch, there's already a question mark in the URL string, we
748 then append the data with an ampersand separator instead! */
752 * Then append ? followed by the get fields to the url.
754 urlbuffer = malloc(strlen(this_url) + strlen(httpgetfields) + 3);
756 res = CURLE_OUT_OF_MEMORY;
760 sprintf(urlbuffer, "%s%c%s", this_url, sep, httpgetfields);
762 /* Append / before the ? to create a well-formed url
763 if the url contains a hostname only
765 sprintf(urlbuffer, "%s/?%s", this_url, httpgetfields);
767 Curl_safefree(this_url); /* free previous URL */
768 this_url = urlbuffer; /* use our new URL instead! */
772 config->errors = stderr;
774 if((!outfile || !strcmp(outfile, "-")) && !config->use_ascii) {
775 /* We get the output to stdout and we have not got the ASCII/text
776 flag, then set stdout to be binary */
780 if(config->tcp_nodelay)
781 my_setopt(curl, CURLOPT_TCP_NODELAY, 1);
784 my_setopt(curl, CURLOPT_WRITEDATA, &outs);
785 /* what call to write */
786 my_setopt(curl, CURLOPT_WRITEFUNCTION, tool_write_cb);
790 input.config = config;
791 /* Note that if CURLOPT_READFUNCTION is fread (the default), then
792 * lib/telnet.c will Curl_poll() on the input file descriptor
793 * rather then calling the READFUNCTION at regular intervals.
794 * The circumstances in which it is preferable to enable this
795 * behaviour, by omitting to set the READFUNCTION & READDATA options,
796 * have not been determined.
798 my_setopt(curl, CURLOPT_READDATA, &input);
799 /* what call to read */
800 my_setopt(curl, CURLOPT_READFUNCTION, tool_read_cb);
802 /* in 7.18.0, the CURLOPT_SEEKFUNCTION/DATA pair is taking over what
803 CURLOPT_IOCTLFUNCTION/DATA pair previously provided for seeking */
804 my_setopt(curl, CURLOPT_SEEKDATA, &input);
805 my_setopt(curl, CURLOPT_SEEKFUNCTION, tool_seek_cb);
807 if(config->recvpersecond)
808 /* tell libcurl to use a smaller sized buffer as it allows us to
809 make better sleeps! 7.9.9 stuff! */
810 my_setopt(curl, CURLOPT_BUFFERSIZE, config->recvpersecond);
812 /* size of uploaded file: */
813 if(uploadfilesize != -1)
814 my_setopt(curl, CURLOPT_INFILESIZE_LARGE, uploadfilesize);
815 my_setopt_str(curl, CURLOPT_URL, this_url); /* what to fetch */
816 my_setopt(curl, CURLOPT_NOPROGRESS, config->noprogress);
817 if(config->no_body) {
818 my_setopt(curl, CURLOPT_NOBODY, 1);
819 my_setopt(curl, CURLOPT_HEADER, 1);
822 my_setopt(curl, CURLOPT_HEADER, config->include_headers);
824 #if !defined(CURL_DISABLE_PROXY)
826 /* TODO: Make this a run-time check instead of compile-time one. */
828 my_setopt_str(curl, CURLOPT_PROXY, config->proxy);
829 my_setopt_str(curl, CURLOPT_PROXYUSERPWD, config->proxyuserpwd);
831 /* new in libcurl 7.3 */
832 my_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, config->proxytunnel);
834 /* new in libcurl 7.5 */
836 my_setopt_enum(curl, CURLOPT_PROXYTYPE, config->proxyver);
838 /* new in libcurl 7.10 */
839 if(config->socksproxy) {
840 my_setopt_str(curl, CURLOPT_PROXY, config->socksproxy);
841 my_setopt_enum(curl, CURLOPT_PROXYTYPE, config->socksver);
844 /* new in libcurl 7.10.6 */
845 if(config->proxyanyauth)
846 my_setopt_flags(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
847 else if(config->proxynegotiate)
848 my_setopt_flags(curl, CURLOPT_PROXYAUTH, CURLAUTH_GSSNEGOTIATE);
849 else if(config->proxyntlm)
850 my_setopt_flags(curl, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
851 else if(config->proxydigest)
852 my_setopt_flags(curl, CURLOPT_PROXYAUTH, CURLAUTH_DIGEST);
853 else if(config->proxybasic)
854 my_setopt_flags(curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
856 /* new in libcurl 7.19.4 */
857 my_setopt(curl, CURLOPT_NOPROXY, config->noproxy);
861 my_setopt(curl, CURLOPT_FAILONERROR, config->failonerror);
862 my_setopt(curl, CURLOPT_UPLOAD, uploadfile?TRUE:FALSE);
863 my_setopt(curl, CURLOPT_DIRLISTONLY, config->dirlistonly);
864 my_setopt(curl, CURLOPT_APPEND, config->ftp_append);
866 if(config->netrc_opt)
867 my_setopt(curl, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
868 else if(config->netrc || config->netrc_file)
869 my_setopt(curl, CURLOPT_NETRC, CURL_NETRC_REQUIRED);
871 my_setopt(curl, CURLOPT_NETRC, CURL_NETRC_IGNORED);
873 if(config->netrc_file)
874 my_setopt(curl, CURLOPT_NETRC_FILE, config->netrc_file);
876 my_setopt(curl, CURLOPT_TRANSFERTEXT, config->use_ascii);
877 my_setopt_str(curl, CURLOPT_USERPWD, config->userpwd);
878 my_setopt_str(curl, CURLOPT_RANGE, config->range);
879 my_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
880 my_setopt(curl, CURLOPT_TIMEOUT, config->timeout);
882 if(built_in_protos & CURLPROTO_HTTP) {
884 my_setopt(curl, CURLOPT_FOLLOWLOCATION,
885 config->followlocation);
886 my_setopt(curl, CURLOPT_UNRESTRICTED_AUTH,
887 config->unrestricted_auth);
889 switch(config->httpreq) {
890 case HTTPREQ_SIMPLEPOST:
891 my_setopt_str(curl, CURLOPT_POSTFIELDS,
893 my_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE,
894 config->postfieldsize);
897 my_setopt_httppost(curl, CURLOPT_HTTPPOST, config->httppost);
903 my_setopt_str(curl, CURLOPT_REFERER, config->referer);
904 my_setopt(curl, CURLOPT_AUTOREFERER, config->autoreferer);
905 my_setopt_str(curl, CURLOPT_USERAGENT, config->useragent);
906 my_setopt_slist(curl, CURLOPT_HTTPHEADER, config->headers);
908 /* new in libcurl 7.5 */
909 my_setopt(curl, CURLOPT_MAXREDIRS, config->maxredirs);
911 /* new in libcurl 7.9.1 */
912 if(config->httpversion)
913 my_setopt_enum(curl, CURLOPT_HTTP_VERSION, config->httpversion);
915 /* new in libcurl 7.10.6 (default is Basic) */
917 my_setopt_flags(curl, CURLOPT_HTTPAUTH, config->authtype);
919 /* curl 7.19.1 (the 301 version existed in 7.18.2) */
920 my_setopt(curl, CURLOPT_POSTREDIR, config->post301 |
921 (config->post302 ? CURL_REDIR_POST_302 : FALSE));
923 /* new in libcurl 7.21.6 */
925 my_setopt_str(curl, CURLOPT_ACCEPT_ENCODING, "");
927 /* new in libcurl 7.21.6 */
928 if(config->tr_encoding)
929 my_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1);
931 } /* (built_in_protos & CURLPROTO_HTTP) */
933 my_setopt_str(curl, CURLOPT_FTPPORT, config->ftpport);
934 my_setopt(curl, CURLOPT_LOW_SPEED_LIMIT,
935 config->low_speed_limit);
936 my_setopt(curl, CURLOPT_LOW_SPEED_TIME, config->low_speed_time);
937 my_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE,
938 config->sendpersecond);
939 my_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE,
940 config->recvpersecond);
941 my_setopt(curl, CURLOPT_RESUME_FROM_LARGE,
942 config->use_resume?config->resume_from:0);
944 my_setopt(curl, CURLOPT_SSLCERT, config->cert);
945 my_setopt_str(curl, CURLOPT_SSLCERTTYPE, config->cert_type);
946 my_setopt(curl, CURLOPT_SSLKEY, config->key);
947 my_setopt_str(curl, CURLOPT_SSLKEYTYPE, config->key_type);
948 my_setopt_str(curl, CURLOPT_KEYPASSWD, config->key_passwd);
950 if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
952 /* SSH and SSL private key uses same command-line option */
953 /* new in libcurl 7.16.1 */
954 my_setopt_str(curl, CURLOPT_SSH_PRIVATE_KEYFILE, config->key);
955 /* new in libcurl 7.16.1 */
956 my_setopt_str(curl, CURLOPT_SSH_PUBLIC_KEYFILE, config->pubkey);
958 /* new in libcurl 7.17.1: SSH host key md5 checking allows us
959 to fail if we are not talking to who we think we should */
960 my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
965 my_setopt_str(curl, CURLOPT_CAINFO, config->cacert);
967 my_setopt_str(curl, CURLOPT_CAPATH, config->capath);
969 my_setopt_str(curl, CURLOPT_CRLFILE, config->crlfile);
971 if(curlinfo->features & CURL_VERSION_SSL) {
972 if(config->insecure_ok) {
973 my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
974 my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);
977 my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
978 /* libcurl default is strict verifyhost -> 2L */
979 /* my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); */
983 if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
984 if(!config->insecure_ok) {
987 res = CURLE_OUT_OF_MEMORY;
990 file = aprintf("%s/%sssh/known_hosts", home, DOT_CHAR);
992 /* new in curl 7.19.6 */
993 res = res_setopt_str(curl, CURLOPT_SSH_KNOWNHOSTS, file);
995 if(res == CURLE_UNKNOWN_OPTION)
996 /* libssh2 version older than 1.1.1 */
1006 if(config->no_body || config->remote_time) {
1007 /* no body or use remote time */
1008 my_setopt(curl, CURLOPT_FILETIME, TRUE);
1011 my_setopt(curl, CURLOPT_CRLF, config->crlf);
1012 my_setopt_slist(curl, CURLOPT_QUOTE, config->quote);
1013 my_setopt_slist(curl, CURLOPT_POSTQUOTE, config->postquote);
1014 my_setopt_slist(curl, CURLOPT_PREQUOTE, config->prequote);
1016 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
1018 /* TODO: Make this a run-time check instead of compile-time one. */
1021 my_setopt_str(curl, CURLOPT_COOKIE, config->cookie);
1023 if(config->cookiefile)
1024 my_setopt_str(curl, CURLOPT_COOKIEFILE, config->cookiefile);
1026 /* new in libcurl 7.9 */
1027 if(config->cookiejar)
1028 my_setopt_str(curl, CURLOPT_COOKIEJAR, config->cookiejar);
1030 /* new in libcurl 7.9.7 */
1031 my_setopt(curl, CURLOPT_COOKIESESSION, config->cookiesession);
1035 my_setopt_enum(curl, CURLOPT_SSLVERSION, config->ssl_version);
1036 my_setopt_enum(curl, CURLOPT_TIMECONDITION, config->timecond);
1037 my_setopt(curl, CURLOPT_TIMEVALUE, config->condtime);
1038 my_setopt_str(curl, CURLOPT_CUSTOMREQUEST, config->customrequest);
1039 my_setopt(curl, CURLOPT_STDERR, config->errors);
1041 /* three new ones in libcurl 7.3: */
1042 my_setopt_str(curl, CURLOPT_INTERFACE, config->iface);
1043 my_setopt_str(curl, CURLOPT_KRBLEVEL, config->krblevel);
1045 progressbarinit(&progressbar, config);
1046 if((config->progressmode == CURL_PROGRESS_BAR) &&
1047 !config->noprogress && !config->mute) {
1048 /* we want the alternative style, then we have to implement it
1050 my_setopt(curl, CURLOPT_PROGRESSFUNCTION, tool_progress_cb);
1051 my_setopt(curl, CURLOPT_PROGRESSDATA, &progressbar);
1054 /* new in libcurl 7.6.2: */
1055 my_setopt_slist(curl, CURLOPT_TELNETOPTIONS, config->telnet_options);
1057 /* new in libcurl 7.7: */
1058 my_setopt_str(curl, CURLOPT_RANDOM_FILE, config->random_file);
1059 my_setopt(curl, CURLOPT_EGDSOCKET, config->egd_file);
1060 my_setopt(curl, CURLOPT_CONNECTTIMEOUT, config->connecttimeout);
1062 if(config->cipher_list)
1063 my_setopt_str(curl, CURLOPT_SSL_CIPHER_LIST, config->cipher_list);
1065 /* new in libcurl 7.9.2: */
1066 if(config->disable_epsv)
1068 my_setopt(curl, CURLOPT_FTP_USE_EPSV, FALSE);
1070 /* new in libcurl 7.10.5 */
1071 if(config->disable_eprt)
1073 my_setopt(curl, CURLOPT_FTP_USE_EPRT, FALSE);
1075 if(config->tracetype != TRACE_NONE) {
1076 my_setopt(curl, CURLOPT_DEBUGFUNCTION, tool_debug_cb);
1077 my_setopt(curl, CURLOPT_DEBUGDATA, config);
1078 my_setopt(curl, CURLOPT_VERBOSE, TRUE);
1081 /* new in curl 7.9.3 */
1082 if(config->engine) {
1083 res = res_setopt_str(curl, CURLOPT_SSLENGINE, config->engine);
1086 my_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1);
1089 /* new in curl 7.10.7, extended in 7.19.4 but this only sets 0 or 1 */
1090 my_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS,
1091 config->ftp_create_dirs);
1093 /* new in curl 7.10.8 */
1094 if(config->max_filesize)
1095 my_setopt(curl, CURLOPT_MAXFILESIZE_LARGE,
1096 config->max_filesize);
1098 if(4 == config->ip_version)
1099 my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1100 else if(6 == config->ip_version)
1101 my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
1103 my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
1105 /* new in curl 7.15.5 */
1106 if(config->ftp_ssl_reqd)
1107 my_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1109 /* new in curl 7.11.0 */
1110 else if(config->ftp_ssl)
1111 my_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1113 /* new in curl 7.16.0 */
1114 else if(config->ftp_ssl_control)
1115 my_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_CONTROL);
1117 /* new in curl 7.16.1 */
1118 if(config->ftp_ssl_ccc)
1119 my_setopt_enum(curl, CURLOPT_FTP_SSL_CCC, config->ftp_ssl_ccc_mode);
1121 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1123 /* TODO: Make this a run-time check instead of compile-time one. */
1125 /* new in curl 7.19.4 */
1126 if(config->socks5_gssapi_service)
1127 my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_SERVICE,
1128 config->socks5_gssapi_service);
1130 /* new in curl 7.19.4 */
1131 if(config->socks5_gssapi_nec)
1132 my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_NEC,
1133 config->socks5_gssapi_nec);
1137 my_setopt_str(curl, CURLOPT_FTP_ACCOUNT, config->ftp_account);
1139 my_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, config->ignorecl);
1142 my_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, config->ftp_skip_ip);
1145 my_setopt(curl, CURLOPT_FTP_FILEMETHOD, config->ftp_filemethod);
1148 if(config->localport) {
1149 my_setopt(curl, CURLOPT_LOCALPORT, config->localport);
1150 my_setopt_str(curl, CURLOPT_LOCALPORTRANGE,
1151 config->localportrange);
1155 my_setopt_str(curl, CURLOPT_FTP_ALTERNATIVE_TO_USER,
1156 config->ftp_alternative_to_user);
1159 if(config->disable_sessionid)
1160 my_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE,
1161 !config->disable_sessionid);
1165 my_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, FALSE);
1166 my_setopt(curl, CURLOPT_HTTP_TRANSFER_DECODING, FALSE);
1170 if(!config->nokeepalive) {
1171 my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
1172 if(config->alivetime != 0) {
1173 #if !defined(TCP_KEEPIDLE) || !defined(TCP_KEEPINTVL)
1174 warnf(config, "Keep-alive functionality somewhat crippled due to "
1175 "missing support in your operating system!\n");
1177 my_setopt(curl, CURLOPT_TCP_KEEPIDLE, config->alivetime);
1178 my_setopt(curl, CURLOPT_TCP_KEEPINTVL, config->alivetime);
1182 my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 0L);
1185 if(config->tftp_blksize)
1186 my_setopt(curl, CURLOPT_TFTP_BLKSIZE, config->tftp_blksize);
1188 if(config->mail_from)
1189 my_setopt_str(curl, CURLOPT_MAIL_FROM, config->mail_from);
1191 if(config->mail_rcpt)
1192 my_setopt_slist(curl, CURLOPT_MAIL_RCPT, config->mail_rcpt);
1195 if(config->ftp_pret)
1196 my_setopt(curl, CURLOPT_FTP_USE_PRET, TRUE);
1198 if(config->proto_present)
1199 my_setopt_flags(curl, CURLOPT_PROTOCOLS, config->proto);
1200 if(config->proto_redir_present)
1201 my_setopt_flags(curl, CURLOPT_REDIR_PROTOCOLS, config->proto_redir);
1203 if((urlnode->flags & GETOUT_USEREMOTE)
1204 && config->content_disposition) {
1205 my_setopt(curl, CURLOPT_HEADERFUNCTION, tool_header_cb);
1206 my_setopt(curl, CURLOPT_HEADERDATA, &outs);
1209 /* if HEADERFUNCTION was set to something in the previous loop, it
1210 is important that we set it (back) to NULL now */
1211 my_setopt(curl, CURLOPT_HEADERFUNCTION, NULL);
1212 my_setopt(curl, CURLOPT_HEADERDATA, config->headerfile?&heads:NULL);
1217 my_setopt_slist(curl, CURLOPT_RESOLVE, config->resolve);
1220 if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) {
1221 if(config->tls_username)
1222 my_setopt_str(curl, CURLOPT_TLSAUTH_USERNAME,
1223 config->tls_username);
1224 if(config->tls_password)
1225 my_setopt_str(curl, CURLOPT_TLSAUTH_PASSWORD,
1226 config->tls_password);
1227 if(config->tls_authtype)
1228 my_setopt_str(curl, CURLOPT_TLSAUTH_TYPE,
1229 config->tls_authtype);
1233 if(config->gssapi_delegation)
1234 my_setopt_str(curl, CURLOPT_GSSAPI_DELEGATION,
1235 config->gssapi_delegation);
1238 if(config->ssl_allow_beast)
1239 my_setopt(curl, CURLOPT_SSL_OPTIONS, (long)CURLSSLOPT_ALLOW_BEAST);
1241 if(config->mail_auth)
1242 my_setopt_str(curl, CURLOPT_MAIL_AUTH, config->mail_auth);
1244 /* initialize retry vars for loop below */
1245 retry_sleep_default = (config->retry_delay) ?
1246 config->retry_delay*1000L : RETRY_SLEEP_DEFAULT; /* ms */
1248 retry_numretries = config->req_retry;
1249 retry_sleep = retry_sleep_default; /* ms */
1250 retrystart = tvnow();
1252 #ifndef CURL_DISABLE_LIBCURL_OPTION
1253 res = easysrc_perform();
1260 res = curl_easy_perform(curl);
1262 if(config->content_disposition && outs.stream && !config->mute &&
1264 printf("curl: Saved to filename '%s'\n", outs.filename);
1266 /* if retry-max-time is non-zero, make sure we haven't exceeded the
1268 if(retry_numretries &&
1269 (!config->retry_maxtime ||
1270 (tvdiff(tvnow(), retrystart) <
1271 config->retry_maxtime*1000L)) ) {
1277 RETRY_LAST /* not used */
1280 if((CURLE_OPERATION_TIMEDOUT == res) ||
1281 (CURLE_COULDNT_RESOLVE_HOST == res) ||
1282 (CURLE_COULDNT_RESOLVE_PROXY == res) ||
1283 (CURLE_FTP_ACCEPT_TIMEOUT == res))
1284 /* retry timeout always */
1285 retry = RETRY_TIMEOUT;
1286 else if((CURLE_OK == res) ||
1287 (config->failonerror &&
1288 (CURLE_HTTP_RETURNED_ERROR == res))) {
1289 /* If it returned OK. _or_ failonerror was enabled and it
1290 returned due to such an error, check for HTTP transient
1291 errors to retry on. */
1292 char *effective_url = NULL;
1293 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
1295 checkprefix("http", effective_url)) {
1296 /* This was HTTP(S) */
1297 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1300 case 500: /* Internal Server Error */
1301 case 502: /* Bad Gateway */
1302 case 503: /* Service Unavailable */
1303 case 504: /* Gateway Timeout */
1306 * At this point, we have already written data to the output
1307 * file (or terminal). If we write to a file, we must rewind
1308 * or close/re-open the file so that the next attempt starts
1309 * over from the beginning.
1311 * TODO: similar action for the upload case. We might need
1312 * to start over reading from a previous point if we have
1313 * uploaded something when this was returned.
1320 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1322 if(response/100 == 4)
1324 * This is typically when the FTP server only allows a certain
1325 * amount of users and we are not one of them. All 4xx codes
1332 static const char * const m[]={
1333 NULL, "timeout", "HTTP error", "FTP error"
1335 warnf(config, "Transient problem: %s "
1336 "Will retry in %ld seconds. "
1337 "%ld retries left.\n",
1338 m[retry], retry_sleep/1000L, retry_numretries);
1340 tool_go_sleep(retry_sleep);
1342 if(!config->retry_delay) {
1344 if(retry_sleep > RETRY_SLEEP_MAX)
1345 retry_sleep = RETRY_SLEEP_MAX;
1347 if(outs.bytes && outs.filename) {
1348 /* We have written data to a output file, we truncate file
1351 fprintf(config->errors, "Throwing away %"
1352 CURL_FORMAT_CURL_OFF_T " bytes\n",
1354 fflush(outs.stream);
1355 /* truncate file at the position where we started appending */
1356 #ifdef HAVE_FTRUNCATE
1357 if(ftruncate( fileno(outs.stream), outs.init)) {
1358 /* when truncate fails, we can't just append as then we'll
1359 create something strange, bail out */
1361 fprintf(config->errors,
1362 "failed to truncate, exiting\n");
1363 res = CURLE_WRITE_ERROR;
1366 /* now seek to the end of the file, the position where we
1367 just truncated the file in a large file-safe way */
1368 fseek(outs.stream, 0, SEEK_END);
1370 /* ftruncate is not available, so just reposition the file
1371 to the location we would have truncated it. This won't
1372 work properly with large files on 32-bit systems, but
1373 most of those will have ftruncate. */
1374 fseek(outs.stream, (long)outs.init, SEEK_SET);
1376 outs.bytes = 0; /* clear for next round */
1378 continue; /* curl_easy_perform loop */
1380 } /* if retry_numretries */
1382 /* In all ordinary cases, just break out of loop here */
1383 break; /* curl_easy_perform loop */
1387 if((config->progressmode == CURL_PROGRESS_BAR) &&
1389 /* if the custom progress bar has been displayed, we output a
1391 fputs("\n", progressbar.out);
1393 if(config->writeout)
1394 ourWriteOut(curl, &outs, config->writeout);
1396 if(config->writeenv)
1400 ** Code within this loop may jump directly here to label 'show_error'
1401 ** in order to display an error message for CURLcode stored in 'res'
1402 ** variable and exit loop once that necessary writing and cleanup
1403 ** in label 'quit_urls' has been done.
1409 if(is_vms_shell()) {
1410 /* VMS DCL shell behavior */
1411 if(!config->showerror)
1412 vms_show = VMSSTS_HIDE;
1416 if(res && config->showerror) {
1417 fprintf(config->errors, "curl: (%d) %s\n", res, (errorbuffer[0]) ?
1418 errorbuffer : curl_easy_strerror((CURLcode)res));
1419 if(res == CURLE_SSL_CACERT)
1420 fprintf(config->errors, "%s%s",
1421 CURL_CA_CERT_ERRORMSG1, CURL_CA_CERT_ERRORMSG2);
1424 /* Fall through comment to 'quit_urls' label */
1427 ** Upon error condition and always that a message has already been
1428 ** displayed, code within this loop may jump directly here to label
1429 ** 'quit_urls' otherwise it should jump to 'show_error' label above.
1431 ** When 'res' variable is _not_ CURLE_OK loop will exit once that
1432 ** all code following 'quit_urls' has been executed. Otherwise it
1433 ** will loop to the beginning from where it may exit if there are
1434 ** no more urls left.
1439 /* Set file extended attributes */
1440 if(!res && config->xattr && outs.fopened && outs.stream) {
1441 int rc = fwrite_xattr(curl, fileno(outs.stream));
1443 warnf(config, "Error setting extended attributes: %s\n",
1447 /* Close the file */
1448 if(outs.fopened && outs.stream) {
1449 int rc = fclose(outs.stream);
1451 /* something went wrong in the writing process */
1452 res = CURLE_WRITE_ERROR;
1453 fprintf(config->errors, "(%d) Failed writing body\n", res);
1456 else if(!outs.s_isreg && outs.stream) {
1457 /* Dump standard stream buffered data */
1458 int rc = fflush(outs.stream);
1460 /* something went wrong in the writing process */
1461 res = CURLE_WRITE_ERROR;
1462 fprintf(config->errors, "(%d) Failed writing body\n", res);
1467 if(!res && outs.s_isreg && outs.filename) {
1468 /* Set the url (up to 80 chars) as comment for the file */
1469 if(strlen(url) > 78)
1471 SetComment(outs.filename, url);
1476 /* File time can only be set _after_ the file has been closed */
1477 if(!res && config->remote_time && outs.s_isreg && outs.filename) {
1478 /* Ask libcurl if we got a remote file time */
1480 curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
1482 struct utimbuf times;
1483 times.actime = (time_t)filetime;
1484 times.modtime = (time_t)filetime;
1485 utime(outs.filename, ×); /* set the time we got */
1489 /* No more business with this output struct */
1490 if(outs.alloc_filename)
1491 Curl_safefree(outs.filename);
1492 memset(&outs, 0, sizeof(struct OutStruct));
1494 /* Free loop-local allocated memory and close loop-local opened fd */
1496 Curl_safefree(outfile);
1497 Curl_safefree(this_url);
1502 infd = STDIN_FILENO;
1506 /* when url globbing, exit loop upon critical error */
1507 if(is_fatal_error(res))
1511 /* when not url globbing, exit loop upon any error */
1514 } /* loop to the next URL */
1516 /* Free loop-local allocated memory */
1518 Curl_safefree(uploadfile);
1521 /* Free list of remaining URLs */
1527 /* when file globbing, exit loop upon critical error */
1528 if(is_fatal_error(res))
1532 /* when not file globbing, exit loop upon any error */
1535 } /* loop to the next globbed upload file */
1537 /* Free loop-local allocated memory */
1539 Curl_safefree(outfiles);
1542 /* Free list of globbed upload files */
1543 glob_cleanup(inglob);
1547 /* Free this URL node data without destroying the
1548 the node itself nor modifying next pointer. */
1549 Curl_safefree(urlnode->url);
1550 Curl_safefree(urlnode->outfile);
1551 Curl_safefree(urlnode->infile);
1555 ** Bail out upon critical errors
1557 if(is_fatal_error(res))
1560 } /* for-loop through all URLs */
1563 ** Nested loops end here.
1568 /* Free function-local referenced allocated memory */
1569 Curl_safefree(httpgetfields);
1571 /* Free list of given URLs */
1572 clean_getout(config);
1574 /* Cleanup the curl handle now that our
1575 progressbar struct is still in scope */
1577 curl_easy_cleanup(curl);
1578 config->easy = curl = NULL;
1580 #ifndef CURL_DISABLE_LIBCURL_OPTION
1584 /* Close function-local opened file descriptors */
1586 if(heads.fopened && heads.stream)
1587 fclose(heads.stream);
1588 if(heads.alloc_filename)
1589 Curl_safefree(heads.filename);
1591 if(config->trace_fopened && config->trace_stream)
1592 fclose(config->trace_stream);
1594 #ifndef CURL_DISABLE_LIBCURL_OPTION
1595 /* Dump the libcurl code if previously enabled.
1596 NOTE: that this function relies on config->errors amongst other things
1597 so not everything can be closed and cleaned before this is called */
1598 dumpeasysrc(config);
1601 if(config->errors_fopened && config->errors)
1602 fclose(config->errors);
1604 main_free(); /* cleanup */