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