Coverage Report

Created: 2026-12-01 06:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httrack/src/htssinglefile.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
/* --single-file asset inliner. See htssinglefile.h.
30
   This pass substitutes the marks htsparse left while saving, and parses no
31
   HTML or CSS. An unresolvable mark keeps its link, so a rerun is a no-op. */
32
/* ------------------------------------------------------------ */
33
34
#include "htssinglefile.h"
35
36
#include "htscore.h"
37
#include "htslib.h"
38
#include "htsio.h"
39
#include "htssafe.h"
40
#include "htsrandom.h"
41
#include "htstools.h"
42
#include "htswizard.h"
43
44
#include <stdint.h>
45
#include <stdlib.h>
46
47
/* Inlinable MIME classes. */
48
0
#define SF_C_IMAGE 1
49
0
#define SF_C_FONT 2
50
0
#define SF_C_CSS 4
51
0
#define SF_C_JS 8
52
53
/* An asset that carries marks of its own (a stylesheet importing another) is
54
   expanded before encoding; deeper than this it keeps its links. */
55
0
#define SF_MAX_CSS_DEPTH 4
56
57
/* Bounds on hostile input: a longer reference, or one resolving to more
58
   components than this, is left alone. */
59
#define SF_MAX_REF 4096
60
0
#define SF_MAX_COMPONENTS 128
61
62
/* Over-cap assets reported per pass; beyond that the log would carry one line
63
   per referencing page. */
64
0
#define SF_MAX_WARN 32
65
66
typedef struct sf_ctx {
67
  httrackp *opt;
68
  const char *root; /* mirror root, '/'-separated, no trailing separator */
69
  size_t root_len;
70
  const char *page_dir; /* directory holding the page being rewritten */
71
  int *warn_budget;
72
  LLint budget; /* bytes this page may still inline */
73
  int inlined;
74
  int marks; /* marks consumed: the file changed even when none inlined */
75
} sf_ctx;
76
77
/* ------------------------------------------------------------ */
78
/* Marks                                                         */
79
/* ------------------------------------------------------------ */
80
81
/* This run's mark secret. In memory only: persisting it would put a forgery
82
   key inside a tree people publish. */
83
struct hts_singlefile_state {
84
  char intro[sizeof(SINGLEFILE_MARK_INTRO) + SINGLEFILE_SECRET_HEX];
85
};
86
87
9.98k
void singlefile_free(httrackp *opt) {
88
9.98k
  if (opt != NULL && opt->singlefile_state != NULL) {
89
0
    freet(opt->singlefile_state);
90
0
    opt->singlefile_state = NULL;
91
0
  }
92
9.98k
}
93
94
0
const char *singlefile_intro(httrackp *opt) {
95
0
  static const char hex[] = "0123456789abcdef";
96
0
  struct hts_singlefile_state *st;
97
0
  unsigned char raw[SINGLEFILE_SECRET_HEX / 2];
98
0
  size_t i;
99
100
0
  if (opt->singlefile_state != NULL)
101
0
    return ((struct hts_singlefile_state *) opt->singlefile_state)->intro;
102
0
  if (!hts_random_bytes(raw, sizeof(raw))) {
103
    /* A guessable mark is a forgeable one, so there is no safe fallback. */
104
0
    hts_log_print(opt, LOG_ERROR,
105
0
                  "single-file: no secure random source, nothing will be "
106
0
                  "inlined");
107
0
    return NULL;
108
0
  }
109
0
  st = (struct hts_singlefile_state *) calloct(1, sizeof(*st));
110
0
  if (st == NULL)
111
0
    return NULL;
112
0
  strcpybuff(st->intro, SINGLEFILE_MARK_INTRO);
113
0
  for (i = 0; i < sizeof(raw); i++) {
114
0
    st->intro[sizeof(SINGLEFILE_MARK_INTRO) - 1 + i * 2] = hex[raw[i] >> 4];
115
0
    st->intro[sizeof(SINGLEFILE_MARK_INTRO) + i * 2] = hex[raw[i] & 15];
116
0
  }
117
0
  opt->singlefile_state = st;
118
0
  return st->intro;
119
0
}
120
121
0
hts_boolean singlefile_may_mark(httrackp *opt, hts_span body) {
122
0
  const char *const intro = singlefile_intro(opt);
123
124
0
  if (intro == NULL)
125
0
    return HTS_FALSE;
126
0
  if (hts_memstr(body, hts_span_of(intro)) != NULL) {
127
0
    hts_log_print(opt, LOG_ERROR,
128
0
                  "single-file: document already carries this run's mark, "
129
0
                  "leaving it alone");
130
0
    return HTS_FALSE;
131
0
  }
132
0
  return HTS_TRUE;
133
0
}
134
135
const char *singlefile_mark(httrackp *opt, hts_buf buf, char cls,
136
0
                            size_t reflen) {
137
0
  const char *const intro = singlefile_intro(opt);
138
139
0
  buf.p[0] = '\0';
140
  /* Nothing sf_parse_mark would refuse: an unread mark stays in the page as
141
     text and takes its reference with it. */
142
0
  if (intro != NULL && reflen <= SINGLEFILE_MAX_SPAN)
143
0
    snprintf(buf.p, buf.size, "%s.%c.%d", intro, cls, (int) reflen);
144
0
  return buf.p;
145
0
}
146
147
/* These (tag, attribute) pairs name a page or media stream, never an asset.
148
   A NULL tag matches any. Other references go by MIME type alone. */
