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