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