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