Coverage Report

Created: 2026-12-01 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httrack/src/htslib_selftest.c
Line
Count
Source
1
/* ------------------------------------------------------------ */
2
/*
3
HTTrack Website Copier, Offline Browser for Windows and Unix
4
Copyright (C) 2026 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: htslib_selftest.c subroutines:                         */
30
/*       self-tests for the engine utility primitives           */
31
/* Author: Xavier Roche                                         */
32
/* ------------------------------------------------------------ */
33
34
#include "htsselftest_int.h"
35
#include "htsname.h"
36
#include "htsfetch.h"
37
#include "htspsl.h"
38
#include "htsalias.h"
39
#include "htsbuf.h"
40
41
#include <ctype.h>
42
#include <limits.h>
43
#include <locale.h>
44
#include <stdint.h>
45
#ifndef _WIN32
46
#include <sys/wait.h> /* the forking sigterm self-test reaps its children */
47
#endif
48
49
/* Prints and counts a failed check at the self-test's line. */
50
0
static int mono_fail(int line, hts_boolean ok) {
51
0
  if (ok)
52
0
    return 0;
53
0
  printf("FAIL line %d\n", line);
54
0
  return 1;
55
0
}
56
57
/* -#test=mono: the monotonic clock's units, its never deadline and timeouts. */
58
0
static int st_mono(httrackp *opt, int argc, char **argv) {
59
0
  const hts_mono t = hts_mono_from_ms(5000);
60
0
  const hts_mono now = hts_mono_now();
61
0
  int errors = 0;
62
63
0
  errors +=
64
0
      mono_fail(__LINE__, hts_mono_diff_ms(hts_mono_add_s(t, 2), t) == 2000);
65
0
  errors +=
66
0
      mono_fail(__LINE__, hts_mono_diff_ms(hts_mono_add_ms(t, 2), t) == 2);
67
0
  errors += mono_fail(__LINE__,
68
0
                      hts_mono_diff_ms(hts_mono_add_ms(t, -7000), t) == -7000);
69
0
  errors +=
70
0
      mono_fail(__LINE__, hts_mono_diff_ms(t, hts_mono_add_s(t, 1)) == -1000);
71
  /* seconds widen before the multiply, so INT_MAX does not wrap */
72
0
  errors += mono_fail(__LINE__, hts_mono_diff_ms(hts_mono_add_s(t, INT_MAX),
73
0
                                                 t) == (TStamp) INT_MAX * 1000);
74
0
  errors += mono_fail(__LINE__, hts_mono_before(t, hts_mono_add_ms(t, 1)));
75
0
  errors += mono_fail(__LINE__, !hts_mono_before(t, t));
76
0
  errors += mono_fail(__LINE__, !hts_mono_before(hts_mono_add_ms(t, 1), t));
77
0
  errors += mono_fail(__LINE__, hts_mono_before(now, hts_mono_never()));
78
0
  errors += mono_fail(__LINE__, hts_mono_before(hts_mono_add_s(now, INT_MAX),
79
0
                                                hts_mono_never()));
80
0
  errors += mono_fail(__LINE__, !hts_mono_before(hts_mono_never(), now));
81
0
  errors += mono_fail(__LINE__, !hts_mono_before(hts_mono_now(), now));
82
  /* a timeout counts milliseconds, so a crossed second boundary is not one */
83
0
  errors +=
84
0
      mono_fail(__LINE__, !hts_timeout_elapsed(hts_mono_add_ms(t, 999),
85
0
                                               hts_mono_add_ms(t, 1001), 1));
86
0
  errors +=
87
0
      mono_fail(__LINE__, !hts_timeout_elapsed(t, hts_mono_add_ms(t, 999), 1));
88
0
  errors +=
89
0
      mono_fail(__LINE__, hts_timeout_elapsed(t, hts_mono_add_ms(t, 1000), 1));
90
0
  errors +=
91
0
      mono_fail(__LINE__, !hts_timeout_elapsed(t, hts_mono_add_s(t, 29), 30));
92
0
  errors +=
93
0
      mono_fail(__LINE__, hts_timeout_elapsed(t, hts_mono_add_s(t, 30), 30));
94
0
  errors += mono_fail(__LINE__, hts_timeout_elapsed(t, t, 0));
95
0
  errors +=
96
0
      mono_fail(__LINE__, hts_timeout_elapsed(t, hts_mono_add_ms(t, -1), -1));
97
0
  printf("%s\n", errors == 0 ? "ok" : "FAIL");
98
0
  return errors == 0 ? 0 : 1;
99
0
}
100
101
/* Prints the long and the short rendering of a duration. */
102
0
static int st_duration(httrackp *opt, int argc, char **argv) {
103
0
  char lng[256], shrt[256];
104
105
0
  (void) opt;
106
0
  if (argc < 1)
107
0
    return 1;
108
0
  sec2str(HTS_BUF(lng), (TStamp) strtoll(argv[0], NULL, 10));
109
0
  qsec2str_sized(HTS_SIZED(shrt), (TStamp) strtoll(argv[0], NULL, 10));
110
0
  printf("%s|%s\n", lng, shrt);
111
0
  return 0;
112
0
}
113
114
/* Base-64 of ARGV[0], repeated ARGV[1] times, with CRLF when ARGV[2] is 1,
115
   into an output of ARGV[3] bytes. */
116
0
static int st_base64(httrackp *opt, int argc, char **argv) {
117
0
  char one[256], in[4096], out[8192];
118
0
  const size_t n = argc < 1 ? 0 : st_decode_body(argv[0], HTS_BUF(one));
119
0
  const int repeat = argc < 2 ? 1 : atoi(argv[1]);
120
0
  const size_t size = argc < 4 ? sizeof(out) : (size_t) atoi(argv[3]);
121
0
  size_t len = 0, i;
122
0
  int r;
123
124
0
  (void) opt;
125
0
  if (argc < 1 || repeat < 0 || (size_t) repeat > sizeof(in) / (n + 1) ||
126
0
      size > sizeof(out))
127
0
    return 1;
128
0
  for (r = 0; r < repeat; r++, len += n)
129
0
    memcpy(in + len, one, n);
130
0
  code64(hts_span_at(in, len), hts_buf_at(out, size),
131
0
         argc > 2 && atoi(argv[2]) != 0 ? HTS_TRUE : HTS_FALSE);
132
0
  for (i = 0; out[i] != '\0'; i++) {
133
0
    if (out[i] == '\r')
134
0
      fputs("\\r", stdout);
135
0
    else if (out[i] == '\n')
136
0
      fputs("\\n", stdout);
137
0
    else
138
0
      putchar(out[i]);
139
0
  }
140
0
  putchar('\n');
141
0
  return 0;
142
0
}
143
144
/* very minimalistic internal tests */
145
0
static void basic_selftests(void) {
146
  // BUG 756328
147
0
  const char *const source =
148
0
      "/intent/"
149
0
      "tweet?url=https%3A%2F%2Fwww.httrack.com%2Fvacatures%2F1562519%"
150
0
      "2Fmedewerker-data-services&text=Medewerker+Data+Services&via=httrackcom";
151
0
  char buffer[1024];
152
0
  fil_normalized(source, buffer);
153
  // MD5 selftests
154
0
  md5selftest();
155
  // cookie_get field extraction (tab-separated, 0-based)
156
0
  {
157
0
    char cbuf[8192];
158
159
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "a\tb\tc", 0), "a") == 0);
160
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "a\tb\tc", 1), "b") == 0);
161
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "a\tb\tc", 2), "c") == 0);
162
    // multi-char fields catch length/boundary bugs that 1-char fields hide
163
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "host\tx\t/path/to", 0),
164
0
                   "host") == 0);
165
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "host\tx\t/path/to", 2),
166
0
                   "/path/to") == 0);
167
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "a\t\tc", 1), "") ==
168
0
            0); // empty field
169
0
    assertf(strcmp(cookie_get(cbuf, sizeof(cbuf), "a\tb\tc", 9), "") ==
170
0
            0); // beyond last
171
0
  }
172
  // back_infostr()'s size trailer must not clobber the URL written before it.
173
0
  {
174
0
    static const struct {
175
0
      int code;
176
0
      const char *tag;
177
0
    } cases[] = {
178
0
        {200, "READY "},     {-1, "ERROR "},       {-2, "TIMEOUT "},
179
0
        {-3, "TOOSLOW "},    {400, "BADREQUEST "}, {403, "FORBIDDEN "},
180
0
        {404, "NOT FOUND "}, {500, "SERVERROR "},  {999, "ERROR(999)"},
181
0
    };
182
183
0
    const int ncases = (int) (sizeof(cases) / sizeof(cases[0]));
184
0
    const int n = 2000;
185
0
    lien_back *slots = calloct(n, sizeof(lien_back));
186
0
    char line[HTS_URLMAXSIZE * 4 + 1024];
187
0
    char expect[HTS_URLMAXSIZE * 4 + 1024];
188
0
    struct_back sb;
189
0
    int idx;
190
191
0
    memset(&sb, 0, sizeof(sb));
192
0
    sb.lnk = slots;
193
0
    sb.count = n;
194
0
    sb.ready = NULL;
195
0
    sb.ready_size_bytes = 0;
196
0
    for (idx = 0; idx < n; idx++) {
197
0
      lien_back *const slot = &slots[idx];
198
199
0
      slot->r.location = slot->location_buffer;
200
0
      slot->status = STATUS_READY;
201
0
      slot->r.statuscode = cases[idx % ncases].code;
202
0
      slot->r.size = idx;
203
0
      slot->r.totalsize = idx + 1;
204
0
      snprintf(slot->url_adr, sizeof(slot->url_adr), "http://h%d.example", idx);
205
0
      snprintf(slot->url_fil, sizeof(slot->url_fil), "/p/%d.html", idx);
206
0
    }
207
0
    for (idx = 0; idx < n; idx++) {
208
0
      line[0] = '\0';
209
0
      back_infostr(&sb, idx, 3, HTS_BUF(line));
210
      // Match exactly, because a presence check lets a partial clobber through.
211
0
      snprintf(expect, sizeof(expect),
212
0
               "%s\"http://h%d.example/p/%d.html\" " LLintP " " LLintP " ",
213
0
               cases[idx % ncases].tag, idx, idx, (LLint) idx,
214
0
               (LLint) (idx + 1));
215
0
      assertf(strcmp(line, expect) == 0);
216
0
    }
217
    // j&1 half and j=2: connect shows no URL, INFOSC has no space, 401 too
218
0
    {
219
0
      static const struct {
220
0
        int status, code, j;
221
0
        const char *expect;
222
0
      } by_status[] = {
223
0
          {STATUS_CONNECTING, 0, 1, "CONNECT "},
224
0
          {STATUS_WAIT_HEADERS, 0, 1, "INFOS \"http://h.example/p\" 7 8 "},
225
0
          {STATUS_CHUNK_WAIT, 0, 1, "INFOSC\"http://h.example/p\" 7 8 "},
226
0
          {STATUS_CHUNK_CR, 0, 1, "INFOSC\"http://h.example/p\" 7 8 "},
227
0
          {STATUS_TRANSFER, 0, 1, "RECEIVE \"http://h.example/p\" 7 8 "},
228
0
          {STATUS_READY, 401, 3, "FORBIDDEN \"http://h.example/p\" 7 8 "},
229
0
          {STATUS_READY, 200, 1, ""},
230
0
          {STATUS_TRANSFER, 0, 2, ""}};
231
232
0
      size_t k;
233
234
0
      for (k = 0; k < sizeof(by_status) / sizeof(by_status[0]); k++) {
235
0
        lien_back *const slot = &slots[0];
236
237
0
        slot->status = by_status[k].status;
238
0
        slot->r.statuscode = by_status[k].code;
239
0
        slot->r.size = 7;
240
0
        slot->r.totalsize = 8;
241
0
        snprintf(slot->url_adr, sizeof(slot->url_adr), "http://h.example");
242
0
        snprintf(slot->url_fil, sizeof(slot->url_fil), "/p");
243
0
        line[0] = '\0';
244
0
        back_infostr(&sb, 0, by_status[k].j, HTS_BUF(line));
245
0
        assertf(strcmp(line, by_status[k].expect) == 0);
246
0
      }
247
0
    }
248
    // Lock setters store 1, BACK_PINNED and 0
249
0
    back_set_locked(&sb, 0);
250
0
    assertf(slots[0].locked == 1);
251
0
    back_set_pinned(&sb, 0);
252
0
    assertf(slots[0].locked == BACK_PINNED);
253
0
    back_set_unlocked(&sb, 0);
254
0
    assertf(slots[0].locked == 0);
255
    // back_info()'s own status buffer must hold url_adr and url_fil together.
256
0
    {
257
0
      lien_back *const slot = &slots[0];
258
0
      const size_t adrlen = sizeof(slot->url_adr) - 8;
259
0
      const size_t fillen = sizeof(slot->url_fil) - 8;
260
0
      FILE *const fp = tmpfile();
261
0
      size_t got;
262
263
0
      assertf(fp != NULL);
264
0
      slot->status = STATUS_READY;
265
0
      slot->r.statuscode = 200;
266
0
      slot->r.size = 1;
267
0
      slot->r.totalsize = 2;
268
0
      memset(slot->url_adr, 'a', adrlen);
269
0
      slot->url_adr[adrlen] = '\0';
270
0
      slot->url_fil[0] = '/';
271
0
      memset(slot->url_fil + 1, 'b', fillen - 1);
272
0
      slot->url_fil[fillen] = '\0';
273
0
      back_info(&sb, 0, 3, fp);
274
0
      rewind(fp);
275
0
      got = fread(line, 1, sizeof(line) - 1, fp);
276
0
      line[got] = '\0';
277
0
      fclose(fp);
278
0
      snprintf(expect, sizeof(expect),
279
0
               "READY \"%s%s\" " LLintP " " LLintP " " LF, slot->url_adr,
280
0
               slot->url_fil, (LLint) 1, (LLint) 2);
281
0
      assertf(strcmp(line, expect) == 0);
282
0
    }
283
0
    freet(slots);
284
0
  }
285
  // fil_normalized() sorts the query and collapses "//" outside it.
286
0
  {
287
0
    char norm[256];
288
289
0
    assertf(strcmp(fil_normalized("/p?b=2&a=1&c=3", norm), "/p?a=1&b=2&c=3") ==
290
0
            0);
291
0
    assertf(strcmp(fil_normalized("/a//b", norm), "/a/b") == 0);
292
    // "//" is collapsed only before the query; inside the query it is kept
293
0
    assertf(strcmp(fil_normalized("/a//b?x=c//d", norm), "/a/b?x=c//d") == 0);
294
0
  }
295
  // give_mimext(): mime type -> file extension, bounded into the caller buffer.
296
  // Returns 1 when an extension was written, 0 otherwise.
297
0
  {
298
0
    char ext[16];
299
300
0
    assertf(give_mimext(HTS_BUF(ext), "image/gif") == 1);
301
0
    assertf(strcmp(ext, "gif") == 0);
302
0
    assertf(give_mimext(HTS_BUF(ext), "text/html") == 1);
303
0
    assertf(strcmp(ext, "html") == 0);
304
0
    assertf(give_mimext(HTS_BUF(ext), "no/such-mime-type") == 0);
305
0
    assertf(ext[0] == '\0');
306
    // modern web formats -> extension. Avoid MIME types the
307
    // application/<=4-char-subtype fallback could fabricate without a row.
308
0
    assertf(give_mimext(HTS_BUF(ext), "image/webp") == 1);
309
0
    assertf(strcmp(ext, "webp") == 0);
310
0
    assertf(give_mimext(HTS_BUF(ext), "application/manifest+json") == 1);
311
0
    assertf(strcmp(ext, "webmanifest") == 0);
312
0
    assertf(give_mimext(HTS_BUF(ext), "font/woff2") == 1);
313
0
    assertf(strcmp(ext, "woff2") == 0);
314
0
  }
315
  // convtolower(): lower-cases into the caller buffer (bounded by its size).
316
0
  {
317
0
    char low[64];
318
319
0
    assertf(strcmp(convtolower(HTS_BUF(low), "ABC/Def.HTML"), "abc/def.html") ==
320
0
            0);
321
0
  }
322
  // get_httptype_sized() writes a long MIME type (73 chars for OOXML) whole.
323
0
  {
324
0
    httrackp *opt = hts_create_opt();
325
0
    htsblk r; // write into the real struct field, not a stand-in
326
327
0
    assertf(opt != NULL);
328
    // a long MIME (Office OOXML reaches 73 chars) must fit htsblk.contenttype
329
    // whole: a [64] field would make this bounded copy abort.
330
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
331
0
                               "deck.pptx", 0) == 1);
332
0
    assertf(strcmp(r.contenttype,
333
0
                   "application/vnd.openxmlformats-officedocument."
334
0
                   "presentationml.presentation") == 0);
335
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
336
0
                               "x.gif", 0) == 1);
337
0
    assertf(strcmp(r.contenttype, "image/gif") == 0);
338
    // modern extensions map back to their MIME type
339
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
340
0
                               "x.webp", 0) == 1);
341
0
    assertf(strcmp(r.contenttype, "image/webp") == 0);
342
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
343
0
                               "app.wasm", 0) == 1);
344
0
    assertf(strcmp(r.contenttype, "application/wasm") == 0);
345
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
346
0
                               "mod.mjs", 0) == 1);
347
0
    assertf(strcmp(r.contenttype, "text/javascript") == 0);
348
    // no extension and flag==0: nothing written, returns 0
349
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
350
0
                               "noextfile", 0) == 0);
351
0
    assertf(r.contenttype[0] == '\0');
352
    // no extension and flag==1: octet-stream fallback, returns 1
353
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
354
0
                               "noextfile", 1) == 1);
355
0
    assertf(strcmp(r.contenttype, "application/octet-stream") == 0);
356
    // a 0 return still clears a stale buffer, unmatched rule loaded or not
357
0
    {
358
0
      static const char *const fils[] = {"noextfile", "", "/x.zzz"};
359
0
      size_t k;
360
361
0
      for (k = 0; k < sizeof(fils) / sizeof(fils[0]); k++) {
362
0
        StringCopy(opt->mimedefs, k == 2 ? "\ncgi=text/html\n" : "\n");
363
0
        memset(r.contenttype, 'X', sizeof(r.contenttype) - 1);
364
0
        r.contenttype[sizeof(r.contenttype) - 1] = '\0';
365
0
        assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
366
0
                                   fils[k], 0) == 0);
367
0
        assertf(r.contenttype[0] == '\0');
368
0
      }
369
0
      StringCopy(opt->mimedefs, "\n");
370
0
    }
371
    // empty fil: no extension to scan; must not over-read before the string.
372
    // flag==0 -> 0 (nothing written), flag==1 -> octet-stream.
373
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype), "",
374
0
                               0) == 0);
375
0
    assertf(r.contenttype[0] == '\0');
376
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype), "",
377
0
                               1) == 1);
378
0
    assertf(strcmp(r.contenttype, "application/octet-stream") == 0);
379
    // a user --assume rule with an empty value matches but writes nothing:
380
    // get_userhttptype returns 1 with the buffer empty, so get_httptype_sized
381
    // must still report 0 (callers test the return like the old
382
    // strnotempty(s)).
383
0
    StringCopy(opt->mimedefs, "\ncgi=\n");
384
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
385
0
                               "/x.cgi", 0) == 0);
386
0
    assertf(r.contenttype[0] == '\0');
387
0
    StringCopy(opt->mimedefs, "\ncgi=text/html\n");
388
0
    assertf(get_httptype_sized(opt, r.contenttype, sizeof(r.contenttype),
389
0
                               "/x.cgi", 0) == 1);
390
0
    assertf(strcmp(r.contenttype, "text/html") == 0);
391
0
    hts_free_opt(opt);
392
0
  }
393
  // adr_normalized_sized(): bounded host normalization (passthrough when
394
  // already normal).
395
0
  {
396
0
    char n[HTS_URLMAXSIZE];
397
398
0
    assertf(strcmp(adr_normalized_sized("example.com", n, sizeof(n)),
399
0
                   "example.com") == 0);
400
0
  }
401
  // standard_name(): builds "<name><md5?>.<ext>" into a bounded buffer. The md5
402
  // is appended (4 chars) only when the URL has a query string (see url_md5),
403
  // so test both; pin the structure (name + ext, lengths), not the md5 chars.
404
0
  {
405
0
    char b[HTS_URLMAXSIZE * 2];
406
0
    const char *nom = "index.html"; // name part
407
0
    const char *dot = nom + 5;      // points at ".html"
408
0
    size_t len;
409
410
    // no query -> no md5: "index" + ".html"
411
0
    standard_name(HTS_BUF(b), dot, nom, "http://example.com/index.html", 0);
412
0
    assertf(strcmp(b, "index.html") == 0);
413
    // query -> 4 md5 chars between name and ext: "index" + md5(4) + ".html"
414
0
    standard_name(HTS_BUF(b), dot, nom, "http://example.com/index.html?v=1", 0);
415
0
    len = strlen(b);
416
0
    assertf(len == 5 + 4 + 5);
417
0
    assertf(strncmp(b, "index", 5) == 0);
418
0
    assertf(strcmp(b + len - 5, ".html") == 0);
419
    // short names: name kept (<=8), the extension is clamped to 3 -> ".htm"
420
0
    standard_name(HTS_BUF(b), dot, nom, "http://example.com/index.html?v=1", 1);
421
0
    len = strlen(b);
422
0
    assertf(len == 5 + 4 + 4);
423
0
    assertf(strcmp(b + len - 4, ".htm") == 0);
424
    // short names with a >8-char name: the name is clamped to 8 ("indexpag")
425
0
    {
426
0
      const char *lnom = "indexpage.html";
427
0
      const char *ldot = lnom + 9; // points at ".html"
428
429
0
      standard_name(HTS_BUF(b), ldot, lnom,
430
0
                    "http://example.com/indexpage.html?v=1", 1);
431
0
      len = strlen(b);
432
0
      assertf(len == 8 + 4 + 4);
433
0
      assertf(strncmp(b, "indexpag", 8) == 0);
434
0
      assertf(strcmp(b + len - 4, ".htm") == 0);
435
0
    }
436
    // a buffer too small for it all drops the extension, then the md5, but
437
    // keeps a name byte: never a cut extension, never a new dotfile
438
0
    {
439
0
      const char *const q = "http://example.com/index.html?v=1";
440
0
      const char *const nq = "http://example.com/index.html";
441
0
      const char *const dotf = ".htaccess";
442
0
      char sml[16];
443
444
0
      standard_name(HTS_BUF_N(sml, 1), dot, nom, q, 0);
445
0
      assertf(strcmp(sml, "") == 0);
446
0
      standard_name(HTS_BUF_N(sml, 2), dot, nom, q, 0);
447
0
      assertf(strcmp(sml, "i") == 0);
448
0
      standard_name(HTS_BUF_N(sml, 6), dot, nom, q, 0);
449
0
      assertf(strcmp(sml, "i3860") == 0); // md5("v=1") starts 3860
450
0
      standard_name(HTS_BUF_N(sml, 6), dot, nom, nq, 0);
451
0
      assertf(strcmp(sml, "index") == 0);
452
0
      standard_name(HTS_BUF_N(sml, 7), dot, nom, nq, 0);
453
0
      assertf(strcmp(sml, "i.html") == 0);
454
0
      standard_name(HTS_BUF_N(sml, 5), dot, nom, nq, 1);
455
0
      assertf(strcmp(sml, "inde") == 0);
456
0
      standard_name(HTS_BUF_N(sml, 6), dot, nom, nq, 1);
457
0
      assertf(strcmp(sml, "i.htm") == 0);
458
0
      standard_name(HTS_BUF_N(sml, 4), dotf, dotf, dotf, 0);
459
0
      assertf(strcmp(sml, "hta") == 0);
460
0
      standard_name(HTS_BUF(sml), dotf, dotf, dotf, 0);
461
0
      assertf(strcmp(sml, ".htaccess") == 0);
462
0
    }
463
0
  }
464
  // longfile_to_83(): single-name 8-3 (mode 1) / ISO9660 (mode 2) conversion;
465
  // uppercases, clamps the name (8 / 31) and the extension (3). It rewrites
466
  // 'save' in place, so pass a mutable array.
467
0
  {
468
0
    char n83[256];
469
470
0
    {
471
0
      char save[] = "longfilename.html";
472
473
0
      longfile_to_83(1, HTS_BUF(n83), save); // 8-3: name->8, ext->3
474
0
      assertf(strcmp(n83, "LONGFILE.HTM") == 0);
475
0
    }
476
0
    {
477
0
      char save[] = "longfilename.html";
478
479
      // exact fit: 12 chars + NUL
480
0
      longfile_to_83(1, HTS_BUF_N(n83, sizeof("LONGFILE.HTM")), save);
481
0
      assertf(strcmp(n83, "LONGFILE.HTM") == 0);
482
0
    }
483
0
    {
484
0
      char save[] = "longfilename.html";
485
486
0
      longfile_to_83(2, HTS_BUF(n83), save); // ISO9660: name->31, ext->3
487
0
      assertf(strcmp(n83, "LONGFILENAME.HTM") == 0);
488
0
    }
489
0
    { // sanitization: leading '.'->'_', interior dots
490
0
      char save[] = ".a b.c.d e"; // collapse to '_', spaces/specials -> '_'
491
                                  // (only the last dot stays as the separator)
492
0
      longfile_to_83(1, HTS_BUF(n83), save);
493
0
      assertf(strcmp(n83, "_A_B_C.D_E") == 0);
494
0
    }
495
0
  }
496
  // long_to_83(): per-segment 8-3 conversion of a whole path.
497
0
  {
498
0
    char n83[HTS_URLMAXSIZE * 2];
499
0
    char save[] = "dir/longfilename.html";
500
501
0
    long_to_83(1, HTS_BUF(n83), save);
502
0
    assertf(strcmp(n83, "DIR/LONGFILE.HTM") == 0);
503
0
    { // exact fit: 16 chars plus the NUL
504
0
      char fit[sizeof("DIR/LONGFILE.HTM")];
505
506
0
      long_to_83(1, HTS_BUF(fit), save);
507
0
      assertf(strcmp(fit, "DIR/LONGFILE.HTM") == 0);
508
0
    }
509
0
  }
510
  // lienrelatif(): relative path from the directory of curr_fil to link.
511
0
  {
512
0
    char s[HTS_URLMAXSIZE * 2];
513
514
    // same directory -> just the basename
515
0
    assertf(lienrelatif(HTS_BUF(s), "dir/page.html", "dir/index.html") == 0);
516
0
    assertf(strcmp(s, "page.html") == 0);
517
    // link one level up -> a "../" prefix
518
0
    assertf(lienrelatif(HTS_BUF(s), "a.html", "dir/index.html") == 0);
519
0
    assertf(strcmp(s, "../a.html") == 0);
520
    // an empty current path: the trim used to walk off the front of it, which
521
    // "?x" reaches too because the query pre-pass hands on the part before it
522
0
    assertf(lienrelatif(HTS_BUF(s), "dir/page.html", "") == 0);
523
0
    assertf(strcmp(s, "dir/page.html") == 0);
524
0
    assertf(lienrelatif(HTS_BUF(s), "dir/page.html", "?x") == 0);
525
0
    assertf(strcmp(s, "dir/page.html") == 0);
526
0
  }
527
0
}
528
529
/* Poison dst, then empty it, so a write-nothing implementation cannot pass. */
530
0
static void reset_dst(hts_buf dst, size_t *used) {
531
0
  memset(dst.p, '#', dst.size);
532
0
  dst.p[0] = '\0';
533
0
  *used = 0;
534
0
}
535
536
/* contenttype abuts msg and is poisoned to catch an off-by-one NUL. */
537
0
static hts_boolean blk_neighbours_intact(const htsblk *r) {
538
0
  return r->contenttype[0] == '#' && r->statuscode == 1234;
539
0
}
540
541
/* Self-tests for the htssafe.h bounded string ops.
542
   Returns 0 if every bounded operation behaved correctly, 1 otherwise.
543
   The abort-on-overflow guarantee is checked separately by the "overflow"
544
   sub-mode (it aborts the process by design). */
545
0
static int string_safety_selftests(void) {
546
0
  char buf[16];
547
548
  /* strcpybuff into a sized array: exact copy */
549
0
  strcpybuff(buf, "abc");
550
0
  if (strcmp(buf, "abc") != 0)
551
0
    return 1;
552
553
  /* strcatbuff append within capacity */
554
0
  strcatbuff(buf, "de");
555
0
  if (strcmp(buf, "abcde") != 0)
556
0
    return 1;
557
558
  /* strncatbuff appends at most N source chars */
559
0
  strcpybuff(buf, "ab");
560
0
  strncatbuff(buf, "cdef", 2);
561
0
  if (strcmp(buf, "abcd") != 0)
562
0
    return 1;
563
564
  /* A decayed source has no known capacity, so the whole tail must land; a
565
     sizeof(char*) capacity would abort here instead. */
566
0
  {
567
0
    char src[32] = "0123456789abcdefghij";
568
0
    char dst[32];
569
570
0
    strcpybuff(dst, src + 1);
571
0
    if (strcmp(dst, "123456789abcdefghij") != 0)
572
0
      return 1;
573
0
  }
574
575
  /* Truncating append: stops at N without aborting, what the status-message
576
     call sites rely on. */
577
0
  {
578
0
    char dst[10]; /* never sizeof(char*), or MSVC reads it as a pointer */
579
580
0
    dst[0] = '\0';
581
0
    strncatbuff(dst, "abcdefghijkl", sizeof(dst) - 1);
582
0
    if (strcmp(dst, "abcdefghi") != 0)
583
0
      return 1;
584
0
  }
585
586
  /* strlcpybuff: explicit-capacity copy into a pointer destination, the form
587
     the migration moves toward */
588
0
  {
589
0
    char storage[8];
590
0
    char *const p = storage;
591
592
0
    strlcpybuff(p, "hello", sizeof(storage));
593
0
    if (strcmp(p, "hello") != 0)
594
0
      return 1;
595
0
  }
596
597
  /* strcpybuff's unchecked pointer-destination fallback must still copy.
598
     C11 mode has no fallback. */
599
0
#ifndef HTS_BUFF_C11_
600
0
#if defined(__GNUC__)
601
0
#pragma GCC diagnostic push
602
0
#pragma GCC diagnostic ignored "-Wattribute-warning"
603
0
#endif
604
0
  {
605
0
    char storage[8];
606
0
    char *const p = storage;
607
608
0
    strcpybuff(p, "ptr");
609
0
    if (strcmp(p, "ptr") != 0)
610
0
      return 1;
611
0
  }
612
0
#if defined(__GNUC__)
613
0
#pragma GCC diagnostic pop
614
0
#endif
615
0
#endif
616
617
  /* htsbuff: bounded builder over a fixed array (append, truncating append,
618
     reset, and length tracking) */
619
0
  {
620
0
    char dst[8];
621
0
    htsbuff b = htsbuff_array(dst);
622
623
0
    htsbuff_cat(&b, "ab");
624
0
    htsbuff_cat(&b, "cd");
625
0
    if (strcmp(htsbuff_str(&b), "abcd") != 0 || b.len != 4)
626
0
      return 1;
627
628
0
    htsbuff_catn(&b, "efghij", 2); /* append at most 2 */
629
0
    if (strcmp(htsbuff_str(&b), "abcdef") != 0)
630
0
      return 1;
631
632
0
    htsbuff_cpy(&b, "xyz"); /* reset */
633
0
    if (strcmp(htsbuff_str(&b), "xyz") != 0 || b.len != 3)
634
0
      return 1;
635
636
0
    htsbuff_catc(&b, '!'); /* single character */
637
0
    if (strcmp(htsbuff_str(&b), "xyz!") != 0 || b.len != 4)
638
0
      return 1;
639
0
  }
640
641
  /* boundary: filling to exactly cap-1 must succeed (one more aborts, which the
642
     overflow-buff mode checks) */
643
0
  {
644
0
    char d2[4];
645
0
    htsbuff c = htsbuff_array(d2);
646
647
0
    htsbuff_cat(&c, "abc");
648
0
    if (strcmp(htsbuff_str(&c), "abc") != 0 || c.len != 3)
649
0
      return 1;
650
0
  }
651
652
  /* sprintfbuff: truncate-and-report. Must never abort (its callers format
653
     remote banners) nor write past the array, which the canary catches. */
654
0
  {
655
0
    struct {
656
0
      char dst[8];
657
0
      char canary[8];
658
0
    } s;
659
660
0
    const char *const big = "0123456789abcdefghijklmnopqrstuvwxyz";
661
662
    /* repoison before every call, or an implementation that measures first and
663
       writes nothing "passes" the truncating cases on the previous content */
664
0
    memset(&s, '#', sizeof(s));
665
0
    if (!sprintfbuff(s.dst, "%s-%d", "ab", 42) || strcmp(s.dst, "ab-42") != 0)
666
0
      return 1;
667
668
    /* exact fit: 7 characters plus the NUL */
669
0
    memset(s.dst, '#', sizeof(s.dst));
670
0
    if (!sprintfbuff(s.dst, "%s", "1234567") || strcmp(s.dst, "1234567") != 0)
671
0
      return 1;
672
673
    /* one over, then far over: truncated to the prefix, terminated, reported */
674
0
    memset(s.dst, '#', sizeof(s.dst));
675
0
    if (sprintfbuff(s.dst, "%s", "12345678") || strcmp(s.dst, "1234567") != 0)
676
0
      return 1;
677
0
    memset(s.dst, '#', sizeof(s.dst));
678
0
    if (sprintfbuff(s.dst, "%s", big) || strcmp(s.dst, "0123456") != 0)
679
0
      return 1;
680
681
    /* explicit-capacity form, down to the degenerate size 1 */
682
0
    {
683
0
      char *const p = s.dst;
684
685
0
      memset(s.dst, '#', sizeof(s.dst));
686
0
      if (slprintfbuff(p, 1, "%s", "x") || p[0] != '\0')
687
0
        return 1;
688
0
      memset(s.dst, '#', sizeof(s.dst));
689
0
      if (!slprintfbuff(p, sizeof(s.dst), "%s", "ok") || strcmp(p, "ok") != 0)
690
0
        return 1;
691
0
    }
692
693
0
    if (memcmp(s.canary, "########", sizeof(s.canary)) != 0)
694
0
      return 1;
695
0
  }
696
697
  /* Each case resets the destination so a no-op cannot pass (#1685). */
698
0
  {
699
0
    struct {
700
0
      char dst[8];
701
0
      char canary[8];
702
0
    } s;
703
704
0
    const char *const big = "0123456789abcdefghijklmnopqrstuvwxyz";
705
0
    size_t used;
706
707
0
    memset(&s, '#', sizeof(s));
708
709
    /* well under capacity: the cursor lands on the new end */
710
0
    reset_dst(HTS_BUF(s.dst), &used);
711
0
    slcatprintfbuff_clip(s.dst, sizeof(s.dst), &used, "%s-%d", "ab", 42);
712
0
    if (strcmp(s.dst, "ab-42") != 0 || used != 5)
713
0
      return 1;
714
715
    /* a second append continues where the cursor left it */
716
0
    slcatprintfbuff_clip(s.dst, sizeof(s.dst), &used, "%s", "xy");
717
0
    if (strcmp(s.dst, "ab-42xy") != 0 || used != 7)
718
0
      return 1;
719
720
    /* exact fit: capacity - 1 characters plus the NUL */
721
0
    reset_dst(HTS_BUF(s.dst), &used);
722
0
    slcatprintfbuff_clip(s.dst, sizeof(s.dst), &used, "%s", "1234567");
723
0
    if (strcmp(s.dst, "1234567") != 0 || used != 7)
724
0
      return 1;
725
726
    /* one over, then far over: clipped to the prefix and terminated. The
727
       expected bytes differ between the two, so a write-nothing implementation
728
       cannot pass on the leftovers. */
729
0
    reset_dst(HTS_BUF(s.dst), &used);
730
0
    slcatprintfbuff_clip(s.dst, sizeof(s.dst), &used, "%s", "12345678");
731
0
    if (strcmp(s.dst, "1234567") != 0 || used != 7)
732
0
      return 1;
733
0
    reset_dst(HTS_BUF(s.dst), &used);
734
0
    slcatprintfbuff_clip(s.dst, sizeof(s.dst), &used, "%s", big);
735
0
    if (strcmp(s.dst, "0123456") != 0 || used != 7)
736
0
      return 1;
737
738
    /* a full destination takes nothing more and the cursor stays put */
739
0
    slcatprintfbuff_clip(s.dst, sizeof(s.dst), &used, "%s", "zz");
740
0
    if (strcmp(s.dst, "0123456") != 0 || used != 7)
741
0
      return 1;
742
743
0
    if (memcmp(s.canary, "########", sizeof(s.canary)) != 0)
744
0
      return 1;
745
0
  }
746
747
  /* strclipbuff: truncate-and-report, never abort. Same canary shape; the
748
     destination is poisoned before every call so a case cannot pass on the
749
     previous one's bytes. */
750
0
  {
751
0
    struct {
752
0
      char dst[8];
753
0
      char canary[8];
754
0
    } s;
755
756
0
    memset(&s, '#', sizeof(s));
757
    /* well under capacity: no padding, nothing eaten off the end */
758
0
    memset(s.dst, '#', sizeof(s.dst));
759
0
    if (!strclipbuff(s.dst, sizeof(s.dst), "abc") || strcmp(s.dst, "abc") != 0)
760
0
      return 1;
761
762
    /* exact fit: capacity - 1 characters plus the NUL */
763
0
    memset(s.dst, '#', sizeof(s.dst));
764
0
    if (!strclipbuff(s.dst, sizeof(s.dst), "1234567") ||
765
0
        strcmp(s.dst, "1234567") != 0)
766
0
      return 1;
767
768
    /* These expected bytes differ from the case above, so leftovers fail. */
769
0
    memset(s.dst, '#', sizeof(s.dst));
770
0
    if (strclipbuff(s.dst, sizeof(s.dst), "abcdefgh") ||
771
0
        strcmp(s.dst, "abcdefg") != 0)
772
0
      return 1;
773
0
    memset(s.dst, '#', sizeof(s.dst));
774
0
    if (strclipbuff(s.dst, sizeof(s.dst), "0123456789abcdef") ||
775
0
        strcmp(s.dst, "0123456") != 0)
776
0
      return 1;
777
778
    /* degenerate capacity 1: only the NUL fits. Capacity 2 pins the boundary
779
       between that and the sizes above: one character plus the NUL. */
780
0
    memset(s.dst, '#', sizeof(s.dst));
781
0
    if (strclipbuff(s.dst, 1, "x") || s.dst[0] != '\0')
782
0
      return 1;
783
0
    memset(s.dst, '#', sizeof(s.dst));
784
0
    if (strclipbuff(s.dst, 2, "yz") || strcmp(s.dst, "y") != 0)
785
0
      return 1;
786
787
    /* the empty string fits any non-zero capacity */
788
0
    memset(s.dst, '#', sizeof(s.dst));
789
0
    if (!strclipbuff(s.dst, sizeof(s.dst), "") || s.dst[0] != '\0')
790
0
      return 1;
791
792
    /* a byte over 0x7f must not end the copy early */
793
0
    memset(s.dst, '#', sizeof(s.dst));
794
0
    if (!strclipbuff(s.dst, sizeof(s.dst), "\xff\xfe") ||
795
0
        strcmp(s.dst, "\xff\xfe") != 0)
796
0
      return 1;
797
798
0
    if (memcmp(s.canary, "########", sizeof(s.canary)) != 0)
799
0
      return 1;
800
0
  }
801
802
  /* htsblk_failf: clips a reason quoted from a remote reply into msg[] and
803
     touches nothing else in the block */
804
0
  {
805
0
    htsblk r;
806
0
    char expect[sizeof(r.msg)];
807
0
    char big[4 * sizeof(r.msg)];
808
809
0
    memset(&r, 0, sizeof(r));
810
0
    memset(r.contenttype, '#', sizeof(r.contenttype));
811
0
    r.statuscode = 1234;
812
813
0
    memset(r.msg, '#', sizeof(r.msg));
814
0
    htsblk_failf(&r, "PASV incorrect: %s", "220 ok");
815
0
    if (strcmp(r.msg, "PASV incorrect: 220 ok") != 0 ||
816
0
        !blk_neighbours_intact(&r))
817
0
      return 1;
818
819
    /* exact fit: capacity - 1 characters plus the NUL */
820
0
    memset(expect, 'y', sizeof(expect) - 1);
821
0
    expect[sizeof(expect) - 1] = '\0';
822
0
    memcpy(expect, "Bad password: ", sizeof("Bad password: ") - 1);
823
0
    memset(r.msg, '#', sizeof(r.msg));
824
0
    htsblk_failf(&r, "%s", expect);
825
0
    if (strcmp(r.msg, expect) != 0 || !blk_neighbours_intact(&r))
826
0
      return 1;
827
828
    /* far over: the expected bytes differ from the cases above, so writing
829
       nothing cannot pass on the leftovers */
830
0
    memset(big, 'z', sizeof(big) - 1);
831
0
    big[sizeof(big) - 1] = '\0';
832
0
    memset(expect, 'z', sizeof(expect) - 1);
833
0
    expect[sizeof(expect) - 1] = '\0';
834
0
    memcpy(expect, "Bad user name: ", sizeof("Bad user name: ") - 1);
835
836
0
    memset(r.msg, '#', sizeof(r.msg));
837
0
    htsblk_failf(&r, "Bad user name: %s", big);
838
0
    if (strcmp(r.msg, expect) != 0 || !blk_neighbours_intact(&r))
839
0
      return 1;
840
0
  }
841
842
  /* StringCatN/StringSetLength must eval SIZE once: (n_eval++, V) leaves
843
     n_eval == 2 on a double-eval macro. */
844
0
  {
845
0
    String s = STRING_EMPTY;
846
0
    int n_eval = 0;
847
848
0
    StringCat(s, "hello");
849
0
    StringCatN(s, "world", (n_eval++, 3)); /* strlen>SIZE so the clamp runs */
850
0
    if (n_eval != 1 || strcmp(StringBuff(s), "hellowor") != 0) {
851
0
      StringFree(s);
852
0
      return 1;
853
0
    }
854
855
0
    n_eval = 0;
856
0
    StringSetLength(s, (n_eval++, 5));
857
0
    if (n_eval != 1 || StringLength(s) != 5) {
858
0
      StringFree(s);
859
0
      return 1;
860
0
    }
861
0
    StringFree(s);
862
0
  }
863
864
  /* Each String macro evaluates its String arguments once: every s[(i++, N)]
865
     counts one evaluation. */
866
0
  {
867
0
    String s[2] = {STRING_EMPTY, STRING_EMPTY};
868
0
    int i = 0, j = 0, bad;
869
870
0
    StringInit(s[(i++, 0)]);
871
0
    StringRoomTotal(s[(i++, 0)], 8);
872
0
    StringRoom(s[(i++, 0)], 8);
873
0
    StringClear(s[(i++, 0)]);
874
0
    StringMemcpy(s[(i++, 0)], "ab", 2);
875
0
    StringMemcat(s[(i++, 0)], "cd", 2);
876
0
    StringCopyN(s[(i++, 0)], "abcd", 3);
877
0
    StringCopy(s[(i++, 0)], "wxyz");
878
0
    StringCopyS(s[(i++, 1)], s[(j++, 0)]);
879
0
    StringSetLength(s[(i++, 1)], 3);
880
0
    StringPopRight(s[(i++, 1)]);
881
0
    bad = StringRight(s[(i++, 1)], 1) != 'x';
882
0
    StringRightRW(s[(i++, 1)], 1) = 'X';
883
0
    StringSetBuffer(s[(i++, 0)], StringAcquire(&s[(j++, 1)]));
884
0
    bad |= strcmp(StringBuff(s[0]), "wX") != 0 || StringBuff(s[1]) != NULL;
885
0
    StringFree(s[(i++, 0)]);
886
0
    bad |= StringBuff(s[0]) != NULL;
887
0
    if (bad || i != 15 || j != 2) {
888
0
      printf("  FAIL: a String macro evaluated its String %d/15 %d/2 times\n",
889
0
             i, j);
890
0
      return 1;
891
0
    }
892
0
  }
893
894
  /* StringSubRW still reads/writes after dropping its duplicate definition. */
895
0
  {
896
0
    String s = STRING_EMPTY;
897
898
0
    StringCat(s, "abc");
899
0
    StringSubRW(s, 1) = 'X';
900
0
    if (StringSub(s, 1) != 'X' || strcmp(StringBuff(s), "aXc") != 0) {
901
0
      StringFree(s);
902
0
      return 1;
903
0
    }
904
0
    StringFree(s);
905
0
  }
906
907
0
  return 0;
908
0
}
909
910
/* The value stored under key #i. */
911
0
static long hashtable_value(size_t i) {
912
0
  return (long) i * 1664525 + 1013904223;
913
0
}
914
915
/* Key #i: line i of the file, or a generated URL when there is no file. */
916
static const char *hashtable_key(hts_buf buffer, const char **strings, size_t i,
917
0
                                 long expected) {
918
0
  if (strings != NULL)
919
0
    return strings[i];
920
0
  snprintf(buffer.p, buffer.size,
921
0
           "http://www.example.com/website/sample/for/hashtable/"
922
0
           "%ld/index.html?foo=%ld&bar",
923
0
           (long) i, expected);
924
0
  return buffer.p;
925
0
}
926
927
0
static int st_hashtable(httrackp *opt, int argc, char **argv) {
928
0
  char *snum;
929
0
  unsigned long count = 0;
930
0
  const char *const names[] = {
931
0
      "",        "add",         "delete",        "dry-add",
932
0
      "dry-del", "test-exists", "test-not-exist"};
933
934
0
  const struct {
935
0
    enum {
936
0
      DO_END,
937
0
      DO_ADD,
938
0
      DO_DEL,
939
0
      DO_DRY_ADD,
940
0
      DO_DRY_DEL,
941
0
      TEST_ADD,
942
0
      TEST_DEL
943
0
    } type;
944
945
0
    size_t modulus;
946
0
    size_t offset;
947
0
  } bench[] = {{DO_ADD, 4, 0},     /* add 4/0 */
948
0
               {TEST_ADD, 4, 0},   /* check 4/0 */
949
0
               {TEST_DEL, 4, 1},   /* check 4/1 */
950
0
               {TEST_DEL, 4, 2},   /* check 4/2 */
951
0
               {TEST_DEL, 4, 3},   /* check 4/3 */
952
0
               {DO_DRY_DEL, 4, 1}, /* del 4/1 */
953
0
               {DO_DRY_DEL, 4, 2}, /* del 4/2 */
954
0
               {DO_DRY_DEL, 4, 3}, /* del 4/3 */
955
0
               {DO_ADD, 4, 1},     /* add 4/1 */
956
0
               {DO_DRY_ADD, 4, 1}, /* add 4/1 */
957
0
               {TEST_ADD, 4, 0},   /* check 4/0 */
958
0
               {TEST_ADD, 4, 1},   /* check 4/1 */
959
0
               {TEST_DEL, 4, 2},   /* check 4/2 */
960
0
               {TEST_DEL, 4, 3},   /* check 4/3 */
961
0
               {DO_ADD, 4, 2},     /* add 4/2 */
962
0
               {DO_DRY_DEL, 4, 3}, /* del 4/3 */
963
0
               {DO_ADD, 4, 3},     /* add 4/3 */
964
0
               {DO_DEL, 4, 3},     /* del 4/3 */
965
0
               {TEST_ADD, 4, 0},   /* check 4/0 */
966
0
               {TEST_ADD, 4, 1},   /* check 4/1 */
967
0
               {TEST_ADD, 4, 2},   /* check 4/2 */
968
0
               {TEST_DEL, 4, 3},   /* check 4/3 */
969
0
               {DO_DEL, 4, 0},     /* del 4/0 */
970
0
               {DO_DEL, 4, 1},     /* del 4/1 */
971
0
               {DO_DEL, 4, 2},     /* del 4/2 */
972
               /* empty here */
973
0
               {TEST_DEL, 1, 0},  /* check */
974
0
               {DO_ADD, 4, 0},    /* add 4/0 */
975
0
               {DO_ADD, 4, 1},    /* add 4/1 */
976
0
               {DO_ADD, 4, 2},    /* add 4/2 */
977
0
               {DO_DEL, 42, 0},   /* add 42/0 */
978
0
               {TEST_DEL, 42, 0}, /* check 42/0 */
979
0
               {TEST_ADD, 42, 2}, /* check 42/2 */
980
0
               {DO_END}};
981
982
0
  char *buff = NULL;
983
0
  const char **strings = NULL;
984
985
0
  basic_selftests();
986
0
  if (argc < 1) {
987
0
    fprintf(stderr, "hashtable: needs a count or a file\n");
988
0
    exit(EXIT_FAILURE);
989
0
  }
990
0
  snum = strdupt(argv[0]);
991
992
  /* produce random patterns, or read from a file */
993
0
  if (sscanf(snum, "%lu", &count) != 1) {
994
0
    const LLint fs = fsize(snum);
995
    /* one width for the buffer and the walk below: a 64-bit size wraps
996
       malloct() short while the loop still counts to the real end */
997
0
    const size_t size = fs >= 0 ? llint_to_size_t(fs) : (size_t) -1;
998
0
    FILE *fp = size != (size_t) -1 ? fopen(snum, "rb") : NULL;
999
0
    if (fp != NULL) {
1000
0
      buff = malloct(size);
1001
0
      if (buff != NULL && hts_fread_exact(buff, size, fp)) {
1002
0
        size_t capa = 0;
1003
0
        size_t i, last;
1004
0
        for (i = 0, last = 0, count = 0; i < size; i++) {
1005
0
          if (buff[i] == 10 || buff[i] == 0) {
1006
0
            buff[i] = '\0';
1007
0
            if (capa == count) {
1008
0
              if (capa == 0) {
1009
0
                capa = 16;
1010
0
              } else {
1011
0
                capa <<= 1;
1012
0
              }
1013
0
              strings = (const char **) realloct((void *) strings,
1014
0
                                                 capa * sizeof(char *));
1015
0
              assertf(strings != NULL);
1016
0
            }
1017
0
            strings[count++] = &buff[last];
1018
0
            last = i + 1;
1019
0
          }
1020
0
        }
1021
0
      }
1022
0
      fclose(fp);
1023
0
    }
1024
0
  }
1025
1026
  /* successfully read */
1027
0
  if (count > 0) {
1028
0
    coucal hashtable = coucal_new(0);
1029
0
    size_t loop;
1030
0
    for (loop = 0; bench[loop].type != DO_END; loop++) {
1031
0
      size_t i;
1032
0
      for (i = bench[loop].offset; i < (size_t) count;
1033
0
           i += bench[loop].modulus) {
1034
0
        int result = 0; /* no final else: an unknown type reports failure */
1035
0
        char buffer[256];
1036
0
        const long expected = hashtable_value(i);
1037
0
        const char *const name =
1038
0
            hashtable_key(HTS_BUF(buffer), strings, i, expected);
1039
0
        if (bench[loop].type == DO_ADD || bench[loop].type == DO_DRY_ADD) {
1040
0
          size_t k;
1041
0
          result = coucal_write(hashtable, name, (uintptr_t) expected);
1042
0
          for (k = 0; k < /* stash_size*2 */ 32; k++) {
1043
0
            (void) coucal_write(hashtable, name, (uintptr_t) expected);
1044
0
          }
1045
          /* revert logic */
1046
0
          if (bench[loop].type == DO_DRY_ADD) {
1047
0
            result = result ? 0 : 1;
1048
0
          }
1049
0
        } else if (bench[loop].type == DO_DEL ||
1050
0
                   bench[loop].type == DO_DRY_DEL) {
1051
0
          size_t k;
1052
0
          result = coucal_remove(hashtable, name);
1053
0
          for (k = 0; k < /* stash_size*2 */ 32; k++) {
1054
0
            (void) coucal_remove(hashtable, name);
1055
0
          }
1056
          /* revert logic */
1057
0
          if (bench[loop].type == DO_DRY_DEL) {
1058
0
            result = result ? 0 : 1;
1059
0
          }
1060
0
        } else if (bench[loop].type == TEST_ADD ||
1061
0
                   bench[loop].type == TEST_DEL) {
1062
0
          intptr_t value = -1;
1063
0
          result = coucal_readptr(hashtable, name, &value);
1064
0
          if (bench[loop].type == TEST_ADD && result && value != expected) {
1065
0
            fprintf(stderr, "value failed for %s (expected %ld, got %ld)\n",
1066
0
                    name, (long) expected, (long) value);
1067
0
            exit(EXIT_FAILURE);
1068
0
          }
1069
          /* revert logic */
1070
0
          if (bench[loop].type == TEST_DEL) {
1071
0
            result = result ? 0 : 1;
1072
0
          }
1073
0
        }
1074
0
        if (!result) {
1075
0
          fprintf(stderr,
1076
0
                  "failed %s{%d/+%d} test on loop %ld"
1077
0
                  " at offset %ld for %s\n",
1078
0
                  names[bench[loop].type], (int) bench[loop].modulus,
1079
0
                  (int) bench[loop].offset, (long) loop, (long) i, name);
1080
0
          exit(EXIT_FAILURE);
1081
0
        }
1082
0
      }
1083
0
    }
1084
0
    coucal_delete(&hashtable);
1085
0
    fprintf(stderr, "all hashtable tests were successful!\n");
1086
0
  } else {
1087
0
    fprintf(stderr, "Malformed number\n");
1088
0
    exit(EXIT_FAILURE);
1089
0
  }
1090
0
  freet(buff);
1091
0
  freet(strings);
1092
0
  freet(snum);
1093
0
  return 0;
1094
0
}
1095
1096
0
static int st_strsafe(httrackp *opt, int argc, char **argv) {
1097
0
  if (argc >= 1 && strncmp(argv[0], "overflow", 8) == 0) {
1098
    /* The source comes from argv so the compiler cannot see its length. */
1099
    /* Not sizeof(char*), because MSVC's array-vs-pointer check reads an ILP32
1100
       char[4] as a pointer and skips the bound. */
1101
0
    char small[6];
1102
0
    const char *const src = (argc >= 2) ? argv[1] : "overflowing";
1103
1104
0
    if (strcmp(argv[0], "overflow-buff") == 0) {
1105
0
      htsbuff b = htsbuff_array(small);
1106
1107
0
      htsbuff_cat(&b, src);
1108
0
    } else if (strcmp(argv[0], "overflow-src") == 0) {
1109
      /* Array source with no NUL: its capacity still comes from sizeof(), so
1110
         the bounded strlen aborts rather than running off the array. */
1111
0
      char nonul[6]; /* never sizeof(char*), per the note above */
1112
0
      char big[64];
1113
1114
0
      memset(nonul, src[0], sizeof(nonul));
1115
0
      strcpybuff(big, nonul);
1116
0
    } else {
1117
0
      strcpybuff(small, src);
1118
0
    }
1119
0
    printf("strsafe: NOT aborted\n"); /* must be unreachable */
1120
0
    return 1;
1121
0
  } else {
1122
0
    const int err = string_safety_selftests();
1123
1124
0
    printf("strsafe: %s\n", err ? "FAIL" : "OK");
1125
0
    return err;
1126
0
  }
1127
0
}
1128
1129
/* Wide enough that a capacity still fitting a size_t makes capa*width wrap. */
1130
typedef struct {
1131
  char pad[4096];
1132
} arrays_wide_t;
1133
1134
/* Returns 0 when htsarrays.h growth always reached the requested room. */
1135
0
static int array_growth_selftests(void) {
1136
0
  TypedArray(char) a = EMPTY_TYPED_ARRAY;
1137
0
  TypedArray(arrays_wide_t) w = EMPTY_TYPED_ARRAY;
1138
0
  size_t i;
1139
0
  int err = 0;
1140
1141
0
  TypedArrayEnsureRoom(a, 1);
1142
0
  ST_FAIL_IF(err, TypedArrayRoom(a) < 1 || TypedArrayCapa(a) < 16);
1143
1144
  /* A request past the current capacity must be met, not landed short of. */
1145
0
  TypedArrayAppend(a, "0123456789", 10);
1146
0
  TypedArrayEnsureRoom(a, 1000);
1147
0
  ST_FAIL_IF(err, TypedArrayRoom(a) < 1000 || TypedArraySize(a) != 10);
1148
0
  ST_FAIL_IF(err, memcmp(TypedArrayElts(a), "0123456789", 10) != 0);
1149
1150
  /* Capacity must always keep capa*width representable. */
1151
0
  TypedArrayEnsureRoom(w, 3);
1152
0
  ST_FAIL_IF(err,
1153
0
             TypedArrayRoom(w) < 3 ||
1154
0
                 TypedArrayCapa(w) > ((size_t) -1) / sizeof(arrays_wide_t));
1155
1156
  /* Asking for the room left must not reach the allocator, which aborts on a
1157
     borrowed store. That abort is the assertion (OSS-Fuzz 5622506602692608). */
1158
0
  {
1159
0
    char borrowed[64];
1160
0
    TypedArray(char) b = EMPTY_TYPED_ARRAY;
1161
1162
0
    TypedArrayPtr(b) = borrowed;
1163
0
    TypedArrayCapa(b) = sizeof(borrowed);
1164
0
    TypedArraySize(b) = 10;
1165
0
    TypedArrayEnsureRoom(b, TypedArrayRoom(b));
1166
0
  } /* No TypedArrayFree: the store is not the allocator's. */
1167
1168
  /* A zero-count append on a never-grown array must not take the address of
1169
     its missing store. Only Clang's UBSan can fail this case. */
1170
0
  {
1171
0
    TypedArray(char) z = EMPTY_TYPED_ARRAY;
1172
1173
0
    TypedArrayAppend(z, "abc", 0);
1174
0
    TypedArrayFree(z);
1175
0
  }
1176
1177
  /* Many small growths, checking the payload survives every reallocation. */
1178
0
  for (i = 0; i < 5000; i++) {
1179
0
    TypedArrayAdd(a, (char) ('a' + (i % 26)));
1180
0
  }
1181
0
  if (TypedArraySize(a) != 5010)
1182
0
    err = 1;
1183
0
  else {
1184
0
    for (i = 0; i < 5000; i++) {
1185
0
      ST_FAIL_IF(err, TypedArrayNth(a, 10 + i) != (char) ('a' + (i % 26)));
1186
0
    }
1187
0
  }
1188
1189
0
  TypedArrayFree(a);
1190
0
  TypedArrayFree(w);
1191
0
  return err;
1192
0
}
1193
1194
/* Returns 0 when TypedArrayReserve, Push and At report what they did. */
1195
0
static int array_push_selftests(void) {
1196
0
  TypedArray(char) a = EMPTY_TYPED_ARRAY;
1197
0
  void *ptr;
1198
0
  size_t capa, size, i;
1199
0
  int err = 0;
1200
1201
  /* A push at capacity grows the store and keeps what it held. */
1202
0
  ST_FAIL_IF(err, !TypedArrayPush(a, 'a'));
1203
0
  while (TypedArrayRoom(a) != 0)
1204
0
    ST_FAIL_IF(err, !TypedArrayPush(a, (char) ('a' + TypedArraySize(a))));
1205
0
  capa = TypedArrayCapa(a);
1206
0
  ST_FAIL_IF(err, !TypedArrayPush(a, 'z'));
1207
0
  ST_FAIL_IF(err, TypedArrayCapa(a) <= capa || TypedArraySize(a) != capa + 1);
1208
0
  for (i = 1; i < capa; i++)
1209
0
    ST_FAIL_IF(err, TypedArrayNth(a, i) != (char) ('a' + i));
1210
1211
  /* A room that fits exactly needs no grow. */
1212
0
  ptr = TypedArrayPtr(a);
1213
0
  capa = TypedArrayCapa(a);
1214
0
  size = TypedArraySize(a);
1215
0
  ST_FAIL_IF(err, TypedArrayRoom(a) == 0);
1216
  /* Armed, so a realloc it should not make fails the reserve. */
1217
0
  hts_realloct_fault_selftest = 1;
1218
0
  ST_FAIL_IF(err, !TypedArrayReserve(a, TypedArrayRoom(a)));
1219
0
  ST_FAIL_IF(err, hts_realloct_fault_selftest != 1);
1220
0
  hts_realloct_fault_selftest = 0;
1221
0
  ST_FAIL_IF(err, TypedArrayPtr(a) != ptr || TypedArrayCapa(a) != capa);
1222
1223
  /* A push after a refused grow still lands. */
1224
0
  hts_realloct_fault_selftest = 1;
1225
0
  ST_FAIL_IF(err, TypedArrayReserve(a, capa));
1226
0
  hts_realloct_fault_selftest = 0;
1227
0
  ST_FAIL_IF(err, TypedArrayPtr(a) != ptr || TypedArrayCapa(a) != capa ||
1228
0
                      TypedArraySize(a) != size);
1229
0
  ST_FAIL_IF(err, !TypedArrayPush(a, '!'));
1230
0
  ST_FAIL_IF(err, TypedArraySize(a) != size + 1);
1231
1232
  /* At reads the element N names, and writes the last one. */
1233
0
  ST_FAIL_IF(err, TypedArrayAt(a, 0) != 'a' || TypedArrayAt(a, 1) != 'b');
1234
0
  ST_FAIL_IF(err, TypedArrayAt(a, TypedArraySize(a) - 1) != '!');
1235
0
  TypedArrayAt(a, TypedArraySize(a) - 1) = '?';
1236
0
  ST_FAIL_IF(err, TypedArrayNth(a, TypedArraySize(a) - 1) != '?');
1237
1238
  /* A push whose grow the allocator refuses fails and changes nothing. */
1239
0
  while (TypedArrayRoom(a) != 0)
1240
0
    ST_FAIL_IF(err, !TypedArrayPush(a, '.'));
1241
0
  ptr = TypedArrayPtr(a);
1242
0
  capa = TypedArrayCapa(a);
1243
0
  hts_realloct_fault_selftest = 1;
1244
0
  ST_FAIL_IF(err, TypedArrayPush(a, 'x'));
1245
0
  hts_realloct_fault_selftest = 0;
1246
0
  ST_FAIL_IF(err, TypedArrayPtr(a) != ptr || TypedArrayCapa(a) != capa ||
1247
0
                      TypedArraySize(a) != capa);
1248
1249
0
  TypedArrayFree(a);
1250
0
  return err;
1251
0
}
1252
1253
/* Returns 0 when a room past what a size_t holds fails at once and changes
1254
   nothing. A missing bound loops forever, so the caller bounds the run. */
1255
0
static int array_reserve_overflow_selftests(void) {
1256
0
  TypedArray(char) a = EMPTY_TYPED_ARRAY;
1257
0
  TypedArray(arrays_wide_t) w = EMPTY_TYPED_ARRAY;
1258
  /* volatile keeps the overflowing rooms runtime values. */
1259
0
  volatile size_t room;
1260
0
  void *ptr;
1261
0
  size_t capa;
1262
0
  int err = 0;
1263
1264
0
  ST_FAIL_IF(err, !TypedArrayPush(a, 'k'));
1265
0
  ptr = TypedArrayPtr(a);
1266
0
  capa = TypedArrayCapa(a);
1267
0
  room = (size_t) -1;
1268
0
  ST_FAIL_IF(err, TypedArrayReserve(a, room));
1269
0
  room = ((size_t) -1) / sizeof(arrays_wide_t) + 1;
1270
0
  ST_FAIL_IF(err, TypedArrayReserve(w, room));
1271
0
  ST_FAIL_IF(err, TypedArrayPtr(w) != NULL || TypedArrayCapa(w) != 0);
1272
0
  ST_FAIL_IF(err, TypedArrayPtr(a) != ptr || TypedArrayCapa(a) != capa ||
1273
0
                      TypedArraySize(a) != 1);
1274
0
  ST_FAIL_IF(err, !TypedArrayPush(a, '!') || TypedArrayAt(a, 1) != '!');
1275
0
  TypedArrayFree(a);
1276
0
  return err;
1277
0
}
1278
1279
/* The arena's promise is that what it hands out never moves, so this keeps
1280
   every pointer it returns and re-reads them all at the end. */
1281
0
static int st_arena(httrackp *opt, int argc, char **argv) {
1282
0
  enum { count = 4096 };
1283
1284
0
  hts_arena arena = {NULL, 0, 0};
1285
0
  char **kept = (char **) calloct(count, sizeof(*kept));
1286
0
  char BIGSTK big[HTS_ARENA_MIN * 2];
1287
0
  char token[256];
1288
0
  int i;
1289
1290
0
  assertf(kept != NULL);
1291
1292
  /* Enough tokens to span many chunks, each holding its own index. */
1293
0
  for (i = 0; i < count; i++) {
1294
0
    snprintf(token, sizeof(token), "%d-%*s", i, 200, "x");
1295
0
    kept[i] = hts_arena_strdup(&arena, token);
1296
0
    assertf(kept[i] != NULL);
1297
0
  }
1298
  /* One allocation larger than a whole chunk takes one of its own. */
1299
0
  memset(big, 'b', sizeof(big) - 1);
1300
0
  big[sizeof(big) - 1] = '\0';
1301
0
  assertf(hts_arena_strdup(&arena, big) != NULL);
1302
  /* An aligned allocation is aligned whatever the byte-sized ones did to it. */
1303
0
  for (i = 0; i < 8; i++) {
1304
0
    void *const p = hts_arena_alloc(&arena, sizeof(hts_arena_align));
1305
1306
0
    assertf(p != NULL);
1307
0
    assertf(((size_t) (char *) p) % HTS_ARENA_ALIGN == 0);
1308
0
    assertf(hts_arena_strdup(&arena, "x") != NULL);
1309
0
  }
1310
  /* Nothing moved: every token still reads back as itself. */
1311
0
  for (i = 0; i < count; i++) {
1312
0
    snprintf(token, sizeof(token), "%d-%*s", i, 200, "x");
1313
0
    assertf(strcmp(kept[i], token) == 0);
1314
0
  }
1315
  /* A size no allocation could hold is refused, not truncated. */
1316
0
  assertf(hts_arena_alloc(&arena, (size_t) -1) == NULL);
1317
  /* Strings are packed, because aligning each costs bytes on every link. */
1318
0
  {
1319
0
    hts_arena packed = {NULL, 0, 0};
1320
0
    const char *const a = hts_arena_strdup(&packed, "abc");
1321
0
    const char *const b = hts_arena_strdup(&packed, "de");
1322
1323
0
    assertf(a != NULL && b == a + sizeof("abc"));
1324
0
    hts_arena_free(&packed);
1325
0
  }
1326
1327
0
  freet(kept);
1328
0
  hts_arena_free(&arena);
1329
0
  assertf(arena.chunks == NULL && arena.size == 0 && arena.used == 0);
1330
0
  hts_arena_free(&arena); /* releasing an empty arena is a no-op */
1331
0
  printf("arena self-test OK\n");
1332
0
  return 0;
1333
0
}
1334
1335
/* Serialize 'count' UCS2 code units, re-encode them and compare the result
1336
   against 'expect' (its length taken as the expected byte count, so a NUL is
1337
   not usable inside a case). */
1338
static int ucs2_check(const unsigned short *units, size_t count,
1339
0
                      const char *expect, hts_boolean swap) {
1340
0
  const size_t want = strlen(expect);
1341
0
  unsigned char *src = (unsigned char *) malloct(count * 2 + 1);
1342
0
  size_t got_size = (size_t) -1;
1343
0
  char *got;
1344
0
  size_t i;
1345
0
  int err = 0;
1346
1347
0
  if (src == NULL)
1348
0
    return 1;
1349
0
  for (i = 0; i < count; i++) {
1350
0
    src[i * 2 + (swap ? 0 : 1)] = (unsigned char) (units[i] & 0xff);
1351
0
    src[i * 2 + (swap ? 1 : 0)] = (unsigned char) (units[i] >> 8);
1352
0
  }
1353
0
  got = hts_ucs2_to_utf8(hts_span_at((const char *) src, count * 2), swap,
1354
0
                         &got_size);
1355
0
  ST_FAIL_IF(err, got == NULL || got_size != want ||
1356
0
                      memcmp(got, expect, want) != 0 || got[got_size] != '\0');
1357
0
  freet(got);
1358
0
  freet(src);
1359
0
  return err;
1360
0
}
1361
1362
/* The growth is the UCS4 re-encoder's only allocation, so any return at all
1363
   from a starved run says the refusal was not caught. */
1364
0
static int st_ucs4_oom(httrackp *opt, int argc, char **argv) {
1365
#if defined(__GNU__)
1366
  /* GNU/Hurd kills a starved process with SIGSEGV before the tested abort. */
1367
  printf("ucs4: a capped process does not survive here, skipped\n");
1368
  return 0;
1369
#elif !defined(_WIN32)
1370
  {
1371
0
    enum { units = 512 * 1024 };
1372
1373
0
    char *src = (char *) malloct(units);
1374
0
    struct rlimit saved, tight;
1375
0
    hts_UCS4 *out;
1376
1377
0
    if (src == NULL || getrlimit(RLIMIT_AS, &saved) != 0) {
1378
0
      printf("ucs4: cannot cap memory, skipped\n");
1379
0
      freet(src);
1380
0
      return 0;
1381
0
    }
1382
0
    memset(src, 'a', units); /* one UCS4 unit per byte, so the output is 4x */
1383
0
    tight = saved;
1384
0
    tight.rlim_cur = 1024 * 1024;
1385
0
    if (setrlimit(RLIMIT_AS, &tight) != 0) {
1386
0
      printf("ucs4: cannot cap memory, skipped\n");
1387
0
      freet(src);
1388
0
      return 0;
1389
0
    }
1390
0
    out = hts_convertUTF8StringToUCS4(hts_span_at(src, units), NULL);
1391
0
    (void) setrlimit(RLIMIT_AS, &saved);
1392
0
    freet(src);
1393
0
    if (out == NULL) {
1394
0
      printf("ucs4: the refused growth returned instead of aborting\n");
1395
0
      return 1;
1396
0
    }
1397
0
    freet(out);
1398
0
    printf("ucs4: cap did not bite, skipped\n");
1399
0
    return 0;
1400
0
  }
1401
#else
1402
  printf("ucs4: cannot cap memory, skipped\n");
1403
  return 0;
1404
#endif
1405
0
}
1406
1407
/* The bytes of array A, which may be unsigned char, as a span. */
1408
#define BYTES_SPAN(A)                                                          \
1409
0
  hts_span_at((const char *) (A), sizeof(A) + HTS_BUF_GUARD_(A))
1410
1411
0
static int st_ucs2(httrackp *opt, int argc, char **argv) {
1412
  /* A BOM, ASCII, a two-byte and a three-byte code point, a surrogate pair
1413
     and an unpaired surrogate: only the ASCII one is a single output byte. */
1414
0
  static const unsigned short mixed[] = {0xFEFF, 'a',    0x00E9, 0x20AC,
1415
0
                                         0xD83D, 0xDE00, 0xD800};
1416
0
  static const char mixed_utf8[] = "\xEF\xBB\xBF"
1417
0
                                   "a"
1418
0
                                   "\xC3\xA9"
1419
0
                                   "\xE2\x82\xAC"
1420
0
                                   "\xF0\x9F\x98\x80"
1421
0
                                   "\xEF\xBF\xBD";
1422
  /* The ends of the supplementary range, planes 2 and 3, and halves out of
1423
     order, doubled, or followed by a BMP unit. */
1424
0
  static const unsigned short pairs[] = {
1425
0
      0xD800, 0xDC00, 0xDBFF, 0xDFFF, 0xD840, 0xDC00, 0xD869, 0xDED6,
1426
0
      0xD880, 0xDC3F, 0xDC00, 0xD800, 'b',    0xDC00, 0xDC00, 0xD800,
1427
0
      0xD800, 0xD800, 0xDBFF, 0xD800, 0xE000, 0xDBFF};
1428
0
  static const char pairs_utf8[] = "\xF0\x90\x80\x80"
1429
0
                                   "\xF4\x8F\xBF\xBF"
1430
0
                                   "\xF0\xA0\x80\x80"
1431
0
                                   "\xF0\xAA\x9B\x96"
1432
0
                                   "\xF0\xB0\x80\xBF"
1433
0
                                   "\xEF\xBF\xBD"
1434
0
                                   "\xEF\xBF\xBD"
1435
0
                                   "b"
1436
0
                                   "\xEF\xBF\xBD"
1437
0
                                   "\xEF\xBF\xBD"
1438
0
                                   "\xEF\xBF\xBD"
1439
0
                                   "\xEF\xBF\xBD"
1440
0
                                   "\xEF\xBF\xBD"
1441
0
                                   "\xEF\xBF\xBD"
1442
0
                                   "\xEF\xBF\xBD"
1443
0
                                   "\xEE\x80\x80"
1444
0
                                   "\xEF\xBF\xBD";
1445
  /* A BOM, 'a', then one dangling byte: an odd-length (truncated) body. */
1446
0
  static const unsigned char odd[] = {0xFF, 0xFE, 'a', 0, 'b'};
1447
0
  static const unsigned short empty[] = {0};
1448
1449
0
  if (argc >= 1 && strcmp(argv[0], "oom") == 0) {
1450
0
#ifndef _WIN32
1451
    /* Starve the output allocation. Big enough that the allocator must ask
1452
       the kernel rather than serve it from what it already holds. */
1453
0
    enum { units = 512 * 1024 };
1454
1455
0
    unsigned char *src = (unsigned char *) malloct(units * 2);
1456
0
    struct rlimit saved, tight;
1457
0
    size_t out_size = 0;
1458
0
    char *out;
1459
0
    size_t i;
1460
1461
0
    if (src == NULL || getrlimit(RLIMIT_AS, &saved) != 0) {
1462
0
      printf("ucs2: cannot cap memory, skipped\n");
1463
0
      freet(src);
1464
0
      return 0;
1465
0
    }
1466
0
    for (i = 0; i < units; i++) { /* U+20AC, three UTF-8 bytes each */
1467
0
      src[i * 2] = 0x20;
1468
0
      src[i * 2 + 1] = 0xAC;
1469
0
    }
1470
0
    tight = saved;
1471
0
    tight.rlim_cur = 1024 * 1024;
1472
0
    if (setrlimit(RLIMIT_AS, &tight) != 0) {
1473
0
      printf("ucs2: cannot cap memory, skipped\n");
1474
0
      freet(src);
1475
0
      return 0;
1476
0
    }
1477
0
    out = hts_ucs2_to_utf8(hts_span_at((const char *) src, units * 2),
1478
0
                           HTS_FALSE, &out_size);
1479
0
    (void) setrlimit(RLIMIT_AS, &saved);
1480
0
    freet(src);
1481
0
    if (out != NULL) {
1482
      /* RLIMIT_AS is advisory on this host, so the run cannot grade. */
1483
0
      freet(out);
1484
0
      printf("ucs2: cap did not bite, skipped\n");
1485
0
      return 0;
1486
0
    }
1487
0
    printf("ucs2: oom OK\n");
1488
0
    return 0;
1489
#else
1490
    printf("ucs2: cannot cap memory, skipped\n");
1491
    return 0;
1492
#endif
1493
0
  } else {
1494
0
    int err = 0;
1495
1496
0
    ST_FAIL_IF(err, ucs2_check(mixed, sizeof(mixed) / sizeof(mixed[0]),
1497
0
                               mixed_utf8, HTS_TRUE));
1498
0
    ST_FAIL_IF(err, ucs2_check(mixed, sizeof(mixed) / sizeof(mixed[0]),
1499
0
                               mixed_utf8, HTS_FALSE));
1500
0
    ST_FAIL_IF(err, ucs2_check(pairs, sizeof(pairs) / sizeof(pairs[0]),
1501
0
                               pairs_utf8, HTS_TRUE));
1502
    /* a pair that ends the body is still a pair */
1503
0
    ST_FAIL_IF(err, ucs2_check(pairs, 2, "\xF0\x90\x80\x80", HTS_FALSE));
1504
0
    {
1505
0
      size_t n = 0;
1506
0
      char *got = hts_ucs2_to_utf8(BYTES_SPAN(odd), HTS_TRUE, &n);
1507
1508
0
      ST_FAIL_IF(err, got == NULL || n != 7 ||
1509
0
                          memcmp(got,
1510
0
                                 "\xEF\xBB\xBF"
1511
0
                                 "a"
1512
0
                                 "\xEF\xBF\xBD",
1513
0
                                 7) != 0);
1514
0
      freet(got);
1515
0
    }
1516
    /* What the crawler converts on: some ASCII, almost nothing suspicious. */
1517
0
    {
1518
0
      static const unsigned char text[] = {'<', 0, 'p', 0, '>', 0, 0x2D, 0x4E,
1519
0
                                           '<', 0, '/', 0, 'p', 0, '>',  0};
1520
0
      static const unsigned char few[] = {'<', 0, 'p', 0, '>', 0, 0x2D, 0x4E};
1521
0
      unsigned char bad[sizeof(text)];
1522
0
      const hts_span odd_text =
1523
0
          hts_span_at((const char *) text, sizeof(text) - 1);
1524
0
      size_t k;
1525
1526
0
      ST_FAIL_IF(err, !hts_utf16_looks_like_text(BYTES_SPAN(text), HTS_TRUE) ||
1527
0
                          hts_utf16_looks_like_text(BYTES_SPAN(few), HTS_TRUE));
1528
      /* One unit each: lone high and low halves, private use, noncharacters
1529
         and a C0 control; a dangling byte is not one of them. */
1530
0
      for (k = 0; k < 6; k++) {
1531
0
        static const unsigned short units[] = {0xD800, 0xDC00, 0xE000,
1532
0
                                               0xF8FF, 0xFDD0, 0xFFFE};
1533
1534
0
        memcpy(bad, text, sizeof(text));
1535
0
        bad[6] = (unsigned char) (units[k] & 0xff);
1536
0
        bad[7] = (unsigned char) (units[k] >> 8);
1537
0
        ST_FAIL_IF(err, hts_utf16_looks_like_text(BYTES_SPAN(bad), HTS_TRUE));
1538
0
      }
1539
0
      memcpy(bad, text, sizeof(text));
1540
0
      bad[6] = 0x01;
1541
0
      bad[7] = 0;
1542
0
      ST_FAIL_IF(err, hts_utf16_looks_like_text(BYTES_SPAN(bad), HTS_TRUE) ||
1543
0
                          !hts_utf16_looks_like_text(odd_text, HTS_TRUE));
1544
0
    }
1545
    /* 200 units allow 2 suspicious ones (1 in 200), not 3. */
1546
0
    {
1547
0
      unsigned char body[400];
1548
0
      size_t k;
1549
1550
0
      for (k = 0; k < sizeof(body); k += 2) {
1551
0
        body[k] = k < 6 ? 0x01 : 'a';
1552
0
        body[k + 1] = 0;
1553
0
      }
1554
0
      ST_FAIL_IF(err, hts_utf16_looks_like_text(BYTES_SPAN(body), HTS_TRUE));
1555
0
      body[0] = 'a';
1556
0
      ST_FAIL_IF(err, !hts_utf16_looks_like_text(BYTES_SPAN(body), HTS_TRUE));
1557
0
    }
1558
    /* Every code unit alone, to pin the encoder against its ranges. */
1559
0
    {
1560
0
      unsigned int u;
1561
1562
0
      for (u = 0; u <= 0xFFFF && !err; u++) {
1563
0
        const unsigned short unit = (unsigned short) u;
1564
0
        char expect[4];
1565
0
        size_t len = 0;
1566
1567
0
        if (u <= 0x7F)
1568
0
          expect[len++] = (char) u;
1569
0
        else if (u <= 0x7FF) {
1570
0
          expect[len++] = (char) (0xC0 | (u >> 6));
1571
0
          expect[len++] = (char) (0x80 | (u & 0x3F));
1572
0
        } else if (u >= 0xD800 && u <= 0xDFFF) {
1573
0
          expect[len++] = (char) 0xEF;
1574
0
          expect[len++] = (char) 0xBF;
1575
0
          expect[len++] = (char) 0xBD;
1576
0
        } else {
1577
0
          expect[len++] = (char) (0xE0 | (u >> 12));
1578
0
          expect[len++] = (char) (0x80 | ((u >> 6) & 0x3F));
1579
0
          expect[len++] = (char) (0x80 | (u & 0x3F));
1580
0
        }
1581
0
        expect[len] = '\0';
1582
0
        ST_FAIL_IF(err, u != 0 && ucs2_check(&unit, 1, expect, HTS_TRUE));
1583
0
      }
1584
0
    }
1585
0
    ST_FAIL_IF(err, ucs2_check(empty, 0, "", HTS_TRUE));
1586
0
    printf("ucs2: %s\n", err ? "FAIL" : "OK");
1587
0
    return err;
1588
0
  }
1589
0
}
1590
1591
0
static int st_arrays(httrackp *opt, int argc, char **argv) {
1592
  /* volatile keeps the sizes below opaque, so these stay runtime checks rather
1593
     than compile-time allocation warnings. */
1594
0
  volatile size_t room;
1595
1596
0
  if (argc >= 1 && strcmp(argv[0], "overflow-capa") == 0) {
1597
    /* Room whose byte size overflows a size_t must abort. */
1598
0
    TypedArray(arrays_wide_t) w = EMPTY_TYPED_ARRAY;
1599
1600
0
    room = ((size_t) -1) / sizeof(arrays_wide_t) + 1;
1601
0
    TypedArrayEnsureRoom(w, room);
1602
    /* Printing the pointer keeps the compiler from folding this away. */
1603
0
    printf("arrays: NOT aborted (%p)\n", TypedArrayPtr(w));
1604
0
    return 1;
1605
0
  } else if (argc >= 1 && strcmp(argv[0], "overflow-loop") == 0) {
1606
    /* Doubling past SIZE_MAX must neither spin nor abort the process. */
1607
0
    TypedArray(char) a = EMPTY_TYPED_ARRAY;
1608
0
    int err = 0;
1609
1610
0
    TypedArrayAppend(a, "kept", 4);
1611
0
    room = (size_t) -1 - TypedArraySize(a);
1612
0
    TypedArrayEnsureRoom(a, room);
1613
0
    ST_FAIL_IF(err, TypedArrayHasRoom(a, room));
1614
    /* An append that cannot fit is a no-op, so existing bytes survive. */
1615
0
    TypedArrayAppend(a, "lost", room);
1616
0
    ST_FAIL_IF(err, TypedArraySize(a) != 4 ||
1617
0
                        memcmp(TypedArrayElts(a), "kept", 4) != 0);
1618
0
    printf("arrays: growth failure %s\n", err ? "FAIL" : "OK");
1619
0
    TypedArrayFree(a);
1620
0
    return err;
1621
0
  } else if (argc >= 1 && strcmp(argv[0], "push") == 0) {
1622
0
    const int err = array_push_selftests();
1623
1624
0
    printf("arrays: push %s\n", err ? "FAIL" : "OK");
1625
0
    return err;
1626
0
  } else if (argc >= 1 && strcmp(argv[0], "reserve-overflow") == 0) {
1627
0
    const int err = array_reserve_overflow_selftests();
1628
1629
0
    printf("arrays: reserve overflow %s\n", err ? "FAIL" : "OK");
1630
0
    return err;
1631
0
  } else if (argc >= 1 && strcmp(argv[0], "at-past-end") == 0) {
1632
0
    TypedArray(char) a = EMPTY_TYPED_ARRAY;
1633
1634
0
    room = 0;
1635
0
    (void) TypedArrayPush(a, 'a');
1636
0
    printf("arrays: NOT aborted (%d)\n", TypedArrayAt(a, room + 1));
1637
0
    TypedArrayFree(a);
1638
0
    return 1;
1639
0
  } else {
1640
0
    const int err = array_growth_selftests();
1641
1642
0
    printf("arrays: %s\n", err ? "FAIL" : "OK");
1643
0
    return err;
1644
0
  }
1645
0
}
1646
1647
0
static int st_random(httrackp *opt, int argc, char **argv) {
1648
0
  enum { want = 64, pad = 16, rounds = 8 };
1649
1650
0
  unsigned char buf[want + pad], first[want], touched[want], varies[want];
1651
0
  int err = 0, live = 0, r, i;
1652
1653
0
  memset(touched, 0, sizeof(touched));
1654
0
  memset(varies, 0, sizeof(varies));
1655
0
  for (r = 0; r < rounds; r++) {
1656
    /* A fixed canary cannot tell a skipped byte from one the fill wrote. */
1657
0
    const unsigned char filler = (unsigned char) (0xa5 + r);
1658
1659
0
    memset(buf, filler, sizeof(buf));
1660
0
    ST_FAIL_IF(err, !hts_random_bytes(buf, want));
1661
0
    for (i = 0; i < want; i++) {
1662
0
      if (buf[i] != filler)
1663
0
        touched[i] = 1;
1664
0
    }
1665
0
    for (i = 0; i < pad; i++) {
1666
      /* wrote past the requested length */
1667
0
      ST_FAIL_IF(err, buf[want + i] != filler);
1668
0
    }
1669
0
    if (r == 0) {
1670
0
      memcpy(first, buf, want);
1671
0
    } else {
1672
0
      for (i = 0; i < want; i++) {
1673
0
        if (buf[i] != first[i])
1674
0
          varies[i] = 1;
1675
0
      }
1676
0
    }
1677
0
  }
1678
0
  for (i = 0; i < want; i++) {
1679
    /* a short fill left this byte alone in every round */
1680
0
    ST_FAIL_IF(err, !touched[i]);
1681
0
    live += varies[i];
1682
0
  }
1683
  /* A stuck or constant source cannot move half the bytes over 8 draws. */
1684
0
  ST_FAIL_IF(err, live < want / 2);
1685
  /* a zero-length ask succeeds and writes nothing */
1686
0
  memset(buf, 0x5a, sizeof(buf));
1687
0
  ST_FAIL_IF(err, !hts_random_bytes(buf, 0));
1688
0
  for (i = 0; i < (int) sizeof(buf); i++) {
1689
0
    ST_FAIL_IF(err, buf[i] != 0x5a);
1690
0
  }
1691
0
  return st_verdict("random", err);
1692
0
}
1693
1694
/* Build a path of exactly len chars under base; returns that length. */
1695
static size_t st_structcheck_longpath(hts_buf dst, const char *base,
1696
0
                                      size_t len) {
1697
0
  size_t n = strlen(base);
1698
1699
0
  assertf(len < dst.size && n + 2 <= len);
1700
0
  memmove(dst.p, base, n);
1701
0
  while (n < len) {
1702
0
    size_t seg = len - n - 1;
1703
1704
0
    if (seg > 200) /* stay under the usual 255-byte component limit */
1705
0
      seg = len - n == 202 ? 199 : 200; /* never leave a bare separator */
1706
0
    dst.p[n++] = '/';
1707
0
    memset(dst.p + n, 'x', seg);
1708
0
    n += seg;
1709
0
  }
1710
0
  dst.p[n] = '\0';
1711
0
  return n;
1712
0
}
1713
1714
/* The path guard, and the <name>.txt rename structcheck() performs when a
1715
   regular file sits where a directory has to go (#745). */
1716
0
static int st_structcheck(httrackp *opt, int argc, char **argv) {
1717
0
  char BIGSTK path[HTS_URLMAXSIZE * 2];
1718
0
  char BIGSTK target[HTS_URLMAXSIZE * 2];
1719
0
  FILE *fp;
1720
1721
  /* over the guard: refused before a single directory is created */
1722
0
  st_structcheck_longpath(HTS_BUF(path), argv[0], HTS_URLMAXSIZE + 1);
1723
0
  errno = 0;
1724
0
  assertf(structcheck(path) == -1);
1725
0
  assertf(errno == EINVAL);
1726
0
  errno = 0;
1727
0
  assertf(structcheck_utf8(path) == -1);
1728
0
  assertf(errno == EINVAL);
1729
0
  {
1730
0
    char *const sep = strchr(path + strlen(argv[0]) + 1, '/');
1731
1732
0
    assertf(sep != NULL);
1733
0
    sep[1] = '\0'; /* the outermost component it would have created */
1734
0
    assertf(!dir_exists(path));
1735
0
  }
1736
1737
  /* a bare file name creates nothing (run from a scratch directory) */
1738
0
  assertf(structcheck("abc.zip") == 0);
1739
0
  assertf(!dir_exists("a/"));
1740
0
  assertf(structcheck_utf8("xyz.zip") == 0);
1741
0
  assertf(!dir_exists("x/"));
1742
  /* a relative path with no existing ancestor is created whole */
1743
0
  assertf(structcheck_utf8("nx/a/b/c") == 0);
1744
0
  assertf(dir_exists("nx/a/b/"));
1745
1746
  /* a regular file where a directory belongs is renamed to <name>.txt */
1747
0
  snprintf(path, sizeof(path), "%s/sc", argv[0]);
1748
0
  fp = fopen(path, "wb");
1749
0
  assertf(fp != NULL);
1750
0
  fclose(fp);
1751
0
  snprintf(path, sizeof(path), "%s/sc/sub/", argv[0]);
1752
0
  assertf(structcheck(path) == 0);
1753
0
  assertf(dir_exists(path));
1754
0
  snprintf(target, sizeof(target), "%s/sc.txt", argv[0]);
1755
0
  assertf(fexist(target));
1756
1757
  /* the utf-8 entry point carries the same rename */
1758
0
  snprintf(path, sizeof(path), "%s/u8", argv[0]);
1759
0
  fp = FOPEN(path, "wb");
1760
0
  assertf(fp != NULL);
1761
0
  fclose(fp);
1762
0
  snprintf(path, sizeof(path), "%s/u8/sub/", argv[0]);
1763
0
  assertf(structcheck_utf8(path) == 0);
1764
0
  assertf(dir_exists(path));
1765
0
  snprintf(target, sizeof(target), "%s/u8.txt", argv[0]);
1766
0
  assertf(fexist_utf8(target));
1767
1768
  /* A deep path is created, and a file in its way is moved aside. */
1769
0
  snprintf(path, sizeof(path), "%s/d1/d2/d3/d4/", argv[0]);
1770
0
  assertf(structcheck_utf8(path) == 0);
1771
0
  assertf(dir_exists(path));
1772
0
  snprintf(path, sizeof(path), "%s/d1/f", argv[0]);
1773
0
  fp = FOPEN(path, "wb");
1774
0
  assertf(fp != NULL);
1775
0
  fclose(fp);
1776
0
  snprintf(path, sizeof(path), "%s/d1/f/x/y/z", argv[0]);
1777
0
  assertf(structcheck_utf8(path) == 0);
1778
0
  snprintf(path, sizeof(path), "%s/d1/f/x/y/", argv[0]);
1779
0
  assertf(dir_exists(path));
1780
0
  snprintf(target, sizeof(target), "%s/d1/f.txt", argv[0]);
1781
0
  assertf(fexist_utf8(target));
1782
1783
  /* an existing <name>.txt is never replaced */
1784
0
  for (int u8 = 0; u8 < 2; u8++) {
1785
0
    const char *const nm = u8 ? "k8" : "kp";
1786
0
    char got[16];
1787
1788
0
    snprintf(path, sizeof(path), "%s/%s.txt", argv[0], nm);
1789
0
    fp = FOPEN(path, "wb");
1790
0
    assertf(fp != NULL);
1791
0
    fputs("KEEP", fp);
1792
0
    fclose(fp);
1793
0
    snprintf(path, sizeof(path), "%s/%s.1.txt", argv[0], nm);
1794
0
    fp = FOPEN(path, "wb");
1795
0
    assertf(fp != NULL);
1796
0
    fputs("TAKEN", fp);
1797
0
    fclose(fp);
1798
0
    snprintf(path, sizeof(path), "%s/%s", argv[0], nm);
1799
0
    fp = FOPEN(path, "wb");
1800
0
    assertf(fp != NULL);
1801
0
    fputs("PAGE", fp);
1802
0
    fclose(fp);
1803
0
    snprintf(path, sizeof(path), "%s/%s/sub/", argv[0], nm);
1804
0
    assertf((u8 ? structcheck_utf8(path) : structcheck(path)) == 0);
1805
0
    assertf(dir_exists(path));
1806
0
    snprintf(path, sizeof(path), "%s/%s.txt", argv[0], nm);
1807
0
    fp = FOPEN(path, "rb");
1808
0
    assertf(fp != NULL);
1809
0
    memset(got, 0, sizeof(got));
1810
0
    assertf(fread(got, 1, 4, fp) == 4 && memcmp(got, "KEEP", 4) == 0);
1811
0
    fclose(fp);
1812
0
    snprintf(path, sizeof(path), "%s/%s.2.txt", argv[0], nm);
1813
0
    fp = FOPEN(path, "rb");
1814
0
    assertf(fp != NULL);
1815
0
    assertf(fread(got, 1, 4, fp) == 4 && memcmp(got, "PAGE", 4) == 0);
1816
0
    fclose(fp);
1817
0
  }
1818
1819
0
  printf("structcheck self-test OK\n");
1820
0
  return 0;
1821
0
}
1822
1823
/* hts_gmtime() must not share gmtime()'s static buffer (#794). */
1824
0
#define GMTIME_THREADS 8
1825
0
#define GMTIME_ROUNDS 50000
1826
1827
static const struct {
1828
  time_t t;
1829
  int year, mon, mday, hour, min, sec, wday, yday;
1830
} gmtime_refs[] = {
1831
    {(time_t) 0, 70, 0, 1, 0, 0, 0, 4, 0},
1832
    {(time_t) 951782400, 100, 1, 29, 0, 0, 0, 2, 59}, /* a leap day */
1833
    {(time_t) 1000000000, 101, 8, 9, 1, 46, 40, 0, 251},
1834
    {(time_t) 2147483647, 138, 0, 19, 3, 14, 7, 2, 18}, /* 32-bit ceiling */
1835
};
1836
1837
0
#define GMTIME_REFS ((int) (sizeof(gmtime_refs) / sizeof(gmtime_refs[0])))
1838
1839
0
static hts_boolean gmtime_ref_matches(int i, const struct tm *tm) {
1840
0
  if (tm->tm_year != gmtime_refs[i].year || tm->tm_mon != gmtime_refs[i].mon ||
1841
0
      tm->tm_mday != gmtime_refs[i].mday ||
1842
0
      tm->tm_hour != gmtime_refs[i].hour || tm->tm_min != gmtime_refs[i].min ||
1843
0
      tm->tm_sec != gmtime_refs[i].sec || tm->tm_wday != gmtime_refs[i].wday ||
1844
0
      tm->tm_yday != gmtime_refs[i].yday)
1845
0
    return HTS_FALSE;
1846
0
  return HTS_TRUE;
1847
0
}
1848
1849
static htsmutex gmtime_lock = HTSMUTEX_INIT;
1850
static int gmtime_bad = 0;
1851
1852
0
static void gmtime_thread(void *arg) {
1853
0
  const int i = *(const int *) arg;
1854
0
  int bad = 0, round;
1855
1856
0
  for (round = 0; round < GMTIME_ROUNDS; round++) {
1857
0
    struct tm tmv;
1858
1859
0
    if (!hts_gmtime(gmtime_refs[i].t, &tmv) || !gmtime_ref_matches(i, &tmv))
1860
0
      bad++;
1861
0
  }
1862
0
  hts_mutexlock(&gmtime_lock);
1863
0
  gmtime_bad += bad;
1864
0
  hts_mutexrelease(&gmtime_lock);
1865
0
}
1866
1867
0
static int st_gmtime(httrackp *opt, int argc, char **argv) {
1868
0
  static int idx[GMTIME_THREADS];
1869
0
  int err = 0, i;
1870
1871
0
  for (i = 0; i < GMTIME_REFS; i++) {
1872
0
    struct tm tmv;
1873
1874
0
    if (!hts_gmtime(gmtime_refs[i].t, &tmv)) {
1875
0
      fprintf(stderr, "gmtime: conversion #%d failed\n", i);
1876
0
      err = 1;
1877
0
    } else if (!gmtime_ref_matches(i, &tmv)) {
1878
0
      fprintf(stderr,
1879
0
              "gmtime: #%d gave %04d-%02d-%02d %02d:%02d:%02d (wday %d, "
1880
0
              "yday %d)\n",
1881
0
              i, tmv.tm_year + 1900, tmv.tm_mon + 1, tmv.tm_mday, tmv.tm_hour,
1882
0
              tmv.tm_min, tmv.tm_sec, tmv.tm_wday, tmv.tm_yday);
1883
0
      err = 1;
1884
0
    }
1885
0
  }
1886
1887
  /* Callers detect failure only from the return value. */
1888
0
  if (sizeof(time_t) >= 8) {
1889
0
    const time_t beyond = (time_t) INT64_MAX;
1890
0
    struct tm tmv;
1891
1892
0
    if (hts_gmtime(beyond, &tmv)) {
1893
0
      fprintf(stderr,
1894
0
              "gmtime: an out-of-range time_t was reported converted\n");
1895
0
      err = 1;
1896
0
    }
1897
0
  }
1898
1899
0
  for (i = 0; i < GMTIME_THREADS; i++) {
1900
0
    idx[i] = i % GMTIME_REFS;
1901
0
    if (hts_newthread_checked(gmtime_thread, &idx[i]) != 0) {
1902
0
      fprintf(stderr, "gmtime: cannot spawn\n");
1903
0
      return 1;
1904
0
    }
1905
0
  }
1906
0
  htsthread_wait();
1907
0
  if (gmtime_bad != 0) {
1908
0
    fprintf(stderr, "gmtime: %d/%d concurrent conversions were corrupt\n",
1909
0
            gmtime_bad, GMTIME_THREADS * GMTIME_ROUNDS);
1910
0
    err = 1;
1911
0
  }
1912
1913
0
  return st_verdict("gmtime self-test", err);
1914
0
}
1915
1916
/* Is the masked in exactly want? Prints the difference when it is not. */
1917
0
static int maskpw_row(const char *in, const char *want, hts_mask_mode mode) {
1918
0
  char *got = hts_mask_passwords(in, mode);
1919
0
  const int err = got == NULL || strcmp(got, want) != 0;
1920
1921
0
  if (err)
1922
0
    fprintf(stderr, "maskpw: '%.80s' gave '%.80s', want '%.80s'\n", in,
1923
0
            got != NULL ? got : "(null)", want);
1924
0
  freet(got);
1925
0
  return err;
1926
0
}
1927
1928
/* A hostile URL of n ":@" pairs: in a path it stays, in a userinfo it is one
1929
   password. */
1930
0
static int maskpw_pairs(size_t n) {
1931
0
  const size_t len = 2 * n;
1932
0
  char *pairs = (char *) malloct(len + 1);
1933
0
  char *in = (char *) malloct(len + 32);
1934
0
  int err;
1935
1936
0
  if (pairs == NULL || in == NULL) {
1937
0
    freet(pairs);
1938
0
    freet(in);
1939
0
    return 1;
1940
0
  }
1941
0
  memset(pairs, ':', len);
1942
0
  for (size_t i = 1; i < len; i += 2)
1943
0
    pairs[i] = '@';
1944
0
  pairs[len] = '\0';
1945
0
  snprintf(in, len + 32, "http://h/x?%s", pairs);
1946
0
  err = maskpw_row(in, in, HTS_MASK_LIST);
1947
0
  snprintf(in, len + 32, "a%sh/ -x", pairs);
1948
0
  err |= maskpw_row(in, "a:***@h/ -x", HTS_MASK_LIST);
1949
0
  snprintf(in, len + 32, "http://a%sh", pairs);
1950
0
  err |= maskpw_row(in, "http://a:***@h", HTS_MASK_ADDR);
1951
0
  freet(pairs);
1952
0
  freet(in);
1953
0
  return err;
1954
0
}
1955
1956
/* Do the nologin helpers hide the password and nothing else? */
1957
0
static int nologin_rows(httrackp *opt) {
1958
0
  static const struct {
1959
0
    const char *in, *want;
1960
0
  } adrs[] = {{"u:p@h:80", "u:***@h:80"}, {"u:p@q@h", "u:***@h"},
1961
0
              {"u@h", "***@h"},           {":p@h", ":***@h"},
1962
0
              {"h:80", "h:80"},           {"file://", "file://"},
1963
0
              {"https://h", "https://h"}, {"https://u:p@h", "https://u:***@h"}},
1964
0
    urls[] = {{"http://u:p@h/x", "http://u:***@h/x"},
1965
0
              {"//u:p@q@h", "//u:***@h"},
1966
0
              {"http://tok@h/x", "http://***@h/x"},
1967
0
              {"HTTPS://u:a b@[::1]:8/", "HTTPS://u:***@[::1]:8/"},
1968
0
              {"http://h/x?a@b", "http://h/x?a@b"},
1969
0
              {"mailto:a@b", "mailto:a@b"},
1970
0
              {"u:p@h/x", "u:p@h/x"},
1971
0
              {"http://u:p@hostname.example/x", "http://u:***@hostname.e"}};
1972
1973
0
  char buf[24];
1974
0
  const int index = opt->state.concat.index;
1975
0
  int err = 0;
1976
0
  size_t i;
1977
1978
0
  for (i = 0; i < sizeof(adrs) / sizeof(adrs[0]); i++) {
1979
0
    const char *got = adr_nologin_r(HTS_BUF(buf), adrs[i].in);
1980
1981
0
    if (strcmp(got, adrs[i].want) != 0) {
1982
0
      fprintf(stderr, "adr_nologin: '%s' gave '%s'\n", adrs[i].in, got);
1983
0
      err = 1;
1984
0
    }
1985
0
  }
1986
0
  for (i = 0; i < sizeof(urls) / sizeof(urls[0]); i++) {
1987
0
    const char *got = url_nologin_r(HTS_BUF(buf), urls[i].in);
1988
1989
0
    if (strcmp(got, urls[i].want) != 0) {
1990
0
      fprintf(stderr, "url_nologin: '%s' gave '%s'\n", urls[i].in, got);
1991
0
      err = 1;
1992
0
    }
1993
0
  }
1994
  /* An address without a login is returned as is, and takes no buffer. */
1995
0
  if (adr_nologin(opt, adrs[4].in) != adrs[4].in ||
1996
0
      url_nologin(opt, urls[6].in) != urls[6].in ||
1997
0
      opt->state.concat.index != index) {
1998
0
    fprintf(stderr, "nologin: a rotating buffer was taken without a login\n");
1999
0
    err = 1;
2000
0
  }
2001
  /* Without an opt, as back_delete(NULL, ...) logs, the login is dropped. */
2002
0
  if (strcmp(adr_nologin(NULL, urls[0].in), "h/x") != 0 ||
2003
0
      strcmp(url_nologin(NULL, urls[0].in), "h/x") != 0) {
2004
0
    fprintf(stderr, "nologin: a NULL opt kept the login\n");
2005
0
    err = 1;
2006
0
  }
2007
0
  if (strcmp(adr_nologin(opt, NULL), "") != 0) {
2008
0
    fprintf(stderr, "nologin: a NULL address did not read as empty\n");
2009
0
    err = 1;
2010
0
  }
2011
0
  return err;
2012
0
}
2013
2014
/* Reads back the log of o, from offset at, into buf. */
2015
0
static void secrets_read(FILE *fp, long at, hts_buf buf) {
2016
0
  size_t n;
2017
2018
0
  fflush(fp);
2019
0
  fseek(fp, at, SEEK_SET);
2020
0
  n = fread(buf.p, 1, buf.size - 1, fp);
2021
0
  buf.p[n] = '\0';
2022
0
  fseek(fp, 0, SEEK_END);
2023
0
}
2024
2025
/* Logs line through o and checks the log holds want, and none of bad. */
2026
static int secrets_row(httrackp *o, FILE *fp, const char *line,
2027
0
                       const char *want, const char *bad) {
2028
0
  char got[4096];
2029
0
  const long at = ftell(fp);
2030
2031
0
  hts_log_print(o, LOG_NOTICE, "%s", line);
2032
0
  secrets_read(fp, at, HTS_BUF(got));
2033
0
  if (strstr(got, want) == NULL || (bad != NULL && strstr(got, bad) != NULL)) {
2034
0
    fprintf(stderr, "secrets: '%s' logged '%s', want '%s'\n", line, got, want);
2035
0
    return 1;
2036
0
  }
2037
0
  return 0;
2038
0
}
2039
2040
/* A hostile page offers 200 passwords, each twice: the first
2041
   HTS_SECRET_MAX stay hidden, and one warning says so. */
2042
0
static int secrets_full(void) {
2043
0
  httrackp *const o = hts_create_opt();
2044
0
  FILE *const fp = tmpfile();
2045
0
  char got[4096];
2046
0
  const char *w;
2047
0
  int err = 0, i;
2048
2049
0
  if (o == NULL || fp == NULL) {
2050
0
    fprintf(stderr, "secrets: out of memory\n");
2051
0
    if (fp != NULL)
2052
0
      fclose(fp);
2053
0
    if (o != NULL)
2054
0
      hts_free_opt(o);
2055
0
    return 1;
2056
0
  }
2057
0
  o->log = fp;
2058
0
  o->debug = LOG_DEBUG;
2059
0
  for (i = 0; i < 200; i++) {
2060
0
    char url[64];
2061
2062
0
    snprintf(url, sizeof(url), "http://u:ZPWCAP%03d@h/", i);
2063
0
    hts_secret_add_login(o, url);
2064
0
    hts_secret_add_login(o, url);
2065
0
  }
2066
0
  hts_log_print(o, LOG_NOTICE, "u:ZPWCAP000@h u:ZPWCAP%03d@h u:ZPWCAP%03d@h",
2067
0
                HTS_SECRET_MAX - 1, HTS_SECRET_MAX);
2068
0
  secrets_read(fp, 0, HTS_BUF(got));
2069
0
  w = strstr(got, "passwords seen");
2070
0
  if (strstr(got, "u:***@h u:***@h u:ZPWCAP064@h") == NULL || w == NULL ||
2071
0
      strstr(w + 1, "passwords seen") != NULL) {
2072
0
    fprintf(stderr, "secrets: full set logged '%s'\n", got);
2073
0
    err = 1;
2074
0
  }
2075
0
  o->log = NULL;
2076
0
  fclose(fp);
2077
0
  hts_free_opt(o);
2078
0
  return err;
2079
0
}
2080
2081
/* Prints S with CR and LF spelt out. */
2082
0
static void secretheaders_print(const char *s) {
2083
0
  for (; *s != '\0'; s++)
2084
0
    if (*s == '\r' || *s == '\n')
2085
0
      printf("%s", *s == '\r' ? "\\r" : "\\n");
2086
0
    else
2087
0
      putchar(*s);
2088
0
}
2089
2090
/* Prints, per argument, the tokens learnt, then the shown and logged forms. */
2091
0
static int st_secretheaders(httrackp *opt, int argc, char **argv) {
2092
0
  int a;
2093
2094
0
  (void) opt;
2095
0
  for (a = 0; a < argc; a++) {
2096
0
    httrackp *const o = hts_create_opt();
2097
0
    FILE *const fp = tmpfile();
2098
0
    char text[128], probe[128], got[1024];
2099
0
    size_t n, i, j;
2100
2101
0
    if (o == NULL || fp == NULL) {
2102
0
      fprintf(stderr, "secretheaders: out of memory\n");
2103
0
      if (fp != NULL)
2104
0
        fclose(fp);
2105
0
      if (o != NULL)
2106
0
        hts_free_opt(o);
2107
0
      return 1;
2108
0
    }
2109
0
    if (st_decode_body(argv[a], HTS_BUF(text)) + 1 >= sizeof(text)) {
2110
0
      fprintf(stderr, "secretheaders: input over %d bytes\n",
2111
0
              (int) sizeof(text) - 2);
2112
0
      fclose(fp);
2113
0
      hts_free_opt(o);
2114
0
      return 1;
2115
0
    }
2116
0
    n = strlen(text);
2117
0
    hts_secret_add_headers(o, text);
2118
0
    for (i = 0; i < n; i++)
2119
0
      for (j = i + HTS_SECRET_TOKEN; j <= n; j++) {
2120
0
        memcpy(probe, text + i, j - i);
2121
0
        probe[j - i] = '\0';
2122
0
        hts_hide_secrets(o, probe, sizeof(probe));
2123
0
        if (strcmp(probe, "***") == 0)
2124
0
          printf("[%.*s]", (int) (j - i), text + i);
2125
0
      }
2126
0
    printf(" shown=");
2127
0
    secretheaders_print(hts_header_shown(o, text, HTS_BUF(got)));
2128
0
    fprintfio(fp, text, "> ", o);
2129
0
    secrets_read(fp, 0, HTS_BUF(got));
2130
0
    printf(" log=");
2131
0
    secretheaders_print(got);
2132
0
    printf("\n");
2133
0
    fclose(fp);
2134
0
    hts_free_opt(o);
2135
0
  }
2136
0
  return 0;
2137
0
}
2138
2139
/* Prints the slices of TEXT the log masks, its -%H log, and its shown form. */
2140
0
static int st_secretslices(httrackp *opt, int argc, char **argv) {
2141
0
  httrackp *const o = hts_create_opt();
2142
0
  FILE *const fp = tmpfile();
2143
0
  char headers[128], text[128], probe[128], got[1024];
2144
0
  const size_t size = argc > 3 ? (size_t) atoi(argv[3]) : 0;
2145
0
  size_t n, i, j;
2146
0
  int err = 0;
2147
2148
0
  (void) opt;
2149
0
  if (argc < 3 || o == NULL || fp == NULL || size > sizeof(got) ||
2150
0
      st_decode_body(argv[1], HTS_BUF(headers)) + 1 >= sizeof(headers) ||
2151
0
      st_decode_body(argv[2], HTS_BUF(text)) + 1 >= sizeof(text)) {
2152
0
    fprintf(stderr, "secretslices: bad arguments\n");
2153
0
    err = 1;
2154
0
  } else {
2155
0
    hts_secret_add_login(o, argv[0]);
2156
0
    hts_secret_add_headers(o, headers);
2157
0
    n = strlen(text);
2158
0
    for (i = 0; i < n; i++)
2159
0
      for (j = i + 1; j <= n; j++) {
2160
0
        memcpy(probe, text + i, j - i);
2161
0
        probe[j - i] = '\0';
2162
0
        hts_hide_secrets(o, probe, sizeof(probe));
2163
0
        if (strncmp(probe, text + i, j - i) != 0 || probe[j - i] != '\0') {
2164
0
          printf("[%u,%u=", (unsigned) i, (unsigned) j);
2165
0
          secretheaders_print(probe);
2166
0
          printf("]");
2167
0
        }
2168
0
      }
2169
0
    fprintfio(fp, text, "> ", o);
2170
0
    secrets_read(fp, 0, HTS_BUF(got));
2171
0
    printf(" log=");
2172
0
    secretheaders_print(got);
2173
0
    if (size != 0) {
2174
0
      printf(" shown=");
2175
0
      secretheaders_print(hts_header_shown(o, text, hts_buf_at(got, size)));
2176
0
    }
2177
0
    printf("\n");
2178
0
  }
2179
0
  if (fp != NULL)
2180
0
    fclose(fp);
2181
0
  if (o != NULL)
2182
0
    hts_free_opt(o);
2183
0
  return err;
2184
0
}
2185
2186
0
static int st_secrets(httrackp *opt, int argc, char **argv) {
2187
0
  httrackp *const o = hts_create_opt();
2188
0
  FILE *const fp = tmpfile();
2189
0
  char got[4096];
2190
0
  char big[HTS_SECRET_MAXLEN + 16];
2191
0
  const char *w;
2192
0
  long at;
2193
0
  int err = 0;
2194
2195
0
  if (o == NULL || fp == NULL) {
2196
0
    fprintf(stderr, "secrets: out of memory\n");
2197
0
    if (fp != NULL)
2198
0
      fclose(fp);
2199
0
    if (o != NULL)
2200
0
      hts_free_opt(o);
2201
0
    return 1;
2202
0
  }
2203
0
  o->log = fp;
2204
0
  o->debug = LOG_DEBUG;
2205
  // none known: the line goes out as given
2206
0
  err |= secrets_row(o, fp, "a u:index@h/index.html", "a u:index@h/index.html",
2207
0
                     NULL);
2208
  // a password is hidden only as a login, at any length
2209
0
  hts_secret_add_login(o, "http://u:index@h/");
2210
0
  hts_secret_add_login(o, "http://u:download@h/");
2211
0
  err |= secrets_row(o, fp,
2212
0
                     "a u:index@h/index.html http://index.example/ index@h "
2213
0
                     "myindex@h /index (index@h <x:index@h \"index@h",
2214
0
                     "a u:***@h/index.html http://index.example/ ***@h "
2215
0
                     "myindex@h /index (***@h <x:***@h \"***@h",
2216
0
                     NULL);
2217
0
  err |= secrets_row(o, fp,
2218
0
                     "GET /download/file.html ftp://download@h u:download@h",
2219
0
                     "GET /download/file.html ftp://***@h u:***@h", NULL);
2220
  // an address is no login
2221
0
  err |= secrets_row(o, fp,
2222
0
                     "mailto:index@h MAILTO:index@h news:index@h "
2223
0
                     "a@index@h //x:index@h",
2224
0
                     "mailto:index@h MAILTO:index@h news:index@h "
2225
0
                     "a@index@h //x:index@h",
2226
0
                     NULL);
2227
  // a token is hidden anywhere, a short one not at all
2228
0
  hts_secret_add_headers(o, "X-Keep: ZPWKEEP12345\r\n"
2229
0
                            "Authorization: Bearer ZPWTOKEN123\r\n"
2230
0
                            "cookie: a=1; sid=ZPWSID9999\r\n"
2231
0
                            "Proxy-Authorization Basic ZPWNOCOLON1\r\n"
2232
0
                            "Authorization: Bearer ZPWSHRT");
2233
0
  err |= secrets_row(o, fp,
2234
0
                     "GET /x?t=ZPWTOKEN123&s=ZPWSID9999 a=1 ZPWKEEP12345 "
2235
0
                     "ZPWNOCOLON1 ZPWSHRT u:ZPWSHRT@h",
2236
0
                     "GET /x?t=***&s=ZPWSID9999 a=1 ZPWKEEP12345 *** ZPWSHRT "
2237
0
                     "u:ZPWSHRT@h",
2238
0
                     NULL);
2239
  // raw and unescaped, the way Basic sends it
2240
0
  hts_secret_add_login(o, "ftp://u:ZPW%40ESC99@h/");
2241
0
  err |= secrets_row(o, fp, "u:ZPW%40ESC99@h u:ZPW@ESC99@h ZPW%40ESC99",
2242
0
                     "u:***@h u:***@h ZPW%40ESC99", NULL);
2243
  // the user part of a login may hold an '@'
2244
0
  hts_secret_add_login(o, "http://john@example.com:ZPWATPW99@h/");
2245
0
  err |= secrets_row(o, fp, "http://john@example.com:ZPWATPW99@h/ ZPWATPW99",
2246
0
                     "http://john@example.com:***@h/ ZPWATPW99", NULL);
2247
  // a cookie value is no token: it is often an ordinary word
2248
0
  hts_secret_add_headers(o, "Cookie: consent=zpwaccepted\r\n");
2249
0
  err |=
2250
0
      secrets_row(o, fp, "/privacy/zpwaccepted-terms.html consent=zpwaccepted",
2251
0
                  "/privacy/zpwaccepted-terms.html consent=zpwaccepted", NULL);
2252
  // a user alone is no password
2253
0
  hts_secret_add_login(o, "http://ZPWUSERONLY@h/");
2254
0
  err |= secrets_row(o, fp, "ZPWUSERONLY@h", "ZPWUSERONLY@h", NULL);
2255
  // the unescaped login is learnt while the escaped one is under the cap
2256
0
  {
2257
0
    char url[sizeof(big) + 16], line[sizeof(big) + 16];
2258
0
    size_t n;
2259
2260
0
    for (n = HTS_SECRET_MAXLEN - 1; n <= HTS_SECRET_MAXLEN; n++) {
2261
0
      const hts_boolean fits = n < HTS_SECRET_MAXLEN;
2262
2263
0
      memset(big, fits ? 'F' : 'G', n);
2264
0
      memcpy(big, "%41", 3);
2265
0
      big[n] = '\0';
2266
0
      snprintf(url, sizeof(url), "http://u:%s@h/", big);
2267
0
      hts_secret_add_login(o, url);
2268
0
      snprintf(line, sizeof(line), "u:A%s@h", big + 3);
2269
0
      err |= secrets_row(o, fp, line, fits ? "u:***@h" : line,
2270
0
                         fits ? NULL : "***");
2271
0
    }
2272
0
  }
2273
  // too long to keep: one warning
2274
0
  memset(big, 'Z', sizeof(big) - 1);
2275
0
  big[sizeof(big) - 1] = '\0';
2276
0
  at = ftell(fp);
2277
0
  hts_secret_add(o, hts_span_at(big, HTS_SECRET_MAXLEN + 1), HTS_SECRET_HEADER);
2278
0
  hts_secret_add(o, hts_span_at(big + 1, HTS_SECRET_MAXLEN + 1),
2279
0
                 HTS_SECRET_LOGIN);
2280
0
  secrets_read(fp, at, HTS_BUF(got));
2281
0
  w = strstr(got, "over 1024 bytes");
2282
0
  if (w == NULL || strstr(w + 1, "over 1024 bytes") != NULL) {
2283
0
    fprintf(stderr, "secrets: a long secret logged '%s'\n", got);
2284
0
    err = 1;
2285
0
  }
2286
0
  err |= secrets_row(o, fp, big, big, "***");
2287
  // the -%H log and a front end's own buffer
2288
0
  at = ftell(fp);
2289
0
  fprintfio(fp, "GET /?k=ZPWTOKEN123 HTTP/1.1\r\nX-K: ZPWTOKEN123\r\n", "<<< ",
2290
0
            o);
2291
0
  secrets_read(fp, at, HTS_BUF(got));
2292
0
  if (strcmp(got, "<<< GET /?k=*** HTTP/1.1\r\n<<< X-K: ***\r\n") != 0) {
2293
0
    fprintf(stderr, "secrets: fprintfio wrote '%s'\n", got);
2294
0
    err = 1;
2295
0
  }
2296
0
  strcpybuff(got, "h/x?t=ZPWTOKEN123");
2297
0
  hts_hide_secrets(o, got, sizeof(got));
2298
0
  if (strcmp(got, "h/x?t=***") != 0) {
2299
0
    fprintf(stderr, "secrets: hts_hide_secrets gave '%s'\n", got);
2300
0
    err = 1;
2301
0
  }
2302
0
  o->log = NULL;
2303
0
  fclose(fp);
2304
0
  hts_free_opt(o);
2305
0
  err |= secrets_full();
2306
0
  return st_verdict("secrets self-test", err);
2307
0
}
2308
2309
0
static int st_maskpw(httrackp *opt, int argc, char **argv) {
2310
0
  static const struct {
2311
0
    hts_mask_mode mode;
2312
0
    const char *in, *want;
2313
0
  } rows[] = {
2314
0
      {HTS_MASK_LIST, "", ""},
2315
0
      {HTS_MASK_LIST, "u:p@h http://v:q@g +*:*@* -*:*@*/x",
2316
0
       "u:***@h http://v:***@g +*:*@* -*:*@*/x"},
2317
0
      {HTS_MASK_LIST, "HTTP://u:p@h:80/x ftp://u:p@h",
2318
0
       "HTTP://u:***@h:80/x ftp://u:***@h"},
2319
0
      {HTS_MASK_LIST, "http://h1/ http://h/?r=ftp://u:p@g/",
2320
0
       "http://h1/ http://h/?r=ftp://u:p@g/"},
2321
0
      {HTS_MASK_LIST, "http://h/x?t=10:30@x", "http://h/x?t=10:30@x"},
2322
0
      {HTS_MASK_ADDR, "http://u:p@h/", "http://u:***@h/"},
2323
0
      {HTS_MASK_ADDR, "http://u@h/", "http://***@h/"},
2324
0
      {HTS_MASK_ADDR, "http://:p@h/", "http://:***@h/"},
2325
0
      {HTS_MASK_ADDR, "http://u:@h/", "http://u:***@h/"},
2326
      // the engine splits the userinfo at the last '@'
2327
0
      {HTS_MASK_ADDR, "http://u:p@SECRETB@h/", "http://u:***@h/"},
2328
0
      {HTS_MASK_ADDR, "http://user:pw;SECRETA@h/", "http://user:***@h/"},
2329
0
      {HTS_MASK_ADDR, "http://u:a,b=c\"d'e(f)<g> h@h/", "http://u:***@h/"},
2330
0
      {HTS_MASK_ADDR, "http://u:a%2Fb@h/", "http://u:***@h/"},
2331
      // a raw '/' ends the authority, so the engine sends no password
2332
0
      {HTS_MASK_ADDR, "http://u:a/b@h/", "http://u:a/b@h/"},
2333
0
      {HTS_MASK_ADDR, "u:p@h:8080", "u:***@h:8080"},
2334
0
      {HTS_MASK_ADDR, "u:p@q@h:8080", "u:***@h:8080"},
2335
0
      {HTS_MASK_ADDR, "u:a b@h/", "u:***@h/"},
2336
0
      {HTS_MASK_ADDR, "http://u:p@h:8080", "http://u:***@h:8080"},
2337
0
      {HTS_MASK_ADDR, "h:8080", "h:8080"},
2338
0
      {HTS_MASK_ADDR, "u@h:8080", "***@h:8080"},
2339
0
      {HTS_MASK_LIST, "tok@h/ http://tok@g/ +*@g/*",
2340
0
       "***@h/ http://***@g/ +*@g/*"},
2341
0
  };
2342
2343
0
  static const char *const modes[] = {"list", "addr"};
2344
0
  int err = 0;
2345
0
  size_t i;
2346
2347
0
  if (argc >= 2) {
2348
0
    char *got = NULL;
2349
2350
0
    for (i = 0; i < sizeof(modes) / sizeof(modes[0]); i++)
2351
0
      if (strcmp(argv[0], modes[i]) == 0)
2352
0
        got = hts_mask_passwords(argv[1], (hts_mask_mode) i);
2353
0
    if (got == NULL)
2354
0
      return 1;
2355
0
    printf("%s\n", got);
2356
0
    freet(got);
2357
0
    return 0;
2358
0
  }
2359
0
  for (i = 0; i < sizeof(rows) / sizeof(rows[0]); i++)
2360
0
    err |= maskpw_row(rows[i].in, rows[i].want, rows[i].mode);
2361
0
  err |= nologin_rows(opt);
2362
0
  err |= maskpw_pairs(300);
2363
0
  err |= maskpw_pairs(10000);
2364
0
  return st_verdict("maskpw self-test", err);
2365
0
}
2366
2367
/* #806: hts_localtime() must own its output too, same rationale as
2368
   hts_gmtime() (#794). Reference table computed under TZ=XXX5 (fixed
2369
   UTC-5, no DST), which the driving .test script sets. */
2370
0
#define LOCALTIME_THREADS 8
2371
0
#define LOCALTIME_ROUNDS 50000
2372
2373
static const struct {
2374
  time_t t;
2375
  int year, mon, mday, hour, min, sec, wday, yday;
2376
} localtime_refs[] = {
2377
    {(time_t) 0, 69, 11, 31, 19, 0, 0, 3, 364},
2378
    {(time_t) 951782400, 100, 1, 28, 19, 0, 0, 1,
2379
     58}, /* a leap day, GMT side */
2380
    {(time_t) 1000000000, 101, 8, 8, 20, 46, 40, 6, 250},
2381
    {(time_t) 2147483647, 138, 0, 18, 22, 14, 7, 1, 17},
2382
};
2383
2384
#define LOCALTIME_REFS                                                         \
2385
0
  ((int) (sizeof(localtime_refs) / sizeof(localtime_refs[0])))
2386
2387
0
static hts_boolean localtime_ref_matches(int i, const struct tm *tm) {
2388
0
  if (tm->tm_year != localtime_refs[i].year ||
2389
0
      tm->tm_mon != localtime_refs[i].mon ||
2390
0
      tm->tm_mday != localtime_refs[i].mday ||
2391
0
      tm->tm_hour != localtime_refs[i].hour ||
2392
0
      tm->tm_min != localtime_refs[i].min ||
2393
0
      tm->tm_sec != localtime_refs[i].sec ||
2394
0
      tm->tm_wday != localtime_refs[i].wday ||
2395
0
      tm->tm_yday != localtime_refs[i].yday)
2396
0
    return HTS_FALSE;
2397
0
  return HTS_TRUE;
2398
0
}
2399
2400
static htsmutex localtime_lock = HTSMUTEX_INIT;
2401
static int localtime_bad = 0;
2402
2403
0
static void localtime_thread(void *arg) {
2404
0
  const int i = *(const int *) arg;
2405
0
  int bad = 0, round;
2406
2407
0
  for (round = 0; round < LOCALTIME_ROUNDS; round++) {
2408
0
    struct tm tmv;
2409
2410
0
    if (!hts_localtime(localtime_refs[i].t, &tmv) ||
2411
0
        !localtime_ref_matches(i, &tmv))
2412
0
      bad++;
2413
0
  }
2414
0
  hts_mutexlock(&localtime_lock);
2415
0
  localtime_bad += bad;
2416
0
  hts_mutexrelease(&localtime_lock);
2417
0
}
2418
2419
0
static int st_localtime(httrackp *opt, int argc, char **argv) {
2420
0
  static int idx[LOCALTIME_THREADS];
2421
0
  int err = 0, i;
2422
2423
0
  for (i = 0; i < LOCALTIME_REFS; i++) {
2424
0
    struct tm tmv;
2425
2426
0
    if (!hts_localtime(localtime_refs[i].t, &tmv)) {
2427
0
      fprintf(stderr, "localtime: conversion #%d failed\n", i);
2428
0
      err = 1;
2429
0
    } else if (!localtime_ref_matches(i, &tmv)) {
2430
0
      fprintf(stderr,
2431
0
              "localtime: #%d gave %04d-%02d-%02d %02d:%02d:%02d (wday %d, "
2432
0
              "yday %d)\n",
2433
0
              i, tmv.tm_year + 1900, tmv.tm_mon + 1, tmv.tm_mday, tmv.tm_hour,
2434
0
              tmv.tm_min, tmv.tm_sec, tmv.tm_wday, tmv.tm_yday);
2435
0
      err = 1;
2436
0
    }
2437
0
  }
2438
2439
0
  if (sizeof(time_t) >= 8) {
2440
0
    const time_t beyond = (time_t) INT64_MAX;
2441
0
    struct tm tmv;
2442
2443
0
    if (hts_localtime(beyond, &tmv)) {
2444
0
      fprintf(stderr,
2445
0
              "localtime: an out-of-range time_t was reported converted\n");
2446
0
      err = 1;
2447
0
    }
2448
0
  }
2449
2450
0
  for (i = 0; i < LOCALTIME_THREADS; i++) {
2451
0
    idx[i] = i % LOCALTIME_REFS;
2452
0
    if (hts_newthread_checked(localtime_thread, &idx[i]) != 0) {
2453
0
      fprintf(stderr, "localtime: cannot spawn\n");
2454
0
      return 1;
2455
0
    }
2456
0
  }
2457
0
  htsthread_wait();
2458
0
  if (localtime_bad != 0) {
2459
0
    fprintf(stderr, "localtime: %d/%d concurrent conversions were corrupt\n",
2460
0
            localtime_bad, LOCALTIME_THREADS * LOCALTIME_ROUNDS);
2461
0
    err = 1;
2462
0
  }
2463
2464
  /* get_filetime_rfc822() must report GMT, never the process's local zone,
2465
     and never a silent fallback to it on gmtime() failure (#806). */
2466
0
  {
2467
0
    char path[HTS_URLMAXSIZE];
2468
0
    char date[256];
2469
0
    struct tm parsed;
2470
2471
0
    snprintf(path, sizeof(path), "%s/filetime.bin", argv[0]);
2472
0
    structcheck(path);
2473
0
    {
2474
0
      FILE *fp = FOPEN(path, "wb");
2475
2476
0
      if (fp == NULL) {
2477
0
        fprintf(stderr, "localtime: cannot write %s\n", path);
2478
0
        return 1;
2479
0
      }
2480
0
      fputc('x', fp);
2481
0
      fclose(fp);
2482
0
    }
2483
0
    if (set_filetime_rfc822(path, "Tue, 29 Feb 2000 00:00:00 GMT") != 0) {
2484
0
      fprintf(stderr, "localtime: cannot set %s's mtime\n", path);
2485
0
      err = 1;
2486
0
    } else if (!get_filetime_rfc822(path, HTS_BUF(date))) {
2487
0
      fprintf(stderr, "localtime: get_filetime_rfc822 failed on %s\n", path);
2488
0
      err = 1;
2489
0
    } else if (convert_time_rfc822(&parsed, date) == NULL ||
2490
0
               parsed.tm_year != 100 || parsed.tm_mon != 1 ||
2491
0
               parsed.tm_mday != 29 || parsed.tm_hour != 0) {
2492
0
      fprintf(stderr,
2493
0
              "localtime: get_filetime_rfc822 reported \"%s\" (TZ=%s)\n", date,
2494
0
              getenv("TZ") ? getenv("TZ") : "");
2495
0
      err = 1;
2496
0
    }
2497
0
  }
2498
2499
0
  return st_verdict("localtime self-test", err);
2500
0
}
2501
2502
/* Dates on both sides of 2038-01-19T03:14:07Z, where a 32-bit time_t ends.
2503
   argv[0] is a scratch directory for the file-time check. The clip rows only
2504
   bite on a 32-bit time_t, which CI's linux-i386 job runs. */
2505
0
static int st_y2038(httrackp *opt, int argc, char **argv) {
2506
0
  static const struct {
2507
0
    const char *date;
2508
0
    int64_t secs;
2509
0
  } cases[] = {
2510
0
      {"Thu, 01 Jan 1970 00:00:00 GMT", 0},
2511
0
      {"Wed, 31 Dec 1969 23:59:59 GMT", -1},
2512
0
      {"Fri, 13 Dec 1901 20:45:52 GMT", -2147483648LL},
2513
0
      {"Tue, 29 Feb 2000 12:00:00 GMT", 951825600},
2514
0
      {"Tue, 19 Jan 2038 03:14:07 GMT", 2147483647},
2515
0
      {"Tue, 19 Jan 2038 03:14:08 GMT", 2147483648LL},
2516
0
      {"Sun, 07 Feb 2106 06:28:15 GMT", 4294967295LL},
2517
0
      {"Sun, 07 Feb 2106 06:28:16 GMT", 4294967296LL},
2518
0
      {"Fri, 31 Dec 9999 23:59:59 GMT", 253402300799LL},
2519
      /* centuries that are not leap years */
2520
0
      {"Thu, 01 Mar 1900 00:00:00 GMT", -2203891200LL},
2521
0
      {"Mon, 01 Mar 2100 00:00:00 GMT", 4107542400LL},
2522
0
  };
2523
2524
0
  const time_t ref = (time_t) 2147483640; /* 2038-01-19T03:14:00Z */
2525
0
  const hts_boolean narrow = sizeof(time_t) < sizeof(int64_t);
2526
0
  size_t i;
2527
0
  int err = 0;
2528
2529
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
2530
0
    const int64_t got = hts_parse_date(cases[i].date, 50);
2531
2532
0
    if (got != cases[i].secs) {
2533
0
      printf("y2038: \"%s\" gave " LLintP ", expected " LLintP "\n",
2534
0
             cases[i].date, (LLint) got, (LLint) cases[i].secs);
2535
0
      err = 1;
2536
0
    }
2537
0
  }
2538
2539
  /* Out-of-range fields carry over as timegm() does. */
2540
0
  {
2541
0
    struct tm tm;
2542
2543
0
    memset(&tm, 0, sizeof(tm));
2544
0
    tm.tm_year = 138;
2545
0
    tm.tm_mon = 12; /* January 2039 */
2546
0
    tm.tm_mday = 0; /* the day before: 2038-12-31 */
2547
0
    tm.tm_hour = -1;
2548
0
    if (hts_utc_seconds(&tm) != 2177362800LL) {
2549
0
      printf("y2038: unnormalised fields gave " LLintP "\n",
2550
0
             (LLint) hts_utc_seconds(&tm));
2551
0
      err = 1;
2552
0
    }
2553
0
    tm.tm_year = 138;
2554
0
    tm.tm_mon = -23; /* February 2036 */
2555
0
    tm.tm_mday = 1;
2556
0
    tm.tm_hour = 0;
2557
0
    if (hts_utc_seconds(&tm) != 2085436800LL) {
2558
0
      printf("y2038: a negative month gave " LLintP "\n",
2559
0
             (LLint) hts_utc_seconds(&tm));
2560
0
      err = 1;
2561
0
    }
2562
    /* years 0 and -1, below the first 400-year era */
2563
0
    tm.tm_year = -1900;
2564
0
    tm.tm_mon = 0;
2565
0
    if (hts_utc_seconds(&tm) != -62167219200LL) {
2566
0
      printf("y2038: year 0 gave " LLintP "\n", (LLint) hts_utc_seconds(&tm));
2567
0
      err = 1;
2568
0
    }
2569
0
    tm.tm_year = -1901;
2570
0
    if (hts_utc_seconds(&tm) != -62198755200LL) {
2571
0
      printf("y2038: year -1 gave " LLintP "\n", (LLint) hts_utc_seconds(&tm));
2572
0
      err = 1;
2573
0
    }
2574
0
  }
2575
2576
  /* A wait across the 2038 boundary, and one too long for an int. */
2577
0
  if (hts_parse_retry_after("Tue, 19 Jan 2038 03:14:00 GMT", ref) != 0 ||
2578
0
      hts_parse_retry_after("Tue, 19 Jan 2038 03:14:10 GMT", ref) != 10 ||
2579
0
      hts_parse_retry_after("Sat, 19 Jan 2039 03:14:00 GMT", ref) !=
2580
0
          365 * 86400 ||
2581
0
      hts_parse_retry_after("Sun, 07 Feb 2106 06:28:16 GMT", ref) != INT_MAX ||
2582
0
      hts_parse_retry_after("Fri, 31 Dec 9999 23:59:59 GMT", ref) != INT_MAX) {
2583
0
    printf("y2038: a Retry-After date past 2038 was misread\n");
2584
0
    err = 1;
2585
0
  }
2586
2587
  /* A date past time_t clips and never wraps. */
2588
0
  if ((int64_t) hts_time_clip(2147483648LL) !=
2589
0
          (narrow ? 2147483647LL : 2147483648LL) ||
2590
0
      (int64_t) hts_time_clip(253402300799LL) !=
2591
0
          (narrow ? 2147483647LL : 253402300799LL) ||
2592
0
      (int64_t) hts_time_clip(-2147483649LL) !=
2593
0
          (narrow ? -2147483648LL : -2147483649LL) ||
2594
0
      (int64_t) hts_time_clip(2147483647LL) != 2147483647LL) {
2595
0
    printf("y2038: hts_time_clip wrapped\n");
2596
0
    err = 1;
2597
0
  }
2598
0
  {
2599
0
    time_t got = (time_t) 7;
2600
2601
0
    if (hts_time_exact(2147483648LL, &got) != !narrow ||
2602
0
        (int64_t) got != (narrow ? 7 : 2147483648LL) ||
2603
0
        !hts_time_exact(2147483647LL, &got) || (int64_t) got != 2147483647LL ||
2604
0
        hts_time_exact(-2147483649LL, &got) != !narrow) {
2605
0
      printf("y2038: hts_time_exact accepted a clipped date\n");
2606
0
      err = 1;
2607
0
    }
2608
0
  }
2609
2610
  /* A mirrored file dated after 2038 keeps that date, or the last second a
2611
     32-bit time_t holds. */
2612
0
  if (argc >= 1) {
2613
0
    char path[HTS_URLMAXSIZE];
2614
0
    FILE *fp;
2615
0
    hts_boolean wide_fs = HTS_TRUE;
2616
2617
0
    snprintf(path, sizeof(path), "%s/y2038.bin", argv[0]);
2618
0
    structcheck(path);
2619
0
    fp = FOPEN(path, "wb");
2620
0
    if (fp == NULL) {
2621
0
      printf("y2038: cannot write %s\n", path);
2622
0
      return 1;
2623
0
    }
2624
0
    fclose(fp);
2625
0
#ifndef _WIN32
2626
    /* XFS without bigtime and ext4 with 128-byte inodes clip past 2038. Raw
2627
       calls, so a clipping get_filetime() cannot switch its own check off. */
2628
0
    if (!narrow) {
2629
0
      struct utimbuf tim;
2630
0
      struct stat st;
2631
2632
0
      tim.actime = tim.modtime = (time_t) cases[6].secs;
2633
0
      (void) utime(path, &tim);
2634
0
      if (stat(path, &st) != 0 || (int64_t) st.st_mtime != cases[6].secs) {
2635
0
        printf("y2038: this filesystem clips dates past 2038, skipped\n");
2636
0
        wide_fs = HTS_FALSE;
2637
0
      }
2638
0
    }
2639
0
#endif
2640
0
    for (i = 5; wide_fs && i <= 6; i++) {
2641
0
      const int64_t want = narrow ? 2147483647LL : cases[i].secs;
2642
0
      time_t got;
2643
2644
0
      if (set_filetime_rfc822(path, cases[i].date) != 0) {
2645
0
        printf("y2038: cannot date %s as \"%s\"\n", path, cases[i].date);
2646
0
        err = 1;
2647
0
      } else if ((int64_t) (got = get_filetime(path)) != want) {
2648
0
        printf("y2038: \"%s\" dated the file " LLintP ", expected " LLintP "\n",
2649
0
               cases[i].date, (LLint) got, (LLint) want);
2650
0
        err = 1;
2651
0
      }
2652
0
    }
2653
    /* The epoch and -1 mean no date: refused, and the file keeps its time. */
2654
0
    if (set_filetime_rfc822(path, cases[4].date) != 0 ||
2655
0
        set_filetime_rfc822(path, cases[0].date) != -1 ||
2656
0
        set_filetime_rfc822(path, cases[1].date) != -1 ||
2657
0
        (int64_t) get_filetime(path) != cases[4].secs) {
2658
0
      printf("y2038: the epoch changed the file's date\n");
2659
0
      err = 1;
2660
0
    }
2661
0
  }
2662
2663
0
  return st_verdict("y2038", err);
2664
0
}
2665
2666
/* Poison the whole arena, then copy str to its offset off. */
2667
0
static void repoison(hts_buf arena, size_t off, const char *str) {
2668
0
  memset(arena.p, '#', arena.size);
2669
0
  strlcpybuff(arena.p + off, str, arena.size - off);
2670
0
}
2671
2672
/* The x[strlen(x) - 1] class is tested here (#770, #781, #821). The byte
2673
   below the string holds '#' because a stray NUL would look untouched. */
2674
0
static int st_lastchar(httrackp *opt, int argc, char **argv) {
2675
0
  enum { off = 8 };
2676
2677
0
  char arena[16];
2678
0
  char *const s = &arena[off];
2679
0
  const int guard = off - 1; /* what the old idiom clobbers */
2680
0
  int err = 0;
2681
2682
  /* the empty string: every helper must report "nothing" and touch nothing */
2683
0
  repoison(HTS_BUF(arena), off, "");
2684
0
  ST_CHECK(err, hts_lastchar(s) == '\0');
2685
0
  ST_CHECK(err, arena[guard] == '#');
2686
0
  repoison(HTS_BUF(arena), off, "");
2687
0
  ST_CHECK(err, hts_striplastchar(s, '/') == HTS_FALSE);
2688
0
  ST_CHECK(err, arena[guard] == '#');
2689
0
  ST_CHECK(err, s[0] == '\0');
2690
0
  repoison(HTS_BUF(arena), off, "");
2691
0
  ST_CHECK(err, hts_choplastchar(s) == HTS_FALSE);
2692
0
  ST_CHECK(err, arena[guard] == '#');
2693
0
  ST_CHECK(err, s[0] == '\0');
2694
2695
  /* a '/' at the underflow spot must not pass for the last byte (#768) */
2696
0
  repoison(HTS_BUF(arena), off, "");
2697
0
  arena[guard] = '/';
2698
0
  ST_CHECK(err, hts_lastchar(s) == '\0');
2699
0
  ST_CHECK(err, hts_striplastchar(s, '/') == HTS_FALSE);
2700
0
  ST_CHECK(err, arena[guard] == '/');
2701
2702
  /* non-empty: ordinary behaviour */
2703
0
  repoison(HTS_BUF(arena), off, "ab/");
2704
0
  ST_CHECK(err, hts_lastchar(s) == '/');
2705
0
  ST_CHECK(err, hts_striplastchar(s, '/') == HTS_TRUE);
2706
0
  ST_CHECK(err, strcmp(s, "ab") == 0);
2707
0
  ST_CHECK(err, hts_striplastchar(s, '/') == HTS_FALSE);
2708
0
  ST_CHECK(err, strcmp(s, "ab") == 0);
2709
0
  ST_CHECK(err, hts_choplastchar(s) == HTS_TRUE);
2710
0
  ST_CHECK(err, strcmp(s, "a") == 0);
2711
0
  ST_CHECK(err, hts_choplastchar(s) == HTS_TRUE);
2712
0
  ST_CHECK(err, s[0] == '\0');
2713
0
  ST_CHECK(err, arena[guard] == '#');
2714
2715
  /* one-character string: the boundary the guards get wrong */
2716
0
  repoison(HTS_BUF(arena), off, "/");
2717
0
  ST_CHECK(err, hts_lastchar(s) == '/');
2718
0
  ST_CHECK(err, hts_striplastchar(s, '/') == HTS_TRUE);
2719
0
  ST_CHECK(err, s[0] == '\0');
2720
0
  ST_CHECK(err, arena[guard] == '#');
2721
2722
  /* the pointer spelling (#781): on an empty string the address must be the
2723
     terminating NUL, never the byte before it */
2724
0
  repoison(HTS_BUF(arena), off, "");
2725
0
  ST_CHECK(err, hts_lastcharoffset(s) == 0);
2726
0
  ST_CHECK(err, hts_lastcharptr(s) == s);
2727
0
  ST_CHECK(err, *hts_lastcharptr(s) == '\0');
2728
0
  *hts_lastcharptr(s) = 'Z'; /* a write through it must stay inside s */
2729
0
  ST_CHECK(err, arena[guard] == '#');
2730
0
  ST_CHECK(err, s[0] == 'Z');
2731
2732
  /* the neighbour must not be mistaken for the string's own last byte */
2733
0
  repoison(HTS_BUF(arena), off, "");
2734
0
  arena[guard] = '/';
2735
0
  ST_CHECK(err, hts_lastcharptr(s) == s);
2736
0
  ST_CHECK(err, *hts_lastcharptr(s) != '/');
2737
0
  ST_CHECK(err, arena[guard] == '/');
2738
2739
  /* the walk-back loops the sites use must stop at once on an empty string */
2740
0
  repoison(HTS_BUF(arena), off, "");
2741
0
  {
2742
0
    const char *p = hts_lastcharptr(s);
2743
0
    int steps = 0;
2744
2745
0
    while (p > s && *p != '/')
2746
0
      p--, steps++;
2747
0
    ST_CHECK(err, steps == 0);
2748
0
    ST_CHECK(err, p == s);
2749
0
  }
2750
2751
0
  repoison(HTS_BUF(arena), off, "ab/");
2752
0
  ST_CHECK(err, hts_lastcharoffset(s) == 2);
2753
0
  ST_CHECK(err, hts_lastcharptr(s) == s + 2);
2754
0
  ST_CHECK(err, *hts_lastcharptr(s) == '/');
2755
0
  repoison(HTS_BUF(arena), off, "/");
2756
0
  ST_CHECK(err, hts_lastcharptr(s) == s);
2757
0
  ST_CHECK(err, *hts_lastcharptr(s) == '/');
2758
0
  ST_CHECK(err, arena[guard] == '#');
2759
2760
  /* the size_t index spelling (#821): (i > 0) cannot reject SIZE_MAX, so only
2761
     a safe seed stops the sites' walk-back */
2762
0
  repoison(HTS_BUF(arena), off, "");
2763
0
  {
2764
0
    const size_t vacuous = strlen(s) - 1;
2765
0
    size_t i = hts_lastcharoffset(s);
2766
0
    int steps = 0;
2767
2768
0
    ST_CHECK(err, vacuous > 0);
2769
0
    ST_CHECK(err, i == 0);
2770
    /* step-capped so a bad seed fails the count instead of running off */
2771
0
    while ((i > 0) && (steps < 8) && (s[i] != '/'))
2772
0
      i--, steps++;
2773
0
    ST_CHECK(err, steps == 0);
2774
0
    ST_CHECK(err, s[i] != '/');
2775
0
    ST_CHECK(err, arena[guard] == '#');
2776
0
  }
2777
2778
  /* and the same loop must still find the real byte on a non-empty string */
2779
0
  repoison(HTS_BUF(arena), off, "a/b");
2780
0
  {
2781
0
    size_t i = hts_lastcharoffset(s);
2782
0
    int steps = 0;
2783
2784
0
    while ((i > 0) && (steps < 8) && (s[i] != '/'))
2785
0
      i--, steps++;
2786
0
    ST_CHECK(err, i == 1);
2787
0
    ST_CHECK(err, arena[guard] == '#');
2788
0
  }
2789
2790
  /* control: the canary must catch the unguarded idiom's write */
2791
0
  repoison(HTS_BUF(arena), off, "");
2792
0
  s[-1] = '\0';
2793
0
  ST_CHECK(err, arena[guard] != '#');
2794
0
  repoison(HTS_BUF(arena), off, "");
2795
0
  *(s + strlen(s) - 1) = 'X';
2796
0
  ST_CHECK(err, arena[guard] != '#');
2797
2798
0
  return st_verdict("lastchar self-test", err);
2799
0
}
2800
2801
/* The character classes htslib.h defines, paired with the htssafe.h set string
2802
   a strspn()/strcspn() skip names them by. A macro cannot be a table entry, so
2803
   each gets a wrapper. */
2804
0
static hts_boolean cc_space(unsigned char c) { return is_space((char) c) != 0; }
2805
2806
0
static hts_boolean cc_realspace(unsigned char c) {
2807
0
  return is_realspace((char) c) != 0;
2808
0
}
2809
2810
0
static hts_boolean cc_taborspace(unsigned char c) {
2811
0
  return is_taborspace((char) c) != 0;
2812
0
}
2813
2814
0
static hts_boolean cc_retorsep(unsigned char c) {
2815
0
  return is_retorsep((char) c) != 0;
2816
0
}
2817
2818
static const struct {
2819
  const char *set;
2820
  hts_boolean (*pred)(unsigned char);
2821
} cc_classes[] = {
2822
    {HTS_SPACES, cc_space},
2823
    {HTS_REALSPACES, cc_realspace},
2824
    {HTS_TABORSPACES, cc_taborspace},
2825
    {HTS_RETORSEP, cc_retorsep},
2826
};
2827
2828
/* Do strspn() and strcspn() over class CLS land where the loops they replaced
2829
   would have landed in S? */
2830
0
static hts_boolean cc_span_agrees(size_t cls, const char *s) {
2831
0
  const char *const set = cc_classes[cls].set;
2832
0
  hts_boolean (*const pred)(unsigned char) = cc_classes[cls].pred;
2833
0
  size_t span, cspan;
2834
2835
  /* the span loop needs no terminator guard, because no class holds byte 0 */
2836
0
  for (span = 0; pred((unsigned char) s[span]) != 0; span++)
2837
0
    ;
2838
0
  for (cspan = 0; s[cspan] != '\0' && pred((unsigned char) s[cspan]) == 0;
2839
0
       cspan++)
2840
0
    ;
2841
0
  return strspn(s, set) == span && strcspn(s, set) == cspan;
2842
0
}
2843
2844
/* -#test=chartab: HTS_BLANKS holds exactly SPACE, TAB, CR and LF, and lochar()
2845
   lowercases ASCII letters only, for every byte. */
2846
0
static int st_chartab(httrackp *opt, int argc, char **argv) {
2847
0
  int err = 0;
2848
0
  int c;
2849
2850
0
  for (c = 1; c < 256; c++) {
2851
0
    const hts_boolean blank = c == 32 || c == 9 || c == 13 || c == 10;
2852
0
    const char ch = (char) c;
2853
2854
0
    if ((strchr(HTS_BLANKS, ch) != NULL) != blank) {
2855
0
      printf("HTS_BLANKS: byte %d is %s\n", c, blank ? "missing" : "present");
2856
0
      err = 1;
2857
0
    }
2858
0
  }
2859
0
  for (c = 0; c < 256; c++) {
2860
0
    const char ch = (char) c;
2861
0
    const char want = (char) (c >= 65 && c <= 90 ? c + 32 : c);
2862
2863
0
    if (lochar(ch) != want) {
2864
0
      printf("lochar: byte %d gives %d, want %d\n", c, (int) lochar(ch),
2865
0
             (int) want);
2866
0
      err = 1;
2867
0
    }
2868
0
  }
2869
0
  return st_verdict("chartab", err);
2870
0
}
2871
2872
/* -#test=strcasecmp: hts_strcasecmp folds A-Z and compares unsigned bytes. */
2873
0
static int st_strcasecmp(httrackp *opt, int argc, char **argv) {
2874
0
  static const struct {
2875
0
    const char *a, *b;
2876
0
    int sign;
2877
0
  } cases[] = {
2878
0
      {"ab", "abc", -1},
2879
0
      {"", "about.html", -1},
2880
0
      {"a.com", "a.com.evil", -1},
2881
0
      {"", "TRUE", -1},
2882
0
      {"abd", "abc", 1},
2883
0
      {"ABC", "abc", 0},
2884
0
      {"", "", 0},
2885
0
      {"TRUE", "true", 0},
2886
0
      {"A_b", "ab", -1},
2887
0
      {"\xc3\xa9t\xc3\xa9", "zoo", 1},
2888
0
  };
2889
2890
0
  size_t i;
2891
0
  int err = 0;
2892
2893
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
2894
0
    const int ab = hts_strcasecmp(cases[i].a, cases[i].b);
2895
0
    const int ba = hts_strcasecmp(cases[i].b, cases[i].a);
2896
0
    const int sign = (ab > 0) - (ab < 0);
2897
2898
0
    if (sign != cases[i].sign || (ba > 0) - (ba < 0) != -sign) {
2899
0
      printf("strcasecmp: (\"%s\", \"%s\") gives %d, reversed %d\n", cases[i].a,
2900
0
             cases[i].b, ab, ba);
2901
0
      err = 1;
2902
0
    }
2903
0
  }
2904
0
  return st_verdict("strcasecmp", err);
2905
0
}
2906
2907
0
static void uninit_worker_noop(void *arg) { (void) arg; }
2908
2909
/* Did the worker's hts_uninit() return with the thread lock still built? */
2910
static hts_boolean uninit_worker_kept;
2911
2912
0
static void uninit_worker(void *arg) {
2913
0
  (void) arg;
2914
0
  hts_uninit();
2915
0
  uninit_worker_kept = htsthread_lock_live();
2916
0
}
2917
2918
0
static void uninit_report(const char *step) {
2919
0
  printf("%s:psl-%s,lock-%s", step, hts_psl_loaded() ? "on" : "off",
2920
0
         htsthread_lock_live() ? "on" : "off");
2921
0
}
2922
2923
/* A worker's hts_uninit() must neither wait for itself nor free the lock it
2924
   still takes. Then two hts_uninit() calls free the Public Suffix List and the
2925
   thread lock, and hts_init() plus a new worker rebuild both. */
2926
0
static int st_uninit(httrackp *opt, int argc, char **argv) {
2927
0
  int i;
2928
2929
0
  hts_init();
2930
0
  if (hts_newthread_checked(uninit_worker, NULL) != 0)
2931
0
    return 1;
2932
0
  htsthread_wait();
2933
0
  printf("worker:%s", uninit_worker_kept ? "kept" : "freed");
2934
0
  hts_init();
2935
0
  for (i = 0; i < 2; i++) {
2936
0
    hts_uninit();
2937
0
    uninit_report(" uninit");
2938
0
  }
2939
0
  hts_init();
2940
0
  if (hts_newthread_checked(uninit_worker_noop, NULL) != 0)
2941
0
    return 1;
2942
0
  htsthread_wait();
2943
0
  uninit_report(" rejoin");
2944
0
  printf("\n");
2945
0
  return 0;
2946
0
}
2947
2948
/* The byte below the string holds '#' because a stray NUL looks untouched. */
2949
0
static int st_rtrim(httrackp *opt, int argc, char **argv) {
2950
0
  enum { off = 8 };
2951
2952
0
  char arena[24];
2953
0
  char *const s = &arena[off];
2954
0
  const int guard = off - 1;
2955
0
  int err = 0;
2956
0
  int c;
2957
0
  size_t cls;
2958
2959
  /* nothing but spaces: the case that ran the old loop off the front */
2960
0
  repoison(HTS_BUF(arena), off, "   ");
2961
0
  hts_rtrim(s, HTS_REALSPACES);
2962
0
  ST_CHECK(err, s[0] == '\0');
2963
0
  ST_CHECK(err, arena[guard] == '#');
2964
2965
  /* a space below the string must not be trimmed as part of it */
2966
0
  repoison(HTS_BUF(arena), off, "   ");
2967
0
  arena[guard] = ' ';
2968
0
  hts_rtrim(s, HTS_REALSPACES);
2969
0
  ST_CHECK(err, s[0] == '\0');
2970
0
  ST_CHECK(err, arena[guard] == ' ');
2971
2972
0
  repoison(HTS_BUF(arena), off, "");
2973
0
  hts_rtrim(s, HTS_REALSPACES);
2974
0
  ST_CHECK(err, s[0] == '\0');
2975
0
  ST_CHECK(err, arena[guard] == '#');
2976
2977
0
  repoison(HTS_BUF(arena), off, "a b \t\r\n");
2978
0
  hts_rtrim(s, HTS_REALSPACES);
2979
0
  ST_CHECK(err, strcmp(s, "a b") == 0);
2980
0
  ST_CHECK(err, arena[guard] == '#');
2981
2982
0
  repoison(HTS_BUF(arena), off, "ab");
2983
0
  hts_rtrim(s, HTS_REALSPACES);
2984
0
  ST_CHECK(err, strcmp(s, "ab") == 0);
2985
2986
  /* quotes count as space for is_space() but not for is_realspace() */
2987
0
  repoison(HTS_BUF(arena), off, "v\" ");
2988
0
  hts_rtrim(s, HTS_REALSPACES);
2989
0
  ST_CHECK(err, strcmp(s, "v\"") == 0);
2990
0
  repoison(HTS_BUF(arena), off, "v\" ");
2991
0
  hts_rtrim(s, HTS_SPACES);
2992
0
  ST_CHECK(err, strcmp(s, "v") == 0);
2993
2994
  /* Each set string must hold exactly the bytes its macro accepts, or a
2995
     strspn()/strcspn() skip stops somewhere the old loop did not. */
2996
0
  for (cls = 0; cls < sizeof(cc_classes) / sizeof(cc_classes[0]); cls++) {
2997
0
    for (c = 0; c < 256; c++) {
2998
0
      const char b = (char) c;
2999
      /* strchr() answers yes for the terminator, so byte 0 (member of no
3000
         class) is spelled out. */
3001
0
      const hts_boolean in_set =
3002
0
          c != 0 && strchr(cc_classes[cls].set, b) != NULL;
3003
3004
0
      ST_CHECK(err, in_set == cc_classes[cls].pred((unsigned char) c));
3005
0
    }
3006
0
  }
3007
3008
  /* A skip lands where its loop did. Three letters cover shorter strings
3009
     because the terminator is one, and the first takes every byte value. */
3010
0
  for (cls = 0; cls < sizeof(cc_classes) / sizeof(cc_classes[0]); cls++) {
3011
    /* 'x' is in no class, so the alphabet always holds a non-member */
3012
0
    ST_CHECK(err, !cc_classes[cls].pred((unsigned char) 'x'));
3013
0
    for (c = 1; c < 256; c++) {
3014
0
      const char alpha[3] = {(char) c, 'x', '\0'};
3015
0
      int i, j, k;
3016
3017
0
      for (i = 0; i < 3; i++) {
3018
0
        for (j = 0; j < 3; j++) {
3019
0
          for (k = 0; k < 3; k++) {
3020
0
            const char word[4] = {alpha[i], alpha[j], alpha[k], '\0'};
3021
3022
0
            ST_CHECK(err, cc_span_agrees(cls, word));
3023
0
          }
3024
0
        }
3025
0
      }
3026
0
    }
3027
0
  }
3028
3029
  /* control: the canary must be able to fail */
3030
0
  repoison(HTS_BUF(arena), off, "   ");
3031
0
  s[-1] = '\0';
3032
0
  ST_CHECK(err, arena[guard] != '#');
3033
3034
0
  return st_verdict("rtrim self-test", err);
3035
0
}
3036
3037
/* Format EXPECTED into S as two arguments, and check what came back. HEAD and
3038
   TAIL are scratch buffers. */
3039
static int strsprintf_case(String *s, hts_span expected, hts_buf head,
3040
0
                           hts_buf tail) {
3041
0
  const size_t len = expected.len, half = len / 2;
3042
3043
0
  assertf(len < head.size && len < tail.size);
3044
0
  memcpy(head.p, expected.p, half);
3045
0
  head.p[half] = '\0';
3046
0
  memcpy(tail.p, expected.p + half, len - half);
3047
0
  tail.p[len - half] = '\0';
3048
0
  StringSprintf(*s, "%s%s", head.p, tail.p);
3049
0
  return StringLength(*s) == len &&
3050
0
         memcmp(StringBuff(*s), expected.p, len) == 0 &&
3051
0
         StringBuff(*s)[len] == '\0';
3052
0
}
3053
3054
/* An output as long as the capacity (256, doubling) must fit its NUL (#836). */
3055
0
static int st_strsprintf(httrackp *opt, int argc, char **argv) {
3056
0
  static const size_t caps[] = {256, 512, 1024, 2048};
3057
3058
0
  enum { maxLen = 2100 };
3059
3060
0
  char *expected = malloct(maxLen + 1);
3061
0
  char *head = malloct(maxLen + 1);
3062
0
  char *tail = malloct(maxLen + 1);
3063
0
  const hts_buf hbuf = hts_buf_at(head, maxLen + 1);
3064
0
  const hts_buf tbuf = hts_buf_at(tail, maxLen + 1);
3065
0
  String reused = STRING_EMPTY;
3066
0
  size_t i, len;
3067
0
  int err = 0;
3068
3069
0
  if (expected == NULL || head == NULL || tail == NULL) {
3070
0
    printf("strsprintf self-test: FAIL (out of memory)\n");
3071
0
    freet(expected);
3072
0
    freet(head);
3073
0
    freet(tail);
3074
0
    return 1;
3075
0
  }
3076
0
  for (i = 0; i < maxLen; i++)
3077
0
    expected[i] = (char) ('a' + (i % 26));
3078
0
  expected[maxLen] = '\0';
3079
3080
  /* a total of 0 still allocates, so StringBuff is never NULL after it */
3081
0
  {
3082
0
    String s = STRING_EMPTY;
3083
3084
0
    StringRoomTotal(s, 0);
3085
0
    if (StringBuff(s) == NULL) {
3086
0
      printf("  FAIL: StringRoomTotal(0) left no buffer\n");
3087
0
      err = 1;
3088
0
    }
3089
0
    StringFree(s);
3090
0
  }
3091
3092
  /* one call on a String whose capacity is pinned to the boundary, so len ==
3093
     capacity is reached exactly once per boundary */
3094
0
  for (i = 0; !err && i < sizeof(caps) / sizeof(caps[0]); i++) {
3095
0
    for (len = caps[i] - 3; !err && len <= caps[i] + 3; len++) {
3096
0
      String s = STRING_EMPTY;
3097
3098
0
      StringRoomTotal(s, caps[i]);
3099
0
      if (StringCapacity(s) != caps[i]) {
3100
0
        printf("  FAIL: capacity %u pinned to %u\n", (unsigned) caps[i],
3101
0
               (unsigned) StringCapacity(s));
3102
0
        err = 1;
3103
0
      } else if (!strsprintf_case(&s, hts_span_at(expected, len), hbuf, tbuf)) {
3104
0
        printf("  FAIL: length %u at capacity %u\n", (unsigned) len,
3105
0
               (unsigned) caps[i]);
3106
0
        err = 1;
3107
0
      }
3108
0
      StringFree(s);
3109
0
    }
3110
0
  }
3111
3112
  /* the same String reused: its capacity grows under it between calls, and a
3113
     shorter output must not leave the previous one behind */
3114
0
  for (len = 0; !err && len <= maxLen; len++) {
3115
0
    if (!strsprintf_case(&reused, hts_span_at(expected, len), hbuf, tbuf)) {
3116
0
      printf("  FAIL: growing length %u\n", (unsigned) len);
3117
0
      err = 1;
3118
0
    }
3119
0
  }
3120
0
  for (len = maxLen + 1; !err && len-- > 0;) {
3121
0
    if (!strsprintf_case(&reused, hts_span_at(expected, len), hbuf, tbuf)) {
3122
0
      printf("  FAIL: shrinking length %u\n", (unsigned) len);
3123
0
      err = 1;
3124
0
    }
3125
0
  }
3126
0
  StringFree(reused);
3127
3128
  /* An argument libc cannot convert empties the String. Probe libc first,
3129
     because some platforms format an unpaired surrogate. */
3130
0
  {
3131
0
    static const wchar_t bad[] = {(wchar_t) 0xd800, 0};
3132
0
    char probe[32];
3133
3134
0
    if (snprintf(probe, sizeof(probe), "%ls", bad) < 0) {
3135
0
      String s = STRING_EMPTY;
3136
3137
0
      StringCopy(s, "leftover");
3138
0
      StringSprintf(s, "%ls", bad);
3139
0
      if (StringNotEmpty(s) || StringBuff(s) == NULL ||
3140
0
          StringBuff(s)[0] != '\0') {
3141
0
        printf("  FAIL: a failed conversion left %u bytes behind\n",
3142
0
               (unsigned) StringLength(s));
3143
0
        err = 1;
3144
0
      }
3145
0
      StringFree(s);
3146
0
    } else { /* stderr: test 150 pins stdout to the one-line verdict */
3147
0
      fprintf(stderr, "  (skipped: this libc formats an unconvertible wide "
3148
0
                      "string)\n");
3149
0
    }
3150
0
  }
3151
3152
  /* WebDAV pops a trailing '/', so a give-up that empties the String must
3153
     not underflow its length. */
3154
0
  {
3155
0
    String never = STRING_EMPTY;
3156
0
    String cleared = STRING_EMPTY;
3157
3158
0
    StringPopRight(never); /* never written to: buffer_ is still NULL */
3159
0
    if (StringLength(never) != 0 || StringBuff(never) != NULL) {
3160
0
      printf("  FAIL: pop on an unallocated String\n");
3161
0
      err = 1;
3162
0
    }
3163
0
    StringClear(cleared);
3164
0
    StringPopRight(cleared);
3165
0
    if (StringLength(cleared) != 0 || StringBuff(cleared)[0] != '\0') {
3166
0
      printf("  FAIL: pop on an emptied String\n");
3167
0
      err = 1;
3168
0
    }
3169
    /* control: the guard must not swallow a pop that has a byte to drop */
3170
0
    StringSprintf(cleared, "ab");
3171
0
    StringPopRight(cleared);
3172
0
    if (StringLength(cleared) != 1 || strcmp(StringBuff(cleared), "a") != 0) {
3173
0
      printf("  FAIL: pop on a non-empty String\n");
3174
0
      err = 1;
3175
0
    }
3176
0
    StringFree(never);
3177
0
    StringFree(cleared);
3178
0
  }
3179
3180
0
  freet(expected);
3181
0
  freet(head);
3182
0
  freet(tail);
3183
3184
0
  return st_verdict("strsprintf self-test", err);
3185
0
}
3186
3187
#ifndef _WIN32
3188
/* Point both output streams at fd, raise code, and hand back the errno the
3189
   handler left behind, or 0 if it put the caller's back. */
3190
0
static int sig_raise_on(int code, int fd) {
3191
0
  static const int sentinel = 0x5167;
3192
0
  int saved_out, saved_err, leaked;
3193
3194
0
  fflush(stdout);
3195
0
  fflush(stderr);
3196
0
  saved_out = dup(1);
3197
0
  saved_err = dup(2);
3198
0
  assertf(saved_out != -1 && saved_err != -1);
3199
0
  assertf(dup2(fd, 1) != -1 && dup2(fd, 2) != -1);
3200
0
  errno = sentinel;
3201
0
  assertf(raise(code) == 0);
3202
0
  leaked = errno;
3203
0
  assertf(dup2(saved_out, 1) != -1 && dup2(saved_err, 2) != -1);
3204
0
  close(saved_out);
3205
0
  close(saved_err);
3206
0
  return leaked == sentinel ? 0 : leaked;
3207
0
}
3208
3209
/* httrack.c's own handlers, reached here because main() installs them before
3210
   any self-test runs. SIGTSTP is left out: sig_back() either suspends the
3211
   process or forks it into the background. */
3212
0
static int st_sighandlers(httrackp *opt, int argc, char **argv) {
3213
0
  static const struct {
3214
0
    int code;
3215
0
    const char *name;
3216
0
    const char *says; /* what the user must still be told, NULL if silent */
3217
0
    hts_boolean with_code; /* the line ends with the signal number and a ')' */
3218
0
  } cases[] = {
3219
0
      {SIGCHLD, "SIGCHLD", NULL, HTS_FALSE},
3220
0
      {SIGPIPE, "SIGPIPE", NULL, HTS_FALSE},
3221
0
      {SIGTERM, "SIGTERM", "Exit requested to engine (signal ", HTS_TRUE},
3222
0
      {SIGINT, "SIGINT",
3223
0
       "** Finishing pending transfers.. press again ^C to quit.", HTS_FALSE}};
3224
3225
  /* a descriptor no write can succeed on, so a leaked errno shows */
3226
0
  const int readonly = open("/dev/null", O_RDONLY);
3227
0
  FILE *const capture = tmpfile();
3228
0
  int capfd;
3229
0
  int err = 0;
3230
0
  size_t i;
3231
3232
0
  assertf(readonly != -1);
3233
0
  assertf(capture != NULL);
3234
0
  capfd = fileno(capture);
3235
0
  assertf(capfd != -1);
3236
3237
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
3238
0
    const int code = cases[i].code;
3239
0
    int pass;
3240
3241
    /* Twice: on the refusing descriptor, where a leaked errno shows, and on a
3242
       file, where what the handler wrote can be read back. */
3243
0
    for (pass = 0; pass < 2; pass++) {
3244
0
      const int fd = pass == 0 ? readonly : capfd;
3245
0
      char captured[512];
3246
0
      ssize_t got;
3247
0
      void (*installed)(int);
3248
0
      int leaked;
3249
3250
      /* the control: a disposition main() never touched proves nothing below */
3251
0
      installed = signal(code, SIG_DFL);
3252
0
      assertf(installed != SIG_ERR);
3253
0
      assertf(signal(code, installed) == SIG_DFL);
3254
0
      if (installed == SIG_DFL || installed == SIG_IGN) {
3255
0
        printf("  FAIL: %s carries no handler to exercise\n", cases[i].name);
3256
0
        err = 1;
3257
0
        break;
3258
0
      }
3259
      /* sig_leave() only takes its own branch during a mirror; outside one it
3260
         ends the process, which is what the second ^C is for */
3261
0
      if (code == SIGINT)
3262
0
        opt->state._hts_in_mirror = 1;
3263
      /* the handler writes at the shared offset, so rewind as well as empty */
3264
0
      assertf(ftruncate(capfd, 0) == 0);
3265
0
      assertf(lseek(capfd, 0, SEEK_SET) == 0);
3266
3267
0
      leaked = sig_raise_on(code, fd);
3268
0
      if (leaked != 0) {
3269
0
        printf("  FAIL: the %s handler left errno at %d\n", cases[i].name,
3270
0
               leaked);
3271
0
        err = 1;
3272
0
      }
3273
      /* and it still did its job */
3274
0
      if (code == SIGTERM && opt->state.exit_xh != 1) {
3275
0
        printf("  FAIL: SIGTERM did not ask the engine to exit\n");
3276
0
        err = 1;
3277
0
      }
3278
0
      if (code == SIGINT && !opt->state.stop) {
3279
0
        printf("  FAIL: SIGINT did not ask the mirror to stop\n");
3280
0
        err = 1;
3281
0
      }
3282
0
      opt->state._hts_in_mirror = 0;
3283
0
      opt->state.exit_xh = 0;
3284
0
      opt->state.stop = 0;
3285
      /* sig_finish() and sig_leave() re-arm to the terminating handler, so the
3286
         next raise would end the process instead of testing it */
3287
0
      assertf(signal(code, installed) != SIG_ERR);
3288
3289
0
      if (pass == 0)
3290
0
        continue;
3291
0
      assertf(lseek(capfd, 0, SEEK_SET) == 0);
3292
0
      got = read(capfd, captured, sizeof(captured) - 1);
3293
0
      assertf(got >= 0);
3294
0
      captured[got] = '\0';
3295
0
      if (cases[i].says == NULL) {
3296
0
        if (got != 0) {
3297
0
          printf("  FAIL: %s is meant to be silent, but wrote \"%s\"\n",
3298
0
                 cases[i].name, captured);
3299
0
          err = 1;
3300
0
        }
3301
0
      } else {
3302
0
        char want[256];
3303
3304
0
        if (cases[i].with_code)
3305
0
          snprintf(want, sizeof(want), "%s%d)", cases[i].says, code);
3306
0
        else
3307
0
          snprintf(want, sizeof(want), "%s", cases[i].says);
3308
0
        if (strstr(captured, want) == NULL) {
3309
0
          printf("  FAIL: %s wrote \"%s\" instead of \"%s\"\n", cases[i].name,
3310
0
                 captured, want);
3311
0
          err = 1;
3312
0
        }
3313
0
      }
3314
0
    }
3315
0
  }
3316
0
  close(readonly);
3317
0
  fclose(capture);
3318
0
  return st_verdict("sighandlers self-test", err);
3319
0
}
3320
#endif
3321
3322
#ifndef _WIN32
3323
/* Raised by the child's atexit hook below. */
3324
static int sigterm_atexit_fd = -1;
3325
3326
0
static void sigterm_atexit_marker(void) {
3327
0
  const char c = 'A';
3328
3329
0
  (void) (write(sigterm_atexit_fd, &c, 1) == 1);
3330
0
}
3331
3332
/* The ^C that terminates must skip atexit, where OpenSSL's teardown can
3333
   deadlock on the malloc lock the interrupted thread holds. */
3334
0
static int st_sigterm(httrackp *opt, int argc, char **argv) {
3335
0
  static const struct {
3336
0
    const char *name;
3337
0
    int in_mirror; /* sig_leave() only defers while a mirror runs */
3338
0
    int raises;
3339
0
  } cases[] = {{"a ^C outside a mirror", 0, 1},
3340
0
               {"the second ^C during a mirror", 1, 2}};
3341
3342
0
  int err = 0;
3343
0
  size_t i;
3344
3345
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
3346
0
    FILE *const errs = tmpfile();
3347
0
    char marker[8], said[512];
3348
0
    int fds[2], status = -1;
3349
0
    ssize_t got;
3350
0
    pid_t pid;
3351
3352
0
    assertf(errs != NULL);
3353
0
    assertf(pipe(fds) == 0);
3354
0
    fflush(NULL); /* nothing buffered for the child to flush or to drop */
3355
0
    pid = fork();
3356
0
    assertf(pid != -1);
3357
0
    if (pid == 0) {
3358
0
      int n;
3359
3360
0
      close(fds[0]);
3361
0
      sigterm_atexit_fd = fds[1];
3362
      /* an unarmed hook would make every exit() look like _exit() */
3363
0
      if (atexit(sigterm_atexit_marker) != 0)
3364
0
        _exit(71);
3365
0
      if (dup2(fileno(errs), 2) == -1)
3366
0
        _exit(72);
3367
0
      opt->state._hts_in_mirror = cases[i].in_mirror;
3368
0
      for (n = 0; n < cases[i].raises; n++) {
3369
0
        if (raise(SIGINT) != 0)
3370
0
          _exit(73);
3371
0
      }
3372
0
      _exit(74); /* the handler returned, so it terminated nothing */
3373
0
    }
3374
0
    close(fds[1]);
3375
0
    got = read(fds[0], marker, sizeof(marker));
3376
0
    assertf(got >= 0);
3377
0
    close(fds[0]);
3378
0
    assertf(waitpid(pid, &status, 0) == pid);
3379
3380
0
    if (!WIFEXITED(status)) {
3381
      /* SIG_DFL would land here, and then the case below proves nothing */
3382
0
      printf("  FAIL: %s killed the child by signal %d instead of exiting\n",
3383
0
             cases[i].name, WIFSIGNALED(status) ? WTERMSIG(status) : -1);
3384
0
      err = 1;
3385
0
    } else if (WEXITSTATUS(status) != 0) {
3386
0
      printf("  FAIL: %s left the child at exit code %d\n", cases[i].name,
3387
0
             WEXITSTATUS(status));
3388
0
      err = 1;
3389
0
    } else if (got != 0) {
3390
0
      printf("  FAIL: %s ran the atexit chain\n", cases[i].name);
3391
0
      err = 1;
3392
0
    }
3393
    /* and the user is still told, so safety was not bought with silence */
3394
0
    rewind(errs);
3395
0
    got = (ssize_t) fread(said, 1, sizeof(said) - 1, errs);
3396
0
    assertf(got >= 0);
3397
0
    said[got] = '\0';
3398
0
    if (strstr(said, "Program terminated") == NULL) {
3399
0
      printf("  FAIL: %s said \"%s\" instead of naming the termination\n",
3400
0
             cases[i].name, said);
3401
0
      err = 1;
3402
0
    }
3403
0
    fclose(errs);
3404
0
  }
3405
0
  return st_verdict("sigterm self-test", err);
3406
0
}
3407
#endif
3408
3409
/* Eight FTP workers and the crawl thread each add STATRECV_ROUNDS times, so a
3410
   plain += drops some and the total comes up short. -M reads that total. */
3411
0
#define STATRECV_THREADS 8
3412
0
#define STATRECV_ROUNDS 100000
3413
3414
0
static void statrecv_thread(void *arg) {
3415
0
  int i;
3416
3417
0
  (void) arg;
3418
0
  for (i = 0; i < STATRECV_ROUNDS; i++)
3419
0
    hts_stat_recv_add(1);
3420
0
}
3421
3422
0
static int st_statrecv(httrackp *opt, int argc, char **argv) {
3423
0
  const LLint expected = (LLint) (STATRECV_THREADS + 1) * STATRECV_ROUNDS;
3424
0
  const LLint recv_was = hts_stat_recv_get();
3425
0
  LLint total;
3426
0
  int err = 0;
3427
0
  int i;
3428
3429
0
  hts_stat_recv_set(0);
3430
0
  for (i = 0; i < STATRECV_THREADS; i++) {
3431
0
    if (hts_newthread_checked(statrecv_thread, NULL) != 0) {
3432
0
      fprintf(stderr, "statrecv: cannot spawn\n");
3433
0
      htsthread_wait(); /* a spawned worker would else add to the total below */
3434
0
      hts_stat_recv_set(recv_was);
3435
0
      return 1;
3436
0
    }
3437
0
  }
3438
0
  statrecv_thread(NULL); /* the crawl thread's own share, as hts_read() adds */
3439
0
  htsthread_wait();
3440
0
  total = hts_stat_recv_get();
3441
0
  if (total != expected) {
3442
0
    fprintf(stderr,
3443
0
            "statrecv: the counter holds " LLintP " of " LLintP
3444
0
            " bytes added, so " LLintP " adds were lost\n",
3445
0
            total, expected, expected - total);
3446
0
    err = 1;
3447
0
  }
3448
3449
  /* the case above trusts the setter to have zeroed the total */
3450
0
  hts_stat_recv_set(recv_was + 1);
3451
0
  if (hts_stat_recv_get() != recv_was + 1) {
3452
0
    fprintf(stderr, "statrecv: the setter did not take\n");
3453
0
    err = 1;
3454
0
  }
3455
3456
  /* a front end reads the published copy, and nothing else does */
3457
0
  hts_stat_recv_publish();
3458
0
  if (HTS_STAT.HTS_TOTAL_RECV != recv_was + 1) {
3459
0
    fprintf(stderr,
3460
0
            "statrecv: the published total is " LLintP ", not " LLintP "\n",
3461
0
            (LLint) HTS_STAT.HTS_TOTAL_RECV, recv_was + 1);
3462
0
    err = 1;
3463
0
  }
3464
0
  hts_stat_recv_set(recv_was);
3465
0
  hts_stat_recv_publish();
3466
3467
0
  return st_verdict("statrecv", err);
3468
0
}
3469
3470
/* An overrun or a stray NUL must disturb this byte. */
3471
0
#define QUERYPARAM_POISON 'Z'
3472
3473
/* Prints the value %[param] looks up as [value], or "(none)" for no such key.
3474
   The buffer is poisoned first, so a stray NUL, a missing one and a write past
3475
   the size all show. */
3476
0
static int st_queryparam(httrackp *opt, int argc, char **argv) {
3477
0
  char buff[256];
3478
0
  size_t size = sizeof(buff);
3479
0
  const char *overrun = "";
3480
0
  hts_boolean found;
3481
0
  size_t i;
3482
3483
0
  if (argc < 2 || argc > 3) {
3484
0
    fprintf(stderr, "queryparam: takes a url, a name and an optional size\n");
3485
0
    return 1;
3486
0
  }
3487
0
  if (argc == 3) {
3488
0
    size = (size_t) atoi(argv[2]);
3489
0
    if (size < 1 || size > sizeof(buff)) {
3490
0
      fprintf(stderr, "queryparam: the size is 1..%u\n",
3491
0
              (unsigned) sizeof(buff));
3492
0
      return 1;
3493
0
    }
3494
0
  }
3495
0
  memset(buff, QUERYPARAM_POISON, sizeof(buff));
3496
0
  found = url_query_value(argv[0], argv[1], hts_buf_at(buff, size));
3497
0
  for (i = size; i < sizeof(buff); i++) {
3498
0
    if (buff[i] != QUERYPARAM_POISON)
3499
0
      overrun = " OVERRUN";
3500
0
  }
3501
0
  if (memchr(buff, '\0', size) == NULL) {
3502
0
    printf("UNTERMINATED%s\n", overrun);
3503
0
    return 1;
3504
0
  }
3505
0
  if (found) {
3506
0
    printf("[%s]%s\n", buff, overrun);
3507
0
  } else {
3508
    /* The lookup empties the buffer whether or not it finds the key. */
3509
0
    printf("(none)%s%s\n", buff[0] != '\0' ? " NOT-EMPTIED" : "", overrun);
3510
0
  }
3511
0
  return 0;
3512
0
}
3513
3514
/* Every size reads the same field and clips its value to size - 1 bytes, so
3515
   the widest read is the oracle for the narrow ones. */
3516
static void querysweep_one(parsediff_stats *st, const char *url,
3517
0
                           const char *name) {
3518
0
  static const size_t sizes[] = {1, 2, 4, 63, 64, 65, 254, 255};
3519
0
  char oracle[256];
3520
0
  hts_boolean oracle_found;
3521
0
  size_t i;
3522
3523
0
  memset(oracle, QUERYPARAM_POISON, sizeof(oracle));
3524
0
  oracle_found = url_query_value(url, name, HTS_BUF(oracle));
3525
0
  if (memchr(oracle, '\0', sizeof(oracle)) == NULL) {
3526
0
    parsediff_fail(st, "url_query_value left no terminator", url, name, "", "");
3527
0
    return;
3528
0
  }
3529
0
  for (i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++) {
3530
0
    const size_t size = sizes[i];
3531
0
    char buff[256];
3532
0
    hts_boolean found;
3533
0
    size_t j;
3534
3535
0
    st->cases++;
3536
0
    memset(buff, QUERYPARAM_POISON, sizeof(buff));
3537
0
    found = url_query_value(url, name, hts_buf_at(buff, size));
3538
0
    for (j = size; j < sizeof(buff); j++) {
3539
0
      if (buff[j] != QUERYPARAM_POISON) {
3540
0
        parsediff_fail(st, "url_query_value wrote past the size", url, name,
3541
0
                       oracle, "");
3542
0
        break;
3543
0
      }
3544
0
    }
3545
0
    if (memchr(buff, '\0', size) == NULL) {
3546
0
      parsediff_fail(st, "url_query_value left no terminator", url, name,
3547
0
                     oracle, "");
3548
0
    } else if (found != oracle_found || strlen(buff) >= size ||
3549
0
               strncmp(buff, oracle, size - 1) != 0) {
3550
0
      parsediff_fail(st, "url_query_value clipped wrong", url, name, oracle,
3551
0
                     buff);
3552
0
    }
3553
0
  }
3554
0
}
3555
3556
/* Nothing in fuzz/ reaches url_query_value, so these queries are generated. */
3557
0
static int st_querysweep(httrackp *opt, int argc, char **argv) {
3558
0
  static const char *const names[] = {"id", "a", "sid", "", "x?id"};
3559
0
  static const char *const alphabet[] = {"a", "=",   "&",   "%",   "?",  ";",
3560
0
                                         "#", "+",   " ",   "sid", "id", "/",
3561
0
                                         "1", "%41", "abc", "x"};
3562
  /* These field lengths straddle the buffer sizes above. */
3563
0
  static const size_t lengths[] = {63, 64, 65, 254, 255, 256, 300};
3564
0
  parsediff_stats st = {0, 0};
3565
0
  uint32_t seed = 1872;
3566
0
  size_t i, j;
3567
0
  int r;
3568
3569
0
  for (i = 0; i < sizeof(lengths) / sizeof(lengths[0]); i++) {
3570
0
    char *run = parsediff_run('x', lengths[i]);
3571
0
    String q = STRING_EMPTY;
3572
3573
0
    StringCat(q, "/p?a=1&id=");
3574
0
    StringCat(q, run);
3575
0
    StringCat(q, "&");
3576
0
    StringCat(q, run);
3577
0
    StringCat(q, "=v");
3578
0
    for (j = 0; j < sizeof(names) / sizeof(names[0]); j++)
3579
0
      querysweep_one(&st, StringBuff(q), names[j]);
3580
0
    querysweep_one(&st, StringBuff(q), run);
3581
0
    StringFree(q);
3582
0
    freet(run);
3583
0
  }
3584
0
  for (r = 0; r < 4000; r++) {
3585
0
    String q = STRING_EMPTY;
3586
3587
0
    StringCat(q, "/p?");
3588
0
    parsediff_random(&q, &seed, alphabet,
3589
0
                     sizeof(alphabet) / sizeof(alphabet[0]), 24);
3590
0
    for (j = 0; j < sizeof(names) / sizeof(names[0]); j++)
3591
0
      querysweep_one(&st, StringBuff(q), names[j]);
3592
0
    StringFree(q);
3593
0
  }
3594
0
  printf("querysweep: %lu cases, %lu failures\n", st.cases, st.failures);
3595
0
  if (st.failures == 0)
3596
0
    printf("querysweep: OK\n");
3597
0
  return st.failures != 0;
3598
0
}
3599
3600
/* Prints each field of argv[0] as [key] or [key|value], because '|' shows
3601
   where the key ends. */
3602
0
static int st_querynext(httrackp *opt, int argc, char **argv) {
3603
0
  const char *cur;
3604
0
  hts_query_field f;
3605
0
  String out = STRING_EMPTY;
3606
0
  int bad = 0;
3607
3608
0
  if (argc > 1) {
3609
0
    fprintf(stderr, "querynext: takes one query\n");
3610
0
    return 1;
3611
0
  }
3612
0
  for (cur = argc == 1 ? argv[0] : ""; hts_query_next(&cur, &f);) {
3613
0
    StringAddchar(out, '[');
3614
0
    StringCatSpan(&out, f.key);
3615
0
    bad |= f.whole.p != f.key.p;
3616
0
    if (hts_span_present(f.val)) {
3617
0
      StringAddchar(out, '|');
3618
0
      StringCatSpan(&out, f.val);
3619
0
      bad |= f.whole.len != f.key.len + 1 + f.val.len ||
3620
0
             f.val.p != f.key.p + f.key.len + 1;
3621
0
    } else {
3622
0
      bad |= f.whole.len != f.key.len || f.val.len != 0;
3623
0
    }
3624
0
    StringAddchar(out, ']');
3625
0
  }
3626
0
  printf("%s%s\n", StringBuff(out), bad ? " BADLEN" : "");
3627
0
  StringFree(out);
3628
0
  return bad;
3629
0
}
3630
3631
/* Prints fil_normalized_filtered() of argv[0], stripping argv[1]'s keys. */
3632
0
static int st_normfil(httrackp *opt, int argc, char **argv) {
3633
0
  char dest[HTS_URLMAXSIZE * 2];
3634
3635
0
  if (argc < 1 || argc > 2 || strlen(argv[0]) >= HTS_URLMAXSIZE) {
3636
0
    fprintf(stderr, "normfil: takes a path and an optional strip list\n");
3637
0
    return 1;
3638
0
  }
3639
0
  printf("[%s]\n",
3640
0
         fil_normalized_filtered(argv[0], dest, argc == 2 ? argv[1] : NULL));
3641
0
  return 0;
3642
0
}
3643
3644
/* This is the old --strip-query rule matcher. */
3645
0
static int legacy_hts_query_key_stripped(hts_span key, const char *strip) {
3646
0
  const char *p = strip;
3647
3648
0
  while (*p != '\0') {
3649
0
    const char *start = p;
3650
0
    size_t toklen;
3651
3652
0
    while (*p != '\0' && *p != ',')
3653
0
      p++;
3654
0
    toklen = (size_t) (p - start);
3655
0
    while (toklen > 0 && *start == ' ') {
3656
0
      start++;
3657
0
      toklen--;
3658
0
    }
3659
0
    while (toklen > 0 && start[toklen - 1] == ' ')
3660
0
      toklen--;
3661
0
    if (toklen == 1 && start[0] == '*')
3662
0
      return 1;
3663
0
    if (toklen == key.len && memcmp(start, key.p, key.len) == 0)
3664
0
      return 1;
3665
0
    if (*p == ',')
3666
0
      p++;
3667
0
  }
3668
0
  return 0;
3669
0
}
3670
3671
/* spandiff compares the frozen old rule parsers with the span-based ones. */
3672
3673
static const char *legacy_hts_query_strip_keys(const char *rules,
3674
                                               const char *adr, const char *fil,
3675
0
                                               hts_buf dest) {
3676
0
  const char *p, *q;
3677
0
  const char *result = NULL;
3678
0
  char BIGSTK url[HTS_URLMAXSIZE * 4];
3679
3680
0
  if (rules == NULL || *rules == '\0' || dest.size == 0)
3681
0
    return NULL;
3682
0
  (void) strclipbuff(url, sizeof(url), jump_normalized_const(adr));
3683
0
  if (fil[0] != '/')
3684
0
    (void) strclipbuff(&url[strlen(url)], sizeof(url) - strlen(url), "/");
3685
0
  q = strchr(fil, '?');
3686
0
  {
3687
0
    const size_t room = sizeof(url) - strlen(url) - 1;
3688
0
    const size_t fillen = q != NULL ? (size_t) (q - fil) : strlen(fil);
3689
3690
0
    strlncatbuff(url, fil, sizeof(url), fillen < room ? fillen : room);
3691
0
  }
3692
0
  for (p = rules; *p != '\0';) {
3693
0
    const char *const line = p;
3694
0
    const char *eol, *eq, *keys;
3695
0
    char BIGSTK pat[HTS_URLMAXSIZE * 2];
3696
3697
0
    while (*p != '\0' && *p != '\n')
3698
0
      p++;
3699
0
    eol = p;
3700
0
    if (*p == '\n')
3701
0
      p++;
3702
0
    if (eol == line)
3703
0
      continue;
3704
0
    eq = memchr(line, '=', (size_t) (eol - line));
3705
0
    if (eq != NULL) {
3706
0
      size_t patlen = (size_t) (eq - line);
3707
3708
0
      if (patlen >= sizeof(pat))
3709
0
        patlen = sizeof(pat) - 1;
3710
0
      memcpy(pat, line, patlen);
3711
0
      pat[patlen] = '\0';
3712
0
      keys = eq + 1;
3713
0
    } else {
3714
0
      pat[0] = '*';
3715
0
      pat[1] = '\0';
3716
0
      keys = line;
3717
0
    }
3718
0
    if (strjoker(url, pat, NULL, NULL) != NULL) {
3719
0
      size_t klen = (size_t) (eol - keys);
3720
3721
0
      if (klen >= dest.size)
3722
0
        klen = dest.size - 1;
3723
0
      memcpy(dest.p, keys, klen);
3724
0
      dest.p[klen] = '\0';
3725
0
      result = dest.p;
3726
0
    }
3727
0
  }
3728
0
  return result;
3729
0
}
3730
3731
static const char *legacy_hts_host_alias_match(const char *rules,
3732
                                               const char *host,
3733
                                               const char *full,
3734
                                               hts_boolean collapse_www,
3735
0
                                               size_t *canonlen) {
3736
0
  const char *p;
3737
0
  const char *canon = NULL;
3738
3739
0
  for (p = rules; *p != '\0';) {
3740
0
    const char *const line = p;
3741
0
    const char *eol, *eq, *pat;
3742
3743
0
    while (*p != '\0' && *p != '\n')
3744
0
      p++;
3745
0
    eol = p;
3746
0
    if (*p == '\n')
3747
0
      p++;
3748
0
    eq = memchr(line, '=', (size_t) (eol - line));
3749
0
    if (eq == NULL || eq == line || eq + 1 == eol)
3750
0
      continue;
3751
0
    for (pat = line; pat < eq;) {
3752
0
      const char *const sep = memchr(pat, ',', (size_t) (eq - pat));
3753
0
      const char *const end = sep != NULL ? sep : eq;
3754
0
      const char *start = pat;
3755
0
      size_t len = (size_t) (end - pat);
3756
0
      char BIGSTK glob[HTS_URLMAXSIZE * 2];
3757
3758
0
      while (len > 0 && (*start == ' ' || *start == '\t')) {
3759
0
        start++;
3760
0
        len--;
3761
0
      }
3762
0
      while (len > 0 && (start[len - 1] == ' ' || start[len - 1] == '\t' ||
3763
0
                         start[len - 1] == '/'))
3764
0
        len--;
3765
0
      if (len != 0 && len < sizeof(glob)) {
3766
0
        char *ghost;
3767
3768
0
        memcpy(glob, start, len);
3769
0
        glob[len] = '\0';
3770
0
        ghost = glob + (jump_protocol_const(glob) - glob);
3771
0
        if (collapse_www) {
3772
0
          const char *const bare = jump_normalized_const(ghost);
3773
3774
0
          if (bare != ghost)
3775
0
            memmove(ghost, bare, strlen(bare) + 1);
3776
0
        }
3777
0
        if (strjoker(strstr(glob, "://") != NULL ? full : host,
3778
0
                     strstr(glob, "://") != NULL ? glob : ghost, NULL,
3779
0
                     NULL) != NULL) {
3780
0
          const char *end = eol;
3781
3782
0
          canon = eq + 1;
3783
0
          while (canon < end && (*canon == ' ' || *canon == '\t'))
3784
0
            canon++;
3785
0
          while (end > canon &&
3786
0
                 (end[-1] == ' ' || end[-1] == '\t' || end[-1] == '/'))
3787
0
            end--;
3788
0
          *canonlen = (size_t) (end - canon);
3789
0
          break;
3790
0
        }
3791
0
      }
3792
0
      pat = end + 1;
3793
0
    }
3794
0
  }
3795
0
  return canon;
3796
0
}
3797
3798
static hts_boolean legacy_hts_host_alias_token_ok(hts_span tok,
3799
0
                                                  hts_boolean glob) {
3800
0
  char BIGSTK buff[HTS_URLMAXSIZE * 2];
3801
0
  const char *host;
3802
0
  size_t len;
3803
3804
0
  while (tok.len > 0 && (*tok.p == ' ' || *tok.p == '\t'))
3805
0
    tok = hts_span_skip(tok, 1);
3806
0
  while (tok.len > 0 &&
3807
0
         (tok.p[tok.len - 1] == ' ' || tok.p[tok.len - 1] == '\t'))
3808
0
    tok.len--;
3809
0
  len = tok.len;
3810
0
  if (len == 0 || len >= sizeof(buff))
3811
0
    return HTS_FALSE;
3812
0
  memcpy(buff, tok.p, len);
3813
0
  buff[len] = '\0';
3814
0
  while (len > 0 && buff[len - 1] == '/')
3815
0
    buff[--len] = '\0';
3816
0
  host = glob && strstr(buff, "://") != NULL ? strstr(buff, "://") + 3
3817
0
                                             : jump_protocol_const(buff);
3818
0
  if (*host == '\0' || strcmp(host, "primary") == 0)
3819
0
    return HTS_FALSE;
3820
0
  if (strchr(host, '/') != NULL)
3821
0
    return HTS_FALSE;
3822
0
  for (; *host != '\0'; host++) {
3823
0
    if ((unsigned char) *host < ' ' || *host == '\x7f')
3824
0
      return HTS_FALSE;
3825
0
    if (strchr(glob ? "=# " : "=,*?();\\#@ ", *host) != NULL)
3826
0
      return HTS_FALSE;
3827
0
  }
3828
0
  return HTS_TRUE;
3829
0
}
3830
3831
0
static hts_boolean legacy_hts_host_alias_rule_ok(const char *rule) {
3832
0
  const char *const eq = rule != NULL ? strchr(rule, '=') : NULL;
3833
0
  const char *pat;
3834
3835
0
  if (eq == NULL || eq == rule || eq[1] == '\0')
3836
0
    return HTS_FALSE;
3837
0
  if (!legacy_hts_host_alias_token_ok(hts_span_of(eq + 1), HTS_FALSE))
3838
0
    return HTS_FALSE;
3839
0
  for (pat = rule; pat < eq;) {
3840
0
    const char *const sep = memchr(pat, ',', (size_t) (eq - pat));
3841
0
    const char *const end = sep != NULL ? sep : eq;
3842
3843
0
    if (!legacy_hts_host_alias_token_ok(hts_span_between(pat, end), HTS_TRUE))
3844
0
      return HTS_FALSE;
3845
0
    pat = end + 1;
3846
0
  }
3847
0
  return HTS_TRUE;
3848
0
}
3849
3850
static const char *legacy_hts_host_alias_looping(const char *rules,
3851
                                                 hts_boolean collapse_www,
3852
0
                                                 hts_buf dest) {
3853
0
  const char *p;
3854
3855
0
  if (rules == NULL || dest.size == 0)
3856
0
    return NULL;
3857
0
  for (p = rules; *p != '\0';) {
3858
0
    const char *const line = p;
3859
0
    const char *eol, *eq;
3860
3861
0
    while (*p != '\0' && *p != '\n')
3862
0
      p++;
3863
0
    eol = p;
3864
0
    if (*p == '\n')
3865
0
      p++;
3866
0
    eq = memchr(line, '=', (size_t) (eol - line));
3867
0
    if (eq == NULL || eq + 1 == eol)
3868
0
      continue;
3869
0
    {
3870
0
      const size_t len = (size_t) (eol - eq - 1);
3871
0
      char BIGSTK canon[HTS_URLMAXSIZE * 2], tmp[HTS_URLMAXSIZE * 2];
3872
0
      hts_boolean settled;
3873
3874
0
      if (len >= sizeof(canon))
3875
0
        continue;
3876
0
      memcpy(canon, eq + 1, len);
3877
0
      canon[len] = '\0';
3878
0
      (void) !hts_host_alias_resolve(rules, canon, collapse_www, HTS_BUF(tmp),
3879
0
                                     &settled);
3880
0
      if (!settled) {
3881
0
        if (strlen(canon) >= dest.size)
3882
0
          continue;
3883
0
        hts_buf_cpy(dest, canon);
3884
0
        return dest.p;
3885
0
      }
3886
0
    }
3887
0
  }
3888
0
  return NULL;
3889
0
}
3890
3891
static void spandiff_one(parsediff_stats *st, const char *rules,
3892
0
                         const char *longhost, const char *longfil) {
3893
0
  static const char *const keys[] = {"",      "a",         "sid",    "*",
3894
0
                                     "a.com", " ",         "x",      "utm",
3895
0
                                     "b",     "www.a.com", "a.com/", NULL};
3896
  /* NULL in an {adr, fil} pair means longhost or longfil. */
3897
0
  static const char *const adrs[] = {
3898
0
      "a.com", "/p?sid=1&a=2", "www.a.com", "x",     "http://b", "/x/y?z", "",
3899
0
      "",      NULL,           "/p?utm=1",  "a.com", NULL};
3900
  /* NULL in a {host, full} pair means longhost. */
3901
0
  static const char *const hosts[] = {
3902
0
      "a.com", "http://a.com", "www.a.com", "https://www.a.com",
3903
0
      "b",     "ftp://b",      "",          "http://",
3904
0
      "x.com", "http://x.com", NULL,        NULL};
3905
0
  static const size_t sizes[] = {1, 2, 8, 4096};
3906
0
  size_t i, j;
3907
0
  int www;
3908
0
  hts_span rest = hts_span_of(rules);
3909
0
  hts_span line;
3910
3911
0
  for (i = 0; keys[i] != NULL; i++) {
3912
0
    st->cases++;
3913
0
    if (hts_query_key_stripped(hts_span_of(keys[i]), rules) !=
3914
0
        (legacy_hts_query_key_stripped(hts_span_of(keys[i]), rules) != 0))
3915
0
      parsediff_fail(st, "hts_query_key_stripped", rules, keys[i], "", "");
3916
0
  }
3917
0
  for (i = 0; i < sizeof(adrs) / sizeof(adrs[0]); i += 2) {
3918
0
    const char *const adr = adrs[i] != NULL ? adrs[i] : longhost;
3919
0
    const char *const fil = adrs[i + 1] != NULL ? adrs[i + 1] : longfil;
3920
3921
0
    for (j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) {
3922
0
      char o[4096], n[4096];
3923
0
      const char *ro, *rn;
3924
3925
0
      memset(o, 'O', sizeof(o));
3926
0
      memset(n, 'O', sizeof(n));
3927
0
      st->cases++;
3928
0
      ro =
3929
0
          legacy_hts_query_strip_keys(rules, adr, fil, hts_buf_at(o, sizes[j]));
3930
0
      rn = hts_query_strip_keys(rules, adr, fil, hts_buf_at(n, sizes[j]));
3931
0
      if ((ro == NULL) != (rn == NULL) ||
3932
0
          (ro != NULL && (rn != n || strcmp(o, n) != 0)))
3933
0
        parsediff_fail(st, "hts_query_strip_keys", rules, adr,
3934
0
                       ro != NULL ? o : "(none)", rn != NULL ? n : "(none)");
3935
0
    }
3936
0
  }
3937
0
  for (i = 0; i < sizeof(hosts) / sizeof(hosts[0]); i += 2) {
3938
0
    const char *const host = hosts[i] != NULL ? hosts[i] : longhost;
3939
0
    const char *const full = hosts[i + 1] != NULL ? hosts[i + 1] : longhost;
3940
3941
0
    for (www = 0; www < 2; www++) {
3942
0
      size_t lo = 0, ln = 0;
3943
0
      const char *const co =
3944
0
          legacy_hts_host_alias_match(rules, host, full, www, &lo);
3945
0
      const char *const cn = hts_host_alias_match(rules, host, full, www, &ln);
3946
3947
0
      st->cases++;
3948
0
      if (co != cn || (co != NULL && lo != ln))
3949
0
        parsediff_fail(st, "hts_host_alias_match", rules, host, "", "");
3950
0
    }
3951
0
  }
3952
0
  st->cases++;
3953
0
  if (hts_host_alias_rule_ok(rules) != legacy_hts_host_alias_rule_ok(rules))
3954
0
    parsediff_fail(st, "hts_host_alias_rule_ok", rules, "", "", "");
3955
0
  for (www = 0; www < 2; www++) {
3956
0
    for (j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) {
3957
0
      char o[4096], n[4096];
3958
0
      const char *ro, *rn;
3959
3960
0
      memset(o, 'O', sizeof(o));
3961
0
      memset(n, 'O', sizeof(n));
3962
0
      st->cases++;
3963
0
      ro = legacy_hts_host_alias_looping(rules, www, hts_buf_at(o, sizes[j]));
3964
0
      rn = hts_host_alias_looping(rules, www, hts_buf_at(n, sizes[j]));
3965
0
      if ((ro == NULL) != (rn == NULL) || (rn != NULL && rn != n) ||
3966
0
          memcmp(o, n, sizeof(o)) != 0)
3967
0
        parsediff_fail(st, "hts_host_alias_looping", rules, "",
3968
0
                       ro != NULL ? o : "(none)", rn != NULL ? n : "(none)");
3969
0
    }
3970
0
  }
3971
  /* each line alone, which is what --host-alias hands the validator */
3972
0
  while (hts_span_next_in(&rest, '\n', &line)) {
3973
0
    char *one = malloct(line.len + 1);
3974
3975
0
    assertf(one != NULL);
3976
0
    (void) !hts_buf_put_span_clip(hts_buf_at(one, line.len + 1), line);
3977
0
    st->cases++;
3978
0
    if (hts_host_alias_rule_ok(one) != legacy_hts_host_alias_rule_ok(one))
3979
0
      parsediff_fail(st, "hts_host_alias_rule_ok", one, "line", "", "");
3980
0
    freet(one);
3981
0
  }
3982
0
}
3983
3984
0
static int st_spandiff(httrackp *opt, int argc, char **argv) {
3985
0
  static const char *const hand[] = {"",
3986
0
                                     "\n",
3987
0
                                     "\n\n",
3988
0
                                     "=",
3989
0
                                     "==",
3990
0
                                     ",",
3991
0
                                     ",=a.com",
3992
0
                                     "a.com,=b",
3993
0
                                     "a.com=",
3994
0
                                     "=a.com",
3995
0
                                     "a.com=b.com",
3996
0
                                     " a.com = b.com ",
3997
0
                                     "\ta.com\t=\tb.com/\t",
3998
0
                                     "a.com/=b.com//",
3999
0
                                     "a.com/ /=b.com/ /",
4000
0
                                     "a.com /=b.com",
4001
0
                                     "www.a.com=b",
4002
0
                                     "a.com=www.b",
4003
0
                                     "http://a.com=b",
4004
0
                                     "*://a.com=b",
4005
0
                                     "https://*=b",
4006
0
                                     "a.com,b,x.com=c",
4007
0
                                     "x,,a.com=c",
4008
0
                                     "a.com=b=c",
4009
0
                                     "a.com=b,c",
4010
0
                                     "a.com=b\na.com=c",
4011
0
                                     "a.com=b\n\na.com=",
4012
0
                                     "a.com=b\n",
4013
0
                                     "\na.com=b",
4014
0
                                     "a.com=primary",
4015
0
                                     "a.com=b/c",
4016
0
                                     "a.com=user@b",
4017
0
                                     "*=b",
4018
0
                                     "*.com=b",
4019
0
                                     "sid",
4020
0
                                     "sid,utm",
4021
0
                                     " sid , utm ",
4022
0
                                     "*",
4023
0
                                     " * ",
4024
0
                                     "a,,b",
4025
0
                                     "a,",
4026
0
                                     ",a",
4027
0
                                     " ",
4028
0
                                     "*=sid",
4029
0
                                     "a.com/*=sid\n*=utm",
4030
0
                                     "*a.com*=sid,a\nx*=",
4031
0
                                     "x/y*=z",
4032
0
                                     "=sid",
4033
0
                                     "a.com=b\r",
4034
0
                                     "a.com\r=b",
4035
0
                                     "a=",
4036
0
                                     "=",
4037
0
                                     "a=\n=b",
4038
0
                                     "a.com=b.com\nb.com=a.com",
4039
0
                                     "x=a.com\na.com=b.com\nb.com=a.com",
4040
0
                                     "=a\na=b\nb=a",
4041
0
                                     "a=b\nb=c\nc=d\nd=e\ne=f\nf=g\ng=h\nh="
4042
0
                                     "i\ni=j\nj=k",
4043
0
                                     "a=b\nb=c\nc=d\nd=e\ne=f\nf=g\ng=h\nh="
4044
0
                                     "i\ni=j",
4045
0
                                     "a=b\r\nb=a\r\n",
4046
0
                                     "a b c",
4047
0
                                     "a  b ",
4048
0
                                     "  ",
4049
0
                                     NULL};
4050
  /* Runs around the 2048-byte pattern and glob buffers. */
4051
0
  static const size_t lengths[] = {2045, 2046, 2047, 2048, 2049};
4052
0
  static const char *const alphabet[] = {
4053
0
      "a.com", "b",  "x",     "*",       "=",   ",",   "\n",  " ",
4054
0
      "\t",    "/",  "www.",  "http://", "sid", "utm", "a",   "?",
4055
0
      "*.com", "//", "x.com", "primary", "@",   "\r",  "://", ""};
4056
0
  parsediff_stats st = {0, 0};
4057
0
  uint32_t seed = 546;
4058
0
  size_t i;
4059
0
  int r;
4060
0
  char *longhost = parsediff_run('x', 2047);
4061
0
  String longfil = STRING_EMPTY;
4062
4063
  /* Only a clipped pattern, a.com/ followed by *x..x, matches this path,
4064
     because strjoker refuses a longer pattern. */
4065
0
  StringCat(longfil, "/");
4066
0
  StringMemcat(longfil, longhost, 2040);
4067
  /* A span may hold a NUL, and no trim set matches one. */
4068
0
  {
4069
0
    static const char nul[] = " a\0b ";
4070
0
    const hts_span s = {nul, sizeof(nul) - 1};
4071
0
    hts_span rest = s, f, t;
4072
0
    char d[8];
4073
4074
0
    t = hts_span_trim(s, " ab", " ab");
4075
0
    if (t.p != nul + 2 || t.len != 1)
4076
0
      parsediff_fail(&st, "hts_span_trim NUL", "' a\\0b '", "", "", "");
4077
0
    if (!hts_span_next_in(&rest, '\0', &f) || f.len != 2 ||
4078
0
        !hts_span_next_in(&rest, '\0', &f) || f.p != nul + 3 || f.len != 2 ||
4079
0
        hts_span_next_in(&rest, '\0', &f))
4080
0
      parsediff_fail(&st, "hts_span_next_in NUL", "' a\\0b '", "", "", "");
4081
0
    if (!hts_span_copy(s, d, sizeof(d)) || memcmp(d, nul, sizeof(nul)) != 0)
4082
0
      parsediff_fail(&st, "hts_span_copy NUL", "' a\\0b '", "", "", "");
4083
0
  }
4084
  /* No NUL follows these bytes, so an over-read shows under ASan. */
4085
0
  {
4086
0
    static const char text[] = " a,b=c/";
4087
0
    const size_t len = sizeof(text) - 1;
4088
0
    char *buf = malloct(len);
4089
0
    hts_span s, rest, f, h, t;
4090
0
    char d[sizeof(text)];
4091
0
    size_t n = 0;
4092
4093
0
    assertf(buf != NULL);
4094
0
    memcpy(buf, text, len);
4095
0
    s = hts_span_at(buf, len);
4096
0
    for (rest = s; hts_span_next_in(&rest, ',', &f);)
4097
0
      n++;
4098
0
    if (n != 2 || f.p != buf + 3 || f.len != len - 3)
4099
0
      parsediff_fail(&st, "hts_span_next_in unterminated", text, "", "", "");
4100
0
    if (hts_span_split(f, ';', &h, &t) || !hts_span_split(f, '=', &h, &t) ||
4101
0
        t.p != buf + 5 || t.len != 2)
4102
0
      parsediff_fail(&st, "hts_span_split unterminated", text, "", "", "");
4103
0
    t = hts_span_trim(s, " ", "/");
4104
0
    if (t.p != buf + 1 || t.len != len - 2)
4105
0
      parsediff_fail(&st, "hts_span_trim unterminated", text, "", "", "");
4106
0
    if (!hts_span_copy(s, d, sizeof(d)) || strcmp(d, text) != 0)
4107
0
      parsediff_fail(&st, "hts_span_copy unterminated", text, "", "", "");
4108
0
    freet(buf);
4109
0
  }
4110
0
  for (i = 0; hand[i] != NULL; i++)
4111
0
    spandiff_one(&st, hand[i], longhost, StringBuff(longfil));
4112
0
  for (i = 0; i < sizeof(lengths) / sizeof(lengths[0]); i++) {
4113
0
    static const char *const shapes[] = {
4114
0
        "%s=b.com",  "%s/=b.com",    "%s =b.com",    " %s=b.com", "a.com=%s",
4115
0
        "a.com=%s/", "%s*=sid",      "%s=sid",       "sid,%s",    "*=%s",
4116
0
        "%s",        "b,%s,c=a.com", "a.com/*%s=sid"};
4117
0
    char *run = parsediff_run('x', lengths[i]);
4118
0
    size_t k;
4119
4120
0
    for (k = 0; k < sizeof(shapes) / sizeof(shapes[0]); k++) {
4121
0
      const char *const at = strstr(shapes[k], "%s");
4122
0
      String rules = STRING_EMPTY;
4123
4124
0
      StringMemcat(rules, shapes[k], (size_t) (at - shapes[k]));
4125
0
      StringCat(rules, run);
4126
0
      StringCat(rules, at + 2);
4127
0
      spandiff_one(&st, StringBuff(rules), longhost, StringBuff(longfil));
4128
0
      if (strncmp(shapes[k], "a.com/*", 7) == 0) {
4129
0
        char o[8], n[8];
4130
4131
0
        if (legacy_hts_query_strip_keys(StringBuff(rules), "a.com",
4132
0
                                        StringBuff(longfil),
4133
0
                                        HTS_BUF(o)) == NULL ||
4134
0
            hts_query_strip_keys(StringBuff(rules), "a.com",
4135
0
                                 StringBuff(longfil), HTS_BUF(n)) == NULL)
4136
0
          parsediff_fail(&st, "clipped pattern matches", StringBuff(rules),
4137
0
                         "a.com", "", "");
4138
0
      }
4139
0
      StringFree(rules);
4140
0
    }
4141
    /* A loop that a clipped copy of the too-long first target would join. */
4142
0
    {
4143
0
      const size_t scheme = strlen("http://");
4144
0
      String rules = STRING_EMPTY;
4145
4146
0
      StringCat(rules, "a=http://");
4147
0
      StringMemcat(rules, run, lengths[i] - scheme);
4148
0
      StringCat(rules, "\nhttp://");
4149
0
      StringMemcat(rules, run, lengths[i] - scheme - 1);
4150
0
      StringCat(rules, "=b\nb=http://");
4151
0
      StringMemcat(rules, run, lengths[i] - scheme - 1);
4152
0
      spandiff_one(&st, StringBuff(rules), longhost, StringBuff(longfil));
4153
0
      StringFree(rules);
4154
0
    }
4155
0
    freet(run);
4156
0
  }
4157
0
  for (r = 0; r < 6000; r++) {
4158
0
    String rules = STRING_EMPTY;
4159
4160
0
    parsediff_random(&rules, &seed, alphabet,
4161
0
                     sizeof(alphabet) / sizeof(alphabet[0]), 16);
4162
0
    spandiff_one(&st, StringBuff(rules) != NULL ? StringBuff(rules) : "",
4163
0
                 longhost, StringBuff(longfil));
4164
0
    StringFree(rules);
4165
0
  }
4166
0
  freet(longhost);
4167
0
  StringFree(longfil);
4168
0
  printf("spandiff: %lu cases, %lu failures\n", st.cases, st.failures);
4169
0
  if (st.failures == 0)
4170
0
    printf("spandiff: OK\n");
4171
0
  return st.failures != 0;
4172
0
}
4173
4174
/* CR and LF print as \r and \n, which Windows text-mode stdout leaves alone. */
4175
0
static void span_add_visible(String *out, hts_span s) {
4176
0
  size_t i;
4177
4178
0
  for (i = 0; i < s.len; i++) {
4179
0
    if (s.p[i] == '\r')
4180
0
      StringCat(*out, "\\r");
4181
0
    else if (s.p[i] == '\n')
4182
0
      StringCat(*out, "\\n");
4183
0
    else
4184
0
      StringAddchar(*out, s.p[i]);
4185
0
  }
4186
0
}
4187
4188
/* N if P is WANT, for checking what HTS_SIZED passes. */
4189
0
static size_t st_sized(const char *p, size_t n, const char *want) {
4190
0
  return p == want ? n : 0;
4191
0
}
4192
4193
/* buf [tail-overrun]: the sizes HTS_BUF, HTS_BUF_N, HTS_SIZED, hts_buf_skip and
4194
   hts_buf_none give. tail-overrun takes a tail with no byte left, which must
4195
   abort. */
4196
0
static int st_buf(httrackp *opt, int argc, char **argv) {
4197
0
  struct {
4198
0
    char f[7];
4199
0
    char g[64];
4200
0
  } st;
4201
4202
0
  char a[32];
4203
0
  const hts_buf b = HTS_BUF(a);
4204
0
  hts_buf t;
4205
0
  int bad = 0;
4206
4207
0
  (void) opt;
4208
0
  if (argc >= 1 && strcmp(argv[0], "tail-overrun") == 0)
4209
0
    (void) hts_buf_skip(b, b.size);
4210
0
  if (b.p != a || b.size != sizeof(a) || HTS_BUF(st.f).p != st.f ||
4211
0
      HTS_BUF(st.f).size != 7 || HTS_BUF_N(st.g, 64).size != 64 ||
4212
0
      HTS_BUF_N(a, 1).p != a || HTS_BUF_N(a, 1).size != 1 ||
4213
0
      st_sized(HTS_SIZED(a), a) != 32 || st_sized(HTS_SIZED(st.f), st.f) != 7) {
4214
0
    printf("buf: wrong array size\n");
4215
0
    bad = 1;
4216
0
  }
4217
0
  t = hts_buf_skip(b, 0);
4218
0
  if (t.p != a || t.size != 32) {
4219
0
    printf("buf: tail 0 moved\n");
4220
0
    bad = 1;
4221
0
  }
4222
0
  t = hts_buf_skip(b, 31);
4223
0
  if (t.p != a + 31 || t.size != 1) {
4224
0
    printf("buf: tail 31 is %d bytes\n", (int) t.size);
4225
0
    bad = 1;
4226
0
  }
4227
  /* a size-0 buffer is not the absent one */
4228
0
  if (!hts_buf_is_none(hts_buf_none()) || hts_buf_none().size != 0 ||
4229
0
      hts_buf_is_none(b) || hts_buf_is_none(hts_buf_at(a, 0))) {
4230
0
    printf("buf: hts_buf_none is not the absent buffer\n");
4231
0
    bad = 1;
4232
0
  }
4233
0
  if (!bad)
4234
0
    printf("buf: OK\n");
4235
0
  return bad;
4236
0
}
4237
4238
/* Announce the line of a call that must abort, before it aborts. */
4239
0
static void st_abort_line(int line) {
4240
0
  printf("aborts at line %d\n", line);
4241
0
  fflush(stdout);
4242
0
}
4243
4244
/* bufwrite [cpy|cat|catn|unterminated[-cpy|-catn]]: the hts_buf write helpers.
4245
   An argument overflows that helper, which must abort at the line it prints. */
4246
0
static int st_bufwrite(httrackp *opt, int argc, char **argv) {
4247
0
  struct {
4248
0
    char name[12]; /* not pointer-sized, so MSVC sees an array */
4249
0
    char secret[16];
4250
0
  } r;
4251
4252
0
  char a[8], big[16], out[64];
4253
0
  const hts_buf b = HTS_BUF_N(big, 6);
4254
0
  const char *const mode = argc >= 1 ? argv[0] : "";
4255
0
  int bad = 0;
4256
4257
0
  (void) opt;
4258
0
  memset(r.name, 'N', sizeof(r.name));
4259
0
  strcpybuff(r.secret, "SECRET");
4260
0
  out[0] = '\0';
4261
0
  memset(big, 'X', sizeof(big));
4262
0
  big[0] = '\0';
4263
0
  if (strcmp(mode, "cpy") == 0) {
4264
0
    st_abort_line(__LINE__ + 1);
4265
0
    hts_buf_cpy(b, "abcdef");
4266
0
  }
4267
0
  if (strcmp(mode, "cat") == 0) {
4268
0
    st_abort_line(__LINE__ + 1);
4269
0
    hts_buf_cat(HTS_BUF_N(big, 4), "abcd");
4270
0
  }
4271
0
  if (strcmp(mode, "catn") == 0) {
4272
0
    st_abort_line(__LINE__ + 1);
4273
0
    hts_buf_catn(HTS_BUF_N(big, 2), "abcd", 2);
4274
0
  }
4275
0
  if (strcmp(mode, "unterminated") == 0) {
4276
0
    st_abort_line(__LINE__ + 1);
4277
0
    hts_buf_cat(HTS_BUF(out), r.name);
4278
0
  }
4279
0
  if (strcmp(mode, "unterminated-cpy") == 0) {
4280
0
    st_abort_line(__LINE__ + 1);
4281
0
    hts_buf_cpy(HTS_BUF(out), r.name);
4282
0
  }
4283
0
  if (strcmp(mode, "unterminated-catn") == 0) {
4284
0
    st_abort_line(__LINE__ + 1);
4285
0
    hts_buf_catn(HTS_BUF(out), r.name, 4);
4286
0
  }
4287
0
  memset(big, 'X', sizeof(big));
4288
0
  hts_buf_cpy(b, "ab");
4289
0
  hts_buf_cat(b, "c");
4290
0
  hts_buf_catn(b, "dxyz", 2);
4291
0
  bad |= strcmp(big, "abcdx") != 0 || big[6] != 'X';
4292
0
  hts_buf_cpy(HTS_BUF(a), "1234567");
4293
0
  bad |= strcmp(a, "1234567") != 0;
4294
0
  memset(big, 'Y', sizeof(big));
4295
0
  bad |= !hts_buf_cpy_clip(b, "12345") || strcmp(big, "12345") != 0;
4296
0
  memset(big, 'Z', sizeof(big));
4297
0
  bad |= hts_buf_cpy_clip(b, "abcdef") || strcmp(big, "abcde") != 0;
4298
0
  memset(big, 'Y', sizeof(big));
4299
0
  bad |= !hts_buf_printf(b, "%d-%s", 12, "ab") || strcmp(big, "12-ab") != 0;
4300
0
  memset(big, 'Z', sizeof(big));
4301
0
  bad |= hts_buf_printf(b, "%d+%s", 34, "cde") || strcmp(big, "34+cd") != 0;
4302
0
  memset(big, 'Y', sizeof(big));
4303
0
  hts_buf_printf_clip(b, "%s", "uvwxyz");
4304
0
  bad |= strcmp(big, "uvwxy") != 0 || big[6] != 'Y';
4305
  /* put_span: the span stops before the source's NUL, and a misfit is "" */
4306
0
  memset(big, 'Y', sizeof(big));
4307
0
  bad |= !hts_buf_put_span(b, hts_span_at("abcdefgh", 5)) ||
4308
0
         strcmp(big, "abcde") != 0 || big[6] != 'Y';
4309
0
  memset(big, 'Z', sizeof(big));
4310
0
  bad |= hts_buf_put_span(b, hts_span_at("abcdefgh", 6)) || big[0] != '\0' ||
4311
0
         big[1] != 'Z';
4312
0
  memset(big, 'Y', sizeof(big));
4313
0
  bad |= !hts_buf_put_span(b, hts_span_at("", 0)) || big[0] != '\0' ||
4314
0
         big[1] != 'Y';
4315
0
  memset(big, 'Z', sizeof(big));
4316
0
  bad |=
4317
0
      hts_buf_put_span(hts_buf_at(big, 0), hts_span_at("", 0)) || big[0] != 'Z';
4318
  /* put_span_clip: a misfit keeps its first size - 1 bytes */
4319
0
  memset(big, 'Y', sizeof(big));
4320
0
  bad |= !hts_buf_put_span_clip(b, hts_span_at("abcdefgh", 5)) ||
4321
0
         strcmp(big, "abcde") != 0 || big[6] != 'Y';
4322
0
  memset(big, 'Z', sizeof(big));
4323
0
  bad |= hts_buf_put_span_clip(b, hts_span_at("abcdefgh", 6)) ||
4324
0
         strcmp(big, "abcde") != 0 || big[6] != 'Z';
4325
0
  memset(big, 'Z', sizeof(big));
4326
0
  bad |= hts_buf_put_span_clip(hts_buf_at(big, 0), hts_span_at("a", 1)) ||
4327
0
         hts_buf_put_span_clip(hts_buf_at(big, 0), hts_span_at("", 0)) ||
4328
0
         big[0] != 'Z';
4329
  /* hts_span_dup copies exactly the span, including an inner NUL. */
4330
0
  {
4331
0
    char *d = hts_span_dup(hts_span_at("ab\0cdef", 4));
4332
0
    char *e = hts_span_dup(hts_span_at("x", 0));
4333
4334
0
    bad |= d == NULL || memcmp(d, "ab\0c", 5) != 0 || e == NULL || e[0] != '\0';
4335
0
    freet(d);
4336
0
    freet(e);
4337
0
  }
4338
0
  printf(bad ? "bufwrite: FAILED\n" : "bufwrite: OK\n");
4339
0
  return bad;
4340
0
}
4341
4342
/* Fill B with 'P' and its canary with 'C', then copy TEXT in unless NULL. */
4343
0
static void st_buftry_reset(char *b, size_t size, const char *text) {
4344
0
  memset(b, 'P', size);
4345
0
  memset(b + 8, 'C', size - 8);
4346
0
  if (text != NULL)
4347
0
    memcpy(b, text, strlen(text) + 1);
4348
0
}
4349
4350
/* Does B read as WANT (with its NUL), and keep its poison and canary after? */
4351
0
static hts_boolean st_buftry_is(const char *b, size_t size, const char *want) {
4352
0
  const size_t n = strlen(want) + 1;
4353
0
  size_t i;
4354
4355
0
  if (memcmp(b, want, n) != 0)
4356
0
    return HTS_FALSE;
4357
0
  for (i = n; i < size; i++) {
4358
0
    if (b[i] != (i < 8 ? 'P' : 'C'))
4359
0
      return HTS_FALSE;
4360
0
  }
4361
0
  return HTS_TRUE;
4362
0
}
4363
4364
/* buftry: hts_buf_try_cpy and hts_buf_try_cat copy whole or refuse. */
4365
0
static int st_buftry(httrackp *opt, int argc, char **argv) {
4366
0
  char r[12]; /* an 8-byte buffer, then a 4-byte canary */
4367
0
  const hts_buf b = HTS_BUF_N(r, 8);
4368
0
  int bad = 0;
4369
4370
0
  (void) opt;
4371
0
  (void) argc;
4372
0
  (void) argv;
4373
  /* try_cpy: an exact fit, one over, an empty S, then sizes 1 and 0 */
4374
0
  st_buftry_reset(r, sizeof(r), NULL);
4375
0
  bad |=
4376
0
      !hts_buf_try_cpy(b, "1234567") || !st_buftry_is(r, sizeof(r), "1234567");
4377
0
  st_buftry_reset(r, sizeof(r), NULL);
4378
0
  bad |= hts_buf_try_cpy(b, "12345678") || !st_buftry_is(r, sizeof(r), "");
4379
0
  st_buftry_reset(r, sizeof(r), NULL);
4380
0
  bad |= !hts_buf_try_cpy(b, "") || !st_buftry_is(r, sizeof(r), "");
4381
0
  st_buftry_reset(r, sizeof(r), NULL);
4382
0
  bad |=
4383
0
      !hts_buf_try_cpy(hts_buf_at(r, 1), "") || !st_buftry_is(r, sizeof(r), "");
4384
0
  st_buftry_reset(r, sizeof(r), NULL);
4385
0
  bad |=
4386
0
      hts_buf_try_cpy(hts_buf_at(r, 1), "a") || !st_buftry_is(r, sizeof(r), "");
4387
0
  st_buftry_reset(r, sizeof(r), NULL);
4388
0
  bad |= hts_buf_try_cpy(hts_buf_at(r, 0), "") || r[0] != 'P';
4389
0
  bad |= hts_buf_try_cpy(hts_buf_none(), "");
4390
  /* try_cat: an exact fit, one over, an empty S, a full B, sizes 1 and 0 */
4391
0
  st_buftry_reset(r, sizeof(r), "abc");
4392
0
  bad |= !hts_buf_try_cat(b, "defg") || !st_buftry_is(r, sizeof(r), "abcdefg");
4393
0
  st_buftry_reset(r, sizeof(r), "abc");
4394
0
  bad |= hts_buf_try_cat(b, "defgh") || !st_buftry_is(r, sizeof(r), "abc");
4395
0
  st_buftry_reset(r, sizeof(r), "abc");
4396
0
  bad |= !hts_buf_try_cat(b, "") || !st_buftry_is(r, sizeof(r), "abc");
4397
0
  st_buftry_reset(r, sizeof(r), "1234567");
4398
0
  bad |= hts_buf_try_cat(b, "x") || !st_buftry_is(r, sizeof(r), "1234567");
4399
0
  bad |= !hts_buf_try_cat(b, "") || !st_buftry_is(r, sizeof(r), "1234567");
4400
0
  st_buftry_reset(r, sizeof(r), "");
4401
0
  bad |=
4402
0
      !hts_buf_try_cat(hts_buf_at(r, 1), "") || !st_buftry_is(r, sizeof(r), "");
4403
0
  bad |=
4404
0
      hts_buf_try_cat(hts_buf_at(r, 1), "a") || !st_buftry_is(r, sizeof(r), "");
4405
0
  st_buftry_reset(r, sizeof(r), NULL);
4406
0
  bad |= hts_buf_try_cat(hts_buf_at(r, 0), "") || r[0] != 'P';
4407
0
  bad |= hts_buf_try_cat(hts_buf_none(), "");
4408
  /* a B with no NUL is already over, so even "" is refused */
4409
0
  bad |= hts_buf_try_cat(b, "") || r[7] != 'P' || r[8] != 'C';
4410
0
  printf(bad ? "buftry: FAILED\n" : "buftry: OK\n");
4411
0
  return bad;
4412
0
}
4413
4414
/* Print what a span primitive reads as [bytes], for next|nextsep|nextin|split C
4415
   TEXT, param C TEXT, trim L R TEXT, copy SIZE TEXT, or
4416
   header|headersplit TEXT. */
4417
0
static int st_span(httrackp *opt, int argc, char **argv) {
4418
0
  String out = STRING_EMPTY;
4419
0
  hts_span s, a, b;
4420
0
  int ret = 0;
4421
4422
0
  if (argc < 2 || (strncmp(argv[0], "header", 6) != 0 && argc < 3) ||
4423
0
      (strcmp(argv[0], "trim") == 0 && argc < 4)) {
4424
0
    fprintf(stderr, "span: bad arguments\n");
4425
0
    return 1;
4426
0
  }
4427
0
  s = hts_span_of(argv[argc - 1]);
4428
0
  if (strcmp(argv[0], "next") == 0) {
4429
0
    const char *const end = s.p + s.len;
4430
4431
0
    while (hts_span_next_in(&s, argv[1][0], &a)) {
4432
0
      StringAddchar(out, '[');
4433
0
      StringCatSpan(&out, a);
4434
0
      StringAddchar(out, ']');
4435
0
    }
4436
0
    if (s.p != end)
4437
0
      StringCat(out, " BADEND");
4438
0
  } else if (strcmp(argv[0], "nextsep") == 0) {
4439
    /* Each field shows with the separator it ended on. */
4440
0
    while (hts_span_next_in(&s, argv[1][0], &a)) {
4441
0
      StringAddchar(out, '[');
4442
0
      span_add_visible(&out, hts_span_between(a.p, s.p));
4443
0
      StringAddchar(out, ']');
4444
0
    }
4445
0
  } else if (strcmp(argv[0], "nextin") == 0) {
4446
    /* Each field shows with what is left after it. */
4447
0
    while (hts_span_next_in(&s, argv[1][0], &a)) {
4448
0
      StringAddchar(out, '[');
4449
0
      span_add_visible(&out, a);
4450
0
      StringAddchar(out, '|');
4451
0
      span_add_visible(&out, s);
4452
0
      StringAddchar(out, ']');
4453
0
    }
4454
0
  } else if (strcmp(argv[0], "split") == 0) {
4455
0
    if (hts_span_split(s, argv[1][0], &a, &b)) {
4456
0
      StringAddchar(out, '[');
4457
0
      StringCatSpan(&out, a);
4458
0
      StringAddchar(out, '|');
4459
0
      StringCatSpan(&out, b);
4460
0
      StringAddchar(out, ']');
4461
0
    } else {
4462
0
      StringCat(out, "none");
4463
0
    }
4464
0
  } else if (strcmp(argv[0], "param") == 0) {
4465
    /* Each field shows as [name|value], or [name] with no value. A "hex:" text
4466
       keeps its CRs, which Windows text-mode stdin folds. */
4467
0
    char text[256];
4468
0
    const size_t n = st_decode_body(argv[2], HTS_BUF(text));
4469
4470
0
    if (n + 1 >= sizeof(text)) {
4471
0
      fprintf(stderr, "span: param takes a text below 255 bytes\n");
4472
0
      StringFree(out);
4473
0
      return 1;
4474
0
    }
4475
0
    for (s = hts_span_at(text, n); hts_param_next(&s, argv[1][0], &a, &b);) {
4476
0
      StringAddchar(out, '[');
4477
0
      span_add_visible(&out, a);
4478
0
      if (hts_span_present(b)) {
4479
0
        StringAddchar(out, '|');
4480
0
        span_add_visible(&out, b);
4481
0
      }
4482
0
      StringAddchar(out, ']');
4483
0
    }
4484
0
    if (s.p != text + n)
4485
0
      StringCat(out, " BADEND");
4486
0
  } else if (strcmp(argv[0], "header") == 0) {
4487
    /* Each line shows as [line|name|value], then what stopped the walk. A
4488
       "hex:" text keeps its CRLFs, which Windows text-mode stdin folds. */
4489
0
    char text[256];
4490
0
    hts_header_field f;
4491
4492
0
    s = hts_span_at(text, st_decode_body(argv[argc - 1], HTS_BUF(text)));
4493
4494
0
    while (hts_header_next(&s, &f)) {
4495
0
      StringAddchar(out, '[');
4496
0
      span_add_visible(&out, f.line);
4497
0
      StringAddchar(out, '|');
4498
0
      span_add_visible(&out, f.name);
4499
0
      StringAddchar(out, '|');
4500
0
      span_add_visible(&out, f.value);
4501
0
      StringAddchar(out, ']');
4502
0
    }
4503
0
    StringCat(out, " rest=");
4504
0
    span_add_visible(&out, s);
4505
0
  } else if (strcmp(argv[0], "headersplit") == 0) {
4506
0
    hts_header_split(s, &a, &b);
4507
0
    StringAddchar(out, '[');
4508
0
    span_add_visible(&out, a);
4509
0
    StringAddchar(out, '|');
4510
0
    span_add_visible(&out, b);
4511
0
    StringAddchar(out, ']');
4512
0
  } else if (strcmp(argv[0], "trim") == 0) {
4513
0
    a = hts_span_trim(s, argv[1], argv[2]);
4514
0
    StringAddchar(out, '[');
4515
0
    StringCatSpan(&out, a);
4516
0
    StringAddchar(out, ']');
4517
0
  } else if (strcmp(argv[0], "copy") == 0) {
4518
0
    LLint size;
4519
0
    char dst[64];
4520
0
    hts_boolean fit;
4521
4522
0
    if (!hts_parse_llint(argv[1], NULL, 0, (LLint) sizeof(dst) - 1, &size)) {
4523
0
      fprintf(stderr, "span: size must be below %d\n", (int) sizeof(dst));
4524
0
      StringFree(out);
4525
0
      return 1;
4526
0
    }
4527
0
    memset(dst, '#', sizeof(dst));
4528
0
    dst[sizeof(dst) - 1] = '\0';
4529
0
    fit = hts_span_copy(s, dst, (size_t) size);
4530
0
    StringCat(out, fit ? "fit [" : "clipped [");
4531
    /* the '#' past the terminator shows nothing more was written */
4532
0
    StringMemcat(out, dst,
4533
0
                 (size_t) size < sizeof(dst) - 1 ? (size_t) size + 1
4534
0
                                                 : sizeof(dst) - 1);
4535
0
    StringAddchar(out, ']');
4536
0
  } else {
4537
0
    fprintf(stderr, "span: unknown mode %s\n", argv[0]);
4538
0
    ret = 1;
4539
0
  }
4540
0
  if (ret == 0) {
4541
0
    const char *p;
4542
4543
    /* a NUL from copy shows as '0' */
4544
0
    for (p = StringBuff(out);
4545
0
         StringLength(out) != 0 && p < StringBuff(out) + StringLength(out); p++)
4546
0
      putchar(*p != '\0' ? *p : '0');
4547
0
    putchar('\n');
4548
0
  }
4549
0
  StringFree(out);
4550
0
  return ret;
4551
0
}
4552
4553
/* Check the span comparisons and skip on spans that hold NULs. */
4554
0
static int st_spancmp(httrackp *opt, int argc, char **argv) {
4555
0
  enum { EQ, EQ_CI, STARTS, STARTS_CI, ENDS, ENDS_CI };
4556
4557
0
  static const char *const names[] = {"eq",          "eq_ci",
4558
0
                                      "starts_with", "starts_with_ci",
4559
0
                                      "ends_with",   "ends_with_ci"};
4560
4561
  /* &"abc"[1] catches an ends_with() that reads before S */
4562
0
  static const struct {
4563
0
    int fn;
4564
0
    const char *a;
4565
0
    size_t alen;
4566
0
    const char *b;
4567
0
    size_t blen;
4568
0
    hts_boolean want;
4569
0
  } cases[] = {
4570
0
      {EQ, "", 0, "", 0, HTS_TRUE},
4571
0
      {EQ, NULL, 0, "", 0, HTS_TRUE},
4572
0
      {EQ, "", 0, "a", 1, HTS_FALSE},
4573
0
      {EQ, "a", 1, "", 0, HTS_FALSE},
4574
0
      {EQ, "*", 1, "*", 1, HTS_TRUE},
4575
0
      {EQ, "**", 1, "*", 1, HTS_TRUE},
4576
0
      {EQ, "**", 2, "*", 1, HTS_FALSE},
4577
0
      {EQ, "a\0b", 3, "a", 1, HTS_FALSE},
4578
0
      {EQ, "a\0b", 3, "a\0b", 3, HTS_TRUE},
4579
0
      {EQ, "a\0b", 3, "a\0c", 3, HTS_FALSE},
4580
0
      {EQ, "ab", 1, "ab", 2, HTS_FALSE},
4581
0
      {EQ, "ab", 2, "abc", 2, HTS_TRUE},
4582
0
      {EQ, "ab", 2, "aB", 2, HTS_FALSE},
4583
0
      {EQ_CI, "", 0, "", 0, HTS_TRUE},
4584
0
      {EQ_CI, "aBc", 3, "AbC", 3, HTS_TRUE},
4585
0
      {EQ_CI, "aBc", 2, "AbC", 3, HTS_FALSE},
4586
0
      {EQ_CI, "aBc", 3, "AbC", 2, HTS_FALSE},
4587
0
      {EQ_CI, "a\0b", 3, "a", 1, HTS_FALSE},
4588
0
      {EQ_CI, "a\0b", 3, "A\0B", 3, HTS_TRUE},
4589
0
      {EQ_CI, "a\0b", 3, "a\0c", 3, HTS_FALSE},
4590
0
      {EQ_CI, "[", 1, "{", 1, HTS_FALSE},
4591
0
      {EQ_CI, "@", 1, "`", 1, HTS_FALSE},
4592
0
      {EQ_CI, "\xc9", 1, "\xe9", 1, HTS_FALSE},
4593
0
      {EQ_CI, "\xe9", 1, "\xe9", 1, HTS_TRUE},
4594
0
      {STARTS, "", 0, "", 0, HTS_TRUE},
4595
0
      {STARTS, NULL, 0, "", 0, HTS_TRUE},
4596
0
      {STARTS, "", 0, "a", 1, HTS_FALSE},
4597
0
      {STARTS, "abc", 3, "ab", 2, HTS_TRUE},
4598
0
      {STARTS, "ab", 2, "", 0, HTS_TRUE},
4599
0
      {STARTS, "abc", 1, "ab", 2, HTS_FALSE},
4600
0
      {STARTS, "ab", 2, "ab", 2, HTS_TRUE},
4601
0
      {STARTS, "a\0b", 3, "a", 1, HTS_TRUE},
4602
0
      {STARTS, "a\0b", 3, "a\0", 2, HTS_TRUE},
4603
0
      {STARTS, "a\0b", 3, "a\0c", 3, HTS_FALSE},
4604
0
      {STARTS, "\0ab", 3, "ab", 2, HTS_FALSE},
4605
0
      {STARTS, "Abc", 3, "ab", 2, HTS_FALSE},
4606
0
      {STARTS_CI, "ABc", 3, "ab", 2, HTS_TRUE},
4607
0
      {STARTS_CI, "AB", 1, "ab", 2, HTS_FALSE},
4608
0
      {STARTS_CI, "\0ab", 3, "ab", 2, HTS_FALSE},
4609
0
      {STARTS_CI, "a\0B", 3, "a\0b", 3, HTS_TRUE},
4610
0
      {STARTS_CI, "a\0b", 3, "a\0c", 3, HTS_FALSE},
4611
0
      {STARTS_CI, "ab", 2, "", 0, HTS_TRUE},
4612
0
      {STARTS_CI, "[x", 2, "{", 1, HTS_FALSE},
4613
0
      {STARTS_CI, "\xc9x", 2, "\xe9", 1, HTS_FALSE},
4614
0
      {ENDS, "", 0, "", 0, HTS_TRUE},
4615
0
      {ENDS, NULL, 0, "", 0, HTS_TRUE},
4616
0
      {ENDS, "a", 1, "ab", 2, HTS_FALSE},
4617
0
      {ENDS, &"abc"[1], 2, "abc", 3, HTS_FALSE},
4618
0
      {ENDS, "abc", 3, "bc", 2, HTS_TRUE},
4619
0
      {ENDS, "ab", 2, "", 0, HTS_TRUE},
4620
0
      {ENDS, "abc", 2, "bc", 2, HTS_FALSE},
4621
0
      {ENDS, "abc", 2, "ab", 2, HTS_TRUE},
4622
0
      {ENDS, "b\0a", 3, "a", 1, HTS_TRUE},
4623
0
      {ENDS, "b\0a", 3, "\0a", 2, HTS_TRUE},
4624
0
      {ENDS, "ab\0", 3, "b", 1, HTS_FALSE},
4625
0
      {ENDS, "line\r", 5, "\r", 1, HTS_TRUE},
4626
0
      {ENDS, "abC", 3, "bc", 2, HTS_FALSE},
4627
0
      {ENDS_CI, "aBC", 3, "bc", 2, HTS_TRUE},
4628
0
      {ENDS_CI, "aBc", 3, "AbC", 3, HTS_TRUE},
4629
0
      {ENDS_CI, "aBC", 2, "bc", 2, HTS_FALSE},
4630
0
      {ENDS_CI, &"ABC"[1], 2, "abc", 3, HTS_FALSE},
4631
0
      {ENDS_CI, "ab\0", 3, "b", 1, HTS_FALSE},
4632
0
      {ENDS_CI, "a\0b", 3, "a\0c", 3, HTS_FALSE},
4633
0
      {ENDS_CI, "ab", 2, "", 0, HTS_TRUE},
4634
0
      {ENDS_CI, "x[", 2, "{", 1, HTS_FALSE},
4635
0
      {ENDS_CI, "x\xc9", 2, "\xe9", 1, HTS_FALSE},
4636
0
      {ENDS_CI, "c", 1, "bc", 2, HTS_FALSE},
4637
0
  };
4638
4639
  /* {offset into "ab\0cd", length, skip, offset and length left} */
4640
0
  static const size_t skips[][5] = {
4641
0
      {0, 5, 0, 0, 5}, {0, 5, 2, 2, 3}, {0, 5, 3, 3, 2}, {0, 5, 5, 5, 0},
4642
0
      {0, 5, 6, 5, 0}, {1, 2, 9, 3, 0}, {0, 0, 1, 0, 0}};
4643
0
  static const char skipped[] = "ab\0cd";
4644
0
  size_t i, failures = 0, spans_checked = 0;
4645
4646
0
  (void) opt;
4647
0
  (void) argc;
4648
0
  (void) argv;
4649
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
4650
0
    const hts_span a = hts_span_at(cases[i].a, cases[i].alen);
4651
0
    const hts_span b = hts_span_at(cases[i].b, cases[i].blen);
4652
0
    hts_boolean got;
4653
4654
0
    switch (cases[i].fn) {
4655
0
    case EQ:
4656
0
      got = hts_span_eq(a, b);
4657
0
      break;
4658
0
    case EQ_CI:
4659
0
      got = hts_span_eq_ci(a, b);
4660
0
      break;
4661
0
    case STARTS:
4662
0
      got = hts_span_starts_with(a, b);
4663
0
      break;
4664
0
    case STARTS_CI:
4665
0
      got = hts_span_starts_with_ci(a, b);
4666
0
      break;
4667
0
    case ENDS:
4668
0
      got = hts_span_ends_with(a, b);
4669
0
      break;
4670
0
    default:
4671
0
      got = hts_span_ends_with_ci(a, b);
4672
0
      break;
4673
0
    }
4674
0
    if (got != cases[i].want) {
4675
0
      printf("spancmp: case %d: %s gave %d\n", (int) i, names[cases[i].fn],
4676
0
             (int) got);
4677
0
      failures++;
4678
0
    }
4679
0
  }
4680
0
  for (i = 0; i < sizeof(skips) / sizeof(skips[0]); i++) {
4681
0
    const hts_span s = hts_span_skip(
4682
0
        hts_span_at(skipped + skips[i][0], skips[i][1]), skips[i][2]);
4683
4684
0
    if (s.p != skipped + skips[i][3] || s.len != skips[i][4]) {
4685
0
      printf("spancmp: skip %d gave %d+%d\n", (int) i, (int) (s.p - skipped),
4686
0
             (int) s.len);
4687
0
      failures++;
4688
0
    }
4689
0
  }
4690
0
  {
4691
0
    static const char one[] = "x";
4692
0
    const hts_span spans[] = {hts_span_at(NULL, 0), hts_span_at(one, 0),
4693
0
                              hts_span_at(one, 1), hts_span_of(NULL)};
4694
0
    const hts_boolean empty[] = {HTS_TRUE, HTS_TRUE, HTS_FALSE, HTS_TRUE};
4695
0
    const hts_boolean present[] = {HTS_FALSE, HTS_TRUE, HTS_TRUE, HTS_TRUE};
4696
4697
0
    for (i = 0; i < sizeof(spans) / sizeof(spans[0]); i++, spans_checked++) {
4698
0
      if (hts_span_empty(spans[i]) != empty[i] ||
4699
0
          hts_span_present(spans[i]) != present[i]) {
4700
0
        printf("spancmp: span %d gave empty %d present %d\n", (int) i,
4701
0
               (int) hts_span_empty(spans[i]),
4702
0
               (int) hts_span_present(spans[i]));
4703
0
        failures++;
4704
0
      }
4705
0
    }
4706
0
  }
4707
0
  printf("spancmp: %d cases, %d failures\n",
4708
0
         (int) (sizeof(cases) / sizeof(cases[0]) +
4709
0
                sizeof(skips) / sizeof(skips[0]) + spans_checked),
4710
0
         (int) failures);
4711
0
  if (failures == 0)
4712
0
    printf("spancmp: OK\n");
4713
0
  return failures != 0;
4714
0
}
4715
4716
/* Check hts_span_index: the first match wins, and _ci folds only A-Z. */
4717
0
static int st_spanindex(httrackp *opt, int argc, char **argv) {
4718
0
  static const char *const words[] = {"ab", "Ab", "", "abc", NULL};
4719
0
  static const char *const high[] = {"{", "\xe9", NULL};
4720
0
  static const char *const none[] = {NULL};
4721
4722
0
  static const struct {
4723
0
    const char *const *words;
4724
0
    const char *s;
4725
0
    size_t len;
4726
0
    hts_boolean ci;
4727
0
    int want;
4728
0
  } cases[] = {
4729
0
      {words, "ab", 2, HTS_FALSE, 0},   {words, "Ab", 2, HTS_FALSE, 1},
4730
0
      {words, "AB", 2, HTS_FALSE, -1},  {words, "AB", 2, HTS_TRUE, 0},
4731
0
      {words, NULL, 0, HTS_FALSE, 2},   {words, "x", 0, HTS_TRUE, 2},
4732
0
      {words, "a", 1, HTS_TRUE, -1},    {words, "abcd", 4, HTS_FALSE, -1},
4733
0
      {words, "abcd", 3, HTS_FALSE, 3}, {words, "ab\0", 3, HTS_FALSE, -1},
4734
0
      {words, "ABC", 3, HTS_TRUE, 3},   {high, "[", 1, HTS_TRUE, -1},
4735
0
      {high, "\xc9", 1, HTS_TRUE, -1},  {high, "\xe9", 1, HTS_TRUE, 1},
4736
0
      {none, "", 0, HTS_FALSE, -1},     {none, "a", 1, HTS_TRUE, -1},
4737
0
  };
4738
4739
0
  size_t i, failures = 0;
4740
4741
0
  (void) opt;
4742
0
  (void) argc;
4743
0
  (void) argv;
4744
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
4745
0
    const hts_span s = hts_span_at(cases[i].s, cases[i].len);
4746
0
    const int got = cases[i].ci ? hts_span_index_ci(s, cases[i].words)
4747
0
                                : hts_span_index(s, cases[i].words);
4748
4749
0
    if (got != cases[i].want) {
4750
0
      printf("spanindex: case %d gave %d\n", (int) i, got);
4751
0
      failures++;
4752
0
    }
4753
0
  }
4754
0
  {
4755
0
    unsigned int map[256];
4756
4757
0
    map_characters(hts_span_at("\0\xff\xff", 3), map);
4758
0
    assertf(map[0] == 1 && map[255] == 2);
4759
0
  }
4760
0
  printf("spanindex: %d cases, %d failures\n",
4761
0
         (int) (sizeof(cases) / sizeof(cases[0])), (int) failures);
4762
0
  if (failures == 0)
4763
0
    printf("spanindex: OK\n");
4764
0
  return failures != 0;
4765
0
}
4766
4767
/* Check hts_span_list_has on comma lists. */
4768
0
static int st_spanlist(httrackp *opt, int argc, char **argv) {
4769
0
  static const struct {
4770
0
    const char *list;
4771
0
    hts_boolean has; // does the list hold "chunked"?
4772
0
  } cases[] = {
4773
0
      {"chunked", HTS_TRUE},
4774
0
      {"gzip, chunked", HTS_TRUE},
4775
0
      {"  Chunked\t", HTS_TRUE},
4776
0
      {"chunked, gzip", HTS_TRUE},
4777
0
      {"gzip,chunked,", HTS_TRUE},
4778
0
      {"gzip ,  ,", HTS_FALSE},
4779
0
      {"xchunked, chunkedx", HTS_FALSE},
4780
0
      {"chunk ed", HTS_FALSE},
4781
0
      {"\"chunked\"", HTS_FALSE},
4782
0
      {"", HTS_FALSE},
4783
0
      {" , \t,", HTS_FALSE},
4784
0
  };
4785
4786
0
  size_t i, failures = 0;
4787
4788
0
  (void) opt;
4789
0
  (void) argc;
4790
0
  (void) argv;
4791
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
4792
0
    if (hts_span_list_has(hts_span_of(cases[i].list), ',',
4793
0
                          hts_span_of("chunked")) != cases[i].has) {
4794
0
      printf("spanlist: case %d failed\n", (int) i);
4795
0
      failures++;
4796
0
    }
4797
0
  }
4798
  // An empty token matches no item, even an empty one.
4799
0
  if (hts_span_list_has(hts_span_of("a,,b"), ',', hts_span_of(""))) {
4800
0
    printf("spanlist: an empty item matched\n");
4801
0
    failures++;
4802
0
  }
4803
0
  printf("spanlist: %d cases, %d failures\n",
4804
0
         (int) (sizeof(cases) / sizeof(cases[0])), (int) failures);
4805
0
  if (failures == 0)
4806
0
    printf("spanlist: OK\n");
4807
0
  return failures != 0;
4808
0
}
4809
4810
/* Check the C-string case-insensitive names, empty strings included. */
4811
0
static int st_cinames(httrackp *opt, int argc, char **argv) {
4812
0
  static const struct {
4813
0
    const char *a, *b;
4814
0
    hts_boolean eq, starts; /* hts_streq_ci(a, b), hts_starts_with_ci(a, b) */
4815
0
  } cases[] = {
4816
0
      {"", "", HTS_TRUE, HTS_TRUE},
4817
0
      {"a", "", HTS_FALSE, HTS_TRUE},
4818
0
      {"", "a", HTS_FALSE, HTS_FALSE},
4819
0
      {"get /", "GET ", HTS_FALSE, HTS_TRUE},
4820
0
      {"ge", "get ", HTS_FALSE, HTS_FALSE},
4821
0
      {"Host:", "host:", HTS_TRUE, HTS_TRUE},
4822
0
      {"ab", "abc", HTS_FALSE, HTS_FALSE},
4823
0
      {"abc", "abd", HTS_FALSE, HTS_FALSE},
4824
0
      {"[", "{", HTS_FALSE, HTS_FALSE},
4825
0
      {"@x", "`", HTS_FALSE, HTS_FALSE},
4826
0
      {"\xc9", "\xe9", HTS_FALSE, HTS_FALSE},
4827
0
      {"x\xe9y", "X\xe9", HTS_FALSE, HTS_TRUE},
4828
0
      {"\xe9", "\xe9", HTS_TRUE, HTS_TRUE},
4829
0
  };
4830
4831
0
  size_t i, failures = 0;
4832
4833
0
  (void) opt;
4834
0
  (void) argc;
4835
0
  (void) argv;
4836
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
4837
0
    const size_t alen = strlen(cases[i].a);
4838
    /* an exact-size copy, so ASan sees a read past the subject */
4839
0
    char *a = malloct(alen + 1);
4840
0
    const char *rest;
4841
0
    hts_boolean skipped;
4842
0
    int bad;
4843
4844
0
    assertf(a != NULL);
4845
0
    memcpy(a, cases[i].a, alen + 1);
4846
0
    rest = a;
4847
0
    skipped = hts_skip_prefix_ci(&rest, cases[i].b);
4848
0
    bad = hts_streq_ci(a, cases[i].b) != cases[i].eq ||
4849
0
          hts_starts_with_ci(a, cases[i].b) != cases[i].starts ||
4850
0
          skipped != cases[i].starts ||
4851
0
          rest != (skipped ? a + strlen(cases[i].b) : a);
4852
0
    if (bad) {
4853
0
      printf("cinames: FAIL case %u (\"%s\", \"%s\")\n", (unsigned) i,
4854
0
             cases[i].a, cases[i].b);
4855
0
      failures++;
4856
0
    }
4857
0
    freet(a);
4858
0
  }
4859
0
  printf("cinames: %u cases, %u failures\n",
4860
0
         (unsigned) (sizeof(cases) / sizeof(cases[0])), (unsigned) failures);
4861
0
  if (failures == 0)
4862
0
    printf("cinames: OK\n");
4863
0
  return failures != 0;
4864
0
}
4865
4866
/* Check that hts_path_join() puts one '/' between two parts and refuses,
4867
   leaving an empty string, any path that does not fit. */
4868
0
static int st_pathjoin(httrackp *opt, int argc, char **argv) {
4869
0
  static const struct {
4870
0
    const char *dir, *name;
4871
0
    size_t size;
4872
0
    const char *want; /* NULL: does not fit */
4873
0
  } cases[] = {
4874
0
      {"a/", "b", 8, "a/b"},
4875
0
      {"a", "b", 8, "a/b"},
4876
0
      {"a", "/b", 8, "a/b"},
4877
0
      {"a/", "/b", 8, "a//b"},
4878
0
      {"", "b", 8, "b"},
4879
0
      {"a", "", 8, "a"},
4880
0
      {"a/", "", 8, "a/"},
4881
0
      {"", "", 1, ""},
4882
0
      {"ab", "cd", 6, "ab/cd"},
4883
0
      {"ab", "cd", 5, NULL},
4884
0
      {"ab/", "cd", 6, "ab/cd"},
4885
0
      {"ab/", "cd", 5, NULL},
4886
0
      {"abcd", "", 5, "abcd"},
4887
0
      {"abcd", "e", 5, NULL},
4888
0
      {"abcde", "", 5, NULL},
4889
0
      {"abcdef", "x", 4, NULL},
4890
0
      {"a", "bcdefg", 4, NULL},
4891
0
      {"a", "b", 0, NULL},
4892
0
      {NULL, "b", 8, "b"},
4893
0
      {"a", NULL, 8, "a"},
4894
0
      {NULL, NULL, 1, ""},
4895
0
      {"", "/b", 8, "/b"},
4896
      /* '\\' separates only on DOS-style platforms */
4897
0
      {"a\\", "b", 8, HTS_DOSNAME ? "a\\b" : "a\\/b"},
4898
0
      {"a", "\\b", 8, HTS_DOSNAME ? "a\\b" : "a/\\b"},
4899
0
  };
4900
4901
0
  static const struct {
4902
0
    const char *dir, *name;
4903
0
    const char *want, *dos; /* want NULL: does not fit in 16 bytes */
4904
0
  } native[] = {
4905
0
      {"a/b", "c", "a/b/c", "a\\b\\c"},
4906
0
      {"a/", "/c", "a//c", "a\\\\c"},
4907
0
      {"", "a/b", "a/b", "a\\b"},
4908
0
      {"abcdefgh", "ijklmnop", NULL, NULL},
4909
0
  };
4910
4911
0
  size_t i, failures = 0;
4912
4913
0
  (void) opt;
4914
0
  (void) argc;
4915
0
  (void) argv;
4916
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
4917
    /* poisoned, with a canary just past the size the join is given */
4918
0
    char buf[16];
4919
0
    const size_t size = cases[i].size;
4920
0
    hts_boolean fit;
4921
4922
0
    memset(buf, 'Q', sizeof(buf));
4923
0
    fit = hts_path_join(hts_buf_at(buf, size), cases[i].dir, cases[i].name);
4924
0
    if (fit != (cases[i].want != NULL) || buf[size] != 'Q' ||
4925
0
        (size != 0 && strcmp(buf, fit ? cases[i].want : "") != 0)) {
4926
0
      printf("pathjoin: FAIL case %u (\"%s\", \"%s\", %u)\n", (unsigned) i,
4927
0
             cases[i].dir != NULL ? cases[i].dir : "(null)",
4928
0
             cases[i].name != NULL ? cases[i].name : "(null)", (unsigned) size);
4929
0
      failures++;
4930
0
    }
4931
0
  }
4932
  /* the native form converts every '/', the inserted one included */
4933
0
  for (i = 0; i < sizeof(native) / sizeof(native[0]); i++) {
4934
0
    char buf[16];
4935
0
    const hts_boolean fit =
4936
0
        hts_fpath_join(HTS_BUF(buf), native[i].dir, native[i].name);
4937
0
    const char *const want = native[i].want == NULL ? ""
4938
0
                             : HTS_DOSNAME          ? native[i].dos
4939
0
                                                    : native[i].want;
4940
4941
0
    if (fit != (native[i].want != NULL) || strcmp(buf, want) != 0) {
4942
0
      printf("pathjoin: FAIL native case %u (\"%s\", \"%s\")\n", (unsigned) i,
4943
0
             native[i].dir, native[i].name);
4944
0
      failures++;
4945
0
    }
4946
0
  }
4947
0
  printf("pathjoin: %u cases, %u failures\n",
4948
0
         (unsigned) (sizeof(cases) / sizeof(cases[0]) +
4949
0
                     sizeof(native) / sizeof(native[0])),
4950
0
         (unsigned) failures);
4951
0
  if (failures == 0)
4952
0
    printf("pathjoin: OK\n");
4953
0
  return failures != 0;
4954
0
}
4955
4956
/* Check the span finders on an empty span, a match at either end and none. */
4957
0
static int st_spanfind(httrackp *opt, int argc, char **argv) {
4958
0
  static const struct {
4959
0
    char fn; /* f find, a find_any, t take_until, < first, > last */
4960
0
    const char *s;
4961
0
    size_t len;
4962
0
    const char *arg; /* the byte to find is arg[0] */
4963
0
    long want;       /* an index, a byte, or -1 */
4964
0
  } cases[] = {
4965
0
      {'f', NULL, 0, "a", 0},       {'f', "abc", 3, "a", 0},
4966
0
      {'f', "abc", 3, "c", 2},      {'f', "abc", 3, "x", 3},
4967
0
      {'f', "abc", 2, "c", 2},      {'f', "a\0b", 3, "", 1},
4968
0
      {'f', "aba", 3, "a", 0},      {'a', NULL, 0, "a", 0},
4969
0
      {'a', "abc", 3, "xa", 0},     {'a', "abc", 3, "c", 2},
4970
0
      {'a', "abc", 3, "xy", 3},     {'a', "a\0b", 3, "b", 2},
4971
0
      {'a', "a\0b", 3, "", 3},      {'a', "abc", 2, "c", 2},
4972
0
      {'t', NULL, 0, ";", 0},       {'t', "ab;c", 4, ";", 2},
4973
0
      {'t', ";a", 2, ";", 0},       {'t', "ab", 2, ";", 2},
4974
0
      {'<', NULL, 0, "", -1},       {'<', "ab", 2, "", 'a'},
4975
0
      {'<', "\xff", 1, "", 0xff},   {'<', "\0", 1, "", 0},
4976
0
      {'>', NULL, 0, "", -1},       {'>', "ab", 2, "", 'b'},
4977
0
      {'>', "ab\xe9", 3, "", 0xe9}, {'>', "ab", 1, "", 'a'},
4978
0
  };
4979
4980
0
  size_t i, failures = 0;
4981
4982
0
  (void) opt;
4983
0
  (void) argc;
4984
0
  (void) argv;
4985
0
  for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
4986
    /* an exact-size copy, so ASan sees a read past the span */
4987
0
    char *copy = cases[i].s != NULL ? malloct(cases[i].len) : NULL;
4988
0
    hts_span s, rest;
4989
0
    long got;
4990
4991
0
    assertf(cases[i].s == NULL || copy != NULL);
4992
0
    if (copy != NULL)
4993
0
      memcpy(copy, cases[i].s, cases[i].len);
4994
0
    s = rest = hts_span_at(copy, cases[i].len);
4995
4996
0
    switch (cases[i].fn) {
4997
0
    case 'f':
4998
0
      got = (long) hts_span_find(s, cases[i].arg[0]);
4999
0
      break;
5000
0
    case 'a':
5001
0
      got = (long) hts_span_find_any(s, cases[i].arg);
5002
0
      break;
5003
0
    case 't':
5004
0
      got = (long) hts_span_take_until(&rest, cases[i].arg).len;
5005
      /* the rest starts at the byte that stopped the take */
5006
0
      if (rest.len != s.len - (size_t) got ||
5007
0
          (s.p != NULL ? rest.p != s.p + got : rest.p != NULL))
5008
0
        got = -2;
5009
0
      break;
5010
0
    case '<':
5011
0
      got = hts_span_first(s);
5012
0
      break;
5013
0
    default:
5014
0
      got = hts_span_last(s);
5015
0
      break;
5016
0
    }
5017
0
    if (got != cases[i].want) {
5018
0
      printf("spanfind: case %d gave %ld\n", (int) i, got);
5019
0
      failures++;
5020
0
    }
5021
0
    freet(copy);
5022
0
  }
5023
0
  printf("spanfind: %d cases, %d failures\n",
5024
0
         (int) (sizeof(cases) / sizeof(cases[0])), (int) failures);
5025
0
  if (failures == 0)
5026
0
    printf("spanfind: OK\n");
5027
0
  return failures != 0;
5028
0
}
5029
5030
/* Feed each line of a file to treathead_opt() the way the response loop does,
5031
   and print what it read. A "%%" line starts a new response. */
5032
0
static int st_headerparse(httrackp *opt, int argc, char **argv) {
5033
0
  static t_cookie jar;
5034
0
  char location[HTS_LOCATION_SIZE];
5035
0
  size_t len;
5036
0
  char *data;
5037
0
  const char *p, *end;
5038
0
  int record = 0;
5039
5040
0
  if (argc < 1 || (data = st_slurp(argv[0], &len)) == NULL) {
5041
0
    fprintf(stderr, "headerparse: cannot read the corpus\n");
5042
0
    return 1;
5043
0
  }
5044
0
  p = data;
5045
0
  end = data + len;
5046
0
  while (p < end) {
5047
0
    htsblk r;
5048
0
    char rcvd[2048];
5049
0
    int offset;
5050
5051
0
    memset(&r, 0, sizeof(r));
5052
0
    r.totalsize = -1;
5053
0
    r.retry_after = -1;
5054
0
    r.location = location;
5055
0
    location[0] = '\0';
5056
0
    jar.max_len = sizeof(jar.data);
5057
0
    jar.data[0] = '\0';
5058
0
    for (; p < end; p += offset) {
5059
0
      const hts_boolean cut = binput_line(p, end, HTS_BUF(rcvd), &offset);
5060
5061
0
      if (strcmp(rcvd, "%%") == 0) {
5062
0
        p += offset;
5063
0
        break;
5064
0
      }
5065
0
      if (!cut && strnotempty(rcvd))
5066
0
        treathead_opt(opt, &jar, "www.example.com", "/dir/page.html", &r, rcvd);
5067
0
    }
5068
0
    printf("#%d size=" LLintP " empty=%d chunk=%d keep=%d/%d/%d trailers=%d"
5069
0
           " compressed=%d te=%d range=" LLintP "-" LLintP "/" LLintP
5070
0
           " retry=%d\n",
5071
0
           record++, r.totalsize, r.empty, r.is_chunk, r.keep_alive,
5072
0
           r.keep_alive_max, r.keep_alive_t, r.keep_alive_trailers,
5073
0
           r.compressed, r.transfer_coding, r.crange_start, r.crange_end,
5074
0
           r.crange, r.retry_after);
5075
0
    printf(" type=[%s] charset=[%s] encoding=[%s] cdispo=[%s]\n", r.contenttype,
5076
0
           r.charset, r.contentencoding, r.cdispo);
5077
0
    printf(" lastmod=[%s] etag=[%s] location=[%s]\n", r.lastmodified, r.etag,
5078
0
           location);
5079
0
    printf(" jar=[%s]\n", jar.data);
5080
0
  }
5081
0
  freet(data);
5082
0
  return 0;
5083
0
}
5084
5085
/* ------------------------------------------------------------ */
5086
/* Registry: this module's tests, in the order -#test lists them. */
5087
/* ------------------------------------------------------------ */
5088
5089
0
static int st_pathcontained(httrackp *opt, int argc, char **argv) {
5090
  /* A ".." component escapes, but ".." inside a name does not. */
5091
0
  static const char *const escaping[] = {
5092
0
      "..",       "../x",      "a/../b", "a/..",    "/..", "..\\x",
5093
0
      "a\\..\\b", "x/../../y", "./../x", "a//../b", NULL};
5094
0
  static const char *const contained[] = {"a..b",  "..a",   "a..",    "...",
5095
0
                                          "a/b.c", "a/...", "a/b..c", ".",
5096
0
                                          "",      "a/./b", NULL};
5097
  /* hts_path_is_relative_contained() also refuses a name carrying its own
5098
     root, which url_savename() leans on to keep a hook inside the mirror. */
5099
0
  static const char *const rooted[] = {
5100
0
      "/x", "\\x", "\\\\srv\\share", "C:\\x", "c:rel", "z:/x", NULL};
5101
0
  static const char *const relative[] = {"x", "a/b", "a..b", "c_/x", "", NULL};
5102
0
  int failures = 0;
5103
0
  size_t i;
5104
5105
0
  for (i = 0; escaping[i] != NULL; i++) {
5106
0
    if (hts_path_is_contained(escaping[i])) {
5107
0
      printf("pathcontained: '%s' was accepted\n", escaping[i]);
5108
0
      failures++;
5109
0
    }
5110
0
  }
5111
0
  for (i = 0; contained[i] != NULL; i++) {
5112
0
    if (!hts_path_is_contained(contained[i])) {
5113
0
      printf("pathcontained: '%s' was refused\n", contained[i]);
5114
0
      failures++;
5115
0
    }
5116
0
  }
5117
0
  for (i = 0; escaping[i] != NULL; i++) {
5118
0
    if (hts_path_is_relative_contained(escaping[i])) {
5119
0
      printf("pathcontained: relative '%s' was accepted\n", escaping[i]);
5120
0
      failures++;
5121
0
    }
5122
0
  }
5123
0
  for (i = 0; rooted[i] != NULL; i++) {
5124
0
    if (hts_path_is_relative_contained(rooted[i])) {
5125
0
      printf("pathcontained: rooted '%s' was accepted\n", rooted[i]);
5126
0
      failures++;
5127
0
    }
5128
0
  }
5129
0
  for (i = 0; relative[i] != NULL; i++) {
5130
0
    if (!hts_path_is_relative_contained(relative[i])) {
5131
0
      printf("pathcontained: relative '%s' was refused\n", relative[i]);
5132
0
      failures++;
5133
0
    }
5134
0
  }
5135
0
  if (failures == 0)
5136
0
    printf("pathcontained: OK\n");
5137
0
  return failures != 0;
5138
0
}
5139
5140
/* Undo make_content_id()'s escaping; 0 on a byte it never emits. */
5141
0
static int cid_unescape(const char *cid, hts_buf dest) {
5142
0
  size_t j = 0;
5143
5144
0
  for (; *cid != '\0'; cid++) {
5145
0
    if (j + 1 >= dest.size)
5146
0
      return 0;
5147
0
    if (*cid == '-') {
5148
0
      const int c = hts_ehex(cid + 1);
5149
5150
0
      if (c < 0)
5151
0
        return 0;
5152
0
      dest.p[j++] = (char) c;
5153
0
      cid += 2;
5154
0
    } else if (hts_isalnum((unsigned char) *cid)) {
5155
0
      dest.p[j++] = *cid;
5156
0
    } else {
5157
0
      return 0;
5158
0
    }
5159
0
  }
5160
0
  dest.p[j] = '\0';
5161
0
  return 1;
5162
0
}
5163
5164
/* A plug-in hook that forwards to prev, which the defaults always fill. */
5165
static int chain_hits = 0;
5166
5167
0
static void chain_hit(void) { chain_hits++; }
5168
5169
#define CHAIN_PREV(CARG, NAME)                                                 \
5170
0
  (chain_hit(), assertf(CALLBACKARG_PREV_FUN(CARG, NAME) != NULL),             \
5171
0
   CALLBACKARG_PREV_FUN(CARG, NAME))
5172
0
#define CHAIN_PCARG CALLBACKARG_PREV_CARG(carg)
5173
5174
0
static void __cdecl cp_init(t_hts_callbackarg *carg) {
5175
0
  CHAIN_PREV(carg, init)(CHAIN_PCARG);
5176
0
}
5177
5178
0
static void __cdecl cp_uninit(t_hts_callbackarg *carg) {
5179
0
  CHAIN_PREV(carg, uninit)(CHAIN_PCARG);
5180
0
}
5181
5182
0
static int __cdecl cp_start(t_hts_callbackarg *carg, httrackp *opt) {
5183
0
  return CHAIN_PREV(carg, start)(CHAIN_PCARG, opt);
5184
0
}
5185
5186
0
static int __cdecl cp_end(t_hts_callbackarg *carg, httrackp *opt) {
5187
0
  return CHAIN_PREV(carg, end)(CHAIN_PCARG, opt);
5188
0
}
5189
5190
0
static int __cdecl cp_chopt(t_hts_callbackarg *carg, httrackp *opt) {
5191
0
  return CHAIN_PREV(carg, chopt)(CHAIN_PCARG, opt);
5192
0
}
5193
5194
static int __cdecl cp_preprocess(t_hts_callbackarg *carg, httrackp *opt,
5195
                                 char **html, int *len, const char *adr,
5196
0
                                 const char *fil) {
5197
0
  return CHAIN_PREV(carg, preprocess)(CHAIN_PCARG, opt, html, len, adr, fil);
5198
0
}
5199
5200
static int __cdecl cp_postprocess(t_hts_callbackarg *carg, httrackp *opt,
5201
                                  char **html, int *len, const char *adr,
5202
0
                                  const char *fil) {
5203
0
  return CHAIN_PREV(carg, postprocess)(CHAIN_PCARG, opt, html, len, adr, fil);
5204
0
}
5205
5206
static int __cdecl cp_check_html(t_hts_callbackarg *carg, httrackp *opt,
5207
                                 char *html, int len, const char *adr,
5208
0
                                 const char *fil) {
5209
0
  return CHAIN_PREV(carg, check_html)(CHAIN_PCARG, opt, html, len, adr, fil);
5210
0
}
5211
5212
static const char *__cdecl cp_query(t_hts_callbackarg *carg, httrackp *opt,
5213
0
                                    const char *question) {
5214
0
  return CHAIN_PREV(carg, query)(CHAIN_PCARG, opt, question);
5215
0
}
5216
5217
static const char *__cdecl cp_query2(t_hts_callbackarg *carg, httrackp *opt,
5218
0
                                     const char *question) {
5219
0
  return CHAIN_PREV(carg, query2)(CHAIN_PCARG, opt, question);
5220
0
}
5221
5222
static const char *__cdecl cp_query3(t_hts_callbackarg *carg, httrackp *opt,
5223
0
                                     const char *question) {
5224
0
  return CHAIN_PREV(carg, query3)(CHAIN_PCARG, opt, question);
5225
0
}
5226
5227
static int __cdecl cp_loop(t_hts_callbackarg *carg, httrackp *opt,
5228
                           lien_back *back, int back_max, int back_index,
5229
                           int lien_tot, int lien_ntot, int stat_time,
5230
0
                           hts_stat_struct *stats) {
5231
0
  return CHAIN_PREV(carg, loop)(CHAIN_PCARG, opt, back, back_max, back_index,
5232
0
                                lien_tot, lien_ntot, stat_time, stats);
5233
0
}
5234
5235
static void __cdecl cp_pause(t_hts_callbackarg *carg, httrackp *opt,
5236
0
                             const char *lockfile) {
5237
0
  CHAIN_PREV(carg, pause)(CHAIN_PCARG, opt, lockfile);
5238
0
}
5239
5240
static int __cdecl cp_check_link(t_hts_callbackarg *carg, httrackp *opt,
5241
0
                                 const char *adr, const char *fil, int status) {
5242
0
  return CHAIN_PREV(carg, check_link)(CHAIN_PCARG, opt, adr, fil, status);
5243
0
}
5244
5245
static int __cdecl cp_check_mime(t_hts_callbackarg *carg, httrackp *opt,
5246
                                 const char *adr, const char *fil,
5247
0
                                 const char *mime, int status) {
5248
0
  return CHAIN_PREV(carg, check_mime)(CHAIN_PCARG, opt, adr, fil, mime, status);
5249
0
}
5250
5251
static void __cdecl cp_filesave(t_hts_callbackarg *carg, httrackp *opt,
5252
0
                                const char *file) {
5253
0
  CHAIN_PREV(carg, filesave)(CHAIN_PCARG, opt, file);
5254
0
}
5255
5256
static void __cdecl cp_filesave2(t_hts_callbackarg *carg, httrackp *opt,
5257
                                 const char *adr, const char *fil,
5258
                                 const char *sav, int is_new, int is_modified,
5259
0
                                 int not_updated) {
5260
0
  CHAIN_PREV(carg, filesave2)(CHAIN_PCARG, opt, adr, fil, sav, is_new,
5261
0
                              is_modified, not_updated);
5262
0
}
5263
5264
static int __cdecl cp_linkdetected(t_hts_callbackarg *carg, httrackp *opt,
5265
0
                                   char *link) {
5266
0
  return CHAIN_PREV(carg, linkdetected)(CHAIN_PCARG, opt, link);
5267
0
}
5268
5269
static int __cdecl cp_linkdetected2(t_hts_callbackarg *carg, httrackp *opt,
5270
0
                                    char *link, const char *tag) {
5271
0
  return CHAIN_PREV(carg, linkdetected2)(CHAIN_PCARG, opt, link, tag);
5272
0
}
5273
5274
static int __cdecl cp_xfrstatus(t_hts_callbackarg *carg, httrackp *opt,
5275
0
                                lien_back *back) {
5276
0
  return CHAIN_PREV(carg, xfrstatus)(CHAIN_PCARG, opt, back);
5277
0
}
5278
5279
static int __cdecl cp_savename(t_hts_callbackarg *carg, httrackp *opt,
5280
                               const char *adr, const char *fil,
5281
                               const char *ref_adr, const char *ref_fil,
5282
0
                               char *save) {
5283
0
  return CHAIN_PREV(carg, savename)(CHAIN_PCARG, opt, adr, fil, ref_adr,
5284
0
                                    ref_fil, save);
5285
0
}
5286
5287
static int __cdecl cp_sendhead(t_hts_callbackarg *carg, httrackp *opt,
5288
                               char *buff, const char *adr, const char *fil,
5289
                               const char *ref_adr, const char *ref_fil,
5290
0
                               htsblk *outgoing) {
5291
0
  return CHAIN_PREV(carg, sendhead)(CHAIN_PCARG, opt, buff, adr, fil, ref_adr,
5292
0
                                    ref_fil, outgoing);
5293
0
}
5294
5295
static int __cdecl cp_receivehead(t_hts_callbackarg *carg, httrackp *opt,
5296
                                  char *buff, const char *adr, const char *fil,
5297
                                  const char *ref_adr, const char *ref_fil,
5298
0
                                  htsblk *incoming) {
5299
0
  return CHAIN_PREV(carg, receivehead)(CHAIN_PCARG, opt, buff, adr, fil,
5300
0
                                       ref_adr, ref_fil, incoming);
5301
0
}
5302
5303
/* A hook chained onto an unset slot gets the engine default as prev. */
5304
0
static int st_chainprev(httrackp *unused, int argc, char **argv) {
5305
0
  httrackp *const opt = hts_create_opt();
5306
0
  char html[] = "<html></html>", link[] = "x.html", save[] = "x.html";
5307
0
  char *page = html;
5308
0
  int len = (int) strlen(html);
5309
5310
  /* Each named slot gets the hook that is chained below onto its field. */
5311
0
  const struct {
5312
0
    const char *name;
5313
0
    uintptr_t fun;
5314
0
  } hooks[] = {{"init", (uintptr_t) cp_init},
5315
0
               {"free", (uintptr_t) cp_uninit},
5316
0
               {"start", (uintptr_t) cp_start},
5317
0
               {"end", (uintptr_t) cp_end},
5318
0
               {"change-options", (uintptr_t) cp_chopt},
5319
0
               {"preprocess-html", (uintptr_t) cp_preprocess},
5320
0
               {"postprocess-html", (uintptr_t) cp_postprocess},
5321
0
               {"check-html", (uintptr_t) cp_check_html},
5322
0
               {"query", (uintptr_t) cp_query},
5323
0
               {"query2", (uintptr_t) cp_query2},
5324
0
               {"query3", (uintptr_t) cp_query3},
5325
0
               {"loop", (uintptr_t) cp_loop},
5326
0
               {"check-link", (uintptr_t) cp_check_link},
5327
0
               {"check-mime", (uintptr_t) cp_check_mime},
5328
0
               {"pause", (uintptr_t) cp_pause},
5329
0
               {"save-file", (uintptr_t) cp_filesave},
5330
0
               {"save-file2", (uintptr_t) cp_filesave2},
5331
0
               {"link-detected", (uintptr_t) cp_linkdetected},
5332
0
               {"link-detected2", (uintptr_t) cp_linkdetected2},
5333
0
               {"transfer-status", (uintptr_t) cp_xfrstatus},
5334
0
               {"save-name", (uintptr_t) cp_savename},
5335
0
               {"send-header", (uintptr_t) cp_sendhead},
5336
0
               {"receive-header", (uintptr_t) cp_receivehead}};
5337
0
  size_t i;
5338
5339
0
  (void) unused;
5340
0
  (void) argc;
5341
0
  (void) argv;
5342
0
  assertf(opt != NULL);
5343
0
  assertf(!HAS_CALLBACK(opt, query2) && !HAS_CALLBACK(opt, query3));
5344
0
  for (i = 0; i < sizeof(hooks) / sizeof(hooks[0]); i++)
5345
0
    assertf(htswrap_read(opt, hooks[i].name) == 0);
5346
5347
0
  CHAIN_FUNCTION(opt, init, cp_init, NULL);
5348
0
  CHAIN_FUNCTION(opt, uninit, cp_uninit, NULL);
5349
0
  CHAIN_FUNCTION(opt, start, cp_start, NULL);
5350
0
  CHAIN_FUNCTION(opt, end, cp_end, NULL);
5351
0
  CHAIN_FUNCTION(opt, chopt, cp_chopt, NULL);
5352
0
  CHAIN_FUNCTION(opt, preprocess, cp_preprocess, NULL);
5353
0
  CHAIN_FUNCTION(opt, postprocess, cp_postprocess, NULL);
5354
0
  CHAIN_FUNCTION(opt, check_html, cp_check_html, NULL);
5355
0
  CHAIN_FUNCTION(opt, query, cp_query, NULL);
5356
0
  CHAIN_FUNCTION(opt, query2, cp_query2, NULL);
5357
0
  CHAIN_FUNCTION(opt, query3, cp_query3, NULL);
5358
0
  CHAIN_FUNCTION(opt, loop, cp_loop, NULL);
5359
0
  CHAIN_FUNCTION(opt, check_link, cp_check_link, NULL);
5360
0
  CHAIN_FUNCTION(opt, check_mime, cp_check_mime, NULL);
5361
0
  CHAIN_FUNCTION(opt, pause, cp_pause, NULL);
5362
0
  CHAIN_FUNCTION(opt, filesave, cp_filesave, NULL);
5363
0
  CHAIN_FUNCTION(opt, filesave2, cp_filesave2, NULL);
5364
0
  CHAIN_FUNCTION(opt, linkdetected, cp_linkdetected, NULL);
5365
0
  CHAIN_FUNCTION(opt, linkdetected2, cp_linkdetected2, NULL);
5366
0
  CHAIN_FUNCTION(opt, xfrstatus, cp_xfrstatus, NULL);
5367
0
  CHAIN_FUNCTION(opt, savename, cp_savename, NULL);
5368
0
  CHAIN_FUNCTION(opt, sendhead, cp_sendhead, NULL);
5369
0
  CHAIN_FUNCTION(opt, receivehead, cp_receivehead, NULL);
5370
0
  assertf(HAS_CALLBACK(opt, query2) && HAS_CALLBACK(opt, query3));
5371
0
  for (i = 0; i < sizeof(hooks) / sizeof(hooks[0]); i++)
5372
0
    assertf(htswrap_read(opt, hooks[i].name) == hooks[i].fun);
5373
  /* These slots have no string name. */
5374
0
  assertf(htswrap_add(opt, "detect", (void *) cp_check_link) != 0);
5375
0
  assertf(htswrap_add(opt, "parse", (void *) cp_check_link) != 0);
5376
0
  assertf(htswrap_add(opt, "extsavename", (void *) cp_check_link) != 0);
5377
5378
0
  RUN_CALLBACK_NOARG(opt, init);
5379
0
  assertf(RUN_CALLBACK0(opt, start) == 1);
5380
0
  assertf(RUN_CALLBACK0(opt, chopt) == 1);
5381
0
  assertf(RUN_CALLBACK4(opt, preprocess, &page, &len, "h", "/") == 1);
5382
0
  assertf(RUN_CALLBACK4(opt, postprocess, &page, &len, "h", "/") == 1);
5383
0
  assertf(page == html && len == (int) strlen(html));
5384
0
  assertf(RUN_CALLBACK4(opt, check_html, html, len, "h", "/") == 1);
5385
0
  assertf(strcmp(RUN_CALLBACK1(opt, query, "q"), "") == 0);
5386
0
  assertf(strcmp(RUN_CALLBACK1(opt, query2, "q"), "") == 0);
5387
0
  assertf(strcmp(RUN_CALLBACK1(opt, query3, "q"), "") == 0);
5388
0
  assertf(RUN_CALLBACK3(opt, check_link, "h", "/", 200) == -1);
5389
0
  assertf(RUN_CALLBACK4(opt, check_mime, "h", "/", "text/html", 200) == -1);
5390
0
  RUN_CALLBACK1(opt, filesave, "f");
5391
0
  RUN_CALLBACK6(opt, filesave2, "h", "/", "f", 1, 1, 0);
5392
0
  assertf(RUN_CALLBACK1(opt, linkdetected, link) == 1);
5393
0
  assertf(RUN_CALLBACK2(opt, linkdetected2, link, "<a") == 1);
5394
0
  assertf(RUN_CALLBACK1(opt, xfrstatus, NULL) == 1);
5395
0
  assertf(RUN_CALLBACK5(opt, savename, "h", "/", "r", "/", save) == 1);
5396
0
  assertf(RUN_CALLBACK6(opt, sendhead, link, "h", "/", "r", "/", NULL) == 1);
5397
0
  assertf(RUN_CALLBACK6(opt, receivehead, link, "h", "/", "r", "/", NULL) == 1);
5398
0
  assertf(RUN_CALLBACK0(opt, end) == 1);
5399
0
  RUN_CALLBACK_NOARG(opt, uninit);
5400
0
  assertf(chain_hits == 21);
5401
5402
  /* Unsetting a slot restores the default, so a new chain still has a prev. */
5403
0
  assertf(htswrap_add(opt, "check-link", NULL) == 0);
5404
0
  assertf(htswrap_read(opt, "check-link") == 0);
5405
0
  CHAIN_FUNCTION(opt, check_link, cp_check_link, NULL);
5406
0
  assertf(RUN_CALLBACK3(opt, check_link, "h", "/", 200) == -1);
5407
0
  assertf(chain_hits == 22);
5408
5409
0
  hts_free_opt(opt);
5410
0
  return st_verdict("chainprev", 0);
5411
0
}
5412
5413
/* Unescaping every id back to its own URL is what proves the map injective;
5414
   make_content_id() in htslib.c says why that matters. */
5415
0
static int st_contentid(httrackp *opt, int argc, char **argv) {
5416
  /* "/p.gif" escapes to "-2egif", and the other two names spell that escape
5417
     out, with the old marker and with the new one */
5418
0
  static const char *const fils[] = {"/p.gif", "/pX2egif", "/p-2egif", NULL};
5419
0
  char BIGSTK cid[HTS_URLMAXSIZE * 3];
5420
0
  char BIGSTK url[HTS_URLMAXSIZE * 3];
5421
0
  char BIGSTK back[HTS_URLMAXSIZE * 3];
5422
0
  char fil[8];
5423
0
  int failures = 0;
5424
0
  int i, c;
5425
5426
0
  for (i = 0; fils[i] != NULL; i++) {
5427
0
    make_content_id("www.example.com", fils[i], HTS_BUF(cid));
5428
0
    snprintf(url, sizeof(url), "www.example.com%s", fils[i]);
5429
0
    if (!cid_unescape(cid, HTS_BUF(back)) || strcmp(back, url) != 0) {
5430
0
      printf("contentid: '%s' -> '%s' -> '%s'\n", url, cid, back);
5431
0
      failures++;
5432
0
    }
5433
0
  }
5434
5435
  /* every byte a path can carry, so no unescaped character is missed */
5436
0
  for (c = 1; c <= 255; c++) {
5437
0
    snprintf(fil, sizeof(fil), "/a%cb", c);
5438
0
    snprintf(url, sizeof(url), "h%s", fil);
5439
0
    make_content_id("h", fil, HTS_BUF(cid));
5440
0
    if (!cid_unescape(cid, HTS_BUF(back)) || strcmp(back, url) != 0) {
5441
0
      printf("contentid: byte %d -> '%s' -> '%s'\n", c, cid, back);
5442
0
      failures++;
5443
0
    }
5444
0
  }
5445
5446
  /* a clip leaves room for the NUL */
5447
0
  {
5448
0
    char tiny[4];
5449
5450
0
    if (cid_unescape("abcd", HTS_BUF(tiny)) ||
5451
0
        !cid_unescape("abc", HTS_BUF(tiny)) || strcmp(tiny, "abc") != 0) {
5452
0
      printf("contentid: a 4-byte buffer took 4 bytes or refused 3\n");
5453
0
      failures++;
5454
0
    }
5455
0
  }
5456
0
  if (failures == 0)
5457
0
    printf("contentid: OK\n");
5458
0
  return failures != 0;
5459
0
}
5460
5461
/* No capacity up to the whole id may abort, sizeof(void *) included. */
5462
0
static int st_contentid_tail(httrackp *opt, int argc, char **argv) {
5463
0
  static const char host[] = "www.example.com";
5464
0
  static const char fil[] = "/abcdefghijklmnop";
5465
0
  char full[256];
5466
0
  char cid[256];
5467
0
  const size_t full_len = make_content_id(host, fil, HTS_BUF(full));
5468
0
  int failures = 0;
5469
0
  size_t size;
5470
5471
0
  for (size = 1; size <= full_len + 1; size++) {
5472
0
    size_t ret, len;
5473
5474
0
    if (size == sizeof(void *))
5475
0
      continue; /* a caller passing that is the mistake the check is for */
5476
0
    memset(cid, 'X', sizeof(cid));
5477
0
    ret = make_content_id(host, fil, hts_buf_at(cid, size));
5478
0
    len = strnlen(cid, size);
5479
0
    if (len == size || ret > size || cid[size] != 'X' ||
5480
0
        strncmp(cid, full, len) != 0) {
5481
0
      printf("contentid-tail: size %d -> %d '%.*s'\n", (int) size, (int) ret,
5482
0
             (int) len, cid);
5483
0
      failures++;
5484
0
    }
5485
0
  }
5486
0
  if (failures == 0)
5487
0
    printf("contentid-tail: OK\n");
5488
0
  return failures != 0;
5489
0
}
5490
5491
/* Print the host each login parser finds in a URL address. */
5492
0
static int st_userinfo(httrackp *opt, int argc, char **argv) {
5493
0
  int i;
5494
5495
0
  for (i = 0; i < argc; i++)
5496
0
    printf("host=%s end=%s login=%d\n", jump_identification_const(argv[i]),
5497
0
           login_end(argv[i]), link_has_authorization(argv[i]));
5498
0
  return 0;
5499
0
}
5500
5501
/* Check how hts_escape_typed_login() rewrites a typed URL. */
5502
0
static int st_typedlogin(httrackp *opt, int argc, char **argv) {
5503
0
  static const struct {
5504
0
    const char *url;
5505
0
    const char *want;
5506
0
  } rows[] = {
5507
0
      {"http://u:p?w@h/", "http://u:p%3Fw@h/"},
5508
0
      {"http://u:a?b#c\\d@h/", "http://u:a%3Fb%23c%5Cd@h/"},
5509
0
      {"http://u:4471?Wv3m@h/", "http://u:4471%3FWv3m@h/"},
5510
0
      {"http://u:?x@h/", "http://u:%3Fx@h/"},
5511
0
      {"http://admin:Zq9x@ss?Wv3m@h/x?y#z",
5512
0
       "http://admin:Zq9x@ss%3FWv3m@h/x?y#z"},
5513
0
      {"u:p?w@h:80/x?q", "u:p%3Fw@h:80/x?q"},
5514
0
      {"//u:p#w@h", "//u:p%23w@h"},
5515
0
      {"ftp://u:p?w@h", "ftp://u:p%3Fw@h"},
5516
0
      {"http://host:8099?e=a@b.com", "http://host:8099%3Fe=a@b.com"},
5517
0
      {"http://u:p%3Fw@h/", "http://u:p%3Fw@h/"},
5518
0
      {"http://u:p%3Fw@h/?a#b", "http://u:p%3Fw@h/?a#b"},
5519
0
      {"http://h/x?a@b#c", "http://h/x?a@b#c"},
5520
0
      {"http://h?a#b\\c", "http://h?a#b\\c"},
5521
0
      {"http://u:p@h/x?a@b", "http://u:p@h/x?a@b"},
5522
0
      {"http://u:p?w@[::1]:8080/x?y", "http://u:p%3Fw@[::1]:8080/x?y"},
5523
0
      {"http://[::1]:80/x?a@b", "http://[::1]:80/x?a@b"},
5524
0
  };
5525
5526
0
  char out[256];
5527
0
  size_t i;
5528
0
  int failures = 0;
5529
5530
0
  for (i = 0; i < sizeof(rows) / sizeof(rows[0]); i++) {
5531
0
    const hts_boolean ok = hts_escape_typed_login(rows[i].url, HTS_BUF(out));
5532
5533
0
    if (!ok || strcmp(out, rows[i].want) != 0) {
5534
0
      printf("FAIL %s: %s\n", rows[i].url, out);
5535
0
      failures++;
5536
0
    } else if (!hts_escape_typed_login(rows[i].want, HTS_BUF(out)) ||
5537
0
               strcmp(out, rows[i].want) != 0) {
5538
0
      printf("FAIL twice %s: %s\n", rows[i].want, out);
5539
0
      failures++;
5540
0
    }
5541
0
  }
5542
  // an escape that does not fit is dropped whole
5543
0
  if (hts_escape_typed_login("u:ab?@h", HTS_BUF_N(out, 6)) ||
5544
0
      strcmp(out, "u:ab") != 0) {
5545
0
    printf("FAIL short: %s\n", out);
5546
0
    failures++;
5547
0
  }
5548
0
  printf("typedlogin: %d failure(s)\n", failures);
5549
0
  return failures != 0;
5550
0
}
5551
5552
/* Append " NAME=text" for a present span to OUT, a NUL as "\0". */
5553
0
static void urlview_field(hts_buf out, const char *name, hts_span sp) {
5554
0
  size_t len = strlen(out.p);
5555
0
  size_t i;
5556
5557
0
  if (!hts_span_present(sp))
5558
0
    return;
5559
0
  snprintf(out.p + len, out.size - len, " %s=", name);
5560
0
  for (i = 0; i < sp.len; i++) {
5561
0
    len = strlen(out.p);
5562
0
    snprintf(out.p + len, out.size - len, sp.p[i] != '\0' ? "%c" : "\\0",
5563
0
             sp.p[i]);
5564
0
  }
5565
0
}
5566
5567
/* Describe *V as "ok=1 scheme=... host=...", leaving absent parts out. */
5568
static const char *urlview_describe(hts_buf out, hts_boolean ok,
5569
0
                                    const hts_url_view *v) {
5570
0
  snprintf(out.p, out.size, "ok=%d", ok ? 1 : 0);
5571
0
  urlview_field(out, "scheme", v->scheme);
5572
0
  urlview_field(out, "userinfo", v->userinfo);
5573
0
  urlview_field(out, "host", v->host);
5574
0
  urlview_field(out, "port", v->port);
5575
0
  urlview_field(out, "path", v->path);
5576
0
  urlview_field(out, "query", v->query);
5577
0
  urlview_field(out, "fragment", v->fragment);
5578
0
  return out.p;
5579
0
}
5580
5581
/* Does every span lie in [s, s + len), in order, the last one at the end, with
5582
   a non-empty path starting at a terminator? */
5583
0
static hts_boolean urlview_tiles(hts_span str, const hts_url_view *v) {
5584
0
  const hts_span *const parts[] = {&v->scheme,  &v->userinfo, &v->host,
5585
0
                                   &v->port,    &v->path,     &v->query,
5586
0
                                   &v->fragment};
5587
0
  const char *const end = str.p + str.len;
5588
0
  const char *at = str.p;
5589
0
  size_t i;
5590
5591
  /* memchr() over 4 bytes, because strchr() would match a NUL */
5592
0
  if (!hts_span_present(v->host) || !hts_span_present(v->path) ||
5593
0
      (!hts_span_empty(v->path) && memchr("/?#\\", v->path.p[0], 4) == NULL))
5594
0
    return HTS_FALSE;
5595
0
  for (i = 0; i < sizeof(parts) / sizeof(parts[0]); i++) {
5596
0
    const hts_span *const sp = parts[i];
5597
5598
0
    if (!hts_span_present(*sp))
5599
0
      continue;
5600
0
    if (sp->p < at || sp->len > (size_t) (end - sp->p))
5601
0
      return HTS_FALSE;
5602
0
    at = sp->p + sp->len;
5603
0
  }
5604
0
  return at == end ? HTS_TRUE : HTS_FALSE;
5605
0
}
5606
5607
/* -#test=urlview [url...]: print each URL's view, or check the table. */
5608
0
static int st_urlview(httrackp *opt, int argc, char **argv) {
5609
0
  static const struct {
5610
0
    const char *url;
5611
0
    const char *want;
5612
0
  } rows[] = {
5613
0
      {"http://u:p@h:8080/x?q#f",
5614
0
       "ok=1 scheme=http userinfo=u:p host=h port=8080 path=/x query=q "
5615
0
       "fragment=f"},
5616
      /* an '@' after the authority is not a login */
5617
0
      {"http://h1?u=a@h2/x", "ok=1 scheme=http host=h1 path= query=u=a@h2/x"},
5618
0
      {"http://h1#u=a@h2/x",
5619
0
       "ok=1 scheme=http host=h1 path= fragment=u=a@h2/x"},
5620
0
      {"http://h1\\u=a@h2/x", "ok=1 scheme=http host=h1 path=\\u=a@h2/x"},
5621
0
      {"http://h/p@q/x", "ok=1 scheme=http host=h path=/p@q/x"},
5622
0
      {"http://u@h/x?a@b",
5623
0
       "ok=1 scheme=http userinfo=u host=h path=/x query=a@b"},
5624
0
      {"http://h\\@evil/", "ok=1 scheme=http host=h path=\\@evil/"},
5625
      /* the browser rule: the last '@' of the authority ends the login */
5626
0
      {"http://u:p@q@h/", "ok=1 scheme=http userinfo=u:p@q host=h path=/"},
5627
0
      {"http://@h/", "ok=1 scheme=http userinfo= host=h path=/"},
5628
      /* '?' and '#' before any '/' */
5629
0
      {"http://h?a/b", "ok=1 scheme=http host=h path= query=a/b"},
5630
0
      {"http://h#a?b/c", "ok=1 scheme=http host=h path= fragment=a?b/c"},
5631
0
      {"http://h?#", "ok=1 scheme=http host=h path= query= fragment="},
5632
0
      {"http://h?", "ok=1 scheme=http host=h path= query="},
5633
      /* IPv6 literals, ports and zone ids */
5634
0
      {"http://[::1]:8080/x", "ok=1 scheme=http host=[::1] port=8080 path=/x"},
5635
0
      {"http://[::1]/", "ok=1 scheme=http host=[::1] path=/"},
5636
0
      {"http://[::1]:/", "ok=1 scheme=http host=[::1] port= path=/"},
5637
0
      {"http://[fe80::1%25eth0]:80/",
5638
0
       "ok=1 scheme=http host=[fe80::1%25eth0] port=80 path=/"},
5639
0
      {"http://u:p@[::1]:1/", "ok=1 scheme=http userinfo=u:p host=[::1] port=1 "
5640
0
                              "path=/"},
5641
0
      {"http://[::1/x", "ok=0 scheme=http host=[::1 path=/x"},
5642
0
      {"http://[::1]x:80/", "ok=0 scheme=http host=[::1]x:80 path=/"},
5643
      /* empty host */
5644
0
      {"http:///x", "ok=1 scheme=http host= path=/x"},
5645
0
      {"http://:80/", "ok=1 scheme=http host= port=80 path=/"},
5646
0
      {"file:///etc/x", "ok=1 scheme=file host= path=/etc/x"},
5647
0
      {"", "ok=1 host= path="},
5648
      /* scheme-less: an adr starts at its authority */
5649
0
      {"h:80/x", "ok=1 host=h port=80 path=/x"},
5650
0
      {"example.com", "ok=1 host=example.com path="},
5651
0
      {"localhost:8080", "ok=1 host=localhost port=8080 path="},
5652
0
      {"//u@h/x", "ok=1 userinfo=u host=h path=/x"},
5653
0
      {"u:p@h", "ok=1 userinfo=u:p host=h path="},
5654
      /* schemes */
5655
0
      {"HTTPS://U@H/", "ok=1 scheme=HTTPS userinfo=U host=H path=/"},
5656
0
      {"gopher://u@h/x", "ok=1 scheme=gopher userinfo=u host=h path=/x"},
5657
0
      {"connect:proxy:443", "ok=1 scheme=connect host=proxy port=443 path="},
5658
0
      {"http:h/x", "ok=1 scheme=http host=h path=/x"},
5659
0
      {"HTTP:h/x", "ok=1 scheme=HTTP host=h path=/x"},
5660
0
      {"File://u@h/x", "ok=1 scheme=File userinfo=u host=h path=/x"},
5661
0
      {"a+b://u@h/x", "ok=1 scheme=a+b userinfo=u host=h path=/x"},
5662
0
      {"a.b://h/", "ok=1 scheme=a.b host=h path=/"},
5663
0
      {"a-b://h/", "ok=1 scheme=a-b host=h path=/"},
5664
0
      {"1x://u@h/", "ok=1 host=1x port= path=//u@h/"},
5665
      /* ports */
5666
0
      {"http://h:65535/", "ok=1 scheme=http host=h port=65535 path=/"},
5667
0
      {"http://h:0/", "ok=1 scheme=http host=h port=0 path=/"},
5668
0
      {"http://h:/", "ok=1 scheme=http host=h port= path=/"},
5669
0
      {"http://h:65536/", "ok=0 scheme=http host=h port=65536 path=/"},
5670
0
      {"http://h:99999999999999999999/",
5671
0
       "ok=0 scheme=http host=h port=99999999999999999999 path=/"},
5672
0
      {"http://h:8a/", "ok=0 scheme=http host=h port=8a path=/"},
5673
0
      {"http://h:-1/", "ok=0 scheme=http host=h port=-1 path=/"},
5674
0
      {"http://h:1:2/", "ok=0 scheme=http host=h port=1:2 path=/"},
5675
0
  };
5676
5677
  /* A string with LEN bytes, which may hold a NUL. */
5678
0
  static const struct {
5679
0
    const char *s;
5680
0
    size_t len;
5681
0
    const char *want;
5682
0
  } bounded[] = {
5683
0
      {"http://h/xyz?q", 9, "ok=1 scheme=http host=h path=/"},
5684
0
      {"http:", 4, "ok=1 host=http path="},
5685
0
      {"http://h\0x@evil:80/p", 20,
5686
0
       "ok=1 scheme=http userinfo=h\\0x host=evil port=80 path=/p"},
5687
0
  };
5688
5689
0
  static const struct {
5690
0
    const char *s;
5691
0
    size_t len;
5692
0
  } tokens[] = {{"http:", 5}, {"http", 4}, {"gopher:", 7}, {"//", 2},
5693
0
                {"/", 1},     {"u", 1},    {":", 1},       {"@", 1},
5694
0
                {"?", 1},     {"#", 1},    {"\\", 1},      {"[", 1},
5695
0
                {"]", 1},     {"80", 2},   {"h", 1},       {"\0", 1}};
5696
5697
0
  const size_t ntok = sizeof(tokens) / sizeof(tokens[0]);
5698
0
  char out[512];
5699
0
  hts_url_view v;
5700
0
  size_t i, j, k;
5701
0
  int failures = 0;
5702
5703
0
  (void) opt;
5704
0
  if (argc > 0) {
5705
0
    int a;
5706
5707
0
    for (a = 0; a < argc; a++) {
5708
0
      const hts_boolean ok = hts_url_view_parse(hts_span_of(argv[a]), &v);
5709
5710
0
      printf("%s\n", urlview_describe(HTS_BUF(out), ok, &v));
5711
0
    }
5712
0
    return 0;
5713
0
  }
5714
0
  for (i = 0; i < sizeof(rows) / sizeof(rows[0]); i++) {
5715
0
    const hts_boolean ok = hts_url_view_parse(hts_span_of(rows[i].url), &v);
5716
5717
0
    urlview_describe(HTS_BUF(out), ok, &v);
5718
0
    if (strcmp(out, rows[i].want) != 0) {
5719
0
      printf("FAIL %s: %s\n", rows[i].url, out);
5720
0
      failures++;
5721
0
    }
5722
0
  }
5723
  /* LEN bounds the read, and a NUL is an ordinary byte */
5724
0
  for (i = 0; i < sizeof(bounded) / sizeof(bounded[0]); i++) {
5725
0
    const hts_boolean ok =
5726
0
        hts_url_view_parse(hts_span_at(bounded[i].s, bounded[i].len), &v);
5727
5728
0
    if (strcmp(urlview_describe(HTS_BUF(out), ok, &v), bounded[i].want) != 0) {
5729
0
      printf("FAIL bounded %s: %s\n", bounded[i].s, out);
5730
0
      failures++;
5731
0
    }
5732
0
  }
5733
  /* every string of up to three tokens, in a buffer with no NUL after it */
5734
0
  for (i = 0; i < ntok * ntok * ntok + ntok * ntok + ntok + 1; i++) {
5735
0
    char s[32];
5736
0
    char *buf;
5737
0
    size_t len = 0;
5738
5739
0
    for (j = i, k = 0; j != 0 && k < 3; j = (j - 1) / ntok, k++) {
5740
0
      const size_t t = (j - 1) % ntok;
5741
5742
0
      memcpy(s + len, tokens[t].s, tokens[t].len);
5743
0
      len += tokens[t].len;
5744
0
    }
5745
0
    buf = malloct(len != 0 ? len : 1);
5746
0
    memcpy(buf, s, len);
5747
0
    (void) hts_url_view_parse(hts_span_at(buf, len), &v);
5748
0
    if (!urlview_tiles(hts_span_at(buf, len), &v)) {
5749
0
      printf("FAIL tiles (%d bytes) %.*s\n", (int) len, (int) len, s);
5750
0
      failures++;
5751
0
    }
5752
0
    freet(buf);
5753
0
  }
5754
0
  printf("urlview: %d failure(s)\n", failures);
5755
0
  return failures != 0;
5756
0
}
5757
5758
/* -#test=clienthints <user-agent>: the Sec-CH-UA* values it implies. */
5759
0
static int st_clienthints(httrackp *opt, int argc, char **argv) {
5760
0
  hts_client_hints ch;
5761
5762
0
  if (argc != 1) {
5763
0
    fprintf(stderr, "clienthints: takes a user-agent\n");
5764
0
    return 1;
5765
0
  }
5766
0
  if (!hts_client_hints_of(argv[0], &ch))
5767
0
    printf("none\n");
5768
0
  else
5769
0
    printf("ua=%s mobile=?%d platform=%s\n", ch.ua, ch.mobile ? 1 : 0,
5770
0
           ch.platform);
5771
0
  return 0;
5772
0
}
5773
5774
/* -#test=headerverdict <line> [earlier...] prints hts_custom_header_verdict()
5775
   for a -%X line following the earlier ones. */
5776
0
static int st_headerverdict(httrackp *opt, int argc, char **argv) {
5777
0
  static const char *const names[] = {"sent",
5778
0
                                      "dropped-orphan-fold",
5779
0
                                      "dropped-malformed",
5780
0
                                      "dropped-framing",
5781
0
                                      "sent-replaces-earlier",
5782
0
                                      "sent-unless-engine-overrides"};
5783
0
  char headers[1024];
5784
0
  hts_header_verdict v;
5785
0
  int i;
5786
5787
0
  headers[0] = '\0';
5788
0
  for (i = 1; i < argc; i++) {
5789
0
    strcatbuff(headers, argv[i]);
5790
0
    strcatbuff(headers, "\r\n");
5791
0
  }
5792
0
  v = hts_custom_header_verdict(argc > 1 ? headers : NULL, argv[0]);
5793
0
  if ((size_t) v >= sizeof(names) / sizeof(names[0]))
5794
0
    return 1;
5795
0
  printf("%s=%d\n", names[v], (int) v);
5796
0
  return 0;
5797
0
}
5798
5799
/* -#test=browserfamily <user-agent> prints the browser whose tables it gets. */
5800
0
static int st_browserfamily(httrackp *opt, int argc, char **argv) {
5801
0
  if (argc != 1) {
5802
0
    fprintf(stderr, "browserfamily: takes a user-agent\n");
5803
0
    return 1;
5804
0
  }
5805
0
  printf("%s\n", st_family_name(hts_browser_family_of(argv[0])));
5806
0
  return 0;
5807
0
}
5808
5809
/* -#test=headerorder <none|chrome|firefox> <dest> prints a request's header
5810
   order, and fails unless it names every header once. */
5811
0
static int st_headerorder(httrackp *opt, int argc, char **argv) {
5812
0
  const int n = http_header_slot_count();
5813
0
  const unsigned char *order;
5814
0
  unsigned char seen[64];
5815
0
  hts_browser_family family;
5816
0
  int dest, i;
5817
5818
0
  if (argc != 2 || n > (int) sizeof(seen)) {
5819
0
    fprintf(stderr, "headerorder: takes <none|chrome|firefox> <dest>\n");
5820
0
    return 1;
5821
0
  }
5822
0
  if (!st_family_of(argv[0], &family) || !st_dest_of(argv[1], &dest))
5823
0
    return 1;
5824
0
  order = http_header_order(family, dest);
5825
0
  memset(seen, 0, sizeof(seen));
5826
0
  for (i = 0; i < n; i++) {
5827
0
    if (order[i] >= n || seen[order[i]]++ != 0) {
5828
0
      printf("slot %d repeats or is out of range\n", order[i]);
5829
0
      return 1;
5830
0
    }
5831
0
    printf("%s%s", i != 0 ? "," : "", http_header_slot_name(order[i]));
5832
0
  }
5833
0
  printf("\n");
5834
0
  return 0;
5835
0
}
5836
5837
/* A module that cannot be recorded leaves opt->libHandles as it was. */
5838
0
static int st_libhandlesoom(httrackp *opt, int argc, char **argv) {
5839
0
  const htslibhandles saved = opt->libHandles;
5840
0
  hts_boolean added;
5841
0
  int ok, all;
5842
5843
0
  opt->libHandles.count = 0;
5844
0
  opt->libHandles.handles = NULL;
5845
0
  hts_realloct_fault_selftest = 1;
5846
0
  added = hts_libhandles_add(opt, NULL, "first");
5847
0
  hts_realloct_fault_selftest = 0;
5848
0
  ok = !added && opt->libHandles.count == 0 && opt->libHandles.handles == NULL;
5849
0
  printf("empty list: ok=%d\n", ok);
5850
0
  all = ok;
5851
5852
0
  ok = hts_libhandles_add(opt, NULL, "first") && opt->libHandles.count == 1;
5853
0
  printf("control: ok=%d\n", ok);
5854
0
  all = all && ok;
5855
5856
0
  hts_realloct_fault_selftest = 1;
5857
0
  added = hts_libhandles_add(opt, NULL, "second");
5858
0
  hts_realloct_fault_selftest = 0;
5859
0
  ok = !added && opt->libHandles.count == 1 &&
5860
0
       strcmp(opt->libHandles.handles[0].moduleName, "first") == 0;
5861
0
  printf("one module: ok=%d\n", ok);
5862
0
  all = all && ok;
5863
5864
0
  freet(opt->libHandles.handles[0].moduleName);
5865
0
  freet(opt->libHandles.handles);
5866
0
  opt->libHandles = saved;
5867
0
  printf("libhandlesoom self-test %s\n", all ? "OK" : "FAILED");
5868
0
  return all ? 0 : 1;
5869
0
}
5870
5871
/* plug_wrapper refuses, and unplugs, a module it cannot record. */
5872
0
static int st_plugoom(httrackp *opt, int argc, char **argv) {
5873
0
  const int before = opt->libHandles.count;
5874
0
  int ret, ok, all;
5875
5876
0
  if (argc < 1) {
5877
0
    printf("usage: -#test=plugoom <module>\n");
5878
0
    return 1;
5879
0
  }
5880
0
  hts_realloct_fault_selftest = 1;
5881
0
  ret = plug_wrapper(opt, argv[0], argv[0]);
5882
0
  hts_realloct_fault_selftest = 0;
5883
0
  ok = ret == 0 && opt->libHandles.count == before;
5884
0
  printf("refused: ret=%d ok=%d\n", ret, ok);
5885
0
  all = ok;
5886
5887
0
  ret = plug_wrapper(opt, argv[0], argv[0]);
5888
0
  ok = ret == 1 && opt->libHandles.count == before + 1;
5889
0
  printf("control: ret=%d ok=%d\n", ret, ok);
5890
0
  all = all && ok;
5891
0
  printf("plugoom self-test %s\n", all ? "OK" : "FAILED");
5892
0
  return all ? 0 : 1;
5893
0
}
5894
5895
/* The libc functions the htsctype.h helpers stand in for. */
5896
static const struct {
5897
  const char *name;
5898
  int (*libc)(int);
5899
  int (*hts)(int);
5900
  hts_boolean returns_char; /* rather than a yes/no */
5901
} st_ctype_pairs[] = {
5902
    {"isdigit", isdigit, hts_isdigit, HTS_FALSE},
5903
    {"isupper", isupper, hts_isupper, HTS_FALSE},
5904
    {"islower", islower, hts_islower, HTS_FALSE},
5905
    {"isalpha", isalpha, hts_isalpha, HTS_FALSE},
5906
    {"isalnum", isalnum, hts_isalnum, HTS_FALSE},
5907
    {"isxdigit", isxdigit, hts_isxdigit, HTS_FALSE},
5908
    {"isspace", isspace, hts_isspace, HTS_FALSE},
5909
    {"tolower", tolower, hts_tolower, HTS_TRUE},
5910
    {"toupper", toupper, hts_toupper, HTS_TRUE},
5911
};
5912
5913
/* Does each helper give the "C" locale's answer for EOF and every byte? */
5914
0
static hts_boolean st_ctype_matches_c(void) {
5915
0
  hts_boolean ok = HTS_TRUE;
5916
0
  size_t i;
5917
0
  int c;
5918
5919
0
  setlocale(LC_ALL, "C");
5920
0
  for (i = 0; i < sizeof(st_ctype_pairs) / sizeof(st_ctype_pairs[0]); i++) {
5921
0
    for (c = EOF; c <= 255; c++) {
5922
0
      const int want = st_ctype_pairs[i].libc(c),
5923
0
                got = st_ctype_pairs[i].hts(c);
5924
5925
0
      if (st_ctype_pairs[i].returns_char ? want != got : !want != !got) {
5926
0
        printf("ctype C: %s(%d) is %d, libc says %d\n", st_ctype_pairs[i].name,
5927
0
               c, got, want);
5928
0
        ok = HTS_FALSE;
5929
0
      }
5930
0
    }
5931
    /* a negative char is undefined for libc: no class, case unchanged */
5932
0
    for (c = -128; c < EOF; c++) {
5933
0
      if (st_ctype_pairs[i].hts(c) !=
5934
0
          (st_ctype_pairs[i].returns_char ? c : 0)) {
5935
0
        printf("ctype C: %s(%d) is %d\n", st_ctype_pairs[i].name, c,
5936
0
               st_ctype_pairs[i].hts(c));
5937
0
        ok = HTS_FALSE;
5938
0
      }
5939
0
    }
5940
0
  }
5941
0
  return ok;
5942
0
}
5943
5944
/* Does hts_strtod_c() round every value as the "C" locale's strtod() does? */
5945
0
static hts_boolean st_strtod_matches_c(void) {
5946
0
  static const char *const odd[] = {"1.005",
5947
0
                                    "0.123456789",
5948
0
                                    "1e22",
5949
0
                                    "0.07",
5950
0
                                    "123456789012345",
5951
0
                                    "9007199254740993",
5952
0
                                    "1e-5",
5953
0
                                    "86400.001",
5954
0
                                    "2.5E-3",
5955
0
                                    "-0.07",
5956
0
                                    "5e",
5957
0
                                    "-x",
5958
0
                                    "7e+2",
5959
0
                                    "0.07000000000000000000000",
5960
0
                                    "1000e22",
5961
0
                                    "123000e20"};
5962
0
  hts_boolean ok = HTS_TRUE;
5963
0
  char buf[32];
5964
0
  int n;
5965
5966
0
  setlocale(LC_ALL, "C");
5967
0
  for (n = 0; n < 200000 + (int) (sizeof(odd) / sizeof(odd[0])); n++) {
5968
0
    const char *s = buf;
5969
5970
0
    if (n < 100000)
5971
0
      snprintf(buf, sizeof(buf), "%d.%03d", n / 1000, n % 1000);
5972
0
    else if (n < 200000)
5973
0
      snprintf(buf, sizeof(buf), "0.%05d", n - 100000);
5974
0
    else
5975
0
      s = odd[n - 200000];
5976
    /* stored, so x87 compares doubles rather than 80-bit values */
5977
0
    volatile double got = hts_strtod_c(s, NULL), want = strtod(s, NULL);
5978
5979
0
    if (got != want) {
5980
0
      printf("strtod C: %s reads %.17g, libc says %.17g\n", s, got, want);
5981
0
      ok = HTS_FALSE;
5982
0
    }
5983
0
  }
5984
0
  return ok;
5985
0
}
5986
5987
/* Sun, 06 Nov 1994 08:49:37, the RFC 9110 example date. */
5988
0
static void st_locale_date(struct tm *tm) {
5989
0
  memset(tm, 0, sizeof(*tm));
5990
0
  tm->tm_year = 94;
5991
0
  tm->tm_mon = 10;
5992
0
  tm->tm_mday = 6;
5993
0
  tm->tm_wday = 0;
5994
0
  tm->tm_hour = 8;
5995
0
  tm->tm_min = 49;
5996
0
  tm->tm_sec = 37;
5997
0
}
5998
5999
/* Prints which libc answers this locale changes, so the caller knows the
6000
   locale really took effect. */
6001
0
static void st_locale_libc_diverges(const char *name) {
6002
0
  struct tm tm;
6003
0
  char buf[256];
6004
0
  int c, high = 0;
6005
6006
0
  printf("libc-diverges %s:", name);
6007
#ifdef _WIN32
6008
  if (_stricmp("I", "i") != 0 || toupper('i') != 'I')
6009
#else
6010
0
  if (strcasecmp("I", "i") != 0 || toupper('i') != 'I')
6011
0
#endif
6012
0
    printf(" case");
6013
0
  for (c = 0x80; c <= 0xff; c++)
6014
0
    high |= isalpha(c);
6015
0
  if (high)
6016
0
    printf(" isalpha");
6017
0
  if (strtod("0.5", NULL) != 0.5)
6018
0
    printf(" strtod");
6019
0
  st_locale_date(&tm);
6020
0
  if (strftime(buf, sizeof(buf), "%a %b", &tm) == 0 ||
6021
0
      strcmp(buf, "Sun Nov") != 0)
6022
0
    printf(" strftime");
6023
0
  printf("\n");
6024
0
}
6025
6026
/* Prints a failed check of the engine under locale name, and clears *ok. */
6027
static void st_locale_check(hts_boolean *ok, const char *name, int cond,
6028
0
                            const char *what) {
6029
0
  if (!cond) {
6030
0
    printf("locale %s: FAIL %s\n", name, what);
6031
0
    *ok = HTS_FALSE;
6032
0
  }
6033
0
}
6034
6035
/* Do the engine's own parsers and formatters ignore this locale? */
6036
0
static hts_boolean st_locale_engine_ok(const char *name) {
6037
0
  hts_boolean ok = HTS_TRUE;
6038
0
  struct tm tm;
6039
0
  char buf[256];
6040
0
  const char *end;
6041
0
  double rate, pmin, pmax;
6042
0
  int c;
6043
6044
0
  st_locale_date(&tm);
6045
0
  time_rfc822(HTS_BUF(buf), &tm);
6046
0
  st_locale_check(&ok, name, strcmp(buf, "Sun, 06 Nov 1994 08:49:37 GMT") == 0,
6047
0
                  "time_rfc822");
6048
0
  st_locale_check(&ok, name, optrate_read("0.5", &rate) == 3 && rate == 0.5,
6049
0
                  "optrate_read");
6050
0
  st_locale_check(&ok, name,
6051
0
                  optpause_read("1.5:2.5", &pmin, &pmax) == 2 && pmin == 1.5 &&
6052
0
                      pmax == 2.5,
6053
0
                  "optpause_read");
6054
0
  st_locale_check(&ok, name,
6055
0
                  hts_strtod_c(" -2.5e1x", &end) == -25 && *end == 'x',
6056
0
                  "hts_strtod_c");
6057
0
  st_locale_check(&ok, name,
6058
0
                  optpause_read(" 5:10 ", &pmin, &pmax) == 2 &&
6059
0
                      optpause_read("5", &pmin, &pmax) == 1 &&
6060
0
                      optpause_read("5:", &pmin, &pmax) == 0 &&
6061
0
                      optpause_read("5x", &pmin, &pmax) == 0 &&
6062
0
                      optpause_read("0x10", &pmin, &pmax) == 0,
6063
0
                  "optpause_read junk");
6064
0
  st_locale_check(&ok, name,
6065
0
                  optrate_read("0x5", &rate) == 3 && rate == -1 &&
6066
0
                      optrate_read("5x", &rate) == 1 && rate == 5 &&
6067
0
                      optrate_read("10x", &rate) == 2 && rate == 10 &&
6068
0
                      optrate_read("x", &rate) == 1 && rate == -1 &&
6069
0
                      optrate_read("1.0x", &rate) == 3 && rate == 1,
6070
0
                  "optrate_read hex");
6071
0
  st_locale_check(&ok, name,
6072
0
                  hts_strcasecmp("INDEX.HTML", "index.html") == 0 &&
6073
0
                      hts_strncasecmp("Iz", "iy", 1) == 0 &&
6074
0
                      hts_strcasecmp("\xc9", "\xe9") != 0,
6075
0
                  "hts_strcasecmp");
6076
0
  for (c = 0x80; c <= 0xff; c++)
6077
0
    st_locale_check(&ok, name, !hts_isalpha(c) && hts_toupper(c) == c,
6078
0
                    "high byte");
6079
0
  st_locale_check(&ok, name, hts_toupper('i') == 'I' && hts_tolower('I') == 'i',
6080
0
                  "dotless i");
6081
0
  return ok;
6082
0
}
6083
6084
/* Runs the engine's text handling under each named locale, as a host that
6085
   calls setlocale() would. */
6086
0
static int st_locale(httrackp *opt, int argc, char **argv) {
6087
0
  hts_boolean ok = st_ctype_matches_c();
6088
0
  int i;
6089
6090
0
  (void) opt;
6091
0
  if (ok)
6092
0
    printf("ctype C: ok\n");
6093
0
  if (st_strtod_matches_c())
6094
0
    printf("strtod C: ok\n");
6095
0
  else
6096
0
    ok = HTS_FALSE;
6097
0
  ok = st_locale_engine_ok("C") && ok;
6098
0
  for (i = 0; i < argc; i++) {
6099
0
    if (setlocale(LC_ALL, argv[i]) == NULL) {
6100
0
      printf("locale %s: unavailable\n", argv[i]);
6101
0
      continue;
6102
0
    }
6103
0
    st_locale_libc_diverges(argv[i]);
6104
0
    if (st_locale_engine_ok(argv[i]))
6105
0
      printf("locale %s: ok\n", argv[i]);
6106
0
    else
6107
0
      ok = HTS_FALSE;
6108
0
  }
6109
0
  setlocale(LC_ALL, "C");
6110
0
  return ok ? 0 : 1;
6111
0
}
6112
6113
/* Does buf hold a cap-clipped string of full bytes, canary untouched? */
6114
0
static hts_boolean st_sized_len_ok(const char *buf, size_t cap, size_t full) {
6115
0
  return memchr(buf, '\0', cap) == buf + (full < cap ? full : cap - 1) &&
6116
0
         st_sized_guard_ok(buf, cap);
6117
0
}
6118
6119
/* The deprecated forms are what these measure, so silence them here only. */
6120
#if defined(__GNUC__) || defined(__clang__)
6121
#pragma GCC diagnostic push
6122
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
6123
#elif defined(_MSC_VER)
6124
#pragma warning(push)
6125
#pragma warning(disable : 4996)
6126
#endif
6127
0
static void st_qsec2str_legacy(char *st, TStamp t) { qsec2str(st, t); }
6128
6129
0
static void st_infostatuscode_legacy(char *msg, int code) {
6130
0
  infostatuscode(msg, code);
6131
0
}
6132
#if defined(__GNUC__) || defined(__clang__)
6133
#pragma GCC diagnostic pop
6134
#elif defined(_MSC_VER)
6135
#pragma warning(pop)
6136
#endif
6137
6138
/* The duration, date and status writers clip to the size they are given. */
6139
0
static int st_lib_sized(httrackp *opt, int argc, char **argv) {
6140
  /* Each row exercises one branch of the duration formatter. */
6141
0
  static const struct {
6142
0
    TStamp t;
6143
0
    const char *want;
6144
0
  } durs[] = {{3 * 86400 + 2 * 3600 + 4 * 60 + 5,
6145
0
               "3 days, 2 hours 4 minutes 5 seconds"},
6146
0
              {7445, "2 hours 4 minutes 5 seconds"},
6147
0
              {245, "4 minutes 5 seconds"},
6148
0
              {5, "5 seconds"}};
6149
6150
0
  static const char qdur[] = "2147483647d,23h,59min59s";
6151
6152
  /* clipped, one byte short, an exact fit, and the unknown-code fallback */
6153
0
  static const struct {
6154
0
    int code;
6155
0
    size_t cap;
6156
0
    const char *want;
6157
0
  } codes[] = {{404, 4, "Not Found"},
6158
0
               {404, 9, "Not Found"},
6159
0
               {404, 10, "Not Found"},
6160
0
               {799, 8, "Unknown error"},
6161
0
               {799, 14, "Unknown error"}};
6162
0
  static const char date[] = "Sun, 06 Nov 1994 08:49:37 GMT";
6163
0
  static const char mdate[] = "Tue, 29 Feb 2000 00:00:00 GMT";
6164
  /* The caps are 8 bytes, one byte short, and an exact fit. */
6165
0
  const size_t rcaps[] = {8, sizeof(date) - 1, sizeof(date)};
6166
0
  char path[HTS_URLMAXSIZE];
6167
0
  char gmt[256], local[256];
6168
0
  struct tm tm;
6169
0
  size_t i, k;
6170
0
  int fail = 0;
6171
6172
0
  (void) opt;
6173
0
  if (argc < 1)
6174
0
    return 1;
6175
0
  snprintf(path, sizeof(path), "%s/lib-sized.bin", argv[0]);
6176
0
  {
6177
0
    FILE *const fp = FOPEN(path, "wb");
6178
6179
0
    if (fp == NULL || fclose(fp) != 0 ||
6180
0
        set_filetime_rfc822(path, mdate) != 0) {
6181
0
      printf("lib-sized: cannot prepare %s\n", path);
6182
0
      return 1;
6183
0
    }
6184
0
  }
6185
0
  for (i = 0; i < sizeof(durs) / sizeof(durs[0]); i++) {
6186
0
    const size_t len = strlen(durs[i].want);
6187
0
    const size_t dcaps[] = {8, len, len + 1};
6188
6189
0
    for (k = 0; k < 3; k++) {
6190
0
      char *buf = st_sized_alloc(dcaps[k]);
6191
6192
0
      sec2str(hts_buf_at(buf, dcaps[k]), durs[i].t);
6193
0
      if (!st_sized_clip_ok(buf, dcaps[k], durs[i].want)) {
6194
0
        printf("lib-sized: sec2str(%d) into %u bytes\n", (int) durs[i].t,
6195
0
               (unsigned) dcaps[k]);
6196
0
        fail = 1;
6197
0
      }
6198
0
      freet(buf);
6199
0
    }
6200
0
  }
6201
  /* the clock may tick between calls, so later rows compare only lengths */
6202
0
  time_gmt_rfc822(HTS_BUF(gmt));
6203
0
  time_local_rfc822(HTS_BUF(local));
6204
0
  if (strlen(gmt) < 4 || strcmp(gmt + strlen(gmt) - 4, " GMT") != 0 ||
6205
0
      strstr(local, "GMT") != NULL) {
6206
0
    printf("lib-sized: GMT is '%s' and local is '%s'\n", gmt, local);
6207
0
    fail = 1;
6208
0
  }
6209
0
  st_locale_date(&tm);
6210
0
  for (k = 0; k < 3; k++) {
6211
0
    const size_t rcap = rcaps[k];
6212
0
    char *buf = st_sized_alloc(rcap);
6213
6214
0
    time_rfc822(hts_buf_at(buf, rcap), &tm);
6215
0
    if (!st_sized_clip_ok(buf, rcap, date)) {
6216
0
      printf("lib-sized: time_rfc822 into %u bytes\n", (unsigned) rcap);
6217
0
      fail = 1;
6218
0
    }
6219
0
    if (!get_filetime_rfc822(path, hts_buf_at(buf, rcap)) ||
6220
0
        !st_sized_clip_ok(buf, rcap, mdate)) {
6221
0
      printf("lib-sized: get_filetime_rfc822 into %u bytes\n", (unsigned) rcap);
6222
0
      fail = 1;
6223
0
    }
6224
0
    time_gmt_rfc822(hts_buf_at(buf, rcap));
6225
0
    if (!st_sized_len_ok(buf, rcap, strlen(gmt))) {
6226
0
      printf("lib-sized: time_gmt_rfc822 into %u bytes\n", (unsigned) rcap);
6227
0
      fail = 1;
6228
0
    }
6229
0
    time_local_rfc822(hts_buf_at(buf, rcap));
6230
0
    if (!st_sized_len_ok(buf, rcap, strlen(local))) {
6231
0
      printf("lib-sized: time_local_rfc822 into %u bytes\n", (unsigned) rcap);
6232
0
      fail = 1;
6233
0
    }
6234
0
    freet(buf);
6235
0
  }
6236
0
  for (k = 0; k < 4; k++) {
6237
    /* one byte short, an exact fit, and the 32 bytes qsec2str() assumes */
6238
0
    const size_t qcaps[] = {8, sizeof(qdur) - 1, sizeof(qdur), 32};
6239
0
    char *buf = st_sized_alloc(qcaps[k]);
6240
0
    const TStamp longest = (TStamp) 2147483647 * 86400 + 86399;
6241
6242
0
    if (k == 3)
6243
0
      st_qsec2str_legacy(buf, longest);
6244
0
    else
6245
0
      qsec2str_sized(buf, qcaps[k], longest);
6246
0
    if (!st_sized_clip_ok(buf, qcaps[k], qdur)) {
6247
0
      printf("lib-sized: qsec2str into %u bytes wrote '%.32s'\n",
6248
0
             (unsigned) qcaps[k], buf);
6249
0
      fail = 1;
6250
0
    }
6251
0
    freet(buf);
6252
0
  }
6253
0
  for (i = 0; i < sizeof(codes) / sizeof(codes[0]); i++) {
6254
0
    char *buf = st_sized_alloc(codes[i].cap);
6255
6256
0
    infostatuscode_sized(buf, codes[i].cap, codes[i].code);
6257
0
    if (!st_sized_clip_ok(buf, codes[i].cap, codes[i].want)) {
6258
0
      printf("lib-sized: infostatuscode(%d) into %u bytes\n", codes[i].code,
6259
0
             (unsigned) codes[i].cap);
6260
0
      fail = 1;
6261
0
    }
6262
0
    freet(buf);
6263
0
  }
6264
0
  {
6265
    /* the longest reason phrase fits the 64 bytes infostatuscode() assumes */
6266
0
    const char *want = "";
6267
0
    int code = 0, c;
6268
0
    char *buf = st_sized_alloc(64);
6269
6270
0
    for (c = 100; c < 600; c++) {
6271
0
      const char *const text = infostatuscode_const(c);
6272
6273
0
      if (text != NULL && strlen(text) > strlen(want)) {
6274
0
        want = text;
6275
0
        code = c;
6276
0
      }
6277
0
    }
6278
0
    st_infostatuscode_legacy(buf, code);
6279
0
    if (strlen(want) < 30 || !st_sized_clip_ok(buf, 64, want)) {
6280
0
      printf("lib-sized: infostatuscode(%d) wrote '%.64s'\n", code, buf);
6281
0
      fail = 1;
6282
0
    }
6283
0
    freet(buf);
6284
0
  }
6285
0
  for (k = 5; k <= 6; k++) {
6286
    /* fslash converts on every platform; one byte short leaves "" */
6287
0
    char *buf = st_sized_alloc(k);
6288
6289
0
    if (!st_sized_clip_ok(fslash(hts_buf_at(buf, k), "a\\b\\c"), k,
6290
0
                          k == 6 ? "a/b/c" : "")) {
6291
0
      printf("lib-sized: fslash into %u bytes wrote '%.6s'\n", (unsigned) k,
6292
0
             buf);
6293
0
      fail = 1;
6294
0
    }
6295
0
    freet(buf);
6296
0
  }
6297
0
  (void) UNLINK(path);
6298
0
  return st_verdict("lib-sized", fail);
6299
0
}
6300
6301
const struct selftest_entry selftests_lib[] = {
6302
    {"lib-sized", "<dir>",
6303
     "the duration and date writers stay inside the buffer they are given",
6304
     st_lib_sized},
6305
    {"locale", "<locale>...", "text handling ignores the locale a host may set",
6306
     st_locale},
6307
    {"plugoom", "<module>", "a module that cannot be recorded is unplugged",
6308
     st_plugoom},
6309
    {"libhandlesoom", "", "a module that cannot be recorded changes nothing",
6310
     st_libhandlesoom},
6311
    {"userinfo", "<url>...", "the host each login parser finds in a URL",
6312
     st_userinfo},
6313
    {"typedlogin", "", "escape the ?, # and \\ of a typed URL's login",
6314
     st_typedlogin},
6315
    {"urlview", "[url...]", "the spans hts_url_view_parse() finds in a URL",
6316
     st_urlview},
6317
    {"clienthints", "<user-agent>",
6318
     "the client hints a browser sending this User-Agent adds", st_clienthints},
6319
    {"headerverdict", "<line> [earlier...]",
6320
     "what the engine does with a -%X line", st_headerverdict},
6321
    {"browserfamily", "<user-agent>",
6322
     "the browser whose header tables this User-Agent gets", st_browserfamily},
6323
    {"headerorder", "<none|chrome|firefox> <dest>",
6324
     "the header order of a request from that browser", st_headerorder},
6325
    {"hashtable", "<count|file>", "coucal hashtable stress test", st_hashtable},
6326
    {"strsafe", "[overflow|overflow-buff|overflow-src [str]]",
6327
     "bounded string-op self-test", st_strsafe},
6328
    {"duration", "<seconds>", "a duration as long and as short text",
6329
     st_duration},
6330
    {"mono", "", "the monotonic clock's units, never deadline and timeouts",
6331
     st_mono},
6332
    {"base64", "<hex:..|string> [repeat] [crlf] [size]",
6333
     "base-64 of a repeated string, with a CRLF every 76 characters",
6334
     st_base64},
6335
    {"strsprintf", "", "StringSprintf grows to fit at every capacity boundary",
6336
     st_strsprintf},
6337
    {"arena", "", "htsarena.h hands out addresses that never move", st_arena},
6338
    {"pathcontained", "",
6339
     "a \"..\" component, and a name carrying its own root, are refused; a "
6340
     "\"..\" inside a name is not",
6341
     st_pathcontained},
6342
    {"arrays",
6343
     "[overflow-capa|overflow-loop|push|reserve-overflow|at-past-end]",
6344
     "htsarrays.h growth reaches the requested room, or reports it failed",
6345
     st_arrays},
6346
    {"ucs4-oom", "", "a UCS4 re-encode the allocator refuses aborts",
6347
     st_ucs4_oom},
6348
    {"ucs2", "[oom]", "UCS2 to UTF-8 re-encoding, and its failure return",
6349
     st_ucs2},
6350
    {"lastchar", "",
6351
     "last-char helpers never index before the buffer (#770, #781, #821)",
6352
     st_lastchar},
6353
    {"rtrim", "", "hts_rtrim never walks below the buffer", st_rtrim},
6354
    {"uninit", "", "hts_uninit releases what hts_init sets up, twice safely",
6355
     st_uninit},
6356
    {"chartab", "", "HTS_BLANKS and lochar() over every byte", st_chartab},
6357
    {"strcasecmp", "",
6358
     "hts_strcasecmp compares the whole of both strings, ignoring case",
6359
     st_strcasecmp},
6360
    {"queryparam", "<url> <name> [size]", "the value %[param] reads for a key",
6361
     st_queryparam},
6362
    {"querysweep", "", "%[param] stays inside every buffer size it is given",
6363
     st_querysweep},
6364
    {"querynext", "[query]", "the fields the shared query iterator reads",
6365
     st_querynext},
6366
    {"normfil", "<path> [strip]", "the dedup key of a path, query sorted",
6367
     st_normfil},
6368
    {"spandiff", "",
6369
     "the span iterator matches the rule-list parsers it replaced",
6370
     st_spandiff},
6371
    {"buf", "[tail-overrun]",
6372
     "the sizes HTS_BUF, HTS_BUF_N, hts_buf_skip and hts_buf_none give",
6373
     st_buf},
6374
    {"bufwrite", "[cpy|cat|catn|unterminated[-cpy|-catn]]",
6375
     "the hts_buf write helpers copy, append, clip and print in bounds",
6376
     st_bufwrite},
6377
    {"buftry", "", "hts_buf_try_cpy and hts_buf_try_cat write all or refuse",
6378
     st_buftry},
6379
    {"span",
6380
     "<next|nextsep|split|param|trim|copy|header|headersplit> [args] <text>",
6381
     "the fields and copies the span primitive makes", st_span},
6382
    {"spancmp", "", "span compares read a NUL as a byte and fold only A-Z",
6383
     st_spancmp},
6384
    {"spanindex", "", "the word a span matches in a NULL-terminated list",
6385
     st_spanindex},
6386
    {"spanlist", "", "the token a span list holds", st_spanlist},
6387
    {"spanfind", "", "the byte a span finder stops at, from either end",
6388
     st_spanfind},
6389
    {"cinames", "", "hts_streq_ci and the prefix tests fold only A-Z",
6390
     st_cinames},
6391
    {"pathjoin", "", "hts_path_join() inserts one '/' and refuses a long path",
6392
     st_pathjoin},
6393
    {"headerparse", "<file>",
6394
     "the fields treathead_opt() reads from each response in a file",
6395
     st_headerparse},
6396
    {"gmtime", "",
6397
     "hts_gmtime() fills the caller's buffer, not a static (#794)", st_gmtime},
6398
    {"secretheaders", "<text|hex:..>...",
6399
     "the header tokens the log learns from each block, and how it shows it",
6400
     st_secretheaders},
6401
    {"secretslices", "<url> <headers> <text> [size]",
6402
     "each slice of a text the log masks, after learning a login and tokens",
6403
     st_secretslices},
6404
    {"secrets", "",
6405
     "the log hides a password it has seen in a login, and a header token "
6406
     "anywhere",
6407
     st_secrets},
6408
    {"maskpw", "[list|addr <text>]",
6409
     "the command-line echo masks the password of a URL login and nothing "
6410
     "else",
6411
     st_maskpw},
6412
    {"y2038", "[dir]", "dates before and after 2038 read as 64-bit seconds",
6413
     st_y2038},
6414
    {"localtime", "<dir>",
6415
     "hts_localtime() and get_filetime_rfc822()'s GMT labelling (#806)",
6416
     st_localtime},
6417
    {"random", "", "hts_random_bytes() fills exactly the requested length",
6418
     st_random},
6419
    {"structcheck", "<dir>",
6420
     "structcheck path guard and the <name>.txt rename it performs",
6421
     st_structcheck},
6422
#ifndef _WIN32
6423
    {"sighandlers", "",
6424
     "the signal handlers save errno and write with no locking output",
6425
     st_sighandlers},
6426
    {"sigterm", "", "the terminating ^C handler runs no atexit hook",
6427
     st_sigterm},
6428
#endif
6429
    {"statrecv", "",
6430
     "the received-bytes counter keeps every add from every thread",
6431
     st_statrecv},
6432
    {"contentid", "", "every .mht Content-ID unescapes back to its own URL",
6433
     st_contentid},
6434
    {"contentid-tail", "",
6435
     "a Content-ID clips at every capacity, sizeof(void *) remainder included",
6436
     st_contentid_tail},
6437
    {"chainprev", "",
6438
     "a plug-in that chains to an unset callback reaches the engine default",
6439
     st_chainprev},
6440
    {NULL, NULL, NULL, NULL},
6441
};