149
static const htspair_t sf_deny_rules[] = {
150
    {"a", "href"},      {"area", "href"},   {"iframe", "src"},
151
    {"frame", "src"},   {"applet", "code"}, {NULL, "longdesc"},
152
    {NULL, "usemap"},   {NULL, "archive"},  {NULL, "profile"},
153
    {NULL, "codebase"}, {NULL, NULL},
154
};
155
156
/* Does the start tag at tag_name carry a rel naming a stylesheet? 1 yes, 0 a
157
   rel that names something else, -1 no rel at all. */
158
0
static int sf_rel_is_stylesheet(const char *tag_name) {
159
0
  size_t i;
160
161
0
  for (i = 0; i < HTS_URLMAXSIZE && tag_name[i] != '\0' && tag_name[i] != '>';
162
0
       i++) {
163
0
    const int want = (int) sizeof("stylesheet") - 1;
164
0
    const char *value;
165
0
    int p, j, len;
166
167
0
    if (i != 0 && !is_space(tag_name[i - 1]))
168
0
      continue;
169
0
    p = rech_tageq(tag_name + i, "rel");
170
0
    if (p == 0)
171
0
      continue;
172
    /* rel's own value only, as a token: an unbounded search reads the next
173
       tag's rel, and a stray "stylesheet" there inlines a page. */
174
0
    len = rech_endtoken(tag_name + i + p, &value);
175
    /* Cut at this tag's '>'. A tag left unclosed has none, so the value runs
176
       to the document NUL. */
177
0
    for (j = 0; j < len; j++) {
178
0
      if (value[j] == '>') {
179
0
        len = j;
180
0
        break;
181
0
      }
182
0
    }
183
0
    for (j = 0; j < len;) {
184
0
      int start;
185
186
0
      while (j < len && is_space(value[j]))
187
0
        j++;
188
0
      start = j;
189
0
      while (j < len && !is_space(value[j]))
190
0
        j++;
191
0
      if (j - start == want &&
192
0
          hts_strncasecmp(value + start, "stylesheet", want) == 0)
193
0
        return 1;
194
0
    }
195
0
    return 0;
196
0
  }
197
0
  return -1;
198
0
}
199
200
/* A NULL tag means "any tag" here, but ends htswizard's table. */
201
0
static hts_boolean sf_denied(const char *tag_name, const char *attr) {
202
0
  size_t i;
203
204
0
  for (i = 0; i < sizeof(sf_deny_rules) / sizeof(sf_deny_rules[0]); i++) {
205
0
    const htspair_t *const r = &sf_deny_rules[i];
206
207
0
    if (r->attr == NULL)
208
0
      break;
209
0
    if (r->tag != NULL && !hts_cmp_tag_token(tag_name, r->tag))
210
0
      continue;
211
0
    if (hts_cmp_tag_token(attr, r->attr))
212
0
      return HTS_TRUE;
213
0
  }
214
0
  return HTS_FALSE;
215
0
}
216
217
char singlefile_ref_class(const char *tag_name, const char *attr,
218
0
                          const char *body) {
219
0
  char prevc;
220
221
0
  if (attr == NULL)
222
0
    return 0;
223
0
  if (sf_denied(tag_name, attr))
224
0
    return 0;
225
0
  prevc = html_prevc(attr, body);
226
0
  if (tag_name == NULL) {
227
    /* A stylesheet or a script body: only @import names another stylesheet. */
228
0
    return rech_tageq_at(attr, prevc, "import") != 0 ? SINGLEFILE_CLASS_CSS
229
0
                                                     : SINGLEFILE_CLASS_ANY;
230
0
  }
231
0
  if (hts_cmp_tag_token(tag_name, "script") &&
232
0
      rech_tageq_at(attr, prevc, "src") != 0)
233
0
    return SINGLEFILE_CLASS_JS;
234
0
  if (hts_cmp_tag_token(tag_name, "link") &&
235
0
      rech_tageq_at(attr, prevc, "href") != 0) {
236
0
    const int rel = sf_rel_is_stylesheet(tag_name);
237
238
    /* No rel names nothing the browser would load, so it stays a link. */
239
0
    if (rel < 0)
240
0
      return 0;
241
0
    return rel > 0 ? SINGLEFILE_CLASS_CSS : SINGLEFILE_CLASS_ANY;
242
0
  }
243
0
  return SINGLEFILE_CLASS_ANY;
244
0
}
245
246
/* ------------------------------------------------------------ */
247
/* Paths                                                         */
248
/* ------------------------------------------------------------ */
249
250
0
static int sf_is_sep(int c) { return c == '/' || c == '\\'; }
251
252
/* Copy path into out with '/' separators and no trailing one. */
253
0
static void sf_normalize_path(const char *path, String *out) {
254
0
  size_t i;
255
256
0
  StringClear(*out);
257
0
  for (i = 0; path[i] != '\0'; i++)
258
0
    StringAddchar(*out, sf_is_sep((unsigned char) path[i]) ? '/' : path[i]);
259
0
  while (StringLength(*out) > 1 && StringRight(*out, 1) == '/')
260
0
    StringPopRight(*out);
261
0
}
262
263
/* Directory part of a '/'-separated path (empty when it has none). */
264
0
static void sf_dirname(const char *path, String *out) {
265
0
  const char *last = NULL;
266
0
  const char *p;
267
268
0
  for (p = path; *p != '\0'; p++) {
269
0
    if (*p == '/')
270
0
      last = p;
271
0
  }
272
0
  StringClear(*out);
273
0
  if (last != NULL)
274
0
    StringMemcat(*out, path, (size_t) (last - path));
275
0
}
276
277
/* Append to_path as seen from from_dir, both '/'-separated under one root. */
278
static void sf_relative_from(const char *from_dir, const char *to_path,
279
0
                             String *out) {
280
0
  size_t common = 0, i = 0, j, nup = 0;
281
282
0
  while (from_dir[i] != '\0' && to_path[i] != '\0' &&
283
0
         from_dir[i] == to_path[i]) {
284
0
    if (from_dir[i] == '/')
285
0
      common = i + 1;
286
0
    i++;
287
0
  }
288
  /* from_dir is an ancestor of to_path: nothing to climb, and common must not
289
     advance past from_dir's terminator. */
290
0
  if (from_dir[i] == '\0' && to_path[i] == '/') {
291
0
    StringCat(*out, to_path + i + 1);
292
0
    return;
293
0
  }
294
0
  for (j = common; from_dir[j] != '\0'; j++) {
295
0
    if (from_dir[j] == '/')
296
0
      nup++;
297
0
  }
298
0
  if (from_dir[common] != '\0')
299
0
    nup++;
300
0
  for (j = 0; j < nup; j++)
301
0
    StringMemcat(*out, "../", 3);
302
0
  StringCat(*out, to_path + common);
303
0
}
304
305
/* Resolve the mirrored reference ref against base_dir into out, a
306
   '/'-separated path under ctx->root naming an existing regular file. Returns
307
   HTS_FALSE for a fragment, an absolute or scheme-bearing URL (data:
308
   included), a reference climbing out of the mirror, or a missing target.
309
   Containment is lexical, so a symlink planted in the output directory is
310
   followed. Fetched content cannot create one. */
