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