Coverage Report

Created: 2026-12-01 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httrack/src/htslib.c
Line
Count
Source
1
/* ------------------------------------------------------------ */
2
/*
3
HTTrack Website Copier, Offline Browser for Windows and Unix
4
Copyright (C) 1998 Xavier Roche and other contributors
5
6
SPDX-License-Identifier: GPL-3.0-or-later
7
8
This program is free software: you can redistribute it and/or modify
9
it under the terms of the GNU General Public License as published by
10
the Free Software Foundation, either version 3 of the License, or
11
(at your option) any later version.
12
13
This program is distributed in the hope that it will be useful,
14
but WITHOUT ANY WARRANTY; without even the implied warranty of
15
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
GNU General Public License for more details.
17
18
You should have received a copy of the GNU General Public License
19
along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21
Ethical use: we kindly ask that you NOT use this software to harvest email
22
addresses or to collect any other private information about people. Doing so
23
would dishonor our work and waste the many hours we have spent on it.
24
25
Please visit our Website: http://www.httrack.com
26
*/
27
28
/* ------------------------------------------------------------ */
29
/* File: Subroutines                                            */
30
/* Author: Xavier Roche                                         */
31
/* ------------------------------------------------------------ */
32
33
// Fichier librairie .c
34
35
#include "htscore.h"
36
#include "htsbundle.h"
37
#include "htssitemap.h"
38
#include "htswarc.h"
39
#include "htschanges.h"
40
#include "htssinglefile.h"
41
#include "htsfetch.h"
42
#include "htspsl.h"
43
44
/* specific definitions */
45
#include "htsdate.h"
46
#include "htsbase.h"
47
#include "htsio.h"
48
#include "htsnet.h"
49
#include "htsbauth.h"
50
#include "htsthread.h"
51
#include "htscrashtest.h"
52
#include "htsback.h"
53
#include "htsftp.h"
54
#include "htswrap.h"
55
#include "htsmd5.h"
56
#include "htsmodules.h"
57
#include "htscharset.h"
58
#include "htsencoding.h"
59
#include "htsescape.h"
60
#include "htscodec.h"
61
#include "htslines.h"
62
#include "htsckd.h"
63
#include "htsbuf.h"
64
65
#include <limits.h>
66
67
/* macOS reaches Multipath TCP through connectx() on an AF_MULTIPATH socket. */
68
#if HTS_INET_MPTCP && defined(__APPLE__)
69
#define HTS_INET_MPTCP_DARWIN 1
70
#ifndef AF_MULTIPATH
71
/* The macOS SDK lacks it, and a wrong value only leaves Multipath TCP off. */
72
#define AF_MULTIPATH 39
73
#endif
74
#else
75
#define HTS_INET_MPTCP_DARWIN 0
76
#endif
77
#if HTS_INET_MPTCP && !HTS_INET_MPTCP_DARWIN
78
#include <sys/utsname.h>
79
#endif
80
81
/* Without this header Multipath TCP still works but goes unreported, which is
82
   also where macOS stands. */
83
#if HTS_INET_MPTCP && defined(HAVE_LINUX_MPTCP_H)
84
#include <linux/mptcp.h>
85
0
#define HTS_INET_MPTCP_INFO 1
86
#else
87
#define HTS_INET_MPTCP_INFO 0
88
#endif
89
90
#ifdef _WIN32
91
#include <direct.h>
92
#else
93
#ifdef HAVE_SYS_TYPES_H
94
#include <sys/types.h>
95
#endif
96
#ifdef HAVE_SYS_STAT_H
97
#include <sys/stat.h>
98
#endif
99
#ifdef HAVE_UNISTD_H
100
#include <unistd.h>
101
#endif
102
#endif /* _WIN32 */
103
#include <stdarg.h>
104
105
#include <stdint.h>
106
#include <string.h>
107
#include <time.h>
108
#include <stdarg.h>
109
110
#ifndef _WIN32
111
#include <sys/time.h>
112
#else
113
#include <sys/timeb.h>
114
#endif
115
#include <fcntl.h>
116
117
// pour utimbuf
118
#ifdef _WIN32
119
#include <sys/utime.h>
120
#else
121
#include <utime.h>
122
#endif /* _WIN32 */
123
124
#include <sys/stat.h>
125
126
/* END specific definitions */
127
128
static void deletesoc_r(htsblk *r);
129
static void time_rfc822_local(hts_buf s, struct tm *A);
130
/* Split byte count n into {number, unit}, both stored inside strc. */
131
static char **int2bytes2(strc_int2bytes2 *strc, LLint n);
132
133
/* Which bytes an escape_* function percent-escapes, one per function. */
134
typedef enum hts_escape_class {
135
  HTS_ESC_CHECK_URL,
136
  HTS_ESC_IN_URL,
137
  HTS_ESC_SPC_URL,
138
  HTS_ESC_URI,
139
  HTS_ESC_CONTROL_URL,
140
  HTS_ESC_URI_UTF
141
} hts_escape_class;
142
143
/* Percent-escaper behind the escape_* family. */
144
static size_t x_escape_http(const char *const s, hts_buf out,
145
                            const hts_escape_class mode);
146
/* Copies src to dst, writing each byte of set that lies inside escaped, a
147
   part of src, as %XX. An escape that does not fit is dropped whole. Returns
148
   HTS_FALSE when dst was too small. */
149
static hts_boolean hts_escape_span(hts_span src, hts_span escaped,
150
                                   const char *set, hts_buf dst);
151
static int hts_read(htsblk *r, hts_buf buff);
152
153
/* variables globales */
154
int _DEBUG_HEAD;
155
FILE *ioinfo;
156
157
#if HTS_USEOPENSSL
158
SSL_CTX *openssl_ctx = NULL;
159
#endif
160
161
// Reserved (RFC2396)
162
0
#define CIS(c,ch) ( ((unsigned char)(c)) == (ch) )
163
#define CHAR_RESERVED(c)                                                       \
164
0
  (CIS(c, ';') || CIS(c, '/') || CIS(c, '?') || CIS(c, ':') || CIS(c, '@') ||  \
165
0
   CIS(c, '&') || CIS(c, '=') || CIS(c, '+') || CIS(c, '$') || CIS(c, ','))
166
// Delimiters (RFC2396)
167
#define CHAR_DELIM(c)                                                          \
168
0
  (CIS(c, '<') || CIS(c, '>') || CIS(c, '#') || CIS(c, '%') || CIS(c, '\"'))
169
// Unwise (RFC2396)
170
#define CHAR_UNWISE(c)                                                         \
171
0
  (CIS(c, '{') || CIS(c, '}') || CIS(c, '|') || CIS(c, '\\') || CIS(c, '^') || \
172
0
   CIS(c, '[') || CIS(c, ']') || CIS(c, '`'))
173
// Special (escape chars) (RFC2396 + >127 )
174
0
#define CHAR_LOW(c)       ( ((unsigned char)(c) <= 31) )
175
0
#define CHAR_HIG(c)       ( ((unsigned char)(c) >= 127) )
176
0
#define CHAR_SPECIAL(c)   ( CHAR_LOW(c) || CHAR_HIG(c) )
177
// We try to avoid them and encode them instead
178
#define CHAR_XXAVOID(c)                                                        \
179
0
  (CIS(c, ' ') || CIS(c, '*') || CIS(c, '\'') || CIS(c, '\"') ||               \
180
0
   CIS(c, '&') || CIS(c, '!'))
181
#define CHAR_MARK(c)                                                           \
182
0
  (CIS(c, '-') || CIS(c, '_') || CIS(c, '.') || CIS(c, '!') || CIS(c, '~') ||  \
183
0
   CIS(c, '*') || CIS(c, '\'') || CIS(c, '(') || CIS(c, ')'))
184
185
// Initialize a htsblk structure
186
0
void hts_init_htsblk(htsblk * r) {
187
0
  memset(r, 0, sizeof(htsblk)); // effacer
188
0
  r->soc = INVALID_SOCKET;
189
0
  r->msg[0] = '\0';
190
0
  r->statuscode = STATUSCODE_INVALID;
191
0
  r->totalsize = -1;
192
0
  r->retry_after = -1;
193
0
}
194
195
T_SOC http_xfopen(httrackp *opt, const char *adr, const char *fil,
196
0
                  htsblk *retour) {
197
0
  T_SOC soc = INVALID_SOCKET;
198
0
  char BIGSTK tempo_fil[HTS_URLMAXSIZE * 2];
199
200
  // default result: error
201
0
  retour->adr = NULL;
202
0
  retour->size = 0;
203
0
  retour->msg[0] = '\0';
204
0
  retour->statuscode = STATUSCODE_NON_FATAL;
205
206
  /* no proxy, or proxy not usable here (local file) */
207
0
  if ((!(retour->req.proxy.active)) || (strcmp(adr, "file://") == 0)) {
208
0
    soc = newhttp(opt, adr, retour, -1);
209
0
  } else {
210
    // to the proxy; https tunnels to the origin via CONNECT in back_wait
211
    // (#85)
212
0
    soc = newhttp(opt, retour->req.proxy.name, retour, retour->req.proxy.port);
213
0
  }
214
215
0
  retour->soc = soc;
216
217
  /* Check for errors */
218
0
  if (soc == INVALID_SOCKET) {
219
0
    if (!strnotempty(retour->msg)) {
220
0
      const int last_errno = hts_socket_errno();
221
0
      char errbuf[HTS_STRERROR_SIZE];
222
223
0
      htsblk_failf(retour, "Connect error: %s",
224
0
                   hts_strerror(last_errno, HTS_BUF(errbuf)));
225
0
    }
226
0
  }
227
  // a local file: LOCAL_SOCKET_ID is a pseudo-socket, and no proxy applies
228
0
  if (soc == LOCAL_SOCKET_ID) {
229
0
    retour->is_file = 1;
230
231
    // file:///C|... : retry without the leading slash
232
0
    if (!fexist(fconv(
233
0
            OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
234
0
            unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), fil))))
235
0
      if (fexist(fconv(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
236
0
                       unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
237
0
                                     fil + 1)))) {
238
0
        strcpybuff(tempo_fil, fil + 1);
239
0
        fil = tempo_fil;
240
0
      }
241
0
    retour->totalsize = fsize(
242
0
        fconv(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
243
0
              unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), fil)));
244
0
    retour->msg[0] = '\0';
245
0
    soc = INVALID_SOCKET;
246
0
    if (retour->totalsize < 0)
247
0
      strcpybuff(retour->msg, "Unable to open local file");
248
0
    else {
249
0
      retour->fp = FOPEN(
250
0
          fconv(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
251
0
                unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), fil)),
252
0
          "rb");
253
0
      if (retour->fp == NULL)
254
0
        soc = INVALID_SOCKET;
255
0
      else
256
0
        soc = LOCAL_SOCKET_ID;
257
0
    }
258
0
    retour->soc = soc;
259
0
    if (soc != INVALID_SOCKET) {
260
0
      retour->statuscode = HTTP_OK;
261
0
      strcpybuff(retour->msg, "OK");
262
0
      guess_httptype_sized(opt, retour->contenttype,
263
0
                           sizeof(retour->contenttype), fil);
264
0
    } else if (strnotempty(retour->msg) == 0)
265
0
      strcpybuff(retour->msg, "Unable to open local file");
266
0
    return soc;
267
0
  }
268
269
  // the header is read later, by back_wait
270
0
  if (soc != INVALID_SOCKET)
271
0
    retour->totalsize = -1;
272
273
0
  return soc;
274
0
}
275
276
/* Buffer printing */
277
typedef struct buff_struct {
278
  /** Buffer **/
279
  char *buffer;
280
  /** Buffer capacity in bytes **/
281
  size_t capacity;
282
  /** Buffer write position ; MUST point to a valid \0. **/
283
  size_t pos;
284
  /** Did a print not fit? Every later one is then skipped. **/
285
  hts_boolean overflow;
286
} buff_struct;
287
288
static void print_buffer(buff_struct *const str,
289
                         HTS_FORMAT_STRING const char *format, ...)
290
    HTS_PRINTF_FUN(2, 3);
291
292
/* Prints on a static buffer, raising str->overflow rather than writing past
293
   its end; what to do about a partial buffer is the caller's call. */
294
static void print_buffer(buff_struct *const str,
295
0
                         HTS_FORMAT_STRING const char *format, ...) {
296
0
  size_t result;
297
0
  va_list args;
298
0
  size_t remaining;
299
0
  char *position;
300
301
  /* Security check. */
302
0
  assertf(str != NULL);
303
0
  assertf(str->pos < str->capacity);
304
305
0
  if (str->overflow)
306
0
    return;
307
308
  /* Print */
309
0
  position = &str->buffer[str->pos];
310
0
  remaining = str->capacity - str->pos;
311
0
  va_start(args, format);
312
0
  result = (size_t) vsnprintf(position, remaining, format, args);
313
0
  va_end(args);
314
0
  if (result >= remaining) {
315
0
    position[0] = '\0';
316
0
    str->overflow = HTS_TRUE;
317
0
    return;
318
0
  }
319
320
  /* Increment. */
321
0
  str->pos += strlen(position);
322
0
  assertf(str->pos < str->capacity);
323
0
}
324
325
/* Append a "Cookie:" request line for every stored cookie matching adr/path.
326
   Only an "https://" adr gets Secure cookies, and its port is ignored. Pairs
327
   use the RFC 6265 form, because modern servers reject RFC 2965 $Version and
328
   $Path (#151). A pair that does not fit is dropped whole and counted in
329
   *skipped (may be NULL), so the line never ends mid-pair. The line takes all
330
   of bstr's remaining room, so reserve is the room the caller still needs
331
   after it. Returns the number emitted. */
332
static int append_cookie_header(buff_struct *bstr, t_cookie *cookie,
333
                                const char *adr, const char *path,
334
0
                                size_t reserve, int *skipped) {
335
0
  const size_t crlf_len = sizeof(H_CRLF) - 1;
336
0
  const hts_boolean https = hts_starts_with_ci(adr, "https://");
337
0
  const int64_t now = (int64_t) time(NULL);
338
0
  const char *domain;
339
0
  char host[COOKIE_MAX_DOMAIN];
340
0
  char *b;
341
0
  int count = 0;
342
0
  size_t max_pos;
343
344
0
  if (skipped != NULL)
345
0
    *skipped = 0;
346
0
  if (cookie == NULL || bstr->overflow)
347
0
    return 0;
348
0
  if (!cookie_host(adr, HTS_SIZED(host)))
349
0
    return 0;
350
0
  domain = host;
351
352
  /* Highest position a pair may reach: cookies get what is left once this
353
     line's CRLF, the NUL and whatever the caller still owes are set aside.
354
     Both tests are what keep the subtractions from wrapping. */
355
0
  if (bstr->capacity <= crlf_len + 1)
356
0
    return 0;
357
0
  max_pos = bstr->capacity - crlf_len - 1;
358
0
  if (reserve >= max_pos)
359
0
    return 0;
360
0
  max_pos -= reserve;
361
362
0
  b = cookie->data;
363
0
  do {
364
0
    b = cookie_find(b, "", domain, path); // next matching cookie
365
0
    if (b != NULL && !cookie_sendable(b, https, now)) {
366
0
      b = cookie_nextfield(b);
367
0
    } else if (b != NULL) {
368
0
      const size_t mark = bstr->pos;
369
0
      hts_boolean kept = HTS_FALSE;
370
371
0
      if (mark < max_pos) {
372
0
        const hts_span name = cookie_field(b, 5), value = cookie_field(b, 6);
373
374
0
        if (count == 0)
375
0
          print_buffer(bstr, "Cookie: ");
376
0
        else
377
0
          print_buffer(bstr, "; ");
378
0
        print_buffer(bstr, "%.*s=%.*s", (int) name.len, name.p, (int) value.len,
379
0
                     value.p);
380
0
        kept = !bstr->overflow && bstr->pos <= max_pos;
381
0
      }
382
0
      if (kept) {
383
0
        count++;
384
0
      } else {
385
        /* Rewind: half a pair would be read as another cookie's value. */
386
0
        bstr->pos = mark;
387
0
        bstr->buffer[mark] = '\0';
388
0
        bstr->overflow = HTS_FALSE;
389
0
        if (skipped != NULL)
390
0
          (*skipped)++;
391
0
      }
392
0
      b = cookie_nextfield(b);
393
0
    }
394
0
  } while (b != NULL);
395
0
  if (count != 0)
396
0
    print_buffer(bstr, H_CRLF);
397
0
  return count;
398
0
}
399
400
/* Build the request Cookie line for adr/path into dst (always
401
   NUL-terminated). Returns the number of cookies emitted. */
402
int http_cookie_header(t_cookie *cookie, const char *adr, const char *path,
403
0
                       hts_buf dst) {
404
0
  buff_struct bstr = {dst.p, dst.size, 0};
405
406
0
  assertf(dst.p != NULL && dst.size > 0);
407
0
  dst.p[0] = '\0';
408
0
  return append_cookie_header(&bstr, cookie, adr, path, 0, NULL);
409
0
}
410
411
0
hts_boolean hts_body_missing_unexpectedly(const htsblk *r) {
412
0
  if (r->adr != NULL || r->is_write != 0)
413
0
    return HTS_FALSE;
414
0
  if (HTTP_IS_REDIRECT(r->statuscode) ||
415
0
      r->statuscode == HTTP_PRECONDITION_FAILED ||
416
0
      r->statuscode == HTTP_REQUESTED_RANGE_NOT_SATISFIABLE)
417
0
    return HTS_FALSE;
418
0
  return HTS_TRUE;
419
0
}
420
421
0
hts_span hts_blk_body(const htsblk *r) {
422
0
  return hts_span_at(r->adr,
423
0
                     r->adr != NULL && r->size > 0 ? (size_t) r->size : 0);
424
0
}
425
426
/* Read the next line of the custom block *REST, ended by CRLF, CR or LF.
427
   Unlike hts_header_next, a blank line does not end the block. */
428
0
static hts_boolean custom_line_next(hts_span *rest, hts_span *line) {
429
0
  const char *const p = rest->p;
430
0
  size_t n = 0;
431
432
0
  if (hts_span_empty(*rest))
433
0
    return HTS_FALSE;
434
0
  while (n < rest->len && p[n] != '\r' && p[n] != '\n')
435
0
    n++;
436
0
  *line = hts_span_at(p, n);
437
0
  if (n + 1 < rest->len && p[n] == '\r' && p[n + 1] == '\n')
438
0
    n++;
439
0
  *rest = hts_span_skip(*rest, n + 1);
440
0
  return HTS_TRUE;
441
0
}
442
443
/* Does LINE continue the line before it? */
444
0
static hts_boolean header_folded(hts_span line) {
445
0
  const int c = hts_span_first(line);
446
447
0
  return c == ' ' || c == '\t';
448
0
}
449
450
/* Servers differ on "Host : x", so the engine sends it as Host without the
451
   blank. */
452
0
static hts_span header_name(hts_span line) {
453
0
  hts_span name, value;
454
455
0
  hts_header_split(line, &name, &value);
456
0
  return name;
457
0
}
458
459
/* Cut S at its first CR or LF. */
460
0
static hts_span first_line(const char *s) {
461
0
  return hts_span_at(s, strcspn(s, "\r\n"));
462
0
}
463
464
/* Is NAME an RFC 7230 token? */
465
0
static hts_boolean header_name_valid(hts_span name) {
466
0
  size_t i;
467
468
0
  for (i = 0; i < name.len; i++) {
469
0
    const unsigned char c = (unsigned char) name.p[i];
470
471
0
    if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') &&
472
0
        !(c >= '0' && c <= '9') && strchr("!#$%&'*+-.^_`|~", c) == NULL)
473
0
      return HTS_FALSE;
474
0
  }
475
0
  return !hts_span_empty(name);
476
0
}
477
478
/* No list may hold "", which would match a line with no name. */
479
0
hts_boolean header_name_in(const char *line, const char *const *names) {
480
0
  return hts_span_index_ci(header_name(first_line(line)), names) >= 0;
481
0
}
482
483
/* http_headers_have_field() for a NAME without the colon */
484
0
static hts_boolean http_headers_have_name(hts_span headers, hts_span name) {
485
0
  hts_span line;
486
487
0
  if (hts_span_empty(name))
488
0
    return HTS_FALSE;
489
  /* anchored, so a folded line or a name inside a value cannot match */
490
0
  while (custom_line_next(&headers, &line))
491
    /* the prefix test first, because most lines fail it */
492
0
    if (hts_span_starts_with_ci(line, name) &&
493
0
        hts_span_eq_ci(header_name(line), name))
494
0
      return HTS_TRUE;
495
0
  return HTS_FALSE;
496
0
}
497
498
hts_boolean http_headers_have_field(const char *headers,
499
0
                                    const char *field_name) {
500
0
  hts_span name = hts_span_of(field_name);
501
502
0
  if (hts_span_ends_with(name, hts_span_of(":"))) /* the tree spells both */
503
0
    name.len--;
504
0
  return http_headers_have_name(hts_span_of(headers), name);
505
0
}
506
507
/* These fields frame the message or act per hop. */
508
0
static hts_boolean header_refused(hts_span name) {
509
0
  static const char *const refused[] = {
510
0
      HTS_SPAN_WORDS("Content-Length", "Transfer-Encoding", "Connection",
511
0
                     "Keep-Alive", "TE", "Upgrade", "Expect")};
512
513
0
  return hts_span_index_ci(name, refused) >= 0;
514
0
}
515
516
/* A request carries these once, so a later custom line overrides one before. */
517
0
static hts_boolean header_single(hts_span name) {
518
0
  static const char *const single[] = {
519
0
      HTS_SPAN_WORDS("Host", "Cookie", "Authorization")};
520
521
0
  return hts_span_index_ci(name, single) >= 0;
522
0
}
523
524
/* An update or a resume writes these itself, dropping the custom line. */
525
0
static hts_boolean header_engine_conditional(hts_span name) {
526
0
  static const char *const conditional[] = {
527
0
      HTS_SPAN_WORDS("Range", "If-Match", "If-None-Match", "If-Modified-Since",
528
0
                     "If-Unmodified-Since")};
529
530
0
  return hts_span_index_ci(name, conditional) >= 0;
531
0
}
532
533
/* Find the last unfolded line of HEADERS. */
534
0
static hts_boolean last_unfolded_line(hts_span headers, hts_span *last) {
535
0
  hts_boolean found = HTS_FALSE;
536
0
  hts_span line;
537
538
0
  while (custom_line_next(&headers, &line))
539
0
    if (!header_folded(line)) {
540
0
      *last = line;
541
0
      found = HTS_TRUE;
542
0
    }
543
0
  return found;
544
0
}
545
546
0
static hts_header_verdict header_verdict(hts_span headers, hts_span line) {
547
0
  const hts_span name = header_name(line);
548
0
  hts_span parent;
549
550
0
  if (header_folded(line))
551
    /* alone, or the parent would find its own field in headers */
552
0
    return last_unfolded_line(headers, &parent)
553
0
               ? header_verdict(hts_span_of(NULL), parent)
554
0
               : HTS_HEADER_DROPPED_ORPHAN_FOLD;
555
0
  if (!header_name_valid(name))
556
0
    return HTS_HEADER_DROPPED_MALFORMED;
557
0
  if (header_refused(name))
558
0
    return HTS_HEADER_DROPPED_FRAMING;
559
0
  if (header_single(name) && http_headers_have_name(headers, name))
560
0
    return HTS_HEADER_SENT_REPLACES_EARLIER;
561
0
  if (header_engine_conditional(name))
562
0
    return HTS_HEADER_SENT_UNLESS_ENGINE_OVERRIDES;
563
0
  return HTS_HEADER_SENT;
564
0
}
565
566
HTSEXT_API hts_header_verdict hts_custom_header_verdict(const char *headers,
567
0
                                                        const char *line) {
568
0
  if (line == NULL)
569
0
    return HTS_HEADER_DROPPED_MALFORMED;
570
0
  return header_verdict(hts_span_of(headers), first_line(line));
571
0
}
572
573
0
const char *http_custom_header_warning(const char *headers, const char *line) {
574
  /* a fold's parent line already got its warning */
575
0
  if ((*line == ' ' || *line == '\t') && headers != NULL && *headers != '\0')
576
0
    return NULL;
577
0
  switch (hts_custom_header_verdict(headers, line)) {
578
0
  case HTS_HEADER_DROPPED_ORPHAN_FOLD:
579
0
    return "folded line with no header to continue ignored";
580
0
  case HTS_HEADER_DROPPED_MALFORMED:
581
0
    return "malformed header ignored";
582
0
  case HTS_HEADER_DROPPED_FRAMING:
583
0
    return "framing header ignored";
584
0
  case HTS_HEADER_SENT_REPLACES_EARLIER:
585
0
    return "header replaces an earlier one";
586
0
  case HTS_HEADER_SENT_UNLESS_ENGINE_OVERRIDES: /* valid, so a bundle may carry
587
                                                   it */
588
0
  case HTS_HEADER_SENT:
589
0
    break;
590
0
  }
591
0
  return NULL;
592
0
}
593
594
/* The -%X warnings, plus Host, Cookie and Proxy-*. */
595
0
const char *http_bundle_header_refusal(const char *headers, const char *line) {
596
0
  static const char *const engine[] = {HTS_SPAN_WORDS("Host", "Cookie")};
597
0
  const char *const why = http_custom_header_warning(headers, line);
598
599
0
  if (why != NULL)
600
0
    return why;
601
0
  if (header_name_in(line, engine))
602
0
    return "Host and Cookie are the engine's";
603
0
  if (hts_starts_with_ci(line, "Proxy-"))
604
0
    return "a proxy header is not for the site";
605
0
  return NULL;
606
0
}
607
608
/* Dropping a line drops its folded continuations too: kept, that value would
609
   attach to whichever header precedes it in the request. */
610
0
static void append_custom_headers(buff_struct *bstr, const char *headers) {
611
  /* only what the engine wrote, so the box may repeat its own fields */
612
0
  const hts_span engine = hts_span_at(bstr->buffer, bstr->pos);
613
0
  hts_span rest = hts_span_of(headers), line;
614
  /* a leading folded line would attach to the engine's last header */
615
0
  hts_boolean keep = HTS_FALSE;
616
617
0
  while (custom_line_next(&rest, &line)) {
618
0
    const hts_span name = header_name(line);
619
620
0
    if (!header_folded(line))
621
0
      keep = header_name_valid(name) && !header_refused(name) &&
622
0
             !http_headers_have_name(engine, name) &&
623
             /* the last of a single-valued field wins, as later options do */
624
0
             !(header_single(name) && http_headers_have_name(rest, name));
625
0
    if (keep) {
626
      /* a folded line has no name, and a kept named line has a colon */
627
0
      const char *const from =
628
0
          line.p + (header_folded(line) ? 0 : hts_span_find(line, ':'));
629
630
      /* One write, so a line that does not fit leaves nothing behind. */
631
0
      print_buffer(bstr, "%.*s%.*s", (int) name.len, name.p,
632
0
                   (int) (rest.p - from), from);
633
0
    }
634
0
  }
635
0
}
636
637
0
void http_append_custom_headers(hts_buf dst, const char *headers) {
638
0
  buff_struct bstr = {dst.p, dst.size, 0};
639
640
0
  assertf(dst.p != NULL && dst.size > 0);
641
0
  bstr.pos = strlen(dst.p);
642
0
  append_custom_headers(&bstr, headers);
643
0
}
644
645
/* See htslib.h. Clip an oversized body, because aborting loses the mirror. */
646
0
size_t http_postfile_body(hts_buf buffer, size_t pos, FILE *fp) {
647
0
  size_t room;
648
0
  size_t got;
649
650
0
  assertf(pos < buffer.size);
651
0
  room = buffer.size - pos - 1; /* the NUL every consumer strlen()s up to */
652
0
  got = fread(&buffer.p[pos], 1, room, fp);
653
0
  buffer.p[pos + got] = '\0';
654
0
  return pos + strlen(&buffer.p[pos]);
655
0
}
656
657
0
hts_boolean hts_location_is_safe(const char *location) {
658
0
  return (location == NULL || strstr(location, POSTTOK) == NULL) ? HTS_TRUE
659
0
                                                                 : HTS_FALSE;
660
0
}
661
662
0
static hts_boolean hts_request_is_secure(const htsblk *retour) {
663
#if HTS_USEOPENSSL
664
  return retour->ssl ? HTS_TRUE : HTS_FALSE;
665
#else
666
0
  (void) retour;
667
0
  return HTS_FALSE;
668
0
#endif
669
0
}
670
671
/* Is the product token TOK named name ("Chrome" for "Chrome/141")? On a
672
   match, *major is the version's first number, or -1 when the version is
673
   malformed. */
674
0
static hts_boolean ua_product_is(hts_span tok, const char *name, int *major) {
675
0
  hts_span product, version, head, tail;
676
0
  LLint v;
677
678
0
  if (!hts_span_split(tok, '/', &product, &version) ||
679
0
      !hts_span_eq(product, hts_span_of(name)))
680
0
    return HTS_FALSE;
681
0
  *major = -1;
682
0
  if (!hts_span_split(version, '.', &head, &tail))
683
0
    head = version;
684
0
  if (hts_span_starts_with(version, hts_span_of("0")) ||
685
0
      !hts_span_parse_llint(head, 0, 99999, &v) ||
686
0
      !hts_span_empty(hts_span_trim(version, "0123456789.", "")))
687
0
    return HTS_TRUE;
688
0
  *major = (int) v;
689
0
  return HTS_TRUE;
690
0
}
691
692
/* Does the UA comment contain word? */
693
0
static hts_boolean ua_comment_has(hts_span comment, const char *word) {
694
0
  const hts_span w = hts_span_of(word);
695
696
0
  for (; comment.len >= w.len; comment = hts_span_skip(comment, 1)) {
697
0
    if (hts_span_starts_with(comment, w))
698
0
      return HTS_TRUE;
699
0
  }
700
0
  return HTS_FALSE;
701
0
}
702
703
0
hts_boolean hts_client_hints_of(const char *user_agent, hts_client_hints *ch) {
704
  /* Chromium's GREASE brand and brand order (user_agent_utils.cc), seeded by
705
     the major. Before M108 the formula differed. */
706
0
  enum { GREASE_FIRST_MAJOR = 108 };
707
708
0
  static const char grease_chars[] = " (:-./);=?_";
709
0
  static const char *const grease_versions[] = {"8", "99", "24"};
710
0
  static const int orders[6][3] = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2},
711
0
                                   {1, 2, 0}, {2, 0, 1}, {2, 1, 0}};
712
0
  hts_span comment = {NULL, 0};
713
0
  int chrome = -1;
714
0
  int edge = 0; /* 0: no Edg token */
715
0
  hts_boolean mobile = HTS_FALSE, mozilla = HTS_FALSE;
716
0
  const char *p;
717
0
  char brands[3][48];
718
0
  const char *shuffled[3];
719
0
  int i;
720
721
0
  memset(ch, 0, sizeof(*ch));
722
0
  if (user_agent == NULL)
723
0
    return HTS_FALSE;
724
  /* Every product token must be one Chrome or Edge sends, so any other
725
     browser built on Chromium (Opera, Samsung, headless) gets no hints. */
726
0
  for (p = user_agent; *p != '\0';) {
727
0
    size_t n;
728
0
    int major;
729
0
    hts_span tok;
730
731
0
    if (*p == ' ') {
732
0
      p++;
733
0
    } else if (*p == '(') {
734
0
      const char *const end = strchr(p, ')');
735
736
0
      if (end == NULL)
737
0
        return HTS_FALSE;
738
0
      if (comment.p == NULL)
739
0
        comment = hts_span_between(p + 1, end);
740
0
      p = end + 1;
741
0
    } else {
742
0
      for (n = 0; (unsigned char) p[n] > ' ' && p[n] != '('; n++)
743
0
        ;
744
0
      tok = hts_span_at(p, n);
745
0
      if (ua_product_is(tok, "Chrome", &major))
746
0
        chrome = major;
747
0
      else if (ua_product_is(tok, "Edg", &major))
748
0
        edge = major;
749
0
      else if (ua_product_is(tok, "Mozilla", &major))
750
0
        mozilla = HTS_TRUE;
751
0
      else if (hts_span_eq(tok, hts_span_of("Mobile")))
752
0
        mobile = HTS_TRUE;
753
0
      else if (!ua_product_is(tok, "AppleWebKit", &major) &&
754
0
               !ua_product_is(tok, "Safari", &major))
755
0
        return HTS_FALSE;
756
0
      p += n;
757
0
    }
758
0
  }
759
  /* Edge's major is always the Chromium one. */
760
0
  if (!mozilla || chrome < GREASE_FIRST_MAJOR || (edge != 0 && edge != chrome))
761
0
    return HTS_FALSE;
762
763
  /* Android before Linux: an Android comment names both. */
764
0
  if (ua_comment_has(comment, "Android"))
765
0
    strcpybuff(ch->platform, "\"Android\"");
766
0
  else if (ua_comment_has(comment, "CrOS"))
767
0
    strcpybuff(ch->platform, "\"Chrome OS\"");
768
0
  else if (ua_comment_has(comment, "Windows"))
769
0
    strcpybuff(ch->platform, "\"Windows\"");
770
0
  else if (ua_comment_has(comment, "Macintosh"))
771
0
    strcpybuff(ch->platform, "\"macOS\"");
772
0
  else if (ua_comment_has(comment, "Linux"))
773
0
    strcpybuff(ch->platform, "\"Linux\"");
774
0
  else
775
0
    return HTS_FALSE;
776
777
0
  snprintf(brands[0], sizeof(brands[0]), "\"Not%cA%cBrand\";v=\"%s\"",
778
0
           grease_chars[chrome % 11], grease_chars[(chrome + 1) % 11],
779
0
           grease_versions[chrome % 3]);
780
0
  snprintf(brands[1], sizeof(brands[1]), "\"Chromium\";v=\"%d\"", chrome);
781
0
  if (edge > 0)
782
0
    snprintf(brands[2], sizeof(brands[2]), "\"Microsoft Edge\";v=\"%d\"", edge);
783
0
  else
784
0
    snprintf(brands[2], sizeof(brands[2]), "\"Google Chrome\";v=\"%d\"",
785
0
             chrome);
786
0
  for (i = 0; i < 3; i++)
787
0
    shuffled[orders[chrome % 6][i]] = brands[i];
788
0
  snprintf(ch->ua, sizeof(ch->ua), "%s, %s, %s", shuffled[0], shuffled[1],
789
0
           shuffled[2]);
790
0
  ch->mobile = mobile;
791
0
  return HTS_TRUE;
792
0
}
793
794
/* Is user_agent Firefox from 90, the first to send Sec-Fetch-*? Every product
795
   token must be one Firefox sends, so a fork naming itself gets no table. */
796
0
static hts_boolean ua_is_firefox(const char *user_agent) {
797
0
  enum { FETCH_META_FIRST_MAJOR = 90 };
798
799
0
  hts_boolean mozilla = HTS_FALSE, gecko = HTS_FALSE;
800
0
  int firefox = -1;
801
0
  const char *p;
802
803
0
  for (p = user_agent; *p != '\0';) {
804
0
    size_t n;
805
0
    int major;
806
0
    hts_span tok;
807
808
0
    if (*p == ' ') {
809
0
      p++;
810
0
    } else if (*p == '(') {
811
0
      const char *const end = strchr(p, ')');
812
813
0
      if (end == NULL)
814
0
        return HTS_FALSE;
815
0
      p = end + 1;
816
0
    } else {
817
0
      for (n = 0; (unsigned char) p[n] > ' ' && p[n] != '('; n++)
818
0
        ;
819
0
      tok = hts_span_at(p, n);
820
0
      if (ua_product_is(tok, "Firefox", &major))
821
0
        firefox = major;
822
0
      else if (ua_product_is(tok, "Gecko", &major))
823
0
        gecko = HTS_TRUE;
824
0
      else if (ua_product_is(tok, "Mozilla", &major))
825
0
        mozilla = HTS_TRUE;
826
0
      else
827
0
        return HTS_FALSE;
828
0
      p += n;
829
0
    }
830
0
  }
831
0
  return mozilla && gecko && firefox >= FETCH_META_FIRST_MAJOR ? HTS_TRUE
832
0
                                                               : HTS_FALSE;
833
0
}
834
835
0
hts_browser_family hts_browser_family_of(const char *user_agent) {
836
0
  hts_client_hints ch;
837
838
0
  if (user_agent == NULL)
839
0
    return HTS_BROWSER_NONE;
840
0
  if (hts_client_hints_of(user_agent, &ch))
841
0
    return HTS_BROWSER_CHROME;
842
0
  return ua_is_firefox(user_agent) ? HTS_BROWSER_FIREFOX : HTS_BROWSER_NONE;
843
0
}
844
845
/* Return fetch, or NULL when a browser would send no Sec-Fetch-*. That is the
846
   case for an unknown destination, -%Q0, an untrustworthy URL, and a
847
   User-Agent that is no current browser or that -%X replaces. An unset site
848
   means a hop missed hts_fetch_through, which must not read as same-origin. */
849
static const hts_fetch_meta *
850
fetch_meta_sent(httrackp *opt, const hts_fetch_meta *fetch, const char *adr,
851
0
                const htsblk *retour, const char *custom) {
852
0
  if (fetch == NULL || fetch->dest == HTS_FETCH_DEST_UNKNOWN ||
853
0
      fetch->site == HTS_FETCH_SITE_UNSET ||
854
0
      opt->browser_headers == HTS_FALSE || !hts_fetch_trustworthy(adr) ||
855
0
      !retour->req.user_agent_send || retour->req.user_agent == NULL ||
856
0
      strncmp(retour->req.user_agent, "Mozilla/5.0 ", 12) != 0 ||
857
0
      http_headers_have_field(custom, "User-Agent"))
858
0
    return NULL;
859
0
  return fetch;
860
0
}
861
862
/* A browser table may reorder these headers, which go out in this order
863
   without one. */