311
static hts_boolean sf_resolve(const sf_ctx *ctx, const char *base_dir,
312
0
                              hts_span ref, String *out) {
313
0
  char raw[SF_MAX_REF];
314
0
  char decoded[SF_MAX_REF];
315
0
  size_t stack[SF_MAX_COMPONENTS];
316
0
  String acc = STRING_EMPTY;
317
0
  hts_boolean ok = HTS_TRUE;
318
0
  size_t i, n;
319
0
  int sp = 0, part;
320
0
  const hts_span r = hts_span_trim(ref, " \t\r\n\f", " \t\r\n\f");
321
322
  /* A mirrored name carries no query or fragment. */
323
0
  n = hts_span_find_any(r, "#?");
324
0
  if (n == 0)
325
0
    return HTS_FALSE;
326
  /* Site-root-relative: no base to resolve it against. */
327
0
  if (sf_is_sep((unsigned char) r.p[0]))
328
0
    return HTS_FALSE;
329
0
  for (i = 0; i < n; i++) { /* a colon before any separator marks a scheme */
330
0
    const unsigned char c = (unsigned char) r.p[i];
331
332
0
    if (c == ':')
333
0
      return HTS_FALSE;
334
0
    if (sf_is_sep(c) ||
335
0
        (!hts_isalnum((unsigned char) c) && c != '+' && c != '.' && c != '-'))
336
0
      break;
337
0
  }
338
0
  if (!hts_buf_put_span(HTS_BUF(raw), hts_span_at(r.p, n)))
339
0
    return HTS_FALSE;
340
0
  unescape_amp(raw); /* HTML entities first, then the percent escapes */
341
0
  unescape_http(decoded, sizeof(decoded), raw);
342
0
  if (decoded[0] == '\0')
343
0
    return HTS_FALSE;
344
  /* base_dir must be the root or a directory under it, matched on a component
345
     boundary: a bare prefix test would also accept a sibling <root>foo. */
346
0
  if (strncmp(base_dir, ctx->root, ctx->root_len) != 0 ||
347
0
      (base_dir[ctx->root_len] != '\0' &&
348
0
       !sf_is_sep((unsigned char) base_dir[ctx->root_len])))
349
0
    return HTS_FALSE;
350
351
  /* Walk the page's directory relative to the root, then the reference. */
352
0
  StringClear(acc);
353
0
  for (part = 0; ok && part < 2; part++) {
354
0
    const char *p = part == 0 ? base_dir + ctx->root_len : decoded;
355
356
0
    while (ok && *p != '\0') {
357
0
      const char *const start = p;
358
0
      size_t clen;
359
360
0
      while (*p != '\0' && !sf_is_sep((unsigned char) *p))
361
0
        p++;
362
0
      clen = (size_t) (p - start);
363
0
      if (*p != '\0')
364
0
        p++;
365
0
      if (clen == 0 || (clen == 1 && start[0] == '.'))
366
0
        continue;
367
0
      if (clen == 2 && start[0] == '.' && start[1] == '.') {
368
0
        if (sp == 0) { /* would climb out of the mirror */
369
0
          ok = HTS_FALSE;
370
0
          break;
371
0
        }
372
0
        sp--;
373
0
        StringSetLength(acc, sp > 0 ? (int) stack[sp - 1] : 0);
374
0
        StringBuffRW(acc)[StringLength(acc)] = '\0';
375
0
        continue;
376
0
      }
377
0
      if (sp == SF_MAX_COMPONENTS) {
378
0
        ok = HTS_FALSE;
379
0
        break;
380
0
      }
381
0
      if (StringLength(acc) > 0)
382
0
        StringAddchar(acc, '/');
383
0
      StringMemcat(acc, start, clen);
384
0
      stack[sp++] = StringLength(acc);
385
0
    }
386
0
  }
387
0
  if (ok && StringLength(acc) > 0) {
388
0
    StringCopy(*out, ctx->root);
389
0
    StringCat(*out, "/");
390
0
    StringCat(*out, StringBuff(acc));
391
0
    ok = fexist_utf8(StringBuff(*out)) ? HTS_TRUE : HTS_FALSE;
392
0
  } else {
393
0
    ok = HTS_FALSE;
394
0
  }
395
0
  StringFree(acc);
396
0
  return ok;
397
0
}
398
399
/* ------------------------------------------------------------ */
400
/* MIME, reading, encoding                                       */
401
/* ------------------------------------------------------------ */
402
403
/* Inlinable class of the file at path, or 0; out receives the type to
404
   advertise in the data: URI. */
