Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/pkg
Path: blob/main/external/curl/src/tool_cb_hdr.c
2649 views
1
/***************************************************************************
2
* _ _ ____ _
3
* Project ___| | | | _ \| |
4
* / __| | | | |_) | |
5
* | (__| |_| | _ <| |___
6
* \___|\___/|_| \_\_____|
7
*
8
* Copyright (C) Daniel Stenberg, <[email protected]>, 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
#ifdef HAVE_UNISTD_H
27
#include <unistd.h>
28
#endif
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
#include "tool_libinfo.h"
37
#include "tool_strdup.h"
38
39
#include "memdebug.h" /* keep this as LAST include */
40
41
static char *parse_filename(const char *ptr, size_t len);
42
43
#ifdef _WIN32
44
#define BOLD "\x1b[1m"
45
#define BOLDOFF "\x1b[22m"
46
#else
47
#define BOLD "\x1b[1m"
48
/* Switch off bold by setting "all attributes off" since the explicit
49
bold-off code (21) is not supported everywhere - like in the mac
50
Terminal. */
51
#define BOLDOFF "\x1b[0m"
52
/* OSC 8 hyperlink escape sequence */
53
#define LINK "\x1b]8;;"
54
#define LINKST "\x1b\\"
55
#define LINKOFF LINK LINKST
56
#endif
57
58
#ifdef LINK
59
static void write_linked_location(CURL *curl, const char *location,
60
size_t loclen, FILE *stream);
61
#endif
62
63
int tool_write_headers(struct HdrCbData *hdrcbdata, FILE *stream)
64
{
65
struct curl_slist *h = hdrcbdata->headlist;
66
int rc = 1;
67
while(h) {
68
/* not "handled", just show it */
69
size_t len = strlen(h->data);
70
if(len != fwrite(h->data, 1, len, stream))
71
goto fail;
72
h = h->next;
73
}
74
rc = 0; /* success */
75
fail:
76
curl_slist_free_all(hdrcbdata->headlist);
77
hdrcbdata->headlist = NULL;
78
return rc;
79
}
80
81
82
/*
83
** callback for CURLOPT_HEADERFUNCTION
84
*
85
* 'size' is always 1
86
*/
87
size_t tool_header_cb(char *ptr, size_t size, size_t nmemb, void *userdata)
88
{
89
struct per_transfer *per = userdata;
90
struct HdrCbData *hdrcbdata = &per->hdrcbdata;
91
struct OutStruct *outs = &per->outs;
92
struct OutStruct *heads = &per->heads;
93
struct OutStruct *etag_save = &per->etag_save;
94
const char *str = ptr;
95
const size_t cb = size * nmemb;
96
const char *end = (char *)ptr + cb;
97
const char *scheme = NULL;
98
99
if(!per->config)
100
return CURL_WRITEFUNC_ERROR;
101
102
#ifdef DEBUGBUILD
103
if(size * nmemb > (size_t)CURL_MAX_HTTP_HEADER) {
104
warnf("Header data exceeds write limit");
105
return CURL_WRITEFUNC_ERROR;
106
}
107
#endif
108
109
#ifdef _WIN32
110
/* Discard incomplete UTF-8 sequence buffered from body */
111
if(outs->utf8seq[0])
112
memset(outs->utf8seq, 0, sizeof(outs->utf8seq));
113
#endif
114
115
/*
116
* Write header data when curl option --dump-header (-D) is given.
117
*/
118
119
if(per->config->headerfile && heads->stream) {
120
size_t rc = fwrite(ptr, size, nmemb, heads->stream);
121
if(rc != nmemb)
122
return rc;
123
/* flush the stream to send off what we got earlier */
124
if(fflush(heads->stream)) {
125
errorf("Failed writing headers to %s", per->config->headerfile);
126
return CURL_WRITEFUNC_ERROR;
127
}
128
}
129
130
curl_easy_getinfo(per->curl, CURLINFO_SCHEME, &scheme);
131
scheme = proto_token(scheme);
132
if((scheme == proto_http || scheme == proto_https)) {
133
long response = 0;
134
curl_easy_getinfo(per->curl, CURLINFO_RESPONSE_CODE, &response);
135
136
if((response/100 != 2) && (response/100 != 3))
137
/* only care about etag and content-disposition headers in 2xx and 3xx
138
responses */
139
;
140
/*
141
* Write etag to file when --etag-save option is given.
142
*/
143
else if(per->config->etag_save_file && etag_save->stream &&
144
/* match only header that start with etag (case insensitive) */
145
checkprefix("etag:", str)) {
146
const char *etag_h = &str[5];
147
const char *eot = end - 1;
148
if(*eot == '\n') {
149
while(ISBLANK(*etag_h) && (etag_h < eot))
150
etag_h++;
151
while(ISSPACE(*eot))
152
eot--;
153
154
if(eot >= etag_h) {
155
size_t etag_length = eot - etag_h + 1;
156
/*
157
* Truncate the etag save stream, it can have an existing etag value.
158
*/
159
#if defined(HAVE_FTRUNCATE) && !defined(__MINGW32CE__)
160
if(ftruncate(fileno(etag_save->stream), 0)) {
161
return CURL_WRITEFUNC_ERROR;
162
}
163
#else
164
if(fseek(etag_save->stream, 0, SEEK_SET)) {
165
return CURL_WRITEFUNC_ERROR;
166
}
167
#endif
168
169
fwrite(etag_h, 1, etag_length, etag_save->stream);
170
/* terminate with newline */
171
fputc('\n', etag_save->stream);
172
(void)fflush(etag_save->stream);
173
}
174
}
175
}
176
177
/*
178
* This callback sets the filename where output shall be written when
179
* curl options --remote-name (-O) and --remote-header-name (-J) have
180
* been simultaneously given and additionally server returns an HTTP
181
* Content-Disposition header specifying a filename property.
182
*/
183
184
else if(hdrcbdata->honor_cd_filename) {
185
if((cb > 20) && checkprefix("Content-disposition:", str)) {
186
const char *p = str + 20;
187
188
/* look for the 'filename=' parameter
189
(encoded filenames (*=) are not supported) */
190
for(;;) {
191
char *filename;
192
size_t len;
193
194
while((p < end) && *p && !ISALPHA(*p))
195
p++;
196
if(p > end - 9)
197
break;
198
199
if(memcmp(p, "filename=", 9)) {
200
/* no match, find next parameter */
201
while((p < end) && *p && (*p != ';'))
202
p++;
203
if((p < end) && *p)
204
continue;
205
else
206
break;
207
}
208
p += 9;
209
210
len = cb - (size_t)(p - str);
211
filename = parse_filename(p, len);
212
if(filename) {
213
if(outs->stream) {
214
/* indication of problem, get out! */
215
free(filename);
216
return CURL_WRITEFUNC_ERROR;
217
}
218
219
if(per->config->output_dir) {
220
outs->filename = curl_maprintf("%s/%s", per->config->output_dir,
221
filename);
222
free(filename);
223
if(!outs->filename)
224
return CURL_WRITEFUNC_ERROR;
225
}
226
else
227
outs->filename = filename;
228
229
outs->is_cd_filename = TRUE;
230
outs->s_isreg = TRUE;
231
outs->fopened = FALSE;
232
outs->alloc_filename = TRUE;
233
hdrcbdata->honor_cd_filename = FALSE; /* done now! */
234
if(!tool_create_output_file(outs, per->config))
235
return CURL_WRITEFUNC_ERROR;
236
if(tool_write_headers(&per->hdrcbdata, outs->stream))
237
return CURL_WRITEFUNC_ERROR;
238
}
239
break;
240
}
241
if(!outs->stream && !tool_create_output_file(outs, per->config))
242
return CURL_WRITEFUNC_ERROR;
243
if(tool_write_headers(&per->hdrcbdata, outs->stream))
244
return CURL_WRITEFUNC_ERROR;
245
} /* content-disposition handling */
246
247
if(hdrcbdata->honor_cd_filename &&
248
hdrcbdata->config->show_headers) {
249
/* still awaiting the Content-Disposition header, store the header in
250
memory. Since it is not null-terminated, we need an extra dance. */
251
char *clone = curl_maprintf("%.*s", (int)cb, str);
252
if(clone) {
253
struct curl_slist *old = hdrcbdata->headlist;
254
hdrcbdata->headlist = curl_slist_append(old, clone);
255
free(clone);
256
if(!hdrcbdata->headlist) {
257
curl_slist_free_all(old);
258
return CURL_WRITEFUNC_ERROR;
259
}
260
}
261
else {
262
curl_slist_free_all(hdrcbdata->headlist);
263
hdrcbdata->headlist = NULL;
264
return CURL_WRITEFUNC_ERROR;
265
}
266
return cb; /* done for now */
267
}
268
}
269
}
270
if(hdrcbdata->config->writeout) {
271
char *value = memchr(ptr, ':', cb);
272
if(value) {
273
if(per->was_last_header_empty)
274
per->num_headers = 0;
275
per->was_last_header_empty = FALSE;
276
per->num_headers++;
277
}
278
else if(ptr[0] == '\r' || ptr[0] == '\n')
279
per->was_last_header_empty = TRUE;
280
}
281
if(hdrcbdata->config->show_headers &&
282
(scheme == proto_http || scheme == proto_https ||
283
scheme == proto_rtsp || scheme == proto_file)) {
284
/* bold headers only for selected protocols */
285
char *value = NULL;
286
287
if(!outs->stream && !tool_create_output_file(outs, per->config))
288
return CURL_WRITEFUNC_ERROR;
289
290
if(global->isatty &&
291
#ifdef _WIN32
292
tool_term_has_bold &&
293
#endif
294
global->styled_output)
295
value = memchr(ptr, ':', cb);
296
if(value) {
297
size_t namelen = value - ptr;
298
curl_mfprintf(outs->stream, BOLD "%.*s" BOLDOFF ":", (int)namelen, ptr);
299
#ifndef LINK
300
fwrite(&value[1], cb - namelen - 1, 1, outs->stream);
301
#else
302
if(curl_strnequal("Location", ptr, namelen)) {
303
write_linked_location(per->curl, &value[1], cb - namelen - 1,
304
outs->stream);
305
}
306
else
307
fwrite(&value[1], cb - namelen - 1, 1, outs->stream);
308
#endif
309
}
310
else
311
/* not "handled", just show it */
312
fwrite(ptr, cb, 1, outs->stream);
313
}
314
return cb;
315
}
316
317
/*
318
* Copies a filename part and returns an ALLOCATED data buffer.
319
*/
320
static char *parse_filename(const char *ptr, size_t len)
321
{
322
char *copy;
323
char *p;
324
char *q;
325
char stop = '\0';
326
327
copy = memdup0(ptr, len);
328
if(!copy)
329
return NULL;
330
331
p = copy;
332
if(*p == '\'' || *p == '"') {
333
/* store the starting quote */
334
stop = *p;
335
p++;
336
}
337
else
338
stop = ';';
339
340
/* scan for the end letter and stop there */
341
q = strchr(p, stop);
342
if(q)
343
*q = '\0';
344
345
/* if the filename contains a path, only use filename portion */
346
q = strrchr(p, '/');
347
if(q) {
348
p = q + 1;
349
if(!*p) {
350
tool_safefree(copy);
351
return NULL;
352
}
353
}
354
355
/* If the filename contains a backslash, only use filename portion. The idea
356
is that even systems that do not handle backslashes as path separators
357
probably want the path removed for convenience. */
358
q = strrchr(p, '\\');
359
if(q) {
360
p = q + 1;
361
if(!*p) {
362
tool_safefree(copy);
363
return NULL;
364
}
365
}
366
367
/* make sure the filename does not end in \r or \n */
368
q = strchr(p, '\r');
369
if(q)
370
*q = '\0';
371
372
q = strchr(p, '\n');
373
if(q)
374
*q = '\0';
375
376
if(copy != p)
377
memmove(copy, p, strlen(p) + 1);
378
379
#if defined(_WIN32) || defined(MSDOS)
380
{
381
char *sanitized;
382
SANITIZEcode sc = sanitize_file_name(&sanitized, copy, 0);
383
tool_safefree(copy);
384
if(sc)
385
return NULL;
386
copy = sanitized;
387
}
388
#endif /* _WIN32 || MSDOS */
389
390
return copy;
391
}
392
393
#ifdef LINK
394
/*
395
* Treat the Location: header specially, by writing a special escape
396
* sequence that adds a hyperlink to the displayed text. This makes
397
* the absolute URL of the redirect clickable in supported terminals,
398
* which could not happen otherwise for relative URLs. The Location:
399
* header is supposed to always be absolute so this theoretically
400
* should not be needed but the real world returns plenty of relative
401
* URLs here.
402
*/
403
static void write_linked_location(CURL *curl, const char *location,
404
size_t loclen, FILE *stream)
405
{
406
/* This would so simple if CURLINFO_REDIRECT_URL were available here */
407
CURLU *u = NULL;
408
char *copyloc = NULL, *locurl = NULL, *scheme = NULL, *finalurl = NULL;
409
const char *loc = location;
410
size_t llen = loclen;
411
int space_skipped = 0;
412
const char *vver = getenv("VTE_VERSION");
413
414
if(vver) {
415
curl_off_t num;
416
if(curlx_str_number(&vver, &num, CURL_OFF_T_MAX) ||
417
/* Skip formatting for old versions of VTE <= 0.48.1 (Mar 2017) since
418
some of those versions have formatting bugs. (#10428) */
419
(num <= 4801))
420
goto locout;
421
}
422
423
/* Strip leading whitespace of the redirect URL */
424
while(llen && (*loc == ' ' || *loc == '\t')) {
425
++loc;
426
--llen;
427
++space_skipped;
428
}
429
430
/* Strip the trailing end-of-line characters, normally "\r\n" */
431
while(llen && (loc[llen-1] == '\n' || loc[llen-1] == '\r'))
432
--llen;
433
434
/* CURLU makes it easy to handle the relative URL case */
435
u = curl_url();
436
if(!u)
437
goto locout;
438
439
/* Create a null-terminated and whitespace-stripped copy of Location: */
440
copyloc = memdup0(loc, llen);
441
if(!copyloc)
442
goto locout;
443
444
/* The original URL to use as a base for a relative redirect URL */
445
if(curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &locurl))
446
goto locout;
447
if(curl_url_set(u, CURLUPART_URL, locurl, 0))
448
goto locout;
449
450
/* Redirected location. This can be either absolute or relative. */
451
if(curl_url_set(u, CURLUPART_URL, copyloc, 0))
452
goto locout;
453
454
if(curl_url_get(u, CURLUPART_URL, &finalurl, CURLU_NO_DEFAULT_PORT))
455
goto locout;
456
457
if(curl_url_get(u, CURLUPART_SCHEME, &scheme, 0))
458
goto locout;
459
460
if(!strcmp("http", scheme) ||
461
!strcmp("https", scheme) ||
462
!strcmp("ftp", scheme) ||
463
!strcmp("ftps", scheme)) {
464
curl_mfprintf(stream, "%.*s" LINK "%s" LINKST "%.*s" LINKOFF,
465
space_skipped, location,
466
finalurl,
467
(int)loclen - space_skipped, loc);
468
goto locdone;
469
}
470
471
/* Not a "safe" URL: do not linkify it */
472
473
locout:
474
/* Write the normal output in case of error or unsafe */
475
fwrite(location, loclen, 1, stream);
476
477
locdone:
478
if(u) {
479
curl_free(finalurl);
480
curl_free(scheme);
481
curl_url_cleanup(u);
482
free(copyloc);
483
}
484
}
485
#endif
486
487