864
typedef enum http_header_slot {
865
  HDR_REFERER,
866
  HDR_CONTENT_LENGTH,
867
  HDR_CONNECTION,
868
  HDR_HOST,
869
  HDR_FROM,
870
  HDR_CH_UA,
871
  HDR_CH_UA_MOBILE,
872
  HDR_CH_UA_PLATFORM,
873
  HDR_UPGRADE_INSECURE,
874
  HDR_USER_AGENT,
875
  HDR_ACCEPT,
876
  HDR_FETCH_SITE,
877
  HDR_FETCH_MODE,
878
  HDR_FETCH_USER,
879
  HDR_FETCH_DEST,
880
  HDR_ACCEPT_LANGUAGE,
881
  HDR_ACCEPT_ENCODING,
882
  HDR_ORIGIN,
883
  HDR_COUNT
884
} http_header_slot;
885
886
/* A span locates one header in the scratch block, and is empty when unsent. */
887
typedef struct http_header_span {
888
  size_t start, end;
889
} http_header_span;
890
891
/* Chrome 155 and Firefox 158 send these orders. A header the browser never
892
   sends goes first (Content-length, From) or last. */
893
static const unsigned char header_orders[][HDR_COUNT] = {
894
    {HDR_REFERER, HDR_CONTENT_LENGTH, HDR_CONNECTION, HDR_HOST, HDR_FROM,
895
     HDR_CH_UA, HDR_CH_UA_MOBILE, HDR_CH_UA_PLATFORM, HDR_UPGRADE_INSECURE,
896
     HDR_USER_AGENT, HDR_ACCEPT, HDR_FETCH_SITE, HDR_FETCH_MODE, HDR_FETCH_USER,
897
     HDR_FETCH_DEST, HDR_ACCEPT_LANGUAGE, HDR_ACCEPT_ENCODING, HDR_ORIGIN},
898
    /* Chrome navigation */
899
    {HDR_CONTENT_LENGTH, HDR_FROM, HDR_HOST, HDR_CONNECTION, HDR_ORIGIN,
900
     HDR_CH_UA, HDR_CH_UA_MOBILE, HDR_CH_UA_PLATFORM, HDR_ACCEPT_LANGUAGE,
901
     HDR_UPGRADE_INSECURE, HDR_USER_AGENT, HDR_ACCEPT, HDR_FETCH_SITE,
902
     HDR_FETCH_MODE, HDR_FETCH_USER, HDR_FETCH_DEST, HDR_REFERER,
903
     HDR_ACCEPT_ENCODING},
904
    /* Chrome subresource */
905
    {HDR_CONTENT_LENGTH, HDR_FROM, HDR_HOST, HDR_CONNECTION, HDR_ORIGIN,
906
     HDR_CH_UA_PLATFORM, HDR_ACCEPT_LANGUAGE, HDR_CH_UA, HDR_UPGRADE_INSECURE,
907
     HDR_USER_AGENT, HDR_CH_UA_MOBILE, HDR_ACCEPT, HDR_FETCH_SITE,
908
     HDR_FETCH_MODE, HDR_FETCH_USER, HDR_FETCH_DEST, HDR_REFERER,
909
     HDR_ACCEPT_ENCODING},
910
    /* Firefox: Origin was never captured, so it sits where Firefox's CORS
911
       requests put it. */
912
    {HDR_CONTENT_LENGTH, HDR_FROM, HDR_HOST, HDR_USER_AGENT, HDR_ACCEPT,
913
     HDR_ACCEPT_LANGUAGE, HDR_ACCEPT_ENCODING, HDR_ORIGIN, HDR_CONNECTION,
914
     HDR_REFERER, HDR_UPGRADE_INSECURE, HDR_FETCH_DEST, HDR_FETCH_MODE,
915
     HDR_FETCH_SITE, HDR_FETCH_USER, HDR_CH_UA, HDR_CH_UA_MOBILE,
916
     HDR_CH_UA_PLATFORM}};
917
918
0
const unsigned char *http_header_order(hts_browser_family family, int dest) {
919
0
  switch (family) {
920
0
  case HTS_BROWSER_CHROME:
921
0
    return header_orders[hts_fetch_is_navigation(dest) ? 1 : 2];
922
0
  case HTS_BROWSER_FIREFOX:
923
0
    return header_orders[3];
924
0
  default:
925
0
    return header_orders[0];
926
0
  }
927
0
}
928
929
0
const char *http_header_slot_name(int slot) {
930
0
  static const char *const names[HDR_COUNT] = {"Referer",
931
0
                                               "Content-length",
932
0
                                               "Connection",
933
0
                                               "Host",
934
0
                                               "From",
935
0
                                               "sec-ch-ua",
936
0
                                               "sec-ch-ua-mobile",
937
0
                                               "sec-ch-ua-platform",
938
0
                                               "Upgrade-Insecure-Requests",
939
0
                                               "User-Agent",
940
0
                                               "Accept",
941
0
                                               "Sec-Fetch-Site",
942
0
                                               "Sec-Fetch-Mode",
943
0
                                               "Sec-Fetch-User",
944
0
                                               "Sec-Fetch-Dest",
945
0
                                               "Accept-Language",
946
0
                                               "Accept-Encoding",
947
0
                                               "Origin"};
948
949
0
  return slot >= 0 && slot < HDR_COUNT ? names[slot] : NULL;
950
0
}
951
952
0
int http_header_slot_count(void) { return HDR_COUNT; }
953
954
// envoi d'une requète
955
int http_sendhead(httrackp *opt, t_cookie *cookie, int mode, const char *xsend,
956
                  const char *adr, const char *fil, const char *referer_adr,
957
                  const char *referer_fil, const hts_fetch_meta *fetch,
958
0
                  htsblk *retour) {
959
0
  char BIGSTK buffer_head_request[16384];
960
0
  buff_struct bstr = { buffer_head_request, sizeof(buffer_head_request), 0 };
961
  /* The headers a browser table orders are rendered here before they go out. */
962
0
  char BIGSTK buffer_headers[16384];
963
0
  buff_struct hdr = {buffer_headers, sizeof(buffer_headers), 0};
964
0
  http_header_span slots[HDR_COUNT];
965
966
0
  int direct_url = 0;           // ne pas analyser l'url (exemple: ftp://)
967
0
  const char *search_tag = NULL;
968
  /* What follows the headers, so the cookie line can leave it room. */
969
0
  size_t body_len = 0;
970
971
  /* the extra-headers box wins: skip the engine's own line (#1337, #1340) */
972
0
  const char *const custom = retour->req.headers;
973
0
  const hts_fetch_meta *const sent_fetch =
974
0
      fetch_meta_sent(opt, fetch, adr, retour, custom);
975
  /* That browser's tables pick the Accept, header order and Accept-Language. */
976
0
  const hts_browser_family family =
977
0
      sent_fetch != NULL ? hts_browser_family_of(retour->req.user_agent)
978
0
                         : HTS_BROWSER_NONE;
979
980
  /* adr and the referer come off the network and can carry raw CR/LF; capped
981
     at their own source buffers, so the worst case emitted does not grow. */
982
0
  char BIGSTK esc[HTS_URLMAXSIZE * 2];
983
984
  /* Only a user-supplied URL has no referer, so a crawled page cannot name
985
     >postfile: below and have the engine send it a local file. */
986
0
  const char *const post_fil = strnotempty(referer_adr) ? "" : fil;
987
988
  // Initialize buffer
989
0
  buffer_head_request[0] = '\0';
990
0
  buffer_headers[0] = '\0';
991
0
  memset(slots, 0, sizeof(slots));
992
993
  // Undocumented: >post: posts what follows it, >postfile: sends the file it
994
  // names as the raw request.
995
  // example: http://www.example.com/test.cgi?foo>post:posteddata=10&foo=5
996
  // example: http://www.example.com/test.cgi?foo>postfile:post0.txt
997
0
  search_tag = strstr(post_fil, POSTTOK ":");
998
0
  if (!search_tag) {
999
0
    search_tag = strstr(post_fil, POSTTOK "file:");
1000
0
    if (search_tag) {           // postfile
1001
0
      if (mode == 0) {          // GET!
1002
0
        FILE *fp =
1003
0
          FOPEN(unescape_http(OPT_GET_BUFF(opt), 
1004
0
                OPT_GET_BUFF_SIZE(opt), search_tag + strlen(POSTTOK) + 5), "rb");
1005
0
        if (fp) {
1006
0
          char BIGSTK line[1100];
1007
0
          char BIGSTK protocol[256], url[HTS_URLMAXSIZE * 2], method[256];
1008
1009
          /* a TAB may separate the request line's words */
1010
0
          hts_readline(fp, HTS_BUF_N(line, 1000), HTS_LINE_DROP_FF);
1011
          /* widths bound method[256], url[HTS_URLMAXSIZE*2], protocol[256] */
1012
0
          if (sscanf(line, "%255s %2047s %255s", method, url, protocol) == 3) {
1013
            // http proxy: absolute-URI; socks/CONNECT tunnel: origin-form
1014
0
            if (retour->req.proxy.active &&
1015
0
                !hts_proxy_is_socks(retour->req.proxy.name) &&
1016
0
                !hts_proxy_is_connect(retour->req.proxy.name)) {
1017
              /* only adr is raw here: the other three are %s-scanned */
1018
0
              print_buffer(&bstr, "%s http://%s%s %s\r\n", method,
1019
0
                           escape_check_url_addr(adr, HTS_BUF(esc)), url,
1020
0
                           protocol);
1021
0
            } else {
1022
0
              print_buffer(&bstr,
1023
0
                       "%s %s %s\r\n", method, url, protocol);
1024
0
            }
1025
            // the rest of the file goes out raw
1026
0
            bstr.pos = http_postfile_body(
1027
0
                hts_buf_at(bstr.buffer, bstr.capacity), bstr.pos, fp);
1028
0
          }
1029
0
          fclose(fp);
1030
0
        }
1031
0
      }
1032
0
    }
1033
0
  }
1034
  // Fin postfile
1035
1036
0
  if (bstr.pos == 0) { // PAS POSTFILE
1037
    // Type de requète?
1038
0
    if ((search_tag) && (mode == 0)) {
1039
0
      print_buffer(&bstr, "POST ");
1040
0
    } else if (mode == 0) {     // GET
1041
0
      print_buffer(&bstr, "GET ");
1042
0
    } else {                    // if (mode==1) {
1043
0
      if (!retour->req.http11)  // forcer HTTP/1.0
1044
0
        print_buffer(&bstr, "GET ");       // certains serveurs (cgi) buggent avec HEAD
1045
0
      else
1046
0
        print_buffer(&bstr, "HEAD ");
1047
0
    }
1048
1049
    // an http proxy needs an absolute URI; a socks or CONNECT tunnel does not
1050
0
    if (retour->req.proxy.active &&
1051
0
        !hts_proxy_is_socks(retour->req.proxy.name) &&
1052
0
        !hts_proxy_is_connect(retour->req.proxy.name) &&
1053
0
        (strncmp(adr, "https://", 8) != 0)) {
1054
0
      if (!link_has_authority(adr)) { // default http
1055
0
        print_buffer(&bstr, "http://%s",
1056
0
                     escape_check_url_addr(jump_identification_const(adr),
1057
0
                                           HTS_BUF(esc)));
1058
0
      } else {                  // ftp:// en proxy http
1059
0
        direct_url = 1;         // ne pas analyser user/pass
1060
0
        print_buffer(&bstr, "%s", escape_check_url_addr(adr, HTS_BUF(esc)));
1061
0
      }
1062
0
    }
1063
    // NOM DU FICHIER
1064
    // on slash doit être présent en début, sinon attention aux bad request! (400)
1065
0
    if (*fil != '/')
1066
0
      print_buffer(&bstr, "/");
1067
1068
0
    {
1069
0
      char BIGSTK tempo[HTS_URLMAXSIZE * 2];
1070
1071
0
      tempo[0] = '\0';
1072
0
      if (search_tag)
1073
0
        strncatbuff(tempo, fil, (int) (search_tag - fil));
1074
0
      else
1075
0
        strcpybuff(tempo, fil);
1076
0
      inplace_escape_check_url(tempo, sizeof(tempo));
1077
0
      print_buffer(&bstr, "%s", tempo);  // avec échappement
1078
0
    }
1079
1080
    // protocole
1081
0
    if (!retour->req.http11) { // forcer HTTP/1.0
1082
0
      print_buffer(&bstr, " HTTP/1.0\x0d\x0a");
1083
0
    } else { // Requète 1.1
1084
0
      print_buffer(&bstr, " HTTP/1.1\x0d\x0a");
1085
0
    }
1086
1087
    /* supplemental data */
1088
0
    if (xsend)
1089
0
      print_buffer(&bstr, "%s", xsend);  // éventuelles autres lignes
1090
1091
    // https/connect://: auth rides the CONNECT; socks: the handshake
1092
0
    if (retour->req.proxy.active &&
1093
0
        !hts_proxy_is_socks(retour->req.proxy.name) &&
1094
0
        !hts_proxy_is_connect(retour->req.proxy.name) &&
1095
0
        strncmp(adr, "https://", 8) != 0) {
1096
0
      if (link_has_authorization(retour->req.proxy.name) &&
1097
0
          !http_headers_have_field(custom, "Proxy-Authorization")) {
1098
0
        char autorisation[1100];
1099
1100
0
        const int got = hts_basic_auth_value(opt, retour->req.proxy.name,
1101
0
                                             HTS_BUF(autorisation));
1102
1103
0
        if (got > 0)
1104
0
          print_buffer(&bstr, "Proxy-Authorization: Basic %s" H_CRLF,
1105
0
                       autorisation);
1106
0
        else if (got < 0)
1107
0
          hts_log_print(opt, LOG_WARNING,
1108
0
                        "proxy authorization dropped, credentials too long");
1109
0
      }
1110
0
    }
1111
    // Referer?
1112
0
    if (referer_adr != NULL && referer_fil != NULL && strnotempty(referer_adr)
1113
0
        && strnotempty(referer_fil)
1114
0
      ) {                       // non vide
1115
0
      if ((strcmp(referer_adr, "file://") != 0) &&
1116
0
          (/* no https referer to http urls */
1117
0
           (strncmp(referer_adr, "https://", 8) != 0) /* referer is not https */
1118
0
           || (strncmp(adr, "https://", 8) ==
1119
0
               0) /* or referer AND addresses are https */
1120
0
           ) &&
1121
0
          !http_headers_have_field(custom, "Referer")) { // not file://
1122
        /* An https or ftp address is stored with its scheme, an http one bare.
1123
         */
1124
0
        const char *const scheme =
1125
0
            strncmp(referer_adr, "https://", 8) == 0 ? "https://"
1126
0
            : strncmp(referer_adr, "ftp://", 6) == 0 ? "ftp://"
1127
0
                                                     : "http://";
1128
1129
        /* one escape per piece, so neither can outgrow its own source buffer */
1130
0
        slots[HDR_REFERER].start = hdr.pos;
1131
0
        print_buffer(&hdr, "Referer: %s%s", scheme,
1132
0
                     escape_check_url_addr(
1133
0
                         jump_identification_const(referer_adr), HTS_BUF(esc)));
1134
0
        print_buffer(&hdr, "%s" H_CRLF,
1135
0
                     escape_check_url_addr(referer_fil, HTS_BUF(esc)));
1136
0
        slots[HDR_REFERER].end = hdr.pos;
1137
0
      }
1138
0
    }
1139
    // HTTP field: referer
1140
0
    else if (strnotempty(retour->req.referer) &&
1141
0
             !http_headers_have_field(custom, "Referer")) {
1142
0
      slots[HDR_REFERER].start = hdr.pos;
1143
0
      print_buffer(&hdr, "Referer: %s" H_CRLF, retour->req.referer);
1144
0
      slots[HDR_REFERER].end = hdr.pos;
1145
0
    }
1146
    // POST?
1147
0
    if (mode == 0) {            // GET!
1148
0
      if (search_tag) {
1149
0
        body_len =
1150
0
            strlen(unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
1151
0
                                 search_tag + strlen(POSTTOK) + 1));
1152
0
        slots[HDR_CONTENT_LENGTH].start = hdr.pos;
1153
0
        print_buffer(&hdr, "Content-length: %d" H_CRLF, (int) body_len);
1154
0
        slots[HDR_CONTENT_LENGTH].end = hdr.pos;
1155
0
      }
1156
0
    }
1157
    // keep-alive reuses the socket
1158
0
    slots[HDR_CONNECTION].start = hdr.pos;
1159
0
    if (retour->req.http11 && !retour->req.nokeepalive) {
1160
0
      print_buffer(&hdr, "Connection: keep-alive" H_CRLF);
1161
0
    } else {
1162
0
      print_buffer(&hdr, "Connection: close" H_CRLF);
1163
0
    }
1164
0
    slots[HDR_CONNECTION].end = hdr.pos;
1165
1166
0
    {
1167
0
      const char *real_adr = jump_identification_const(adr);
1168
1169
      // Mandatory per RFC2616
1170
0
      if (!direct_url &&
1171
0
          !http_headers_have_field(custom, "Host")) { // not ftp:// for example
1172
0
        slots[HDR_HOST].start = hdr.pos;
1173
0
        print_buffer(&hdr, "Host: %s" H_CRLF,
1174
0
                     escape_check_url_addr(real_adr, HTS_BUF(esc)));
1175
0
        slots[HDR_HOST].end = hdr.pos;
1176
0
      }
1177
1178
      // HTTP field: from
1179
0
      if (strnotempty(retour->req.from) &&
1180
0
          !http_headers_have_field(custom, "From")) { // HTTP from
1181
0
        slots[HDR_FROM].start = hdr.pos;
1182
0
        print_buffer(&hdr, "From: %s" H_CRLF, retour->req.from);
1183
0
        slots[HDR_FROM].end = hdr.pos;
1184
0
      }
1185
1186
      /* HTTPS only, and only beside the User-Agent the hints come from. */
1187
0
      if (opt->browser_headers != HTS_FALSE && hts_request_is_secure(retour) &&
1188
0
          retour->req.user_agent_send &&
1189
0
          !http_headers_have_field(custom, "User-Agent")) {
1190
0
        hts_client_hints ch;
1191
1192
0
        if (hts_client_hints_of(retour->req.user_agent, &ch)) {
1193
0
          if (!http_headers_have_field(custom, "Sec-CH-UA")) {
1194
0
            slots[HDR_CH_UA].start = hdr.pos;
1195
0
            print_buffer(&hdr, "sec-ch-ua: %s" H_CRLF, ch.ua);
1196
0
            slots[HDR_CH_UA].end = hdr.pos;
1197
0
          }
1198
0
          if (!http_headers_have_field(custom, "Sec-CH-UA-Mobile")) {
1199
0
            slots[HDR_CH_UA_MOBILE].start = hdr.pos;
1200
0
            print_buffer(&hdr, "sec-ch-ua-mobile: ?%d" H_CRLF,
1201
0
                         ch.mobile ? 1 : 0);
1202
0
            slots[HDR_CH_UA_MOBILE].end = hdr.pos;
1203
0
          }
1204
0
          if (!http_headers_have_field(custom, "Sec-CH-UA-Platform")) {
1205
0
            slots[HDR_CH_UA_PLATFORM].start = hdr.pos;
1206
0
            print_buffer(&hdr, "sec-ch-ua-platform: %s" H_CRLF, ch.platform);
1207
0
            slots[HDR_CH_UA_PLATFORM].end = hdr.pos;
1208
0
          }
1209
0
        }
1210
0
      }
1211
1212
      /* On https only, so a server answering it cannot move a plain http
1213
         crawl onto https. */
1214
0
      if (sent_fetch != NULL && hts_fetch_is_navigation(sent_fetch->dest) &&
1215
0
          hts_request_is_secure(retour) &&
1216
0
          !http_headers_have_field(custom, "Upgrade-Insecure-Requests")) {
1217
0
        slots[HDR_UPGRADE_INSECURE].start = hdr.pos;
1218
0
        print_buffer(&hdr, "Upgrade-Insecure-Requests: 1" H_CRLF);
1219
0
        slots[HDR_UPGRADE_INSECURE].end = hdr.pos;
1220
0
      }
1221
1222
0
      if (retour->req.user_agent_send && strnotempty(retour->req.user_agent) &&
1223
0
          !http_headers_have_field(custom, "User-Agent")) {
1224
0
        slots[HDR_USER_AGENT].start = hdr.pos;
1225
0
        print_buffer(&hdr, "User-Agent: %s" H_CRLF, retour->req.user_agent);
1226
0
        slots[HDR_USER_AGENT].end = hdr.pos;
1227
0
      }
1228
1229
      /* dest comes from fetch, so a KIND= entry applies without Sec-Fetch-*. */
1230
0
      {
1231
0
        char accept_buf[HTS_ACCEPT_MAXSIZE];
1232
0
        const char *accept;
1233
1234
        /* held until printed: accept may point into accept_kinds */
1235
0
        hts_mutexlock(&opt->state.lock);
1236
0
        accept = hts_accept_lookup(StringBuff(opt->accept_kinds),
1237
0
                                   retour->req.accept, opt->accept_given,
1238
0
                                   fetch != NULL ? fetch->dest
1239
0
                                                 : HTS_FETCH_DEST_UNKNOWN,
1240
0
                                   family, HTS_BUF(accept_buf));
1241
0
        if (strnotempty(accept) && !http_headers_have_field(custom, "Accept")) {
1242
0
          slots[HDR_ACCEPT].start = hdr.pos;
1243
0
          print_buffer(&hdr, "Accept: %s" H_CRLF, accept);
1244
0
          slots[HDR_ACCEPT].end = hdr.pos;
1245
0
        }
1246
0
        hts_mutexrelease(&opt->state.lock);
1247
0
      }
1248
1249
0
      if (sent_fetch != NULL) {
1250
0
        if (!http_headers_have_field(custom, "Sec-Fetch-Site")) {
1251
0
          slots[HDR_FETCH_SITE].start = hdr.pos;
1252
0
          print_buffer(&hdr, "Sec-Fetch-Site: %s" H_CRLF,
1253
0
                       hts_fetch_site_name(sent_fetch->site));
1254
0
          slots[HDR_FETCH_SITE].end = hdr.pos;
1255
0
        }
1256
0
        if (!http_headers_have_field(custom, "Sec-Fetch-Mode")) {
1257
0
          slots[HDR_FETCH_MODE].start = hdr.pos;
1258
0
          print_buffer(&hdr, "Sec-Fetch-Mode: %s" H_CRLF,
1259
0
                       hts_fetch_mode_name(sent_fetch));
1260
0
          slots[HDR_FETCH_MODE].end = hdr.pos;
1261
0
        }
1262
0
        if (sent_fetch->user &&
1263
0
            !http_headers_have_field(custom, "Sec-Fetch-User")) {
1264
0
          slots[HDR_FETCH_USER].start = hdr.pos;
1265
0
          print_buffer(&hdr, "Sec-Fetch-User: ?1" H_CRLF);
1266
0
          slots[HDR_FETCH_USER].end = hdr.pos;
1267
0
        }
1268
0
        if (!http_headers_have_field(custom, "Sec-Fetch-Dest")) {
1269
0
          slots[HDR_FETCH_DEST].start = hdr.pos;
1270
0
          print_buffer(&hdr, "Sec-Fetch-Dest: %s" H_CRLF,
1271
0
                       hts_fetch_dest_name(sent_fetch->dest));
1272
0
          slots[HDR_FETCH_DEST].end = hdr.pos;
1273
0
        }
1274
0
      }
1275
1276
      /* A browser table replaces the built-in -%l, never the user's. */
1277
0
      if (strnotempty(retour->req.lang_iso) &&
1278
0
          !http_headers_have_field(custom, "Accept-Language")) {
1279
0
        const char *lang = retour->req.lang_iso;
1280
1281
0
        if (family != HTS_BROWSER_NONE && !opt->lang_given)
1282
0
          lang = HTS_ACCEPT_LANGUAGE_BROWSER;
1283
0
        slots[HDR_ACCEPT_LANGUAGE].start = hdr.pos;
1284
0
        print_buffer(&hdr, "Accept-Language: %s" H_CRLF, lang);
1285
0
        slots[HDR_ACCEPT_LANGUAGE].end = hdr.pos;
1286
0
      }
1287
1288
      // Compression accepted ?
1289
0
      if (retour->req.http11 &&
1290
0
          !http_headers_have_field(custom, "Accept-Encoding")) {
1291
0
        hts_boolean compressible =
1292
0
            (!retour->req.range_used && !retour->req.nocompression);
1293
1294
0
        slots[HDR_ACCEPT_ENCODING].start = hdr.pos;
1295
0
        print_buffer(
1296
0
            &hdr, "Accept-Encoding: %s" H_CRLF,
1297
0
            hts_acceptencoding(compressible, hts_request_is_secure(retour)));
1298
0
        slots[HDR_ACCEPT_ENCODING].end = hdr.pos;
1299
0
      }
1300
1301
      /* Chrome sends a cors request's Origin even same-origin, Firefox only
1302
         cross-origin. */
1303
0
      if (sent_fetch != NULL && family != HTS_BROWSER_NONE &&
1304
0
          strcmp(hts_fetch_mode_name(sent_fetch), "cors") == 0 &&
1305
0
          !http_headers_have_field(custom, "Origin")) {
1306
0
        const char *const from =
1307
0
            sent_fetch->initiator > 0 && sent_fetch->initiator < opt->lien_tot
1308
0
                ? heap(sent_fetch->initiator)->adr
1309
0
                : NULL;
1310
0
        char origin[HTS_URLMAXSIZE * 2];
1311
1312
0
        if (from != NULL && hts_fetch_origin(from, HTS_BUF(origin)) &&
1313
0
            (family == HTS_BROWSER_CHROME ||
1314
0
             hts_fetch_site_of(from, adr) != HTS_FETCH_SITE_SAME_ORIGIN)) {
1315
0
          slots[HDR_ORIGIN].start = hdr.pos;
1316
0
          print_buffer(&hdr, "Origin: %s" H_CRLF, origin);
1317
0
          slots[HDR_ORIGIN].end = hdr.pos;
1318
0
        }
1319
0
      }
1320
1321
      /* Each header in the order the browser sends them. */
1322
0
      {
1323
0
        const unsigned char *const order = http_header_order(
1324
0
            family,
1325
0
            sent_fetch != NULL ? sent_fetch->dest : HTS_FETCH_DEST_UNKNOWN);
1326
0
        int i;
1327
1328
        /* Only a library caller can set opt strings past the argv caps. */
1329
0
        if (hdr.overflow)
1330
0
          bstr.overflow = HTS_TRUE;
1331
0
        for (i = 0; i < HDR_COUNT; i++) {
1332
0
          const http_header_span *const h = &slots[order[i]];
1333
1334
0
          if (h->end > h->start)
1335
0
            print_buffer(&bstr, "%.*s", (int) (h->end - h->start),
1336
0
                         hdr.buffer + h->start);
1337
0
        }
1338
0
      }
1339
      /* Authentification */
1340
0
      {
1341
0
        char autorisation[1100];
1342
0
        const char *a;
1343
1344
0
        autorisation[0] = '\0';
1345
0
        if (link_has_authorization(adr)) {      // ohh une authentification!
1346
0
          const char *a = jump_identification_const(adr);
1347
1348
0
          if (!direct_url) {    // pas ftp:// par exemple
1349
0
            const int got =
1350
0
                hts_basic_auth_value(opt, adr, HTS_BUF(autorisation));
1351
1352
0
            if (got > 0) {
1353
0
              if (cookie != NULL && strcmp(fil, "/robots.txt") != 0 &&
1354
0
                  !bauth_add(cookie, adr, fil, autorisation))
1355
                /* debug: it repeats on every request under this login */
1356
0
                hts_log_print(opt, LOG_DEBUG,
1357
0
                              "authorization not kept for later requests to %s",
1358
0
                              a);
1359
0
            } else if (got < 0) {
1360
              /* 'a' is past the '@': the log gets the host, not the secret. */
1361
0
              hts_log_print(
1362
0
                  opt, LOG_WARNING,
1363
0
                  "authorization dropped, credentials too long for %s", a);
1364
0
            }
1365
0
          }
1366
0
        } else if ((a = bauth_check(cookie, adr, fil)))
1367
0
          strcpybuff(autorisation, a);
1368
0
        if (strnotempty(autorisation) &&
1369
0
            !http_headers_have_field(custom, "Authorization")) {
1370
0
          print_buffer(&bstr, "Authorization: Basic %s"H_CRLF, autorisation);
1371
0
        }
1372
0
      }
1373
0
    }
1374
1375
    // Custom header(s), minus the fields the request already carries
1376
0
    if (strnotempty(custom)) {
1377
0
      append_custom_headers(&bstr, custom);
1378
0
    }
1379
1380
    /* Stored cookies matching this host/path, last because the line takes
1381
       whatever room the headers above left it. */
1382
0
    if (cookie != NULL && !http_headers_have_field(custom, "Cookie")) {
1383
0
      int skipped;
1384
1385
0
      append_cookie_header(&bstr, cookie, adr, fil,
1386
0
                           sizeof(H_CRLF) - 1 + body_len, &skipped);
1387
0
      if (skipped != 0) {
1388
0
        hts_log_print(opt, LOG_WARNING,
1389
0
                      "Request too large for %d cookie(s) of %s%s", skipped,
1390
0
                      jump_identification_const(adr), fil);
1391
0
      }
1392
0
    }
1393
1394
    // CRLF de fin d'en tête
1395
0
    print_buffer(&bstr, H_CRLF);
1396
1397
    // données complémentaires?
1398
0
    if (search_tag)
1399
0
      if (mode == 0)            // GET!
1400
0
        print_buffer(&bstr, "%s",
1401
0
                   unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
1402
0
                                 search_tag + strlen(POSTTOK) + 1));
1403
0
  }
1404
1405
  /* Nothing sums the fields above against the request buffer. A clipped
1406
     request would fetch another resource, or drop the credentials. */
1407
0
  if (bstr.overflow) {
1408
0
    hts_log_print(opt, LOG_WARNING, "Request header too large for %s%s",
1409
0
                  jump_identification_const(adr), fil);
1410
0
    deletesoc_r(retour);
1411
0
    strcpybuff(retour->msg, "Request header too large");
1412
0
    retour->soc = INVALID_SOCKET;
1413
0
    return -1;
1414
0
  }
1415
0
  if (_DEBUG_HEAD) {
1416
0
    if (ioinfo) {
1417
0
      hts_secret_fprintf(opt, ioinfo, "[%d] request for %s%s:\r\n",
1418
0
                         retour->debugid, jump_identification_const(adr), fil);
1419
0
      fprintfio(ioinfo, bstr.buffer, "<<< ", opt);
1420
0
      fprintf(ioinfo, "\r\n");
1421
0
      fflush(ioinfo);
1422
0
    }
1423
0
  }                             // Fin test pas postfile
1424
  //
1425
1426
  // Stash the raw request for the WARC request record (freed at
1427
  // back_clear_entry)
1428
0
  if (StringNotEmpty(opt->warc_file))
1429
0
    warc_stash_request(retour, bstr.buffer);
1430
1431
  // Callback
1432
0
  {
1433
0
    int test_head =
1434
0
      RUN_CALLBACK6(opt, sendhead, bstr.buffer, adr, fil, referer_adr, referer_fil,
1435
0
                    retour);
1436
0
    if (test_head != 1) {
1437
0
      deletesoc_r(retour);
1438
0
      strcpybuff(retour->msg, "Header refused by external wrapper");
1439
0
      retour->soc = INVALID_SOCKET;
1440
0
      return -1;
1441
0
    }
1442
0
  }
1443
1444
  // Envoi
1445
0
  HTS_STAT.last_request = mtime_local();
1446
0
  if (sendc(retour, bstr.buffer) < 0) {        // ERREUR, socket rompue?...
1447
0
    deletesoc_r(retour);        // fermer tout de même
1448
    // et tenter de reconnecter
1449
1450
0
    strcpybuff(retour->msg, "Write error");
1451
0
    retour->soc = INVALID_SOCKET;
1452
0
  }
1453
1454
  // RX'98
1455
0
  return 0;
1456
0
}
1457
1458
/* The three-digit HTTP status code at s, or -1 when s does not start with
1459
   exactly three digits. */