405
0
static int sf_mime_class(httrackp *opt, const char *path, hts_buf out) {
406
0
  const char *const mime = out.p;
407
408
0
  out.p[0] = '\0';
409
0
  if (!guess_httptype_sized(opt, out.p, out.size, path) || mime[0] == '\0')
410
0
    return 0;
411
0
  if (hts_starts_with_ci(mime, "image/"))
412
0
    return SF_C_IMAGE;
413
0
  if (hts_starts_with_ci(mime, "font/") ||
414
0
      hts_starts_with_ci(mime, "application/font") ||
415
0
      hts_starts_with_ci(mime, "application/x-font") ||
416
0
      hts_streq_ci(mime, "application/vnd.ms-fontobject"))
417
0
    return SF_C_FONT;
418
0
  if (hts_streq_ci(mime, "text/css"))
419
0
    return SF_C_CSS;
420
0
  if (is_javascript_mime_type(mime))
421
0
    return SF_C_JS;
422
0
  return 0;
423
0
}
424
425
/* readfile2_utf8() with the base64 size limit applied. */
426
0
static char *sf_readfile(const char *path, size_t *size) {
427
0
  LLint len = 0;
428
0
  char *adr;
429
430
0
  *size = 0;
431
0
  adr = readfile2_utf8(path, &len);
432
0
  if (adr == NULL)
433
0
    return NULL;
434
0
  if (len < 0 || len > SINGLEFILE_HARD_MAX_SIZE) {
435
0
    freet(adr);
436
0
    return NULL;
437
0
  }
438
0
  *size = llint_to_size_t(len);
439
0
  return adr;
440
0
}
441
442
0
static hts_boolean sf_append_base64(String *out, hts_span data) {
443
  /* code64() emits exactly one padded 4-byte group per 3 input bytes. */
444
0
  const size_t b64len = ((data.len + 2) / 3) * 4;
445
0
  char *buf;
446
447
0
  if (data.len > SINGLEFILE_HARD_MAX_SIZE)
448
0
    return HTS_FALSE;
449
0
  buf = (char *) malloct(b64len + 1);
450
0
  if (buf == NULL)
451
0
    return HTS_FALSE;
452
0
  code64(data, hts_buf_at(buf, b64len + 1), HTS_FALSE);
453
0
  StringMemcat(*out, buf, b64len);
454
0
  freet(buf);
455
0
  return HTS_TRUE;
456
0
}
457
458
/* Append s, escaping what an unquoted CSS url(), an HTML attribute or
459
   an appended fragment could choke on. preencoded text already carries the
460
   document's own '%' and '&' escapes, and encoding those again changes it. */
