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