1460
0
static int hts_status_code(const char *s) {
1461
  /* RFC 9110 15: exactly three digits. sscanf("%d") range-checks nothing and
1462
     glibc wraps, so "4294967496" would read as a 200. */
1463
0
  if (s[0] >= '0' && s[0] <= '9' && s[1] >= '0' && s[1] <= '9' && s[2] >= '0' &&
1464
0
      s[2] <= '9' && (s[3] < '0' || s[3] > '9'))
1465
0
    return (s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0');
1466
0
  return -1;
1467
0
}
1468
1469
0
int hts_status_line_code(const char *line) {
1470
0
  const char *a = line;
1471
1472
0
  while (*a == ' ' || *a == '\t' || *a == '\r' || *a == '\n')
1473
0
    a++;
1474
0
  if (!hts_starts_with_ci(a, "HTTP/"))
1475
0
    return -1;
1476
0
  while (*a != '\0' && *a != ' ' && *a != '\t' && *a != '\r' && *a != '\n')
1477
0
    a++;
1478
0
  while (*a == ' ' || *a == '\t' || *a == '\r' || *a == '\n')
1479
0
    a++;
1480
0
  return hts_status_code(a);
1481
0
}
1482
1483
// traiter 1ere ligne d'en tête
1484
0
void treatfirstline(htsblk * retour, const char *rcvd) {
1485
0
  const char *a = rcvd;
1486
1487
  // exemple:
1488
  // HTTP/1.0 200 OK
1489
0
  if (*a) {
1490
    // note: certains serveurs buggés renvoient HTTP/1.0\n200 OK ou " HTTP/1.0 200 OK"
1491
0
    while((*a == ' ') || (*a == 10) || (*a == 13) || (*a == 9))
1492
0
      a++;                      // épurer espaces au début
1493
0
    if (hts_starts_with_ci(a, "HTTP/")) {
1494
      // sauter HTTP/1.x
1495
0
      while((*a != ' ') && (*a != '\0') && (*a != 10) && (*a != 13)
1496
0
            && (*a != 9))
1497
0
        a++;
1498
0
      if (*a != '\0') {
1499
0
        while((*a == ' ') || (*a == 10) || (*a == 13) || (*a == 9))
1500
0
          a++;                  // épurer espaces
1501
0
        if ((retour->statuscode = hts_status_code(a)) >= 0) {
1502
          // skip the code
1503
0
          while((*a != ' ') && (*a != '\0') && (*a != 10) && (*a != 13)
1504
0
                && (*a != 9))
1505
0
            a++;
1506
0
          while((*a == ' ') || (*a == 10) || (*a == 13) || (*a == 9))
1507
0
            a++;                // épurer espaces
1508
          /* A lone CR does not end the line the reader stopped at, so a phrase
1509
             kept as-is would write the log's own field separators. */
1510
0
          if ((strlen(a) > 1) && (strlen(a) < 64) && hts_is_control_free(a))
1511
0
            strcpybuff(retour->msg, a); // message retour
1512
0
          else
1513
0
            infostatuscode_sized(HTS_SIZED(retour->msg), retour->statuscode);
1514
          // type MIME par défaut2
1515
0
          strcpybuff(retour->contenttype, HTS_UNKNOWN_MIME);
1516
0
        } else { // pas de code!
1517
0
          retour->statuscode = STATUSCODE_INVALID;
1518
0
          strcpybuff(retour->msg, "Unknown response structure");
1519
0
        }
1520
0
      } else {                  // euhh??
1521
0
        retour->statuscode = STATUSCODE_INVALID;
1522
0
        strcpybuff(retour->msg, "Unknown response structure");
1523
0
      }
1524
0
    } else {
1525
0
      if (*a == '<') {
1526
        /* This is dirty .. */
1527
0
        retour->statuscode = HTTP_OK;
1528
0
        retour->keep_alive = 0;
1529
0
        strcpybuff(retour->msg, "Unknown, assuming junky server");
1530
0
        strcpybuff(retour->contenttype, HTS_UNKNOWN_MIME);
1531
0
      } else if (strnotempty(a)) {
1532
0
        retour->statuscode = STATUSCODE_INVALID;
1533
0
        strcpybuff(retour->msg, "Unknown (not HTTP/xx) response structure");
1534
0
      } else {
1535
        /* This is dirty .. */
1536
0
        retour->statuscode = HTTP_OK;
1537
0
        retour->keep_alive = 0;
1538
0
        strcpybuff(retour->msg, "Unknown, assuming junky server");
1539
0
        strcpybuff(retour->contenttype, HTS_UNKNOWN_MIME);
1540
0
      }
1541
0
    }
1542
0
  } else {                      // vide!
1543
    /*
1544
       retour->statuscode=STATUSCODE_INVALID;
1545
       strcpybuff(retour->msg,"Empty reponse or internal error");
1546
     */
1547
    /* This is dirty .. */
1548
0
    retour->statuscode = HTTP_OK;
1549
0
    strcpybuff(retour->msg, "Unknown, assuming junky server");
1550
0
    strcpybuff(retour->contenttype, HTS_UNKNOWN_MIME);
1551
0
  }
1552
0
}
1553
1554
/* A signed or oversized value reads as 0, which turns keep-alive off. */
1555
0
static void keep_alive_param(const char *s, int *value) {
1556
0
  LLint v;
1557
0
  const hts_scan_result got = hts_scan_llint(&s, 0, INT_MAX, &v);
1558
1559
0
  if (got != HTS_SCAN_NONE)
1560
0
    *value = got == HTS_SCAN_OK ? (int) v : 0;
1561
0
}
1562
1563
0
hts_boolean hts_content_length_agrees(const char *s, LLint *seen) {
1564
0
  for (;;) {
1565
0
    LLint v;
1566
0
    const hts_scan_result got = hts_scan_llint(&s, 0, INT64_MAX, &v);
1567
1568
0
    if (got != HTS_SCAN_NONE) {
1569
0
      if (got == HTS_SCAN_REFUSED)
1570
0
        v = -2;
1571
0
      if (*seen != -1 && (v < 0 || v != *seen))
1572
0
        return HTS_FALSE;
1573
0
      *seen = v;
1574
0
    }
1575
0
    s += strcspn(s, ",");
1576
0
    if (*s == '\0')
1577
0
      return HTS_TRUE;
1578
0
    s++;
1579
0
  }
1580
0
}
1581
1582
/* RFC 6265 5.1.4 default-path of request path fil, as a length into fil below
1583
   size, the destination capacity; 0 means "/". A directory too long backs off
1584
   to an ancestor. */
1585
0
static size_t cookie_default_path_len(const char *fil, size_t size) {
1586
0
  size_t len = fil != NULL && fil[0] == '/' ? strcspn(fil, "?") : 0;
1587
1588
  // fil[len] is never "/" at the start, so this stops on the rightmost one
1589
0
  while (len > 0 && (len >= size || fil[len] != '/'))
1590
0
    len--;
1591
0
  return len;
1592
0
}
1593
1594
// Read one response header line, and store any cookie it sets.
1595
void treathead(t_cookie * cookie, const char *adr, const char *fil, htsblk * retour,
1596
0
               char *rcvd) {
1597
0
  treathead_opt(NULL, cookie, adr, fil, retour, rcvd);
1598
0
}
1599
1600
/* Is NAME the header LIT, in any case? The length test skips most calls. */
1601
#define HEADER_IS(name, lit)                                                   \
1602
0
  ((name).len == sizeof(lit) - 1 && hts_span_eq_ci((name), hts_span_of(lit)))
1603
1604
/* VALUE past its leading blanks. */
1605
0
static hts_span header_value(const char *value) {
1606
0
  return hts_span_trim(hts_span_of(value), HTS_REALSPACES, "");
1607
0
}
1608
1609
/* A header added here also goes into hts_header_is_read(). */
1610
void treathead_opt(httrackp *opt, t_cookie *cookie, const char *adr,
1611
0
                   const char *fil, htsblk *retour, char *rcvd) {
1612
0
  char *const colon = strchr(rcvd, ':');
1613
0
  hts_span name;
1614
0
  char *value;
1615
1616
0
  if (colon == NULL)
1617
0
    return;
1618
0
  name = hts_span_between(rcvd, colon);
1619
0
  value = colon + 1;
1620
0
  if (HEADER_IS(name, "Content-length")) {
1621
0
    const char *a = value;
1622
0
    LLint size;
1623
1624
0
    if (hts_scan_llint(&a, 0, INT64_MAX, &size) == HTS_SCAN_OK) {
1625
0
      retour->totalsize = size;
1626
0
      if (retour->totalsize == 0) {
1627
0
        retour->empty = 1;
1628
0
      }
1629
0
    }
1630
0
  } else if (HEADER_IS(name, "Content-Disposition")) {
1631
0
    char tmp[256];
1632
1633
0
    if (hts_header_param(value, ";", "filename", HTS_SIZED(tmp))) {
1634
0
      const char *a = tmp;
1635
0
      const char *c;
1636
1637
0
      while (is_space(*a))
1638
0
        a++;
1639
0
      while ((c = strchr(a, '/')) != NULL) /* skip all / (see RFC2616) */
1640
0
        a = c + 1;
1641
0
      hts_rtrim(tmp, HTS_SPACES);
1642
0
      if (strlen(a) < 200) {
1643
0
        strcpybuff(retour->cdispo, a);
1644
0
      }
1645
0
    }
1646
0
  } else if (HEADER_IS(name, "Last-Modified") ||
1647
0
             (HEADER_IS(name, "Date") &&
1648
0
              retour->lastmodified[0] == '\0')) { // Date stands in for it
1649
0
    const hts_span v = header_value(value);
1650
1651
0
    if (v.len < sizeof(retour->lastmodified))
1652
0
      (void) !hts_buf_put_span_clip(HTS_BUF(retour->lastmodified), v); // fits
1653
0
  } else if (HEADER_IS(name, "Etag")) {
1654
0
    if (retour) {
1655
0
      const hts_span v = header_value(value);
1656
1657
0
      if (v.len < 64)
1658
0
        (void) !hts_buf_put_span_clip(HTS_BUF(retour->etag), v); // fits
1659
0
      else
1660
0
        retour->etag[0] = '\0';
1661
0
    }
1662
0
  } else if (HEADER_IS(name, "Transfer-Encoding")) {
1663
0
    static const char *const compression[] = {
1664
0
        HTS_SPAN_WORDS("gzip", "x-gzip", "deflate")};
1665
0
    hts_span rest = hts_span_of(value);
1666
0
    hts_span item;
1667
1668
    // RFC 2616 3.6: codings in the order applied, chunked once and final
1669
0
    while (hts_span_next_in(&rest, ',', &item)) {
1670
0
      item = hts_span_trim(item, HTS_REALSPACES, HTS_REALSPACES);
1671
0
      if (hts_span_empty(item))
1672
0
        continue;
1673
      /* a chunked before this item was not the final coding */
1674
0
      if (retour->is_chunk)
1675
0
        retour->transfer_coding = HTS_TE_UNREADABLE;
1676
0
      retour->is_chunk = hts_span_eq_ci(item, hts_span_of("chunked"));
1677
0
      if (retour->is_chunk || hts_span_eq_ci(item, hts_span_of("identity")))
1678
0
        continue;
1679
      /* one compression layer, as for Content-Encoding: a parameter, a second
1680
         layer or an unknown coding leaves a body we can not read */
1681
0
      retour->transfer_coding =
1682
0
          retour->transfer_coding == HTS_TE_NONE &&
1683
0
                  hts_span_index_ci(item, compression) >= 0
1684
0
              ? HTS_TE_INFLATE
1685
0
              : HTS_TE_UNREADABLE;
1686
0
    }
1687
0
    if (retour->transfer_coding != HTS_TE_NONE)
1688
0
      retour->compressed = 1;
1689
0
  } else if (HEADER_IS(name, "Content-type")) {
1690
0
    if (retour) {
1691
0
      char tempo[1100];
1692
1693
0
      char chs[256];
1694
0
      char *const semi = strchr(value, ';');
1695
1696
0
      if (hts_header_param(value, ";", "charset", HTS_SIZED(chs))) {
1697
0
        const char *const c = chs + strspn(chs, HTS_SPACES);
1698
0
        const size_t n = strcspn(c, HTS_SPACES);
1699
1700
        // A charset is one token.
1701
0
        if (n != 0 && n < sizeof(retour->charset) - 2) {
1702
0
          retour->charset[0] = '\0';
1703
0
          strlncatbuff(retour->charset, c, sizeof(retour->charset), n);
1704
0
        }
1705
0
      }
1706
0
      if (semi != NULL)
1707
0
        *semi = '\0';
1708
      // An empty/whitespace Content-Type value yields no token: keep the
1709
      // sentinel default rather than reading an uninitialized tempo.
1710
0
      if (sscanf(value, "%1099s", tempo) == 1) { // tempo[1100], server data
1711
0
        if (!hts_buf_try_cpy(
1712
0
                HTS_BUF_N(retour->contenttype, sizeof(retour->contenttype) - 2),
1713
0
                tempo))
1714
0
          strcpybuff(retour->contenttype, "application/octet-stream-unknown");
1715
0
      }
1716
0
    }
1717
0
  } else if (HEADER_IS(name, "Content-Range")) {
1718
    // Content-Range: bytes 0-70870/70871
1719
0
    const char *a;
1720
1721
0
    for (a = value; is_space(*a); a++)
1722
0
      ;
1723
0
    if (hts_strncasecmp(a, "bytes ", 6) == 0) {
1724
0
      LLint start = 0, end = 0, total = 0;
1725
0
      hts_scan_result got;
1726
0
      hts_boolean refused;
1727
1728
0
      for(a += 6; is_space(*a); a++) ;
1729
0
      got = hts_scan_llint(&a, 0, INT64_MAX, &start);
1730
0
      refused = got == HTS_SCAN_REFUSED;
1731
1732
      // A signed or oversized field in "start-end/total" refuses the header.
1733
0
      if (got != HTS_SCAN_NONE && *a == '-') {
1734
0
        a++;
1735
0
        got = hts_scan_llint(&a, 0, INT64_MAX, &end);
1736
0
        refused = refused || got == HTS_SCAN_REFUSED;
1737
0
        if (got != HTS_SCAN_NONE && *a == '/') {
1738
0
          a++;
1739
0
          got = hts_scan_llint(&a, 0, INT64_MAX, &total);
1740
0
          refused = refused || got == HTS_SCAN_REFUSED;
1741
0
        } else {
1742
0
          got = HTS_SCAN_NONE;
1743
0
        }
1744
0
      } else {
1745
0
        got = HTS_SCAN_NONE;
1746
0
      }
1747
      // Only the total after the first '/' counts, as in "*/N".
1748
0
      if (got == HTS_SCAN_NONE) {
1749
0
        start = end = total = 0;
1750
0
        a = strchr(value, '/');
1751
0
        if (a != NULL) {
1752
0
          a++;
1753
0
          if (hts_scan_llint(&a, 1, INT64_MAX, &total) == HTS_SCAN_OK) {
1754
0
            end = total - 1;
1755
0
          } else {
1756
0
            total = 0;
1757
0
          }
1758
0
        }
1759
0
      } else if (refused) {
1760
0
        start = end = total = 0;
1761
0
      }
1762
0
      retour->crange_start = start;
1763
0
      retour->crange_end = end;
1764
0
      retour->crange = total;
1765
0
    }
1766
0
  } else if (HEADER_IS(name, "Connection")) {
1767
0
    const hts_span v = hts_span_of(value);
1768
1769
    // a list such as "Upgrade, Keep-Alive", where close wins
1770
0
    if (!hts_span_empty(header_value(value))) {
1771
0
      if (hts_span_list_has(v, ',', hts_span_of("Keep-Alive")) &&
1772
0
          !hts_span_list_has(v, ',', hts_span_of("close"))) {
1773
0
        if (!retour->keep_alive) {
1774
0
          retour->keep_alive_max = 10;
1775
0
          retour->keep_alive_t = 15;
1776
0
        }
1777
0
        retour->keep_alive = 1;
1778
0
      } else {
1779
0
        retour->keep_alive = 0;
1780
0
      }
1781
0
    }
1782
0
  } else if (HEADER_IS(name, "Keep-Alive")) {
1783
0
    char *a = value;
1784
1785
0
    while(is_space(*a))
1786
0
      a++;
1787
0
    if (*a) {
1788
0
      char v[64];
1789
1790
0
      retour->keep_alive = 1;
1791
0
      retour->keep_alive_max = 10;
1792
0
      retour->keep_alive_t = 15;
1793
0
      if (hts_header_param(a, ",;", "timeout", HTS_SIZED(v)))
1794
0
        keep_alive_param(v, &retour->keep_alive_t);
1795
0
      if (hts_header_param(a, ",;", "max", HTS_SIZED(v)))
1796
0
        keep_alive_param(v, &retour->keep_alive_max);
1797
0
      if (retour->keep_alive_max <= 1 || retour->keep_alive_t < 1) {
1798
0
        retour->keep_alive = 0;
1799
0
      }
1800
0
    }
1801
0
  } else if (HEADER_IS(name, "TE")) {
1802
0
    char *a = value;
1803
1804
0
    while(is_space(*a))
1805
0
      a++;
1806
0
    if (*a) {
1807
0
      if (hts_starts_with_ci(a, "trailers")) {
1808
0
        retour->keep_alive_trailers = 1;
1809
0
      }
1810
0
    }
1811
0
  } else if (HEADER_IS(name, "Content-Encoding")) {
1812
0
    if (retour) {
1813
0
      char tempo[1100];
1814
0
      char *a = value;
1815
1816
0
      while(is_space(*a))
1817
0
        a++;
1818
0
      {
1819
0
        char *a = strchr(value, ';');
1820
1821
0
        if (a)
1822
0
          *a = '\0';
1823
0
      }
1824
      // Bound to tempo[1100]; no token => leave empty, don't read uninit tempo.
1825
0
      if (sscanf(a, "%1099s", tempo) == 1 && strlen(tempo) < 64)
1826
0
        strcpybuff(retour->contentencoding, tempo);
1827
0
      else
1828
0
        retour->contentencoding[0] = '\0';
1829
      /* A coding to undo (or one we can not undo, which must fail the fetch
1830
         rather than save the coded bytes as the page) */
1831
0
      if (hts_codec_parse(retour->contentencoding) != HTS_CODEC_IDENTITY)
1832
0
        retour->compressed = 1;
1833
0
    }
1834
0
  } else if (HEADER_IS(name, "Retry-After")) {
1835
0
    if (retour) {
1836
      /* uncapped: treathead() has no opt, so the caller clips it */
1837
0
      retour->retry_after = hts_parse_retry_after(value, time(NULL));
1838
0
    }
1839
0
  } else if (HEADER_IS(name, "Location")) {
1840
0
    if (retour) {
1841
0
      if (retour->location) {
1842
0
        const hts_span v = header_value(value);
1843
1844
0
        if (!hts_buf_put_span(hts_buf_at(retour->location, HTS_LOCATION_SIZE),
1845
0
                              v)) {
1846
          /* no opt here, so this only reaches a registered log callback */
1847
0
          hts_log_print(NULL, LOG_WARNING,
1848
0
                        "Location header too long (%d bytes), redirect ignored",
1849
0
                        (int) v.len);
1850
0
        } else if (!hts_location_is_safe(retour->location)) {
1851
0
          hts_log_print(NULL, LOG_WARNING,
1852
0
                        "Location naming a post token, redirect ignored");
1853
0
          retour->location[0] = '\0';
1854
0
        }
1855
0
      }
1856
0
    }
1857
0
  } else if (HEADER_IS(name, "Set-Cookie") && cookie != NULL) {
1858
0
    hts_span rest = hts_span_of(value), n, v;
1859
0
    char domain[COOKIE_MAX_DOMAIN]; // .netscape.com
1860
0
    char scoped[COOKIE_MAX_DOMAIN]; // adr without userinfo, brackets or port
1861
0
    char path[COOKIE_MAX_PATH];     // /
1862
0
    char defpath[COOKIE_MAX_PATH];
1863
0
    char cook_name[256];        // nom cookie (MYCOOK)
1864
0
    char BIGSTK cook_value[8192];       // valeur (ID=toto,S=1234)
1865
0
    const int64_t now = (int64_t) time(NULL);
1866
1867
    /* Refuse a host cookie_host() cannot scope, and one too long for the
1868
       default-domain copy below (that would abort the mirror). */
1869
0
    if (adr != NULL &&
1870
0
        (strlen(adr) >= sizeof(domain) || !cookie_host(adr, HTS_SIZED(scoped))))
1871
0
      return;
1872
0
    {
1873
0
      char name[256];
1874
0
      char BIGSTK value[8192];
1875
0
      hts_boolean has_domain = HTS_FALSE;
1876
0
      hts_boolean has_max_age = HTS_FALSE;
1877
0
      hts_boolean has_expires = HTS_FALSE;
1878
0
      int64_t max_age_when = 0, expires_when = 0;
1879
0
      cookie_attr attr = {.host_only = HTS_FALSE,
1880
0
                          .secure = HTS_FALSE,
1881
0
                          .http_only = HTS_FALSE,
1882
0
                          .expires = 0};
1883
0
      hts_boolean first = HTS_TRUE;
1884
1885
0
      name[0] = value[0] = '\0';
1886
      //
1887
1888
      /* raw, because cookie_set() normalises and doing that twice is not the
1889
         same as doing it once; no adr means empty, which it refuses */
1890
0
      strcpybuff(domain, adr != NULL ? adr : "");
1891
0
      {
1892
0
        const size_t dlen = cookie_default_path_len(fil, sizeof(defpath));
1893
1894
0
        defpath[0] = '\0';
1895
0
        if (dlen == 0)
1896
0
          strcpybuff(defpath, "/");
1897
0
        else
1898
0
          strncatbuff(defpath, fil, dlen);
1899
0
      }
1900
0
      strcpybuff(path, defpath);
1901
0
      strcpybuff(cook_name, "");
1902
0
      strcpybuff(cook_value, "");
1903
      // read every pair up to the end of the header
1904
0
      while (hts_param_next(&rest, ';', &n, &v)) {
1905
        // a name stops at a blank or a quote, so "a b=c" is the bare word a
1906
0
        const hts_span key = hts_span_trim(n, HTS_SPACES, HTS_SPACES);
1907
0
        size_t word = 0;
1908
1909
0
        v = hts_span_trim(v, HTS_REALSPACES, HTS_REALSPACES);
1910
0
        while (word < key.len && !is_space(key.p[word]))
1911
0
          word++;
1912
0
        if (hts_span_present(v) && word == key.len) {
1913
          /* RFC 6265 4.1.1 makes the quotes part of a quoted cookie-value. */
1914
0
          if (key.len > 0 && key.len < 200 && v.len < 8000) {
1915
            /* both fit, by the bounds above */
1916
0
            (void) !hts_buf_put_span_clip(HTS_BUF(name), key);
1917
0
            (void) !hts_buf_put_span_clip(HTS_BUF(value), v);
1918
0
            if (first) {
1919
              // the first pair is the cookie, and "name=" may erase one
1920
0
              strcpybuff(cook_name, name);
1921
0
              strcpybuff(cook_value, value);
1922
0
            } else if (hts_streq_ci(name, "domain")) {
1923
0
              if (v.len == 0 || strcmp(value, ".") == 0) {
1924
                // ignored, so the cookie stays on the host
1925
0
              } else if (v.len < sizeof(domain) - 1) {
1926
0
                strcpybuff(domain, value);
1927
0
                has_domain = HTS_TRUE;
1928
0
              } else {
1929
0
                cook_name[0] = 0;
1930
0
                break;
1931
0
              }
1932
0
            } else if (hts_streq_ci(name, "path")) {
1933
0
              if (value[0] != '/') {
1934
0
                strcpybuff(path, defpath); // RFC 6265 5.2.4
1935
0
              } else if (v.len < sizeof(path) - 1) {
1936
0
                strcpybuff(path, value);
1937
0
              } else {
1938
0
                cook_name[0] = 0;
1939
0
                break;
1940
0
              }
1941
0
            } else if (hts_streq_ci(name, "max-age")) {
1942
0
              int64_t when;
1943
1944
              // an invalid value is ignored, not a reset (5.3)
1945
0
              if (cookie_max_age_time(value, now, &when)) {
1946
0
                has_max_age = HTS_TRUE;
1947
0
                max_age_when = when;
1948
0
              }
1949
0
            } else if (hts_streq_ci(name, "expires")) {
1950
0
              int64_t when;
1951
1952
0
              if (cookie_expires_time(value, now, &when)) {
1953
0
                has_expires = HTS_TRUE;
1954
0
                expires_when = when;
1955
0
              }
1956
0
            } else if (hts_streq_ci(name, "secure")) {
1957
0
              attr.secure = HTS_TRUE;
1958
0
            } else if (hts_streq_ci(name, "httponly")) {
1959
0
              attr.http_only = HTS_TRUE;
1960
0
            }
1961
            // RFC 6265 5.2 ignores any other attribute, SameSite for example
1962
0
          }
1963
0
        } else { // a bare attribute, or the word before a blank
1964
0
          const hts_span attribute = hts_span_at(key.p, word);
1965
1966
0
          if (hts_span_eq_ci(attribute, hts_span_of("secure")))
1967
0
            attr.secure = HTS_TRUE;
1968
0
          else if (hts_span_eq_ci(attribute, hts_span_of("httponly")))
1969
0
            attr.http_only = HTS_TRUE;
1970
0
        }
1971
        // an unusable first pair leaves no cookie, so the header is ignored
1972
0
        first = HTS_FALSE;
1973
0
      }
1974
0
      if (strnotempty(cook_name)) {     // cookie?
1975
        /* Max-Age outranks Expires (RFC 6265 5.3 step 3) */
1976
0
        attr.expires =
1977
0
            has_max_age ? max_age_when : (has_expires ? expires_when : 0);
1978
0
        attr.host_only = !has_domain;
1979
1980
        // a Domain= the host may not claim drops the cookie (5.3 step 6)
1981
0
        if (!has_domain ||
1982
0
            (adr != NULL && cookie_domain_allowed(domain, scoped))) {
1983
          /* RFC 6265bis 5.6: plain http may neither set a Secure cookie nor
1984
             shadow, replace or erase one */
1985
0
          if (adr != NULL && !hts_starts_with_ci(adr, "https://") &&
1986
0
              (attr.secure ||
1987
0
               cookie_is_secure_record(cookie, cook_name, domain, path))) {
1988
0
            hts_log_print(
1989
0
                opt, LOG_WARNING,
1990
0
                "Cookies: ignored '%.64s' from plain http, because it "
1991
0
                "sets or hides a Secure cookie (%s)",
1992
0
                cook_name, adr_nologin(opt, adr));
1993
0
          } else if (attr.expires != 0 && attr.expires <= now) {
1994
0
            cookie_remove(cookie, cook_name, domain, path);
1995
0
          } else if (cookie_set_capped(cookie, cook_name, cook_value, domain,
1996
0
                                       path, &attr) != 0) {
1997
0
            hts_log_print(opt, LOG_WARNING,
1998
0
                          "Cookies: the jar did not store '%.64s' set by %s",
1999
0
                          cook_name, adr_nologin(opt, adr));
2000
0
          }
2001
0
        }
2002
0
      }
2003
0
    }
2004
0
  }
2005
0
}
2006
2007
// HTTP status code -> reason phrase (per RFC), or NULL if unknown.
2008
0
const char *infostatuscode_const(int statuscode) {
2009
0
  return hts_status_reason(statuscode);
2010
0
}
2011
2012
/* Contract in httrack-library.h. */
2013
0
HTSEXT_API void infostatuscode_sized(char *msg, size_t size, int statuscode) {
2014
0
  const char *const text = infostatuscode_const(statuscode);
2015
2016
0
  assertf(size != 0);
2017
0
  if (text != NULL) {
2018
0
    strclipbuff(msg, size, text);
2019
0
  } else if (strnotempty(msg) == 0) {
2020
0
    strclipbuff(msg, size, "Unknown error");
2021
0
  }
2022
0
}
2023
2024
// the 64 bytes the deprecated contract documents
2025
0
HTSEXT_API void infostatuscode(char *msg, int statuscode) {
2026
0
  infostatuscode_sized(msg, 64, statuscode);
2027
0
}
2028
2029
/* Wait up to timeout seconds for soc to be readable, or writable when for_write
2030
   is set. No exception set, because POSIX reports urgent data there. */
2031
0
static hts_boolean soc_wait(T_SOC soc, int timeout, hts_boolean for_write) {
2032
0
  fd_set fds;
2033
0
  struct timeval tv;
2034
0
  const int isoc = (int) soc;
2035
2036
0
  if (soc == INVALID_SOCKET)
2037
0
    return HTS_FALSE;
2038
0
  assertf(isoc == soc);
2039
0
  if (!hts_soc_selectable(isoc))
2040
0
    return HTS_FALSE;
2041
0
  FD_ZERO(&fds);
2042
0
  FD_SET(isoc, &fds);
2043
0
  tv.tv_sec = timeout;
2044
0
  tv.tv_usec = 0;
2045
0
  select(isoc + 1, for_write ? NULL : &fds, for_write ? &fds : NULL, NULL, &tv);
2046
0
  return FD_ISSET(isoc, &fds) ? HTS_TRUE : HTS_FALSE;
2047
0
}
2048
2049
0
int check_readinput(htsblk *r) { return soc_wait(r->soc, 0, HTS_FALSE); }
2050
2051
0
int check_readinput_t(T_SOC soc, int timeout) {
2052
0
  return soc_wait(soc, timeout, HTS_FALSE);
2053
0
}
2054
2055
0
int check_writeinput_t(T_SOC soc, int timeout) {
2056
0
  return soc_wait(soc, timeout, HTS_TRUE);
2057
0
}
2058
2059
/* Class the live errno now: back_wait() sees it after free and fflush and
2060
   would rewrite this as a retryable connection error. */
2061
0
static void classify_write_error(htsblk *r) {
2062
0
  r->statuscode =
2063
0
      check_fatal_io_errno() ? STATUSCODE_IO_FATAL : STATUSCODE_IO_ERROR;
2064
0
  strcpybuff(r->msg, "Write error on disk");
2065
0
}
2066
2067
0
hts_boolean hts_inmem_size_fits(LLint size) {
2068
0
  return size >= 0 && size < INT32_MAX ? HTS_TRUE : HTS_FALSE;
2069
0
}
2070
2071
/* A line-mode call reads at most this many bytes, CRs included. */
2072
0
#define HTS_XFREAD_LINE_CALL_MAX 256
2073
/* Returned by hts_peek() when it must not peek on this transport. */
2074
0
#define PEEK_UNSUPPORTED (-100)
2075
2076
/* Set once an MPTCP socket exists on a kernel that may ignore MSG_PEEK. */
2077
static volatile int hts_peek_unsafe = 0;
2078
/* Set by the self-test hook. */
2079
static volatile int hts_peek_forced_off = 0;
2080
/* Line-mode calls that fell back to the bytewise loop, for the self-test. */
2081
static int hts_xfread_bytewise_calls = 0;
2082
2083
#if HTS_INET_MPTCP && !HTS_INET_MPTCP_DARWIN
2084
/* Can MSG_PEEK on an MPTCP socket consume the data? Linux 5.6 to 5.12 ignore
2085
   the flag, and an unreadable version counts as one of them. */
2086
0
static hts_boolean hts_mptcp_peek_is_broken(void) {
2087
0
  struct utsname u;
2088
0
  int major = 0, minor = 0;
2089
2090
0
  if (uname(&u) != 0 || sscanf(u.release, "%d.%d", &major, &minor) != 2)
2091
0
    return HTS_TRUE;
2092
0
  return major < 5 || (major == 5 && minor < 13) ? HTS_TRUE : HTS_FALSE;
2093
0
}
2094
#endif
2095
2096
0
void hts_peek_force_off(hts_boolean off) {
2097
0
  hts_store_release_int(&hts_peek_forced_off, off ? 1 : 0);
2098
0
}
2099
2100
0
int hts_xfread_bytewise_count(void) { return hts_xfread_bytewise_calls; }
2101
2102
/* Copy up to size buffered bytes without consuming them. Returns the count, 0
2103
   when TLS has nothing decrypted yet, READ_EOF, READ_ERROR or PEEK_UNSUPPORTED.
2104
   Only call it when the transport has data, as for hts_read(). */
2105
0
static int hts_peek(htsblk *r, hts_buf buff) {
2106
0
  int ret;
2107
2108
0
  if (r->is_file || hts_load_acquire_int(&hts_peek_unsafe) ||
2109
0
      hts_load_acquire_int(&hts_peek_forced_off))
2110
0
    return PEEK_UNSUPPORTED;
2111
#if HTS_USEOPENSSL
2112
  if (r->ssl) {
2113
    sigpipe_mask m;
2114
2115
    sigpipe_hold(&m);
2116
    ret = SSL_peek(r->ssl_con, buff.p, hts_sat_int(buff.size));
2117
    sigpipe_release(&m);
2118
    if (ret <= 0) {
2119
      const int err_code = SSL_get_error(r->ssl_con, ret);
2120
2121
      if (err_code == SSL_ERROR_WANT_READ || err_code == SSL_ERROR_WANT_WRITE)
2122
        return 0;
2123
      return err_code == SSL_ERROR_ZERO_RETURN ? READ_EOF : READ_ERROR;
2124
    }
2125
    return ret;
2126
  }
2127
#endif
2128
0
  ret = (int) recv(r->soc, buff.p, hts_sat_int(buff.size), MSG_PEEK);
2129
0
  if (ret == 0)
2130
0
    return READ_EOF;
2131
0
  return ret < 0 ? READ_ERROR : ret;
2132
0
}
2133
2134
typedef struct xfread_line_state {
2135
  hts_boolean lf_detected;
2136
  hts_boolean at_beginning;
2137
} xfread_line_state;
2138
2139
/* Appends c at adr[*size] unless it is a CR, and advances *size. A NULL adr is
2140
   a dry run. Returns whether the call must stop after c: on a blank line, on an
2141
   LF opening the call, or on any LF when bufl is HTS_XFREAD_LINE. */
2142
static hts_boolean xfread_line_step(xfread_line_state *st, char *adr,
2143
0
                                    LLint *size, char c, int bufl) {
2144
0
  hts_boolean stop = HTS_FALSE;
2145
2146
0
  if (c == 10) {
2147
0
    if (st->lf_detected || st->at_beginning || bufl < 0)
2148
0
      stop = HTS_TRUE;
2149
0
    st->lf_detected = HTS_TRUE;
2150
0
  }
2151
0
  if (c != 13) {
2152
0
    if (c != 10)
2153
0
      st->lf_detected = HTS_FALSE;
2154
0
    if (adr != NULL)
2155
0
      adr[*size] = c;
2156
0
    (*size)++;
2157
0
    st->at_beginning = HTS_FALSE;
2158
0
  }
2159
0
  if (adr != NULL)
2160
0
    adr[*size] = '\0';
2161
0
  return stop;
2162
0
}
2163
2164
/* The bytewise line modes, the fallback when hts_peek() declines. */
2165
0
static int xfread_lines_bytewise(htsblk *r, int bufl) {
2166
0
  xfread_line_state st = {HTS_FALSE, HTS_TRUE};
2167
0
  int count = HTS_XFREAD_LINE_CALL_MAX;
2168
0
  int tot_nl = 0;
2169
0
  int nl;
2170
2171
0
  do {
2172
0
    char c;
2173
2174
0
    if (r->size >= HTS_LINE_BLOCK_SIZE - 2)
2175
0
      return READ_INTERNAL_ERROR;
2176
0
    nl = hts_read(r, hts_buf_at(&c, 1));
2177
0
    if (nl < 0)
2178
0
      return nl;
2179
0
    if (nl > 0 && xfread_line_step(&st, r->adr, &r->size, c, bufl))
2180
0
      count = 0;
2181
0
    tot_nl += nl;
2182
0
  } while (--count > 0 && check_readinput(r));
2183
0
  return tot_nl;
2184
0
}
2185
2186
/* The line modes. Reads a peeked block in one go, consuming exactly what the
2187
   bytewise loop would, so the bytes left on the socket are the same. */
2188
0
static int xfread_lines(htsblk *r, int bufl) {
2189
0
  char buff[HTS_XFREAD_LINE_CALL_MAX];
2190
0
  xfread_line_state st = {HTS_FALSE, HTS_TRUE};
2191
0
  hts_boolean overflow = HTS_FALSE;
2192
0
  int avail, want, got, i;
2193
2194
0
  if (r->adr == NULL) {
2195
0
    r->adr = (char *) malloct(HTS_LINE_BLOCK_SIZE);
2196
0
    r->size = 0;
2197
0
    if (r->adr == NULL)
2198
0
      return READ_INTERNAL_ERROR;
2199
0
  }
2200
0
  if (r->size >= HTS_LINE_BLOCK_SIZE - 2)
2201
0
    return READ_INTERNAL_ERROR;
2202
0
  avail = hts_peek(r, HTS_BUF(buff));
2203
0
  if (avail == PEEK_UNSUPPORTED) {
2204
0
    hts_xfread_bytewise_calls++;
2205
0
    return xfread_lines_bytewise(r, bufl);
2206
0
  }
2207
0
  if (avail <= 0)
2208
0
    return avail;
2209
  /* Dry run: where would the bytewise loop stop? */
2210
0
  {
2211
0
    xfread_line_state dry = st;
2212
0
    LLint size = r->size;
2213
2214
0
    for (want = 0; want < avail;) {
2215
0
      if (size >= HTS_LINE_BLOCK_SIZE - 2) {
2216
0
        overflow = HTS_TRUE;
2217
0
        break;
2218
0
      }
2219
0
      if (xfread_line_step(&dry, NULL, &size, buff[want++], bufl))
2220
0
        break;
2221
0
    }
2222
0
  }
2223
0
  got = hts_read(r, hts_buf_at(buff, want));
2224
0
  if (got <= 0) /* peeked, so the read cannot fail */
2225
0
    return got;
2226
0
  for (i = 0; i < got; i++) {
2227
0
    if (xfread_line_step(&st, r->adr, &r->size, buff[i], bufl))
2228
0
      break;
2229
0
  }
2230
  /* The bytewise loop fails when it needs a byte past the line buffer. */
2231
0
  return overflow && got == want ? READ_INTERNAL_ERROR : got;
2232
0
}
2233
2234
// Read one block: bufl is a byte count, or one of the HTS_XFREAD_* line modes.
2235
// Note: the +1 in the mallocs is the trailing NUL appended to the data.
2236
0
LLint http_xfread1(htsblk * r, int bufl) {
2237
0
  int nl = -1;
2238
2239
  // EOF
2240
0
  if (r->totalsize >= 0 && r->size == r->totalsize) {
2241
0
    return READ_EOF;
2242
0
  }
2243
2244
0
  if (bufl > 0) {
2245
0
    if (!r->is_write) {         // stocker en mémoire
2246
      // Reject a hostile Content-Length, or an endless stream.
2247
0
      const LLint inmem_want =
2248
0
          (r->totalsize >= 0) ? r->totalsize : (r->size + bufl);
2249
0
      if (!hts_inmem_size_fits(inmem_want)) {
2250
0
        r->statuscode = STATUSCODE_INVALID;
2251
0
        strcpybuff(r->msg, "In-memory content too large");
2252
0
        return READ_ERROR;
2253
0
      }
2254
0
      if (r->totalsize >= 0) {  // totalsize déterminé ET ALLOUE
2255
0
        if (r->adr == NULL) {
2256
0
          r->adr = (char *) malloct((size_t) r->totalsize + 1);
2257
0
          r->size = 0;
2258
0
        }
2259
0
        if (r->adr != NULL) {
2260
          // lecture
2261
          /* Signed first: a body longer than its announced totalsize makes
2262
             this negative, and as a size_t it would drive a read past adr. */
2263
0
          const LLint remaining = r->totalsize - r->size;
2264
0
          const size_t req_size = remaining > 0 ? (size_t) remaining : 0;
2265
0
          const hts_buf rb = hts_buf_at(r->adr + (int) r->size, req_size);
2266
2267
0
          nl = req_size > 0 ? hts_read(r, rb) : 0;
2268
          // nouvelle taille
2269
0
          if (nl >= 0)
2270
0
            r->size += nl;
2271
2272
          /*
2273
             if (r->size >= r->totalsize)
2274
             nl = -1;  // break
2275
           */
2276
2277
0
          r->adr[r->size] = '\0';       // caractère NULL en fin au cas où l'on traite des HTML
2278
0
        }
2279
2280
0
      } else {                  // inconnu..
2281
        // réserver de la mémoire?
2282
0
        if (r->adr == NULL) {
2283
0
          r->adr = (char *) malloct(bufl + 1);
2284
0
          r->size = 0;
2285
0
        } else {
2286
0
          size_t alloc;
2287
0
          char *const grown =
2288
0
              hts_ckd_add(&alloc, (size_t) r->size, (size_t) bufl + 1)
2289
0
                  ? NULL
2290
0
                  : (char *) realloct(r->adr, alloc);
2291
2292
0
          if (grown == NULL) {
2293
            // On failure, keep what was read, as the size guard does.
2294
0
            return READ_ERROR;
2295
0
          }
2296
0
          r->adr = grown;
2297
0
        }
2298
2299
0
        if (r->adr != NULL) {
2300
0
          nl = hts_read(r, hts_buf_at(r->adr + (int) r->size, bufl));
2301
0
          if (nl > 0) {
2302
            // A failed shrink leaves the larger block, which still fits.
2303
0
            char *const fit =
2304
0
                (char *) realloct(r->adr, (size_t) r->size + nl + 1);
2305
2306
0
            if (fit != NULL)
2307
0
              r->adr = fit;
2308
0
            r->size += nl;
2309
0
            r->adr[r->size] = '\0';
2310
0
          }
2311
0
        }
2312
0
      }
2313
2314
      // No buffer is an error.
2315
0
      if (r->adr == NULL)
2316
0
        nl = READ_ERROR;
2317
2318
0
    } else {                    // stocker sur disque
2319
0
      char *buff;
2320
2321
0
      buff = (char *) malloct(bufl);
2322
0
      if (buff != NULL) {
2323
        // lecture
2324
0
        nl = hts_read(r, hts_buf_at(buff, bufl));
2325
        // nouvelle taille
2326
0
        if (nl > 0) {
2327
0
          r->size += nl;
2328
0
          if (!hts_fwrite_exact(buff, (size_t) nl, r->out)) {
2329
0
            classify_write_error(r);
2330
0
            nl = READ_ERROR;
2331
0
          }
2332
0
        }
2333
2334
        // libérer bloc tempo
2335
0
        freet(buff);
2336
0
      } else
2337
0
        nl = READ_ERROR;
2338
2339
      /* The tail stdio held is written here, and glibc's later fclose() returns
2340
         0 once this flush has taken the error. */
2341
0
      if ((nl < 0) && (r->out != NULL) && fflush(r->out) != 0 &&
2342
0
          !statuscode_is_write_error(r->statuscode)) {
2343
0
        classify_write_error(r);
2344
0
        nl = READ_ERROR;
2345
0
      }
2346
2347
0
    }                           // stockage disque ou mémoire
2348
2349
0
  } else {
2350
0
    nl = xfread_lines(r, bufl);
2351
0
  }
2352
  /* Ahead of the EOF test below: r->size is advanced above the fwrite that
2353
     failed, so a body completed by that very read would report a clean EOF. */
2354
0
  if (nl == READ_ERROR && statuscode_is_write_error(r->statuscode)) {
2355
0
    return READ_ERROR;
2356
0
  }
2357
  // EOF
2358
0
  if (r->totalsize >= 0 && r->size == r->totalsize) {
2359
0
    return READ_EOF;
2360
0
  } else {
2361
0
    return nl;
2362
0
  }
2363
0
}
2364
2365
0
hts_boolean socket_set_nonblocking(T_SOC soc, hts_boolean nonblocking) {
2366
#ifdef _WIN32
2367
  unsigned long p = nonblocking ? 1 : 0;
2368
2369
  return ioctlsocket(soc, FIONBIO, &p) == 0 ? HTS_TRUE : HTS_FALSE;
2370
#else
2371
0
  const int flags = fcntl(soc, F_GETFL, 0);
2372
0
  const int wanted = nonblocking ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
2373
2374
0
  if (flags == -1 || fcntl(soc, F_SETFL, wanted) == -1)
2375
0
    return HTS_FALSE;
2376
0
  return HTS_TRUE;
2377
0
#endif
2378
0
}
2379
2380
/* The only mechanism that also covers OpenSSL's own writes, and it exists on
2381
   macOS and the BSDs alone. */
2382
0
void socket_set_nosigpipe(T_SOC soc) {
2383
#ifdef SO_NOSIGPIPE
2384
  const int on = 1;
2385
2386
  (void) setsockopt(soc, SOL_SOCKET, SO_NOSIGPIPE, (const char *) &on,
2387
                    sizeof(on));
2388
#else
2389
0
  (void) soc;
2390
0
#endif
2391
0
}
2392
2393
/* Resolved by hts_init(), before any crawl thread reads them. */
2394
static hts_boolean hts_mptcp_usable = HTS_FALSE;
2395
static hts_boolean hts_mptcp_on_by_default = HTS_FALSE;
2396
#if HTS_INET_MPTCP
2397
/* macOS is left unverified, so its multipath sockets are never peeked. */
2398
static hts_boolean hts_mptcp_peek_broken = HTS_TRUE;
2399
#endif
2400
2401
#if HTS_INET_MPTCP && !HTS_INET_MPTCP_DARWIN
2402
/* Read one small integer sysctl, or -1 when the file cannot be read. */
2403
0
static long hts_mptcp_sysctl(const char *path) {
2404
0
  FILE *fp = fopen(path, "rb");
2405
0
  long value = -1;
2406
2407
0
  if (fp == NULL)
2408
0
    return -1;
2409
0
  if (fscanf(fp, "%ld", &value) != 1)
2410
0
    value = -1;
2411
0
  fclose(fp);
2412
0
  return value;
2413
0
}
2414
2415
/* Can the kernel recover from a SYN a middlebox dropped for its MPTCP option?
2416
   Without the retry and blackhole detection, such a host costs a timeout. */
2417
0
static hts_boolean hts_mptcp_kernel_recovers(void) {
2418
0
  static const char retrans[] =
2419
0
      "/proc/sys/net/mptcp/syn_retrans_before_tcp_fallback";
2420
2421
0
  if (hts_mptcp_sysctl(retrans) < 0)
2422
0
    return HTS_FALSE;
2423
0
  if (hts_mptcp_sysctl("/proc/sys/net/mptcp/blackhole_timeout") <= 0)
2424
0
    return HTS_FALSE;
2425
0
  return HTS_TRUE;
2426
0
}
2427
#endif
2428
2429
/* Being able to open an MPTCP socket is not enough to turn it on by default. */
2430
1
static void hts_mptcp_probe(void) {
2431
#if HTS_INET_MPTCP_DARWIN
2432
  /* Off by default, because macOS has neither the blackhole sysctls nor a way
2433
     to see whether a connection negotiated it. */
2434
  const T_SOC soc = (T_SOC) socket(AF_MULTIPATH, SOCK_STREAM, 0);
2435
2436
  if (soc != INVALID_SOCKET) {
2437
    close(soc);
2438
    hts_mptcp_usable = HTS_TRUE;
2439
  }
2440
#elif HTS_INET_MPTCP
2441
1
  const T_SOC soc = (T_SOC) socket(AF_INET, SOCK_STREAM, IPPROTO_MPTCP);
2442
2443
1
  if (soc != INVALID_SOCKET) {
2444
0
    close(soc);
2445
0
    hts_mptcp_usable = HTS_TRUE;
2446
0
    hts_mptcp_on_by_default = hts_mptcp_kernel_recovers();
2447
0
    hts_mptcp_peek_broken = hts_mptcp_peek_is_broken();
2448
0
  }
2449
1
#endif
2450
1
}
2451
2452
0
hts_boolean hts_mptcp_available(void) { return hts_mptcp_usable; }
2453
2454
0
hts_boolean hts_mptcp_reports(void) {
2455
0
  return HTS_INET_MPTCP_INFO ? HTS_TRUE : HTS_FALSE;
2456
0
}
2457
2458
/* Should this connection be opened with MPTCP? */
2459
0
static hts_boolean hts_mptcp_enabled(const httrackp *opt) {
2460
0
  if (!hts_mptcp_usable)
2461
0
    return HTS_FALSE;
2462
0
  if (opt->mptcp == HTS_DEFAULT)
2463
0
    return hts_mptcp_on_by_default;
2464
0
  return opt->mptcp == HTS_TRUE ? HTS_TRUE : HTS_FALSE;
2465
0
}
2466
2467
T_SOC hts_socket_client(int family, const httrackp *opt,
2468
0
                        hts_boolean will_bind) {
2469
0
  T_SOC soc = INVALID_SOCKET;
2470
2471
#if HTS_INET_MPTCP_DARWIN
2472
  /* AF_MULTIPATH cannot bind on macOS, so a caller that binds gets TCP. */
2473
  if (!will_bind && hts_mptcp_enabled(opt))
2474
    soc = (T_SOC) socket(AF_MULTIPATH, SOCK_STREAM, 0);
2475
#elif HTS_INET_MPTCP
2476
  (void) will_bind;
2477
  /* A refusal here is the kernel declining the protocol. The peer declining it
2478
     is not visible: the kernel completes the handshake as plain TCP. */
2479
0
  if (hts_mptcp_enabled(opt))
2480
0
    soc = (T_SOC) socket(family, SOCK_STREAM, IPPROTO_MPTCP);
2481
#else
2482
  (void) opt;
2483
  (void) will_bind;
2484
#endif
2485
0
#if HTS_INET_MPTCP
2486
0
  if (soc != INVALID_SOCKET && hts_mptcp_peek_broken)
2487
0
    hts_store_release_int(&hts_peek_unsafe, 1);
2488
0
#endif
2489
0
  if (soc == INVALID_SOCKET)
2490
0
    soc = (T_SOC) socket(family, SOCK_STREAM, 0);
2491
0
  if (soc != INVALID_SOCKET)
2492
0
    socket_set_nosigpipe(soc);
2493
0
  return soc;
2494
0
}
2495
2496
int hts_socket_connect(T_SOC soc, const struct sockaddr *addr, SOClen len,
2497
0
                       const httrackp *opt) {
2498
#if HTS_INET_MPTCP_DARWIN
2499
  /* connectx() is how a multipath socket is connected, and it accepts an
2500
     ordinary socket too, so the fallback needs no second path here. A NULL opt
2501
     is the caller saying this socket is not a multipath one. */
2502
  if (opt != NULL && hts_mptcp_enabled(opt)) {
2503
    sa_endpoints_t ep;
2504
2505
    memset(&ep, 0, sizeof(ep));
2506
    ep.sae_dstaddr = addr;
2507
    ep.sae_dstaddrlen = (socklen_t) len;
2508
    return connectx(soc, &ep, SAE_ASSOCID_ANY, 0, NULL, 0, NULL, NULL);
2509
  }
2510
#else
2511
0
  (void) opt;
2512
0
#endif
2513
0
  return connect(soc, addr, len);
2514
0
}
2515
2516
hts_boolean hts_socket_connect_started(T_SOC soc, const SOCaddr *server,
2517
                                       const httrackp *opt,
2518
0
                                       hts_boolean *pending) {
2519
0
  const hts_boolean wait = hts_socket_connect(soc, &SOCaddr_sockaddr(*server),
2520
0
                                              SOCaddr_size(*server), opt) != 0;
2521
2522
0
  if (pending != NULL)
2523
0
    *pending = wait;
2524
0
  return !wait || hts_socket_connect_pending();
2525
0
}
2526
2527
0
hts_boolean hts_socket_is_mptcp(T_SOC soc) {
2528
0
#if HTS_INET_MPTCP_INFO
2529
0
  struct mptcp_info info;
2530
0
  socklen_t len = (socklen_t) sizeof(info);
2531
2532
  /* Refused on a socket the kernel fell back to TCP, where SO_PROTOCOL still
2533
     reads IPPROTO_MPTCP and so answers nothing. */
2534
0
  if (getsockopt(soc, SOL_MPTCP, MPTCP_INFO, (char *) &info, &len) != 0)
2535
0
    return HTS_FALSE;
2536
0
  return HTS_TRUE;
2537
#else
2538
  (void) soc;
2539
  return HTS_FALSE;
2540
#endif
2541
0
}
2542
2543
0
void hts_mptcp_account(httrackp *opt, T_SOC soc) {
2544
  /* Without fallback reporting, every connection would count as multipath. */
2545
0
  if (!hts_mptcp_reports() || !hts_mptcp_enabled(opt))
2546
0
    return;
2547
0
  if (hts_socket_is_mptcp(soc))
2548
0
    opt->mptcp_connections++;
2549
0
  else
2550
0
    opt->mptcp_fallbacks++;
2551
0
}
2552
2553
0
int connect_socket_error(T_SOC soc) {
2554
0
  int soerr = 0;
2555
0
  socklen_t len = (socklen_t) sizeof(soerr);
2556
2557
0
  if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (char *) &soerr, &len) != 0)