461
0
static void sf_append_escaped(String *out, hts_span s, hts_boolean preencoded) {
462
0
  static const char hex[] = "0123456789ABCDEF";
463
0
  size_t i;
464
465
0
  for (i = 0; i < s.len; i++) {
466
0
    const unsigned char c = (unsigned char) s.p[i];
467
468
0
    if (c <= 32 || c >= 127 || c == '"' || c == '\'' || c == '(' || c == ')' ||
469
0
        c == '\\' || c == '<' || c == '>' || c == '#' ||
470
0
        (!preencoded && (c == '%' || c == '&'))) {
471
0
      StringAddchar(*out, '%');
472
0
      StringAddchar(*out, hex[c >> 4]);
473
0
      StringAddchar(*out, hex[c & 15]);
474
0
    } else {
475
0
      StringAddchar(*out, (char) c);
476
0
    }
477
0
  }
478
0
}
479
480
/* A marked reference resolved to a file of another type, which is a bug. */
481
static void sf_warn_mismatch(sf_ctx *ctx, const char *path, char want,
482
0
                             const char *mime) {
483
0
  if (*ctx->warn_budget <= 0)
484
0
    return;
485
0
  (*ctx->warn_budget)--;
486
0
  hts_log_print(
487
0
      ctx->opt, LOG_WARNING,
488
0
      "single-file: %s is %s but was referenced as %s, left as a link", path,
489
0
      mime, want == SINGLEFILE_CLASS_CSS ? "a stylesheet" : "a script");
490
0
}
491
492
static void sf_warn_oversize(sf_ctx *ctx, const char *path, LLint size,
493
0
                             LLint cap) {
494
0
  if (*ctx->warn_budget <= 0)
495
0
    return;
496
0
  if (--(*ctx->warn_budget) == 0) {
497
0
    hts_log_print(ctx->opt, LOG_WARNING,
498
0
                  "single-file: further over-cap assets not reported");
499
0
    return;
500
0
  }
501
0
  hts_log_print(ctx->opt, LOG_WARNING,
502
0
                "single-file: %s left as a link (" LLintP
503
0
                " bytes, over the " LLintP "-byte cap)",
504
0
                path, size, cap);
505
0
}
506
507
/* ------------------------------------------------------------ */
508
/* Substitution                                                  */
509
/* ------------------------------------------------------------ */
510
511
static void sf_expand(sf_ctx *ctx, const char *base_dir, int depth,
512
                      hts_span body, String *out);
513
static size_t sf_strip_marks(const char *intro, hts_buf body);
514
515
/* Replace the reference ref, resolved against base_dir, with its
516
   data: URI appended to out. rebase_dir re-expresses an un-inlinable asset
517
   relative to that directory, for a lenient resolver's base. Returns HTS_TRUE
518
   if out received a data: URI. */
519
static hts_boolean sf_inline(sf_ctx *ctx, const char *base_dir, hts_span ref,
520
                             const char *rebase_dir, int depth, char want,
521
0
                             hts_boolean *resolved, String *out) {
522
0
  String path = STRING_EMPTY;
523
0
  char mime[HTS_MIMETYPE_SIZE];
524
0
  char *file;
525
0
  size_t file_len = 0;
526
0
  LLint size, cap;
527
0
  int cls;
528
0
  hts_boolean done = HTS_FALSE;
529
530
0
  *resolved = sf_resolve(ctx, base_dir, ref, &path);
531
0
  if (!*resolved) {
532
0
    StringFree(path);
533
0
    return HTS_FALSE;
534
0
  }
535
0
  cls = sf_mime_class(ctx->opt, StringBuff(path), HTS_BUF(mime));
536
  /* The referencing context decides when the name carries no usable type.
537
     A contradiction between the two is a bug and is not inlined. */
538
0
  if (want != SINGLEFILE_CLASS_ANY) {
539
0
    const int wanted = want == SINGLEFILE_CLASS_CSS ? SF_C_CSS : SF_C_JS;
540
541
0
    if (cls == 0) {
542
0
      cls = wanted;
543
0
      strlcpybuff(mime, wanted == SF_C_CSS ? "text/css" : "text/javascript",
544
0
                  sizeof(mime));
545
0
    } else if (cls != wanted) {
546
0
      sf_warn_mismatch(ctx, StringBuff(path), want, mime);
547
0
      cls = 0;
548
0
    }
549
0
  }
550
0
  cap = ctx->opt->single_file_max_size;
551
0
  size = fsize_utf8(StringBuff(path));
552
0
  if (cls == 0 || size < 0)
553
0
    goto fallback;
554
0
  if (size > cap || size > SINGLEFILE_HARD_MAX_SIZE) {
555
0
    sf_warn_oversize(ctx, StringBuff(path), size, cap);
556
0
    goto fallback;
557
0
  }
558
0
  if (size > ctx->budget) { /* the page has inlined all it may */
559
0
    sf_warn_oversize(ctx, StringBuff(path), size, ctx->budget);
560
0
    goto fallback;
561
0
  }
562
0
  file = sf_readfile(StringBuff(path), &file_len);
563
0
  if (file == NULL)
564
0
    goto fallback;
565
  /* Charged before the nested expansion: an @import chain otherwise spends
566
     what its ancestors already claimed, and the budget ends up negative. */
567
0
  ctx->budget -= size;
568
  /* Encode into a scratch String, so a failed encode leaves out unchanged. */
569
0
  {
570
0
    String payload = STRING_EMPTY;
571
572
0
    StringClear(payload);
573
0
    if ((cls & (SF_C_CSS | SF_C_JS)) != 0 && depth < SF_MAX_CSS_DEPTH) {
574
0
      String nested = STRING_EMPTY;
575
0
      String nested_dir = STRING_EMPTY;
576
577
0
      sf_dirname(StringBuff(path), &nested_dir);
578
0
      StringClear(nested);
579
0
      sf_expand(ctx, StringBuff(nested_dir), depth + 1,
580
0
                hts_span_at(file, file_len), &nested);
581
0
      done = sf_append_base64(
582
0
          &payload, hts_span_at(StringBuff(nested), StringLength(nested)));
583
0
      StringFree(nested);
584
0
      StringFree(nested_dir);
585
0
    } else {
586
      /* Past the nesting cap the body is embedded as it stands, so a mark it
587
         still carries would ride into the payload and publish the secret. */
588
0
      if ((cls & (SF_C_CSS | SF_C_JS)) != 0) {
589
0
        const char *const intro = singlefile_intro(ctx->opt);
590
591
0
        if (intro != NULL)
592
0
          file_len = sf_strip_marks(intro, hts_buf_at(file, file_len));
593
0
      }
594
0
      done = sf_append_base64(&payload, hts_span_at(file, file_len));
595
0
    }
596
0
    if (done) {
597
0
      StringCat(*out, "data:");
598
0
      StringCat(*out, mime);
599
0
      StringCat(*out, ";base64,");
600
0
      StringMemcat(*out, StringBuff(payload), StringLength(payload));
601
0
    }
602
0
    StringFree(payload);
603
0
  }
604
0
  freet(file);
605
0
  if (done) {
606
0
    ctx->inlined++;
607
0
    StringFree(path);
608
0
    return HTS_TRUE;
609
0
  }
610
0
  ctx->budget += size;
611
612
0
fallback:
613
0
  if (rebase_dir != NULL) {
614
0
    String rel = STRING_EMPTY;
615
616
0
    StringClear(rel);
617
0
    sf_relative_from(rebase_dir, StringBuff(path), &rel);
618
0
    if (StringLength(rel) > 0) {
619
0
      sf_append_escaped(out, hts_span_at(StringBuff(rel), StringLength(rel)),
620
0
                        HTS_FALSE);
621
0
      done = HTS_TRUE;
622
0
    }
623
0
    StringFree(rel);
624
0
  }
625
0
  StringFree(path);
626
0
  return done;
627
0
}
628
629
/* A mark htsparse wrote always names a file it had just saved, so failing to
630
   resolve one means the mirror moved under us since the page was written. */
