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