2558
0
    return -1;
2559
0
  return soerr;
2560
0
}
2561
2562
0
T_SOC newhttp(httrackp *opt, const char *_iadr, htsblk *retour, int port) {
2563
0
  return newhttp_addr(opt, _iadr, retour, port, -1, NULL);
2564
0
}
2565
2566
/* Resolve the -%b host into res. A bare IPv6 literal gets brackets, or the
2567
   cache key would read its last group as a port. */
2568
static hts_dns_status newhttp_bind_resolve(httrackp *opt, const char *host,
2569
0
                                           hts_dns_result *res) {
2570
0
  char buf[HTS_BINDHOST_MAXSIZE + 3];
2571
2572
0
  if (host[0] != '[' && strchr(host, ':') != strrchr(host, ':') &&
2573
0
      strlen(host) <= HTS_BINDHOST_MAXSIZE) {
2574
0
    snprintf(buf, sizeof(buf), "[%s]", host);
2575
0
    host = buf;
2576
0
  }
2577
0
  return hts_dns_resolve(opt, host, opt->timeout, &opt->state.stop, res);
2578
0
}
2579
2580
/* Open a non-blocking connect to *server from the first bind_dns address of
2581
   its family that binds. On failure, set retour's message, and set *try_next
2582
   when the next address may work. */
2583
static T_SOC newhttp_open(httrackp *opt, htsblk *retour, SOCaddr *server,
2584
                          int port, const hts_dns_result *bind_dns,
2585
0
                          hts_boolean *try_next) {
2586
0
  const int family = SOCaddr_sinfamily(*server);
2587
0
  const SOCaddr *local = NULL;
2588
0
  T_SOC soc = INVALID_SOCKET;
2589
0
  int i;
2590
2591
0
  assertf(retour != NULL);
2592
0
  *try_next = HTS_FALSE;
2593
  // make a copy for external clients
2594
0
  SOCaddr_copy_SOCaddr(retour->address, *server);
2595
0
  retour->address_size = SOCaddr_size(retour->address);
2596
2597
0
  if (bind_dns != NULL) {
2598
0
    hts_boolean family_seen = HTS_FALSE;
2599
2600
0
    for (i = 0; i < bind_dns->count && soc == INVALID_SOCKET; i++) {
2601
0
      if (SOCaddr_sinfamily(bind_dns->addr[i]) != family)
2602
0
        continue;
2603
0
      family_seen = HTS_TRUE;
2604
0
      local = &bind_dns->addr[i];
2605
      // a socket that binds cannot be a multipath one
2606
0
      soc = hts_socket_client(family, opt, HTS_TRUE);
2607
0
      retour->debugid = HTS_STAT.stat_sockid++;
2608
0
      if (soc == INVALID_SOCKET)
2609
0
        break;
2610
0
      if (bind(soc, &SOCaddr_sockaddr(*local), SOCaddr_size(*local)) != 0) {
2611
0
        const int last_errno = hts_socket_errno();
2612
0
        char errbuf[HTS_STRERROR_SIZE];
2613
2614
0
        htsblk_failf(retour, HTS_DNS_BIND_PREFIX "%s",
2615
0
                     hts_strerror(last_errno, HTS_BUF(errbuf)));
2616
0
        deletesoc(soc);
2617
0
        soc = INVALID_SOCKET;
2618
0
        local = NULL;
2619
0
      }
2620
0
    }
2621
0
    if (!family_seen)
2622
0
      htsblk_failf(retour, HTS_DNS_BIND_PREFIX "%s",
2623
0
                   "no address of the server's family");
2624
0
    if (soc == INVALID_SOCKET && local == NULL) {
2625
0
      *try_next = HTS_TRUE;
2626
0
      return INVALID_SOCKET;
2627
0
    }
2628
0
  } else {
2629
0
    soc = hts_socket_client(family, opt, HTS_FALSE);
2630
0
    retour->debugid = HTS_STAT.stat_sockid++;
2631
0
  }
2632
0
  if (soc == INVALID_SOCKET) {
2633
0
    const int last_errno = hts_socket_errno();
2634
0
    char errbuf[HTS_STRERROR_SIZE];
2635
2636
0
    htsblk_failf(retour, "Unable to create a socket: %s",
2637
0
                 hts_strerror(last_errno, HTS_BUF(errbuf)));
2638
0
    return INVALID_SOCKET;
2639
0
  }
2640
0
  SOCaddr_initport(*server, port);
2641
2642
0
  if (!socket_set_nonblocking(soc, HTS_TRUE)) {
2643
0
    const int last_errno = hts_socket_errno();
2644
0
    char errbuf[HTS_STRERROR_SIZE];
2645
2646
0
    htsblk_failf(retour, "Non-blocking socket failed: %s",
2647
0
                 hts_strerror(last_errno, HTS_BUF(errbuf)));
2648
0
    deletesoc(soc);
2649
0
    return INVALID_SOCKET;
2650
0
  }
2651
0
  HTS_STAT.last_connect = mtime_local();
2652
2653
  // non-blocking: back_wait sees how a pending connect ended
2654
0
  if (!hts_socket_connect_started(soc, server, local != NULL ? NULL : opt,
2655
0
                                  NULL)) {
2656
0
    const int last_errno = hts_socket_errno();
2657
0
    char errbuf[HTS_STRERROR_SIZE];
2658
2659
0
    htsblk_failf(retour, "Connect error: %s",
2660
0
                 hts_strerror(last_errno, HTS_BUF(errbuf)));
2661
0
    deletesoc(soc);
2662
0
    *try_next = HTS_TRUE;
2663
0
    return INVALID_SOCKET;
2664
0
  }
2665
0
  return soc;
2666
0
}
2667
2668
T_SOC newhttp_addr(httrackp *opt, const char *_iadr, htsblk *retour, int port,
2669
0
                   int addr_index, int *addr_count) {
2670
0
  return newhttp_addrs(opt, _iadr, retour, port, addr_index, 1, addr_count,
2671
0
                       NULL);
2672
0
}
2673
2674
T_SOC newhttp_addrs(httrackp *opt, const char *_iadr, htsblk *retour, int port,
2675
0
                    int addr_index, int tries, int *addr_count, int *skipped) {
2676
0
  T_SOC soc = INVALID_SOCKET; // descipteur de la socket
2677
2678
0
  if (addr_count != NULL) {
2679
0
    *addr_count = 0;
2680
0
  }
2681
0
  if (skipped != NULL) {
2682
0
    *skipped = 0;
2683
0
  }
2684
2685
0
  if (strcmp(_iadr, "file://") != 0) {  /* non fichier */
2686
0
    SOCaddr server;
2687
0
    hts_dns_result dns, bind_res;
2688
0
    const hts_dns_result *bind_dns = NULL;
2689
0
    hts_boolean try_next = HTS_FALSE;
2690
0
    char msg[sizeof(retour->msg)];
2691
0
    int t;
2692
2693
    // tester un éventuel id:pass et virer id:pass@ si détecté
2694
0
    const char *const iadr = jump_identification_const(_iadr);
2695
0
    const char *resolve_host = iadr;
2696
0
    char BIGSTK iadr2[HTS_URLMAXSIZE * 2];
2697
2698
0
    SOCaddr_clear(server);
2699
2700
    // tester un éventuel port
2701
0
    if (port == -1) {
2702
0
      const char *a = jump_toport_const(iadr);
2703
2704
#if HTS_USEOPENSSL
2705
      if (retour->ssl)
2706
        port = 443;
2707
      else
2708
        port = 80;              // port par défaut
2709
#else
2710
0
      port = 80;                // port par défaut
2711
0
#endif
2712
2713
0
      if (a != NULL) {
2714
        // folding a nonsense port into 0..65535 crawls one neither the link nor
2715
        // a port filter named; an empty "host:" just means the default (#614)
2716
0
        if (a[1] != '\0' && !hts_parse_url_port(a + 1, &port)) {
2717
0
          if (retour != NULL) {
2718
0
            htsblk_failf(retour, "Invalid port: %s", a + 1);
2719
0
          }
2720
0
          return INVALID_SOCKET;
2721
0
        }
2722
2723
0
        iadr2[0] = '\0';
2724
        // the address itself, without the ":port"
2725
0
        strncatbuff(iadr2, iadr, (int) (a - iadr));
2726
0
        resolve_host = iadr2;
2727
0
      }
2728
0
    }
2729
2730
    // resolve the full address list and pick the requested candidate; the
2731
    // scheduler retries the next index when a connect fails (dead IPv6 etc.)
2732
0
    (void) hts_dns_resolve(opt, resolve_host, opt->timeout, &opt->state.stop,
2733
0
                           &dns);
2734
0
    if (addr_count != NULL) {
2735
0
      *addr_count = dns.count;
2736
0
    }
2737
0
    if (addr_index < 0) {
2738
0
      tries = dns.count;
2739
0
      addr_index = hts_dns_preferred(opt, resolve_host);
2740
0
      if (addr_index >= dns.count)
2741
0
        addr_index = 0;
2742
0
    }
2743
0
    if (addr_index >= 0 && addr_index < dns.count) {
2744
0
      SOCaddr_copy_SOCaddr(server, dns.addr[addr_index]);
2745
0
    }
2746
2747
0
    if (!SOCaddr_is_valid(server)) {
2748
0
      if (retour != NULL) {
2749
0
        htsblk_failf(retour, HTS_DNS_FAIL_PREFIX "%s", hts_dns_strerror(&dns));
2750
0
      }
2751
0
      return INVALID_SOCKET;
2752
0
    }
2753
2754
0
    if (retour != NULL && strnotempty(retour->req.proxy.bindhost)) {
2755
0
      if (newhttp_bind_resolve(opt, retour->req.proxy.bindhost, &bind_res) !=
2756
0
          HTS_DNS_OK) {
2757
0
        htsblk_failf(retour, HTS_DNS_BIND_PREFIX "%s",
2758
0
                     hts_dns_strerror(&bind_res));
2759
0
        return INVALID_SOCKET;
2760
0
      }
2761
0
      bind_dns = &bind_res;
2762
0
    }
2763
2764
    /* A first connect skips addresses it cannot bind for or connect to at
2765
       once, and back_connect_next() does the same for a fallback. */
2766
0
    strcpybuff(msg, retour->msg);
2767
0
    for (t = 0; t < tries && t < dns.count; t++) {
2768
0
      SOCaddr_copy_SOCaddr(server, dns.addr[(addr_index + t) % dns.count]);
2769
0
      soc = newhttp_open(opt, retour, &server, port, bind_dns, &try_next);
2770
0
      if (soc != INVALID_SOCKET || !try_next)
2771
0
        break;
2772
0
      hts_log_print(opt, LOG_DEBUG, "skipping address %d/%d of %s: %s",
2773
0
                    (addr_index + t) % dns.count + 1, dns.count, resolve_host,
2774
0
                    retour->msg);
2775
0
    }
2776
0
    if (soc != INVALID_SOCKET) {
2777
      // a skipped address must not leave its reason on a working connect
2778
0
      strcpybuff(retour->msg, msg);
2779
0
      if (skipped != NULL) {
2780
0
        *skipped = t;
2781
0
      }
2782
0
    }
2783
2784
0
  } else {                      // on doit ouvrir un fichier local!
2785
    // il sera géré de la même manière qu'une socket (c'est idem!)
2786
2787
0
    soc = LOCAL_SOCKET_ID;      // pseudo-socket locale..
2788
    // soc sera remplacé lors d'un http_fopen() par un handle véritable!
2789
2790
0
  }                             // teste fichier local ou http
2791
2792
0
  return soc;
2793
0
}
2794
2795
// couper http://www.truc.fr/pub/index.html -> www.truc.fr /pub/index.html
2796
// retour=-1 si erreur.
2797
// si file://... alors adresse=file:// (et coupe le ?query dans ce cas)
2798
0
int ident_url_absolute(const char *url, lien_adrfil *adrfil) {
2799
0
  const char *rest = url;
2800
0
  int scheme = 0;
2801
2802
  // effacer adrfil->adr et adrfil->fil
2803
0
  adrfil->adr[0] = adrfil->fil[0] = '\0';
2804
2805
  // Reject an over-long URL: a root-relative path is copied whole into fil[].
2806
0
  if (strlen(url) >= HTS_URLMAXSIZE * 2)
2807
0
    return -1;
2808
2809
  // Scheme?
2810
0
  {
2811
0
    const char *a = url;
2812
2813
0
    while (hts_isalpha((unsigned char) *a))
2814
0
      a++;
2815
0
    if (*a == ':')
2816
0
      scheme = 1;
2817
0
  }
2818
2819
  // 1. optional scheme ":"
2820
0
  if (hts_skip_prefix_ci(&rest, "file:")) { // local file, for the tests
2821
0
    strcpybuff(adrfil->adr, "file://");
2822
0
  } else if (hts_skip_prefix_ci(&rest, "http:")) { // http leaves adr empty
2823
0
  } else if (hts_skip_prefix_ci(&rest, "ftp:")) {
2824
0
    strcpybuff(adrfil->adr, "ftp://");
2825
#if HTS_USEOPENSSL
2826
  } else if (hts_skip_prefix_ci(&rest, "https:")) {
2827
    strcpybuff(adrfil->adr, "https://");
2828
#endif
2829
0
  } else if (scheme) {
2830
0
    return -1; // an unknown scheme
2831
0
  }
2832
2833
  // 2. optional "//" authority
2834
0
  if (strncmp(rest, "//", 2) == 0)
2835
0
    rest += 2;
2836
2837
  // rest now points to the path (not net path)
2838
2839
  //## if (adrfil->adr[0]!=lOCAL_CHAR) {    // adrfil->adresse normale http
2840
0
  if (!hts_starts_with_ci(adrfil->adr, "file:")) { // not a local file
2841
0
    const char *p, *q;
2842
2843
0
    p = rest;
2844
2845
    // p pointe sur le début de l'adrfil->adresse, ex: www.truc.fr/sommaire/index.html
2846
0
    q = hts_authority_end(jump_identification_const(p));
2847
2848
    // chemin www... trop long!!
2849
0
    if ((((int) (q - p))) > HTS_URLMAXSIZE) {
2850
0
      return -1;                // erreur
2851
0
    }
2852
    // recopier adrfil->adresse www..
2853
0
    strncatbuff(adrfil->adr, p, ((int) (q - p)));
2854
    // *( adrfil->adr+( ((int) q) - ((int) p) ) )=0;  // faut arrêter la fumette!
2855
2856
0
    if (q[0] != '/') // the default page
2857
0
      strcatbuff(adrfil->fil, "/");
2858
0
    if (!hts_buf_try_cat(HTS_BUF(adrfil->fil), q))
2859
0
      return -1;
2860
    // SECURITE:
2861
    // simplifier url pour les ../
2862
0
    fil_simplifie(adrfil->fil);
2863
0
  } else { // a local file
2864
0
    const char *p;
2865
0
    size_t i;
2866
0
    char *a;
2867
2868
0
    p = rest;
2869
0
    if (*p == '/' || *p == '\\') {      /* adrfil->file:///.. */
2870
0
      strcatbuff(adrfil->fil, p);       // fichier local ; adrfil->adr="#"
2871
0
    } else {
2872
0
      if (*p == '\0' || p[1] != ':') {  /* empty path: not a DOS drive letter */
2873
0
        strcatbuff(adrfil->fil, "//");  /* adrfil->file://server/foo */
2874
0
        strcatbuff(adrfil->fil, p);
2875
0
      } else {
2876
0
        strcatbuff(adrfil->fil, p);     // adrfil->file://C:\..
2877
0
      }
2878
0
    }
2879
2880
0
    a = strchr(adrfil->fil, '?');
2881
0
    if (a)
2882
0
      *a = '\0';                /* couper query (inutile pour adrfil->file:// lors de la requête) */
2883
    // adrfil->filtrer les \\ -> / pour les fichiers DOS
2884
0
    for(i = 0; adrfil->fil[i] != '\0'; i++)
2885
0
      if (adrfil->fil[i] == '\\')
2886
0
        adrfil->fil[i] = '/';
2887
    // collapse ../ like the http branch above (path-traversal safety)
2888
0
    fil_simplifie(adrfil->fil);
2889
0
  }
2890
2891
  // no hostname
2892
0
  if (!strnotempty(adrfil->adr))
2893
0
    return -1;                  // erreur non reconnu
2894
2895
  // nommer au besoin.. (non utilisé normalement)
2896
0
  if (!strnotempty(adrfil->fil))
2897
0
    strcpybuff(adrfil->fil, "default-index.html");
2898
2899
  // host names are case-insensitive
2900
0
  hts_lowcase(jump_identification(adrfil->adr));
2901
2902
0
  return 0;
2903
0
}
2904
2905
/* Contract in htslib.h. */
2906
0
void fil_simplifie(char *f) {
2907
0
  char *a, *b;
2908
0
  char lc = '/';
2909
0
  int query = 0;
2910
0
  int wasAbsolute = (*f == '/');
2911
2912
0
  for(a = b = f; *a != '\0';) {
2913
0
    if (*a == '?')
2914
0
      query = 1;
2915
0
    if (query == 0 && lc == '/' && a[0] == '.' && a[1] == '/') {        /* foo/./bar or ./foo  */
2916
0
      a += 2;
2917
0
    } else if (query == 0 && lc == '/' && a[0] == '.' && a[1] == '.' && (a[2] == '/' || a[2] == '\0')) {        /* foo/../bar or ../foo or .. */
2918
0
      if (a[2] == '\0')
2919
0
        a += 2;
2920
0
      else
2921
0
        a += 3;
2922
      /* drop the last segment written, never past the root */
2923
0
      if (b > f)
2924
0
        b--;
2925
0
      while (b > f && b[-1] != '/')
2926
0
        b--;
2927
0
      if (wasAbsolute && b == f)
2928
0
        b++;
2929
0
    } else {
2930
0
      *b++ = lc = *a;
2931
0
      a++;
2932
0
    }
2933
0
  }
2934
0
  *b = '\0';
2935
0
  if (*f == '\0') {
2936
0
    if (wasAbsolute) {
2937
0
      f[0] = '/';
2938
0
      f[1] = '\0';
2939
0
    } else {
2940
0
      f[0] = '.';
2941
0
      f[1] = '/';
2942
0
      f[2] = '\0';
2943
0
    }
2944
0
  }
2945
0
}
2946
2947
#if HTS_USEOPENSSL
2948
/* close_notify goes to a peer that has usually gone already, so this is the
2949
   write most likely to raise SIGPIPE. */
2950
static void ssl_shutdown_free(SSL **ssl_con) {
2951
  sigpipe_mask m;
2952
2953
  sigpipe_hold(&m);
2954
  SSL_shutdown(*ssl_con);
2955
  sigpipe_release(&m);
2956
  SSL_free(*ssl_con);
2957
  *ssl_con = NULL;
2958
}
2959
#endif
2960
2961
// fermer liaison fichier ou socket
2962
0
void deletehttp(htsblk *r) {
2963
#if HTS_USEOPENSSL
2964
  /* Free OpenSSL structures */
2965
  if (r->ssl_con)
2966
    ssl_shutdown_free(&r->ssl_con);
2967
#endif
2968
0
  if (r->soc != INVALID_SOCKET) {
2969
0
    if (r->is_file) {
2970
0
      if (r->fp)
2971
0
        fclose(r->fp);
2972
0
      r->fp = NULL;
2973
0
    } else {
2974
0
      if (r->soc != LOCAL_SOCKET_ID)
2975
0
        deletesoc_r(r);
2976
0
    }
2977
0
    r->soc = INVALID_SOCKET;
2978
0
  }
2979
0
}
2980
2981
// free the addr buffer
2982
// always returns 1
2983
0
int deleteaddr(htsblk * r) {
2984
0
  if (r->adr != NULL) {
2985
0
    freet(r->adr);
2986
0
    r->adr = NULL;
2987
0
  }
2988
0
  if (r->headers != NULL) {
2989
0
    freet(r->headers);
2990
0
    r->headers = NULL;
2991
0
  }
2992
0
  return 1;
2993
0
}
2994
2995
// Close a socket, logging a failure.
2996
0
void deletesoc(T_SOC soc) {
2997
0
  if (soc != INVALID_SOCKET && soc != LOCAL_SOCKET_ID) {
2998
0
    if (!hts_closesocket(soc)) {
2999
0
      const int err = hts_socket_errno();
3000
0
      char errbuf[HTS_STRERROR_SIZE];
3001
3002
0
      fprintf(stderr, "* error closing socket " T_SOCP ": %s\n", soc,
3003
0
              hts_strerror(err, HTS_BUF(errbuf)));
3004
0
    }
3005
0
  }
3006
0
}
3007
3008
/* Will also clean other things */
3009
0
static void deletesoc_r(htsblk *r) {
3010
#if HTS_USEOPENSSL
3011
  if (r->ssl_con)
3012
    ssl_shutdown_free(&r->ssl_con);
3013
#endif
3014
0
  if (r->soc != INVALID_SOCKET) {
3015
0
    deletesoc(r->soc);
3016
0
    r->soc = INVALID_SOCKET;
3017
0
  }
3018
0
}
3019
3020
// renvoi le nombre de secondes depuis 1970
3021
0
TStamp time_local(void) {
3022
0
  return ((TStamp) time(NULL));
3023
0
}
3024
3025
// number of millisec since 1970
3026
0
HTSEXT_API TStamp mtime_local(void) {
3027
0
#ifndef _WIN32
3028
0
  struct timeval tv;
3029
0
  if (gettimeofday(&tv, NULL) != 0) {
3030
0
    assert(! "gettimeofday");
3031
0
  }
3032
3033
0
  return (TStamp) (((TStamp) tv.tv_sec * (TStamp) 1000) +
3034
0
                   ((TStamp) tv.tv_usec / (TStamp) 1000));
3035
#else
3036
  struct timeb B;
3037
  ftime(&B);
3038
  return (TStamp) (((TStamp) B.time * (TStamp) 1000)
3039
                   + ((TStamp) B.millitm));
3040
#endif
3041
0
}
3042
3043
/* Contract in htslib.h. Falls back to the wall clock where the platform has
3044
   no monotonic one, which is no worse than before. */
3045
0
TStamp mtime_monotonic(void) {
3046
#if defined(_WIN32)
3047
  return (TStamp) GetTickCount64();
3048
#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
3049
  struct timespec ts;
3050
3051
0
  if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
3052
0
    return (TStamp) ts.tv_sec * 1000 + (TStamp) (ts.tv_nsec / 1000000);
3053
0
  return mtime_local();
3054
#else
3055
  return mtime_local();
3056
#endif
3057
0
}
3058
3059
/* Writes t seconds as days, hours, minutes and seconds, dropping the empty
3060
   leading units, clipped to ST. */
3061
0
static void duration_str(hts_buf st, TStamp t, hts_boolean quick) {
3062
0
  const int j = (int) (t / (3600 * 24));
3063
0
  int h, m, s;
3064
3065
0
  t -= ((TStamp) j) * (3600 * 24);
3066
0
  h = (int) (t / 3600);
3067
0
  t -= ((TStamp) h) * 3600;
3068
0
  m = (int) (t / 60);
3069
0
  t -= ((TStamp) m) * 60;
3070
0
  s = (int) t;
3071
3072
0
  if (j > 0)
3073
0
    snprintf(st.p, st.size,
3074
0
             quick == HTS_TRUE ? "%dd,%02dh,%02dmin%02ds"
3075
0
                               : "%d days, %d hours %d minutes %d seconds",
3076
0
             j, h, m, s);
3077
0
  else if (h > 0)
3078
0
    snprintf(st.p, st.size,
3079
0
             quick == HTS_TRUE ? "%dh,%02dmin%02ds"
3080
0
                               : "%d hours %d minutes %d seconds",
3081
0
             h, m, s);
3082
0
  else if (m > 0)
3083
0
    snprintf(st.p, st.size,
3084
0
             quick == HTS_TRUE ? "%dmin%02ds" : "%d minutes %d seconds", m, s);
3085
0
  else
3086
0
    snprintf(st.p, st.size, quick == HTS_TRUE ? "%ds" : "%d seconds", s);
3087
0
}
3088
3089
0
void sec2str(hts_buf st, TStamp t) { duration_str(st, t, HTS_FALSE); }
3090
3091
/* Contract in httrack-library.h. */
3092
0
HTSEXT_API void qsec2str_sized(char *st, size_t size, TStamp t) {
3093
0
  duration_str(hts_buf_at(st, size), t, HTS_TRUE);
3094
0
}
3095
3096
// the 32 bytes the deprecated contract documents
3097
0
HTSEXT_API void qsec2str(char *st, TStamp t) { qsec2str_sized(st, 32, t); }
3098
3099
0
void time_gmt_rfc822(hts_buf s) {
3100
0
  time_t tt;
3101
0
  struct tm tmv;
3102
3103
0
  assertf(s.size != 0);
3104
0
  tt = time(NULL);
3105
  /* no local-time fallback: it would format local time and still label it GMT
3106
   * (#806) */
3107
0
  if (hts_gmtime(tt, &tmv))
3108
0
    time_rfc822(s, &tmv);
3109
0
  else
3110
0
    s.p[0] = '\0';
3111
0
}
3112
3113
0
void hts_now_iso8601(char out[32]) {
3114
0
  time_t t = time(NULL);
3115
0
  struct tm tmv;
3116
3117
0
  if (!hts_gmtime(t, &tmv))
3118
0
    memset(&tmv, 0, sizeof(tmv));
3119
0
  strftime(out, 32, "%Y-%m-%dT%H:%M:%SZ", &tmv);
3120
0
}
3121
3122
0
void time_local_rfc822(hts_buf s) {
3123
0
  time_t tt;
3124
0
  struct tm tmv;
3125
3126
0
  assertf(s.size != 0);
3127
0
  tt = time(NULL);
3128
0
  if (hts_localtime(tt, &tmv))
3129
0
    time_rfc822_local(s, &tmv);
3130
0
  else
3131
0
    s.p[0] = '\0';
3132
0
}
3133
3134
/* sets file time. -1 if error */
3135
/* Note: utf-8 */
3136
0
static int set_filetime(const char *file, struct tm *tm_time) {
3137
0
  time_t t;
3138
3139
0
  if (hts_tm_filetime(tm_time, &t)) {
3140
0
    STRUCT_UTIMBUF tim;
3141
3142
0
    memset(&tim, 0, sizeof(tim));
3143
0
    tim.actime = tim.modtime = t;
3144
0
    return UTIME(file, &tim);
3145
0
  }
3146
0
  return -1;
3147
0
}
3148
3149
/* Both Retry-After forms (RFC 9110 10.2.3). An unusable value gives -1 rather
3150
   than 0, so a caller can tell it from a server that named zero. */
