1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
24 #include <curl/curl.h>
36 #elif defined(HAVE_SYS_UTIME_H)
37 # include <sys/utime.h>
46 #define ENABLE_CURLX_PRINTF
47 /* use our own printf() functions */
50 #include "tool_binmode.h"
51 #include "tool_cfgable.h"
52 #include "tool_cb_dbg.h"
53 #include "tool_cb_hdr.h"
54 #include "tool_cb_prg.h"
55 #include "tool_cb_rea.h"
56 #include "tool_cb_see.h"
57 #include "tool_cb_skt.h"
58 #include "tool_cb_wrt.h"
59 #include "tool_dirhie.h"
60 #include "tool_doswin.h"
61 #include "tool_easysrc.h"
62 #include "tool_getparam.h"
63 #include "tool_helpers.h"
64 #include "tool_homedir.h"
65 #include "tool_libinfo.h"
66 #include "tool_main.h"
67 #include "tool_msgs.h"
68 #include "tool_operate.h"
69 #include "tool_operhlp.h"
70 #include "tool_parsecfg.h"
71 #include "tool_setopt.h"
72 #include "tool_sleep.h"
73 #include "tool_urlglob.h"
74 #include "tool_util.h"
75 #include "tool_writeenv.h"
76 #include "tool_writeout.h"
77 #include "tool_xattr.h"
79 #include "memdebug.h" /* keep this as LAST include */
81 #define CURLseparator "--_curl_--"
84 /* since O_BINARY as used in bitmasks, setting it to zero makes it usable in
85 source code but yet it doesn't ruin anything */
89 #define CURL_CA_CERT_ERRORMSG1 \
90 "More details here: http://curl.haxx.se/docs/sslcerts.html\n\n" \
91 "curl performs SSL certificate verification by default, " \
92 "using a \"bundle\"\n" \
93 " of Certificate Authority (CA) public keys (CA certs). If the default\n" \
94 " bundle file isn't adequate, you can specify an alternate file\n" \
95 " using the --cacert option.\n"
97 #define CURL_CA_CERT_ERRORMSG2 \
98 "If this HTTPS server uses a certificate signed by a CA represented in\n" \
99 " the bundle, the certificate verification probably failed due to a\n" \
100 " problem with the certificate (it might be expired, or the name might\n" \
101 " not match the domain name in the URL).\n" \
102 "If you'd like to turn off curl's verification of the certificate, use\n" \
103 " the -k (or --insecure) option.\n"
105 int operate(struct Configurable *config, int argc, argv_item_t argv[])
107 char errorbuffer[CURL_ERROR_SIZE];
108 struct ProgressData progressbar;
109 struct getout *urlnode;
111 struct OutStruct heads;
114 char *httpgetfields = NULL;
120 errorbuffer[0] = '\0';
121 /* default headers output stream is stdout */
122 memset(&heads, 0, sizeof(struct OutStruct));
123 heads.stream = stdout;
124 heads.config = config;
126 memory_tracking_init();
129 ** Initialize curl library - do not call any libcurl functions before
130 ** this point. Note that the memory_tracking_init() magic above is an
131 ** exception, but then that's not part of the official public API.
133 if(main_init() != CURLE_OK) {
134 helpf(config->errors, "error initializing curl library\n");
135 return CURLE_FAILED_INIT;
138 /* Get libcurl info right away */
139 if(get_libcurl_info() != CURLE_OK) {
140 helpf(config->errors, "error retrieving curl library information\n");
142 return CURLE_FAILED_INIT;
145 /* Get a curl handle to use for all forthcoming curl transfers */
146 curl = curl_easy_init();
148 helpf(config->errors, "error initializing curl easy handle\n");
150 return CURLE_FAILED_INIT;
155 ** Beyond this point no return'ing from this function allowed.
156 ** Jump to label 'quit_curl' in order to abandon this function
157 ** from outside of nested loops further down below.
160 /* setup proper locale from environment */
161 #ifdef HAVE_SETLOCALE
162 setlocale(LC_ALL, "");
166 config->postfieldsize = -1;
167 config->showerror = -1; /* will show errors */
168 config->use_httpget = FALSE;
169 config->create_dirs = FALSE;
170 config->maxredirs = DEFAULT_MAXREDIRS;
171 config->proto = CURLPROTO_ALL; /* FIXME: better to read from library */
172 config->proto_present = FALSE;
173 config->proto_redir =
174 CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
175 config->proto_redir_present = FALSE;
178 (!curlx_strnequal("--", argv[1], 2) && (argv[1][0] == '-')) &&
179 strchr(argv[1], 'q')) {
181 * The first flag, that is not a verbose name, but a shortname
182 * and it includes the 'q' flag!
187 parseconfig(NULL, config); /* ignore possible failure */
190 if((argc < 2) && !config->url_list) {
191 helpf(config->errors, NULL);
192 res = CURLE_FAILED_INIT;
197 for(i = 1, stillflags = TRUE; i < argc; i++) {
199 ('-' == argv[i][0])) {
202 char *origopt = argv[i];
204 char *flag = argv[i];
206 if(curlx_strequal("--", argv[i]))
207 /* this indicates the end of the flags and thus enables the
208 following (URL) argument to start with -. */
211 nextarg = (i < (argc-1)) ? argv[i+1] : NULL;
213 res = getparameter(flag, nextarg, &passarg, config);
215 int retval = CURLE_OK;
216 if(res != PARAM_HELP_REQUESTED) {
217 const char *reason = param2text(res);
218 helpf(config->errors, "option %s: %s\n", origopt, reason);
219 retval = CURLE_FAILED_INIT;
225 if(passarg) /* we're supposed to skip this */
231 /* just add the URL please */
232 res = getparameter((char *)"--url", argv[i], &used, config);
238 if((!config->url_list || !config->url_list->url) && !config->list_engines) {
239 helpf(config->errors, "no URL specified!\n");
240 res = CURLE_FAILED_INIT;
244 if(!config->useragent)
245 config->useragent = my_useragent();
246 if(!config->useragent) {
247 helpf(config->errors, "out of memory\n");
248 res = CURLE_OUT_OF_MEMORY;
252 /* On WIN32 we can't set the path to curl-ca-bundle.crt
253 * at compile time. So we look here for the file in two ways:
254 * 1: look at the environment variable CURL_CA_BUNDLE for a path
255 * 2: if #1 isn't found, use the windows API function SearchPath()
256 * to find it along the app's path (includes app's dir and CWD)
258 * We support the environment variable thing for non-Windows platforms
259 * too. Just for the sake of it.
261 if(!config->cacert &&
263 !config->insecure_ok) {
265 env = curlx_getenv("CURL_CA_BUNDLE");
267 config->cacert = strdup(env);
268 if(!config->cacert) {
270 helpf(config->errors, "out of memory\n");
271 res = CURLE_OUT_OF_MEMORY;
276 env = curlx_getenv("SSL_CERT_DIR");
278 config->capath = strdup(env);
279 if(!config->capath) {
281 helpf(config->errors, "out of memory\n");
282 res = CURLE_OUT_OF_MEMORY;
287 env = curlx_getenv("SSL_CERT_FILE");
289 config->cacert = strdup(env);
290 if(!config->cacert) {
292 helpf(config->errors, "out of memory\n");
293 res = CURLE_OUT_OF_MEMORY;
304 res = FindWin32CACert(config, "curl-ca-bundle.crt");
311 if(config->postfields) {
312 if(config->use_httpget) {
313 /* Use the postfields data for a http get */
314 httpgetfields = strdup(config->postfields);
315 Curl_safefree(config->postfields);
317 helpf(config->errors, "out of memory\n");
318 res = CURLE_OUT_OF_MEMORY;
321 if(SetHTTPrequest(config,
322 (config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
329 if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq)) {
336 /* This is the first entry added to easysrc and it initializes the slist */
337 easysrc = curl_slist_append(easysrc, "CURL *hnd = curl_easy_init();");
339 helpf(config->errors, "out of memory\n");
340 res = CURLE_OUT_OF_MEMORY;
344 if(config->list_engines) {
345 struct curl_slist *engines = NULL;
346 curl_easy_getinfo(curl, CURLINFO_SSL_ENGINES, &engines);
347 list_engines(engines);
348 curl_slist_free_all(engines);
353 /* Single header file for all URLs */
354 if(config->headerfile) {
355 /* open file for output: */
356 if(!curlx_strequal(config->headerfile, "-")) {
357 FILE *newfile = fopen(config->headerfile, "wb");
359 warnf(config, "Failed to open %s\n", config->headerfile);
360 res = CURLE_WRITE_ERROR;
364 heads.filename = config->headerfile;
365 heads.s_isreg = TRUE;
366 heads.fopened = TRUE;
367 heads.stream = newfile;
373 ** Nested loops start here.
376 /* loop through the list of given URLs */
378 for(urlnode = config->url_list; urlnode; urlnode = urlnode->next) {
380 int up; /* upload file counter within a single upload glob */
381 char *infiles; /* might be a glob pattern */
390 /* urlnode->url is the full URL (it might be NULL) */
393 /* This node has no URL. Free node data without destroying the
394 node itself nor modifying next pointer and continue to next */
395 Curl_safefree(urlnode->outfile);
396 Curl_safefree(urlnode->infile);
398 continue; /* next URL please */
401 /* save outfile pattern before expansion */
402 if(urlnode->outfile) {
403 outfiles = strdup(urlnode->outfile);
405 helpf(config->errors, "out of memory\n");
406 res = CURLE_OUT_OF_MEMORY;
411 infiles = urlnode->infile;
413 if(!config->globoff && infiles) {
414 /* Unless explicitly shut off */
415 res = glob_url(&inglob, infiles, &infilenum,
416 config->showerror?config->errors:NULL);
418 Curl_safefree(outfiles);
423 /* Here's the loop for uploading multiple files within the same
424 single globbed string. If no upload, we enter the loop once anyway. */
425 for(up = 0 ;; up++) {
427 char *uploadfile; /* a single file, never a glob */
441 res = glob_next_url(&uploadfile, inglob);
442 if(res == CURLE_OUT_OF_MEMORY)
443 helpf(config->errors, "out of memory\n");
446 uploadfile = strdup(infiles);
448 helpf(config->errors, "out of memory\n");
449 res = CURLE_OUT_OF_MEMORY;
458 if(!config->globoff) {
459 /* Unless explicitly shut off, we expand '{...}' and '[...]'
460 expressions and return total number of URLs in pattern set */
461 res = glob_url(&urls, urlnode->url, &urlnum,
462 config->showerror?config->errors:NULL);
464 Curl_safefree(uploadfile);
469 urlnum = 1; /* without globbing, this is a single URL */
471 /* if multiple files extracted to stdout, insert separators! */
472 separator= ((!outfiles || curlx_strequal(outfiles, "-")) && urlnum > 1);
474 /* Here's looping around each globbed URL */
480 struct OutStruct outs;
481 struct InStruct input;
482 struct timeval retrystart;
483 curl_off_t uploadfilesize;
484 long retry_numretries;
485 long retry_sleep_default;
492 uploadfilesize = -1; /* -1 means unknown */
494 /* default output stream is stdout */
495 memset(&outs, 0, sizeof(struct OutStruct));
496 outs.stream = stdout;
497 outs.config = config;
500 res = glob_next_url(&this_url, urls);
505 this_url = strdup(urlnode->url);
507 res = CURLE_OUT_OF_MEMORY;
517 outfile = strdup(outfiles);
519 res = CURLE_OUT_OF_MEMORY;
524 if((urlnode->flags&GETOUT_USEREMOTE) ||
525 (outfile && !curlx_strequal("-", outfile)) ) {
528 * We have specified a file name to store the result in, or we have
529 * decided we want to use the remote file name.
533 /* extract the file name from the URL */
534 res = get_url_file_name(&outfile, this_url);
537 if((!outfile || !*outfile) && !config->content_disposition) {
538 helpf(config->errors, "Remote file name has no length!\n");
539 res = CURLE_WRITE_ERROR;
542 #if defined(MSDOS) || defined(WIN32)
543 /* For DOS and WIN32, we do some major replacing of
544 bad characters in the file name before using it */
545 outfile = sanitize_dos_name(outfile);
547 res = CURLE_OUT_OF_MEMORY;
550 #endif /* MSDOS || WIN32 */
553 /* fill '#1' ... '#9' terms from URL pattern */
554 char *storefile = outfile;
555 res = glob_match_url(&outfile, storefile, urls);
556 Curl_safefree(storefile);
559 warnf(config, "bad output glob!\n");
564 /* Create the directory hierarchy, if not pre-existent to a multiple
567 if(config->create_dirs) {
568 res = create_dir_hierarchy(outfile, config->errors);
569 /* create_dir_hierarchy shows error upon CURLE_WRITE_ERROR */
570 if(res == CURLE_WRITE_ERROR)
577 if((urlnode->flags & GETOUT_USEREMOTE)
578 && config->content_disposition) {
579 /* Our header callback sets the filename */
580 DEBUGASSERT(!outs.filename);
583 if(config->resume_from_current) {
584 /* We're told to continue from where we are now. Get the size
585 of the file as it is now and open it for append instead */
586 struct_stat fileinfo;
587 /* VMS -- Danger, the filesize is only valid for stream files */
588 if(0 == stat(outfile, &fileinfo))
589 /* set offset to current file size: */
590 config->resume_from = fileinfo.st_size;
592 /* let offset be 0 */
593 config->resume_from = 0;
596 if(config->resume_from) {
597 /* open file for output: */
598 FILE *file = fopen(outfile, config->resume_from?"ab":"wb");
600 helpf(config->errors, "Can't open '%s'!\n", outfile);
601 res = CURLE_WRITE_ERROR;
606 outs.init = config->resume_from;
609 outs.stream = NULL; /* open when needed */
611 outs.filename = outfile;
616 if(uploadfile && !stdin_upload(uploadfile)) {
618 * We have specified a file to upload and it isn't "-".
620 struct_stat fileinfo;
622 this_url = add_file_name_to_url(curl, this_url, uploadfile);
624 res = CURLE_OUT_OF_MEMORY;
629 * Reading binary from files can be a problem... Only FIXED, VAR
630 * etc WITHOUT implied CC will work Others need a \n appended to a
633 * - Stat gives a size but this is UNRELIABLE in VMS As a f.e. a
634 * fixed file with implied CC needs to have a byte added for every
635 * record processed, this can by derived from Filesize & recordsize
636 * for VARiable record files the records need to be counted! for
637 * every record add 1 for linefeed and subtract 2 for the record
638 * header for VARIABLE header files only the bare record data needs
639 * to be considered with one appended if implied CC
642 infd = open(uploadfile, O_RDONLY | O_BINARY);
643 if((infd == -1) || fstat(infd, &fileinfo)) {
644 helpf(config->errors, "Can't open '%s'!\n", uploadfile);
649 res = CURLE_READ_ERROR;
654 /* we ignore file size for char/block devices, sockets, etc. */
655 if(S_ISREG(fileinfo.st_mode))
656 uploadfilesize = fileinfo.st_size;
659 else if(uploadfile && stdin_upload(uploadfile)) {
660 /* count to see if there are more than one auth bit set
661 in the authtype field */
664 while(bitcheck < 32) {
665 if(config->authtype & (1 << bitcheck++)) {
668 /* more than one, we're done! */
675 * If the user has also selected --anyauth or --proxy-anyauth
676 * we should warn him/her.
678 if(config->proxyanyauth || (authbits>1)) {
680 "Using --anyauth or --proxy-anyauth with upload from stdin"
681 " involves a big risk of it not working. Use a temporary"
682 " file or a fixed auth type instead!\n");
685 DEBUGASSERT(infdopen == FALSE);
686 DEBUGASSERT(infd == STDIN_FILENO);
689 if(curlx_strequal(uploadfile, ".")) {
690 if(curlx_nonblock((curl_socket_t)infd, TRUE) < 0)
692 "fcntl failed on fd=%d: %s\n", infd, strerror(errno));
696 if(uploadfile && config->resume_from_current)
697 config->resume_from = -1; /* -1 will then force get-it-yourself */
699 if(output_expected(this_url, uploadfile)
700 && outs.stream && isatty(fileno(outs.stream)))
701 /* we send the output to a tty, therefore we switch off the progress
703 config->noprogress = config->isatty = TRUE;
705 if(urlnum > 1 && !(config->mute)) {
706 fprintf(config->errors, "\n[%d/%d]: %s --> %s\n",
707 i+1, urlnum, this_url, outfile ? outfile : "<stdout>");
709 printf("%s%s\n", CURLseparator, this_url);
713 /* Find out whether the url contains a file name */
714 const char *pc = strstr(this_url, "://");
721 pc = strrchr(pc, '/'); /* check for a slash */
724 /* there is a slash present in the URL */
727 /* Ouch, there's already a question mark in the URL string, we
728 then append the data with an ampersand separator instead! */
732 * Then append ? followed by the get fields to the url.
734 urlbuffer = malloc(strlen(this_url) + strlen(httpgetfields) + 3);
736 res = CURLE_OUT_OF_MEMORY;
740 sprintf(urlbuffer, "%s%c%s", this_url, sep, httpgetfields);
742 /* Append / before the ? to create a well-formed url
743 if the url contains a hostname only
745 sprintf(urlbuffer, "%s/?%s", this_url, httpgetfields);
747 Curl_safefree(this_url); /* free previous URL */
748 this_url = urlbuffer; /* use our new URL instead! */
752 config->errors = stderr;
754 if((!outfile || !strcmp(outfile, "-")) && !config->use_ascii) {
755 /* We get the output to stdout and we have not got the ASCII/text
756 flag, then set stdout to be binary */
760 if(config->tcp_nodelay)
761 my_setopt(curl, CURLOPT_TCP_NODELAY, 1);
764 my_setopt(curl, CURLOPT_WRITEDATA, &outs);
765 /* what call to write */
766 my_setopt(curl, CURLOPT_WRITEFUNCTION, tool_write_cb);
770 input.config = config;
771 my_setopt(curl, CURLOPT_READDATA, &input);
772 /* what call to read */
773 if((outfile && !curlx_strequal("-", outfile)) ||
774 !checkprefix("telnet:", this_url))
775 my_setopt(curl, CURLOPT_READFUNCTION, tool_read_cb);
777 /* in 7.18.0, the CURLOPT_SEEKFUNCTION/DATA pair is taking over what
778 CURLOPT_IOCTLFUNCTION/DATA pair previously provided for seeking */
779 my_setopt(curl, CURLOPT_SEEKDATA, &input);
780 my_setopt(curl, CURLOPT_SEEKFUNCTION, tool_seek_cb);
782 if(config->recvpersecond)
783 /* tell libcurl to use a smaller sized buffer as it allows us to
784 make better sleeps! 7.9.9 stuff! */
785 my_setopt(curl, CURLOPT_BUFFERSIZE, config->recvpersecond);
787 /* size of uploaded file: */
788 if(uploadfilesize != -1)
789 my_setopt(curl, CURLOPT_INFILESIZE_LARGE, uploadfilesize);
790 my_setopt_str(curl, CURLOPT_URL, this_url); /* what to fetch */
791 my_setopt(curl, CURLOPT_NOPROGRESS, config->noprogress);
792 if(config->no_body) {
793 my_setopt(curl, CURLOPT_NOBODY, 1);
794 my_setopt(curl, CURLOPT_HEADER, 1);
797 my_setopt(curl, CURLOPT_HEADER, config->include_headers);
799 #if !defined(CURL_DISABLE_PROXY)
801 /* TODO: Make this a run-time check instead of compile-time one. */
803 my_setopt_str(curl, CURLOPT_PROXY, config->proxy);
804 my_setopt_str(curl, CURLOPT_PROXYUSERPWD, config->proxyuserpwd);
806 /* new in libcurl 7.3 */
807 my_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, config->proxytunnel);
809 /* new in libcurl 7.5 */
811 my_setopt(curl, CURLOPT_PROXYTYPE, config->proxyver);
813 /* new in libcurl 7.10 */
814 if(config->socksproxy) {
815 my_setopt_str(curl, CURLOPT_PROXY, config->socksproxy);
816 my_setopt(curl, CURLOPT_PROXYTYPE, config->socksver);
819 /* new in libcurl 7.10.6 */
820 if(config->proxyanyauth)
821 my_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
822 else if(config->proxynegotiate)
823 my_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_GSSNEGOTIATE);
824 else if(config->proxyntlm)
825 my_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
826 else if(config->proxydigest)
827 my_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_DIGEST);
828 else if(config->proxybasic)
829 my_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
831 /* new in libcurl 7.19.4 */
832 my_setopt(curl, CURLOPT_NOPROXY, config->noproxy);
836 my_setopt(curl, CURLOPT_FAILONERROR, config->failonerror);
837 my_setopt(curl, CURLOPT_UPLOAD, uploadfile?TRUE:FALSE);
838 my_setopt(curl, CURLOPT_DIRLISTONLY, config->dirlistonly);
839 my_setopt(curl, CURLOPT_APPEND, config->ftp_append);
841 if(config->netrc_opt)
842 my_setopt(curl, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
843 else if(config->netrc || config->netrc_file)
844 my_setopt(curl, CURLOPT_NETRC, CURL_NETRC_REQUIRED);
846 my_setopt(curl, CURLOPT_NETRC, CURL_NETRC_IGNORED);
848 if(config->netrc_file)
849 my_setopt(curl, CURLOPT_NETRC_FILE, config->netrc_file);
851 my_setopt(curl, CURLOPT_TRANSFERTEXT, config->use_ascii);
852 my_setopt_str(curl, CURLOPT_USERPWD, config->userpwd);
853 my_setopt_str(curl, CURLOPT_RANGE, config->range);
854 my_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
855 my_setopt(curl, CURLOPT_TIMEOUT, config->timeout);
857 if(built_in_protos & CURLPROTO_HTTP) {
859 my_setopt(curl, CURLOPT_FOLLOWLOCATION,
860 config->followlocation);
861 my_setopt(curl, CURLOPT_UNRESTRICTED_AUTH,
862 config->unrestricted_auth);
864 switch(config->httpreq) {
865 case HTTPREQ_SIMPLEPOST:
866 my_setopt_str(curl, CURLOPT_POSTFIELDS,
868 my_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE,
869 config->postfieldsize);
872 my_setopt(curl, CURLOPT_HTTPPOST, config->httppost);
878 my_setopt_str(curl, CURLOPT_REFERER, config->referer);
879 my_setopt(curl, CURLOPT_AUTOREFERER, config->autoreferer);
880 my_setopt_str(curl, CURLOPT_USERAGENT, config->useragent);
881 my_setopt(curl, CURLOPT_HTTPHEADER, config->headers);
883 /* new in libcurl 7.5 */
884 my_setopt(curl, CURLOPT_MAXREDIRS, config->maxredirs);
886 /* new in libcurl 7.9.1 */
887 if(config->httpversion)
888 my_setopt(curl, CURLOPT_HTTP_VERSION, config->httpversion);
890 /* new in libcurl 7.10.6 (default is Basic) */
892 my_setopt(curl, CURLOPT_HTTPAUTH, config->authtype);
894 /* curl 7.19.1 (the 301 version existed in 7.18.2) */
895 my_setopt(curl, CURLOPT_POSTREDIR, config->post301 |
896 (config->post302 ? CURL_REDIR_POST_302 : FALSE));
898 /* new in libcurl 7.21.6 */
900 my_setopt_str(curl, CURLOPT_ACCEPT_ENCODING, "");
902 /* new in libcurl 7.21.6 */
903 if(config->tr_encoding)
904 my_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1);
906 } /* (built_in_protos & CURLPROTO_HTTP) */
908 my_setopt_str(curl, CURLOPT_FTPPORT, config->ftpport);
909 my_setopt(curl, CURLOPT_LOW_SPEED_LIMIT,
910 config->low_speed_limit);
911 my_setopt(curl, CURLOPT_LOW_SPEED_TIME, config->low_speed_time);
912 my_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE,
913 config->sendpersecond);
914 my_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE,
915 config->recvpersecond);
916 my_setopt(curl, CURLOPT_RESUME_FROM_LARGE,
917 config->use_resume?config->resume_from:0);
919 my_setopt(curl, CURLOPT_SSLCERT, config->cert);
920 my_setopt_str(curl, CURLOPT_SSLCERTTYPE, config->cert_type);
921 my_setopt(curl, CURLOPT_SSLKEY, config->key);
922 my_setopt_str(curl, CURLOPT_SSLKEYTYPE, config->key_type);
923 my_setopt_str(curl, CURLOPT_KEYPASSWD, config->key_passwd);
925 if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
927 /* SSH and SSL private key uses same command-line option */
928 /* new in libcurl 7.16.1 */
929 my_setopt_str(curl, CURLOPT_SSH_PRIVATE_KEYFILE, config->key);
930 /* new in libcurl 7.16.1 */
931 my_setopt_str(curl, CURLOPT_SSH_PUBLIC_KEYFILE, config->pubkey);
933 /* new in libcurl 7.17.1: SSH host key md5 checking allows us
934 to fail if we are not talking to who we think we should */
935 my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
940 my_setopt_str(curl, CURLOPT_CAINFO, config->cacert);
942 my_setopt_str(curl, CURLOPT_CAPATH, config->capath);
944 my_setopt_str(curl, CURLOPT_CRLFILE, config->crlfile);
946 if(curlinfo->features & CURL_VERSION_SSL) {
947 if(config->insecure_ok) {
948 my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
949 my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);
952 my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
953 /* libcurl default is strict verifyhost -> 2L */
954 /* my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); */
958 if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
959 if(!config->insecure_ok) {
962 res = CURLE_OUT_OF_MEMORY;
965 file = aprintf("%s/%sssh/known_hosts", home, DOT_CHAR);
967 /* new in curl 7.19.6 */
968 res = res_setopt_str(curl, CURLOPT_SSH_KNOWNHOSTS, file);
970 if(res == CURLE_UNKNOWN_OPTION)
971 /* libssh2 version older than 1.1.1 */
981 if(config->no_body || config->remote_time) {
982 /* no body or use remote time */
983 my_setopt(curl, CURLOPT_FILETIME, TRUE);
986 my_setopt(curl, CURLOPT_CRLF, config->crlf);
987 my_setopt(curl, CURLOPT_QUOTE, config->quote);
988 my_setopt(curl, CURLOPT_POSTQUOTE, config->postquote);
989 my_setopt(curl, CURLOPT_PREQUOTE, config->prequote);
991 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
993 /* TODO: Make this a run-time check instead of compile-time one. */
996 my_setopt_str(curl, CURLOPT_COOKIE, config->cookie);
998 if(config->cookiefile)
999 my_setopt_str(curl, CURLOPT_COOKIEFILE, config->cookiefile);
1001 /* new in libcurl 7.9 */
1002 if(config->cookiejar)
1003 my_setopt_str(curl, CURLOPT_COOKIEJAR, config->cookiejar);
1005 /* new in libcurl 7.9.7 */
1006 my_setopt(curl, CURLOPT_COOKIESESSION, config->cookiesession);
1010 my_setopt(curl, CURLOPT_SSLVERSION, config->ssl_version);
1011 my_setopt(curl, CURLOPT_TIMECONDITION, config->timecond);
1012 my_setopt(curl, CURLOPT_TIMEVALUE, config->condtime);
1013 my_setopt_str(curl, CURLOPT_CUSTOMREQUEST, config->customrequest);
1014 my_setopt(curl, CURLOPT_STDERR, config->errors);
1016 /* three new ones in libcurl 7.3: */
1017 my_setopt_str(curl, CURLOPT_INTERFACE, config->iface);
1018 my_setopt_str(curl, CURLOPT_KRBLEVEL, config->krblevel);
1020 progressbarinit(&progressbar, config);
1021 if((config->progressmode == CURL_PROGRESS_BAR) &&
1022 !config->noprogress && !config->mute) {
1023 /* we want the alternative style, then we have to implement it
1025 my_setopt(curl, CURLOPT_PROGRESSFUNCTION, tool_progress_cb);
1026 my_setopt(curl, CURLOPT_PROGRESSDATA, &progressbar);
1029 /* new in libcurl 7.6.2: */
1030 my_setopt(curl, CURLOPT_TELNETOPTIONS, config->telnet_options);
1032 /* new in libcurl 7.7: */
1033 my_setopt_str(curl, CURLOPT_RANDOM_FILE, config->random_file);
1034 my_setopt(curl, CURLOPT_EGDSOCKET, config->egd_file);
1035 my_setopt(curl, CURLOPT_CONNECTTIMEOUT, config->connecttimeout);
1037 if(config->cipher_list)
1038 my_setopt_str(curl, CURLOPT_SSL_CIPHER_LIST, config->cipher_list);
1040 /* new in libcurl 7.9.2: */
1041 if(config->disable_epsv)
1043 my_setopt(curl, CURLOPT_FTP_USE_EPSV, FALSE);
1045 /* new in libcurl 7.10.5 */
1046 if(config->disable_eprt)
1048 my_setopt(curl, CURLOPT_FTP_USE_EPRT, FALSE);
1050 if(config->tracetype != TRACE_NONE) {
1051 my_setopt(curl, CURLOPT_DEBUGFUNCTION, tool_debug_cb);
1052 my_setopt(curl, CURLOPT_DEBUGDATA, config);
1053 my_setopt(curl, CURLOPT_VERBOSE, TRUE);
1056 /* new in curl 7.9.3 */
1057 if(config->engine) {
1058 res = res_setopt_str(curl, CURLOPT_SSLENGINE, config->engine);
1061 my_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1);
1064 /* new in curl 7.10.7, extended in 7.19.4 but this only sets 0 or 1 */
1065 my_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS,
1066 config->ftp_create_dirs);
1068 /* new in curl 7.10.8 */
1069 if(config->max_filesize)
1070 my_setopt(curl, CURLOPT_MAXFILESIZE_LARGE,
1071 config->max_filesize);
1073 if(4 == config->ip_version)
1074 my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1075 else if(6 == config->ip_version)
1076 my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
1078 my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
1080 /* new in curl 7.15.5 */
1081 if(config->ftp_ssl_reqd)
1082 my_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
1084 /* new in curl 7.11.0 */
1085 else if(config->ftp_ssl)
1086 my_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1088 /* new in curl 7.16.0 */
1089 else if(config->ftp_ssl_control)
1090 my_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_CONTROL);
1092 /* new in curl 7.16.1 */
1093 if(config->ftp_ssl_ccc)
1094 my_setopt(curl, CURLOPT_FTP_SSL_CCC, config->ftp_ssl_ccc_mode);
1096 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1098 /* TODO: Make this a run-time check instead of compile-time one. */
1100 /* new in curl 7.19.4 */
1101 if(config->socks5_gssapi_service)
1102 my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_SERVICE,
1103 config->socks5_gssapi_service);
1105 /* new in curl 7.19.4 */
1106 if(config->socks5_gssapi_nec)
1107 my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_NEC,
1108 config->socks5_gssapi_nec);
1112 my_setopt_str(curl, CURLOPT_FTP_ACCOUNT, config->ftp_account);
1114 my_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, config->ignorecl);
1117 my_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, config->ftp_skip_ip);
1120 my_setopt(curl, CURLOPT_FTP_FILEMETHOD, config->ftp_filemethod);
1123 if(config->localport) {
1124 my_setopt(curl, CURLOPT_LOCALPORT, config->localport);
1125 my_setopt_str(curl, CURLOPT_LOCALPORTRANGE,
1126 config->localportrange);
1130 my_setopt_str(curl, CURLOPT_FTP_ALTERNATIVE_TO_USER,
1131 config->ftp_alternative_to_user);
1134 if(config->disable_sessionid)
1135 my_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE,
1136 !config->disable_sessionid);
1140 my_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, FALSE);
1141 my_setopt(curl, CURLOPT_HTTP_TRANSFER_DECODING, FALSE);
1145 if(!config->nokeepalive) {
1146 my_setopt(curl, CURLOPT_SOCKOPTFUNCTION, tool_sockopt_cb);
1147 my_setopt(curl, CURLOPT_SOCKOPTDATA, config);
1151 if(config->tftp_blksize)
1152 my_setopt(curl, CURLOPT_TFTP_BLKSIZE, config->tftp_blksize);
1154 if(config->mail_from)
1155 my_setopt_str(curl, CURLOPT_MAIL_FROM, config->mail_from);
1157 if(config->mail_rcpt)
1158 my_setopt(curl, CURLOPT_MAIL_RCPT, config->mail_rcpt);
1161 if(config->ftp_pret)
1162 my_setopt(curl, CURLOPT_FTP_USE_PRET, TRUE);
1164 if(config->proto_present)
1165 my_setopt(curl, CURLOPT_PROTOCOLS, config->proto);
1166 if(config->proto_redir_present)
1167 my_setopt(curl, CURLOPT_REDIR_PROTOCOLS, config->proto_redir);
1169 if((urlnode->flags & GETOUT_USEREMOTE)
1170 && config->content_disposition) {
1171 my_setopt(curl, CURLOPT_HEADERFUNCTION, tool_header_cb);
1172 my_setopt(curl, CURLOPT_HEADERDATA, &outs);
1175 /* if HEADERFUNCTION was set to something in the previous loop, it
1176 is important that we set it (back) to NULL now */
1177 my_setopt(curl, CURLOPT_HEADERFUNCTION, NULL);
1178 my_setopt(curl, CURLOPT_HEADERDATA, config->headerfile?&heads:NULL);
1183 my_setopt(curl, CURLOPT_RESOLVE, config->resolve);
1186 if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) {
1187 if(config->tls_username)
1188 my_setopt_str(curl, CURLOPT_TLSAUTH_USERNAME,
1189 config->tls_username);
1190 if(config->tls_password)
1191 my_setopt_str(curl, CURLOPT_TLSAUTH_PASSWORD,
1192 config->tls_password);
1193 if(config->tls_authtype)
1194 my_setopt_str(curl, CURLOPT_TLSAUTH_TYPE,
1195 config->tls_authtype);
1199 if(config->gssapi_delegation)
1200 my_setopt_str(curl, CURLOPT_GSSAPI_DELEGATION,
1201 config->gssapi_delegation);
1203 /* initialize retry vars for loop below */
1204 retry_sleep_default = (config->retry_delay) ?
1205 config->retry_delay*1000L : RETRY_SLEEP_DEFAULT; /* ms */
1207 retry_numretries = config->req_retry;
1208 retry_sleep = retry_sleep_default; /* ms */
1209 retrystart = tvnow();
1212 res = curl_easy_perform(curl);
1213 if(!curl_slist_append(easysrc, "ret = curl_easy_perform(hnd);")) {
1214 res = CURLE_OUT_OF_MEMORY;
1218 if(config->content_disposition && outs.stream && !config->mute &&
1220 printf("curl: Saved to filename '%s'\n", outs.filename);
1222 /* if retry-max-time is non-zero, make sure we haven't exceeded the
1224 if(retry_numretries &&
1225 (!config->retry_maxtime ||
1226 (tvdiff(tvnow(), retrystart) <
1227 config->retry_maxtime*1000L)) ) {
1233 RETRY_LAST /* not used */
1236 if(CURLE_OPERATION_TIMEDOUT == res)
1237 /* retry timeout always */
1238 retry = RETRY_TIMEOUT;
1239 else if((CURLE_OK == res) ||
1240 (config->failonerror &&
1241 (CURLE_HTTP_RETURNED_ERROR == res))) {
1242 /* If it returned OK. _or_ failonerror was enabled and it
1243 returned due to such an error, check for HTTP transient
1244 errors to retry on. */
1245 char *effective_url = NULL;
1246 curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
1248 checkprefix("http", effective_url)) {
1249 /* This was HTTP(S) */
1250 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1253 case 500: /* Internal Server Error */
1254 case 502: /* Bad Gateway */
1255 case 503: /* Service Unavailable */
1256 case 504: /* Gateway Timeout */
1259 * At this point, we have already written data to the output
1260 * file (or terminal). If we write to a file, we must rewind
1261 * or close/re-open the file so that the next attempt starts
1262 * over from the beginning.
1264 * TODO: similar action for the upload case. We might need
1265 * to start over reading from a previous point if we have
1266 * uploaded something when this was returned.
1273 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1275 if(response/100 == 4)
1277 * This is typically when the FTP server only allows a certain
1278 * amount of users and we are not one of them. All 4xx codes
1285 static const char * const m[]={
1286 NULL, "timeout", "HTTP error", "FTP error"
1288 warnf(config, "Transient problem: %s "
1289 "Will retry in %ld seconds. "
1290 "%ld retries left.\n",
1291 m[retry], retry_sleep/1000L, retry_numretries);
1293 tool_go_sleep(retry_sleep);
1295 if(!config->retry_delay) {
1297 if(retry_sleep > RETRY_SLEEP_MAX)
1298 retry_sleep = RETRY_SLEEP_MAX;
1300 if(outs.bytes && outs.filename) {
1301 /* We have written data to a output file, we truncate file
1304 fprintf(config->errors, "Throwing away %"
1305 CURL_FORMAT_CURL_OFF_T " bytes\n",
1307 fflush(outs.stream);
1308 /* truncate file at the position where we started appending */
1309 #ifdef HAVE_FTRUNCATE
1310 if(ftruncate( fileno(outs.stream), outs.init)) {
1311 /* when truncate fails, we can't just append as then we'll
1312 create something strange, bail out */
1314 fprintf(config->errors,
1315 "failed to truncate, exiting\n");
1316 res = CURLE_WRITE_ERROR;
1319 /* now seek to the end of the file, the position where we
1320 just truncated the file in a large file-safe way */
1321 fseek(outs.stream, 0, SEEK_END);
1323 /* ftruncate is not available, so just reposition the file
1324 to the location we would have truncated it. This won't
1325 work properly with large files on 32-bit systems, but
1326 most of those will have ftruncate. */
1327 fseek(outs.stream, (long)outs.init, SEEK_SET);
1329 outs.bytes = 0; /* clear for next round */
1331 continue; /* curl_easy_perform loop */
1333 } /* if retry_numretries */
1335 /* In all ordinary cases, just break out of loop here */
1336 break; /* curl_easy_perform loop */
1340 if((config->progressmode == CURL_PROGRESS_BAR) &&
1342 /* if the custom progress bar has been displayed, we output a
1344 fputs("\n", progressbar.out);
1346 if(config->writeout)
1347 ourWriteOut(curl, config->writeout);
1349 if(config->writeenv)
1353 ** Code within this loop may jump directly here to label 'show_error'
1354 ** in order to display an error message for CURLcode stored in 'res'
1355 ** variable and exit loop once that necessary writing and cleanup
1356 ** in label 'quit_urls' has been done.
1362 if(is_vms_shell()) {
1363 /* VMS DCL shell behavior */
1364 if(!config->showerror)
1365 vms_show = VMSSTS_HIDE;
1369 if(res && config->showerror) {
1370 fprintf(config->errors, "curl: (%d) %s\n", res, (errorbuffer[0]) ?
1371 errorbuffer : curl_easy_strerror((CURLcode)res));
1372 if(res == CURLE_SSL_CACERT)
1373 fprintf(config->errors, "%s%s",
1374 CURL_CA_CERT_ERRORMSG1, CURL_CA_CERT_ERRORMSG2);
1377 /* Fall through comment to 'quit_urls' label */
1380 ** Upon error condition and always that a message has already been
1381 ** displayed, code within this loop may jump directly here to label
1382 ** 'quit_urls' otherwise it should jump to 'show_error' label above.
1384 ** When 'res' variable is _not_ CURLE_OK loop will exit once that
1385 ** all code following 'quit_urls' has been executed. Otherwise it
1386 ** will loop to the beginning from where it may exit if there are
1387 ** no more urls left.
1392 /* Set file extended attributes */
1393 if(!res && config->xattr && outs.fopened && outs.stream) {
1394 int rc = fwrite_xattr(curl, fileno(outs.stream));
1396 warnf(config, "Error setting extended attributes: %s\n",
1400 /* Close the file */
1401 if(outs.fopened && outs.stream) {
1402 int rc = fclose(outs.stream);
1404 /* something went wrong in the writing process */
1405 res = CURLE_WRITE_ERROR;
1406 fprintf(config->errors, "(%d) Failed writing body\n", res);
1409 else if(!outs.s_isreg && outs.stream) {
1410 /* Dump standard stream buffered data */
1411 int rc = fflush(outs.stream);
1413 /* something went wrong in the writing process */
1414 res = CURLE_WRITE_ERROR;
1415 fprintf(config->errors, "(%d) Failed writing body\n", res);
1420 if(!res && outs.s_isreg && outs.filename) {
1421 /* Set the url (up to 80 chars) as comment for the file */
1422 if(strlen(url) > 78)
1424 SetComment(outs.filename, url);
1429 /* File time can only be set _after_ the file has been closed */
1430 if(!res && config->remote_time && outs.s_isreg && outs.filename) {
1431 /* Ask libcurl if we got a remote file time */
1433 curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
1435 struct utimbuf times;
1436 times.actime = (time_t)filetime;
1437 times.modtime = (time_t)filetime;
1438 utime(outs.filename, ×); /* set the time we got */
1442 /* No more business with this output struct */
1443 if(outs.alloc_filename)
1444 Curl_safefree(outs.filename);
1445 memset(&outs, 0, sizeof(struct OutStruct));
1447 /* Free loop-local allocated memory and close loop-local opened fd */
1449 Curl_safefree(outfile);
1450 Curl_safefree(this_url);
1455 infd = STDIN_FILENO;
1458 /* upon error exit loop */
1462 } /* loop to the next URL */
1464 /* Free loop-local allocated memory */
1466 Curl_safefree(uploadfile);
1469 /* Free list of remaining URLs */
1474 /* upon error exit loop */
1478 } /* loop to the next globbed upload file */
1480 /* Free loop-local allocated memory */
1482 Curl_safefree(outfiles);
1485 /* Free list of globbed upload files */
1486 glob_cleanup(inglob);
1490 /* Free this URL node data without destroying the
1491 the node itself nor modifying next pointer. */
1492 Curl_safefree(urlnode->url);
1493 Curl_safefree(urlnode->outfile);
1494 Curl_safefree(urlnode->infile);
1497 /* TODO: Should CURLE_SSL_CACERT be included as critical error ? */
1500 ** Bail out upon critical errors
1503 case CURLE_FAILED_INIT:
1504 case CURLE_OUT_OF_MEMORY:
1505 case CURLE_FUNCTION_NOT_FOUND:
1506 case CURLE_BAD_FUNCTION_ARGUMENT:
1509 /* Merrily loop to next URL */
1513 } /* for-loop through all URLs */
1516 ** Nested loops end here.
1521 /* Free function-local referenced allocated memory */
1522 Curl_safefree(httpgetfields);
1524 /* Free list of given URLs */
1525 clean_getout(config);
1527 /* Cleanup the curl handle now that our
1528 progressbar struct is still in scope */
1530 curl_easy_cleanup(curl);
1531 config->easy = curl = NULL;
1534 curl_slist_append(easysrc, "curl_easy_cleanup(hnd);");
1536 /* Close function-local opened file descriptors */
1538 if(heads.fopened && heads.stream)
1539 fclose(heads.stream);
1540 if(heads.alloc_filename)
1541 Curl_safefree(heads.filename);
1543 if(config->trace_fopened && config->trace_stream)
1544 fclose(config->trace_stream);
1546 /* Dump the libcurl code if previously enabled.
1547 NOTE: that this function relies on config->errors amongst other things
1548 so not everything can be closed and cleaned before this is called */
1549 dumpeasysrc(config);
1551 if(config->errors_fopened && config->errors)
1552 fclose(config->errors);
1554 main_free(); /* cleanup */