631
0
static void sf_warn_unresolved(sf_ctx *ctx, hts_span ref) {
632
0
  if (*ctx->warn_budget <= 0)
633
0
    return;
634
0
  (*ctx->warn_budget)--;
635
  /* Clipped: a span runs far past anything that could name a file. */
636
0
  hts_log_print(ctx->opt, LOG_WARNING,
637
0
                "single-file: marked reference \"%.*s\" resolves to no "
638
0
                "mirrored file, left as a link",
639
0
                (int) (ref.len > 256 ? 256 : ref.len), ref.p);
640
0
}
641
642
/* Parse the mark at the start of s: "<intro>.<class>.<len>". Returns its
643
   length, or 0 if it is not one. intro is SINGLEFILE_INTRO_LEN bytes. A NULL
644
   intro matches any well-formed secret, so a later run can delete marks an
645
   interrupted one left behind without its secret. */
646
static size_t sf_parse_mark(const char *intro, hts_span s, char *cls,
647
0
                            size_t *reflen) {
648
0
  size_t i = SINGLEFILE_INTRO_LEN;
649
0
  size_t n = 0;
650
0
  int digits = 0;
651
652
0
  if (s.len < SINGLEFILE_INTRO_LEN)
653
0
    return 0;
654
0
  if (intro != NULL) {
655
0
    if (memcmp(s.p, intro, SINGLEFILE_INTRO_LEN) != 0)
656
0
      return 0;
657
0
  } else {
658
0
    size_t k;
659
660
0
    if (memcmp(s.p, SINGLEFILE_MARK_INTRO, sizeof(SINGLEFILE_MARK_INTRO) - 1) !=
661
0
        0)
662
0
      return 0;
663
0
    for (k = sizeof(SINGLEFILE_MARK_INTRO) - 1; k < SINGLEFILE_INTRO_LEN; k++) {
664
0
      if (!hts_isxdigit((unsigned char) s.p[k]))
665
0
        return 0;
666
0
    }
667
0
  }
668
0
  if (i + 3 >= s.len || s.p[i] != '.')
669
0
    return 0;
670
0
  *cls = s.p[++i];
671
0
  if (*cls != SINGLEFILE_CLASS_ANY && *cls != SINGLEFILE_CLASS_CSS &&
672
0
      *cls != SINGLEFILE_CLASS_JS)
673
0
    return 0;
674
0
  if (++i >= s.len || s.p[i++] != '.')
675
0
    return 0;
676
0
  while (i < s.len && s.p[i] >= '0' && s.p[i] <= '9') {
677
0
    if (n > SINGLEFILE_MAX_SPAN) /* saturated: no digit run can overflow n */
678
0
      return 0;
679
0
    n = n * 10 + (size_t) (s.p[i++] - '0');
680
0
    digits++;
681
0
  }
682
0
  if (digits == 0 || n > SINGLEFILE_MAX_SPAN)
683
0
    return 0;
684
0
  *reflen = n;
685
0
  return i;
686
0
}
687
688
/* Drop every mark from body in place; returns the new length. */
689
0
static size_t sf_strip_marks(const char *intro, hts_buf body) {
690
0
  const hts_span in = hts_span_at(body.p, body.size);
691
0
  size_t r, w = 0;
692
693
0
  for (r = 0; r < in.len;) {
694
0
    char cls;
695
0
    size_t reflen;
696
0
    const size_t marklen =
697
0
        sf_parse_mark(intro, hts_span_skip(in, r), &cls, &reflen);
698
699
0
    if (marklen != 0)
700
0
      r += marklen;
701
0
    else
702
0
      body.p[w++] = body.p[r++];
703
0
  }
704
0
  return w;
705
0
}
706
707
/* Copy body to out, replacing each marked reference by its data:
708
   URI, or by the bare reference when it cannot be inlined. Whatever follows
709
   the reference (a fragment, a kept query) stays after the data: URI. The
710
   substitution is in place, so an unquoted attribute gets base64 '=' padding,
711
   which browsers accept but the HTML grammar forbids. */