3151
0
int hts_parse_retry_after(const char *value, time_t now) {
3152
0
  const char *p = value;
3153
0
  const char *end;
3154
3155
0
  if (value == NULL)
3156
0
    return -1;
3157
0
  while (is_space(*p))
3158
0
    p++;
3159
0
  end = p + strspn(p, "0123456789");
3160
0
  while (is_space(*end))
3161
0
    end++;
3162
3163
  // delta-seconds is the whole value, so "06 Nov 2026 ..." is a date
3164
0
  if (end > p && *end == '\0') {
3165
0
    LLint secs;
3166
3167
    // Every byte is a digit, so a refusal means too big, which clips.
3168
0
    return hts_parse_llint(p, NULL, 0, INT_MAX, &secs) ? (int) secs : INT_MAX;
3169
0
  }
3170
3171
0
  {
3172
0
    const int64_t when = hts_parse_date(p, 50);
3173
3174
0
    if (when == -1)
3175
0
      return -1;
3176
0
    if (when <= (int64_t) now)
3177
0
      return 0;
3178
0
    if (when - (int64_t) now > INT_MAX)
3179
0
      return INT_MAX;
3180
0
    return (int) (when - (int64_t) now);
3181
0
  }
3182
0
}
3183
3184
/* See htslib.h. */
3185
0
int64_t hts_parse_date(const char *s, int pivot) {
3186
0
  struct tm buffer;
3187
0
  struct tm *const tm_s = convert_time_rfc822_pivot(&buffer, s, pivot);
3188
3189
0
  return tm_s != NULL ? hts_utc_seconds(tm_s) : -1;
3190
0
}
3191
3192
/* sets file time from RFC822 date+time, -1 if error*/
3193
/* Note: utf-8 */
3194
0
int set_filetime_rfc822(const char *file, const char *date) {
3195
0
  struct tm buffer;
3196
0
  struct tm *tm_s = convert_time_rfc822(&buffer, date);
3197
3198
0
  if (tm_s) {
3199
0
    return set_filetime(file, tm_s);
3200
0
  } else
3201
0
    return -1;
3202
0
}
3203
3204
0
void hts_stamp_filetime(httrackp *opt, const char *file, const char *date) {
3205
  /* an unparsable date is common, so debug: the file keeps its fetch time */
3206
0
  if (set_filetime_rfc822(file, date) != 0)
3207
0
    hts_log_print(opt, LOG_DEBUG, "Could not set the date of %s to %s", file,
3208
0
                  date);
3209
0
}
3210
3211
/* Note: utf-8 */
3212
0
time_t get_filetime(const char *file) {
3213
0
  STRUCT_STAT buf;
3214
3215
0
  if (STAT(file, &buf) != 0)
3216
0
    return (time_t) -1;
3217
0
  return (time_t) buf.st_mtime;
3218
0
}
3219
3220
/* Note: utf-8 */
3221
0
hts_boolean hts_file_mtime(const char *file, hts_filetime_t *when) {
3222
#ifdef _WIN32
3223
  /* _wstat64() gives whole seconds, too coarse to order a request against a
3224
     mirror started in the same second. GetFileAttributesExW gives 100ns. */
3225
  WIN32_FILE_ATTRIBUTE_DATA attr;
3226
  LPWSTR wfile = hts_pathToUCS2(file);
3227
  ULARGE_INTEGER ticks;
3228
3229
  if (wfile == NULL)
3230
    return HTS_FALSE;
3231
  if (!GetFileAttributesExW(wfile, GetFileExInfoStandard, &attr)) {
3232
    freet(wfile);
3233
    return HTS_FALSE;
3234
  }
3235
  freet(wfile);
3236
  ticks.LowPart = attr.ftLastWriteTime.dwLowDateTime;
3237
  ticks.HighPart = attr.ftLastWriteTime.dwHighDateTime;
3238
  when->sec = (int64_t) (ticks.QuadPart / 10000000ULL);
3239
  when->nsec = (int32_t) ((ticks.QuadPart % 10000000ULL) * 100);
3240
  when->is_plain_file = (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0
3241
                            ? HTS_TRUE
3242
                            : HTS_FALSE;
3243
  return HTS_TRUE;
3244
#else
3245
0
  STRUCT_STAT buf;
3246
3247
0
  if (STAT(file, &buf) != 0)
3248
0
    return HTS_FALSE;
3249
0
  when->sec = (int64_t) buf.st_mtime;
3250
0
#if defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
3251
0
  when->nsec = (int32_t) buf.st_mtim.tv_nsec; /* POSIX 2008 */
3252
#elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
3253
  when->nsec = (int32_t) buf.st_mtimespec.tv_nsec; /* macOS, older BSD */
3254
#else
3255
  /* Whole seconds, which is all a FAT or exFAT filesystem keeps anyway. */
3256
  when->nsec = 0;
3257
#endif
3258
0
  when->is_plain_file = S_ISREG(buf.st_mode) ? HTS_TRUE : HTS_FALSE;
3259
0
  return HTS_TRUE;
3260
0
#endif
3261
0
}
3262
3263
/* Note: utf-8 */
3264
0
hts_boolean hts_file_is_newer(const char *a, const char *b) {
3265
0
  hts_filetime_t ta, tb;
3266
3267
0
  if (!hts_file_mtime(a, &ta) || !ta.is_plain_file)
3268
0
    return HTS_FALSE;
3269
0
  if (!hts_file_mtime(b, &tb))
3270
0
    return HTS_FALSE;
3271
0
  if (ta.sec != tb.sec)
3272
0
    return ta.sec > tb.sec ? HTS_TRUE : HTS_FALSE;
3273
0
  return ta.nsec > tb.nsec ? HTS_TRUE : HTS_FALSE;
3274
0
}
3275
3276
/* Note: utf-8 */
3277
0
hts_boolean hts_file_backdate(const char *file, int seconds) {
3278
0
  hts_filetime_t when;
3279
3280
  /* The file's own stamp rather than a fresh clock reading, so the two can not
3281
     disagree about when this file was written. */
3282
0
  if (!hts_file_mtime(file, &when))
3283
0
    return HTS_FALSE;
3284
0
  when.sec -= seconds;
3285
#ifdef _WIN32
3286
  {
3287
    LPWSTR wfile = hts_pathToUCS2(file);
3288
    ULARGE_INTEGER ticks;
3289
    FILETIME ft;
3290
    HANDLE h;
3291
    hts_boolean ok;
3292
3293
    if (wfile == NULL)
3294
      return HTS_FALSE;
3295
    h = CreateFileW(wfile, FILE_WRITE_ATTRIBUTES,
3296
                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3297
                    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
3298
    freet(wfile);
3299
    if (h == INVALID_HANDLE_VALUE)
3300
      return HTS_FALSE;
3301
    if (when.sec < 0) { /* no write time on this volume */
3302
      CloseHandle(h);
3303
      return HTS_FALSE;
3304
    }
3305
    ticks.QuadPart =
3306
        (ULONGLONG) when.sec * 10000000ULL + (ULONGLONG) (when.nsec / 100);
3307
    ft.dwLowDateTime = ticks.LowPart;
3308
    ft.dwHighDateTime = ticks.HighPart;
3309
    ok = SetFileTime(h, NULL, NULL, &ft) ? HTS_TRUE : HTS_FALSE;
3310
    CloseHandle(h);
3311
    return ok;
3312
  }
3313
#elif defined(HAVE_UTIMENSAT)
3314
  {
3315
0
    struct timespec times[2];
3316
3317
0
    times[0].tv_sec = times[1].tv_sec = (time_t) when.sec;
3318
0
    times[0].tv_nsec = times[1].tv_nsec = (long) when.nsec;
3319
0
    return utimensat(AT_FDCWD, file, times, 0) == 0 ? HTS_TRUE : HTS_FALSE;
3320
0
  }
3321
#else
3322
  {
3323
    struct timeval times[2];
3324
3325
    times[0].tv_sec = times[1].tv_sec = (time_t) when.sec;
3326
    times[0].tv_usec = times[1].tv_usec = (long) (when.nsec / 1000);
3327
    return utimes(file, times) == 0 ? HTS_TRUE : HTS_FALSE;
3328
  }
3329
#endif
3330
0
}
3331
3332
/* Note: utf-8 */
3333
0
int get_filetime_rfc822(const char *file, hts_buf date) {
3334
0
  STRUCT_STAT buf;
3335
3336
0
  assertf(date.size != 0);
3337
0
  date.p[0] = '\0';
3338
0
  if (STAT(file, &buf) == 0) {
3339
0
    struct tm tmv;
3340
0
    time_t tt = buf.st_mtime;
3341
3342
    /* no local-time fallback: it would format local time and still label it GMT
3343
     * (#806) */
3344
0
    if (hts_gmtime(tt, &tmv)) {
3345
0
      time_rfc822(date, &tmv);
3346
0
      return 1;
3347
0
    }
3348
0
  }
3349
0
  return 0;
3350
0
}
3351
3352
0
void time_rfc822(hts_buf s, struct tm *A) {
3353
0
  if (A == NULL) {
3354
0
    int localtime_returned_null = 0;
3355
3356
0
    assertf(localtime_returned_null);
3357
0
  }
3358
0
  hts_format_rfc822(s, A, " GMT");
3359
0
}
3360
3361
// Writes A as an RFC 822 date in local time.
3362
0
static void time_rfc822_local(hts_buf s, struct tm *A) {
3363
0
  if (A == NULL) {
3364
0
    int localtime_returned_null = 0;
3365
3366
0
    assertf(localtime_returned_null);
3367
0
  }
3368
0
  hts_format_rfc822(s, A, "");
3369
0
}
3370
3371
// conversion en b,Kb,Mb
3372
0
HTSEXT_API char *int2bytes(strc_int2bytes2 * strc, LLint n) {
3373
0
  char **a = int2bytes2(strc, n);
3374
3375
0
  strcpybuff(strc->catbuff, a[0]);
3376
0
  strcatbuff(strc->catbuff, a[1]);
3377
0
  return strc->catbuff;
3378
0
}
3379
3380
// conversion en b/s,Kb/s,Mb/s
3381
0
HTSEXT_API char *int2bytessec(strc_int2bytes2 * strc, long int n) {
3382
0
  char buff[256];
3383
0
  char **a = int2bytes2(strc, n);
3384
3385
0
  strcpybuff(buff, a[0]);
3386
0
  strcatbuff(buff, a[1]);
3387
0
  return concat(strc->catbuff, sizeof(strc->catbuff), buff, "/s");
3388
0
}
3389
3390
// conversion en b,Kb,Mb, nombre et type séparés
3391
// limite: 2.10^9.10^6B
3392
3393
/* See http://physics.nist.gov/cuu/Units/binary.html */
3394
0
#define ToLLint(a) ((LLint)(a))
3395
0
#define ToLLintKiB (ToLLint(1024))
3396
0
#define ToLLintMiB (ToLLintKiB * ToLLintKiB)
3397
0
#define ToLLintGiB (ToLLintKiB * ToLLintKiB * ToLLintKiB)
3398
0
#define ToLLintTiB (ToLLintKiB * ToLLintKiB * ToLLintKiB * ToLLintKiB)
3399
#define ToLLintPiB                                                             \
3400
0
  (ToLLintKiB * ToLLintKiB * ToLLintKiB * ToLLintKiB * ToLLintKiB)
3401
3402
0
static char **int2bytes2(strc_int2bytes2 *strc, LLint n) {
3403
0
  const hts_buf num = HTS_BUF(strc->buff1);
3404
3405
0
  if (n < ToLLintKiB) {
3406
0
    hts_buf_printf_clip(num, "%d", (int) (LLint) n);
3407
0
    strcpybuff(strc->buff2, "B");
3408
0
  } else if (n < ToLLintMiB) {
3409
0
    hts_buf_printf_clip(num, "%d,%02d", (int) ((LLint) (n / ToLLintKiB)),
3410
0
                        (int) ((LLint) ((n % ToLLintKiB) * 100) / ToLLintKiB));
3411
0
    strcpybuff(strc->buff2, "KiB");
3412
0
  } else if (n < ToLLintGiB) {
3413
0
    hts_buf_printf_clip(
3414
0
        num, "%d,%02d", (int) ((LLint) (n / (ToLLintMiB))),
3415
0
        (int) ((LLint) (((n % (ToLLintMiB)) * 100) / (ToLLintMiB))));
3416
0
    strcpybuff(strc->buff2, "MiB");
3417
0
  } else if (n < ToLLintTiB) {
3418
0
    hts_buf_printf_clip(
3419
0
        num, "%d,%02d", (int) ((LLint) (n / (ToLLintGiB))),
3420
0
        (int) ((LLint) (((n % (ToLLintGiB)) * 100) / (ToLLintGiB))));
3421
0
    strcpybuff(strc->buff2, "GiB");
3422
0
  } else if (n < ToLLintPiB) {
3423
0
    hts_buf_printf_clip(
3424
0
        num, "%d,%02d", (int) ((LLint) (n / (ToLLintTiB))),
3425
0
        (int) ((LLint) (((n % (ToLLintTiB)) * 100) / (ToLLintTiB))));
3426
0
    strcpybuff(strc->buff2, "TiB");
3427
0
  } else {
3428
0
    hts_buf_printf_clip(
3429
0
        num, "%d,%02d", (int) ((LLint) (n / (ToLLintPiB))),
3430
0
        (int) ((LLint) (((n % (ToLLintPiB)) * 100) / (ToLLintPiB))));
3431
0
    strcpybuff(strc->buff2, "PiB");
3432
0
  }
3433
0
  strc->buffadr[0] = strc->buff1;
3434
0
  strc->buffadr[1] = strc->buff2;
3435
0
  return strc->buffadr;
3436
0
}
3437
3438
// envoi de texte (en têtes généralement) sur la socket soc
3439
0
int sendc(htsblk * r, const char *s) {
3440
0
  const size_t len = strlen(s);
3441
0
  int n, ssz;
3442
3443
0
  if (len > INT_MAX)
3444
0
    return -1;
3445
0
  ssz = (int) len;
3446
3447
#if HTS_USEOPENSSL
3448
  if (r->ssl) {
3449
    sigpipe_mask m;
3450
3451
    sigpipe_hold(&m);
3452
    n = SSL_write(r->ssl_con, s, ssz);
3453
    sigpipe_release(&m);
3454
  } else
3455
#endif
3456
0
    n = hts_send_nosignal(r->soc, s, ssz);
3457
3458
0
  return (n == ssz) ? n : -1;
3459
0
}
3460
3461
// Like linput, but in memory (optimized). A line too long for `s` is clipped
3462
// but consumed whole: resuming inside it reads its tail back as another line.
3463
0
int binput(const char *buff, hts_buf s) {
3464
0
  int count = 0;
3465
0
  size_t destCount = 0;
3466
3467
0
  assertf(s.size != 0);
3468
  // Note: \0 will return 1
3469
0
  while (buff != NULL && buff[count] != '\0' && buff[count] != '\n') {
3470
0
    if (buff[count] != '\r' && destCount < s.size - 1) {
3471
0
      s.p[destCount++] = buff[count];
3472
0
    }
3473
0
    count++;
3474
0
  }
3475
0
  s.p[destCount] = '\0';
3476
3477
  // then return the supplemental jump offset
3478
0
  return count + 1;
3479
0
}
3480
3481
0
hts_boolean hts_header_is_read(const char *line) {
3482
0
  static const char *const names[] = {"Connection:",
3483
0
                                      "Content-Disposition:",
3484
0
                                      "Content-Encoding:",
3485
0
                                      "Content-length:",
3486
0
                                      "Content-Range:",
3487
0
                                      "Content-type:",
3488
0
                                      "Date:",
3489
0
                                      "Etag:",
3490
0
                                      "Keep-Alive:",
3491
0
                                      "Last-Modified:",
3492
0
                                      "Location:",
3493
0
                                      "Retry-After:",
3494
0
                                      "Set-Cookie:",
3495
0
                                      "TE:",
3496
0
                                      "Transfer-Encoding:"};
3497
0
  size_t i;
3498
3499
0
  for (i = 0; i < sizeof(names) / sizeof(names[0]); i++)
3500
0
    if (hts_starts_with_ci(line, names[i]))
3501
0
      return HTS_TRUE;
3502
0
  return HTS_FALSE;
3503
0
}
3504
3505
hts_boolean binput_line(const char *buff, const char *end, hts_buf s,
3506
0
                        int *offset) {
3507
0
  hts_boolean cut = HTS_FALSE;
3508
0
  const char *p;
3509
0
  size_t j = 0;
3510
3511
0
  assertf(s.size != 0);
3512
0
  *offset = 0;
3513
0
  s.p[0] = '\0';
3514
0
  if (buff == NULL || buff >= end)
3515
0
    return HTS_FALSE;
3516
0
  for (p = buff; p < end && *p != '\0' && *p != '\n'; p++) {
3517
0
    if (*p == '\r')
3518
0
      continue;
3519
0
    if (j < s.size - 1)
3520
0
      s.p[j++] = *p;
3521
0
    else
3522
0
      cut = HTS_TRUE; /* keep walking: the tail must not become more headers */
3523
0
  }
3524
0
  s.p[j] = '\0';
3525
0
  *offset = (int) (p - buff) + 1; /* binput's convention: step over the \n */
3526
0
  return cut;
3527
0
}
3528
3529
// case-insensitive strstr()
3530
0
const char *strstrcase(const char *s, const char *o) {
3531
0
  while (*s && !hts_starts_with_ci(s, o))
3532
0
    s++;
3533
0
  if (*s == '\0')
3534
0
    return NULL;
3535
0
  return s;
3536
0
}
3537
3538
0
void map_characters(hts_span s, unsigned int *map) {
3539
0
  size_t i;
3540
3541
0
  memset(map, 0, sizeof(unsigned int) * 256);
3542
0
  for (i = 0; i < s.len; i++)
3543
0
    map[(unsigned char) s.p[i]]++;
3544
0
}
3545
3546
0
hts_boolean map_looks_binary(const unsigned int *map, size_t size) {
3547
0
  unsigned int nspec = 0;
3548
0
  int i;
3549
3550
0
  for (i = 1; i < 32; i++) {
3551
0
    if (!is_realspace(i) && i != 27) /* ESC: ISO-2022 */
3552
0
      nspec += map[i];
3553
0
  }
3554
0
  return nspec > size / 100 && nspec > 10 ? HTS_TRUE : HTS_FALSE;
3555
0
}
3556
3557
// le fichier est-il un fichier html?
3558
//  0 : non
3559
//  1 : oui
3560
// -1 : on sait pas
3561
// -2 : on sait pas, pas d'extension
3562
593k
int ishtml(httrackp * opt, const char *fil) {
3563
  /* User-defined MIME types (overrides ishtml()) */
3564
593k
  char BIGSTK fil_noquery[HTS_URLMAXSIZE * 2];
3565
593k
  char mime[256];
3566
593k
  char *a;
3567
593k
  const char *dotted;
3568
3569
593k
  strcpybuff(fil_noquery, fil);
3570
593k
  if ((a = strchr(fil_noquery, '?')) != NULL) {
3571
0
    *a = '\0';
3572
0
  }
3573
593k
  if (get_userhttptype(opt, HTS_BUF(mime), fil_noquery)) {
3574
0
    if (is_html_mime_type(mime)) {
3575
0
      return 1;
3576
0
    } else {
3577
0
      return 0;
3578
0
    }
3579
0
  }
3580
3581
593k
  if (!strnotempty(fil_noquery)) {
3582
0
    return -2;
3583
0
  }
3584
3585
  /* Search for known ext */
3586
593k
  dotted = hts_path_ext_dot(fil_noquery, "/");
3587
593k
  if (dotted != NULL) {
3588
593k
    int ret = ishtml_ext(hts_span_of(dotted + 1));
3589
3590
593k
    if (ret == -1) {
3591
593k
      switch (is_knowntype(opt, dotted)) {
3592
593k
      case 1:
3593
593k
        ret = 0;                // connu, non html
3594
593k
        break;
3595
0
      case 2:
3596
0
        ret = 1;                // connu, html
3597
0
        break;
3598
0
      default:
3599
0
        ret = -1;               // inconnu..
3600
0
        break;
3601
593k
      }
3602
593k
    }
3603
593k
    return ret;
3604
593k
  } else
3605
0
    return -2;                  // indéterminé, par exemple /truc
3606
593k
}
3607
3608
593k
int ishtml_ext(hts_span ext) {
3609
593k
  static const char *const html_exts[] = {HTS_SPAN_WORDS(
3610
593k
      "html", "htm", "shtml", "phtml", "htmlx", "shtm", "phtm", "htmx")};
3611
3612
593k
  return hts_span_index_ci(ext, html_exts) >= 0 ? 1 : -1;
3613
593k
}
3614
3615
/* Declare a non-const version of FUN */
3616
#define DECLARE_NON_CONST_VERSION(FUN) \
3617
0
char *FUN(char *source) { \
3618
0
  const char *const ret = FUN ##_const(source); \
3619
0
  return ret != NULL ? source + ( ret - source ) : NULL; \
3620
0
}
3621
3622
/* Appends s at buf.p[*len], clipped to buf.size - 1, NUL-terminated. */
3623
0
static void append_clipped(hts_buf buf, size_t *len, hts_span s) {
3624
0
  size_t n = s.len;
3625
3626
0
  if (n > buf.size - 1 - *len)
3627
0
    n = buf.size - 1 - *len;
3628
0
  memcpy(buf.p + *len, s.p, n);
3629
0
  *len += n;
3630
0
  buf.p[*len] = '\0';
3631
0
}
3632
3633
/* Returns adr past its blanks, scheme and "//", the engine's or any
3634
   "scheme://", or adr when it has no scheme. */
3635
0
const char *login_start(const char *adr) {
3636
0
  const char *s = adr;
3637
0
  const char *known;
3638
3639
0
  while (hts_isspace((unsigned char) *s))
3640
0
    s++;
3641
0
  known = jump_protocol_const(s);
3642
0
  if (known != s)
3643
0
    return known;
3644
0
  if (!hts_isalpha((unsigned char) *s))
3645
0
    return adr;
3646
0
  while (hts_isalnum((unsigned char) *s) || *s == '+' || *s == '-' || *s == '.')
3647
0
    s++;
3648
0
  return strncmp(s, "://", 3) == 0 ? s + 3 : adr;
3649
0
}
3650
3651
/* Returns adr past its login, or login_start(adr) when it has none. */
3652
0
const char *login_end(const char *adr) {
3653
0
  const char *s = adr;
3654
0
  hts_url_view v;
3655
3656
0
  while (hts_isspace((unsigned char) *s))
3657
0
    s++;
3658
0
  (void) hts_url_view_parse(hts_span_of(s), &v);
3659
0
  return hts_span_present(v.userinfo) ? v.host.p : login_start(adr);
3660
0
}
3661
3662
0
hts_boolean hts_escape_typed_login(const char *url, hts_buf dst) {
3663
0
  const char *const start = login_start(url);
3664
0
  const char *const at = strrchr_limit(start, '@', strchr(start, '/'));
3665
3666
0
  return hts_escape_span(hts_span_of(url),
3667
0
                         hts_span_between(start, at != NULL ? at - 1 : start),
3668
0
                         "?#\\", dst);
3669
0
}
3670
3671
/* Returns HTS_TRUE when adr has a login, a user alone included. */
3672
0
static hts_boolean has_login(const char *adr) {
3673
0
  return login_end(adr) > login_start(adr) ? HTS_TRUE : HTS_FALSE;
3674
0
}
3675
3676
0
const char *adr_nologin_r(hts_buf out, const char *adr) {
3677
0
  const char *const scheme = login_start(adr);
3678
0
  const char *const host = login_end(adr);
3679
0
  const char *colon;
3680
0
  size_t len = 0;
3681
3682
0
  if (!has_login(adr) || out.size == 0)
3683
0
    return adr;
3684
0
  colon = memchr(scheme, ':', (size_t) (host - scheme));
3685
0
  if (colon != NULL) {
3686
0
    append_clipped(out, &len, hts_span_between(adr, colon));
3687
0
    append_clipped(out, &len, hts_span_of(":***@"));
3688
0
  } else {
3689
0
    append_clipped(out, &len, hts_span_between(adr, scheme));
3690
0
    append_clipped(out, &len, hts_span_of("***@"));
3691
0
  }
3692
0
  append_clipped(out, &len, hts_span_of(host));
3693
0
  return out.p;
3694
0
}
3695
3696
0
const char *url_nologin_r(hts_buf buf, const char *url) {
3697
0
  return login_start(url) != url ? adr_nologin_r(buf, url) : url;
3698
0
}
3699
3700
0
const char *adr_nologin(httrackp *opt, const char *adr) {
3701
0
  if (adr == NULL) // treathead() logs a cookie its caller gave no URL for
3702
0
    return "";
3703
0
  if (!has_login(adr))
3704
0
    return adr;
3705
  // no buffer to mask into: drop the whole login
3706
0
  if (opt == NULL)
3707
0
    return login_end(adr);
3708
0
  return adr_nologin_r(hts_buf_at(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt)),
3709
0
                       adr);
3710
0
}
3711
3712
0
const char *url_nologin(httrackp *opt, const char *url) {
3713
0
  return login_start(url) != url ? adr_nologin(opt, url) : url;
3714
0
}
3715
3716
// Returns source past its login (user:pass@), if any.
3717
0
HTSEXT_API const char *jump_identification_const(const char *source) {
3718
0
  hts_url_view v;
3719
3720
0
  if (strcmp(source, "file://") == 0)
3721
0
    return source;
3722
0
  (void) hts_url_view_parse(hts_span_of(source), &v);
3723
  // a scheme the engine does not know is kept whole
3724
0
  if (hts_span_present(v.scheme) && jump_protocol_const(source) == source)
3725
0
    return source;
3726
0
  return v.host.p;
3727
0
}
3728
3729
/* clang-format reads the macro line as an unfinished statement. */
3730
/* clang-format off */
3731
0
HTSEXT_API DECLARE_NON_CONST_VERSION(jump_identification)
3732
3733
0
const char *jump_normalized_const(const char *source) {
3734
0
  if (strcmp(source, "file://") == 0)
3735
0
    return source;
3736
0
  source = jump_identification_const(source);
3737
0
  if (hts_starts_with_ci(source, "www") && source[3] != '\0') {
3738
0
    if (source[3] == '.') {     // www.foo.com -> foo.com
3739
0
      source += 4;
3740
0
    } else {                    // www-4.foo.com -> foo.com
3741
0
      const char *a = source + 3;
3742
3743
0
      while (*a && (hts_isdigit((unsigned char) *a) || *a == '-'))
3744
0
        a++;
3745
0
      if (*a == '.') {
3746
0
        source = a + 1;
3747
0
      }
3748
0
    }
3749
0
  }
3750
0
  return source;
3751
0
}
3752
3753
/* clang-format on */
3754
3755
0
static int sortNormFnc(const void *a_, const void *b_) {
3756
0
  const hts_query_field *const a = (const hts_query_field *) a_;
3757
0
  const hts_query_field *const b = (const hts_query_field *) b_;
3758
0
  const size_t n = a->whole.len < b->whole.len ? a->whole.len : b->whole.len;
3759
0
  const int c = memcmp(a->whole.p, b->whole.p, n);
3760
3761
0
  if (c != 0)
3762
0
    return c;
3763
0
  return a->whole.len < b->whole.len ? -1 : a->whole.len > b->whole.len ? 1 : 0;
3764
0
}
3765
3766
/* Path normalizer core: optionally collapse redundant '//' (DO_SLASH) and/or
3767
   sort query arguments (DO_QUERY) so equivalent URLs dedupe. */
3768
static char *fil_normalized_ex(const char *source, char *dest, int do_slash,
3769
0
                               int do_query) {
3770
0
  char lastc = 0;
3771
0
  int gotquery = 0;
3772
0
  size_t i, j;
3773
0
  char *query;
3774
3775
0
  for(i = j = 0; source[i] != '\0'; i++) {
3776
0
    if (!gotquery && source[i] == '?') {
3777
0
      gotquery = 1;
3778
0
    }
3779
0
    if (do_slash && !gotquery && lastc == '/' && source[i] == '/') {
3780
      // foo//bar -> foo/bar
3781
0
    } else {
3782
0
      dest[j++] = source[i];
3783
0
    }
3784
0
    lastc = source[i];
3785
0
  }
3786
0
  dest[j++] = '\0';
3787
3788
  /* Sort arguments (&foo=1&bar=2 == &bar=2&foo=1) */
3789
0
  if (do_query && (query = strchr(dest, '?')) != NULL) {
3790
0
    const char *cur = query + 1;
3791
0
    hts_query_field f;
3792
0
    size_t nfields = 0;
3793
3794
0
    while (hts_query_next(&cur, &f))
3795
0
      nfields++;
3796
0
    if (nfields > 1) {
3797
0
      hts_query_field *fields = malloct(nfields * sizeof(*fields));
3798
0
      const size_t qLen = strlen(query);
3799
0
      char *copyBuff = malloct(qLen + 1);
3800
0
      htsbuff cb;
3801
3802
0
      assertf(fields != NULL);
3803
0
      assertf(copyBuff != NULL);
3804
0
      cur = query + 1;
3805
0
      for (i = 0; hts_query_next(&cur, &f); i++) {
3806
0
        assertf(i < nfields);
3807
0
        fields[i] = f;
3808
0
      }
3809
0
      assertf(i == nfields);
3810
3811
0
      qsort(fields, nfields, sizeof(*fields), sortNormFnc);
3812
3813
      /* Replace query by sorted query, of the same length */
3814
0
      cb = htsbuff_ptr(copyBuff, qLen + 1);
3815
0
      for (i = 0; i < nfields; i++) {
3816
0
        htsbuff_catc(&cb, i == 0 ? '?' : '&');
3817
0
        htsbuff_catn(&cb, fields[i].whole.p, fields[i].whole.len);
3818
0
      }
3819
0
      assertf(cb.len == qLen);
3820
0
      strlcpybuff(query, copyBuff, qLen + 1);
3821
3822
0
      freet(fields);
3823
0
      freet(copyBuff);
3824
0
    }
3825
0
  }
3826
3827
0
  return dest;
3828
0
}
3829
3830
0
char *fil_normalized(const char *source, char *dest) {
3831
0
  return fil_normalized_ex(source, dest, 1, 1);
3832
0
}
3833
3834
/* see htscore.h */
3835
0
hts_boolean hts_query_key_stripped(hts_span key, const char *strip) {
3836
0
  hts_span rest = hts_span_of(strip);
3837
0
  hts_span tok;
3838
3839
0
  while (hts_span_next_in(&rest, ',', &tok)) {
3840
0
    tok = hts_span_trim(tok, " ", " ");
3841
0
    if (hts_span_eq(tok, hts_span_of("*")) || hts_span_eq(tok, key))
3842
0
      return HTS_TRUE;
3843
0
  }
3844
0
  return HTS_FALSE;
3845
0
}
3846
3847
/* see htscore.h */
3848
char *fil_normalized_filtered_ex(const char *source, char *dest,
3849
                                 const char *strip, int do_slash,
3850
0
                                 int do_query) {
3851
0
  const char *query;
3852
3853
  /* No strip list, or no query: plain normalization. */
3854
0
  if (strip == NULL || *strip == '\0' ||
3855
0
      (query = strchr(source, '?')) == NULL) {
3856
0
    return fil_normalized_ex(source, dest, do_slash, do_query);
3857
0
  }
3858
3859
  /* Copy the path, re-emit kept query args, let fil_normalized() sort. Walk
3860
     every field incl. empty/trailing ("a&","?&&") so the result is a fixpoint
3861
     (the read re-normalizes it; a dropped empty arg would miss dedup). */
3862
0
  {
3863
0
    char BIGSTK tmp[HTS_URLMAXSIZE * 2];
3864
0
    htsbuff cb = htsbuff_ptr(tmp, sizeof(tmp));
3865
0
    hts_query_field f;
3866
0
    const char *cur;
3867
0
    int wrote = 0;
3868
3869
0
    htsbuff_catn(&cb, source, (size_t) (query - source));
3870
0
    for (cur = query + 1; hts_query_next(&cur, &f);) {
3871
0
      if (!hts_query_key_stripped(f.key, strip)) {
3872
0
        htsbuff_catc(&cb, wrote ? '&' : '?');
3873
0
        htsbuff_catn(&cb, f.whole.p, f.whole.len);
3874
0
        wrote = 1;
3875
0
      }
3876
0
    }
3877
0
    return fil_normalized_ex(tmp, dest, do_slash, do_query);
3878
0
  }
3879
0
}
3880
3881
/* see htscore.h */
3882
char *fil_normalized_filtered(const char *source, char *dest,
3883
0
                              const char *strip) {
3884
0
  return fil_normalized_filtered_ex(source, dest, strip, 1, 1);
3885
0
}
3886
3887
/* hts_query_strip_keys() once some strip rules are known to exist */
3888
static const char *hts_query_strip_keys_match(const char *rules,
3889
                                              const char *adr, const char *fil,
3890
0
                                              hts_buf dest) {
3891
0
  const char *q;
3892
0
  const char *result = NULL;
3893
0
  hts_span rest, line;
3894
  /* holds a host and a path, each up to HTS_URLMAXSIZE * 2 */
3895
0
  char BIGSTK url[HTS_URLMAXSIZE * 4];
3896
3897
  /* Match the normalized host/path without the query, so read and write agree.
3898
     A host/path longer than url[] is hostile input and is clipped, because it
3899
     only changes which rule matches. */
3900
0
  (void) strclipbuff(url, sizeof(url), jump_normalized_const(adr));
3901
0
  if (fil[0] != '/')
3902
0
    (void) strclipbuff(&url[strlen(url)], sizeof(url) - strlen(url), "/");
3903
0
  q = strchr(fil, '?');
3904
0
  {
3905
0
    const size_t room = sizeof(url) - strlen(url) - 1;
3906
0
    const size_t fillen = q != NULL ? (size_t) (q - fil) : strlen(fil);
3907
3908
0
    strlncatbuff(url, fil, sizeof(url), fillen < room ? fillen : room);
3909
0
  }
3910
3911
0
  rest = hts_span_of(rules);
3912
  /* Walk the '\n' entries; last match wins (like the +/- filter eval). Each is
3913
     "pattern=keys"; no '=' is the bare form, pattern "*". */
3914
0
  while (hts_span_next_in(&rest, '\n', &line)) {
3915
0
    hts_span pattern, keys;
3916
0
    char BIGSTK pat[HTS_URLMAXSIZE * 2];
3917
3918
0
    if (hts_span_empty(line))
3919
0
      continue;
3920
0
    if (hts_span_split(line, '=', &pattern, &keys)) {
3921
      /* Clip a too-long pattern, never skip it. */
3922
0
      (void) !hts_buf_put_span_clip(HTS_BUF(pat), pattern);
3923
0
    } else {
3924
0
      strcpybuff(pat, "*");
3925
0
      keys = line;
3926
0
    }
3927
0
    if (strjoker(url, pat, NULL, NULL) != NULL) {
3928
      /* a user rule; every key lookup clips it alike */
3929
0
      (void) !hts_buf_put_span_clip(dest, keys);
3930
0
      result = dest.p;
3931
0
    }
3932
0
  }
3933
0
  return result;
3934
0
}
3935
3936
/* see htscore.h */
3937
const char *hts_query_strip_keys(const char *rules, const char *adr,
3938
0
                                 const char *fil, hts_buf dest) {
3939
0
  if (rules == NULL || *rules == '\0' || dest.size == 0)
3940
0
    return NULL;
3941
0
  return hts_query_strip_keys_match(rules, adr, fil, dest);
3942
0
}
3943
3944
/* see htscore.h */
3945
0
const char *hts_host_alias_rules(httrackp *opt) {
3946
0
  if (opt->hash != NULL)
3947
0
    return opt->hash->host_alias;
3948
0
  return StringNotEmpty(opt->host_alias) ? StringBuff(opt->host_alias) : NULL;
3949
0
}
3950
3951
/* see htslib.h */
3952
0
const char *hts_strip_query_rules(httrackp *opt) {
3953
0
  if (opt->hash != NULL)
3954
0
    return opt->hash->strip_query;
3955
0
  return StringNotEmpty(opt->strip_query) ? StringBuff(opt->strip_query) : NULL;
3956
0
}
3957
3958
/* Split RULE "alias[,alias...]=canonical" at its first '=', both sides
3959
   untrimmed. The matcher and the validator share it so they agree on what a
3960
   rule is. HTS_FALSE when either side is empty. */
3961
static hts_boolean hts_host_alias_split(hts_span rule, hts_span *aliases,
3962
0
                                        hts_span *canon) {
3963
0
  return hts_span_split(rule, '=', aliases, canon) &&
3964
0
         !hts_span_empty(*aliases) && !hts_span_empty(*canon);
3965
0
}
3966
3967
/* see htscore.h */
3968
const char *hts_host_alias_match(const char *rules, const char *host,
3969
                                 const char *full, hts_boolean collapse_www,
3970
0
                                 size_t *canonlen) {
3971
0
  hts_span rest = hts_span_of(rules);
3972
0
  const char *found = NULL;
3973
0
  hts_span line;
3974
3975
0
  while (hts_span_next_in(&rest, '\n', &line)) {
3976
0
    hts_span aliases, canon, alias;
3977
3978
0
    if (!hts_host_alias_split(line, &aliases, &canon))
3979
0
      continue;
3980
0
    while (hts_span_next_in(&aliases, ',', &alias)) {
3981
0
      char BIGSTK glob[HTS_URLMAXSIZE * 2];
3982
3983
      /* A trailing slash is not part of a path. */
3984
0
      alias = hts_span_trim(alias, " \t", " \t/");
3985
0
      if (!hts_span_empty(alias) && hts_span_copy(alias, HTS_SIZED(glob))) {
3986
0
        char *ghost;
3987
3988
        /* the collapse applies to the pattern too, so a rule may spell either
3989
           www.example.com or example.com under -%u */
3990
0
        ghost = glob + (jump_protocol_const(glob) - glob);
3991
0
        if (collapse_www) {
3992
0
          const char *const bare = jump_normalized_const(ghost);
3993
3994
0
          if (bare != ghost)
3995
0
            memmove(ghost, bare, strlen(bare) + 1);
3996
0
        }
3997
        /* a rule that names no scheme keeps matching every scheme */
3998
0
        if (strjoker(strstr(glob, "://") != NULL ? full : host,
3999
0
                     strstr(glob, "://") != NULL ? glob : ghost, NULL,
4000
0
                     NULL) != NULL) {
4001
          /* Trim here, because the resolver compares each match with the
4002
             next to see a chain settle. */
4003
0
          canon = hts_span_trim(canon, " \t", " \t/");
4004
0
          found = canon.p;
4005
0
          *canonlen = canon.len;
4006
0
          break;
4007
0
        }
4008
0
      }
4009
0
    }
4010
0
  }
4011
0
  return found;
4012
0
}
4013
4014
/* Build "scheme://host" from URL's scheme and HOST, for the rules that name a
4015
   scheme. HTS_FALSE if it does not fit DEST. */
4016
static hts_boolean hts_host_alias_subject(const char *url, const char *host,
4017
0
                                          hts_buf dest) {
4018
  /* An address with no scheme is the engine's plain-http form. Spell that one
4019
     out, or a rule naming http:// could never match anything. */
4020
0
  const hts_boolean bare =
4021
0
      jump_protocol_const(url) == url ? HTS_TRUE : HTS_FALSE;
4022
0
  const char *const scheme = bare ? "http://" : url;
4023
0
  const size_t schemelen =
4024
0
      bare ? strlen("http://") : (size_t) (jump_protocol_const(url) - url);
4025
0
  const size_t hostlen = strlen(host);
4026
4027
0
  if (schemelen >= dest.size || hostlen >= dest.size - schemelen)
4028
0
    return HTS_FALSE;
4029
0
  memcpy(dest.p, scheme, schemelen);
4030
0
  memcpy(dest.p + schemelen, host, hostlen);
4031
0
  dest.p[schemelen + hostlen] = '\0';
4032
0
  return HTS_TRUE;
4033
0
}
4034
4035
/* Chain hops resolved before giving up. A longer chain, or a loop, is a
4036
   misconfiguration; the fold leaves those hosts alone rather than settle on an
4037
   arbitrary hop, which would depend on how often a link is named. */
4038
enum { HTS_HOST_ALIAS_MAXHOPS = 8 };
4039
4040
/* hts_host_alias_resolve() once some alias rules are known to exist */
4041
static const char *hts_host_alias_resolve_rules(const char *rules,
4042
                                                const char *adr,
4043
                                                hts_boolean collapse_www,
4044
                                                hts_buf dest,
4045
0
                                                hts_boolean *settled) {
4046
0
  const char *proto, *host, *hostsubj, *canon;
4047
0
  char BIGSTK fullsubj[HTS_URLMAXSIZE * 2];
4048
0
  char schemebuf[32]; /* longest jump_protocol_const knows is "socks5h://" */
4049
0
  size_t canonlen = 0, schemelen;
4050
0
  int hop;
4051
4052
0
  proto = jump_protocol_const(adr);      /* after the scheme */
4053
0
  host = jump_identification_const(adr); /* after the credentials */
4054
0
  schemelen = (size_t) (proto - adr);
4055
0
  if (!hts_buf_put_span(HTS_BUF(schemebuf), hts_span_between(adr, proto)))
4056
0
    return NULL;
4057
  /* Match the host as the dedup layer does, so with the www. collapse on, a
4058
     rule naming example.com also covers www.example.com. */
4059
0
  hostsubj = collapse_www ? jump_normalized_const(host) : host;
4060
0
  if (!hts_host_alias_subject(adr, hostsubj, HTS_BUF(fullsubj)))
4061
0
    return NULL;
4062
0
  canon =
4063
0
      hts_host_alias_match(rules, hostsubj, fullsubj, collapse_www, &canonlen);
4064
0
  if (canon == NULL)
4065
0
    return NULL;
4066
4067
  /* Follow the chain to its end, so the fold is a fixpoint: url_savename names
4068
     the same link more than once, each time from the host it wrote last. */
4069
0
  for (hop = 0;; hop++) {
4070
0
    char BIGSTK canonbuf[HTS_URLMAXSIZE * 2];
4071
0
    const char *next, *dhost, *chost, *cproto;
4072
0
    size_t nextlen = 0, credlen, hostlen;
4073
4074
    /* A rule may name the canonical host's scheme. If not, the scheme in
4075
       effect stays, which may come from an earlier rule in the chain. */
4076
0
    if (!hts_buf_put_span(HTS_BUF(canonbuf), hts_span_at(canon, canonlen)))
4077
0
      return NULL;
4078
    /* the link's credentials are the ones kept, so drop any the rule carries:
4079
       they would otherwise be prepended to them again on every re-fold */
4080
0
    cproto = jump_protocol_const(canonbuf);
4081
0
    chost = jump_identification_const(cproto);
4082
0
    hostlen = canonlen - (size_t) (chost - canonbuf);
4083
0
    if (cproto != canonbuf) { /* the rule names a scheme */
4084
0
      if (!hts_buf_put_span(HTS_BUF(schemebuf),
4085
0
                            hts_span_between(canonbuf, cproto)))
4086
0
        return NULL;
4087
0
      schemelen = (size_t) (cproto - canonbuf);
4088
0
    }
4089
0
    credlen = (size_t) (host - proto);
4090
4091
0
    if (hostlen == 0)
4092
0
      return NULL; /* a rule naming no host: leave the URL alone */
4093
0
    if (schemelen >= dest.size || credlen >= dest.size - schemelen ||
4094
0
        hostlen >= dest.size - schemelen - credlen)
4095
0
      return NULL; /* would not fit: leave the URL alone */
4096
0
    memcpy(dest.p, schemebuf, schemelen);
4097
0
    memcpy(dest.p + schemelen, proto, credlen);
4098
0
    memcpy(dest.p + schemelen + credlen, chost, hostlen);
4099
0
    dest.p[schemelen + credlen + hostlen] = '\0';
4100
4101
0
    dhost = jump_identification_const(dest.p);
4102
0
    if (collapse_www)
4103
0
      dhost = jump_normalized_const(dhost);
4104
0
    if (!hts_host_alias_subject(dest.p, dhost, HTS_BUF(fullsubj)))
4105
0
      return NULL;
4106
0
    next = hts_host_alias_match(rules, dhost, fullsubj, collapse_www, &nextlen);
4107
0
    if (next == NULL)
4108
0
      break; /* settled: no rule maps this host further */
4109
0
    if (nextlen == canonlen && hts_strncasecmp(next, canon, canonlen) == 0)
4110
0
      break; /* a rule matching its own target */
4111
0
    if (hop + 1 >= HTS_HOST_ALIAS_MAXHOPS) {
4112
0
      if (settled != NULL)
4113
0
        *settled = HTS_FALSE;
4114
0
      return NULL;
4115
0
    }
4116
0
    canon = next;
4117
0
    canonlen = nextlen;
4118
0
  }
4119
  /* a host that maps to itself: keep the callers' fast path */
4120
0
  return hts_strcasecmp(dest.p, adr) != 0 ? dest.p : NULL;
4121
0
}
4122
4123
/* see htscore.h */
4124
const char *hts_host_alias_resolve(const char *rules, const char *adr,
4125
                                   hts_boolean collapse_www, hts_buf dest,
4126
0
                                   hts_boolean *settled) {
4127
0
  if (settled != NULL)
4128
0
    *settled = HTS_TRUE;
4129
0
  if (rules == NULL || *rules == '\0' || adr == NULL || dest.size == 0)
4130
0
    return NULL;
4131
  /* engine pseudo-hosts: a "*=host" rule must not swallow them */
4132
0
  if (adr[0] == '\0' || strcmp(adr, "primary") == 0 ||
4133
0
      strcmp(adr, "file://") == 0)
4134
0
    return NULL;
4135
0
  return hts_host_alias_resolve_rules(rules, adr, collapse_www, dest, settled);
4136
0
}
4137
4138
/* see htscore.h */
4139
const char *hts_host_alias(const char *rules, const char *adr,
4140
0
                           hts_boolean collapse_www, hts_buf dest) {
4141
0
  return hts_host_alias_resolve(rules, adr, collapse_www, dest, NULL);
4142
0
}
4143
4144
/* see htscore.h */
4145
0
hts_boolean hts_host_alias_collapse_www(httrackp *opt) {
4146
0
  return opt->urlhack && !opt->no_www_dedup ? HTS_TRUE : HTS_FALSE;
4147
0
}
4148
4149
/* see htscore.h */
4150
0
const char *hts_host_alias_fold(httrackp *opt, lien_adrfil *af) {
4151
0
  const char *const rules = hts_host_alias_rules(opt);
4152
4153
0
  if (rules != NULL) {
4154
0
    char BIGSTK canon[HTS_URLMAXSIZE * 2];
4155
0
    const char *const alias = hts_host_alias(
4156
0
        rules, af->adr, hts_host_alias_collapse_www(opt), HTS_BUF(canon));
4157
4158
0
    if (alias != NULL)
4159
0
      strcpybuff(af->adr, alias);
4160
0
  }
4161
0
  return af->adr;
4162
0
}
4163
4164
/* see htscore.h */
4165
hts_boolean hts_host_same_alias(const char *rules, const char *adra,
4166
0
                                const char *adrb, hts_boolean collapse_www) {
4167
0
  char BIGSTK ca[HTS_URLMAXSIZE * 2], cb[HTS_URLMAXSIZE * 2];
4168
0
  const char *a, *b;
4169
4170
0
  if (rules == NULL || *rules == '\0' || adra == NULL || adrb == NULL)
4171
0
    return HTS_FALSE;
4172
0
  a = hts_host_alias(rules, adra, collapse_www, HTS_BUF(ca));
4173
0
  b = hts_host_alias(rules, adrb, collapse_www, HTS_BUF(cb));
4174
0
  if (a == NULL && b == NULL)
4175
0
    return HTS_FALSE; /* neither is aliased: the caller's own test */
4176
0
  return hts_strcasecmp(jump_identification_const(a != NULL ? a : adra),
4177
0
                        jump_identification_const(b != NULL ? b : adrb)) == 0
4178
0
             ? HTS_TRUE
4179
0
             : HTS_FALSE;
4180
0
}
4181
4182
/* HTS_TRUE if TOKEN is a host, optionally behind the scheme it speaks
4183
   and with a trailing slash. GLOB keeps the filter metacharacters legal, which
4184
   only the alias side of a rule may use. */
4185
0
static hts_boolean hts_host_alias_token_ok(hts_span token, hts_boolean glob) {
4186
0
  char BIGSTK buff[HTS_URLMAXSIZE * 2];
4187
0
  const char *host;
4188
0
  size_t len;
4189
4190
0
  token = hts_span_trim(token, " \t", " \t");
4191
0
  if (hts_span_empty(token) || !hts_span_copy(token, HTS_SIZED(buff)))
4192
0
    return HTS_FALSE;
4193
0
  len = token.len;
4194
0
  while (len > 0 && buff[len - 1] == '/')
4195
0
    buff[--len] = '\0'; /* the matcher strips the whole run */
4196
  /* an alias may glob its scheme; an unknown canonical one lands in the host */
4197
0
  host = glob && strstr(buff, "://") != NULL ? strstr(buff, "://") + 3
4198
0
                                             : jump_protocol_const(buff);
4199
  /* a scheme with no host behind it, and the engine's own pseudo-host, name
4200
     nothing the fold could write into an address */
4201
0
  if (*host == '\0' || strcmp(host, "primary") == 0)
4202
0
    return HTS_FALSE;
4203
  /* --host-alias maps hosts: a path belongs to no part of an address */
4204
0
  if (strchr(host, '/') != NULL)
4205
0
    return HTS_FALSE;
4206
  /* a control byte names no host, and '\n' would split the store's rule list */
4207
0
  for (; *host != '\0'; host++) {
4208
0
    if ((unsigned char) *host < ' ' || *host == '\x7f')
4209
0
      return HTS_FALSE;
4210
0
    if (strchr(glob ? "=# " : "=,*?();\\#@ ", *host) != NULL)
4211
0
      return HTS_FALSE;
4212
0
  }
4213
0
  return HTS_TRUE;
4214
0
}
4215
4216
/* see httrack-library.h */
4217
0
HTSEXT_API hts_boolean hts_host_alias_rule_ok(const char *rule) {
4218
0
  hts_span aliases, canon, alias;
4219
4220
0
  if (!hts_host_alias_split(hts_span_of(rule), &aliases, &canon) ||
4221
0
      !hts_host_alias_token_ok(canon, HTS_FALSE))
4222
0
    return HTS_FALSE;
4223
0
  while (hts_span_next_in(&aliases, ',', &alias)) {
4224
0
    if (!hts_host_alias_token_ok(alias, HTS_TRUE))
4225
0
      return HTS_FALSE;
4226
0
  }
4227
0
  return HTS_TRUE;
4228
0
}
4229
4230
/* see htscore.h */
4231
const char *hts_host_alias_looping(const char *rules, hts_boolean collapse_www,
4232
0
                                   hts_buf dest) {
4233
0
  hts_span rest, line, aliases, target;
4234
4235
0
  if (rules == NULL || dest.size == 0)
4236
0
    return NULL;
4237
0
  rest = hts_span_of(rules);
4238
0
  while (hts_span_next_in(&rest, '\n', &line)) {
4239
0
    char BIGSTK canon[HTS_URLMAXSIZE * 2], tmp[HTS_URLMAXSIZE * 2];
4240
0
    hts_boolean settled;
4241
4242
0
    if (!hts_span_split(line, '=', &aliases, &target) ||
4243
0
        hts_span_empty(target) || !hts_span_copy(target, HTS_SIZED(canon)))
4244
0
      continue;
4245
    /* only whether the chain settles matters here */
4246
0
    (void) !hts_host_alias_resolve(rules, canon, collapse_www, HTS_BUF(tmp),
4247
0
                                   &settled);
4248
0
    if (!settled) {
4249
0
      if (strlen(canon) >= dest.size)
4250
0
        continue; /* Skip a name that does not fit. */
4251
0
      hts_buf_cpy(dest, canon);
4252
0
      return dest.p;
4253
0
    }
4254
0
  }
4255
0
  return NULL;
4256
0
}
4257
4258
HTSEXT_API char *adr_normalized_sized(const char *source, char *dest,
4259
0
                                      size_t destsize) {
4260
  /* not yet too aggressive (no com<->net<->org checkings) */
4261
0
  strlcpybuff(dest, jump_normalized_const(source), destsize);
4262
0
  return dest;
4263
0
}
4264
4265
// deprecated variant; kept for ABI compatibility. Bounds to the implicit
4266
// contract the old callers relied on (an HTS_URLMAXSIZE*2 URL buffer).
4267
0
HTSEXT_API char *adr_normalized(const char *source, char *dest) {
4268
0
  return adr_normalized_sized(source, dest, HTS_URLMAXSIZE * 2);
4269
0
}
4270
4271
0
int hts_basic_auth_value(httrackp *opt, const char *url, hts_buf out) {
4272
0
  hts_url_view v;
4273
0
  size_t idlen;
4274
0
  char user_pass[768];
4275
4276
0
  assertf(out.size >= 1100); /* base-64 of 765 bytes is 1020 */
4277
0
  out.p[0] = '\0';
4278
0
  (void) hts_url_view_parse(hts_span_of(url), &v);
4279
  // no login where jump_identification_const() keeps the URL whole
4280
0
  idlen = jump_identification_const(url) == v.host.p ? v.userinfo.len : 0;
4281
0
  if (idlen == 0)
4282
0
    return 0;
4283
  /* a clipped credential authenticates as somebody else, and an encoded one
4284
     wider than bauth_chain.auth could not be stored for the child pages */
4285
0
  if (idlen > (sizeof(((bauth_chain *) 0)->auth) - 1) / 4 * 3 ||
4286
0
      !hts_buf_put_span(HTS_BUF(user_pass), v.userinfo))
4287
0
    return -1;
4288
0
  strcpybuff(user_pass, unescape_http(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt),
4289
0
                                      user_pass));
4290
0
  code64(hts_span_of(user_pass), out, HTS_FALSE);
4291
0
  hts_secret_add(opt, hts_span_of(out.p), HTS_SECRET_HEADER);
4292
0
  return 1;
4293
0
}
4294
4295
0
hts_boolean hts_sni_hostname(const char *url_adr, hts_buf out) {
4296
0
  hts_url_view v;
4297
4298
0
  (void) hts_url_view_parse(hts_span_of(url_adr), &v);
4299
0
  out.p[0] = '\0';
4300
0
  if (hts_span_empty(v.host) ||
4301
0
      hts_span_starts_with(v.host, hts_span_of("[")) ||
4302
0
      hts_host_is_ipv4(v.host))
4303
0
    return HTS_FALSE;
4304
0
  return hts_buf_put_span(out, v.host);
4305
0
}
4306
4307
#if HTS_USEOPENSSL
4308
static htsmutex ssl_ca_lock = HTSMUTEX_INIT;
4309
static int ssl_ca_state = 0; /* 0 not tried, 1 loaded, -1 failed */
4310
4311
hts_boolean hts_ssl_check_cert(SSL *ssl, const char *url_adr) {
4312
  X509_VERIFY_PARAM *const param = SSL_get0_param(ssl);
4313
  char name[256];
4314
  int state;
4315
4316
  hts_mutexlock(&ssl_ca_lock);
4317
  if (ssl_ca_state == 0)
4318
    ssl_ca_state = SSL_CTX_set_default_verify_paths(openssl_ctx) == 1 ? 1 : -1;
4319
  state = ssl_ca_state;
4320
  hts_mutexrelease(&ssl_ca_lock);
4321
  if (state != 1 || param == NULL)
4322
    return HTS_FALSE;
4323
  if (hts_sni_hostname(url_adr, HTS_BUF(name))) {
4324
    const size_t len = strlen(name);
4325
4326
    /* certificates name "host", never the absolute "host." */
4327
    if (len > 1 && name[len - 1] == '.')
4328
      name[len - 1] = '\0';
4329
    if (X509_VERIFY_PARAM_set1_host(param, name, 0) != 1)
4330
      return HTS_FALSE;
4331
  } else {
4332
    /* an address literal must match an IP name of the certificate */
4333
    const char *const host = jump_identification_const(url_adr);
4334
    const char *const start = host[0] == '[' ? host + 1 : host;
4335
    const size_t len = strcspn(start, host[0] == '[' ? "]" : ":/?#\\");
4336
4337
    if (len == 0 || !hts_buf_put_span(HTS_BUF(name), hts_span_at(start, len)))
4338
      return HTS_FALSE;
4339
    if (X509_VERIFY_PARAM_set1_ip_asc(param, name) != 1)
4340
      return HTS_FALSE;
4341
  }
4342
  SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
4343
  return HTS_TRUE;
4344
}
4345
#endif
4346
4347
0
const char *hts_authority_end(const char *s) { return s + strcspn(s, "/?#\\"); }
4348
4349
/* jump_protocol_const() and the view both read these schemes. A scheme longer
4350
   than a row does not compile. */
