tool: Fixed incorrect return code with --version from commit c10bf9bb36
[platform/upstream/curl.git] / src / tool_operate.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 #include "tool_setup.h"
23
24 #ifdef HAVE_FCNTL_H
25 #  include <fcntl.h>
26 #endif
27
28 #ifdef HAVE_UTIME_H
29 #  include <utime.h>
30 #elif defined(HAVE_SYS_UTIME_H)
31 #  include <sys/utime.h>
32 #endif
33
34 #ifdef HAVE_LOCALE_H
35 #  include <locale.h>
36 #endif
37
38 #ifdef HAVE_NETINET_TCP_H
39 #  include <netinet/tcp.h>
40 #endif
41
42 #ifdef __VMS
43 #  include <fabdef.h>
44 #endif
45
46 #include "rawstr.h"
47
48 #define ENABLE_CURLX_PRINTF
49 /* use our own printf() functions */
50 #include "curlx.h"
51
52 #include "tool_binmode.h"
53 #include "tool_cfgable.h"
54 #include "tool_cb_dbg.h"
55 #include "tool_cb_hdr.h"
56 #include "tool_cb_prg.h"
57 #include "tool_cb_rea.h"
58 #include "tool_cb_see.h"
59 #include "tool_cb_wrt.h"
60 #include "tool_dirhie.h"
61 #include "tool_doswin.h"
62 #include "tool_easysrc.h"
63 #include "tool_getparam.h"
64 #include "tool_helpers.h"
65 #include "tool_homedir.h"
66 #include "tool_libinfo.h"
67 #include "tool_main.h"
68 #include "tool_metalink.h"
69 #include "tool_msgs.h"
70 #include "tool_operate.h"
71 #include "tool_operhlp.h"
72 #include "tool_paramhlp.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"
81 #include "tool_vms.h"
82 #include "tool_help.h"
83 #include "tool_hugehelp.h"
84
85 #include "memdebug.h" /* keep this as LAST include */
86
87 #ifdef CURLDEBUG
88 /* libcurl's debug builds provide an extra function */
89 CURLcode curl_easy_perform_ev(CURL *easy);
90 #endif
91
92 #define CURLseparator  "--_curl_--"
93
94 #ifndef O_BINARY
95 /* since O_BINARY as used in bitmasks, setting it to zero makes it usable in
96    source code but yet it doesn't ruin anything */
97 #  define O_BINARY 0
98 #endif
99
100 #define CURL_CA_CERT_ERRORMSG1                                              \
101   "More details here: http://curl.haxx.se/docs/sslcerts.html\n\n"           \
102   "curl performs SSL certificate verification by default, "                 \
103   "using a \"bundle\"\n"                                                    \
104   " of Certificate Authority (CA) public keys (CA certs). If the default\n" \
105   " bundle file isn't adequate, you can specify an alternate file\n"        \
106   " using the --cacert option.\n"
107
108 #define CURL_CA_CERT_ERRORMSG2                                              \
109   "If this HTTPS server uses a certificate signed by a CA represented in\n" \
110   " the bundle, the certificate verification probably failed due to a\n"    \
111   " problem with the certificate (it might be expired, or the name might\n" \
112   " not match the domain name in the URL).\n"                               \
113   "If you'd like to turn off curl's verification of the certificate, use\n" \
114   " the -k (or --insecure) option.\n"
115
116 static bool is_fatal_error(CURLcode code)
117 {
118   switch(code) {
119   /* TODO: Should CURLE_SSL_CACERT be included as critical error ? */
120   case CURLE_FAILED_INIT:
121   case CURLE_OUT_OF_MEMORY:
122   case CURLE_UNKNOWN_OPTION:
123   case CURLE_FUNCTION_NOT_FOUND:
124   case CURLE_BAD_FUNCTION_ARGUMENT:
125     /* critical error */
126     return TRUE;
127   default:
128     break;
129   }
130
131   /* no error or not critical */
132   return FALSE;
133 }
134
135 #ifdef __VMS
136 /*
137  * get_vms_file_size does what it takes to get the real size of the file
138  *
139  * For fixed files, find out the size of the EOF block and adjust.
140  *
141  * For all others, have to read the entire file in, discarding the contents.
142  * Most posted text files will be small, and binary files like zlib archives
143  * and CD/DVD images should be either a STREAM_LF format or a fixed format.
144  *
145  */
146 static curl_off_t vms_realfilesize(const char * name,
147                                    const struct_stat * stat_buf)
148 {
149   char buffer[8192];
150   curl_off_t count;
151   int ret_stat;
152   FILE * file;
153
154   file = fopen(name, "r");
155   if(file == NULL) {
156     return 0;
157   }
158   count = 0;
159   ret_stat = 1;
160   while(ret_stat > 0) {
161     ret_stat = fread(buffer, 1, sizeof(buffer), file);
162     if(ret_stat != 0)
163       count += ret_stat;
164   }
165   fclose(file);
166
167   return count;
168 }
169
170 /*
171  *
172  *  VmsSpecialSize checks to see if the stat st_size can be trusted and
173  *  if not to call a routine to get the correct size.
174  *
175  */
176 static curl_off_t VmsSpecialSize(const char * name,
177                                  const struct_stat * stat_buf)
178 {
179   switch(stat_buf->st_fab_rfm) {
180   case FAB$C_VAR:
181   case FAB$C_VFC:
182     return vms_realfilesize(name, stat_buf);
183     break;
184   default:
185     return stat_buf->st_size;
186   }
187 }
188 #endif /* __VMS */
189
190 static CURLcode operate_init(struct Configurable *config)
191 {
192   /* Get a curl handle to use for all forthcoming curl transfers */
193   config->easy = curl_easy_init();
194   if(!config->easy) {
195     helpf(config->errors, "error initializing curl easy handle\n");
196     return CURLE_FAILED_INIT;
197   }
198
199   /* Setup proper locale from environment */
200 #ifdef HAVE_SETLOCALE
201   setlocale(LC_ALL, "");
202 #endif
203
204   return CURLE_OK;
205 }
206
207 static CURLcode operate_do(struct Configurable *config)
208 {
209   char errorbuffer[CURL_ERROR_SIZE];
210   struct ProgressData progressbar;
211   struct getout *urlnode;
212
213   struct HdrCbData hdrcbdata;
214   struct OutStruct heads;
215
216   metalinkfile *mlfile_last = NULL;
217
218   CURL *curl = config->easy;
219   char *httpgetfields = NULL;
220
221   int res = 0;
222   unsigned long li;
223
224   bool orig_noprogress;
225   bool orig_isatty;
226
227   errorbuffer[0] = '\0';
228   /* default headers output stream is stdout */
229   memset(&hdrcbdata, 0, sizeof(struct HdrCbData));
230   memset(&heads, 0, sizeof(struct OutStruct));
231   heads.stream = stdout;
232   heads.config = config;
233
234   /*
235   ** Beyond this point no return'ing from this function allowed.
236   ** Jump to label 'quit_curl' in order to abandon this function
237   ** from outside of nested loops further down below.
238   */
239
240   /* Check we have a url */
241   if(!config->url_list || !config->url_list->url) {
242     helpf(config->errors, "no URL specified!\n");
243     res = CURLE_FAILED_INIT;
244     goto quit_curl;
245   }
246
247   /* On WIN32 we can't set the path to curl-ca-bundle.crt
248    * at compile time. So we look here for the file in two ways:
249    * 1: look at the environment variable CURL_CA_BUNDLE for a path
250    * 2: if #1 isn't found, use the windows API function SearchPath()
251    *    to find it along the app's path (includes app's dir and CWD)
252    *
253    * We support the environment variable thing for non-Windows platforms
254    * too. Just for the sake of it.
255    */
256   if(!config->cacert &&
257      !config->capath &&
258      !config->insecure_ok) {
259     char *env;
260     env = curlx_getenv("CURL_CA_BUNDLE");
261     if(env) {
262       config->cacert = strdup(env);
263       if(!config->cacert) {
264         curl_free(env);
265         helpf(config->errors, "out of memory\n");
266         res = CURLE_OUT_OF_MEMORY;
267         goto quit_curl;
268       }
269     }
270     else {
271       env = curlx_getenv("SSL_CERT_DIR");
272       if(env) {
273         config->capath = strdup(env);
274         if(!config->capath) {
275           curl_free(env);
276           helpf(config->errors, "out of memory\n");
277           res = CURLE_OUT_OF_MEMORY;
278           goto quit_curl;
279         }
280       }
281       else {
282         env = curlx_getenv("SSL_CERT_FILE");
283         if(env) {
284           config->cacert = strdup(env);
285           if(!config->cacert) {
286             curl_free(env);
287             helpf(config->errors, "out of memory\n");
288             res = CURLE_OUT_OF_MEMORY;
289             goto quit_curl;
290           }
291         }
292       }
293     }
294
295     if(env)
296       curl_free(env);
297 #ifdef WIN32
298     else {
299       res = FindWin32CACert(config, "curl-ca-bundle.crt");
300       if(res)
301         goto quit_curl;
302     }
303 #endif
304   }
305
306   if(config->postfields) {
307     if(config->use_httpget) {
308       /* Use the postfields data for a http get */
309       httpgetfields = strdup(config->postfields);
310       Curl_safefree(config->postfields);
311       if(!httpgetfields) {
312         helpf(config->errors, "out of memory\n");
313         res = CURLE_OUT_OF_MEMORY;
314         goto quit_curl;
315       }
316       if(SetHTTPrequest(config,
317                         (config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
318                         &config->httpreq)) {
319         res = CURLE_FAILED_INIT;
320         goto quit_curl;
321       }
322     }
323     else {
324       if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq)) {
325         res = CURLE_FAILED_INIT;
326         goto quit_curl;
327       }
328     }
329   }
330
331 #ifndef CURL_DISABLE_LIBCURL_OPTION
332   res = easysrc_init();
333   if(res) {
334     helpf(config->errors, "out of memory\n");
335     goto quit_curl;
336   }
337 #endif
338
339   /* Single header file for all URLs */
340   if(config->headerfile) {
341     /* open file for output: */
342     if(!curlx_strequal(config->headerfile, "-")) {
343       FILE *newfile = fopen(config->headerfile, "wb");
344       if(!newfile) {
345         warnf(config, "Failed to open %s\n", config->headerfile);
346         res = CURLE_WRITE_ERROR;
347         goto quit_curl;
348       }
349       else {
350         heads.filename = config->headerfile;
351         heads.s_isreg = TRUE;
352         heads.fopened = TRUE;
353         heads.stream = newfile;
354       }
355     }
356     else {
357       /* always use binary mode for protocol header output */
358       set_binmode(heads.stream);
359     }
360   }
361
362   /* save the values of noprogress and isatty to restore them later on */
363   orig_noprogress = config->noprogress;
364   orig_isatty = config->isatty;
365
366   /*
367   ** Nested loops start here.
368   */
369
370   /* loop through the list of given URLs */
371
372   for(urlnode = config->url_list; urlnode; urlnode = urlnode->next) {
373
374     unsigned long up; /* upload file counter within a single upload glob */
375     char *infiles; /* might be a glob pattern */
376     char *outfiles;
377     unsigned long infilenum;
378     URLGlob *inglob;
379
380     int metalink = 0; /* nonzero for metalink download. */
381     metalinkfile *mlfile;
382     metalink_resource *mlres;
383
384     outfiles = NULL;
385     infilenum = 1;
386     inglob = NULL;
387
388     if(urlnode->flags & GETOUT_METALINK) {
389       metalink = 1;
390       if(mlfile_last == NULL) {
391         mlfile_last = config->metalinkfile_list;
392       }
393       mlfile = mlfile_last;
394       mlfile_last = mlfile_last->next;
395       mlres = mlfile->resource;
396     }
397     else {
398       mlfile = NULL;
399       mlres = NULL;
400     }
401
402     /* urlnode->url is the full URL (it might be NULL) */
403
404     if(!urlnode->url) {
405       /* This node has no URL. Free node data without destroying the
406          node itself nor modifying next pointer and continue to next */
407       Curl_safefree(urlnode->outfile);
408       Curl_safefree(urlnode->infile);
409       urlnode->flags = 0;
410       continue; /* next URL please */
411     }
412
413     /* save outfile pattern before expansion */
414     if(urlnode->outfile) {
415       outfiles = strdup(urlnode->outfile);
416       if(!outfiles) {
417         helpf(config->errors, "out of memory\n");
418         res = CURLE_OUT_OF_MEMORY;
419         break;
420       }
421     }
422
423     infiles = urlnode->infile;
424
425     if(!config->globoff && infiles) {
426       /* Unless explicitly shut off */
427       res = glob_url(&inglob, infiles, &infilenum,
428                      config->showerror?config->errors:NULL);
429       if(res) {
430         Curl_safefree(outfiles);
431         break;
432       }
433     }
434
435     /* Here's the loop for uploading multiple files within the same
436        single globbed string. If no upload, we enter the loop once anyway. */
437     for(up = 0 ; up < infilenum; up++) {
438
439       char *uploadfile; /* a single file, never a glob */
440       int separator;
441       URLGlob *urls;
442       unsigned long urlnum;
443
444       uploadfile = NULL;
445       urls = NULL;
446       urlnum = 0;
447
448       if(!up && !infiles)
449         Curl_nop_stmt;
450       else {
451         if(inglob) {
452           res = glob_next_url(&uploadfile, inglob);
453           if(res == CURLE_OUT_OF_MEMORY)
454             helpf(config->errors, "out of memory\n");
455         }
456         else if(!up) {
457           uploadfile = strdup(infiles);
458           if(!uploadfile) {
459             helpf(config->errors, "out of memory\n");
460             res = CURLE_OUT_OF_MEMORY;
461           }
462         }
463         else
464           uploadfile = NULL;
465         if(!uploadfile)
466           break;
467       }
468
469       if(metalink) {
470         /* For Metalink download, we don't use glob. Instead we use
471            the number of resources as urlnum. */
472         urlnum = count_next_metalink_resource(mlfile);
473       }
474       else
475       if(!config->globoff) {
476         /* Unless explicitly shut off, we expand '{...}' and '[...]'
477            expressions and return total number of URLs in pattern set */
478         res = glob_url(&urls, urlnode->url, &urlnum,
479                        config->showerror?config->errors:NULL);
480         if(res) {
481           Curl_safefree(uploadfile);
482           break;
483         }
484       }
485       else
486         urlnum = 1; /* without globbing, this is a single URL */
487
488       /* if multiple files extracted to stdout, insert separators! */
489       separator= ((!outfiles || curlx_strequal(outfiles, "-")) && urlnum > 1);
490
491       /* Here's looping around each globbed URL */
492       for(li = 0 ; li < urlnum; li++) {
493
494         int infd;
495         bool infdopen;
496         char *outfile;
497         struct OutStruct outs;
498         struct InStruct input;
499         struct timeval retrystart;
500         curl_off_t uploadfilesize;
501         long retry_numretries;
502         long retry_sleep_default;
503         long retry_sleep;
504         char *this_url = NULL;
505         int metalink_next_res = 0;
506
507         outfile = NULL;
508         infdopen = FALSE;
509         infd = STDIN_FILENO;
510         uploadfilesize = -1; /* -1 means unknown */
511
512         /* default output stream is stdout */
513         memset(&outs, 0, sizeof(struct OutStruct));
514         outs.stream = stdout;
515         outs.config = config;
516
517         if(metalink) {
518           /* For Metalink download, use name in Metalink file as
519              filename. */
520           outfile = strdup(mlfile->filename);
521           if(!outfile) {
522             res = CURLE_OUT_OF_MEMORY;
523             goto show_error;
524           }
525           this_url = strdup(mlres->url);
526           if(!this_url) {
527             res = CURLE_OUT_OF_MEMORY;
528             goto show_error;
529           }
530         }
531         else {
532           if(urls) {
533             res = glob_next_url(&this_url, urls);
534             if(res)
535               goto show_error;
536           }
537           else if(!li) {
538             this_url = strdup(urlnode->url);
539             if(!this_url) {
540               res = CURLE_OUT_OF_MEMORY;
541               goto show_error;
542             }
543           }
544           else
545             this_url = NULL;
546           if(!this_url)
547             break;
548
549           if(outfiles) {
550             outfile = strdup(outfiles);
551             if(!outfile) {
552               res = CURLE_OUT_OF_MEMORY;
553               goto show_error;
554             }
555           }
556         }
557
558         if(((urlnode->flags&GETOUT_USEREMOTE) ||
559             (outfile && !curlx_strequal("-", outfile))) &&
560            (metalink || !config->use_metalink)) {
561
562           /*
563            * We have specified a file name to store the result in, or we have
564            * decided we want to use the remote file name.
565            */
566
567           if(!outfile) {
568             /* extract the file name from the URL */
569             res = get_url_file_name(&outfile, this_url);
570             if(res)
571               goto show_error;
572             if((!outfile || !*outfile) && !config->content_disposition) {
573               helpf(config->errors, "Remote file name has no length!\n");
574               res = CURLE_WRITE_ERROR;
575               goto quit_urls;
576             }
577 #if defined(MSDOS) || defined(WIN32)
578             /* For DOS and WIN32, we do some major replacing of
579                bad characters in the file name before using it */
580             outfile = sanitize_dos_name(outfile);
581             if(!outfile) {
582               res = CURLE_OUT_OF_MEMORY;
583               goto show_error;
584             }
585 #endif /* MSDOS || WIN32 */
586           }
587           else if(urls) {
588             /* fill '#1' ... '#9' terms from URL pattern */
589             char *storefile = outfile;
590             res = glob_match_url(&outfile, storefile, urls);
591             Curl_safefree(storefile);
592             if(res) {
593               /* bad globbing */
594               warnf(config, "bad output glob!\n");
595               goto quit_urls;
596             }
597           }
598
599           /* Create the directory hierarchy, if not pre-existent to a multiple
600              file output call */
601
602           if(config->create_dirs || metalink) {
603             res = create_dir_hierarchy(outfile, config->errors);
604             /* create_dir_hierarchy shows error upon CURLE_WRITE_ERROR */
605             if(res == CURLE_WRITE_ERROR)
606               goto quit_urls;
607             if(res) {
608               goto show_error;
609             }
610           }
611
612           if((urlnode->flags & GETOUT_USEREMOTE)
613              && config->content_disposition) {
614             /* Our header callback MIGHT set the filename */
615             DEBUGASSERT(!outs.filename);
616           }
617
618           if(config->resume_from_current) {
619             /* We're told to continue from where we are now. Get the size
620                of the file as it is now and open it for append instead */
621             struct_stat fileinfo;
622             /* VMS -- Danger, the filesize is only valid for stream files */
623             if(0 == stat(outfile, &fileinfo))
624               /* set offset to current file size: */
625               config->resume_from = fileinfo.st_size;
626             else
627               /* let offset be 0 */
628               config->resume_from = 0;
629           }
630
631           if(config->resume_from) {
632 #ifdef __VMS
633             /* open file for output, forcing VMS output format into stream
634                mode which is needed for stat() call above to always work. */
635             FILE *file = fopen(outfile, config->resume_from?"ab":"wb",
636                                "ctx=stm", "rfm=stmlf", "rat=cr", "mrs=0");
637 #else
638             /* open file for output: */
639             FILE *file = fopen(outfile, config->resume_from?"ab":"wb");
640 #endif
641             if(!file) {
642               helpf(config->errors, "Can't open '%s'!\n", outfile);
643               res = CURLE_WRITE_ERROR;
644               goto quit_urls;
645             }
646             outs.fopened = TRUE;
647             outs.stream = file;
648             outs.init = config->resume_from;
649           }
650           else {
651             outs.stream = NULL; /* open when needed */
652           }
653           outs.filename = outfile;
654           outs.s_isreg = TRUE;
655         }
656
657         if(uploadfile && !stdin_upload(uploadfile)) {
658           /*
659            * We have specified a file to upload and it isn't "-".
660            */
661           struct_stat fileinfo;
662
663           this_url = add_file_name_to_url(curl, this_url, uploadfile);
664           if(!this_url) {
665             res = CURLE_OUT_OF_MEMORY;
666             goto show_error;
667           }
668           /* VMS Note:
669            *
670            * Reading binary from files can be a problem...  Only FIXED, VAR
671            * etc WITHOUT implied CC will work Others need a \n appended to a
672            * line
673            *
674            * - Stat gives a size but this is UNRELIABLE in VMS As a f.e. a
675            * fixed file with implied CC needs to have a byte added for every
676            * record processed, this can by derived from Filesize & recordsize
677            * for VARiable record files the records need to be counted!  for
678            * every record add 1 for linefeed and subtract 2 for the record
679            * header for VARIABLE header files only the bare record data needs
680            * to be considered with one appended if implied CC
681            */
682 #ifdef __VMS
683           /* Calculate the real upload site for VMS */
684           infd = -1;
685           if(stat(uploadfile, &fileinfo) == 0) {
686             fileinfo.st_size = VmsSpecialSize(uploadfile, &fileinfo);
687             switch (fileinfo.st_fab_rfm) {
688             case FAB$C_VAR:
689             case FAB$C_VFC:
690             case FAB$C_STMCR:
691               infd = open(uploadfile, O_RDONLY | O_BINARY);
692               break;
693             default:
694               infd = open(uploadfile, O_RDONLY | O_BINARY,
695                           "rfm=stmlf", "ctx=stm");
696             }
697           }
698           if(infd == -1)
699 #else
700           infd = open(uploadfile, O_RDONLY | O_BINARY);
701           if((infd == -1) || fstat(infd, &fileinfo))
702 #endif
703           {
704             helpf(config->errors, "Can't open '%s'!\n", uploadfile);
705             if(infd != -1) {
706               close(infd);
707               infd = STDIN_FILENO;
708             }
709             res = CURLE_READ_ERROR;
710             goto quit_urls;
711           }
712           infdopen = TRUE;
713
714           /* we ignore file size for char/block devices, sockets, etc. */
715           if(S_ISREG(fileinfo.st_mode))
716             uploadfilesize = fileinfo.st_size;
717
718         }
719         else if(uploadfile && stdin_upload(uploadfile)) {
720           /* count to see if there are more than one auth bit set
721              in the authtype field */
722           int authbits = 0;
723           int bitcheck = 0;
724           while(bitcheck < 32) {
725             if(config->authtype & (1UL << bitcheck++)) {
726               authbits++;
727               if(authbits > 1) {
728                 /* more than one, we're done! */
729                 break;
730               }
731             }
732           }
733
734           /*
735            * If the user has also selected --anyauth or --proxy-anyauth
736            * we should warn him/her.
737            */
738           if(config->proxyanyauth || (authbits>1)) {
739             warnf(config,
740                   "Using --anyauth or --proxy-anyauth with upload from stdin"
741                   " involves a big risk of it not working. Use a temporary"
742                   " file or a fixed auth type instead!\n");
743           }
744
745           DEBUGASSERT(infdopen == FALSE);
746           DEBUGASSERT(infd == STDIN_FILENO);
747
748           set_binmode(stdin);
749           if(curlx_strequal(uploadfile, ".")) {
750             if(curlx_nonblock((curl_socket_t)infd, TRUE) < 0)
751               warnf(config,
752                     "fcntl failed on fd=%d: %s\n", infd, strerror(errno));
753           }
754         }
755
756         if(uploadfile && config->resume_from_current)
757           config->resume_from = -1; /* -1 will then force get-it-yourself */
758
759         if(output_expected(this_url, uploadfile)
760            && outs.stream && isatty(fileno(outs.stream)))
761           /* we send the output to a tty, therefore we switch off the progress
762              meter */
763           config->noprogress = config->isatty = TRUE;
764         else {
765           /* progress meter is per download, so restore config
766              values */
767           config->noprogress = orig_noprogress;
768           config->isatty = orig_isatty;
769         }
770
771         if(urlnum > 1 && !(config->mute)) {
772           fprintf(config->errors, "\n[%lu/%lu]: %s --> %s\n",
773                   li+1, urlnum, this_url, outfile ? outfile : "<stdout>");
774           if(separator)
775             printf("%s%s\n", CURLseparator, this_url);
776         }
777         if(httpgetfields) {
778           char *urlbuffer;
779           /* Find out whether the url contains a file name */
780           const char *pc = strstr(this_url, "://");
781           char sep = '?';
782           if(pc)
783             pc += 3;
784           else
785             pc = this_url;
786
787           pc = strrchr(pc, '/'); /* check for a slash */
788
789           if(pc) {
790             /* there is a slash present in the URL */
791
792             if(strchr(pc, '?'))
793               /* Ouch, there's already a question mark in the URL string, we
794                  then append the data with an ampersand separator instead! */
795               sep='&';
796           }
797           /*
798            * Then append ? followed by the get fields to the url.
799            */
800           if(pc)
801             urlbuffer = aprintf("%s%c%s", this_url, sep, httpgetfields);
802           else
803             /* Append  / before the ? to create a well-formed url
804                if the url contains a hostname only
805             */
806             urlbuffer = aprintf("%s/?%s", this_url, httpgetfields);
807
808           if(!urlbuffer) {
809             res = CURLE_OUT_OF_MEMORY;
810             goto show_error;
811           }
812
813           Curl_safefree(this_url); /* free previous URL */
814           this_url = urlbuffer; /* use our new URL instead! */
815         }
816
817         if(!config->errors)
818           config->errors = stderr;
819
820         if((!outfile || !strcmp(outfile, "-")) && !config->use_ascii) {
821           /* We get the output to stdout and we have not got the ASCII/text
822              flag, then set stdout to be binary */
823           set_binmode(stdout);
824         }
825
826         if(config->tcp_nodelay)
827           my_setopt(curl, CURLOPT_TCP_NODELAY, 1L);
828
829         /* where to store */
830         my_setopt(curl, CURLOPT_WRITEDATA, &outs);
831         if(metalink || !config->use_metalink)
832           /* what call to write */
833           my_setopt(curl, CURLOPT_WRITEFUNCTION, tool_write_cb);
834 #ifdef USE_METALINK
835         else
836           /* Set Metalink specific write callback function to parse
837              XML data progressively. */
838           my_setopt(curl, CURLOPT_WRITEFUNCTION, metalink_write_cb);
839 #endif /* USE_METALINK */
840
841         /* for uploads */
842         input.fd = infd;
843         input.config = config;
844         /* Note that if CURLOPT_READFUNCTION is fread (the default), then
845          * lib/telnet.c will Curl_poll() on the input file descriptor
846          * rather then calling the READFUNCTION at regular intervals.
847          * The circumstances in which it is preferable to enable this
848          * behaviour, by omitting to set the READFUNCTION & READDATA options,
849          * have not been determined.
850          */
851         my_setopt(curl, CURLOPT_READDATA, &input);
852         /* what call to read */
853         my_setopt(curl, CURLOPT_READFUNCTION, tool_read_cb);
854
855         /* in 7.18.0, the CURLOPT_SEEKFUNCTION/DATA pair is taking over what
856            CURLOPT_IOCTLFUNCTION/DATA pair previously provided for seeking */
857         my_setopt(curl, CURLOPT_SEEKDATA, &input);
858         my_setopt(curl, CURLOPT_SEEKFUNCTION, tool_seek_cb);
859
860         if(config->recvpersecond)
861           /* tell libcurl to use a smaller sized buffer as it allows us to
862              make better sleeps! 7.9.9 stuff! */
863           my_setopt(curl, CURLOPT_BUFFERSIZE, (long)config->recvpersecond);
864
865         /* size of uploaded file: */
866         if(uploadfilesize != -1)
867           my_setopt(curl, CURLOPT_INFILESIZE_LARGE, uploadfilesize);
868         my_setopt_str(curl, CURLOPT_URL, this_url);     /* what to fetch */
869         my_setopt(curl, CURLOPT_NOPROGRESS, config->noprogress?1L:0L);
870         if(config->no_body) {
871           my_setopt(curl, CURLOPT_NOBODY, 1L);
872           my_setopt(curl, CURLOPT_HEADER, 1L);
873         }
874         /* If --metalink is used, we ignore --include (headers in
875            output) option because mixing headers to the body will
876            confuse XML parser and/or hash check will fail. */
877         else if(!config->use_metalink)
878           my_setopt(curl, CURLOPT_HEADER, config->include_headers?1L:0L);
879
880         if(config->xoauth2_bearer)
881           my_setopt_str(curl, CURLOPT_XOAUTH2_BEARER, config->xoauth2_bearer);
882
883 #if !defined(CURL_DISABLE_PROXY)
884         {
885           /* TODO: Make this a run-time check instead of compile-time one. */
886
887           my_setopt_str(curl, CURLOPT_PROXY, config->proxy);
888           my_setopt_str(curl, CURLOPT_PROXYUSERPWD, config->proxyuserpwd);
889
890           /* new in libcurl 7.3 */
891           my_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, config->proxytunnel?1L:0L);
892
893           /* new in libcurl 7.5 */
894           if(config->proxy)
895             my_setopt_enum(curl, CURLOPT_PROXYTYPE, (long)config->proxyver);
896
897           /* new in libcurl 7.10 */
898           if(config->socksproxy) {
899             my_setopt_str(curl, CURLOPT_PROXY, config->socksproxy);
900             my_setopt_enum(curl, CURLOPT_PROXYTYPE, (long)config->socksver);
901           }
902
903           /* new in libcurl 7.10.6 */
904           if(config->proxyanyauth)
905             my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
906                               (long)CURLAUTH_ANY);
907           else if(config->proxynegotiate)
908             my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
909                               (long)CURLAUTH_GSSNEGOTIATE);
910           else if(config->proxyntlm)
911             my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
912                               (long)CURLAUTH_NTLM);
913           else if(config->proxydigest)
914             my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
915                               (long)CURLAUTH_DIGEST);
916           else if(config->proxybasic)
917             my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
918                               (long)CURLAUTH_BASIC);
919
920           /* new in libcurl 7.19.4 */
921           my_setopt(curl, CURLOPT_NOPROXY, config->noproxy);
922         }
923 #endif
924
925         my_setopt(curl, CURLOPT_FAILONERROR, config->failonerror?1L:0L);
926         my_setopt(curl, CURLOPT_UPLOAD, uploadfile?1L:0L);
927         my_setopt(curl, CURLOPT_DIRLISTONLY, config->dirlistonly?1L:0L);
928         my_setopt(curl, CURLOPT_APPEND, config->ftp_append?1L:0L);
929
930         if(config->netrc_opt)
931           my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_OPTIONAL);
932         else if(config->netrc || config->netrc_file)
933           my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_REQUIRED);
934         else
935           my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_IGNORED);
936
937         if(config->netrc_file)
938           my_setopt(curl, CURLOPT_NETRC_FILE, config->netrc_file);
939
940         my_setopt(curl, CURLOPT_TRANSFERTEXT, config->use_ascii?1L:0L);
941         if(config->login_options)
942           my_setopt_str(curl, CURLOPT_LOGIN_OPTIONS, config->login_options);
943         my_setopt_str(curl, CURLOPT_USERPWD, config->userpwd);
944         my_setopt_str(curl, CURLOPT_RANGE, config->range);
945         my_setopt(curl, CURLOPT_ERRORBUFFER, errorbuffer);
946         my_setopt(curl, CURLOPT_TIMEOUT_MS, (long)(config->timeout * 1000));
947
948         if(built_in_protos & CURLPROTO_HTTP) {
949
950           long postRedir = 0;
951
952           my_setopt(curl, CURLOPT_FOLLOWLOCATION,
953                     config->followlocation?1L:0L);
954           my_setopt(curl, CURLOPT_UNRESTRICTED_AUTH,
955                     config->unrestricted_auth?1L:0L);
956
957           switch(config->httpreq) {
958           case HTTPREQ_SIMPLEPOST:
959             my_setopt_str(curl, CURLOPT_POSTFIELDS,
960                           config->postfields);
961             my_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE,
962                       config->postfieldsize);
963             break;
964           case HTTPREQ_POST:
965             my_setopt_httppost(curl, CURLOPT_HTTPPOST, config->httppost);
966             break;
967           default:
968             break;
969           }
970
971           my_setopt_str(curl, CURLOPT_REFERER, config->referer);
972           my_setopt(curl, CURLOPT_AUTOREFERER, config->autoreferer?1L:0L);
973           my_setopt_str(curl, CURLOPT_USERAGENT, config->useragent);
974           my_setopt_slist(curl, CURLOPT_HTTPHEADER, config->headers);
975
976           /* new in libcurl 7.5 */
977           my_setopt(curl, CURLOPT_MAXREDIRS, config->maxredirs);
978
979           /* new in libcurl 7.9.1 */
980           if(config->httpversion)
981             my_setopt_enum(curl, CURLOPT_HTTP_VERSION, config->httpversion);
982
983           /* new in libcurl 7.10.6 (default is Basic) */
984           if(config->authtype)
985             my_setopt_bitmask(curl, CURLOPT_HTTPAUTH, (long)config->authtype);
986
987           /* curl 7.19.1 (the 301 version existed in 7.18.2),
988              303 was added in 7.26.0 */
989           if(config->post301)
990             postRedir |= CURL_REDIR_POST_301;
991           if(config->post302)
992             postRedir |= CURL_REDIR_POST_302;
993           if(config->post303)
994             postRedir |= CURL_REDIR_POST_303;
995           my_setopt(curl, CURLOPT_POSTREDIR, postRedir);
996
997           /* new in libcurl 7.21.6 */
998           if(config->encoding)
999             my_setopt_str(curl, CURLOPT_ACCEPT_ENCODING, "");
1000
1001           /* new in libcurl 7.21.6 */
1002           if(config->tr_encoding)
1003             my_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1L);
1004
1005         } /* (built_in_protos & CURLPROTO_HTTP) */
1006
1007         my_setopt_str(curl, CURLOPT_FTPPORT, config->ftpport);
1008         my_setopt(curl, CURLOPT_LOW_SPEED_LIMIT,
1009                   config->low_speed_limit);
1010         my_setopt(curl, CURLOPT_LOW_SPEED_TIME, config->low_speed_time);
1011         my_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE,
1012                   config->sendpersecond);
1013         my_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE,
1014                   config->recvpersecond);
1015
1016         if(config->use_resume)
1017           my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, config->resume_from);
1018         else
1019           my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, CURL_OFF_T_C(0));
1020
1021         my_setopt_str(curl, CURLOPT_SSLCERT, config->cert);
1022         my_setopt_str(curl, CURLOPT_SSLCERTTYPE, config->cert_type);
1023         my_setopt_str(curl, CURLOPT_SSLKEY, config->key);
1024         my_setopt_str(curl, CURLOPT_SSLKEYTYPE, config->key_type);
1025         my_setopt_str(curl, CURLOPT_KEYPASSWD, config->key_passwd);
1026
1027         if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
1028
1029           /* SSH and SSL private key uses same command-line option */
1030           /* new in libcurl 7.16.1 */
1031           my_setopt_str(curl, CURLOPT_SSH_PRIVATE_KEYFILE, config->key);
1032           /* new in libcurl 7.16.1 */
1033           my_setopt_str(curl, CURLOPT_SSH_PUBLIC_KEYFILE, config->pubkey);
1034
1035           /* new in libcurl 7.17.1: SSH host key md5 checking allows us
1036              to fail if we are not talking to who we think we should */
1037           my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
1038                         config->hostpubmd5);
1039         }
1040
1041         if(config->cacert)
1042           my_setopt_str(curl, CURLOPT_CAINFO, config->cacert);
1043         if(config->capath)
1044           my_setopt_str(curl, CURLOPT_CAPATH, config->capath);
1045         if(config->crlfile)
1046           my_setopt_str(curl, CURLOPT_CRLFILE, config->crlfile);
1047
1048         if(curlinfo->features & CURL_VERSION_SSL) {
1049           if(config->insecure_ok) {
1050             my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1051             my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
1052           }
1053           else {
1054             my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
1055             /* libcurl default is strict verifyhost -> 2L   */
1056             /* my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); */
1057           }
1058         }
1059
1060         if(built_in_protos & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
1061           if(!config->insecure_ok) {
1062             char *home;
1063             char *file;
1064             res = CURLE_OUT_OF_MEMORY;
1065             home = homedir();
1066             if(home) {
1067               file = aprintf("%s/%sssh/known_hosts", home, DOT_CHAR);
1068               if(file) {
1069                 /* new in curl 7.19.6 */
1070                 res = res_setopt_str(curl, CURLOPT_SSH_KNOWNHOSTS, file);
1071                 curl_free(file);
1072                 if(res == CURLE_UNKNOWN_OPTION)
1073                   /* libssh2 version older than 1.1.1 */
1074                   res = CURLE_OK;
1075               }
1076               Curl_safefree(home);
1077             }
1078             if(res)
1079               goto show_error;
1080           }
1081         }
1082
1083         if(config->no_body || config->remote_time) {
1084           /* no body or use remote time */
1085           my_setopt(curl, CURLOPT_FILETIME, 1L);
1086         }
1087
1088         my_setopt(curl, CURLOPT_CRLF, config->crlf?1L:0L);
1089         my_setopt_slist(curl, CURLOPT_QUOTE, config->quote);
1090         my_setopt_slist(curl, CURLOPT_POSTQUOTE, config->postquote);
1091         my_setopt_slist(curl, CURLOPT_PREQUOTE, config->prequote);
1092
1093 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
1094         {
1095           /* TODO: Make this a run-time check instead of compile-time one. */
1096
1097           if(config->cookie)
1098             my_setopt_str(curl, CURLOPT_COOKIE, config->cookie);
1099
1100           if(config->cookiefile)
1101             my_setopt_str(curl, CURLOPT_COOKIEFILE, config->cookiefile);
1102
1103           /* new in libcurl 7.9 */
1104           if(config->cookiejar)
1105             my_setopt_str(curl, CURLOPT_COOKIEJAR, config->cookiejar);
1106
1107           /* new in libcurl 7.9.7 */
1108           my_setopt(curl, CURLOPT_COOKIESESSION, config->cookiesession?1L:0L);
1109         }
1110 #endif
1111
1112         my_setopt_enum(curl, CURLOPT_SSLVERSION, config->ssl_version);
1113         my_setopt_enum(curl, CURLOPT_TIMECONDITION, (long)config->timecond);
1114         my_setopt(curl, CURLOPT_TIMEVALUE, (long)config->condtime);
1115         my_setopt_str(curl, CURLOPT_CUSTOMREQUEST, config->customrequest);
1116         my_setopt(curl, CURLOPT_STDERR, config->errors);
1117
1118         /* three new ones in libcurl 7.3: */
1119         my_setopt_str(curl, CURLOPT_INTERFACE, config->iface);
1120         my_setopt_str(curl, CURLOPT_KRBLEVEL, config->krblevel);
1121
1122         progressbarinit(&progressbar, config);
1123         if((config->progressmode == CURL_PROGRESS_BAR) &&
1124            !config->noprogress && !config->mute) {
1125           /* we want the alternative style, then we have to implement it
1126              ourselves! */
1127           my_setopt(curl, CURLOPT_XFERINFOFUNCTION, tool_progress_cb);
1128           my_setopt(curl, CURLOPT_XFERINFODATA, &progressbar);
1129         }
1130
1131         /* new in libcurl 7.24.0: */
1132         if(config->dns_servers)
1133           my_setopt_str(curl, CURLOPT_DNS_SERVERS, config->dns_servers);
1134
1135         /* new in libcurl 7.33.0: */
1136         if(config->dns_interface)
1137           my_setopt_str(curl, CURLOPT_DNS_INTERFACE, config->dns_interface);
1138         if(config->dns_ipv4_addr)
1139           my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP4, config->dns_ipv4_addr);
1140         if(config->dns_ipv6_addr)
1141         my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP6, config->dns_ipv6_addr);
1142
1143         /* new in libcurl 7.6.2: */
1144         my_setopt_slist(curl, CURLOPT_TELNETOPTIONS, config->telnet_options);
1145
1146         /* new in libcurl 7.7: */
1147         my_setopt_str(curl, CURLOPT_RANDOM_FILE, config->random_file);
1148         my_setopt_str(curl, CURLOPT_EGDSOCKET, config->egd_file);
1149         my_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
1150                   (long)(config->connecttimeout * 1000));
1151
1152         if(config->cipher_list)
1153           my_setopt_str(curl, CURLOPT_SSL_CIPHER_LIST, config->cipher_list);
1154
1155         /* new in libcurl 7.9.2: */
1156         if(config->disable_epsv)
1157           /* disable it */
1158           my_setopt(curl, CURLOPT_FTP_USE_EPSV, 0L);
1159
1160         /* new in libcurl 7.10.5 */
1161         if(config->disable_eprt)
1162           /* disable it */
1163           my_setopt(curl, CURLOPT_FTP_USE_EPRT, 0L);
1164
1165         if(config->tracetype != TRACE_NONE) {
1166           my_setopt(curl, CURLOPT_DEBUGFUNCTION, tool_debug_cb);
1167           my_setopt(curl, CURLOPT_DEBUGDATA, config);
1168           my_setopt(curl, CURLOPT_VERBOSE, 1L);
1169         }
1170
1171         /* new in curl 7.9.3 */
1172         if(config->engine) {
1173           res = res_setopt_str(curl, CURLOPT_SSLENGINE, config->engine);
1174           if(res)
1175             goto show_error;
1176           my_setopt(curl, CURLOPT_SSLENGINE_DEFAULT, 1L);
1177         }
1178
1179         /* new in curl 7.10.7, extended in 7.19.4 but this only sets 0 or 1 */
1180         my_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS,
1181                   config->ftp_create_dirs?1L:0L);
1182
1183         /* new in curl 7.10.8 */
1184         if(config->max_filesize)
1185           my_setopt(curl, CURLOPT_MAXFILESIZE_LARGE,
1186                     config->max_filesize);
1187
1188         if(4 == config->ip_version)
1189           my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1190         else if(6 == config->ip_version)
1191           my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
1192         else
1193           my_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER);
1194
1195         /* new in curl 7.15.5 */
1196         if(config->ftp_ssl_reqd)
1197           my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
1198
1199         /* new in curl 7.11.0 */
1200         else if(config->ftp_ssl)
1201           my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);
1202
1203         /* new in curl 7.16.0 */
1204         else if(config->ftp_ssl_control)
1205           my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_CONTROL);
1206
1207         /* new in curl 7.16.1 */
1208         if(config->ftp_ssl_ccc)
1209           my_setopt_enum(curl, CURLOPT_FTP_SSL_CCC,
1210                          (long)config->ftp_ssl_ccc_mode);
1211
1212 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1213         {
1214           /* TODO: Make this a run-time check instead of compile-time one. */
1215
1216           /* new in curl 7.19.4 */
1217           if(config->socks5_gssapi_service)
1218             my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_SERVICE,
1219                           config->socks5_gssapi_service);
1220
1221           /* new in curl 7.19.4 */
1222           if(config->socks5_gssapi_nec)
1223             my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_NEC,
1224                           config->socks5_gssapi_nec);
1225         }
1226 #endif
1227         /* curl 7.13.0 */
1228         my_setopt_str(curl, CURLOPT_FTP_ACCOUNT, config->ftp_account);
1229
1230         my_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, config->ignorecl?1L:0L);
1231
1232         /* curl 7.14.2 */
1233         my_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, config->ftp_skip_ip?1L:0L);
1234
1235         /* curl 7.15.1 */
1236         my_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long)config->ftp_filemethod);
1237
1238         /* curl 7.15.2 */
1239         if(config->localport) {
1240           my_setopt(curl, CURLOPT_LOCALPORT, (long)config->localport);
1241           my_setopt_str(curl, CURLOPT_LOCALPORTRANGE,
1242                         (long)config->localportrange);
1243         }
1244
1245         /* curl 7.15.5 */
1246         my_setopt_str(curl, CURLOPT_FTP_ALTERNATIVE_TO_USER,
1247                       config->ftp_alternative_to_user);
1248
1249         /* curl 7.16.0 */
1250         if(config->disable_sessionid)
1251           /* disable it */
1252           my_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE, 0L);
1253
1254         /* curl 7.16.2 */
1255         if(config->raw) {
1256           my_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 0L);
1257           my_setopt(curl, CURLOPT_HTTP_TRANSFER_DECODING, 0L);
1258         }
1259
1260         /* curl 7.17.1 */
1261         if(!config->nokeepalive) {
1262           my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
1263           if(config->alivetime != 0) {
1264 #if !defined(TCP_KEEPIDLE) || !defined(TCP_KEEPINTVL)
1265             warnf(config, "Keep-alive functionality somewhat crippled due to "
1266                 "missing support in your operating system!\n");
1267 #endif
1268             my_setopt(curl, CURLOPT_TCP_KEEPIDLE, config->alivetime);
1269             my_setopt(curl, CURLOPT_TCP_KEEPINTVL, config->alivetime);
1270           }
1271         }
1272         else
1273           my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 0L);
1274
1275         /* curl 7.20.0 */
1276         if(config->tftp_blksize)
1277           my_setopt(curl, CURLOPT_TFTP_BLKSIZE, config->tftp_blksize);
1278
1279         if(config->mail_from)
1280           my_setopt_str(curl, CURLOPT_MAIL_FROM, config->mail_from);
1281
1282         if(config->mail_rcpt)
1283           my_setopt_slist(curl, CURLOPT_MAIL_RCPT, config->mail_rcpt);
1284
1285         /* curl 7.20.x */
1286         if(config->ftp_pret)
1287           my_setopt(curl, CURLOPT_FTP_USE_PRET, 1L);
1288
1289         if(config->proto_present)
1290           my_setopt_flags(curl, CURLOPT_PROTOCOLS, config->proto);
1291         if(config->proto_redir_present)
1292           my_setopt_flags(curl, CURLOPT_REDIR_PROTOCOLS, config->proto_redir);
1293
1294         if(config->content_disposition
1295            && (urlnode->flags & GETOUT_USEREMOTE)
1296            && (checkprefix("http://", this_url) ||
1297                checkprefix("https://", this_url)))
1298           hdrcbdata.honor_cd_filename = TRUE;
1299         else
1300           hdrcbdata.honor_cd_filename = FALSE;
1301
1302         hdrcbdata.outs = &outs;
1303         hdrcbdata.heads = &heads;
1304
1305         my_setopt(curl, CURLOPT_HEADERFUNCTION, tool_header_cb);
1306         my_setopt(curl, CURLOPT_HEADERDATA, &hdrcbdata);
1307
1308         if(config->resolve)
1309           /* new in 7.21.3 */
1310           my_setopt_slist(curl, CURLOPT_RESOLVE, config->resolve);
1311
1312         /* new in 7.21.4 */
1313         if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) {
1314           if(config->tls_username)
1315             my_setopt_str(curl, CURLOPT_TLSAUTH_USERNAME,
1316                           config->tls_username);
1317           if(config->tls_password)
1318             my_setopt_str(curl, CURLOPT_TLSAUTH_PASSWORD,
1319                           config->tls_password);
1320           if(config->tls_authtype)
1321             my_setopt_str(curl, CURLOPT_TLSAUTH_TYPE,
1322                           config->tls_authtype);
1323         }
1324
1325         /* new in 7.22.0 */
1326         if(config->gssapi_delegation)
1327           my_setopt_str(curl, CURLOPT_GSSAPI_DELEGATION,
1328                         config->gssapi_delegation);
1329
1330         /* new in 7.25.0 */
1331         if(config->ssl_allow_beast)
1332           my_setopt(curl, CURLOPT_SSL_OPTIONS, (long)CURLSSLOPT_ALLOW_BEAST);
1333
1334         if(config->mail_auth)
1335           my_setopt_str(curl, CURLOPT_MAIL_AUTH, config->mail_auth);
1336
1337         /* new in 7.31.0 */
1338         if(config->sasl_ir)
1339           my_setopt(curl, CURLOPT_SASL_IR, 1L);
1340
1341         if(config->nonpn) {
1342           my_setopt(curl, CURLOPT_SSL_ENABLE_NPN, 0L);
1343         }
1344
1345         if(config->noalpn) {
1346           my_setopt(curl, CURLOPT_SSL_ENABLE_ALPN, 0L);
1347         }
1348
1349         /* initialize retry vars for loop below */
1350         retry_sleep_default = (config->retry_delay) ?
1351           config->retry_delay*1000L : RETRY_SLEEP_DEFAULT; /* ms */
1352
1353         retry_numretries = config->req_retry;
1354         retry_sleep = retry_sleep_default; /* ms */
1355         retrystart = tvnow();
1356
1357 #ifndef CURL_DISABLE_LIBCURL_OPTION
1358         res = easysrc_perform();
1359         if(res) {
1360           goto show_error;
1361         }
1362 #endif
1363
1364         for(;;) {
1365 #ifdef USE_METALINK
1366           if(!metalink && config->use_metalink) {
1367             /* If outs.metalink_parser is non-NULL, delete it first. */
1368             if(outs.metalink_parser)
1369               metalink_parser_context_delete(outs.metalink_parser);
1370             outs.metalink_parser = metalink_parser_context_new();
1371             if(outs.metalink_parser == NULL) {
1372               res = CURLE_OUT_OF_MEMORY;
1373               goto show_error;
1374             }
1375             fprintf(config->errors, "Metalink: parsing (%s) metalink/XML...\n",
1376                     this_url);
1377           }
1378           else if(metalink)
1379             fprintf(config->errors, "Metalink: fetching (%s) from (%s)...\n",
1380                     mlfile->filename, this_url);
1381 #endif /* USE_METALINK */
1382
1383 #ifdef CURLDEBUG
1384           if(config->test_event_based)
1385             res = curl_easy_perform_ev(curl);
1386           else
1387 #endif
1388           res = curl_easy_perform(curl);
1389
1390           if(outs.is_cd_filename && outs.stream && !config->mute &&
1391              outs.filename)
1392             printf("curl: Saved to filename '%s'\n", outs.filename);
1393
1394           /* if retry-max-time is non-zero, make sure we haven't exceeded the
1395              time */
1396           if(retry_numretries &&
1397              (!config->retry_maxtime ||
1398               (tvdiff(tvnow(), retrystart) <
1399                config->retry_maxtime*1000L)) ) {
1400             enum {
1401               RETRY_NO,
1402               RETRY_TIMEOUT,
1403               RETRY_HTTP,
1404               RETRY_FTP,
1405               RETRY_LAST /* not used */
1406             } retry = RETRY_NO;
1407             long response;
1408             if((CURLE_OPERATION_TIMEDOUT == res) ||
1409                (CURLE_COULDNT_RESOLVE_HOST == res) ||
1410                (CURLE_COULDNT_RESOLVE_PROXY == res) ||
1411                (CURLE_FTP_ACCEPT_TIMEOUT == res))
1412               /* retry timeout always */
1413               retry = RETRY_TIMEOUT;
1414             else if((CURLE_OK == res) ||
1415                     (config->failonerror &&
1416                      (CURLE_HTTP_RETURNED_ERROR == res))) {
1417               /* If it returned OK. _or_ failonerror was enabled and it
1418                  returned due to such an error, check for HTTP transient
1419                  errors to retry on. */
1420               char *effective_url = NULL;
1421               curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
1422               if(effective_url &&
1423                  checkprefix("http", effective_url)) {
1424                 /* This was HTTP(S) */
1425                 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1426
1427                 switch(response) {
1428                 case 500: /* Internal Server Error */
1429                 case 502: /* Bad Gateway */
1430                 case 503: /* Service Unavailable */
1431                 case 504: /* Gateway Timeout */
1432                   retry = RETRY_HTTP;
1433                   /*
1434                    * At this point, we have already written data to the output
1435                    * file (or terminal). If we write to a file, we must rewind
1436                    * or close/re-open the file so that the next attempt starts
1437                    * over from the beginning.
1438                    *
1439                    * TODO: similar action for the upload case. We might need
1440                    * to start over reading from a previous point if we have
1441                    * uploaded something when this was returned.
1442                    */
1443                   break;
1444                 }
1445               }
1446             } /* if CURLE_OK */
1447             else if(res) {
1448               curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1449
1450               if(response/100 == 4)
1451                 /*
1452                  * This is typically when the FTP server only allows a certain
1453                  * amount of users and we are not one of them.  All 4xx codes
1454                  * are transient.
1455                  */
1456                 retry = RETRY_FTP;
1457             }
1458
1459             if(retry) {
1460               static const char * const m[]={
1461                 NULL, "timeout", "HTTP error", "FTP error"
1462               };
1463               warnf(config, "Transient problem: %s "
1464                     "Will retry in %ld seconds. "
1465                     "%ld retries left.\n",
1466                     m[retry], retry_sleep/1000L, retry_numretries);
1467
1468               tool_go_sleep(retry_sleep);
1469               retry_numretries--;
1470               if(!config->retry_delay) {
1471                 retry_sleep *= 2;
1472                 if(retry_sleep > RETRY_SLEEP_MAX)
1473                   retry_sleep = RETRY_SLEEP_MAX;
1474               }
1475               if(outs.bytes && outs.filename) {
1476                 /* We have written data to a output file, we truncate file
1477                  */
1478                 if(!config->mute)
1479                   fprintf(config->errors, "Throwing away %"
1480                           CURL_FORMAT_CURL_OFF_T " bytes\n",
1481                           outs.bytes);
1482                 fflush(outs.stream);
1483                 /* truncate file at the position where we started appending */
1484 #ifdef HAVE_FTRUNCATE
1485                 if(ftruncate( fileno(outs.stream), outs.init)) {
1486                   /* when truncate fails, we can't just append as then we'll
1487                      create something strange, bail out */
1488                   if(!config->mute)
1489                     fprintf(config->errors,
1490                             "failed to truncate, exiting\n");
1491                   res = CURLE_WRITE_ERROR;
1492                   goto quit_urls;
1493                 }
1494                 /* now seek to the end of the file, the position where we
1495                    just truncated the file in a large file-safe way */
1496                 fseek(outs.stream, 0, SEEK_END);
1497 #else
1498                 /* ftruncate is not available, so just reposition the file
1499                    to the location we would have truncated it. This won't
1500                    work properly with large files on 32-bit systems, but
1501                    most of those will have ftruncate. */
1502                 fseek(outs.stream, (long)outs.init, SEEK_SET);
1503 #endif
1504                 outs.bytes = 0; /* clear for next round */
1505               }
1506               continue; /* curl_easy_perform loop */
1507             }
1508           } /* if retry_numretries */
1509           else if(metalink) {
1510             /* Metalink: Decide to try the next resource or
1511                not. Basically, we want to try the next resource if
1512                download was not successful. */
1513             long response;
1514             if(CURLE_OK == res) {
1515               /* TODO We want to try next resource when download was
1516                  not successful. How to know that? */
1517               char *effective_url = NULL;
1518               curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);
1519               if(effective_url &&
1520                  curlx_strnequal(effective_url, "http", 4)) {
1521                 /* This was HTTP(S) */
1522                 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
1523                 if(response != 200 && response != 206) {
1524                   metalink_next_res = 1;
1525                   fprintf(config->errors,
1526                           "Metalink: fetching (%s) from (%s) FAILED "
1527                           "(HTTP status code %d)\n",
1528                           mlfile->filename, this_url, response);
1529                 }
1530               }
1531             }
1532             else {
1533               metalink_next_res = 1;
1534               fprintf(config->errors,
1535                       "Metalink: fetching (%s) from (%s) FAILED (%s)\n",
1536                       mlfile->filename, this_url,
1537                       (errorbuffer[0]) ?
1538                       errorbuffer : curl_easy_strerror((CURLcode)res));
1539             }
1540           }
1541           if(metalink && !metalink_next_res)
1542             fprintf(config->errors, "Metalink: fetching (%s) from (%s) OK\n",
1543                     mlfile->filename, this_url);
1544
1545           /* In all ordinary cases, just break out of loop here */
1546           break; /* curl_easy_perform loop */
1547
1548         }
1549
1550         if((config->progressmode == CURL_PROGRESS_BAR) &&
1551            progressbar.calls)
1552           /* if the custom progress bar has been displayed, we output a
1553              newline here */
1554           fputs("\n", progressbar.out);
1555
1556         if(config->writeout)
1557           ourWriteOut(curl, &outs, config->writeout);
1558
1559         if(config->writeenv)
1560           ourWriteEnv(curl);
1561
1562         /*
1563         ** Code within this loop may jump directly here to label 'show_error'
1564         ** in order to display an error message for CURLcode stored in 'res'
1565         ** variable and exit loop once that necessary writing and cleanup
1566         ** in label 'quit_urls' has been done.
1567         */
1568
1569         show_error:
1570
1571 #ifdef __VMS
1572         if(is_vms_shell()) {
1573           /* VMS DCL shell behavior */
1574           if(!config->showerror)
1575             vms_show = VMSSTS_HIDE;
1576         }
1577         else
1578 #endif
1579         if(res && config->showerror) {
1580           fprintf(config->errors, "curl: (%d) %s\n", res, (errorbuffer[0]) ?
1581                   errorbuffer : curl_easy_strerror((CURLcode)res));
1582           if(res == CURLE_SSL_CACERT)
1583             fprintf(config->errors, "%s%s",
1584                     CURL_CA_CERT_ERRORMSG1, CURL_CA_CERT_ERRORMSG2);
1585         }
1586
1587         /* Fall through comment to 'quit_urls' label */
1588
1589         /*
1590         ** Upon error condition and always that a message has already been
1591         ** displayed, code within this loop may jump directly here to label
1592         ** 'quit_urls' otherwise it should jump to 'show_error' label above.
1593         **
1594         ** When 'res' variable is _not_ CURLE_OK loop will exit once that
1595         ** all code following 'quit_urls' has been executed. Otherwise it
1596         ** will loop to the beginning from where it may exit if there are
1597         ** no more urls left.
1598         */
1599
1600         quit_urls:
1601
1602         /* Set file extended attributes */
1603         if(!res && config->xattr && outs.fopened && outs.stream) {
1604           int rc = fwrite_xattr(curl, fileno(outs.stream));
1605           if(rc)
1606             warnf(config, "Error setting extended attributes: %s\n",
1607                   strerror(errno));
1608         }
1609
1610         /* Close the file */
1611         if(outs.fopened && outs.stream) {
1612           int rc = fclose(outs.stream);
1613           if(!res && rc) {
1614             /* something went wrong in the writing process */
1615             res = CURLE_WRITE_ERROR;
1616             fprintf(config->errors, "(%d) Failed writing body\n", res);
1617           }
1618         }
1619         else if(!outs.s_isreg && outs.stream) {
1620           /* Dump standard stream buffered data */
1621           int rc = fflush(outs.stream);
1622           if(!res && rc) {
1623             /* something went wrong in the writing process */
1624             res = CURLE_WRITE_ERROR;
1625             fprintf(config->errors, "(%d) Failed writing body\n", res);
1626           }
1627         }
1628
1629 #ifdef __AMIGA__
1630         if(!res && outs.s_isreg && outs.filename) {
1631           /* Set the url (up to 80 chars) as comment for the file */
1632           if(strlen(url) > 78)
1633             url[79] = '\0';
1634           SetComment(outs.filename, url);
1635         }
1636 #endif
1637
1638 #ifdef HAVE_UTIME
1639         /* File time can only be set _after_ the file has been closed */
1640         if(!res && config->remote_time && outs.s_isreg && outs.filename) {
1641           /* Ask libcurl if we got a remote file time */
1642           long filetime = -1;
1643           curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
1644           if(filetime >= 0) {
1645             struct utimbuf times;
1646             times.actime = (time_t)filetime;
1647             times.modtime = (time_t)filetime;
1648             utime(outs.filename, &times); /* set the time we got */
1649           }
1650         }
1651 #endif
1652
1653 #ifdef USE_METALINK
1654         if(!metalink && config->use_metalink && res == CURLE_OK) {
1655           int rv = parse_metalink(config, &outs, this_url);
1656           if(rv == 0)
1657             fprintf(config->errors, "Metalink: parsing (%s) OK\n", this_url);
1658           else if(rv == -1)
1659             fprintf(config->errors, "Metalink: parsing (%s) FAILED\n",
1660                     this_url);
1661         }
1662         else if(metalink && res == CURLE_OK && !metalink_next_res) {
1663           int rv = metalink_check_hash(config, mlfile, outs.filename);
1664           if(rv == 0) {
1665             metalink_next_res = 1;
1666           }
1667         }
1668 #endif /* USE_METALINK */
1669
1670         /* No more business with this output struct */
1671         if(outs.alloc_filename)
1672           Curl_safefree(outs.filename);
1673 #ifdef USE_METALINK
1674         if(outs.metalink_parser)
1675           metalink_parser_context_delete(outs.metalink_parser);
1676 #endif /* USE_METALINK */
1677         memset(&outs, 0, sizeof(struct OutStruct));
1678         hdrcbdata.outs = NULL;
1679
1680         /* Free loop-local allocated memory and close loop-local opened fd */
1681
1682         Curl_safefree(outfile);
1683         Curl_safefree(this_url);
1684
1685         if(infdopen)
1686           close(infd);
1687
1688         if(metalink) {
1689           /* Should exit if error is fatal. */
1690           if(is_fatal_error(res)) {
1691             break;
1692           }
1693           if(!metalink_next_res)
1694             break;
1695           mlres = mlres->next;
1696           if(mlres == NULL)
1697             /* TODO If metalink_next_res is 1 and mlres is NULL,
1698              * set res to error code
1699              */
1700             break;
1701         }
1702         else
1703         if(urlnum > 1) {
1704           /* when url globbing, exit loop upon critical error */
1705           if(is_fatal_error(res))
1706             break;
1707         }
1708         else if(res)
1709           /* when not url globbing, exit loop upon any error */
1710           break;
1711
1712       } /* loop to the next URL */
1713
1714       /* Free loop-local allocated memory */
1715
1716       Curl_safefree(uploadfile);
1717
1718       if(urls) {
1719         /* Free list of remaining URLs */
1720         glob_cleanup(urls);
1721         urls = NULL;
1722       }
1723
1724       if(infilenum > 1) {
1725         /* when file globbing, exit loop upon critical error */
1726         if(is_fatal_error(res))
1727           break;
1728       }
1729       else if(res)
1730         /* when not file globbing, exit loop upon any error */
1731         break;
1732
1733     } /* loop to the next globbed upload file */
1734
1735     /* Free loop-local allocated memory */
1736
1737     Curl_safefree(outfiles);
1738
1739     if(inglob) {
1740       /* Free list of globbed upload files */
1741       glob_cleanup(inglob);
1742       inglob = NULL;
1743     }
1744
1745     /* Free this URL node data without destroying the
1746        the node itself nor modifying next pointer. */
1747     Curl_safefree(urlnode->url);
1748     Curl_safefree(urlnode->outfile);
1749     Curl_safefree(urlnode->infile);
1750     urlnode->flags = 0;
1751
1752     /*
1753     ** Bail out upon critical errors
1754     */
1755     if(is_fatal_error(res))
1756       goto quit_curl;
1757
1758   } /* for-loop through all URLs */
1759
1760   /*
1761   ** Nested loops end here.
1762   */
1763
1764   quit_curl:
1765
1766   /* Free function-local referenced allocated memory */
1767   Curl_safefree(httpgetfields);
1768
1769   /* Free list of given URLs */
1770   clean_getout(config);
1771
1772 #ifndef CURL_DISABLE_LIBCURL_OPTION
1773   easysrc_cleanup();
1774 #endif
1775
1776   hdrcbdata.heads = NULL;
1777
1778   /* Close function-local opened file descriptors */
1779
1780   if(heads.fopened && heads.stream)
1781     fclose(heads.stream);
1782   if(heads.alloc_filename)
1783     Curl_safefree(heads.filename);
1784
1785 #ifndef CURL_DISABLE_LIBCURL_OPTION
1786   /* Dump the libcurl code if previously enabled.
1787      NOTE: that this function relies on config->errors amongst other things
1788      so not everything can be closed and cleaned before this is called */
1789   dumpeasysrc(config);
1790 #endif
1791
1792   return (CURLcode)res;
1793 }
1794
1795 static void operate_free(struct Configurable *config)
1796 {
1797   if(config->easy) {
1798     curl_easy_cleanup(config->easy);
1799     config->easy = NULL;
1800   }
1801
1802   /* Release metalink related resources here */
1803   clean_metalink(config);
1804 }
1805
1806 CURLcode operate(struct Configurable *config, int argc, argv_item_t argv[])
1807 {
1808   CURLcode result = CURLE_OK;
1809
1810   /* Initialize the easy interface */
1811   result = operate_init(config);
1812   if(result)
1813     return result;
1814
1815   /* Parse .curlrc if necessary */
1816   if((argc == 1) || (!curlx_strequal(argv[1], "-q"))) {
1817     parseconfig(NULL, config); /* ignore possible failure */
1818
1819     /* If we had no arguments then make sure a url was specified in .curlrc */
1820     if((argc < 2) && (!config->url_list)) {
1821       helpf(config->errors, NULL);
1822       result = CURLE_FAILED_INIT;
1823     }
1824   }
1825
1826   if(!result) {
1827     /* Parse the command line arguments */
1828     ParameterError res = parse_args(config, argc, argv);
1829     if(res) {
1830       result = CURLE_OK;
1831
1832       /* Check if we were asked for the help */
1833       if(res == PARAM_HELP_REQUESTED)
1834         tool_help();
1835       /* Check if we were asked for the manual */
1836       else if(res == PARAM_MANUAL_REQUESTED)
1837         hugehelp();
1838       /* Check if we were asked for the version information */
1839       else if(res == PARAM_VERSION_INFO_REQUESTED)
1840         tool_version_info();
1841       /* Check if we were asked to list the SSL engines */
1842       else if(res == PARAM_ENGINES_REQUESTED)
1843         tool_list_engines(config->easy);
1844       else
1845         result = CURLE_FAILED_INIT;
1846     }
1847     /* Perform the main operations */
1848     else {
1849       size_t count = 0;
1850       struct Configurable *operation = config;
1851
1852       /* Get the required aguments for each operation */
1853       while(!result && operation) {
1854         result = get_args(operation, count++);
1855
1856         operation = operation->next;
1857       }
1858
1859       /* Reset the operation pointer */
1860       operation = config;
1861
1862       /* Perform each operation */
1863       while(!result && operation) {
1864         result = operate_do(operation);
1865
1866         operation = operation->next;
1867       }
1868     }
1869   }
1870
1871   /* Perform the cleanup */
1872   operate_free(config);
1873
1874   return result;
1875 }