712
static void sf_expand(sf_ctx *ctx, const char *base_dir, int depth,
713
0
                      hts_span body, String *out) {
714
0
  const char *const intro = singlefile_intro(ctx->opt);
715
0
  size_t i = 0, flushed = 0;
716
717
0
  if (intro == NULL) {
718
0
    StringCatSpan(out, body);
719
0
    return;
720
0
  }
721
0
  while (i + SINGLEFILE_INTRO_LEN <= body.len) {
722
0
    hts_boolean resolved = HTS_FALSE;
723
0
    size_t marklen, reflen = 0;
724
0
    char cls = SINGLEFILE_CLASS_ANY;
725
0
    hts_span ref;
726
727
    /* Every mark opens with the intro, so skip the call on any other byte. */
728
0
    marklen = body.p[i] == intro[0]
729
0
                  ? sf_parse_mark(intro, hts_span_skip(body, i), &cls, &reflen)
730
0
                  : 0;
731
    /* We wrote the length, but the file may have been truncated since; a
732
       reference reaching back before what we have is not one of ours. */
733
0
    if (marklen == 0 || reflen > i - flushed) {
734
0
      i++;
735
0
      continue;
736
0
    }
737
0
    ref = hts_span_at(body.p + i - reflen, reflen);
738
0
    StringMemcat(*out, body.p + flushed, i - reflen - flushed);
739
0
    if (!sf_inline(ctx, base_dir, ref, depth > 0 ? ctx->page_dir : NULL, depth,
740
0
                   cls, &resolved, out)) {
741
0
      if (!resolved)
742
0
        sf_warn_unresolved(ctx, ref);
743
0
      StringCatSpan(out, ref);
744
0
    }
745
0
    ctx->marks++;
746
0
    i += marklen;
747
0
    flushed = i;
748
0
  }
749
0
  StringCatSpan(out, hts_span_skip(body, flushed));
750
0
}
751
752
/* ------------------------------------------------------------ */
753
/* Entry points                                                  */
754
/* ------------------------------------------------------------ */
755
756
hts_boolean singlefile_rewrite_html(httrackp *opt, const char *root,
757
                                    const char *page_path, hts_span html,
758
0
                                    LLint page_budget, String *out) {
759
0
  String nroot = STRING_EMPTY;
760
0
  String npage = STRING_EMPTY;
761
0
  String dir = STRING_EMPTY;
762
0
  int budget = SF_MAX_WARN;
763
0
  sf_ctx ctx;
764
765
0
  sf_normalize_path(root, &nroot);
766
0
  sf_normalize_path(page_path, &npage);
767
0
  sf_dirname(StringBuff(npage), &dir);
768
0
  ctx.opt = opt;
769
0
  ctx.root = StringBuff(nroot);
770
0
  ctx.root_len = StringLength(nroot);
771
0
  ctx.page_dir = StringBuff(dir);
772
0
  ctx.warn_budget = &budget;
773
0
  ctx.budget = page_budget;
774
0
  ctx.inlined = 0;
775
0
  ctx.marks = 0;
776
0
  sf_expand(&ctx, StringBuff(dir), 0, html, out);
777
0
  StringFree(nroot);
778
0
  StringFree(npage);
779
0
  StringFree(dir);
780
  /* Any mark consumed means the bytes changed, even if nothing inlined: the
781
     marks themselves must never survive into the delivered mirror. */
782
0
  return ctx.marks > 0 ? HTS_TRUE : HTS_FALSE;
783
0
}
784
785
/* Overwrite path with body. Spools then renames: a half-written file would
786
   destroy a complete mirror file that nothing is going to re-fetch. */
