1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 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.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 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24 #include "tool_setup.h"
25
26 #include "strcase.h"
27
28 #define ENABLE_CURLX_PRINTF
29 /* use our own printf() functions */
30 #include "curlx.h"
31
32 #include "tool_cfgable.h"
33 #include "tool_doswin.h"
34 #include "tool_msgs.h"
35 #include "tool_cb_hdr.h"
36 #include "tool_cb_wrt.h"
37 #include "tool_operate.h"
38 #include "tool_libinfo.h"
39
40 #include "memdebug.h" /* keep this as LAST include */
41
42 static char *parse_filename(const char *ptr, size_t len);
43
44 #ifdef WIN32
45 #define BOLD
46 #define BOLDOFF
47 #else
48 #define BOLD "\x1b[1m"
49 /* Switch off bold by setting "all attributes off" since the explicit
50 bold-off code (21) isn't supported everywhere - like in the mac
51 Terminal. */
52 #define BOLDOFF "\x1b[0m"
53 /* OSC 8 hyperlink escape sequence */
54 #define LINK "\x1b]8;;"
55 #define LINKST "\x1b\\"
56 #define LINKOFF LINK LINKST
57 #endif
58
59 #ifdef LINK
60 static void write_linked_location(CURL *curl, const char *location,
61 size_t loclen, FILE *stream);
62 #endif
63
64 /*
65 ** callback for CURLOPT_HEADERFUNCTION
66 */
67
tool_header_cb(char * ptr,size_t size,size_t nmemb,void * userdata)68 size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata)
69 {
70 struct per_transfer *per = userdata;
71 struct HdrCbData *hdrcbdata = &per->hdrcbdata;
72 struct OutStruct *outs = &per->outs;
73 struct OutStruct *heads = &per->heads;
74 struct OutStruct *etag_save = &per->etag_save;
75 const char *str = ptr;
76 const size_t cb = size * nmemb;
77 const char *end = (char *)ptr + cb;
78 const char *scheme = NULL;
79
80 if(!per->config)
81 return CURL_WRITEFUNC_ERROR;
82
83 #ifdef DEBUGBUILD
84 if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
85 warnf(per->config->global, "Header data exceeds single call write "
86 "limit!\n");
87 return CURL_WRITEFUNC_ERROR;
88 }
89 #endif
90
91 /*
92 * Write header data when curl option --dump-header (-D) is given.
93 */
94
95 if(per->config->headerfile && heads->stream) {
96 size_t rc = fwrite(ptr, size, nmemb, heads->stream);
97 if(rc != cb)
98 return rc;
99 /* flush the stream to send off what we got earlier */
100 (void)fflush(heads->stream);
101 }
102
103 /*
104 * Write etag to file when --etag-save option is given.
105 */
106 if(per->config->etag_save_file && etag_save->stream) {
107 /* match only header that start with etag (case insensitive) */
108 if(curl_strnequal(str, "etag:", 5)) {
109 const char *etag_h = &str[5];
110 const char *eot = end - 1;
111 if(*eot == '\n') {
112 while(ISBLANK(*etag_h) && (etag_h < eot))
113 etag_h++;
114 while(ISSPACE(*eot))
115 eot--;
116
117 if(eot >= etag_h) {
118 size_t etag_length = eot - etag_h + 1;
119 fwrite(etag_h, size, etag_length, etag_save->stream);
120 /* terminate with newline */
121 fputc('\n', etag_save->stream);
122 (void)fflush(etag_save->stream);
123 }
124 }
125 }
126 }
127
128 /*
129 * This callback sets the filename where output shall be written when
130 * curl options --remote-name (-O) and --remote-header-name (-J) have
131 * been simultaneously given and additionally server returns an HTTP
132 * Content-Disposition header specifying a filename property.
133 */
134
135 curl_easy_getinfo(per->curl, CURLINFO_SCHEME, &scheme);
136 scheme = proto_token(scheme);
137 if(hdrcbdata->honor_cd_filename &&
138 (cb > 20) && checkprefix("Content-disposition:", str) &&
139 (scheme == proto_http || scheme == proto_https)) {
140 const char *p = str + 20;
141
142 /* look for the 'filename=' parameter
143 (encoded filenames (*=) are not supported) */
144 for(;;) {
145 char *filename;
146 size_t len;
147
148 while(*p && (p < end) && !ISALPHA(*p))
149 p++;
150 if(p > end - 9)
151 break;
152
153 if(memcmp(p, "filename=", 9)) {
154 /* no match, find next parameter */
155 while((p < end) && (*p != ';'))
156 p++;
157 continue;
158 }
159 p += 9;
160
161 /* this expression below typecasts 'cb' only to avoid
162 warning: signed and unsigned type in conditional expression
163 */
164 len = (ssize_t)cb - (p - str);
165 filename = parse_filename(p, len);
166 if(filename) {
167 if(outs->stream) {
168 /* indication of problem, get out! */
169 free(filename);
170 return CURL_WRITEFUNC_ERROR;
171 }
172
173 outs->is_cd_filename = TRUE;
174 outs->s_isreg = TRUE;
175 outs->fopened = FALSE;
176 outs->filename = filename;
177 outs->alloc_filename = TRUE;
178 hdrcbdata->honor_cd_filename = FALSE; /* done now! */
179 if(!tool_create_output_file(outs, per->config))
180 return CURL_WRITEFUNC_ERROR;
181 }
182 break;
183 }
184 if(!outs->stream && !tool_create_output_file(outs, per->config))
185 return CURL_WRITEFUNC_ERROR;
186 }
187 if(hdrcbdata->config->writeout) {
188 char *value = memchr(ptr, ':', cb);
189 if(value) {
190 if(per->was_last_header_empty)
191 per->num_headers = 0;
192 per->was_last_header_empty = FALSE;
193 per->num_headers++;
194 }
195 else if(ptr[0] == '\r' || ptr[0] == '\n')
196 per->was_last_header_empty = TRUE;
197 }
198 if(hdrcbdata->config->show_headers &&
199 (scheme == proto_http || scheme == proto_https ||
200 scheme == proto_rtsp || scheme == proto_file)) {
201 /* bold headers only for selected protocols */
202 char *value = NULL;
203
204 if(!outs->stream && !tool_create_output_file(outs, per->config))
205 return CURL_WRITEFUNC_ERROR;
206
207 if(hdrcbdata->global->isatty && hdrcbdata->global->styled_output)
208 value = memchr(ptr, ':', cb);
209 if(value) {
210 size_t namelen = value - ptr;
211 fprintf(outs->stream, BOLD "%.*s" BOLDOFF ":", namelen, ptr);
212 #ifndef LINK
213 fwrite(&value[1], cb - namelen - 1, 1, outs->stream);
214 #else
215 if(curl_strnequal("Location", ptr, namelen)) {
216 write_linked_location(per->curl, &value[1], cb - namelen - 1,
217 outs->stream);
218 }
219 else
220 fwrite(&value[1], cb - namelen - 1, 1, outs->stream);
221 #endif
222 }
223 else
224 /* not "handled", just show it */
225 fwrite(ptr, cb, 1, outs->stream);
226 }
227 return cb;
228 }
229
230 /*
231 * Copies a file name part and returns an ALLOCATED data buffer.
232 */
parse_filename(const char * ptr,size_t len)233 static char *parse_filename(const char *ptr, size_t len)
234 {
235 char *copy;
236 char *p;
237 char *q;
238 char stop = '\0';
239
240 /* simple implementation of strndup() */
241 copy = malloc(len + 1);
242 if(!copy)
243 return NULL;
244 memcpy(copy, ptr, len);
245 copy[len] = '\0';
246
247 p = copy;
248 if(*p == '\'' || *p == '"') {
249 /* store the starting quote */
250 stop = *p;
251 p++;
252 }
253 else
254 stop = ';';
255
256 /* scan for the end letter and stop there */
257 q = strchr(p, stop);
258 if(q)
259 *q = '\0';
260
261 /* if the filename contains a path, only use filename portion */
262 q = strrchr(p, '/');
263 if(q) {
264 p = q + 1;
265 if(!*p) {
266 Curl_safefree(copy);
267 return NULL;
268 }
269 }
270
271 /* If the filename contains a backslash, only use filename portion. The idea
272 is that even systems that don't handle backslashes as path separators
273 probably want the path removed for convenience. */
274 q = strrchr(p, '\\');
275 if(q) {
276 p = q + 1;
277 if(!*p) {
278 Curl_safefree(copy);
279 return NULL;
280 }
281 }
282
283 /* make sure the file name doesn't end in \r or \n */
284 q = strchr(p, '\r');
285 if(q)
286 *q = '\0';
287
288 q = strchr(p, '\n');
289 if(q)
290 *q = '\0';
291
292 if(copy != p)
293 memmove(copy, p, strlen(p) + 1);
294
295 #if defined(MSDOS) || defined(WIN32)
296 {
297 char *sanitized;
298 SANITIZEcode sc = sanitize_file_name(&sanitized, copy, 0);
299 Curl_safefree(copy);
300 if(sc)
301 return NULL;
302 copy = sanitized;
303 }
304 #endif /* MSDOS || WIN32 */
305
306 /* in case we built debug enabled, we allow an environment variable
307 * named CURL_TESTDIR to prefix the given file name to put it into a
308 * specific directory
309 */
310 #ifdef DEBUGBUILD
311 {
312 char *tdir = curlx_getenv("CURL_TESTDIR");
313 if(tdir) {
314 char buffer[512]; /* suitably large */
315 msnprintf(buffer, sizeof(buffer), "%s/%s", tdir, copy);
316 Curl_safefree(copy);
317 copy = strdup(buffer); /* clone the buffer, we don't use the libcurl
318 aprintf() or similar since we want to use the
319 same memory code as the "real" parse_filename
320 function */
321 curl_free(tdir);
322 }
323 }
324 #endif
325
326 return copy;
327 }
328
329 #ifdef LINK
330 /*
331 * Treat the Location: header specially, by writing a special escape
332 * sequence that adds a hyperlink to the displayed text. This makes
333 * the absolute URL of the redirect clickable in supported terminals,
334 * which couldn't happen otherwise for relative URLs. The Location:
335 * header is supposed to always be absolute so this theoretically
336 * shouldn't be needed but the real world returns plenty of relative
337 * URLs here.
338 */
339 static
write_linked_location(CURL * curl,const char * location,size_t loclen,FILE * stream)340 void write_linked_location(CURL *curl, const char *location, size_t loclen,
341 FILE *stream) {
342 /* This would so simple if CURLINFO_REDIRECT_URL were available here */
343 CURLU *u = NULL;
344 char *copyloc = NULL, *locurl = NULL, *scheme = NULL, *finalurl = NULL;
345 const char *loc = location;
346 size_t llen = loclen;
347
348 /* Strip leading whitespace of the redirect URL */
349 while(llen && *loc == ' ') {
350 ++loc;
351 --llen;
352 }
353
354 /* Strip the trailing end-of-line characters, normally "\r\n" */
355 while(llen && (loc[llen-1] == '\n' || loc[llen-1] == '\r'))
356 --llen;
357
358 /* CURLU makes it easy to handle the relative URL case */
359 u = curl_url();
360 if(!u)
361 goto locout;
362
363 /* Create a NUL-terminated and whitespace-stripped copy of Location: */
364 copyloc = malloc(llen + 1);
365 if(!copyloc)
366 goto locout;
367 memcpy(copyloc, loc, llen);
368 copyloc[llen] = 0;
369
370 /* The original URL to use as a base for a relative redirect URL */
371 if(curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &locurl))
372 goto locout;
373 if(curl_url_set(u, CURLUPART_URL, locurl, 0))
374 goto locout;
375
376 /* Redirected location. This can be either absolute or relative. */
377 if(curl_url_set(u, CURLUPART_URL, copyloc, 0))
378 goto locout;
379
380 if(curl_url_get(u, CURLUPART_URL, &finalurl, CURLU_NO_DEFAULT_PORT))
381 goto locout;
382
383 if(curl_url_get(u, CURLUPART_SCHEME, &scheme, 0))
384 goto locout;
385
386 if(!strcmp("http", scheme) ||
387 !strcmp("https", scheme) ||
388 !strcmp("ftp", scheme) ||
389 !strcmp("ftps", scheme)) {
390 fprintf(stream, LINK "%s" LINKST "%.*s" LINKOFF,
391 finalurl, loclen, location);
392 goto locdone;
393 }
394
395 /* Not a "safe" URL: don't linkify it */
396
397 locout:
398 /* Write the normal output in case of error or unsafe */
399 fwrite(location, loclen, 1, stream);
400
401 locdone:
402 if(u) {
403 curl_free(finalurl);
404 curl_free(scheme);
405 curl_url_cleanup(u);
406 free(copyloc);
407 }
408 }
409 #endif
410