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