787
static hts_boolean sf_replace_file(httrackp *opt, const char *path,
788
0
                                   hts_span body) {
789
0
  char catbuff[CATBUFF_SIZE];
790
0
  String tmp = STRING_EMPTY;
791
0
  hts_boolean ok = HTS_TRUE;
792
0
  FILE *fp;
793
794
0
  StringCopy(tmp, path);
795
0
  StringCat(tmp, ".sfnew");
796
0
  fp = FOPEN(fconv(catbuff, sizeof(catbuff), StringBuff(tmp)), "wb");
797
0
  if (fp == NULL) {
798
0
    hts_log_print(opt, LOG_WARNING | LOG_ERRNO,
799
0
                  "single-file: could not rewrite %s", path);
800
0
    StringFree(tmp);
801
0
    return HTS_FALSE;
802
0
  }
803
0
  if (!hts_fwrite_span(body, fp))
804
0
    ok = HTS_FALSE;
805
0
#ifndef _WIN32
806
  /* The spool bypassed filecreate(), so set the mode it would have. */
807
0
  if (ok)
808
0
    (void) fchmod(fileno(fp), HTS_ACCESS_FILE);
809
0
#endif
810
0
  if (fclose(fp) != 0)
811
0
    ok = HTS_FALSE;
812
0
  if (ok)
813
0
    ok = hts_rename_over(opt, StringBuff(tmp), path);
814
0
  if (!ok) {
815
0
    hts_log_print(opt, LOG_ERROR, "single-file: could not rewrite %s", path);
816
0
    (void) UNLINK(StringBuff(tmp));
817
0
  }
818
0
  StringFree(tmp);
819
0
  return ok;
820
0
}
821
822
hts_boolean singlefile_rewrite_file(httrackp *opt, const char *root,
823
0
                                    const char *page_path) {
824
0
  String out = STRING_EMPTY;
825
0
  size_t len = 0;
826
0
  char *html = sf_readfile(page_path, &len);
827
0
  hts_boolean ok;
828
829
0
  if (html == NULL)
830
0
    return HTS_FALSE;
831
0
  StringClear(out);
832
0
  ok = singlefile_rewrite_html(opt, root, page_path, hts_span_at(html, len),
833
0
                               SINGLEFILE_MAX_PAGE_SIZE, &out);
834
0
  freet(html);
835
0
  if (ok)
836
0
    ok = sf_replace_file(opt, page_path,
837
0
                         hts_span_at(StringBuff(out), StringLength(out)));
838
0
  StringFree(out);
839
0
  return ok;
840
0
}
841
842
/* Delete every mark from the file, keeping the reference and anything that
843
   followed it. Returns HTS_TRUE if the file changed. */
844
0
static hts_boolean sf_strip_marks_file(httrackp *opt, const char *path) {
845
0
  size_t len = 0, w;
846
0
  char *body;
847
0
  hts_boolean ok;
848
849
0
  body = sf_readfile(path, &len);
850
0
  if (body == NULL)
851
0
    return HTS_FALSE;
852
0
  w = sf_strip_marks(NULL, hts_buf_at(body, len));
853
0
  if (w == len) {
854
0
    freet(body);
855
0
    return HTS_FALSE;
856
0
  }
857
0
  ok = sf_replace_file(opt, path, hts_span_at(body, w));
858
0
  freet(body);
859
0
  return ok;
860
0
}
861
862
0
void singlefile_process_mirror(httrackp *opt) {
863
0
  const char *root;
864
0
  int i, pages = 0;
865
866
0
  if (opt == NULL || !opt->single_file)
867
0
    return;
868
0
  root = StringBuff(opt->path_html_utf8);
869
0
  if (root == NULL || root[0] == '\0')
870
0
    return;
871
0
  for (i = 0; i < opt->lien_tot; i++) {
872
0
    const lien_url *const link = opt->liens[i];
873
874
0
    if (link == NULL || link->sav == NULL || link->sav[0] == '\0')
875
0
      continue;
876
0
    if (ishtml(opt, link->sav) != 1 || !fexist_utf8(link->sav))
877
0
      continue;
878
0
    if (singlefile_rewrite_file(opt, root, link->sav))
879
0
      pages++;
880
0
  }
881
  /* Strip marks only after every page is done, because a stylesheet expands
882
     from the marks in its copy on disk. */
883
0
  for (i = 0; i < opt->lien_tot; i++) {
884
0
    const lien_url *const link = opt->liens[i];
885
886
0
    if (link == NULL || link->sav == NULL || link->sav[0] == '\0')
887
0
      continue;
888
0
    if (!fexist_utf8(link->sav))
889
0
      continue;
890
0
    (void) sf_strip_marks_file(opt, link->sav);
891
0
  }
892
0
  if (pages == 0) {
893
    /* Nothing to inline means the saved pages carry no relative asset links,
894
       which is what --keep-links and --preserve produce. Say so: a silent
895
       no-op looks like the option was ignored. */
896
0
    hts_log_print(opt, LOG_NOTICE,
897
0
                  "single-file: no page had an inlinable asset link "
898
0
                  "(--keep-links or --preserve in use?)");
899
0
  } else {
900
0
    hts_log_print(opt, LOG_INFO,
901
0
                  "single-file: %d page(s) rewritten with inlined assets",
902
0
                  pages);
903
0
  }
904
0
}