4351
static const char hts_engine_schemes[][8] = {
4352
    "http", "ftp", "https", "file", "socks5h", "socks5", "connect"};
4353
4354
/* The most bytes an engine scheme and its ':' span. */
4355
0
#define ENGINE_SCHEME_SPAN (sizeof(hts_engine_schemes[0]) + 1)
4356
4357
/* Return the length of the engine scheme and ':' that start S, or 0. */
4358
0
static size_t engine_scheme_len(hts_span s) {
4359
0
  size_t i;
4360
4361
0
  for (i = 0; i < sizeof(hts_engine_schemes) / sizeof(hts_engine_schemes[0]);
4362
0
       i++) {
4363
0
    const char *const name = hts_engine_schemes[i];
4364
0
    const size_t n = sizeof(hts_engine_schemes[i]);
4365
0
    size_t j;
4366
4367
0
    for (j = 0;
4368
0
         j < n && name[j] != '\0' && j < s.len && streql(s.p[j], name[j]); j++)
4369
0
      ;
4370
0
    if (j < s.len && s.p[j] == ':' && (j == n || name[j] == '\0'))
4371
0
      return j + 1;
4372
0
  }
4373
0
  return 0;
4374
0
}
4375
4376
/* Is the span a decimal port in 0..65535? Empty and 0 pass, because
4377
   hts_parse_url_port() checks the 1..65535 range. */
4378
0
static hts_boolean port_is_valid(hts_span port) {
4379
0
  LLint value;
4380
4381
0
  return hts_span_empty(port) || hts_span_parse_llint(port, 0, 65535, &value);
4382
0
}
4383
4384
0
hts_boolean hts_url_view_parse(hts_span url, hts_url_view *v) {
4385
0
  const char *const s = url.p;
4386
0
  const char *const end = s + url.len;
4387
0
  const char *p = s;
4388
0
  const char *auth_end, *at, *q;
4389
0
  hts_span auth;
4390
0
  hts_boolean ok = HTS_TRUE;
4391
0
  size_t n;
4392
4393
0
  memset(v, 0, sizeof(*v));
4394
0
  if ((n = engine_scheme_len(url)) != 0) {
4395
0
    v->scheme = hts_span_at(s, n - 1);
4396
0
    p = s + n;
4397
0
  } else if (url.len != 0 && hts_isalpha((unsigned char) s[0])) {
4398
0
    for (q = s + 1; q < end && (hts_isalnum((unsigned char) *q) || *q == '+' ||
4399
0
                                *q == '-' || *q == '.');
4400
0
         q++)
4401
0
      ;
4402
0
    if (hts_span_starts_with(hts_span_between(q, end), hts_span_of("://"))) {
4403
0
      v->scheme = hts_span_between(s, q);
4404
0
      p = q + 1;
4405
0
    }
4406
0
  }
4407
0
  if (hts_span_starts_with(hts_span_between(p, end), hts_span_of("//")))
4408
0
    p += 2;
4409
4410
  // the same set as hts_authority_end(), but a NUL is data here
4411
0
  for (auth_end = p; auth_end < end && *auth_end != '/' && *auth_end != '?' &&
4412
0
                     *auth_end != '#' && *auth_end != '\\';
4413
0
       auth_end++)
4414
0
    ;
4415
0
  for (at = NULL, q = p; q < auth_end; q++)
4416
0
    if (*q == '@')
4417
0
      at = q;
4418
0
  if (at != NULL) {
4419
0
    v->userinfo = hts_span_between(p, at);
4420
0
    p = at + 1;
4421
0
  }
4422
4423
0
  auth = hts_span_between(p, auth_end);
4424
0
  if (hts_span_starts_with(auth, hts_span_of("["))) {
4425
0
    hts_span inside, rest;
4426
4427
0
    if (hts_span_split(auth, ']', &inside, &rest) &&
4428
0
        (hts_span_empty(rest) ||
4429
0
         hts_span_starts_with(rest, hts_span_of(":")))) {
4430
0
      v->host = hts_span_at(auth.p, inside.len + 1);
4431
0
      if (!hts_span_empty(rest))
4432
0
        v->port = hts_span_skip(rest, 1);
4433
0
    } else {
4434
0
      v->host = auth;
4435
0
      ok = HTS_FALSE;
4436
0
    }
4437
0
  } else if (!hts_span_split(auth, ':', &v->host, &v->port)) {
4438
0
    v->host = auth;
4439
0
  }
4440
0
  if (hts_span_present(v->port) && !port_is_valid(v->port))
4441
0
    ok = HTS_FALSE;
4442
4443
0
  for (q = auth_end; q < end && *q != '?' && *q != '#'; q++)
4444
0
    ;
4445
0
  v->path = hts_span_between(auth_end, q);
4446
0
  if (q < end && *q == '?') {
4447
0
    const char *const query = q + 1;
4448
4449
0
    for (q = query; q < end && *q != '#'; q++)
4450
0
      ;
4451
0
    v->query = hts_span_between(query, q);
4452
0
  }
4453
0
  if (q < end)
4454
0
    v->fragment = hts_span_between(q + 1, end);
4455
0
  return ok;
4456
0
}
4457
4458
// find the authority's port (:80) or NULL; handles IPv6 literals
4459
0
const char *jump_toport_const(const char *source) {
4460
0
  hts_url_view v;
4461
4462
0
  (void) hts_url_view_parse(hts_span_of(source), &v);
4463
  // jump_identification_const() keeps these whole, so their ':' is the port
4464
0
  if (hts_span_present(v.scheme) &&
4465
0
      (strcmp(source, "file://") == 0 || jump_protocol_const(source) == source))
4466
0
    return source + v.scheme.len;
4467
0
  return hts_span_present(v.port) ? v.port.p - 1 : NULL;
4468
0
}
4469
4470
0
DECLARE_NON_CONST_VERSION(jump_toport)
4471
4472
// strrchr, but not too far
4473
0
const char *strrchr_limit(const char *s, char c, const char *limit) {
4474
0
  if (limit == NULL) {
4475
0
    const char *p = strrchr(s, c);
4476
4477
0
    return p ? (p + 1) : NULL;
4478
0
  } else {
4479
0
    const char *a = NULL, *p;
4480
4481
0
    for(;;) {
4482
0
      p = strchr((a) ? a : s, c);
4483
0
      if ((p >= limit) || (p == NULL))
4484
0
        return a;
4485
0
      a = p + 1;
4486
0
    }
4487
0
  }
4488
0
}
4489
4490
// Returns source past its engine scheme and "//", if any.
4491
0
const char *jump_protocol_const(const char *source) {
4492
  // "Comparisons of scheme names MUST be case-insensitive" (RFC2616)
4493
0
  source += engine_scheme_len(
4494
0
      hts_span_at(source, strnlen(source, ENGINE_SCHEME_SPAN)));
4495
  // net_path
4496
0
  if (strncmp(source, "//", 2) == 0)
4497
0
    source += 2;
4498
0
  return source;
4499
0
}
4500
4501
0
DECLARE_NON_CONST_VERSION(jump_protocol)
4502
4503
0
hts_boolean hts_span_is_control_free(hts_span s) {
4504
0
  size_t i;
4505
4506
0
  for (i = 0; i < s.len; i++) {
4507
0
    if ((unsigned char) s.p[i] < ' ')
4508
0
      return HTS_FALSE;
4509
0
  }
4510
0
  return HTS_TRUE;
4511
0
}
4512
4513
0
hts_boolean hts_is_control_free(const char *str) {
4514
0
  return hts_span_is_control_free(hts_span_of(str));
4515
0
}
4516
4517
0
hts_boolean hts_host_is_ipv4(hts_span host) {
4518
0
  size_t i;
4519
0
  int dots = 0;
4520
4521
0
  for (i = 0; i < host.len; i++) {
4522
0
    if (host.p[i] == '.')
4523
0
      dots++;
4524
0
    else if (host.p[i] < '0' || host.p[i] > '9')
4525
0
      return HTS_FALSE;
4526
0
  }
4527
0
  return dots > 0 ? HTS_TRUE : HTS_FALSE;
4528
0
}
4529
4530
0
hts_boolean hts_host_is_address(hts_span host) {
4531
0
  return hts_span_find(host, ':') < host.len || hts_host_is_ipv4(host);
4532
0
}
4533
4534
0
hts_boolean hts_proxy_is_socks(const char *name) {
4535
0
  if (name == NULL)
4536
0
    return HTS_FALSE;
4537
0
  return hts_starts_with_ci(name, "socks5h:") ||
4538
0
         hts_starts_with_ci(name, "socks5:");
4539
0
}
4540
4541
0
hts_boolean hts_proxy_is_connect(const char *name) {
4542
0
  if (name == NULL)
4543
0
    return HTS_FALSE;
4544
0
  return hts_starts_with_ci(name, "connect:");
4545
0
}
4546
4547
// default proxy port for a -P argument, keyed on the scheme
4548
0
static int proxy_default_port(const char *arg) {
4549
0
  return hts_proxy_is_socks(arg) ? 1080 : 8080;
4550
0
}
4551
4552
// port "a" of -P argument "arg": digits fitting TCP's 1..65535, else the scheme
4553
// default. Not sscanf("%d"): past INT_MAX it wraps to a garbage port (#602)
4554
0
static int parse_proxy_port(const char *a, const char *arg) {
4555
0
  int port;
4556
4557
0
  if (!hts_parse_url_port(a, &port))
4558
0
    return proxy_default_port(arg);
4559
0
  return port;
4560
0
}
4561
4562
0
void hts_parse_proxy(const char *arg, hts_buf name, int *port) {
4563
0
  const char *authority = strstr(arg, "://");
4564
0
  const char *a, *at;
4565
0
  size_t namelen, i;
4566
4567
0
  if (name.size == 0)
4568
0
    return;
4569
  // scan back to the port ':' (or userinfo '@'), never past the authority (a
4570
  // scheme's own colon is not a port separator) nor into an IPv6 literal (']'
4571
  // stops it); inspect a[-1] from one-past-end so no pointer underflows
4572
0
  authority = (authority != NULL) ? authority + 3 : arg;
4573
0
  a = arg + strlen(arg);
4574
0
  while (a > authority && a[-1] != ':' && a[-1] != '@' && a[-1] != ']')
4575
0
    a--;
4576
0
  if (a > authority && a[-1] == ':') {
4577
0
    *port = parse_proxy_port(a, arg);
4578
0
    namelen = (size_t) (a - 1 - arg);
4579
0
  } else {
4580
0
    *port = proxy_default_port(arg);
4581
0
    namelen = strlen(arg);
4582
0
  }
4583
0
  at = authority;
4584
0
  for (i = (size_t) (authority - arg); i < namelen; i++)
4585
0
    if (arg[i] == '@')
4586
0
      at = arg + i;
4587
  // escape what would end the authority early: the login is unescaped later
4588
0
  (void) hts_escape_span(hts_span_at(arg, namelen),
4589
0
                         hts_span_between(authority, at), "/?#\\", name);
4590
0
}
4591
4592
static hts_boolean hts_escape_span(hts_span src, hts_span escaped,
4593
0
                                   const char *set, hts_buf dst) {
4594
0
  size_t i, len = 0;
4595
4596
0
  if (dst.size == 0)
4597
0
    return HTS_FALSE;
4598
0
  for (i = 0; i < src.len; i++) {
4599
0
    const char *const c = src.p + i;
4600
4601
0
    if (c >= escaped.p && c < escaped.p + escaped.len &&
4602
0
        strchr(set, *c) != NULL) {
4603
0
      if (dst.size - len <= 3)
4604
0
        break;
4605
0
      snprintf(dst.p + len, 4, "%%%02X", (unsigned char) *c);
4606
0
      len += 3;
4607
0
    } else {
4608
0
      if (dst.size - len <= 1)
4609
0
        break;
4610
0
      dst.p[len++] = *c;
4611
0
    }
4612
0
  }
4613
0
  dst.p[len] = '\0';
4614
0
  return i == src.len ? HTS_TRUE : HTS_FALSE;
4615
0
}
4616
4617
591k
void code64(hts_span in, hts_buf out, hts_boolean crlf) {
4618
591k
  static const char alphabet[] =
4619
591k
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4620
591k
  const unsigned char *const a = (const unsigned char *) in.p;
4621
591k
  const size_t groups = (in.len + 2) / 3;
4622
591k
  size_t i, j = 0, line = 0;
4623
4624
591k
  assertf(groups * 4 + (crlf ? groups / (HTS_BASE64_LINE_BYTES / 3) * 2 : 0) <
4625
0
          out.size);
4626
4.67M
  for (i = 0; i < in.len; i += 3) {
4627
4.08M
    const size_t n = in.len - i < 3 ? in.len - i : 3;
4628
4.08M
    const unsigned long store = (unsigned long) a[i] << 16 |
4629
4.08M
                                (n > 1 ? (unsigned long) a[i + 1] << 8 : 0) |
4630
4.08M
                                (n > 2 ? a[i + 2] : 0);
4631
4632
4.08M
    out.p[j++] = alphabet[(store >> 18) & 63];
4633
4.08M
    out.p[j++] = alphabet[(store >> 12) & 63];
4634
4.08M
    out.p[j++] = n > 1 ? alphabet[(store >> 6) & 63] : '=';
4635
4.08M
    out.p[j++] = n > 2 ? alphabet[store & 63] : '=';
4636
4.08M
    if (crlf && ++line == HTS_BASE64_LINE_BYTES / 3) {
4637
0
      line = 0;
4638
0
      out.p[j++] = '\r';
4639
0
      out.p[j++] = '\n';
4640
0
    }
4641
4.08M
  }
4642
591k
  out.p[j] = '\0';
4643
591k
}
4644
4645
710k
void unescape_amp(char *s) {
4646
710k
  if (hts_unescapeEntities(s, hts_buf_at(s, strlen(s) + 1)) != 0) {
4647
0
    assertf(! "error escaping html entities");
4648
0
  }
4649
710k
}
4650
4651
// remplacer %20 par ' ', etc..
4652
// buffer MAX 1Ko
4653
710k
HTSEXT_API char *unescape_http(char *const catbuff, const size_t size, const char *const s) {
4654
710k
  size_t i, j;
4655
4656
710k
  RUNTIME_TIME_CHECK_SIZE(size);
4657
4658
5.90M
  for(i = 0, j = 0; s[i] != '\0' && j + 1 < size ; i++) {
4659
5.19M
    int h;
4660
5.19M
    if (s[i] == '%' && (h = hts_ehex(&s[i + 1])) >= 0) {
4661
1.06k
      catbuff[j++] = (char) h;
4662
1.06k
      i += 2;
4663
1.06k
    } else
4664
5.19M
      catbuff[j++] = s[i];
4665
5.19M
  }
4666
710k
  catbuff[j++] = '\0';
4667
710k
  return catbuff;
4668
710k
}
4669
4670
// unescape in URL/URI ONLY what has to be escaped, to form a standard URL/URI
4671
// DOES NOT DECODE %25 (part of CHAR_DELIM)
4672
// no_high & 1: keep high chars (>= 127) escaped
4673
// no_high & 2: decode space
4674
HTSEXT_API char *unescape_http_unharm(char *const catbuff, const size_t size,
4675
                                      const char *s,
4676
0
                                      const hts_boolean no_high) {
4677
0
  size_t i, j;
4678
4679
0
  RUNTIME_TIME_CHECK_SIZE(size);
4680
4681
0
  for(i = 0, j = 0; s[i] != '\0' && j + 1 < size ; i++) {
4682
0
    if (s[i] == '%') {
4683
0
      const int nchar = hts_ehex(&s[i + 1]);
4684
4685
0
      const int test = 
4686
0
        ( CHAR_RESERVED(nchar) && nchar != '+' )        /* %2B => + (not in query!) */
4687
0
        || CHAR_DELIM(nchar)
4688
0
        || CHAR_UNWISE(nchar)
4689
0
        || CHAR_LOW(nchar)    /* CHAR_SPECIAL */
4690
0
        || ( CHAR_XXAVOID(nchar) && ( nchar != ' ' || ( no_high & 2) == 0 ) )
4691
0
        || ( ( no_high & 1 ) && CHAR_HIG(nchar) )
4692
0
        ;
4693
4694
0
      if (!test && nchar >= 0) {  /* can safely unescape */
4695
0
        catbuff[j++] = (char) nchar;
4696
0
        i += 2;
4697
0
      } else {
4698
0
        catbuff[j++] = '%';
4699
0
      }
4700
0
    } else {
4701
0
      catbuff[j++] = s[i];
4702
0
    }
4703
0
  }
4704
0
  catbuff[j++] = '\0';
4705
0
  return catbuff;
4706
0
}
4707
4708
// remplacer " par %xx etc..
4709
// buffer MAX 1Ko
4710
size_t escape_spc_url(const char *const src, char *const dest,
4711
0
                      const size_t size) {
4712
0
  return x_escape_http(src, hts_buf_at(dest, size), HTS_ESC_SPC_URL);
4713
0
}
4714
4715
// smith / john -> smith%20%2f%20john
4716
HTSEXT_API size_t escape_in_url(const char *const src, 
4717
0
                                char *const dest, const size_t size) {
4718
0
  return x_escape_http(src, hts_buf_at(dest, size), HTS_ESC_IN_URL);
4719
0
}
4720
4721
// smith / john -> smith%20/%20john
4722
0
size_t escape_uri(const char *const src, char *const dest, const size_t size) {
4723
0
  return x_escape_http(src, hts_buf_at(dest, size), HTS_ESC_URI);
4724
0
}
4725
4726
size_t escape_uri_utf(const char *const src, char *const dest,
4727
0
                      const size_t size) {
4728
0
  return x_escape_http(src, hts_buf_at(dest, size), HTS_ESC_URI_UTF);
4729
0
}
4730
4731
HTSEXT_API size_t escape_check_url(const char *const src, char *const dest,
4732
0
                                   const size_t size) {
4733
0
  return x_escape_http(src, hts_buf_at(dest, size), HTS_ESC_CHECK_URL);
4734
0
}
4735
4736
0
size_t escape_control_url(const char *const src, hts_buf dest) {
4737
0
  return x_escape_http(src, dest, HTS_ESC_CONTROL_URL);
4738
0
}
4739
4740
// same as escape_check_url, but returns char*
4741
0
char *escape_check_url_addr(const char *const src, hts_buf dest) {
4742
0
  escape_check_url(src, dest.p, dest.size);
4743
0
  return dest.p;
4744
0
}
4745
4746
// Same as above, but appending to "dest"
4747
#undef DECLARE_APPEND_ESCAPE_VERSION
4748
/* clang-format off: an edit realigns all backslashes, churning the macro. */
4749
/* clang-format off */
4750
#define DECLARE_APPEND_ESCAPE_VERSION(NAME) \
4751
0
size_t append_ ##NAME(const char *const src, hts_buf dest) { \
4752
0
  const size_t len = strnlen(dest.p, dest.size); \
4753
0
  assertf(len < dest.size); \
4754
0
  RUNTIME_TIME_CHECK_SIZE(dest.size); \
4755
0
  /* A near-full buffer can leave the remainder the size heuristic rejects. \
4756
0
     Report it as the overflow the caller already tests for. */ \
4757
0
  if (dest.size - len == sizeof(void *)) { \
4758
0
    return dest.size - len; \
4759
0
  } \
4760
0
  return NAME(src, dest.p + len, dest.size - len); \
