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