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