4761
0
}
Unexecuted instantiation: append_escape_in_url
Unexecuted instantiation: append_escape_spc_url
Unexecuted instantiation: append_escape_check_url
4762
/* clang-format on */
4763
4764
DECLARE_APPEND_ESCAPE_VERSION(escape_in_url)
4765
DECLARE_APPEND_ESCAPE_VERSION(escape_spc_url)
4766
DECLARE_APPEND_ESCAPE_VERSION(escape_check_url)
4767
4768
#undef DECLARE_APPEND_ESCAPE_VERSION
4769
4770
// In-place escaping: copy dest aside, then escape that copy back into dest.
4771
typedef size_t (*escape_fn_t)(const char *src, char *dest, size_t size);
4772
4773
0
static size_t inplace_escape(hts_buf dest, escape_fn_t escape) {
4774
0
  char buffer[256];
4775
0
  const size_t len = strnlen(dest.p, dest.size);
4776
0
  const int in_buffer = len + 1 < sizeof(buffer);
4777
0
  char *src = in_buffer ? buffer : malloct(len + 1);
4778
0
  size_t ret;
4779
0
  assertf(src != NULL);
4780
0
  assertf(len < dest.size);
4781
0
  memcpy(src, dest.p, len + 1);
4782
0
  ret = escape(src, dest.p, dest.size);
4783
0
  if (!in_buffer) {
4784
0
    freet(src);
4785
0
  }
4786
0
  return ret;
4787
0
}
4788
4789
// Thin wrappers binding inplace_escape() to each escaper.
4790
#undef DECLARE_INPLACE_ESCAPE_VERSION
4791
#define DECLARE_INPLACE_ESCAPE_VERSION(NAME)                                   \
4792
0
  size_t inplace_##NAME(char *const dest, const size_t size) {                 \
4793
0
    return inplace_escape(hts_buf_at(dest, size), NAME);                       \
4794
0
  }
Unexecuted instantiation: inplace_escape_in_url
Unexecuted instantiation: inplace_escape_spc_url
Unexecuted instantiation: inplace_escape_uri_utf
Unexecuted instantiation: inplace_escape_check_url
Unexecuted instantiation: inplace_escape_uri
4795
4796
DECLARE_INPLACE_ESCAPE_VERSION(escape_in_url)
4797
DECLARE_INPLACE_ESCAPE_VERSION(escape_spc_url)
4798
DECLARE_INPLACE_ESCAPE_VERSION(escape_uri_utf)
4799
DECLARE_INPLACE_ESCAPE_VERSION(escape_check_url)
4800
DECLARE_INPLACE_ESCAPE_VERSION(escape_uri)
4801
4802
#undef DECLARE_INPLACE_ESCAPE_VERSION
4803
4804
size_t make_content_id(const char *const adr, const char *const fil,
4805
0
                       hts_buf dest) {
4806
0
  char *a;
4807
0
  size_t esc_size = escape_in_url(adr, dest.p, dest.size);
4808
  /* the append form takes a remainder the size check would misread */
4809
0
  if (esc_size < dest.size)
4810
0
    esc_size += append_escape_in_url(fil, dest);
4811
0
  RUNTIME_TIME_CHECK_SIZE(dest.size);
4812
  /* A '%' would be decoded again by whoever reads the cid: URL. The marker has
4813
     to be a character escape_in_url() itself escapes, or two URLs can share one
4814
     Content-ID and one part then serves both (#1925). */
4815
0
  for (a = dest.p; (a = strchr(a, '%')) != NULL; a++) {
4816
0
    *a = '-';
4817
0
  }
4818
0
  return esc_size;
4819
0
}
4820
4821
// strip all control characters
4822
0
void escape_remove_control(char *const s) {
4823
0
  size_t i, j;
4824
0
  for(i = 0, j = 0 ; s[i] != '\0' ; i++) {
4825
0
    const unsigned char c = (unsigned  char) s[i];
4826
0
    if (c >= 32) {
4827
0
      if (i != j) {
4828
0
        assertf(j < i);
4829
0
        s[j] = s[i];
4830
0
      }
4831
0
      j++;
4832
0
    }
4833
0
  }
4834
  // compaction left the original tail sitting past j
4835
0
  s[j] = '\0';
4836
0
}
4837
4838
#undef ADD_CHAR
4839
#define ADD_CHAR(DEST, J, SIZE, C)                                             \
4840
0
  do {                                                                         \
4841
0
    assertf(J < SIZE);                                                         \
4842
0
    if ((J) + 1 == (SIZE)) {                                                   \
4843
0
      (DEST)[J] = '\0';                                                        \
4844
0
      return (SIZE);                                                           \
4845
0
    }                                                                          \
4846
0
    (DEST)[(J)++] = (C);                                                       \
4847
0
  } while (0)
4848
4849
/* Returns the number of characters written (not taking in account the terminating \0), or 'size' upon overflow. */
4850
static size_t x_escape_http(const char *const s, hts_buf out,
4851
0
                            const hts_escape_class mode) {
4852
0
  static const char hex[] = "0123456789abcdef";
4853
0
  char *const dest = out.p;
4854
0
  const size_t size = out.size;
4855
0
  size_t i, j;
4856
4857
0
  RUNTIME_TIME_CHECK_SIZE(size);
4858
4859
  // Out-of-bound.
4860
  // Previous character is supposed to be the terminating \0.
4861
0
  if (size == 0) {
4862
0
    return 0;
4863
0
  }
4864
4865
0
  for(i = 0, j = 0 ; s[i] != '\0' ; i++) {
4866
0
    const unsigned char c = (unsigned char) s[i];
4867
0
    int test = 0;
4868
4869
0
    switch (mode) {
4870
0
    case HTS_ESC_CHECK_URL:
4871
0
      test = c == '"' || c == ' ' || CHAR_SPECIAL(c);
4872
0
      break;
4873
0
    case HTS_ESC_IN_URL:
4874
0
      test = CHAR_RESERVED(c) || CHAR_DELIM(c) || CHAR_UNWISE(c) ||
4875
0
             CHAR_SPECIAL(c) || CHAR_XXAVOID(c) || CHAR_MARK(c);
4876
0
      break;
4877
0
    case HTS_ESC_SPC_URL:
4878
0
      test = c == ' ';
4879
0
      break;
4880
0
    case HTS_ESC_URI: // only what must be escaped
4881
0
      test = CHAR_SPECIAL(c) || CHAR_XXAVOID(c);
4882
0
      break;
4883
0
    case HTS_ESC_CONTROL_URL: // C0 controls only, leaving high bytes (UTF-8)
4884
0
      test = CHAR_LOW(c);
4885
0
      break;
4886
0
    case HTS_ESC_URI_UTF:
4887
0
      test = (c != '/' && CHAR_RESERVED(c)) || CHAR_DELIM(c) ||
4888
0
             CHAR_UNWISE(c) || CHAR_SPECIAL(c) || CHAR_XXAVOID(c);
4889
0
      break;
4890
0
    }
4891
4892
0
    if (!test) {
4893
0
      ADD_CHAR(dest, j, size, c);
4894
0
    } else {
4895
0
      ADD_CHAR(dest, j, size, '%');
4896
0
      ADD_CHAR(dest, j, size, hex[c / 16]);
4897
0
      ADD_CHAR(dest, j, size, hex[c % 16]);
4898
0
    }
4899
0
  }
4900
4901
0
  assertf(j < size);
4902
0
  dest[j] = '\0';
4903
0
  return j;
4904
0
}
4905
4906
size_t escape_for_html_print(const char *const s, char *const dest,
4907
0
                             const size_t size) {
4908
0
  size_t i, j;
4909
4910
0
  RUNTIME_TIME_CHECK_SIZE(size);
4911
4912
0
  for(i = 0, j = 0 ; s[i] != '\0' ; i++) {
4913
0
    const unsigned char c = (unsigned char) s[i];
4914
0
    if (c == '&') {
4915
0
      ADD_CHAR(dest, j, size, '&');
4916
0
      ADD_CHAR(dest, j, size, 'a');
4917
0
      ADD_CHAR(dest, j, size, 'm');
4918
0
      ADD_CHAR(dest, j, size, 'p');
4919
0
      ADD_CHAR(dest, j, size, ';');
4920
0
    } else {
4921
0
      ADD_CHAR(dest, j, size, c);
4922
0
    }
4923
0
  }
4924
0
  assertf(j < size);
4925
0
  dest[j] = '\0';
4926
0
  return j;
4927
0
}
4928
4929
size_t escape_for_html_print_full(const char *const s, char *const dest,
4930
0
                                  const size_t size) {
4931
0
  static const char hex[] = "0123456789abcdef";
4932
0
  size_t i, j;
4933
4934
0
  RUNTIME_TIME_CHECK_SIZE(size);
4935
4936
0
  for(i = 0, j = 0 ; s[i] != '\0' ; i++) {
4937
0
    const unsigned char c = (unsigned char) s[i];
4938
0
    if (c == '&') {
4939
0
      ADD_CHAR(dest, j, size, '&');
4940
0
      ADD_CHAR(dest, j, size, 'a');
4941
0
      ADD_CHAR(dest, j, size, 'm');
4942
0
      ADD_CHAR(dest, j, size, 'p');
4943
0
      ADD_CHAR(dest, j, size, ';');
4944
0
    } else if (CHAR_HIG(c)) {
4945
0
      ADD_CHAR(dest, j, size, '&');
4946
0
      ADD_CHAR(dest, j, size, '#');
4947
0
      ADD_CHAR(dest, j, size, 'x');
4948
0
      ADD_CHAR(dest, j, size, hex[c / 16]);
4949
0
      ADD_CHAR(dest, j, size, hex[c % 16]);
4950
0
      ADD_CHAR(dest, j, size, ';');
4951
0
    } else {
4952
0
      ADD_CHAR(dest, j, size, c);
4953
0
    }
4954
0
  }
4955
0
  assertf(j < size);
4956
0
  dest[j] = '\0';
4957
0
  return j;
4958
0
}
4959
4960
#undef ADD_CHAR
4961
4962
// -- Utils fichiers
4963
4964
/* Le fichier existe-t-il? (ou est-il accessible?) */
4965
/* Note: NOT utf-8 */
4966
/* Note: preserve errno */
4967
0
int fexist(const char *s) {
4968
0
  char catbuff[CATBUFF_SIZE];
4969
0
  const int err = errno;
4970
0
  struct stat st;
4971
4972
0
  memset(&st, 0, sizeof(st));
4973
0
  if (stat(fconv(catbuff, sizeof(catbuff), s), &st) == 0) {
4974
0
    if (S_ISREG(st.st_mode)) {
4975
0
      return 1;
4976
0
    } else {
4977
0
      return 0;
4978
0
    }
4979
0
  }
4980
0
  errno = err;
4981
0
  return 0;
4982
0
}
4983
4984
/* Le fichier existe-t-il? (ou est-il accessible?) */
4985
/* Note: utf-8 */
4986
/* Note: preserve errno */
4987
703k
int fexist_utf8(const char *s) {
4988
703k
  char catbuff[CATBUFF_SIZE];
4989
703k
  const int err = errno;
4990
703k
  STRUCT_STAT st;
4991
4992
703k
  memset(&st, 0, sizeof(st));
4993
703k
  if (STAT(fconv(catbuff, sizeof(catbuff), s), &st) == 0) {
4994
594k
    if (S_ISREG(st.st_mode)) {
4995
593k
      return 1;
4996
593k
    } else {
4997
498
      return 0;
4998
498
    }
4999
594k
  }
5000
703k
  errno = err;
5001
109k
  return 0;
5002
703k
}
5003
5004
/* See htslib.h. */
5005
0
hts_boolean hts_path_absent(const char *path) {
5006
0
  char BIGSTK buf[HTS_URLMAXSIZE * 2];
5007
0
  size_t len = strlen(path);
5008
0
  STRUCT_STAT st;
5009
5010
0
  if (len == 0 || len >= sizeof(buf))
5011
0
    return HTS_FALSE;
5012
  /* MSVC's stat fails on a directory named with a trailing separator */
5013
0
  while (len > 1 && (path[len - 1] == '/' || path[len - 1] == PATH_SEPARATOR))
5014
0
    len--;
5015
0
  memcpy(buf, path, len);
5016
0
  buf[len] = '\0';
5017
0
  return STAT(buf, &st) != 0 && errno == ENOENT;
5018
0
}
5019
5020
/* File size, -1 if absent */
5021
/* Note: utf-8 */
5022
1.18M
LLint fsize_utf8(const char *s) {
5023
1.18M
  STRUCT_STAT st;
5024
5025
1.18M
  if (!strnotempty(s)) // empty name: error
5026
0
    return -1;
5027
1.18M
  if (STAT(s, &st) == 0 && S_ISREG(st.st_mode)) {
5028
1.18M
    return st.st_size;
5029
1.18M
  } else {
5030
0
    return -1;
5031
0
  }
5032
1.18M
}
5033
5034
/* root dir, with ending / */
5035
typedef struct {
5036
  char path[1024 + 4];
5037
  int init;
5038
} hts_rootdir_strc;
5039
0
HTSEXT_API const char *hts_rootdir(char *file) {
5040
0
  static hts_rootdir_strc strc = { "", 0 };
5041
0
  if (file) {
5042
0
    if (!strc.init) {
5043
0
      strc.path[0] = '\0';
5044
0
      strc.init = 1;
5045
0
      if (strnotempty(file)) {
5046
0
        const size_t file_len = strlen(file);
5047
0
        char *a;
5048
5049
0
        assertf(file_len < sizeof(strc.path));
5050
0
        strcpybuff(strc.path, file);
5051
0
        while((a = strrchr(strc.path, '\\')))
5052
0
          *a = '/';
5053
0
        if ((a = strrchr(strc.path, '/'))) {
5054
0
          *(a + 1) = '\0';
5055
0
        } else
5056
0
          strc.path[0] = '\0';
5057
0
      }
5058
0
      if (!strnotempty(strc.path)) {
5059
0
        if (getcwd(strc.path, sizeof(strc.path)) == NULL)
5060
0
          strc.path[0] = '\0';
5061
0
        else
5062
0
          strcatbuff(strc.path, "/");
5063
0
      }
5064
0
    }
5065
0
    return NULL;
5066
0
  } else if (strc.init)
5067
0
    return strc.path;
5068
0
  else
5069
0
    return "";
5070
0
}
5071
5072
HTSEXT_API hts_stat_struct HTS_STAT;
5073
5074
/* Where the received-byte total lives (see htslib.h). Its lock guards this and
5075
   nothing else, so a worker counting bytes waits on nothing else either. */
5076
static LLint stat_recv_total = 0;
5077
static htsmutex stat_recv_lock = HTSMUTEX_INIT;
5078
5079
0
void hts_stat_recv_add(LLint bytes) {
5080
0
  hts_mutexlock(&stat_recv_lock);
5081
0
  stat_recv_total += bytes;
5082
0
  hts_mutexrelease(&stat_recv_lock);
5083
0
}
5084
5085
0
LLint hts_stat_recv_get(void) {
5086
0
  LLint bytes;
5087
5088
0
  hts_mutexlock(&stat_recv_lock);
5089
0
  bytes = stat_recv_total;
5090
0
  hts_mutexrelease(&stat_recv_lock);
5091
0
  return bytes;
5092
0
}
5093
5094
0
void hts_stat_recv_set(LLint bytes) {
5095
0
  hts_mutexlock(&stat_recv_lock);
5096
0
  stat_recv_total = bytes;
5097
0
  hts_mutexrelease(&stat_recv_lock);
5098
0
}
5099
5100
0
LLint hts_stat_recv_publish(void) {
5101
0
  return HTS_STAT.HTS_TOTAL_RECV = hts_stat_recv_get();
5102
0
}
5103
5104
//
5105
// return  number of downloadable bytes, depending on rate limiter
5106
// see engine_stats() routine, too
5107
// this routine works quite well for big files and regular ones, but apparently the rate limiter has
5108
// some problems with very small files (rate too high)
5109
0
LLint check_downloadable_bytes(int rate) {
5110
0
  if (rate > 0) {
5111
0
    TStamp time_now;
5112
0
    TStamp elapsed_useconds;
5113
0
    LLint bytes_transferred_during_period;
5114
0
    LLint left;
5115
5116
    // get the older timer
5117
0
    int id_timer = (HTS_STAT.istat_idlasttimer + 1) % 2;
5118
5119
0
    time_now = mtime_monotonic();
5120
0
    elapsed_useconds = time_now - HTS_STAT.istat_timestart[id_timer];
5121
0
    bytes_transferred_during_period =
5122
0
        (hts_stat_recv_get() - HTS_STAT.istat_bytes[id_timer]);
5123
5124
0
    left = ((rate * elapsed_useconds) / 1000) - bytes_transferred_during_period;
5125
0
    if (left <= 0)
5126
0
      left = 0;
5127
5128
0
    return left;
5129
0
  } else
5130
0
    return TAILLE_BUFFER;
5131
0
}
5132
5133
// Lecture dans buff de size octets au maximum en utilisant la socket r (structure htsblk)
5134
// returns: 
5135
// >0 : data received
5136
// == 0 : not yet data
5137
// <0: error or no data: READ_ERROR, READ_EOF or READ_TIMEOUT
5138
0
static int hts_read(htsblk *r, hts_buf buff) {
5139
0
  const int size = hts_sat_int(buff.size);
5140
0
  int retour;
5141
5142
0
  if (r->is_file) {
5143
0
    if (r->fp) {
5144
0
      retour = (int) fread(buff.p, 1, size, r->fp);
5145
0
      if (retour == 0)  // can happen with directories (!)
5146
0
        retour = READ_ERROR;
5147
0
    } else
5148
0
      retour = READ_ERROR;
5149
0
  } else {
5150
#if HTS_USEOPENSSL
5151
    if (r->ssl) {
5152
      /* It writes: the SSL_ERROR_WANT_WRITE arm below is that case. */
5153
      sigpipe_mask m;
5154
5155
      sigpipe_hold(&m);
5156
      retour = SSL_read(r->ssl_con, buff.p, size);
5157
      sigpipe_release(&m);
5158
      if (retour <= 0) {
5159
        int err_code = SSL_get_error(r->ssl_con, retour);
5160
5161
        if ((err_code == SSL_ERROR_WANT_READ)
5162
            || (err_code == SSL_ERROR_WANT_WRITE)
5163
          ) {
5164
          retour = 0;           /* no data yet (ssl cache) */
5165
        } else if (err_code == SSL_ERROR_ZERO_RETURN) {
5166
          retour = READ_EOF;    /* completed */
5167
        } else {
5168
          retour = READ_ERROR;  /* eof or error */
5169
        }
5170
      }
5171
    } else {
5172
#endif
5173
0
      retour = (int) recv(r->soc, buff.p, size, 0);
5174
0
      if (retour == 0) {
5175
0
        retour = READ_EOF;
5176
0
      } else if (retour < 0) {
5177
0
        retour = READ_ERROR;
5178
0
      }
5179
0
    }
5180
0
    if (retour > 0)             // compter flux entrant
5181
0
      hts_stat_recv_add(retour);
5182
#if HTS_USEOPENSSL
5183
  }
5184
#endif
5185
0
  return retour;
5186
0
}
5187
5188
// -- divers //
5189
5190
int hts_realloct_fault_selftest = 0;
5191
5192
static void hts_debug_log_print(HTS_FORMAT_STRING const char *format, ...)
5193
    HTS_PRINTF_FUN(1, 2);
5194
5195
static int hts_dgb_init = 0;
5196
static FILE *hts_dgb_init_fp = NULL;
5197
5198
/* Set the debug verbosity (0 is off); higher levels log more to stderr. Bit
5199
   0x80 redirects debug output to "hts-debug.txt". */
