1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22 #include "tool_setup.h"
23 
24 #include "strcase.h"
25 
26 #define ENABLE_CURLX_PRINTF
27 /* use our own printf() functions */
28 #include "curlx.h"
29 
30 #include "tool_cfgable.h"
31 #include "tool_doswin.h"
32 #include "tool_msgs.h"
33 #include "tool_cb_hdr.h"
34 #include "tool_cb_wrt.h"
35 #include "tool_operate.h"
36 
37 #include "memdebug.h" /* keep this as LAST include */
38 
39 static char *parse_filename(const char *ptr, size_t len);
40 
41 #ifdef WIN32
42 #define BOLD
43 #define BOLDOFF
44 #else
45 #define BOLD "\x1b[1m"
46 /* Switch off bold by setting "all attributes off" since the explicit
47    bold-off code (21) isn't supported everywhere - like in the mac
48    Terminal. */
49 #define BOLDOFF "\x1b[0m"
50 #endif
51 
52 /*
53 ** callback for CURLOPT_HEADERFUNCTION
54 */
55 
tool_header_cb(char * ptr,size_t size,size_t nmemb,void * userdata)56 size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata)
57 {
58   struct per_transfer *per = userdata;
59   struct HdrCbData *hdrcbdata = &per->hdrcbdata;
60   struct OutStruct *outs = &per->outs;
61   struct OutStruct *heads = &per->heads;
62   struct OutStruct *etag_save = &per->etag_save;
63   const char *str = ptr;
64   const size_t cb = size * nmemb;
65   const char *end = (char *)ptr + cb;
66   long protocol = 0;
67 
68   /*
69    * Once that libcurl has called back tool_header_cb() the returned value
70    * is checked against the amount that was intended to be written, if
71    * it does not match then it fails with CURLE_WRITE_ERROR. So at this
72    * point returning a value different from sz*nmemb indicates failure.
73    */
74   size_t failure = (size && nmemb) ? 0 : 1;
75 
76   if(!heads->config)
77     return failure;
78 
79 #ifdef DEBUGBUILD
80   if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
81     warnf(heads->config->global, "Header data exceeds single call write "
82           "limit!\n");
83     return failure;
84   }
85 #endif
86 
87   /*
88    * Write header data when curl option --dump-header (-D) is given.
89    */
90 
91   if(heads->config->headerfile && heads->stream) {
92     size_t rc = fwrite(ptr, size, nmemb, heads->stream);
93     if(rc != cb)
94       return rc;
95     /* flush the stream to send off what we got earlier */
96     (void)fflush(heads->stream);
97   }
98 
99   /*
100    * Write etag to file when --etag-save option is given.
101    * etag string that we want is enveloped in double quotes
102    */
103   if(etag_save->config->etag_save_file && etag_save->stream) {
104     /* match only header that start with etag (case insensitive) */
105     if(curl_strnequal(str, "etag:", 5)) {
106       char *etag_h = NULL;
107       char *first = NULL;
108       char *last = NULL;
109       size_t etag_length = 0;
110 
111       etag_h = ptr;
112       /* point to first occurence of double quote */
113       first = memchr(etag_h, '\"', cb);
114 
115       /*
116        * if server side messed with the etag header and doesn't include
117        * double quotes around the etag, kindly exit with a warning
118        */
119 
120       if(!first) {
121         warnf(
122           etag_save->config->global,
123           "\nReceived header etag is missing double quote/s\n");
124         return 1;
125       }
126       else {
127         /* discard first double quote */
128         first++;
129       }
130 
131       /* point to last occurence of double quote */
132       last = memchr(first, '\"', cb);
133 
134       if(!last) {
135         warnf(
136           etag_save->config->global,
137           "\nReceived header etag is missing double quote/s\n");
138         return 1;
139       }
140 
141       /* get length of desired etag */
142       etag_length = (size_t)last - (size_t)first;
143 
144       fwrite(first, size, etag_length, etag_save->stream);
145       /* terminate with new line */
146       fputc('\n', etag_save->stream);
147     }
148 
149     (void)fflush(etag_save->stream);
150   }
151 
152   /*
153    * This callback sets the filename where output shall be written when
154    * curl options --remote-name (-O) and --remote-header-name (-J) have
155    * been simultaneously given and additionally server returns an HTTP
156    * Content-Disposition header specifying a filename property.
157    */
158 
159   curl_easy_getinfo(per->curl, CURLINFO_PROTOCOL, &protocol);
160   if(hdrcbdata->honor_cd_filename &&
161      (cb > 20) && checkprefix("Content-disposition:", str) &&
162      (protocol & (CURLPROTO_HTTPS|CURLPROTO_HTTP))) {
163     const char *p = str + 20;
164 
165     /* look for the 'filename=' parameter
166        (encoded filenames (*=) are not supported) */
167     for(;;) {
168       char *filename;
169       size_t len;
170 
171       while(*p && (p < end) && !ISALPHA(*p))
172         p++;
173       if(p > end - 9)
174         break;
175 
176       if(memcmp(p, "filename=", 9)) {
177         /* no match, find next parameter */
178         while((p < end) && (*p != ';'))
179           p++;
180         continue;
181       }
182       p += 9;
183 
184       /* this expression below typecasts 'cb' only to avoid
185          warning: signed and unsigned type in conditional expression
186       */
187       len = (ssize_t)cb - (p - str);
188       filename = parse_filename(p, len);
189       if(filename) {
190         if(outs->stream) {
191           int rc;
192           /* already opened and possibly written to */
193           if(outs->fopened)
194             fclose(outs->stream);
195           outs->stream = NULL;
196 
197           /* rename the initial file name to the new file name */
198           rc = rename(outs->filename, filename);
199           if(rc != 0) {
200             warnf(outs->config->global, "Failed to rename %s -> %s: %s\n",
201                   outs->filename, filename, strerror(errno));
202           }
203           if(outs->alloc_filename)
204             Curl_safefree(outs->filename);
205           if(rc != 0) {
206             free(filename);
207             return failure;
208           }
209         }
210         outs->is_cd_filename = TRUE;
211         outs->s_isreg = TRUE;
212         outs->fopened = FALSE;
213         outs->filename = filename;
214         outs->alloc_filename = TRUE;
215         hdrcbdata->honor_cd_filename = FALSE; /* done now! */
216         if(!tool_create_output_file(outs))
217           return failure;
218       }
219       break;
220     }
221     if(!outs->stream && !tool_create_output_file(outs))
222       return failure;
223   }
224 
225   if(hdrcbdata->config->show_headers &&
226     (protocol &
227      (CURLPROTO_HTTP|CURLPROTO_HTTPS|CURLPROTO_RTSP|CURLPROTO_FILE))) {
228     /* bold headers only for selected protocols */
229     char *value = NULL;
230 
231     if(!outs->stream && !tool_create_output_file(outs))
232       return failure;
233 
234     if(hdrcbdata->global->isatty && hdrcbdata->global->styled_output)
235       value = memchr(ptr, ':', cb);
236     if(value) {
237       size_t namelen = value - ptr;
238       fprintf(outs->stream, BOLD "%.*s" BOLDOFF ":", namelen, ptr);
239       fwrite(&value[1], cb - namelen - 1, 1, outs->stream);
240     }
241     else
242       /* not "handled", just show it */
243       fwrite(ptr, cb, 1, outs->stream);
244   }
245   return cb;
246 }
247 
248 /*
249  * Copies a file name part and returns an ALLOCATED data buffer.
250  */
parse_filename(const char * ptr,size_t len)251 static char *parse_filename(const char *ptr, size_t len)
252 {
253   char *copy;
254   char *p;
255   char *q;
256   char  stop = '\0';
257 
258   /* simple implementation of strndup() */
259   copy = malloc(len + 1);
260   if(!copy)
261     return NULL;
262   memcpy(copy, ptr, len);
263   copy[len] = '\0';
264 
265   p = copy;
266   if(*p == '\'' || *p == '"') {
267     /* store the starting quote */
268     stop = *p;
269     p++;
270   }
271   else
272     stop = ';';
273 
274   /* scan for the end letter and stop there */
275   q = strchr(p, stop);
276   if(q)
277     *q = '\0';
278 
279   /* if the filename contains a path, only use filename portion */
280   q = strrchr(p, '/');
281   if(q) {
282     p = q + 1;
283     if(!*p) {
284       Curl_safefree(copy);
285       return NULL;
286     }
287   }
288 
289   /* If the filename contains a backslash, only use filename portion. The idea
290      is that even systems that don't handle backslashes as path separators
291      probably want the path removed for convenience. */
292   q = strrchr(p, '\\');
293   if(q) {
294     p = q + 1;
295     if(!*p) {
296       Curl_safefree(copy);
297       return NULL;
298     }
299   }
300 
301   /* make sure the file name doesn't end in \r or \n */
302   q = strchr(p, '\r');
303   if(q)
304     *q = '\0';
305 
306   q = strchr(p, '\n');
307   if(q)
308     *q = '\0';
309 
310   if(copy != p)
311     memmove(copy, p, strlen(p) + 1);
312 
313 #if defined(MSDOS) || defined(WIN32)
314   {
315     char *sanitized;
316     SANITIZEcode sc = sanitize_file_name(&sanitized, copy, 0);
317     Curl_safefree(copy);
318     if(sc)
319       return NULL;
320     copy = sanitized;
321   }
322 #endif /* MSDOS || WIN32 */
323 
324   /* in case we built debug enabled, we allow an environment variable
325    * named CURL_TESTDIR to prefix the given file name to put it into a
326    * specific directory
327    */
328 #ifdef DEBUGBUILD
329   {
330     char *tdir = curlx_getenv("CURL_TESTDIR");
331     if(tdir) {
332       char buffer[512]; /* suitably large */
333       msnprintf(buffer, sizeof(buffer), "%s/%s", tdir, copy);
334       Curl_safefree(copy);
335       copy = strdup(buffer); /* clone the buffer, we don't use the libcurl
336                                 aprintf() or similar since we want to use the
337                                 same memory code as the "real" parse_filename
338                                 function */
339       curl_free(tdir);
340     }
341   }
342 #endif
343 
344   return copy;
345 }
346