5200
0
static void hts_debug(int level) {
5201
0
  hts_dgb_init = level;
5202
0
  if (hts_dgb_init > 0) {
5203
0
    hts_debug_log_print("hts_debug() called");
5204
0
  }
5205
0
}
5206
5207
0
static FILE *hts_dgb_(void) {
5208
0
  if (hts_dgb_init_fp == NULL) {
5209
0
    if ((hts_dgb_init & 0x80) == 0) {
5210
0
      hts_dgb_init_fp = stderr;
5211
0
    } else {
5212
0
      hts_dgb_init_fp = FOPEN("hts-debug.txt", "wb");
5213
0
      if (hts_dgb_init_fp != NULL) {
5214
0
        fprintf(hts_dgb_init_fp, "* Creating file\r\n");
5215
0
      }
5216
0
    }
5217
0
  }
5218
0
  return hts_dgb_init_fp;
5219
0
}
5220
5221
5
static void hts_debug_log_print(HTS_FORMAT_STRING const char *format, ...) {
5222
5
  if (hts_dgb_init > 0) {
5223
0
    const int error = errno;
5224
0
    FILE *const fp = hts_dgb_();
5225
0
    va_list args;
5226
5227
0
    assertf(format != NULL);
5228
0
    va_start(args, format);
5229
0
    (void) vfprintf(fp, format, args);
5230
0
    va_end(args);
5231
0
    fputs("\n", fp);
5232
0
    fflush(fp);
5233
0
    errno = error;
5234
0
  }
5235
5
}
5236
5237
0
HTSEXT_API const char* hts_version(void) {
5238
0
  return HTTRACK_VERSIONID;
5239
0
}
5240
5241
#if HTS_USEOPENSSL
5242
static int ssl_vulnerable(const char *version) {
5243
#ifdef _WIN32
5244
  static const char *const match = "OpenSSL 1.0.1";
5245
  const size_t match_len = strlen(match);
5246
  if (version != NULL && strncmp(version, match, match_len) == 0) {
5247
    // CVE-2014-0160
5248
    // "OpenSSL 1.0.1g 7 Apr 2014"
5249
    const char minor = version[match_len];
5250
    return minor == ' ' || ( minor >= 'a' && minor <= 'f' );
5251
  }
5252
#endif
5253
  return 0;
5254
}
5255
#endif
5256
5257
0
static void default_coucal_asserthandler(void *arg, const char* exp, const char* file, int line) {
5258
0
  abortf_(exp, file, line);
5259
0
}
5260
5261
0
static int get_loglevel_from_coucal(coucal_loglevel level) {
5262
0
  switch(level) {
5263
0
  case coucal_log_critical:
5264
0
    return LOG_PANIC;
5265
0
    break;
5266
0
  case coucal_log_warning:
5267
0
    return LOG_WARNING;
5268
0
    break;
5269
0
  case coucal_log_info:
5270
0
    return LOG_INFO;
5271
0
    break;
5272
0
  case coucal_log_debug:
5273
0
    return LOG_DEBUG;
5274
0
    break;
5275
0
  case coucal_log_trace:
5276
0
    return LOG_TRACE;
5277
0
    break;
5278
0
  default:
5279
0
    return LOG_ERROR;
5280
0
    break;
5281
0
  }
5282
0
}
5283
5284
/* log to default console */
5285
static HTS_PRINTF_FUN(3, 0) void default_coucal_loghandler(
5286
0
    void *arg, coucal_loglevel level, const char *format, va_list args) {
5287
5288
  /* informational chatter (hashtable stats on delete, etc.) only when
5289
     debugging; keep warnings and critical errors always visible. */
5290
0
  if (level > coucal_log_warning && hts_dgb_init <= 0) {
5291
0
    return;
5292
0
  }
5293
0
  if (level <= coucal_log_warning) {
5294
0
    fprintf(stderr, "** warning: ");
5295
0
  }
5296
0
  vfprintf(stderr, format, args);
5297
0
  fprintf(stderr, "\n");
5298
0
}
5299
5300
/* log to project log */
5301
static HTS_PRINTF_FUN(3, 0) void htsopt_coucal_loghandler(void *arg,
5302
                                                          coucal_loglevel level,
5303
                                                          const char *format,
5304
0
                                                          va_list args) {
5305
0
  httrackp *const opt = (httrackp*) arg;
5306
0
  if (opt != NULL && opt->log != NULL) {
5307
0
    hts_log_vprint(opt, get_loglevel_from_coucal(level), 
5308
0
      format, args);
5309
0
  } else {
5310
0
    default_coucal_loghandler(NULL, level, format, args);
5311
0
  }
5312
0
}
5313
5314
/* attach hashtable logger to project log */
5315
0
void hts_set_hash_handler(coucal hashtable, httrackp *opt) {
5316
  /* Init hashtable default assertion handler. */
5317
0
  coucal_set_assert_handler(hashtable,
5318
0
    htsopt_coucal_loghandler, 
5319
0
    default_coucal_asserthandler,
5320
0
    opt);
5321
0
}
5322
5323
static int hts_init_ok = 0;
5324
1
HTSEXT_API int hts_init(void) {
5325
1
  const char *dbg_env;
5326
5327
  /* */
5328
1
  if (hts_init_ok)
5329
0
    return 1;
5330
1
  hts_init_ok = 1;
5331
5332
  /* enable debugging ? */
5333
1
  dbg_env = getenv("HTS_LOG");
5334
1
  if (dbg_env != NULL && *dbg_env != 0) {
5335
0
    int level = 0;
5336
5337
0
    if (sscanf(dbg_env, "%d", &level) == 1) {
5338
0
      hts_debug(level);
5339
0
    }
5340
0
  }
5341
5342
1
  hts_debug_log_print("entering hts_init()");   /* debug */
5343
5344
  /* Init hashtable default assertion handler. */
5345
1
  coucal_set_global_assert_handler(default_coucal_loghandler, 
5346
1
    default_coucal_asserthandler);
5347
5348
  /* Init threads (lazy init) */
5349
1
  htsthread_init();
5350
5351
  /* Before any thread reads the verdict */
5352
1
  hts_mptcp_probe();
5353
1
  hts_psl_init();
5354
5355
  /* Ensure external modules are loaded */
5356
1
  hts_debug_log_print("calling htspe_init()");  /* debug */
5357
1
  htspe_init();                 /* module load (lazy) */
5358
5359
  /* MD5 Auto-test */
5360
1
  {
5361
1
    char digest[32 + 2];
5362
1
    const char *atest = "MD5 Checksum Autotest";
5363
5364
1
    digest[0] = '\0';
5365
1
    domd5mem(hts_span_of(atest), HTS_BUF(digest),
5366
1
             HTS_TRUE); /* a42ec44369da07ace5ec1d660ba4a69a */
5367
1
    if (strcmp(digest, "a42ec44369da07ace5ec1d660ba4a69a") != 0) {
5368
0
      int fatal_broken_md5 = 0;
5369
5370
0
      assertf(fatal_broken_md5);
5371
0
    }
5372
1
  }
5373
5374
0
  hts_debug_log_print("initializing SSL");      /* debug */
5375
#if HTS_USEOPENSSL
5376
  /*
5377
     Initialize the OpensSSL library
5378
   */
5379
  if (!openssl_ctx) {
5380
    const char *version;
5381
    const SSL_METHOD *method;
5382
5383
    /* OpenSSL >= 1.1.0 / LibreSSL >= 2.7.0 auto-init and provide the generic
5384
       methods. The legacy init and SSLv23/SSLeay calls (deprecated since 1.1.0,
5385
       likely gone in 4.0) are kept only for older OpenSSL. */
5386
#if OPENSSL_VERSION_NUMBER < 0x10100000L \
5387
  || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
5388
    SSL_load_error_strings();
5389
    SSL_library_init();
5390
    version = SSLeay_version(SSLEAY_VERSION);
5391
    method = SSLv23_client_method();
5392
#else
5393
    version = OpenSSL_version(OPENSSL_VERSION);
5394
    method = TLS_client_method();
5395
#endif
5396
5397
    // Check CVE-2014-0160.
5398
    if (ssl_vulnerable(version)) {
5399
      fprintf(stderr, "OpenSSL version == '%s'\n", version);
5400
      abortLog("unable to initialize TLS: OpenSSL version seems vulnerable to heartbleed bug (CVE-2014-0160)");
5401
      assertf("OpenSSL version seems vulnerable to heartbleed bug (CVE-2014-0160)" == NULL);
5402
    }
5403
5404
    openssl_ctx = SSL_CTX_new(method);
5405
    if (!openssl_ctx) {
5406
      fprintf(stderr, "fatal: unable to initialize TLS: SSL_CTX_new()\n");
5407
      abortLog("unable to initialize TLS: SSL_CTX_new()");
5408
      assertf("unable to initialize TLS" == NULL);
5409
    }
5410
    /* TLS floor (no SSLv3/TLS1.0/1.1); --check-cert verifies certs */
5411
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
5412
    SSL_CTX_set_min_proto_version(openssl_ctx, TLS1_2_VERSION);
5413
#else
5414
    SSL_CTX_set_options(openssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
5415
                                         SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
5416
#endif
5417
  }
5418
#endif
5419
5420
1
  hts_debug_log_print("ending hts_init()");     /* debug */
5421
1
  return 1;
5422
1
}
5423
5424
0
HTSEXT_API int hts_uninit(void) {
5425
0
  if (!hts_init_ok)
5426
0
    return 1;
5427
0
  htsthread_uninit();
5428
0
  hts_psl_uninit();
5429
0
  hts_init_ok = 0;
5430
0
  return 1;
5431
0
}
5432
5433
// legacy. do not use
5434
HTSEXT_API hts_boolean hts_log(httrackp *opt, const char *prefix,
5435
0
                               const char *msg) {
5436
0
  if (opt->log != NULL) {
5437
0
    fspc_count(opt, prefix);
5438
0
    fspc(opt->log, prefix);
5439
0
    fprintf(opt->log, "%s" LF, msg);
5440
0
    return 0;
5441
0
  }
5442
0
  return 1;                     /* Error */
5443
0
}
5444
5445
static void (*hts_log_print_callback)(httrackp * opt, int type, const char *format, va_list args) = NULL;
5446
5447
HTSEXT_API void hts_set_log_vprint_callback(void (*callback)(httrackp * opt,
5448
0
                                            int type, const char *format, va_list args)) {
5449
0
  hts_log_print_callback = callback;
5450
0
}
5451
5452
char hts_log_quiet_tag;
5453
5454
void hts_log_vprint(httrackp *opt, int type,
5455
10.1k
                    HTS_FORMAT_STRING const char *format, va_list args) {
5456
10.1k
  assertf(format != NULL);
5457
10.1k
  if (opt == HTS_LOG_QUIET)
5458
0
    return;
5459
10.1k
  if (hts_log_print_callback != NULL) {
5460
0
    va_list args_copy;
5461
0
    va_copy(args_copy, args);
5462
    /* the copy, so the vfprintf() below still has an unread list */
5463
0
    hts_log_print_callback(opt, type, format, args_copy);
5464
0
    va_end(args_copy);
5465
0
  }
5466
10.1k
  if (opt != NULL) {
5467
10.1k
    const int save_errno = errno;
5468
10.1k
    const char *s_type = "unknown";
5469
10.1k
    const int level = type & 0xff;
5470
5471
    // Check log level
5472
10.1k
    if ((int) opt->debug < level) {
5473
0
      return;
5474
0
    }
5475
5476
10.1k
    switch (level) {
5477
0
    case LOG_TRACE:
5478
0
      s_type = "trace";
5479
0
      break;
5480
0
    case LOG_DEBUG:
5481
0
      s_type = "debug";
5482
0
      break;
5483
0
    case LOG_INFO:
5484
0
    case LOG_NOTICE: /* not a warning: counted in the footer's messages */
5485
0
      s_type = "info";
5486
0
      break;
5487
10.1k
    case LOG_WARNING:
5488
10.1k
      s_type = "warning";
5489
10.1k
      break;
5490
0
    case LOG_ERROR:
5491
0
      s_type = "error";
5492
0
      break;
5493
0
    case LOG_PANIC:
5494
0
      s_type = "panic";
5495
0
      break;
5496
10.1k
    }
5497
    /* Count the event, not the line, so errors are reported with no log
5498
     * file (#1681). */
5499
10.1k
    fspc_count(opt, s_type);
5500
5501
10.1k
    if (opt->log != NULL) {
5502
0
      fspc(opt->log, s_type);
5503
0
      secret_vfprintf(opt, opt->log, format, args);
5504
0
      if ((type & LOG_ERRNO) != 0) {
5505
0
        char errbuf[HTS_STRERROR_SIZE];
5506
5507
0
        fprintf(opt->log, ": %s", hts_strerror(save_errno, HTS_BUF(errbuf)));
5508
0
      }
5509
0
      fputs(LF, opt->log);
5510
0
      if (opt->flush) {
5511
0
        fflush(opt->log);
5512
0
      }
5513
0
    }
5514
10.1k
    errno = save_errno;
5515
10.1k
  }
5516
10.1k
}
5517
5518
HTSEXT_API void hts_log_print(httrackp *opt, int type,
5519
10.1k
                              HTS_FORMAT_STRING const char *format, ...) {
5520
10.1k
  va_list args;
5521
10.1k
  assertf(format != NULL);
5522
10.1k
  va_start(args, format);
5523
10.1k
  hts_log_vprint(opt, type, format, args);
5524
10.1k
  va_end(args);
5525
10.1k
}
5526
5527
hts_boolean hts_libhandles_add(httrackp *opt, void *handle,
5528
0
                               const char *moduleName) {
5529
0
  char *name = strdupt(moduleName);
5530
0
  htslibhandle *grown;
5531
5532
0
  if (name == NULL)
5533
0
    return HTS_FALSE;
5534
0
  grown = (htslibhandle *) realloct(opt->libHandles.handles,
5535
0
                                    ((size_t) opt->libHandles.count + 1) *
5536
0
                                        sizeof(htslibhandle));
5537
0
  if (grown == NULL) {
5538
0
    freet(name);
5539
0
    return HTS_FALSE;
5540
0
  }
5541
0
  opt->libHandles.handles = grown;
5542
0
  grown[opt->libHandles.count].handle = handle;
5543
0
  grown[opt->libHandles.count].moduleName = name;
5544
0
  opt->libHandles.count++;
5545
0
  return HTS_TRUE;
5546
0
}
5547
5548
1
int plug_wrapper(httrackp *opt, const char *moduleName, const char *argv) {
5549
1
  void *handle = openFunctionLib(moduleName);
5550
5551
1
  if (handle != NULL) {
5552
0
    t_hts_plug plug = (t_hts_plug) getFunctionPtr(handle, "hts_plug");
5553
0
    t_hts_unplug unplug = (t_hts_unplug) getFunctionPtr(handle, "hts_unplug");
5554
5555
0
    if (plug != NULL) {
5556
0
      int ret = plug(opt, argv);
5557
5558
0
      if (hts_dgb_init > 0 && opt->log != NULL) {
5559
0
        hts_debug_log_print("plugged module '%s' (return code=%d)", moduleName,
5560
0
                            ret);
5561
0
      }
5562
0
      if (ret == 1) {           /* Success! */
5563
0
        if (hts_libhandles_add(opt, handle, moduleName))
5564
0
          return 1;
5565
0
        hts_debug_log_print("* note: out of memory registering %s", moduleName);
5566
0
        if (unplug)
5567
0
          unplug(opt);
5568
0
      } else {
5569
0
        hts_debug_log_print
5570
0
          ("* note: error while running entry point 'hts_plug' in %s",
5571
0
           moduleName);
5572
0
        if (unplug)
5573
0
          unplug(opt);
5574
0
      }
5575
0
    } else {
5576
0
      const int last_errno = errno;
5577
0
      char errbuf[HTS_STRERROR_SIZE];
5578
5579
0
      hts_debug_log_print("* note: can't find entry point 'hts_plug' in %s: %s",
5580
0
                          moduleName,
5581
0
                          hts_strerror(last_errno, HTS_BUF(errbuf)));
5582
0
    }
5583
0
    closeFunctionLib(handle);
5584
0
    return 0;
5585
1
  } else {
5586
1
    const int last_errno = errno;
5587
1
    char errbuf[HTS_STRERROR_SIZE];
5588
5589
1
    hts_debug_log_print("* note: can't load %s: %s", moduleName,
5590
1
                        hts_strerror(last_errno, HTS_BUF(errbuf)));
5591
1
  }
5592
1
  return -1;
5593
1
}
5594
5595
0
static void unplug_wrappers(httrackp * opt) {
5596
0
  if (opt->libHandles.handles != NULL) {
5597
0
    int i;
5598
5599
0
    for(i = 0; i < opt->libHandles.count; i++) {
5600
0
      if (opt->libHandles.handles[i].handle != NULL) {
5601
        /* hts_unplug(), the dll exit point (finalizer) */
5602
0
        t_hts_unplug unplug =
5603
0
          (t_hts_unplug) getFunctionPtr(opt->libHandles.handles[i].handle,
5604
0
                                        "hts_unplug");
5605
0
        if (unplug != NULL)
5606
0
          unplug(opt);
5607
0
        closeFunctionLib(opt->libHandles.handles[i].handle);
5608
0
        opt->libHandles.handles[i].handle = NULL;
5609
0
      }
5610
0
      if (opt->libHandles.handles[i].moduleName != NULL) {
5611
0
        freet(opt->libHandles.handles[i].moduleName);
5612
0
        opt->libHandles.handles[i].moduleName = NULL;
5613
0
      }
5614
0
    }
5615
0
    freet(opt->libHandles.handles);
5616
0
    opt->libHandles.handles = NULL;
5617
0
    opt->libHandles.count = 0;
5618
0
  }
5619
0
}
5620
5621
1
HTSEXT_API httrackp *hts_create_opt(void) {
5622
1
  static const char *const defaultModules[] = {"httrack-plugin", NULL};
5623
1
  httrackp *opt = malloct(sizeof(httrackp));
5624
5625
  /* default options */
5626
1
  memset(opt, 0, sizeof(httrackp));
5627
1
  opt->size_httrackp = sizeof(httrackp);
5628
5629
  /* mutexes */
5630
1
  hts_mutexinit(&opt->state.lock);
5631
1
  hts_secret_init(opt);
5632
5633
  /* custom wrappers */
5634
1
  opt->libHandles.count = 0;
5635
5636
  /* default settings */
5637
5638
1
  opt->wizard = HTS_WIZARD_AUTO; // wizard automatique
5639
1
  opt->quiet = HTS_FALSE;
5640
  //
5641
1
  opt->travel = HTS_TRAVEL_SAME_ADDRESS; // même adresse
5642
1
  opt->depth = 9999;            // mirror total par défaut
5643
1
  opt->extdepth = 0;            // mais pas à l'extérieur
5644
1
  opt->seeker = HTS_SEEKER_DOWN;       // down
5645
1
  opt->urlmode = HTS_URLMODE_RELATIVE; // relatif par défaut
5646
1
  opt->no_type_change = HTS_FALSE;
5647
1
  opt->debug = LOG_NOTICE;      // small log
5648
1
  opt->getmode = HTS_GETMODE_HTML | HTS_GETMODE_NONHTML;
5649
1
  opt->maxsite = -1;            // taille max site (aucune)
5650
1
  opt->maxfile_nonhtml = -1;    // taille max fichier non html
5651
1
  opt->maxfile_html = -1;       // idem pour html
5652
1
  opt->maxsoc = 4;              // nbre socket max
5653
1
  opt->fragment = -1;           // pas de fragmentation
5654
1
  opt->nearlink = HTS_FALSE;
5655
1
  opt->makeindex = HTS_TRUE;
5656
1
  opt->kindex = HTS_KINDEX_OFF;
5657
1
  opt->delete_old = HTS_TRUE;
5658
1
  opt->background_on_suspend = HTS_TRUE;
5659
1
  opt->makestat = HTS_FALSE;
5660
1
  opt->maketrack = HTS_FALSE;
5661
1
  opt->timeout = 120;           // timeout par défaut (2 minutes)
5662
1
  opt->cache = HTS_CACHE_PRIORITY; // cache prioritaire
5663
1
  opt->shell = HTS_FALSE;
5664
1
  opt->proxy.active = 0;        // pas de proxy
5665
1
  opt->user_agent_send = HTS_TRUE;
5666
1
  StringCopy(opt->user_agent, HTS_DEFAULT_USER_AGENT);
5667
1
  StringCopy(opt->referer, "");
5668
1
  StringCopy(opt->from, "");
5669
1
  opt->savename_83 = HTS_SAVENAME_83_LONG; // long names by default
5670
1
  opt->savename_type = 0;       // avec structure originale
5671
1
  opt->savename_delayed =
5672
1
      HTS_SAVENAME_DELAYED_HARD; // always delay the type check (default)
5673
1
  opt->delayed_cached = HTS_TRUE;
5674
1
  opt->mimehtml = HTS_FALSE;
5675
1
  opt->parsejava = HTSPARSE_DEFAULT;    // parser classes
5676
1
  opt->hostcontrol = 0;         // PAS de control host pour timeout et traffic jammer
5677
1
  opt->retry = 2;               // 2 retry par défaut
5678
1
  opt->errpage = HTS_TRUE;
5679
  // d'erreur (404 etc.)
5680
1
  opt->check_type = HTS_TRUE;
5681
  // considéré comme html
5682
1
  opt->all_in_cache = HTS_FALSE;
5683
1
  opt->robots = HTS_ROBOTS_ALWAYS; // traiter les robots.txt
5684
1
  opt->external = HTS_FALSE;
5685
1
  opt->passprivacy = HTS_FALSE;
5686
1
  opt->includequery = HTS_TRUE;
5687
1
  opt->mirror_first_page = HTS_FALSE;
5688
1
  opt->accept_cookie = HTS_TRUE;
5689
1
  opt->cookie = NULL;
5690
1
  opt->http10 = HTS_FALSE;
5691
1
  opt->nokeepalive = HTS_FALSE;
5692
1
  opt->nocompression = HTS_FALSE;
5693
1
  opt->tolerant = HTS_FALSE;
5694
1
  opt->parseall = HTS_TRUE;
5695
1
  opt->parsedebug = HTS_FALSE;
5696
1
  opt->norecatch = HTS_FALSE;
5697
1
  opt->verbosedisplay = HTS_VERBOSE_NONE; // no text animation
5698
1
  opt->sizehack = HTS_FALSE;
5699
1
  opt->urlhack = HTS_TRUE;
5700
1
  opt->no_www_dedup = HTS_FALSE;
5701
1
  opt->no_slash_dedup = HTS_FALSE;
5702
1
  opt->no_query_dedup = HTS_FALSE;
5703
1
  StringCopy(opt->footer, HTS_DEFAULT_FOOTER);
5704
1
  StringCopy(opt->strip_query, "");
5705
1
  StringCopy(opt->host_alias, "");
5706
1
  StringCopy(opt->cookies_file, "");
5707
1
  StringCopy(opt->warc_file, "");
5708
1
  StringCopy(opt->sitemap_url, "");
5709
1
  opt->warc_max_size = 0; /* no rotation unless --warc-max-size sets it */
5710
1
  opt->changes = HTS_FALSE;
5711
1
  opt->changes_state = NULL;
5712
1
  opt->single_file = HTS_FALSE;
5713
1
  opt->single_file_max_size = SINGLEFILE_DEFAULT_MAX_SIZE;
5714
1
  opt->singlefile_state = NULL;
5715
1
  opt->links_unqueued = HTS_FALSE;
5716
1
  opt->mirror_completed = HTS_DEFAULT;
5717
1
  opt->transport_failures = 0;
5718
1
  opt->mptcp = HTS_DEFAULT;
5719
1
  opt->browser_headers = HTS_DEFAULT;
5720
1
  opt->check_cert = HTS_DEFAULT;
5721
1
  opt->mptcp_connections = 0;
5722
1
  opt->mptcp_fallbacks = 0;
5723
1
  opt->upper_links_refused = HTS_FALSE;
5724
1
  opt->abort_left_partial = HTS_FALSE;
5725
1
  StringCopy(opt->why_url, "");
5726
1
  opt->pause_min_ms = 0;
5727
1
  opt->pause_max_ms = 0;
5728
1
  opt->max_retry_after = HTS_DEFAULT_MAX_RETRY_AFTER;
5729
1
  opt->ftp_proxy = HTS_TRUE;
5730
1
  opt->convert_utf8 = HTS_TRUE;
5731
1
  StringCopy(opt->filelist, "");
5732
1
  StringCopy(opt->lang_iso, HTS_ACCEPT_LANGUAGE_LEGACY);
5733
1
  StringCopy(opt->accept, HTS_ACCEPT_LEGACY);
5734
1
  StringCopy(opt->accept_kinds, "");
5735
1
  opt->accept_given = HTS_FALSE;
5736
1
  opt->lang_given = HTS_FALSE;
5737
1
  StringCopy(opt->bundle_dir, "");
5738
1
  opt->bundle_state = NULL;
5739
1
  StringCopy(opt->headers, "");
5740
1
  StringCopy(opt->mimedefs, "\n");      // aucun filtre mime (\n IMPORTANT)
5741
1
  StringClear(opt->mod_blacklist);
5742
  //
5743
1
  opt->log = stdout;
5744
1
  opt->errlog = stderr;
5745
1
  opt->flush = HTS_TRUE;
5746
1
  opt->keyboard = HTS_FALSE;
5747
  //
5748
1
  StringCopy(opt->path_html, "");
5749
1
  StringCopy(opt->path_html_utf8, "");
5750
1
  StringCopy(opt->path_log, "");
5751
1
  StringCopy(opt->path_bin, "");
5752
  //
5753
1
  opt->maxlink = 100000;        // 100,000 liens max par défaut
5754
1
  opt->maxfilter = 200;         // 200 filtres max par défaut
5755
1
  opt->maxcache = 1048576 * 32; // a peu près 32Mo en cache max -- OPTION NON
5756
                                // PARAMETRABLE POUR L'INSTANT --
5757
1
  opt->maxtime = -1;            // temps max en secondes
5758
1
  opt->maxrate = 100000;        // taux maxi
5759
1
  opt->maxconn = 5.0;           // nombre connexions/s
5760
1
  opt->waittime = -1;           // wait until.. hh*3600+mm*60+ss
5761
  //
5762
1
  opt->exec = "";
5763
1
  opt->is_update = HTS_FALSE;
5764
1
  opt->dir_topindex = HTS_FALSE;
5765
  //
5766
1
  opt->bypass_limits = HTS_FALSE;
5767
1
  hts_store_release_int(&opt->state.stop, 0);
5768
1
  hts_store_release_int(&opt->state.exit_xh, 0);
5769
  //
5770
1
  opt->state.is_ended = 0;
5771
5772
  /* Alocated buffers */
5773
5774
1
  opt->callbacks_fun =
5775
1
    (t_hts_htmlcheck_callbacks *) malloct(sizeof(t_hts_htmlcheck_callbacks));
5776
  /* A plug-in that chains to an empty slot gets the engine default as prev. */
5777
1
  *opt->callbacks_fun = default_callbacks;
5778
5779
  /* Preload callbacks : java and flash parser, and the automatic user-defined callback */
5780
5781
1
  {
5782
1
    int i;
5783
5784
2
    for(i = 0; defaultModules[i] != NULL; i++) {
5785
1
      int ret = plug_wrapper(opt, defaultModules[i], defaultModules[i]);
5786
5787
1
      if (ret == 0) {           /* Module aborted initialization */
5788
        /* Ignored. */
5789
0
      }
5790
1
    }
5791
1
  }
5792
5793
1
  return opt;
5794
1
}
5795
5796
0
HTSEXT_API size_t hts_sizeof_opt(void) {
5797
0
  return sizeof(httrackp);
5798
0
}
5799
5800
/* The runtime assert below cannot see a same-sized non-callback member. */
5801
HTS_STATIC_ASSERT(offsetof(t_hts_htmlcheck_callbacks, extsavename) +
5802
                          sizeof(t_hts_htmlcheck_callbacks_item) ==
5803
                      sizeof(t_hts_htmlcheck_callbacks),
5804
                  callbacks_are_a_flat_slot_array);
5805
5806
0
HTSEXT_API void hts_free_opt(httrackp * opt) {
5807
0
  if (opt != NULL) {
5808
    /* An FTP worker reads opt for its whole run, and not every caller drains
5809
       its threads the way httrack.c does before getting here. */
5810
0
    ftp_stop_workers();
5811
0
    hts_bundle_free(opt);
5812
5813
    /* Alocated callbacks */
5814
5815
0
    if (opt->callbacks_fun != NULL) {
5816
0
      int i;
5817
0
      t_hts_htmlcheck_callbacks_item *items =
5818
0
        (t_hts_htmlcheck_callbacks_item *) opt->callbacks_fun;
5819
0
      const int size =
5820
0
        (int) sizeof(t_hts_htmlcheck_callbacks) /
5821
0
        sizeof(t_hts_htmlcheck_callbacks_item);
5822
0
      assertf(sizeof(t_hts_htmlcheck_callbacks_item) * size ==
5823
0
              sizeof(t_hts_htmlcheck_callbacks));
5824
5825
      /* Free all linked lists */
5826
0
      for(i = 0; i < size; i++) {
5827
0
        t_hts_callbackarg *carg, *next_carg;
5828
5829
0
        for(carg = items[i].carg;
5830
0
            carg != NULL && (next_carg = carg->prev.carg, carg != NULL);
5831
0
            carg = next_carg) {
5832
0
          hts_free(carg);
5833
0
        }
5834
0
      }
5835
5836
0
      freet(opt->callbacks_fun);
5837
0
      opt->callbacks_fun = NULL;
5838
0
    }
5839
5840
    /* Close library handles */
5841
0
    unplug_wrappers(opt);
5842
5843
    /* Cache */
5844
0
    if (opt->state.dns_cache != NULL) {
5845
0
      coucal root;
5846
5847
0
      hts_mutexlock(&opt->state.lock);
5848
0
      root = opt->state.dns_cache;
5849
0
      opt->state.dns_cache = NULL;
5850
0
      hts_mutexrelease(&opt->state.lock);
5851
5852
0
      coucal_delete(&root); // frees records via hts_cache_value_free
5853
0
    }
5854
5855
    /* URLs a front end queued but the engine never got to inject */
5856
0
    hts_addurl_free(hts_addurl_take(opt));
5857
0
    hts_addurl_free(hts_addfilter_take(opt));
5858
0
    hts_addurl_free(hts_setfilters_take(opt));
5859
5860
    /* Cancel chain */
5861
0
    if (opt->state.cancel != NULL) {
5862
0
      htsoptstatecancel *cancel;
5863
5864
0
      for(cancel = opt->state.cancel; cancel != NULL;) {
5865
0
        htsoptstatecancel *next = cancel->next;
5866
5867
0
        if (cancel->url != NULL) {
5868
0
          freet(cancel->url);
5869
0
        }
5870
0
        freet(cancel);
5871
0
        cancel = next;
5872
0
      }
5873
0
      opt->state.cancel = NULL;
5874
0
    }
5875
5876
    /* Free strings */
5877
5878
0
    StringFree(opt->proxy.name);
5879
0
    StringFree(opt->proxy.bindhost);
5880
5881
0
    StringFree(opt->savename_userdef);
5882
0
    StringFree(opt->user_agent);
5883
0
    StringFree(opt->referer);
5884
0
    StringFree(opt->from);
5885
0
    StringFree(opt->lang_iso);
5886
0
    StringFree(opt->accept);
5887
0
    StringFree(opt->accept_kinds);
5888
0
    StringFree(opt->bundle_dir);
5889
0
    StringFree(opt->headers);
5890
0
    StringFree(opt->sys_com);
5891
0
    StringFree(opt->mimedefs);
5892
0
    StringFree(opt->filelist);
5893
0
    StringFree(opt->urllist);
5894
0
    StringFree(opt->footer);
5895
0
    StringFree(opt->mod_blacklist);
5896
0
    StringFree(opt->strip_query);
5897
0
    StringFree(opt->host_alias);
5898
0
    StringFree(opt->cookies_file);
5899
0
    StringFree(opt->why_url);
5900
0
    StringFree(opt->warc_file);
5901
0
    StringFree(opt->sitemap_url);
5902
0
    StringFree(opt->state.mimemid);
5903
0
    hts_sitemap_free(opt); /* backstop: httpmirror's early-return paths */
5904
0
    url_savename_refnames_free(opt);
5905
0
    singlefile_free(opt);
5906
5907
0
    hts_changes_free_opt(opt);
5908
5909
0
    StringFree(opt->path_html);
5910
0
    StringFree(opt->path_html_utf8);
5911
0
    StringFree(opt->path_log);
5912
0
    StringFree(opt->path_bin);
5913
5914
    /* mutexes */
5915
0
    hts_secret_free(opt);
5916
0
    hts_mutexfree(&opt->state.lock);
5917
5918
    /* Free structure */
5919
0
    freet(opt);
5920
0
  }
5921
0
}
5922
5923
// TEMPORARY - PUT THIS STRUCTURE INSIDE httrackp !
5924
0
const hts_stat_struct* hts_get_stats(httrackp * opt) {
5925
0
  if (opt == NULL) {
5926
0
    return NULL;
5927
0
  }
5928
5929
0
  hts_stat_recv_publish();
5930
0
  HTS_STAT.stat_nsocket = 0;
5931
0
  HTS_STAT.stat_errors = fspc_get(opt, "error");
5932
0
  HTS_STAT.stat_warnings = fspc_get(opt, "warning");
5933
0
  HTS_STAT.stat_infos = fspc_get(opt, "info");
5934
0
  HTS_STAT.stat_transport_failures = opt->transport_failures;
5935
0
  HTS_STAT.stat_mptcp_connections = opt->mptcp_connections;
5936
0
  HTS_STAT.stat_mptcp_fallbacks = opt->mptcp_fallbacks;
5937
0
  HTS_STAT.nbk = 0;
5938
0
  HTS_STAT.nb = 0;
5939
5940
0
  return &HTS_STAT;
5941
0
}
5942
5943
// defaut wrappers
5944
0
static void __cdecl htsdefault_init(t_hts_callbackarg *carg) {}
5945
5946
0
static void __cdecl htsdefault_uninit(t_hts_callbackarg *carg) {}
5947
0
static int __cdecl htsdefault_start(t_hts_callbackarg * carg, httrackp * opt) {
5948
0
  return 1;
5949
0
}
5950
0
static int __cdecl htsdefault_chopt(t_hts_callbackarg * carg, httrackp * opt) {
5951
0
  return 1;
5952
0
}
5953
0
static int __cdecl htsdefault_end(t_hts_callbackarg * carg, httrackp * opt) {
5954
0
  return 1;
5955
0
}
5956
static int __cdecl htsdefault_preprocesshtml(t_hts_callbackarg * carg,
5957
                                             httrackp * opt, char **html,
5958
                                             int *len, const char *url_adresse,
5959
0
                                             const char *url_fichier) {
5960
0
  return 1;
5961
0
}
5962
static int __cdecl htsdefault_postprocesshtml(t_hts_callbackarg * carg,
5963
                                              httrackp * opt, char **html,
5964
                                              int *len, const char *url_adresse,
5965
0
                                              const char *url_fichier) {
5966
0
  return 1;
5967
0
}
5968
static int __cdecl htsdefault_checkhtml(t_hts_callbackarg * carg,
5969
                                        httrackp * opt, char *html, int len,
5970
                                        const char *url_adresse,
5971
0
                                        const char *url_fichier) {
5972
0
  return 1;
5973
0
}
5974
0
static int __cdecl htsdefault_loop(t_hts_callbackarg * carg, httrackp * opt, lien_back * back, int back_max, int back_index, int lien_n, int lien_tot, int stat_time, hts_stat_struct * stats) {        // appelé à chaque boucle de HTTrack
5975
0
  return 1;
5976
0
}
5977
static const char *__cdecl htsdefault_query(t_hts_callbackarg * carg,
5978
                                            httrackp * opt,
5979
0
                                            const char *question) {
5980
0
  return "";
5981
0
}
5982
static const char *__cdecl htsdefault_query2(t_hts_callbackarg * carg,
5983
                                             httrackp * opt,
5984
0
                                             const char *question) {
5985
0
  return "";
5986
0
}
5987
static const char *__cdecl htsdefault_query3(t_hts_callbackarg * carg,
5988
                                             httrackp * opt,
5989
0
                                             const char *question) {
5990
0
  return "";
5991
0
}
5992
static int __cdecl htsdefault_check(t_hts_callbackarg * carg, httrackp * opt,
5993
                                    const char *adr, const char *fil,
5994
0
                                    int status) {
5995
0
  return -1;
5996
0
}
5997
static int __cdecl htsdefault_check_mime(t_hts_callbackarg * carg,
5998
                                         httrackp * opt, const char *adr,
5999
                                         const char *fil, const char *mime,
6000
0
                                         int status) {
6001
0
  return -1;
6002
0
}
6003
static void __cdecl htsdefault_pause(t_hts_callbackarg * carg, httrackp * opt,
6004
0
                                     const char *lockfile) {
6005
0
  String abortlock = STRING_EMPTY, progress = STRING_EMPTY;
6006
6007
  /* Strings, because lockfile already holds a rotating OPT_GET_BUFF. */
6008
0
  StringCopy(abortlock, StringBuff(opt->path_log));
6009
0
  StringCat(abortlock, HTS_ABORT_LOCKNAME);
6010
0
  StringCopy(progress, StringBuff(opt->path_log));
6011
0
  StringCat(progress, "hts-in_progress.lock");
6012
  /* A stop, an exit or an abort request aimed at this run ends the wait. */
6013
0
  while (fexist_utf8(lockfile) && !hts_run_is_ending(opt) &&
6014
0
         !hts_file_is_newer(StringBuff(abortlock), StringBuff(progress))) {
6015
0
    Sleep(1000);
6016
0
  }
6017
0
  StringFree(progress);
6018
0
  StringFree(abortlock);
6019
0
}
6020
static void __cdecl htsdefault_filesave(t_hts_callbackarg * carg,
6021
0
                                        httrackp * opt, const char *file) {
6022
0
}
6023
static void __cdecl htsdefault_filesave2(t_hts_callbackarg * carg,
6024
                                         httrackp * opt, const char *adr,
6025
                                         const char *file, const char *sav,
6026
                                         int is_new, int is_modified,
6027
0
                                         int not_updated) {
6028
0
}
6029
static int __cdecl htsdefault_linkdetected(t_hts_callbackarg * carg,
6030
0
                                           httrackp * opt, char *link) {
6031
0
  return 1;
6032
0
}
6033
static int __cdecl htsdefault_linkdetected2(t_hts_callbackarg * carg,
6034
                                            httrackp * opt, char *link,
6035
0
                                            const char *start_tag) {
6036
0
  return 1;
6037
0
}
6038
static int __cdecl htsdefault_xfrstatus(t_hts_callbackarg * carg,
6039
0
                                        httrackp * opt, lien_back * back) {
6040
0
  return 1;
6041
0
}
6042
static int __cdecl htsdefault_savename(t_hts_callbackarg * carg, httrackp * opt,
6043
                                       const char *adr_complete,
6044
                                       const char *fil_complete,
6045
                                       const char *referer_adr,
6046
0
                                       const char *referer_fil, char *save) {
6047
0
  return 1;
6048
0
}
6049
static int __cdecl htsdefault_sendhead(t_hts_callbackarg * carg, httrackp * opt,
6050
                                       char *buff, const char *adr,
6051
                                       const char *fil, const char *referer_adr,
6052
                                       const char *referer_fil,
6053
0
                                       htsblk * outgoing) {
6054
0
  return 1;
6055
0
}
6056
static int __cdecl htsdefault_receivehead(t_hts_callbackarg * carg,
6057
                                          httrackp * opt, char *buff,
6058
                                          const char *adr, const char *fil,
6059
                                          const char *referer_adr,
6060
                                          const char *referer_fil,
6061
0
                                          htsblk * incoming) {
6062
0
  return 1;
6063
0
}
6064
static int __cdecl htsdefault_detect(t_hts_callbackarg * carg, httrackp * opt,
6065
0
                                     htsmoduleStruct * str) {
6066
0
  return 0;
6067
0
}
6068
static int __cdecl htsdefault_parse(t_hts_callbackarg * carg, httrackp * opt,
6069
0
                                    htsmoduleStruct * str) {
6070
0
  return 0;
6071
0
}
6072
6073
/* Default internal dummy callbacks */
6074
const t_hts_htmlcheck_callbacks default_callbacks = {
6075
  {htsdefault_init, NULL},
6076
  {htsdefault_uninit, NULL},
6077
  {htsdefault_start, NULL},
6078
  {htsdefault_end, NULL},
6079
  {htsdefault_chopt, NULL},
6080
  {htsdefault_preprocesshtml, NULL},
6081
  {htsdefault_postprocesshtml, NULL},
6082
  {htsdefault_checkhtml, NULL},
6083
  {htsdefault_query, NULL},
6084
  {htsdefault_query2, NULL},
6085
  {htsdefault_query3, NULL},
6086
  {htsdefault_loop, NULL},
6087
  {htsdefault_check, NULL},
6088
  {htsdefault_check_mime, NULL},
6089
  {htsdefault_pause, NULL},
6090
  {htsdefault_filesave, NULL},
6091
  {htsdefault_filesave2, NULL},
6092
  {htsdefault_linkdetected, NULL},
6093
  {htsdefault_linkdetected2, NULL},
6094
  {htsdefault_xfrstatus, NULL},
6095
  {htsdefault_savename, NULL},
6096
  {htsdefault_sendhead, NULL},
6097
  {htsdefault_receivehead, NULL},
6098
  {htsdefault_detect, NULL},
6099
  {htsdefault_parse, NULL}
6100
};
6101
6102
/* Each named slot has the string name htsdefines.h gives it. */
6103
static const struct {
6104
  const char *name;
6105
  size_t offset;
6106
} callback_names[] = {
6107
    {"init", offsetof(t_hts_htmlcheck_callbacks, init)},
6108
    {"free", offsetof(t_hts_htmlcheck_callbacks, uninit)},
6109
    {"start", offsetof(t_hts_htmlcheck_callbacks, start)},
6110
    {"end", offsetof(t_hts_htmlcheck_callbacks, end)},
6111
    {"change-options", offsetof(t_hts_htmlcheck_callbacks, chopt)},
6112
    {"preprocess-html", offsetof(t_hts_htmlcheck_callbacks, preprocess)},
6113
    {"postprocess-html", offsetof(t_hts_htmlcheck_callbacks, postprocess)},
6114
    {"check-html", offsetof(t_hts_htmlcheck_callbacks, check_html)},
6115
    {"query", offsetof(t_hts_htmlcheck_callbacks, query)},
6116
    {"query2", offsetof(t_hts_htmlcheck_callbacks, query2)},
6117
    {"query3", offsetof(t_hts_htmlcheck_callbacks, query3)},
6118
    {"loop", offsetof(t_hts_htmlcheck_callbacks, loop)},
6119
    {"check-link", offsetof(t_hts_htmlcheck_callbacks, check_link)},
6120
    {"check-mime", offsetof(t_hts_htmlcheck_callbacks, check_mime)},
6121
    {"pause", offsetof(t_hts_htmlcheck_callbacks, pause)},
6122
    {"save-file", offsetof(t_hts_htmlcheck_callbacks, filesave)},
6123
    {"save-file2", offsetof(t_hts_htmlcheck_callbacks, filesave2)},
6124
    {"link-detected", offsetof(t_hts_htmlcheck_callbacks, linkdetected)},
6125
    {"link-detected2", offsetof(t_hts_htmlcheck_callbacks, linkdetected2)},
6126
    {"transfer-status", offsetof(t_hts_htmlcheck_callbacks, xfrstatus)},
6127
    {"save-name", offsetof(t_hts_htmlcheck_callbacks, savename)},
6128
    {"send-header", offsetof(t_hts_htmlcheck_callbacks, sendhead)},
6129
    {"receive-header", offsetof(t_hts_htmlcheck_callbacks, receivehead)}};
6130
6131
/* Returns the byte offset of NAME's function pointer, or -1 if no slot has
6132
   that name. Callers memcpy through it, because each slot has its own type. */
6133
0
static ptrdiff_t callback_offset(const char *name) {
6134
0
  size_t i;
6135
6136
0
  for (i = 0; i < sizeof(callback_names) / sizeof(callback_names[0]); i++)
6137
0
    if (strcmp(name, callback_names[i].name) == 0)
6138
0
      return (ptrdiff_t) (callback_names[i].offset +
6139
0
                          offsetof(t_hts_htmlcheck_callbacks_item, fun));
6140
0
  return -1;
6141
0
}
6142
6143
static void *callback_slot(const t_hts_htmlcheck_callbacks *callbacks,
6144
0
                           const char *name) {
6145
0
  const ptrdiff_t off = callback_offset(name);
6146
0
  void *fun = NULL;
6147
6148
0
  if (off >= 0)
6149
0
    memcpy(&fun, (const char *) callbacks + off, sizeof(fun));
6150
0
  return fun;
6151
0
}
6152
6153
int hts_set_callback(t_hts_htmlcheck_callbacks * callbacks, const char *name,
6154
0
                     void *function) {
6155
0
  const ptrdiff_t off = callback_offset(name);
6156
6157
  /* NULL restores the engine default, so a later chain never gets a NULL prev.
6158
   */
6159
0
  if (function == NULL)
6160
0
    function = callback_slot(&default_callbacks, name);
6161
0
  if (off >= 0)
6162
0
    memcpy((char *) callbacks + off, &function, sizeof(function));
6163
0
  return off < 0;
6164
0
}
6165
6166
0
void *hts_get_callback(t_hts_htmlcheck_callbacks *callbacks, const char *name) {
6167
0
  void *const fun = callback_slot(callbacks, name);
6168
6169
  /* An engine default reads as no callback. */
6170
0
  return fun != callback_slot(&default_callbacks, name) ? fun : NULL;
6171
0
}
6172
6173
// end defaut wrappers
6174
6175
/* libc stubs */
6176
6177
0
HTSEXT_API char *hts_strdup(const char *str) {
6178
0
  return strdup(str); /* libc on purpose */
6179
0
}
6180
6181
0
HTSEXT_API void *hts_malloc(size_t size) {
6182
0
  return malloc(size); /* libc on purpose */
6183
0
}
6184
6185
0
HTSEXT_API void *hts_realloc(void *const data, const size_t size) {
6186
0
  return realloc(data, size); /* libc on purpose */
6187
0
}
6188
6189
0
HTSEXT_API void hts_free(void *data) { free(data); /* libc on purpose */ }
6190
6191
/* Dummy functions */
6192
0
HTSEXT_API int hts_resetvar(void) {
6193
0
  return 0;
6194
0
}
6195
6196
#ifdef _WIN32
6197
6198
typedef struct dirent dirent;
6199
6200
DIR *opendir(const char *name) {
6201
  WIN32_FILE_ATTRIBUTE_DATA st;
6202
  DIR *dir;
6203
  size_t size;
6204
  int i;
6205
  LPWSTR wname;
6206
6207
  if (name == NULL || *name == '\0') {
6208
    errno = ENOENT;
6209
    return NULL;
6210
  }
6211
  // Wide \\?\ path: no MAX_PATH cap, no CP_ACP mis-decode (#133,#630).
6212
  wname = hts_pathToUCS2(name);
6213
  if (wname == NULL ||
6214
      !GetFileAttributesExW(wname, GetFileExInfoStandard, &st) ||
6215
      (st.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
6216
    freet(wname);
6217
    errno = ENOENT;
6218
    return NULL;
6219
  }
6220
  freet(wname);
6221
  dir = calloct(1, sizeof(DIR));
6222
  if (dir == NULL) {
6223
    errno = ENOMEM;
6224
    return NULL;
6225
  }
6226
  size = strlen(name) + 3; /* the name, "\\*" and the NUL */
6227
  dir->h = INVALID_HANDLE_VALUE;
6228
  dir->name = malloct(size);
6229
  strlcpybuff(dir->name, name, size);
6230
  for(i = 0; dir->name[i] != '\0'; i++) {
6231
    if (dir->name[i] == '/') {
6232
      dir->name[i] = '\\';
6233
    }
6234
  }
6235
  strlcatbuff(dir->name, "\\*", size);
6236
  return dir;
6237
}
6238
6239
struct dirent *readdir(DIR * dir) {
6240
  WIN32_FIND_DATAW find;
6241
6242
  if (dir->h == INVALID_HANDLE_VALUE) {
6243
    // \\?\-prefix so a long/non-ASCII directory enumerates instead of ENOENT.
6244
    LPWSTR wname = hts_pathToUCS2(dir->name);
6245
6246
    dir->h =
6247
        wname != NULL ? FindFirstFileW(wname, &find) : INVALID_HANDLE_VALUE;
6248
    freet(wname);
6249
  } else {
6250
    if (!FindNextFileW(dir->h, &find)) {
6251
      FindClose(dir->h);
6252
      dir->h = INVALID_HANDLE_VALUE;
6253
    }
6254
  }
6255
  if (dir->h != INVALID_HANDLE_VALUE) {
6256
    char *u = hts_convertUCS2StringToUTF8(find.cFileName, -1);
6257
6258
    dir->entry.d_name[0] = 0;
6259
    if (u != NULL) {
6260
      (void) hts_buf_cpy_clip(HTS_BUF(dir->entry.d_name), u);
6261
      freet(u);
6262
    }
6263
    return &dir->entry;
6264
  }
6265
  errno = ENOENT;
6266
  return NULL;
6267
}
6268
6269
int closedir(DIR * dir) {
6270
  if (dir != NULL) {
6271
    if (dir->h != INVALID_HANDLE_VALUE) {
6272
      CloseHandle(dir->h);
6273
    }
6274
    freet(dir->name);
6275
    freet(dir);
6276
    return 0;
6277
  }
6278
  errno = EBADF;
6279
  return -1;
6280
}
6281
6282
// UTF-8 aware FILE API
6283
6284
static void copyWchar(LPWSTR dest, const char *src) {
6285
  int i;
6286
6287
  for(i = 0; src[i]; i++) {
6288
    dest[i] = src[i];
6289
  }
6290
  dest[i] = '\0';
6291
}
6292
6293
/* UTF-8 path -> UCS-2 for the _w* file APIs. At/above HTS_WIN_LONGPATH_MIN,
6294
   \\?\-prefix it via GetFullPathNameW to clear MAX_PATH (#133); else unchanged.
6295
   Any prefixing failure falls back to the plain converted path. */
6296
#define HTS_WIN_LONGPATH_MIN 240 /* stay clear of MAX_PATH (260) */
6297
6298
LPWSTR hts_pathToUCS2(const char *path) {
6299
  LPWSTR wpath = hts_convertUTF8StringToUCS2(hts_span_of(path), NULL);
6300
6301
  if (wpath == NULL) {
6302
    return NULL;
6303
  }
6304
  const size_t len = wcslen(wpath);
6305
  // Already "\\?\" or "\\.\": don't re-prefix.
6306
  const int verbatim = len >= 4 && wpath[0] == L'\\' && wpath[1] == L'\\' &&
6307
                       (wpath[2] == L'?' || wpath[2] == L'.') &&
6308
                       wpath[3] == L'\\';
6309
6310
  if (len < HTS_WIN_LONGPATH_MIN || verbatim) {
6311
    return wpath;
6312
  }
6313
6314
  const DWORD need = GetFullPathNameW(wpath, 0, NULL, NULL); /* incl NUL */
6315
  LPWSTR full = need != 0 ? malloct((size_t) need * sizeof(WCHAR)) : NULL;
6316
6317
  if (full == NULL) {
6318
    return wpath; /* fall back to the plain path */
6319
  }
6320
  const DWORD written = GetFullPathNameW(wpath, need, full, NULL);
6321
6322
  if (written == 0 || written >= need || full[0] == L'\0') {
6323
    freet(full);
6324
    return wpath;
6325
  }
6326
6327
  const int isUNC = full[0] == L'\\' && full[1] == L'\\';
6328
  // UNC "\\srv\share" -> "\\?\UNC\srv\share": the prefix subsumes the "\\".
6329
  const WCHAR *const pfx = isUNC ? L"\\\\?\\UNC\\" : L"\\\\?\\";
6330
  const WCHAR *const body = isUNC ? full + 2 : full;
6331
  const size_t pfxLen = wcslen(pfx), bodyLen = wcslen(body);
6332
  LPWSTR out = malloct((pfxLen + bodyLen + 1) * sizeof(WCHAR));
6333
6334
  if (out == NULL) {
6335
    freet(full);
6336
    return wpath;
6337
  }
6338
  memcpybuff(out, pfx, pfxLen * sizeof(WCHAR));
6339
  memcpybuff(out + pfxLen, body, (bodyLen + 1) * sizeof(WCHAR));
6340
  freet(full);
6341
  freet(wpath);
6342
  return out;
6343
}
6344
6345
FILE *hts_fopen_utf8(const char *path, const char *mode) {
6346
  WCHAR wmode[32];
6347
  LPWSTR wpath = hts_pathToUCS2(path);
6348
6349
  assertf(strlen(mode) < sizeof(wmode) / sizeof(WCHAR));
6350
  copyWchar(wmode, mode);
6351
  if (wpath != NULL) {
6352
    FILE *const fp = _wfopen(wpath, wmode);
6353
6354
    freet(wpath);
6355
    return fp;
6356
  } else {
6357
    // Fallback on conversion error.
6358
    return fopen(path, mode);
6359
  }
6360
}
6361
6362
int hts_stat_utf8(const char *path, STRUCT_STAT * buf) {
6363
  LPWSTR wpath = hts_pathToUCS2(path);
6364
6365
  if (wpath != NULL) {
6366
    const int result = _wstat64(wpath, buf);
6367
6368
    freet(wpath);
6369
    return result;
6370
  } else {
6371
    // Fallback on conversion error.
6372
    return _stat64(path, buf);
6373
  }
6374
}
6375
6376
int hts_unlink_utf8(const char *path) {
6377
  LPWSTR wpath = hts_pathToUCS2(path);
6378
6379
  if (wpath != NULL) {
6380
    const int result = _wunlink(wpath);
6381
6382
    freet(wpath);
6383
    return result;
6384
  } else {
6385
    // Fallback on conversion error.
6386
    return _unlink(path);
6387
  }
6388
}
6389
6390
int hts_rename_utf8(const char *oldpath, const char *newpath) {
6391
  LPWSTR woldpath = hts_pathToUCS2(oldpath);
6392
  LPWSTR wnewpath = hts_pathToUCS2(newpath);
6393
  if (woldpath != NULL && wnewpath != NULL) {
6394
    const int result = _wrename(woldpath, wnewpath);
6395
    /* Save errno: callers key off it (#779) and freeing may clobber it. */
6396
    const int err = errno;
6397
6398
    freet(woldpath);
6399
    freet(wnewpath);
6400
    errno = err;
6401
    return result;
6402
  } else {
6403
    freet(woldpath);
6404
    freet(wnewpath);
6405
    // Fallback on conversion error.
6406
    return rename(oldpath, newpath);
6407
  }
6408
}
6409
6410
int hts_rmdir_utf8(const char *path) {
6411
  LPWSTR wpath = hts_pathToUCS2(path);
6412
6413
  if (wpath != NULL) {
6414
    const int result = _wrmdir(wpath);
6415
6416
    freet(wpath);
6417
    return result;
6418
  } else {
6419
    // Fallback on conversion error.
6420
    return _rmdir(path);
6421
  }
6422
}
6423
6424
int hts_mkdir_utf8(const char *path) {
6425
  LPWSTR wpath = hts_pathToUCS2(path);
6426
6427
  if (wpath != NULL) {
6428
    const int result = _wmkdir(wpath);
6429
6430
    freet(wpath);
6431
    return result;
6432
  } else {
6433
    // Fallback on conversion error.
6434
    return _mkdir(path);
6435
  }
6436
}
6437
6438
HTSEXT_API int hts_utime_utf8(const char *path, const STRUCT_UTIMBUF * times) {
6439
  STRUCT_UTIMBUF mtimes = *times;
6440
  LPWSTR wpath = hts_pathToUCS2(path);
6441
6442
  if (wpath != NULL) {
6443
    const int result = _wutime(wpath, &mtimes);
6444
6445
    freet(wpath);
6446
    return result;
6447
  } else {
6448
    // Fallback on conversion error.
6449
    return _utime(path, &mtimes);
6450
  }
6451
}
6452
6453
#endif
6454
6455
// Fin