Coverage Report

Created: 2026-12-01 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httrack/src/htscore.c
Line
Count
Source
1
/* ------------------------------------------------------------ */
2
/*
3
HTTrack Website Copier, Offline Browser for Windows and Unix
4
Copyright (C) 1998 Xavier Roche and other contributors
5
6
SPDX-License-Identifier: GPL-3.0-or-later
7
8
This program is free software: you can redistribute it and/or modify
9
it under the terms of the GNU General Public License as published by
10
the Free Software Foundation, either version 3 of the License, or
11
(at your option) any later version.
12
13
This program is distributed in the hope that it will be useful,
14
but WITHOUT ANY WARRANTY; without even the implied warranty of
15
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
GNU General Public License for more details.
17
18
You should have received a copy of the GNU General Public License
19
along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21
Ethical use: we kindly ask that you NOT use this software to harvest email
22
addresses or to collect any other private information about people. Doing so
23
would dishonor our work and waste the many hours we have spent on it.
24
25
Please visit our Website: http://www.httrack.com
26
*/
27
28
/* ------------------------------------------------------------ */
29
/* File: Main source                                            */
30
/* Author: Xavier Roche                                         */
31
/* ------------------------------------------------------------ */
32
33
#include <fcntl.h>
34
#include <limits.h> /* INT_MAX, capping the backing table's size */
35
#include <stdint.h> /* uint64_t for the pause mixer (already a hard dep via md5.h) */
36
37
/* File defs */
38
#include "htscore.h"
39
#include "htsbundle.h"
40
41
#include "htssitemap.h"
42
#include "htswarc.h"
43
#include "htschanges.h"
44
#include "htssinglefile.h"
45
46
/* specific definitions */
47
#include "htsbase.h"
48
#include "htsio.h"
49
#include "htsnet.h"
50
#include "htsbauth.h"
51
#include "htsmd5.h"
52
#include "htsindex.h"
53
54
/* external modules */
55
#include "htsmodules.h"
56
57
// htswrap_add
58
#include "htswrap.h"
59
60
// parser
61
#include "htsparse.h"
62
#include "htsmirror.h"
63
64
/* Cache */
65
#include "htszlib.h"
66
67
/* Charset handling */
68
#include "htscharset.h"
69
70
/* Dynamic typed arrays */
71
#include "htsarrays.h"
72
#include "htsarena.h"
73
#include "htscmdline.h"
74
75
/* Schedule more links from the heap into free slots. */
76
static void back_fill(struct_back *sback, httrackp *opt, cache_back *cache,
77
                      int ptr, int numero_passe);
78
79
/* END specific definitions */
80
81
/* external modules */
82
extern int hts_parse_externals(htsmoduleStruct * str);
83
extern void htspe_init(void);
84
85
// Début de httpmirror, routines annexes
86
87
// au cas où nous devons quitter rapidement xhttpmirror (plus de mémoire, etc)
88
// note: partir de liens_max.. vers 0.. sinon erreur de violation de mémoire: les liens suivants
89
// ne sont plus à nous.. agh! [dur celui-là]
90
0
#define HTMLCHECK_UNINIT { \
91
0
hts_log_print(opt, LOG_INFO, "engine: end"); \
92
0
RUN_CALLBACK0(opt, end); \
93
0
}
94
95
#define XH_extuninit                                                           \
96
0
  do {                                                                         \
97
0
    HTMLCHECK_UNINIT                                                           \
98
0
    hts_record_free(opt);                                                      \
99
0
    if (filters && filters[0]) {                                               \
100
0
      freet(filters[0]);                                                       \
101
0
      filters[0] = NULL;                                                       \
102
0
    }                                                                          \
103
0
    if (filters) {                                                             \
104
0
      freet(filters);                                                          \
105
0
      filters = NULL;                                                          \
106
0
    }                                                                          \
107
0
    back_delete_all(opt, &cache, sback);                                       \
108
0
    back_free(&sback);                                                         \
109
0
    checkrobots_free(&robots);                                                 \
110
0
    if (cache.zipOutput) {                                                     \
111
0
      zipClose(cache.zipOutput,                                                \
112
0
               "Created by HTTrack Website Copier/" HTTRACK_VERSION);          \
113
0
      cache.zipOutput = NULL;                                                  \
114
0
    }                                                                          \
115
0
    if (cache.zipInput) {                                                      \
116
0
      unzClose(cache.zipInput);                                                \
117
0
      cache.zipInput = NULL;                                                   \
118
0
    }                                                                          \
119
0
    if (cache.lst) {                                                           \
120
0
      fclose(cache.lst);                                                       \
121
0
      cache.lst = opt->state.strc.lst = NULL;                                  \
122
0
    }                                                                          \
123
0
    if (cache.txt) {                                                           \
124
0
      fclose(cache.txt);                                                       \
125
0
      cache.txt = NULL;                                                        \
126
0
    }                                                                          \
127
0
    if (opt->log != NULL)                                                      \
128
0
      fflush(opt->log);                                                        \
129
0
    if (makestat_fp) {                                                         \
130
0
      fclose(makestat_fp);                                                     \
131
0
      makestat_fp = NULL;                                                      \
132
0
    }                                                                          \
133
0
    if (maketrack_fp) {                                                        \
134
0
      fclose(maketrack_fp);                                                    \
135
0
      maketrack_fp = NULL;                                                     \
136
0
    }                                                                          \
137
0
    if (opt->accept_cookie && strnotempty(StringBuff(opt->cookies_file))) {    \
138
0
      if (cookies_file_refused > 0)                                            \
139
0
        hts_log_print(opt, LOG_WARNING,                                        \
140
0
                      "Cookies: %s is left unchanged, because %d of its "      \
141
0
                      "lines would be lost",                                   \
142
0
                      StringBuff(opt->cookies_file), cookies_file_refused);    \
143
0
      else if (cookies_file_refused != COOKIE_LOAD_KEEP) /* it said why */     \
144
0
        cookie_save_replacing(opt, opt->cookie,                                \
145
0
                              StringBuff(opt->cookies_file));                  \
146
0
    } else if (opt->accept_cookie && cookies_file_refused != COOKIE_LOAD_KEEP) \
147
0
      cookie_save(opt, opt->cookie, hts_logpath(opt, "cookies.txt"));          \
148
0
    bauth_free(&cookie);                                                       \
149
0
    if (makeindex_fp) {                                                        \
150
0
      fclose(makeindex_fp);                                                    \
151
0
      makeindex_fp = NULL;                                                     \
152
0
    }                                                                          \
153
0
    if (cache_hashtable) {                                                     \
154
0
      coucal_delete(&cache_hashtable);                                         \
155
0
    }                                                                          \
156
0
    if (cache_tests) {                                                         \
157
0
      coucal_delete(&cache_tests);                                             \
158
0
    }                                                                          \
159
0
    if (cache_kept) {                                                          \
160
0
      coucal_delete(&cache_kept);                                              \
161
0
    }                                                                          \
162
0
    if (template_header) {                                                     \
163
0
      freet(template_header);                                                  \
164
0
      template_header = NULL;                                                  \
165
0
    }                                                                          \
166
0
    if (template_body) {                                                       \
167
0
      freet(template_body);                                                    \
168
0
      template_body = NULL;                                                    \
169
0
    }                                                                          \
170
0
    if (template_footer) {                                                     \
171
0
      freet(template_footer);                                                  \
172
0
      template_footer = NULL;                                                  \
173
0
    }                                                                          \
174
0
    hash_free(&hash);                                                          \
175
0
    opt->hash = NULL;                                                          \
176
0
  } while (0)
177
0
#define XH_uninit do { XH_extuninit; if (r.adr) { freet(r.adr); r.adr=NULL; } } while(0)
178
179
struct lien_buffers {
180
  /* Main array of pointers. 
181
     This is the real "lien_url **liens" pointer base. */
182
  TypedArray(lien_url*) ptr;
183
  /* Strings and structures both live where their addresses cannot move: the
184
     entries below point into them. */
185
  hts_arena strings;
186
  hts_arena liens;
187
};
188
189
// duplicate a string, or return NULL upon error (out-of-memory)
190
0
static char *hts_record_link_strdup_(httrackp *opt, const char *s) {
191
0
  lien_buffers *const liensbuf = opt->liensbuf;
192
0
  char *s_dup;
193
194
0
  assertf(liensbuf != NULL);
195
0
  s_dup = hts_arena_strdup(&liensbuf->strings, s);
196
0
  return s_dup;
197
0
}
198
199
0
static char* hts_record_link_strdup(httrackp *opt, const char *s) {
200
0
  assertf(opt != NULL);
201
0
  assertf(s != NULL);
202
0
  return hts_record_link_strdup_(opt, s);
203
0
}
204
205
/* Index of the most recently recorded link. */
206
0
static size_t hts_record_link_latest(httrackp *opt) {
207
0
  lien_buffers *const liensbuf = opt->liensbuf;
208
209
0
  assertf(TypedArraySize(liensbuf->ptr) != 0);
210
0
  return TypedArraySize(liensbuf->ptr) - 1;
211
0
}
212
213
// returns a new zeroed lien_url entry, 
214
// or (size_t) -1 upon error (out-of-memory)
215
// the returned index is the osset within opt->liens[]
216
0
static size_t hts_record_link_alloc(httrackp *opt) {
217
0
  lien_buffers *const liensbuf = opt->liensbuf;
218
0
  lien_url *link;
219
220
0
  assertf(opt != NULL);
221
0
  assertf(liensbuf != NULL);
222
223
  // Limit the number of links
224
0
  if (opt->maxlink > 0 &&
225
0
      TypedArraySize(liensbuf->ptr) >= (size_t) opt->maxlink) {
226
0
    return (size_t) -1;
227
0
  }
228
229
  // The entries are pointed at from elsewhere, so they must keep their address
230
0
  link = (lien_url *) hts_arena_alloc(&liensbuf->liens, sizeof(*link));
231
0
  if (link == NULL) {
232
0
    return (size_t) -1;
233
0
  }
234
0
  memset(link, 0, sizeof(*link));
235
236
  // Add new lien_url pointer to the array of links, plus the guard NULL
237
0
  if (!TypedArrayReserve(liensbuf->ptr, 2)) {
238
0
    return (size_t) -1;
239
0
  }
240
0
  TypedArrayAdd(liensbuf->ptr, link);
241
0
  TypedArrayTail(liensbuf->ptr) = NULL;
242
243
  // Update pointer as it may have changed,
244
  // and update heap top index
245
0
  opt->liens = TypedArrayElts(liensbuf->ptr);
246
0
  assertf(TypedArraySize(liensbuf->ptr) != 0);
247
0
  assertf(TypedArraySize(liensbuf->ptr) < ( (unsigned int) -1 ) / 2);
248
0
  opt->lien_tot = (int) TypedArraySize(liensbuf->ptr);
249
250
  // return tail
251
0
  return hts_record_link_latest(opt);
252
0
}
253
254
/* Undo hts_record_link_alloc(), so no half-built entry stays in the table. */
255
0
static void hts_record_link_drop_latest(httrackp *opt) {
256
0
  lien_buffers *const liensbuf = opt->liensbuf;
257
258
0
  assertf(TypedArraySize(liensbuf->ptr) != 0);
259
0
  TypedArraySize(liensbuf->ptr)--;
260
0
  TypedArrayElts(liensbuf->ptr)[TypedArraySize(liensbuf->ptr)] = NULL;
261
0
  opt->lien_tot = (int) TypedArraySize(liensbuf->ptr);
262
0
}
263
264
0
hts_boolean hts_record_init(httrackp *opt) {
265
0
  if (opt->liensbuf == NULL) {
266
0
    opt->liensbuf = calloct(sizeof(*opt->liensbuf), 1);
267
0
  }
268
0
  return opt->liensbuf != NULL;
269
0
}
270
271
// wipe records
272
0
void hts_record_free(httrackp *opt) {
273
0
  lien_buffers *const liensbuf = opt->liensbuf;
274
275
0
  if (liensbuf != NULL) {
276
0
    TypedArrayFree(liensbuf->ptr);
277
278
0
    hts_arena_free(&liensbuf->strings);
279
0
    hts_arena_free(&liensbuf->liens);
280
281
0
    freet(opt->liensbuf);
282
0
    opt->liensbuf = NULL;
283
0
  }
284
285
0
  opt->liens = NULL;  // no longer defined
286
0
}
287
288
static hts_boolean hts_record_link_(httrackp *opt, const char *address,
289
                                    const char *file, const char *save,
290
                                    const char *ref_address,
291
                                    const char *ref_file,
292
0
                                    const char *codebase) {
293
  // create a new entry
294
0
  const size_t lien_tot = hts_record_link_alloc(opt);
295
0
  lien_url*const link = lien_tot != (size_t) -1 ? opt->liens[lien_tot] : NULL;
296
0
  if (link == NULL) {
297
0
    return HTS_FALSE;
298
0
  }
299
  // record string fields
300
0
  if ( (link->adr = hts_record_link_strdup(opt, address)) == NULL
301
0
    || (link->fil = hts_record_link_strdup(opt, file)) == NULL
302
0
    || (link->sav = hts_record_link_strdup(opt, save)) == NULL
303
0
    || (link->former_adr = hts_record_link_strdup(opt, ref_address)) == NULL
304
0
    || (link->former_fil = hts_record_link_strdup(opt, ref_file)) == NULL
305
0
    ) {
306
0
    hts_record_link_drop_latest(opt);
307
0
    return HTS_FALSE;
308
0
  }
309
310
  // record codebase for java classes
311
0
  if (codebase != NULL) {
312
0
    const size_t len = strlen(file);
313
0
    if (len > 6 && strncmp(&file[len - 6], ".class", 6) == 0) {
314
0
      if ((link->cod = hts_record_link_strdup(opt, codebase)) == NULL) {
315
0
        hts_record_link_drop_latest(opt);
316
0
        return HTS_FALSE;
317
0
      }
318
0
    }
319
0
  }
320
321
  // add entry in the hashtables
322
0
  hash_write(opt->hash, lien_tot);
323
324
0
  return HTS_TRUE;
325
0
}
326
327
/* See htscore.h. */
328
0
hts_boolean hts_maxlinks_no_room(const httrackp *opt) {
329
0
  return opt->maxlink > 0 && opt->lien_tot + 2 > opt->maxlink;
330
0
}
331
332
hts_boolean hts_record_link(httrackp *opt, const char *address,
333
                            const char *file, const char *save,
334
                            const char *ref_address, const char *ref_file,
335
0
                            const char *codebase) {
336
0
  hts_boolean success;
337
338
0
  hts_secret_add_login(opt, address);
339
0
  success = hts_record_link_(opt, address, file, save, ref_address, ref_file,
340
0
                             codebase);
341
0
  if (!success && opt->maxlink > 0 && opt->lien_tot >= opt->maxlink) {
342
0
    hts_log_print(opt, LOG_PANIC, "Too many links (links=%ld, limit=%ld)", 
343
0
                  (long int) heap_top_index(), (long int) opt->maxlink);
344
0
    hts_log_print(opt, LOG_INFO,
345
0
      "To avoid that: use #L option for more links (example: -#L1000000, or -#L0 to disable)");
346
0
  } else if (!success) {
347
0
    hts_log_print(opt, LOG_PANIC, "Not enough memory to record a link");
348
0
  }
349
0
  return success;
350
0
}
351
352
0
void hts_link_set_self_parented(httrackp *opt, int depth, int pass2) {
353
0
  lien_url *const link = heap_top();
354
355
0
  link->testmode = 0;
356
0
  link->link_import = 0;
357
0
  link->depth = depth;
358
0
  link->pass2 = pass2;
359
0
  link->retry = opt->retry;
360
0
  link->premier = heap_top_index();
361
0
  link->precedent = heap_top_index();
362
0
}
363
364
0
void hts_invalidate_link(httrackp * opt, int lpos) {
365
  /* devalidate entry  */
366
0
  opt->liens[lpos]->pass2 = -1;
367
0
}
368
369
// Write the makeindex footer (refresh meta when makeindex_links==1), close
370
// the file, then run usercommand.
371
void hts_finish_makeindex(httrackp *opt, int *makeindex_done,
372
                          FILE **makeindex_fp, int makeindex_links,
373
                          const char *makeindex_firstlink,
374
                          const char *template_footer, const char *adr,
375
0
                          const char *fil) {
376
0
  if (!*makeindex_done) {
377
0
    if (*makeindex_fp) {
378
      /* sized off link_escaped below, so a long first link is not clipped */
379
0
      char BIGSTK tempo[HTS_URLMAXSIZE * 2 + 64];
380
0
      if (makeindex_links == 1) {
381
0
        char BIGSTK link_escaped[HTS_URLMAXSIZE * 2];
382
0
        escape_uri_utf(makeindex_firstlink, HTS_SIZED(link_escaped));
383
        /* no redirect beats one pointing at a clipped URL */
384
0
        if (!sprintfbuff(
385
0
                tempo,
386
0
                "<meta HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=%s\">" CRLF,
387
0
                link_escaped)) {
388
0
          hts_log_print(opt, LOG_WARNING,
389
0
                        "index redirect omitted: first link too long (%s)",
390
0
                        makeindex_firstlink);
391
0
          tempo[0] = '\0';
392
0
        }
393
0
      } else
394
0
        tempo[0] = '\0';
395
0
      hts_template_format(*makeindex_fp, template_footer,
396
0
                          "<!-- Mirror and index made by HTTrack Website "
397
0
                          "Copier/" HTTRACK_VERSION " " HTTRACK_AFF_AUTHORS
398
0
                          " -->",
399
0
                          tempo, /* EOF */ NULL);
400
0
      fflush(*makeindex_fp);
401
0
      fclose(*makeindex_fp);
402
0
      *makeindex_fp = NULL;
403
0
      usercommand(
404
0
          opt, 0, NULL,
405
0
          hts_optpath(opt, StringBuff(opt->path_html_utf8), "index.html"), adr,
406
0
          fil);
407
0
    }
408
0
  }
409
0
  *makeindex_done = 1;
410
0
}
411
412
/* Write body to fp, then close it. On failure errno says why. */
413
0
static hts_boolean hts_write_and_close(FILE *fp, hts_span body) {
414
0
  hts_boolean written = hts_fwrite_span(body, fp);
415
0
  int last_errno = written ? 0 : errno;
416
417
  /* a body small enough to sit in stdio's buffer only fails at fclose */
418
0
  if (fclose(fp) != 0) {
419
0
    written = HTS_FALSE;
420
0
    last_errno = errno;
421
0
  }
422
0
  if (!written)
423
0
    errno = last_errno;
424
0
  return written;
425
0
}
426
427
/* Flush the parsed HTML output buffer to disk. */
428
void hts_finish_html_file(httrackp *opt, cache_back *cache, htsblk *r,
429
                          FILE **fp, hts_span html, const char *adr,
430
0
                          const char *fil, const char *save) {
431
0
  file_notify(opt, adr, fil, save, 1, 1, r->notmodified);
432
0
  hts_changes_html(opt, cache, r, adr, fil, save);
433
0
  *fp = filecreate(&opt->state.strc, save);
434
0
  if (*fp) {
435
0
    const hts_boolean written = hts_write_and_close(*fp, html);
436
437
0
    *fp = NULL;
438
0
    if (!written) {
439
0
      const int fcheck = check_fatal_io_errno();
440
441
0
      if (fcheck)
442
0
        hts_store_release_int(&opt->state.exit_xh, -1);
443
0
      if (opt->log) {
444
0
        hts_log_print(opt, LOG_ERROR | LOG_ERRNO,
445
0
                      "Unable to write HTML file %s", save);
446
0
        if (fcheck)
447
0
          hts_log_print(opt, LOG_ERROR, "* * Fatal write error, giving up");
448
0
      }
449
0
    }
450
0
    if (strnotempty(r->lastmodified))
451
0
      hts_stamp_filetime(opt, save, r->lastmodified);
452
0
  } else {
453
0
    int fcheck = check_fatal_io_errno();
454
455
0
    if (fcheck)
456
0
      hts_io_fatal_abort(opt);
457
0
    hts_log_print(opt, LOG_ERROR | LOG_ERRNO, "Unable to save file %s", save);
458
0
    if (fcheck)
459
0
      hts_log_print(opt, LOG_ERROR, "* * Fatal write error, giving up");
460
0
  }
461
0
}
462
463
0
hts_boolean hts_scan_token(char **ptr, char *dest, size_t destsize) {
464
0
  char *a = *ptr;
465
  /* the token's real length, which may exceed the room */
466
0
  const size_t len = strcspn(a, HTS_REALSPACES);
467
0
  hts_boolean fit;
468
469
0
  assertf(destsize != 0);
470
0
  fit = hts_span_copy(hts_span_at(a, len), dest, destsize);
471
0
  a += len;
472
0
  a += strspn(a, HTS_REALSPACES);
473
0
  *ptr = a;
474
0
  return fit;
475
0
}
476
477
/* Read the 16-bit code unit at byte offset 'i' of 'src'. */
478
static unsigned int ucs2_unit(const unsigned char *src, size_t i,
479
0
                              hts_boolean swap) {
480
0
  return swap ? src[i] + (src[i + 1] << 8) : (src[i] << 8) + src[i + 1];
481
0
}
482
483
/* Decode the code point at byte offset *i and step past it. A surrogate that
484
   is not half of a pair, or a dangling last byte, becomes U+FFFD and sets
485
   *lone when the former. */
486
static hts_UCS4 utf16_next(hts_span src, size_t *i, hts_boolean swap,
487
0
                           hts_boolean *lone) {
488
0
  unsigned int hi;
489
490
0
  if (src.len - *i < 2) {
491
0
    *i = src.len;
492
0
    return 0xFFFD;
493
0
  }
494
0
  hi = ucs2_unit((const unsigned char *) src.p, *i, swap);
495
0
  *i += 2;
496
0
  if (hi < 0xD800 || hi > 0xDFFF)
497
0
    return hi;
498
0
  if (hi <= 0xDBFF && src.len - *i >= 2) {
499
0
    const unsigned int lo = ucs2_unit((const unsigned char *) src.p, *i, swap);
500
501
0
    if (lo >= 0xDC00 && lo <= 0xDFFF) {
502
0
      *i += 2;
503
0
      return 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);
504
0
    }
505
0
  }
506
0
  *lone = HTS_TRUE;
507
0
  return 0xFFFD;
508
0
}
509
510
0
hts_boolean hts_utf16_looks_like_text(hts_span src, hts_boolean swap) {
511
0
  size_t suspicious = 0;
512
0
  size_t ascii = 0;
513
0
  size_t i;
514
515
0
  for (i = 0; i < src.len;) {
516
0
    hts_boolean lone = HTS_FALSE;
517
0
    const hts_UCS4 cp = utf16_next(src, &i, swap, &lone);
518
519
    /* Random units land here about 13% of the time, text almost never. */
520
0
    if (lone ||
521
0
        (cp < 0x20 && cp != '\t' && cp != '\n' && cp != '\f' && cp != '\r') ||
522
0
        (cp >= 0xE000 && cp <= 0xF8FF) || cp >= 0xF0000 ||
523
0
        (cp >= 0xFDD0 && cp <= 0xFDEF) || (cp & 0xFFFE) == 0xFFFE)
524
0
      suspicious++;
525
0
    else if (cp >= 0x20 && cp <= 0x7E)
526
0
      ascii++;
527
0
  }
528
0
  return ascii >= 4 && suspicious <= src.len / 200 ? HTS_TRUE : HTS_FALSE;
529
0
}
530
531
hts_boolean hts_utf16_bom_converts(hts_span src, const unsigned int *map,
532
0
                                   hts_boolean *swap) {
533
0
  const unsigned char *const u = (const unsigned char *) src.p;
534
0
  const hts_boolean bom = src.len >= 2 && ((u[0] == 0xff && u[1] == 0xfe) ||
535
0
                                           (u[0] == 0xfe && u[1] == 0xff));
536
537
0
  *swap = bom && u[0] == 0xff ? HTS_TRUE : HTS_FALSE;
538
  /* A NUL-heavy body converts as before, any other must read as text. */
539
0
  return bom && (map[0] > src.len / 10 || hts_utf16_looks_like_text(src, *swap))
540
0
             ? HTS_TRUE
541
0
             : HTS_FALSE;
542
0
}
543
544
0
char *hts_ucs2_to_utf8(hts_span src, hts_boolean swap, size_t *outsize) {
545
  /* Signed and wide, because three bytes per unit overflows a 32-bit size_t. */
546
0
  LLint total = 0;
547
0
  hts_boolean lone = HTS_FALSE;
548
0
  size_t i;
549
0
  size_t offs = 0;
550
0
  char *dest;
551
0
  hts_buf out;
552
553
  /* Sized exactly, because one UTF-16 unit can take three UTF-8 bytes. */
554
0
  for (i = 0; i < src.len;) {
555
0
    char seq[8];
556
557
0
    total +=
558
0
        (LLint) hts_writeUTF8(utf16_next(src, &i, swap, &lone), HTS_BUF(seq));
559
0
  }
560
0
  if (!hts_inmem_size_fits(total + 1)) {
561
0
    return NULL;
562
0
  }
563
0
  dest = (char *) malloct((size_t) total + 1);
564
0
  if (dest == NULL) {
565
0
    return NULL;
566
0
  }
567
0
  out = hts_buf_at(dest, (size_t) total + 1);
568
0
  for (i = 0; i < src.len;) {
569
0
    offs += hts_writeUTF8(utf16_next(src, &i, swap, &lone),
570
0
                          hts_buf_skip(out, offs));
571
0
  }
572
0
  assertf(offs == (size_t) total);
573
0
  dest[offs] = '\0';
574
0
  *outsize = offs;
575
0
  return dest;
576
0
}
577
578
/* does it look like XML ? (SVG et al.) */
579
0
static int look_like_xml(const char *s) {
580
0
  return strncmp(s, "<?xml", 5) == 0
581
0
    || strncmp(s, "<!-- ", 5) == 0
582
0
    || strncmp(s, "<svg ", 5) == 0
583
0
    ;
584
0
}
585
586
/* --max-time counts from this reading. */
587
static hts_mono mirror_start;
588
589
0
void hts_mirror_clock_start(void) {
590
0
  HTS_STAT.stat_timestart = time_local();
591
0
  mirror_start = hts_mono_now();
592
0
}
593
594
0
TStamp hts_mirror_elapsed_ms(void) {
595
0
  return hts_mono_diff_ms(hts_mono_now(), mirror_start);
596
0
}
597
598
/* Seconds since local midnight, or 0 if the local time is unavailable. */
599
0
static TStamp seconds_since_midnight(void) {
600
0
  TStamp tl = 0;
601
0
  struct tm tmv;
602
603
0
  if (hts_localtime(time(NULL), &tmv)) {
604
0
    tl += tmv.tm_sec;
605
0
    tl += tmv.tm_min * 60;
606
0
    tl += tmv.tm_hour * 60 * 60;
607
0
  }
608
0
  return tl;
609
0
}
610
611
/* Start the stat timers of the shell and of the stat/track files. */
612
static void mirror_stat_timers_start(const httrackp *opt,
613
                                     TStamp *last_info_shell,
614
0
                                     TStamp *makestat_time) {
615
0
  if (opt->shell) {
616
0
    *last_info_shell = HTS_STAT.stat_timestart;
617
0
  }
618
0
  if ((opt->makestat) || (opt->maketrack)) {
619
0
    *makestat_time = HTS_STAT.stat_timestart;
620
0
  }
621
0
}
622
623
// Début de httpmirror, robot
624
// url1 peut être multiple
625
/* Write httpmirror()'s verdict to both the caller's out-parameter and the opt,
626
   where hts_mirror_completed() can still read it after the call returns. */
627
static void set_mirror_completed(httrackp *opt, hts_boolean *completed_out,
628
0
                                 hts_boolean completed) {
629
0
  *completed_out = completed;
630
0
  hts_mutexlock(&opt->state.lock);
631
0
  opt->mirror_completed = completed;
632
0
  hts_mutexrelease(&opt->state.lock);
633
0
}
634
635
const char *hts_urllist_load(const char *path, char **buff, size_t *size,
636
0
                             hts_buf errbuf) {
637
0
  const LLint fs = fsize_utf8(path);
638
0
  const char *err = NULL;
639
640
0
  *buff = NULL;
641
0
  *size = 0;
642
0
  if (fs < 0) {
643
    /* fsize() hides the cause; redo stat() for a precise errno (#49) */
644
0
    STRUCT_STAT st;
645
0
    err = STAT(path, &st) != 0 ? hts_strerror(errno, errbuf)
646
0
                               : "not a regular file";
647
0
  } else if ((*size = llint_to_size_t(fs)) == (size_t) -1) {
648
0
    err = "file too large";
649
0
  } else {
650
0
    FILE *fp = FOPEN(path, "rb");
651
652
0
    if (fp == NULL) {
653
0
      err = hts_strerror(errno, errbuf);
654
0
    } else {
655
0
      *buff = malloct(*size + 1);
656
0
      if (*buff == NULL) {
657
0
        err = "out of memory";
658
0
      } else if (!hts_fread_exact(*buff, *size, fp)) {
659
0
        freet(*buff);
660
0
        err = "read error";
661
0
      } else {
662
0
        (*buff)[*size] = '\0';
663
0
      }
664
0
      fclose(fp);
665
0
    }
666
0
  }
667
0
  if (err != NULL)
668
0
    *size = 0;
669
0
  return err;
670
0
}
671
672
hts_urllist_status hts_urllist_next(hts_span buff, size_t *pos,
673
0
                                    char line[HTS_URLLIST_LINE_SIZE]) {
674
0
  int adv;
675
0
  hts_boolean cut;
676
0
  size_t term;
677
678
0
  if (*pos >= buff.len)
679
0
    return HTS_URLLIST_END;
680
0
  cut = binput_line(buff.p + *pos, buff.p + buff.len,
681
0
                    hts_buf_at(line, HTS_URLMAXSIZE + 1), &adv);
682
  /* the byte it stopped on, past any CR it dropped */
683
0
  term = *pos + (size_t) adv - 1;
684
0
  *pos = term + 1;
685
  /* an embedded NUL ends the read too, and half a URL is not one */
686
0
  if (term < buff.len && buff.p[term] == '\0') {
687
0
    *pos += hts_span_find(hts_span_skip(buff, *pos), '\n') + 1;
688
0
    return HTS_URLLIST_NUL;
689
0
  }
690
  /* a clipped URL is a different URL */
691
0
  return cut ? HTS_URLLIST_LONG : HTS_URLLIST_LINE;
692
0
}
693
694
/* Read old.lst's next "[path]" line. Return HTS_FALSE when it is cut,
695
   malformed, absolute, escaping or too long, which filenote() never writes. */
696
static hts_boolean old_lst_entry(httrackp *opt, hts_span lst, size_t *pos,
697
0
                                 hts_buf line, hts_buf file) {
698
0
  const size_t root = StringLength(opt->path_html);
699
0
  int adv;
700
0
  const hts_boolean cut =
701
0
      binput_line(lst.p + *pos, lst.p + lst.len, line, &adv);
702
0
  size_t len;
703
704
0
  if (adv <= 0) { // a line past INT_MAX bytes: stop walking
705
0
    *pos = lst.len;
706
0
    return HTS_FALSE;
707
0
  }
708
0
  *pos += (size_t) adv;
709
0
  len = strlen(line.p);
710
0
  if (cut || len < 3 || line.p[0] != '[' || line.p[len - 1] != ']' ||
711
0
      line.p[1] == '/' || line.p[1] == '\\')
712
0
    return HTS_FALSE;
713
0
  if (root >= file.size || len - 2 >= file.size - root)
714
0
    return HTS_FALSE;
715
0
  memcpy(file.p, StringBuff(opt->path_html), root);
716
0
  memcpy(file.p + root, line.p + 1, len - 2);
717
0
  file.p[root + len - 2] = '\0';
718
  /* a ".." or drive prefix would walk the purge out of the mirror */
719
0
  if (!hts_path_is_relative_contained(file.p + root))
720
0
    return HTS_FALSE;
721
0
  return HTS_TRUE;
722
0
}
723
724
/* Cuts file, of length *len, to its parent directory. Returns HTS_FALSE when
725
   that parent is not strictly inside the first root bytes, path_html. */
726
0
static hts_boolean chop_to_parent(char *file, size_t root, size_t *len) {
727
0
  size_t n = *len;
728
729
0
  while (n > root && file[n - 1] != '/' && file[n - 1] != '\\')
730
0
    n--;
731
0
  while (n > root && (file[n - 1] == '/' || file[n - 1] == '\\'))
732
0
    n--; // a run of separators, as in "a//b", is one
733
0
  if (n <= root)
734
0
    return HTS_FALSE;
735
0
  file[n] = '\0';
736
0
  *len = n;
737
0
  return HTS_TRUE;
738
0
}
739
740
/* Decodes a rule into dest as the parser decodes a crawled link: the part
741
   before any '?', so "%41" and "%20" match the "A" and space a link holds.
742
   Returns HTS_FALSE if it does not fit in dest. */
743
0
static hts_boolean filter_rule_decode_(const char *rule, hts_buf dest) {
744
0
  char BIGSTK path[HTS_FILTER_MAXLEN * 3 + 1], dec[sizeof(path)];
745
0
  const char *const query = rule + strcspn(rule, "?");
746
0
  const size_t plen = (size_t) (query - rule);
747
0
  size_t len;
748
749
0
  if (!hts_buf_put_span(HTS_BUF(path), hts_span_at(rule, plen)))
750
0
    return HTS_FALSE;
751
0
  len = strlen(unescape_http_unharm(dec, sizeof(dec), path, 1 | 2));
752
0
  if (strlen(query) >= dest.size || len >= dest.size - strlen(query))
753
0
    return HTS_FALSE;
754
0
  memcpy(dest.p, dec, len);
755
0
  memcpy(dest.p + len, query, strlen(query) + 1);
756
0
  return HTS_TRUE;
757
0
}
758
759
/* The jar whose records can win over a bundle's: the -%K file, or the
760
   project's cookies.txt. NULL under -b0. */
761
0
static const char *bundle_jar_file(httrackp *opt, char buff[CATBUFF_SIZE]) {
762
0
  if (!opt->accept_cookie)
763
0
    return NULL;
764
0
  if (strnotempty(StringBuff(opt->cookies_file)))
765
0
    return StringBuff(opt->cookies_file);
766
0
  if (!hts_fpath_join(hts_buf_at(buff, CATBUFF_SIZE), StringBuff(opt->path_log),
767
0
                      "cookies.txt"))
768
0
    abortLog("cookie jar path too long");
769
0
  return buff;
770
0
}
771
772
/* Does a start URL lack a scheme? "//host" counts too, so it still becomes
773
   http:////host. */
774
0
static hts_boolean seed_needs_scheme(const char *url) {
775
0
  for (;;) {
776
0
    if (*url == ' ')
777
0
      url++;
778
0
    else if (strncmp(url, "%20", 3) == 0) /* argv spaces arrive escaped */
779
0
      url += 3;
780
0
    else
781
0
      break;
782
0
  }
783
0
  return !link_has_authority(url) || strncmp(url, "//", 2) == 0;
784
0
}
785
786
/* Append one start URL and its newline, defaulting to http://. */
787
0
static void seed_append(htsbuff *primarybuff, const char *url) {
788
0
  if (seed_needs_scheme(url))
789
0
    htsbuff_cat(primarybuff, "http://");
790
0
  htsbuff_cat(primarybuff, url);
791
0
  htsbuff_cat(primarybuff, "\n");
792
0
}
793
794
/* Load the login bundles, and add their url lines to the start URLs in
795
 *primary, which grows. HTS_FALSE after saying why the run must stop. */
796
static hts_boolean bundle_start(httrackp *opt, char **primary,
797
0
                                htsbuff *primarybuff) {
798
0
  char err[1024];
799
0
  char jarbuff[CATBUFF_SIZE];
800
0
  const char *extra;
801
0
  size_t room = 0;
802
0
  size_t i;
803
804
0
  if (!hts_bundle_load_all(opt, bundle_jar_file(opt, jarbuff), HTS_BUF(err))) {
805
0
    hts_log_print(opt, LOG_ERROR, "Login bundle: %s", err);
806
0
    fprintf(stderr, "Login bundle: %s\n", err);
807
0
    return HTS_FALSE;
808
0
  }
809
0
  for (i = 0; (extra = hts_bundle_url(opt, i)) != NULL; i++)
810
0
    room += strlen(extra) + sizeof("http://\n");
811
0
  if (room != 0) {
812
0
    char *const grown =
813
0
        room < (size_t) -1 - primarybuff->cap
814
0
            ? (char *) realloct(*primary, primarybuff->cap + room)
815
0
            : NULL;
816
817
0
    if (grown == NULL) {
818
0
      printf("PANIC! : Not enough memory [%d]\n", __LINE__);
819
0
      return HTS_FALSE;
820
0
    }
821
0
    *primary = primarybuff->buf = grown;
822
0
    primarybuff->cap += room;
823
0
  }
824
0
  for (i = 0; (extra = hts_bundle_url(opt, i)) != NULL; i++) {
825
0
    seed_append(primarybuff, extra);
826
0
  }
827
0
  return HTS_TRUE;
828
0
}
829
830
/* Copy the mirror-wide fields of base, then set the per-link ones. */
831
static void mirror_module_str(htsmoduleStruct *str, const htsmoduleStruct *base,
832
0
                              char *err_msg, int numero_passe, htsblk *r) {
833
0
  const lien_url *const link = base->opt->liens[*base->ptr_];
834
835
0
  *str = *base;
836
0
  err_msg[0] = '\0';
837
0
  str->err_msg = err_msg;
838
0
  str->filename = link->sav;
839
0
  str->mime = r->contenttype;
840
0
  str->url_host = link->adr;
841
0
  str->url_file = link->fil;
842
0
  str->size = (int) r->size;
843
0
  str->numero_passe = numero_passe;
844
0
}
845
846
/* Copy the mirror-wide fields of base, then set the per-link ones. */
847
static void mirror_module_stre(htsmoduleStructExtended *stre,
848
                               const htsmoduleStructExtended *base, htsblk *r,
849
0
                               int *error, int *store_errpage) {
850
0
  *stre = *base;
851
0
  stre->r_ = r;
852
0
  stre->error_ = error;
853
0
  stre->store_errpage_ = store_errpage;
854
0
}
855
856
/* Load a body that was saved straight to disk, so it can be parsed.
857
   Returns HTS_TRUE when r holds the file. */
858
static hts_boolean load_body_from_disk(httrackp *opt, int ptr, htsblk *r,
859
0
                                       int store_errpage) {
860
0
  if (!may_be_hypertext_mime(opt, r->contenttype, urlfil()) ||
861
0
      heap(ptr)->depth <= 0 || r->adr != NULL || r->size <= 0 ||
862
0
      store_errpage || savename()[0] == '\0') {
863
0
    return HTS_FALSE;
864
0
  }
865
0
  r->adr = readfile2_inmem(savename(), &r->size);
866
0
  if (r->adr != NULL) {
867
0
    hts_log_print(opt, LOG_INFO,
868
0
                  "File successfully loaded for parsing: %s%s (%d bytes)",
869
0
                  adr_nologin(opt, urladr()), urlfil(), (int) r->size);
870
0
  } else {
871
0
    hts_log_print(opt, LOG_ERROR, "File could not be loaded for parsing: %s%s",
872
0
                  adr_nologin(opt, urladr()), urlfil());
873
0
  }
874
0
  return r->adr != NULL;
875
0
}
876
877
/* Store the filter rules of the start list url1 and append its URLs to
878
   primarybuff. HTS_FALSE when memory runs out. */
879
static hts_boolean seed_parse_args(httrackp *opt, char *url1,
880
0
                                   htsbuff *primarybuff, int *filptr) {
881
0
  char *a = url1;
882
883
0
  while (*a) {
884
0
    int joker = 0;
885
886
    // only a leading + or - makes a token a filter rule; anything else is a
887
    // URL
888
0
    if (*a == '+')
889
0
      joker = 1;
890
0
    else if (*a == '-')
891
0
      joker = 1;
892
893
0
    if (joker) { // a filter rule
894
      /* sized off the rule cap, as the array and matcher are (#1288) */
895
0
      char BIGSTK tempo[HTS_FILTER_MAXLEN + 1];
896
0
      char BIGSTK raw[HTS_FILTER_MAXLEN * 3 + 1];
897
0
      int type;
898
0
      int plus = 0;
899
900
0
      if (*a == '+') { // the accept field
901
0
        type = 1;
902
0
        plus = 1;
903
0
        a++;
904
0
      } else if (*a == '-') { // the forbidden[] field
905
0
        type = 0;
906
0
        a++;
907
0
      } else { // dead: joker is set only for '+' or '-'
908
0
        type = 1;
909
0
      }
910
911
      /* one under the cap: the sign is prepended into `rule` below, and the
912
         spare byte is the dead branch's trailing '*' */
913
0
      if (!hts_scan_token(&a, raw, sizeof(raw)) ||
914
0
          !filter_rule_decode_(raw, HTS_BUF_N(tempo, sizeof(tempo) - 1))) {
915
        /* on the console too: the user who typed it may have no log open */
916
0
        printf("Filter rule longer than %d bytes, ignored: %c%.64s...\n",
917
0
               (int) HTS_FILTER_MAXLEN, type ? '+' : '-', raw);
918
0
        hts_log_print(opt, LOG_WARNING,
919
0
                      "Filter rule longer than %d bytes, ignored: %c%.64s...",
920
0
                      (int) HTS_FILTER_MAXLEN, type ? '+' : '-', raw);
921
0
        continue;
922
0
      }
923
924
      // skip a sign with nothing after it
925
0
      if (strnotempty(tempo)) {
926
0
        if ((plus == 0) && (type == 1)) {
927
0
          if (hts_lastchar(tempo) != '*') {
928
0
            strcatbuff(tempo, "*");
929
0
          }
930
0
        }
931
0
        {
932
          /* the sign, whatever tempo holds, and the NUL */
933
0
          char BIGSTK rule[sizeof(tempo) + 1];
934
0
          htsbuff fb = htsbuff_array(rule);
935
936
0
          htsbuff_cpy(&fb, type ? "+" : "-");
937
0
          htsbuff_cat(&fb, tempo);
938
          /* bumps filptr when stored, and logs a drop */
939
0
          (void) !filters_insert(opt, *filptr, rule);
940
0
        }
941
942
0
        if (!filters_grow(opt, 1)) {
943
0
          return HTS_FALSE;
944
0
        }
945
0
      }
946
947
0
    } else { // a plain URL
948
0
      char BIGSTK url[HTS_URLMAXSIZE * 2];
949
950
0
      if (!hts_scan_token(&a, url, sizeof(url))) {
951
0
        printf("URL longer than %d bytes, ignored: %.64s...\n",
952
0
               (int) (sizeof(url) - 1), url_nologin(opt, url));
953
0
        hts_log_print(opt, LOG_WARNING,
954
0
                      "URL longer than %d bytes, ignored: %.64s...",
955
0
                      (int) (sizeof(url) - 1), url_nologin(opt, url));
956
0
        continue;
957
0
      }
958
959
0
      seed_append(primarybuff, url);
960
0
    }
961
0
  }
962
0
  return HTS_TRUE;
963
0
}
964
965
/* --why: print which filter rule decides for the URL. */
966
0
static void mirror_why(httrackp *opt, char **filters, int filptr) {
967
0
  char BIGSTK url[HTS_URLMAXSIZE * 2];
968
0
  lien_adrfil af;
969
970
0
  char BIGSTK typed[HTS_URLMAXSIZE * 2];
971
972
0
  if (seed_needs_scheme(StringBuff(opt->why_url)))
973
0
    snprintf(typed, sizeof(typed), "http://%s", StringBuff(opt->why_url));
974
0
  else
975
0
    snprintf(typed, sizeof(typed), "%s", StringBuff(opt->why_url));
976
  // a typed login reads up to the last '@' before the first '/'
977
0
  if (!hts_escape_typed_login(typed, HTS_BUF(url)))
978
0
    strcpybuff(url, typed);
979
0
  if (ident_url_absolute(url, &af) < 0) {
980
0
    printf("--why: unable to parse URL %s" LF,
981
0
           adr_nologin(opt, StringBuff(opt->why_url)));
982
0
  } else {
983
0
    char *const query = af.fil + strcspn(af.fil, "?");
984
0
    char BIGSTK path[sizeof(af.fil)];
985
0
    int jokDepth = 0;
986
987
    /* decode the path as the parser decodes a crawled link */
988
0
    const char c = *query;
989
0
    *query = '\0';
990
0
    unescape_http_unharm(path, sizeof(path), af.fil, 1 | 2);
991
0
    *query = c;
992
0
    strcatbuff(path, query);
993
0
    strcpybuff(af.fil, path);
994
0
    const int jok =
995
0
        filters_match_url(filters, filptr, af.adr, af.fil, &jokDepth);
996
997
0
    if (jok > 0)
998
0
      printf("%s: accepted by rule #%d (%s)" LF, url_nologin(opt, url),
999
0
             jokDepth + 1, filters[jokDepth]);
1000
0
    else if (jok < 0)
1001
0
      printf("%s: rejected by rule #%d (%s)" LF, url_nologin(opt, url),
1002
0
             jokDepth + 1, filters[jokDepth]);
1003
0
    else
1004
0
      printf("%s: no filter rule matches; the wizard decides "
1005
0
             "(same-site links are followed by default)" LF,
1006
0
             url_nologin(opt, url));
1007
0
  }
1008
0
}
1009
1010
/* Append the URLs of the -%L list to primarybuff. HTS_FALSE when a line named
1011
   a login bundle that was refused. */
1012
0
static hts_boolean seed_append_filelist(httrackp *opt, htsbuff *primarybuff) {
1013
0
  hts_boolean bundles_ok = HTS_TRUE;
1014
0
  char *filelist_buff = NULL;
1015
0
  size_t filelist_sz = 0;
1016
0
  char filelist_errbuf[HTS_STRERROR_SIZE];
1017
0
  const char *const filelist_err =
1018
0
      hts_urllist_load(StringBuff(opt->filelist), &filelist_buff, &filelist_sz,
1019
0
                       HTS_BUF(filelist_errbuf));
1020
1021
0
  if (filelist_buff != NULL) {
1022
0
    size_t filelist_ptr = 0;
1023
0
    int n = 0;
1024
0
    int lineno = 0;
1025
0
    char BIGSTK line[HTS_URLLIST_LINE_SIZE];
1026
0
    const char *bundle_why;
1027
0
    hts_urllist_status status;
1028
0
    const hts_span list = hts_span_at(filelist_buff, filelist_sz);
1029
1030
0
    while ((status = hts_urllist_next(list, &filelist_ptr, line)) !=
1031
0
           HTS_URLLIST_END) {
1032
0
      lineno++;
1033
0
      if (status == HTS_URLLIST_NUL) {
1034
0
        hts_log_print(opt, LOG_WARNING,
1035
0
                      "\"%s\", line %d: URL contains a NUL byte, ignored",
1036
0
                      StringBuff(opt->filelist), lineno);
1037
0
        continue;
1038
0
      }
1039
0
      if (status == HTS_URLLIST_LONG) {
1040
0
        hts_log_print(opt, LOG_WARNING,
1041
0
                      "\"%s\", line %d: URL longer than %d bytes, ignored",
1042
0
                      StringBuff(opt->filelist), lineno, HTS_URLMAXSIZE);
1043
0
        continue;
1044
0
      }
1045
0
      if (hts_is_quoted(hts_span_of(line))) {
1046
0
        hts_log_print(
1047
0
            opt, LOG_ERROR, "\"%s\", line %d: \"%s is quoted, ignored",
1048
0
            StringBuff(opt->filelist), lineno, adr_nologin(opt, line + 1));
1049
0
        continue;
1050
0
      }
1051
0
      bundle_why = hts_bundle_take(opt, line);
1052
0
      if (bundle_why != NULL) {
1053
0
        hts_log_print(opt, LOG_ERROR, "\"%s\", line %d: %s",
1054
0
                      StringBuff(opt->filelist), lineno, bundle_why);
1055
0
        fprintf(stderr, "\"%s\", line %d: %s\n", StringBuff(opt->filelist),
1056
0
                lineno, bundle_why);
1057
0
        bundles_ok = HTS_FALSE;
1058
0
        continue;
1059
0
      }
1060
0
      if (line[0]) {
1061
0
        char BIGSTK typed[HTS_URLLIST_LINE_SIZE * 3];
1062
1063
        // sized so the escape cannot clip
1064
0
        (void) hts_escape_typed_login(line, HTS_BUF(typed));
1065
0
        n++;
1066
0
        seed_append(primarybuff, typed);
1067
0
      }
1068
0
    }
1069
0
    hts_log_print(opt, LOG_NOTICE, "%d links added from %s", n,
1070
0
                  StringBuff(opt->filelist));
1071
1072
    // Free buffer
1073
0
    freet(filelist_buff);
1074
0
  } else {
1075
0
    hts_log_print(opt, LOG_ERROR, "Could not include URL list \"%s\": %s",
1076
0
                  StringBuff(opt->filelist), filelist_err);
1077
0
  }
1078
0
  return bundles_ok;
1079
0
}
1080
1081
/* Queue the --sitemap probe for the first start URL in primary. */
1082
0
static void seed_sitemap(httrackp *opt, const char *primary) {
1083
0
  char BIGSTK first[HTS_URLMAXSIZE * 2];
1084
0
  const char *const eol = strchr(primary, '\n');
1085
0
  const size_t len = eol != NULL ? (size_t) (eol - primary) : 0;
1086
1087
0
  const char *const seed =
1088
0
      hts_buf_put_span(HTS_BUF(first), hts_span_at(primary, len)) ? first : "";
1089
1090
0
  hts_sitemap_seed(opt, seed);
1091
0
}
1092
1093
/* Wait for the -GN start time, then restart the mirror clocks. */
1094
static void mirror_wait_start_time(httrackp *opt, struct_back *sback,
1095
                                   TStamp *last_info_shell,
1096
0
                                   TStamp *makestat_time) {
1097
0
  int rollover = 0;
1098
0
  int ok = 0;
1099
1100
0
  if (seconds_since_midnight() > opt->waittime) // wait for midnight first
1101
0
    rollover = 1;
1102
1103
0
  opt->state._hts_in_html_parsing = 5;
1104
0
  do {
1105
0
    const TStamp tl = seconds_since_midnight();
1106
1107
0
    if (rollover) {
1108
0
      if (tl <= opt->waittime)
1109
0
        rollover = 0;
1110
0
    } else {
1111
0
      if (tl > opt->waittime)
1112
0
        ok = 1; // ok!
1113
0
    }
1114
1115
0
    {
1116
0
      int r;
1117
1118
0
      const int wait = (int) (opt->waittime - tl + (rollover ? 24 * 3600 : 0));
1119
1120
0
      r = RUN_CALLBACK7(opt, loop, sback->lnk, sback->count, 0, 0,
1121
0
                        opt->lien_tot, wait, NULL);
1122
0
      if (!r) {
1123
0
        hts_store_release_int(&opt->state.exit_xh, 1); // exit requested
1124
0
        ok = 1;
1125
0
      } else
1126
0
        Sleep(100);
1127
0
    }
1128
1129
0
  } while (!ok);
1130
0
  opt->state._hts_in_html_parsing = 0;
1131
1132
0
  hts_mirror_clock_start();
1133
0
  mirror_stat_timers_start(opt, last_info_shell, makestat_time);
1134
0
}
1135
1136
/* Reset r for the next link, with the request settings of opt. */
1137
0
static void mirror_request_init(httrackp *opt, htsblk *r, char *loc) {
1138
0
  hts_init_htsblk(r);
1139
0
  r->location = loc; // for a 3xx
1140
  // copy the proxy settings
1141
0
  if ((r->req.proxy.active = opt->proxy.active)) {
1142
0
    if (StringBuff(opt->proxy.bindhost) != NULL)
1143
0
      r->req.proxy.bindhost = StringBuff(opt->proxy.bindhost);
1144
0
    if (StringBuff(opt->proxy.name) != NULL)
1145
0
      r->req.proxy.name = StringBuff(opt->proxy.name);
1146
0
    r->req.proxy.port = opt->proxy.port;
1147
0
  }
1148
0
  r->req.user_agent = StringBuff(opt->user_agent);
1149
0
  r->req.referer = StringBuff(opt->referer);
1150
0
  r->req.from = StringBuff(opt->from);
1151
0
  r->req.lang_iso = StringBuff(opt->lang_iso);
1152
0
  r->req.accept = StringBuff(opt->accept);
1153
0
  r->req.headers = StringBuff(opt->headers);
1154
0
  r->req.user_agent_send = opt->user_agent_send;
1155
0
}
1156
1157
/* Skip the cancelled links, and those done in the background, from ptr on.
1158
   Returns the first link left to fetch, or lien_tot. */
1159
0
static int mirror_skip_ready(httrackp *opt, int ptr) {
1160
0
  while (ptr < opt->lien_tot && (heap(ptr)) &&
1161
0
         ((((urladr() != NULL) ? (urladr()) : (" "))[0] == '!') ||
1162
0
          (((urlfil() != NULL) ? (urlfil()) : (" "))[0] == '\0') ||
1163
0
          ((heap(ptr)->pass2 == -1)))) { // cancelled, or empty path
1164
0
    if (heap(ptr) != NULL && heap(ptr)->pass2 == -1) {
1165
0
      hts_log_print(opt, LOG_DEBUG, "link #%d is ready, skipping: %s%s..", ptr,
1166
0
                    ((urladr() != NULL) ? adr_nologin(opt, urladr()) : (" ")),
1167
0
                    ((urlfil() != NULL) ? (urlfil()) : (" ")));
1168
0
    } else {
1169
0
      hts_log_print(opt, LOG_DEBUG, "link #%d seems ready, skipping: %s%s..",
1170
0
                    ptr,
1171
0
                    ((urladr() != NULL) ? adr_nologin(opt, urladr()) : (" ")),
1172
0
                    ((urlfil() != NULL) ? (urlfil()) : (" ")));
1173
0
    }
1174
    // remove from stats
1175
0
    if (heap(ptr)->pass2 == -1) {
1176
0
      HTS_STAT.stat_background--;
1177
0
    }
1178
0
    ptr++;
1179
0
  }
1180
0
  return ptr;
1181
0
}
1182
1183
/* Retype a body whose MIME type lies, such as text/html served with a
1184
   Content-Disposition naming foo.jpg. HTS_TRUE for a bogus SVG, which is
1185
   binary. */
1186
0
static hts_boolean fix_bogus_mime(httrackp *opt, int ptr, htsblk *r) {
1187
0
  if (r->statuscode == HTTP_OK) { // OK, or a 304 in the background
1188
0
    if (r->adr) {                 // Written file
1189
      // Buggy SVG (Smiling Spectre)
1190
0
      if (strcmp(r->contenttype, "image/svg+xml") == 0 &&
1191
0
          !look_like_xml(r->adr)) {
1192
        // patch it
1193
0
        strcpybuff(r->contenttype, "application/octet-stream");
1194
0
        return HTS_TRUE;
1195
0
      } else if ((is_hypertext_mime(opt, r->contenttype, urlfil()))
1196
                 /* Is HTML or Js, .. */
1197
                 /* NO - real media is real media, not HTML */
1198
                 /*|| (may_be_hypertext_mime(r->contenttype, urlfil()) &&
1199
                    (r->adr) ) */
1200
                 /* Is real media, .. */
1201
0
      ) {
1202
0
        if (strnotempty(r->cdispo)) {         // Content-disposition set!
1203
0
          if (ishtml(opt, savename()) == 0) { // not HTML
1204
            // patch it!
1205
0
            strcpybuff(r->contenttype, "application/octet-stream");
1206
0
          }
1207
0
        }
1208
0
      }
1209
0
    }
1210
0
  }
1211
0
  return HTS_FALSE;
1212
0
}
1213
1214
/* Normalize the bytes of a hypertext body: convert UTF-16 to UTF-8, retype a
1215
   binary one, and blank the NULs the parser cannot handle. Returns is_binary,
1216
   or HTS_TRUE when the body turns out binary. */
1217
static hts_boolean normalize_body_chars(httrackp *opt, int ptr, htsblk *r,
1218
0
                                        hts_boolean is_binary, int *error) {
1219
0
  if (HTTP_IS_OK(r->statuscode) &&
1220
0
      (is_hypertext_mime(opt, r->contenttype, urlfil()) /* Is HTML or Js, .. */
1221
0
       || may_be_hypertext_mime(opt, r->contenttype,
1222
0
                                urlfil())) /* Is real media, .. */
1223
0
  ) {
1224
1225
    /* Convert charset to UTF-8 - NOT! (what about links ? remote server
1226
     * side will have troubles with converted names) */
1227
1228
    /* Check bogus chars */
1229
0
    if ((r->adr) && (r->size)) {
1230
0
      unsigned int map[256];
1231
0
      int i;
1232
1233
0
      map_characters(hts_blk_body(r), &map[0]);
1234
0
      hts_boolean ucs2_swap;
1235
1236
0
      if (hts_utf16_bom_converts(hts_blk_body(r), map, &ucs2_swap)) {
1237
0
        size_t new_size = 0;
1238
0
        char *const new_adr =
1239
0
            hts_ucs2_to_utf8(hts_blk_body(r), ucs2_swap, &new_size);
1240
1241
0
        if (new_adr == NULL) {
1242
          /* Fail only the page, as http_xfread1() does on this NULL. */
1243
0
          hts_log_print(
1244
0
              opt, LOG_ERROR,
1245
0
              "Not enough memory to convert %s%s from UTF-16 to UTF-8",
1246
0
              adr_nologin(opt, urladr()), urlfil());
1247
0
          r->statuscode = STATUSCODE_INVALID;
1248
0
          strcpybuff(r->msg, "Not enough memory");
1249
0
          *error = 1;
1250
0
        } else {
1251
0
          hts_log_print(opt, LOG_WARNING,
1252
0
                        "File %s%s converted from UTF-16 to UTF-8 (old "
1253
0
                        "size: %d bytes, new size: %d bytes)",
1254
0
                        adr_nologin(opt, urladr()), urlfil(), (int) r->size,
1255
0
                        (int) new_size);
1256
0
          freet(r->adr);
1257
0
          r->adr = new_adr;
1258
0
          r->size = (LLint) new_size;
1259
0
        }
1260
        /* NULs also count with no server type, or the blanking below
1261
           corrupts an untyped binary (#1415). */
1262
0
      } else if (map_looks_binary(map, (size_t) r->size) ||
1263
0
                 ((map[0] > r->size / 100) && (map[0] > 10) &&
1264
0
                  hts_streq_ci(r->contenttype, HTS_UNKNOWN_MIME))) {
1265
0
        is_binary = HTS_TRUE;
1266
0
        strcpybuff(r->contenttype, "application/octet-stream");
1267
0
        hts_log_print(opt, LOG_WARNING,
1268
0
                      "File not parsed, looks like binary: %s%s",
1269
0
                      adr_nologin(opt, urladr()), urlfil());
1270
0
      }
1271
1272
      /* This hack allows you to avoid problems with parsing '\0' characters  */
1273
0
      if (!is_binary && !*error) {
1274
0
        for (i = 0; i < r->size; i++) {
1275
0
          if (r->adr[i] == '\0')
1276
0
            r->adr[i] = ' ';
1277
0
        }
1278
0
      }
1279
0
    }
1280
0
  }
1281
0
  return is_binary;
1282
0
}
1283
1284
/* Seed a sitemap's <loc> URLs at top level with a full depth budget. */
1285
static void mirror_sitemap_ingest(httrackp *opt, int ptr,
1286
                                  const htsmoduleStruct *str_base,
1287
0
                                  int numero_passe, htsblk *r) {
1288
0
  htsmoduleStruct BIGSTK smstr;
1289
0
  int smptr = ptr;
1290
1291
0
  smstr = *str_base;
1292
0
  smstr.numero_passe = numero_passe;
1293
0
  smstr.ptr_ = &smptr; /* scratch: the ingester retargets the wizard */
1294
0
  smstr.url_host = urladr();
1295
0
  smstr.url_file = urlfil();
1296
0
  smstr.mime = r->contenttype;
1297
0
  hts_sitemap_ingest(opt, &smstr, urladr(), urlfil(), hts_blk_body(r));
1298
0
}
1299
1300
/* An asset URL on a foreign host that answers an HTML page gets no depth:
1301
   its links are same-host, and would mirror that whole site (#121). */
1302
static void drop_foreign_asset_depth(httrackp *opt, int ptr, const htsblk *r,
1303
0
                                     hts_boolean is_binary) {
1304
0
  if (!is_binary && heap(ptr)->depth > 0 && is_html_mime_type(r->contenttype) &&
1305
0
      hts_link_is_foreign_asset(opt, ptr)) {
1306
0
    hts_log_print(opt, LOG_INFO,
1307
0
                  "Note: not scanning %s%s, an HTML page on a host foreign "
1308
0
                  "to %s; mirror it by adding it as a starting URL",
1309
                  /* normalized: a page-supplied link can carry credentials */
1310
0
                  jump_identification_const(urladr()), urlfil(),
1311
0
                  jump_identification_const(heap(heap(ptr)->precedent)->adr));
1312
0
    heap(ptr)->depth = 0;
1313
0
  }
1314
0
}
1315
1316
/* Should the body in r be parsed for links? */
1317
static hts_boolean mirror_should_parse(httrackp *opt, int ptr, const htsblk *r,
1318
                                       hts_boolean is_binary,
1319
0
                                       int store_errpage) {
1320
0
  return !is_binary &&
1321
0
         ((is_hypertext_mime(opt, r->contenttype,
1322
0
                             urlfil())) /* Is HTML or Js, .. */
1323
0
          || (may_be_hypertext_mime(opt, r->contenttype, urlfil()) &&
1324
0
              r->adr != NULL) /* Is real media, .. */
1325
0
          ) &&
1326
0
         (heap(ptr)->depth > 0)      /* Depth > 0 (recurse depth) */
1327
0
         && (r->adr != NULL)         /* HTML Data exists */
1328
0
         && (r->size > 0)            /* And not empty */
1329
0
         && (!store_errpage)         /* Not an html error page */
1330
0
         && (savename()[0] != '\0'); /* Output filename exists */
1331
0
}
1332
1333
/* With -%T, store the page charset in page_charset: the HTTP one, else the
1334
   meta one, else empty. */
1335
static void detect_page_charset(httrackp *opt, int ptr, const htsblk *r,
1336
0
                                hts_buf page_charset) {
1337
0
  page_charset.p[0] = '\0';
1338
0
  if (opt->convert_utf8) {
1339
    /* HTTP charset is prioritary over meta; one too long stays unset */
1340
0
    if (r->charset[0] != '\0') {
1341
0
      (void) !hts_buf_try_cpy(page_charset, r->charset);
1342
0
    }
1343
    /* Attempt to find a meta charset */
1344
0
    else if (is_html_mime_type(r->contenttype)) {
1345
0
      char *charset = hts_getCharsetFromMeta(hts_blk_body(r));
1346
1347
0
      if (charset != NULL) {
1348
0
        (void) !hts_buf_try_cpy(page_charset, charset);
1349
0
      }
1350
0
      freet(charset);
1351
0
    }
1352
    /* Left empty when the document declared none: guessing UTF-8 here
1353
       would break links, and the parser picks its own fallback */
1354
0
    if (page_charset.p[0] == '\0') {
1355
0
      hts_log_print(opt, LOG_INFO,
1356
0
                    "Warning: could not detect encoding for: %s%s",
1357
0
                    adr_nologin(opt, urladr()), urlfil());
1358
0
    }
1359
0
  }
1360
0
}
1361
1362
/* Read the rules of a fetched robots.txt, and pass on its sitemaps. */
1363
static void mirror_robots_txt(httrackp *opt, int ptr, robots_wizard *robots,
1364
0
                              const htsblk *r) {
1365
0
  char BIGSTK sitemaps[8192];
1366
1367
0
  sitemaps[0] = '\0';
1368
0
  if (r->adr) {
1369
0
    char BIGSTK infobuff[8192];
1370
#ifdef IGNORE_RESTRICTIVE_ROBOTS
1371
    hts_boolean keep_root =
1372
        (opt->robots >= HTS_ROBOTS_ALWAYS_STRICT) ? HTS_TRUE : HTS_FALSE;
1373
#else
1374
0
    hts_boolean keep_root = HTS_TRUE;
1375
0
#endif
1376
1377
0
    robots_parse(opt, robots, urladr(), hts_blk_body(r), HTS_BUF(infobuff),
1378
0
                 keep_root, HTS_BUF(sitemaps));
1379
0
    if (strnotempty(infobuff)) {
1380
0
      hts_log_print(opt, LOG_INFO,
1381
0
                    "Note: robots.txt forbidden links for %s are: %s",
1382
0
                    adr_nologin(opt, urladr()), infobuff);
1383
0
      hts_log_print(opt, LOG_NOTICE,
1384
0
                    "Note: due to %s remote robots.txt rules, links "
1385
0
                    "beginning with these path will be forbidden: %s "
1386
0
                    "(see in the options to disable this)",
1387
0
                    adr_nologin(opt, urladr()), infobuff);
1388
0
    }
1389
0
  }
1390
  /* robots_parse ran, so this body's rules gate the sitemap fetch.
1391
     A failed probe still falls back to the well-known location. */
1392
0
  hts_sitemap_robots(opt, urladr(), sitemaps);
1393
0
}
1394
1395
/* Write a readme beside an HTML page stored without being scanned. */
1396
0
static void write_unscanned_readme(httrackp *opt, int ptr, const htsblk *r) {
1397
0
  char BIGSTK tempo[HTS_URLMAXSIZE * 2];
1398
0
  FILE *fp;
1399
1400
0
  tempo[0] = '\0';
1401
0
  strcpybuff(tempo, savename());
1402
0
  strcatbuff(tempo, ".readme");
1403
1404
  /* filecreate() makes the directory, as the page is not saved yet */
1405
0
  if ((fp = filecreate(NULL, tempo)) != NULL) {
1406
0
    fprintf(fp,
1407
0
            "Info-file generated by HTTrack Website Copier " HTTRACK_VERSION
1408
0
            "%s" CRLF "" CRLF,
1409
0
            hts_get_version_info(opt));
1410
0
    fprintf(fp, "The file %s has not been scanned by HTS" CRLF, savename());
1411
0
    fprintf(fp, "Some links contained in it may be unreachable locally." CRLF);
1412
0
    fprintf(fp, "If you want to get these files, you have to set an upper "
1413
0
                "recurse level, ");
1414
0
    fprintf(fp, "and to rescan the URL." CRLF);
1415
0
    fclose(fp);
1416
0
    usercommand(opt, 0, NULL,
1417
0
                fconv(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), tempo), "",
1418
0
                "");
1419
0
  }
1420
1421
0
  hts_log_print(opt, LOG_WARNING, "Warning: store %s without scan: %s",
1422
0
                r->contenttype, savename());
1423
0
}
1424
1425
/* Save a body that is not on disk yet. */
1426
static void mirror_save_file(httrackp *opt, int ptr, htsblk *r,
1427
0
                             int store_errpage) {
1428
0
  if ((is_hypertext_mime(opt, r->contenttype, urlfil())) && (!store_errpage) &&
1429
0
      (r->size > 0)) { // HTML
1430
0
    write_unscanned_readme(opt, ptr, r);
1431
0
  } else {
1432
0
    if ((opt->getmode & HTS_GETMODE_NONHTML) != 0) {
1433
0
      hts_log_print(opt, LOG_DEBUG, "Store %s: %s", r->contenttype, savename());
1434
0
    } else { // not allowed, such as a cgi-bin answering HTML
1435
0
      hts_log_print(opt, LOG_DEBUG,
1436
0
                    "non-html file ignored after upload at %s : %s",
1437
0
                    adr_nologin(opt, urladr()), urlfil());
1438
0
      if (r->adr) {
1439
0
        freet(r->adr);
1440
0
        r->adr = NULL;
1441
0
      }
1442
0
    }
1443
0
  }
1444
1445
  // A failed transfer has no body: r->adr holds debris from the aborted
1446
  // read, which would destroy the copy being re-fetched (#748).
1447
0
  if (statuscode_is_http(r->statuscode) && (r->adr != NULL || r->size == 0)) {
1448
0
    file_notify(opt, urladr(), urlfil(), savename(), 1, 1, r->notmodified);
1449
0
    if (r->size < 0 ||
1450
0
        filesave(opt, hts_blk_body(r), savename(), urladr(), urlfil()) != 0) {
1451
0
      int fcheck;
1452
1453
0
      if ((fcheck = check_fatal_io_errno())) {
1454
0
        hts_io_fatal_abort(opt);
1455
0
      }
1456
0
      hts_log_print(opt, LOG_ERROR | LOG_ERRNO, "Unable to save file %s",
1457
0
                    savename());
1458
0
    } else if (strnotempty(r->lastmodified)) {
1459
0
      hts_stamp_filetime(opt, savename(), r->lastmodified);
1460
0
    }
1461
0
  }
1462
0
}
1463
1464
/* Hand a saved file to the external parsers, such as the Java class one. */
1465
static void mirror_parse_externals(httrackp *opt, int ptr,
1466
                                   const htsmoduleStruct *str_base,
1467
0
                                   int numero_passe, htsblk *r) {
1468
0
  if (opt->parsejava && (opt->parsejava & HTSPARSE_NO_CLASS) == 0 &&
1469
0
      fexist_utf8(savename())) {
1470
0
    char BIGSTK buff_err_msg[1024];
1471
0
    htsmoduleStruct BIGSTK str;
1472
1473
0
    mirror_module_str(&str, str_base, buff_err_msg, numero_passe, r);
1474
1475
    /* Parse if recognized */
1476
0
    switch (hts_parse_externals(&str)) {
1477
0
    case 1:
1478
0
      hts_log_print(opt, LOG_DEBUG, "(External module): parsed successfully %s",
1479
0
                    savename());
1480
0
      break;
1481
0
    case 0:
1482
0
      hts_log_print(opt, LOG_DEBUG,
1483
0
                    "(External module): couldn't parse successfully %s : %s",
1484
0
                    savename(), str.err_msg);
1485
0
      break;
1486
0
    }
1487
0
  }
1488
0
}
1489
1490
/* Move past the link at ptr, honouring the HTML-first passes, a quota and
1491
   a stop request. Returns the next link, or lien_tot to end the loop. */
1492
0
static int mirror_next_link(httrackp *opt, int ptr, int *numero_passe) {
1493
0
  ptr++;
1494
1495
  // with -p7, HTML first, then the other files in a second pass
1496
0
  if (opt->getmode & HTS_GETMODE_HTML_FIRST) {
1497
0
    if (!*numero_passe) {
1498
0
      while ((ptr < opt->lien_tot) ? (heap(ptr)->pass2) : 0)
1499
0
        ptr++;
1500
0
    } else {
1501
0
      while ((ptr < opt->lien_tot) ? (!heap(ptr)->pass2) : 0)
1502
0
        ptr++;
1503
0
    }
1504
0
    if (ptr >= opt->lien_tot) { // end of this pass
1505
0
      if (!*numero_passe) {     // first pass
1506
0
        hts_log_print(opt, LOG_DEBUG, "Now getting non-html files...");
1507
0
        *numero_passe = 1; // second pass
1508
0
        ptr = 0;
1509
0
        while ((ptr < opt->lien_tot) ? (!heap(ptr)->pass2) : 0)
1510
0
          ptr++;
1511
0
      }
1512
0
    }
1513
0
  }
1514
  // over the quota?
1515
0
  if (!back_checkmirror(opt)) {
1516
0
    ptr = opt->lien_tot;
1517
0
  } else {
1518
0
    const int exit_xh = hts_load_acquire_int(&opt->state.exit_xh);
1519
1520
0
    if (exit_xh != 0) {
1521
0
      hts_log_print(opt, LOG_ERROR,
1522
0
                    exit_xh == 1 ? "Exit requested by shell or user"
1523
0
                                 : "Exit requested by engine");
1524
0
      ptr = opt->lien_tot;
1525
0
    }
1526
0
  }
1527
0
  return ptr;
1528
0
}
1529
1530
/* --changes and --purge-old: compare old.lst with new.lst, report the files
1531
   this run dropped, and with --purge-old delete them. */
1532
0
static void mirror_purge_old(httrackp *opt) {
1533
0
  char *old_lst, *new_lst;
1534
0
  LLint old_sz = 0;
1535
1536
  /* A page that gave up before parsing keeps its own links out of
1537
     new.lst, so their absence says nothing about the site. */
1538
0
  const hts_boolean purge_files = opt->delete_old && !opt->links_unqueued;
1539
1540
0
  hts_changes_indexed(opt);
1541
  //
1542
0
  opt->state._hts_in_html_parsing = 3;
1543
  //
1544
0
  old_lst = readfile2_utf8(hts_logpath(opt, "hts-cache/old.lst"), &old_sz);
1545
0
  if (old_lst != NULL) {
1546
0
    if (opt->delete_old && !purge_files) {
1547
0
      hts_log_print(opt, LOG_WARNING,
1548
0
                    "A page could not be fetched and the links it carries "
1549
0
                    "were never scanned: keeping all previously mirrored "
1550
0
                    "files");
1551
0
    }
1552
    /* new.lst is NUL-terminated for the strstr() lookups below. */
1553
0
    new_lst = readfile2_utf8(hts_logpath(opt, "hts-cache/new.lst"), NULL);
1554
0
    if (new_lst != NULL) {
1555
0
      const size_t root = StringLength(opt->path_html);
1556
0
      const hts_span old = hts_span_at(old_lst, (size_t) old_sz);
1557
      /* This holds filenote()'s longest line, "[" + savelst + "]". */
1558
0
      char BIGSTK line[HTS_URLMAXSIZE * 2 + 2];
1559
0
      char BIGSTK file[HTS_URLMAXSIZE * 2];
1560
0
      size_t pos;
1561
0
      int purge = 0;
1562
1563
0
      for (pos = 0; pos < (size_t) old_sz;) {
1564
0
        if (!old_lst_entry(opt, old, &pos, HTS_BUF(line), HTS_BUF(file)))
1565
0
          continue;
1566
0
        hts_changes_previous(opt, file + root);
1567
0
        if (!strstr(new_lst, line)) { // not found in the new list?
1568
0
          if (fexist_utf8(file)) {    // still on disk
1569
            /* A transfer killed mid-flight also drops out of new.lst.
1570
               Unless purged, its previous copy stands. */
1571
0
            const hts_boolean kept =
1572
0
                !purge_files &&
1573
0
                hash_read(opt->hash, file, NULL, HASH_STRUCT_FILENAME) >= 0;
1574
1575
0
            hts_changes_dropped(opt, file + root, kept);
1576
0
            if (purge_files) {
1577
0
              hts_log_print(opt, LOG_INFO, "Purging %s", file);
1578
0
              UNLINK(file);
1579
0
              purge = 1;
1580
0
            }
1581
0
          }
1582
0
        }
1583
0
      }
1584
0
      if (purge_files) { // emptied directories go with the files
1585
0
        for (pos = 0; pos < (size_t) old_sz;) {
1586
0
          size_t dir;
1587
1588
0
          if (!old_lst_entry(opt, old, &pos, HTS_BUF(line), HTS_BUF(file)))
1589
0
            continue;
1590
0
          dir = strlen(file);
1591
0
          if (!chop_to_parent(file, root, &dir))
1592
0
            continue;
1593
0
          line[dir - root + 1] = '\0';
1594
0
          if (strstr(new_lst, line)) // still in new.lst
1595
0
            continue;
1596
0
          while (RMDIR(file) == 0) { // it existed and was empty
1597
0
            purge = 1;
1598
0
            hts_log_print(opt, LOG_INFO, "Purging directory %s/", file);
1599
0
            if (!chop_to_parent(file, root, &dir))
1600
0
              break;
1601
0
          }
1602
0
        }
1603
0
      }
1604
      //
1605
0
      if (purge_files && !purge) {
1606
0
        hts_log_print(opt, LOG_INFO, "No files purged");
1607
0
      }
1608
0
      freet(new_lst);
1609
0
    }
1610
0
    freet(old_lst);
1611
0
  }
1612
  //
1613
0
  opt->state._hts_in_html_parsing = 0;
1614
0
}
1615
1616
/* Write the end-of-mirror summary to the log, and close the ZIP cache with
1617
   it. */
1618
static void mirror_log_summary(httrackp *opt, hts_boolean aborted,
1619
0
                               cache_back *cache) {
1620
0
  char BIGSTK finalInfo[8192];
1621
0
  size_t finalUsed = 0;
1622
0
  int error = fspc_get(opt, "error");
1623
0
  int warning = fspc_get(opt, "warning");
1624
0
  int info = fspc_get(opt, "info");
1625
0
  char BIGSTK htstime[256];
1626
0
  char BIGSTK infoupdated[256];
1627
1628
0
  const LLint recv = hts_stat_recv_get();
1629
0
  LLint n = recv / hts_max_i64(1, time_local() - HTS_STAT.stat_timestart);
1630
1631
0
  sec2str(HTS_BUF(htstime), time_local() - HTS_STAT.stat_timestart);
1632
0
  infoupdated[0] = '\0';
1633
0
  if (opt->is_update) {
1634
0
    if (HTS_STAT.stat_updated_files > 0) {
1635
0
      slprintfbuff_clip(infoupdated, sizeof(infoupdated), ", %d files updated",
1636
0
                        (int) HTS_STAT.stat_updated_files);
1637
0
    } else {
1638
0
      slprintfbuff_clip(infoupdated, sizeof(infoupdated), ", no files updated");
1639
0
    }
1640
0
  }
1641
0
  finalInfo[0] = '\0';
1642
0
  slcatprintfbuff_clip(
1643
0
      finalInfo, sizeof(finalInfo), &finalUsed,
1644
0
      "HTTrack Website Copier/" HTTRACK_VERSION " mirror %s %s : "
1645
0
      "%d links scanned, %d files written (" LLintP " bytes overall)%s "
1646
0
      "[" LLintP " bytes received at " LLintP " bytes/sec]",
1647
0
      aborted ? "aborted after" : "complete in", htstime,
1648
0
      (int) opt->lien_tot - 1, (int) HTS_STAT.stat_files,
1649
0
      (LLint) HTS_STAT.stat_bytes, infoupdated, (LLint) recv, (LLint) n);
1650
1651
0
  if (HTS_STAT.total_packed > 0 && HTS_STAT.total_unpacked > 0) {
1652
0
    int packed_ratio =
1653
0
        (int) ((LLint) (HTS_STAT.total_packed * 100) / HTS_STAT.total_unpacked);
1654
0
    slcatprintfbuff_clip(
1655
0
        finalInfo, sizeof(finalInfo), &finalUsed,
1656
0
        ", " LLintP
1657
0
        " bytes transferred using HTTP compression in %d files, ratio %d%%",
1658
0
        (LLint) HTS_STAT.total_unpacked, HTS_STAT.total_packedfiles,
1659
0
        (int) packed_ratio);
1660
0
  }
1661
0
  if (!opt->nokeepalive && HTS_STAT.stat_sockid > 0 &&
1662
0
      HTS_STAT.stat_nrequests > HTS_STAT.stat_sockid) {
1663
0
    int rq = (HTS_STAT.stat_nrequests * 10) / HTS_STAT.stat_sockid;
1664
1665
0
    slcatprintfbuff_clip(finalInfo, sizeof(finalInfo), &finalUsed,
1666
0
                         ", %d.%d requests per connection", rq / 10, rq % 10);
1667
0
  }
1668
0
  slcatprintfbuff_clip(finalInfo, sizeof(finalInfo), &finalUsed, LF);
1669
0
  if (error)
1670
0
    slcatprintfbuff_clip(finalInfo, sizeof(finalInfo), &finalUsed,
1671
0
                         "(%d errors, %d warnings, %d messages)" LF, error,
1672
0
                         warning, info);
1673
0
  else
1674
0
    slcatprintfbuff_clip(finalInfo, sizeof(finalInfo), &finalUsed,
1675
0
                         "(No errors, %d warnings, %d messages)" LF, warning,
1676
0
                         info);
1677
0
  if (opt->transport_failures > 0)
1678
0
    slcatprintfbuff_clip(
1679
0
        finalInfo, sizeof(finalInfo), &finalUsed,
1680
0
        "(%d links failed to transfer, so the mirror is incomplete)" LF,
1681
0
        opt->transport_failures);
1682
  /* a fallback is news only to someone who asked for --mptcp */
1683
0
  if (opt->mptcp_connections > 0 ||
1684
0
      (opt->mptcp == HTS_TRUE && opt->mptcp_fallbacks > 0))
1685
0
    slcatprintfbuff_clip(finalInfo, sizeof(finalInfo), &finalUsed,
1686
0
                         "(Multipath TCP: %d HTTP connections negotiated it, "
1687
0
                         "%d fell back to TCP)" LF,
1688
0
                         opt->mptcp_connections, opt->mptcp_fallbacks);
1689
1690
  // Log
1691
0
  fprintf(opt->log, LF "%s", finalInfo);
1692
  /* on disk now: the teardown in httpmirror() holds the only other flush,
1693
     and a ^C or a kill arriving in it would drop this verdict. */
1694
0
  fflush(opt->log);
1695
1696
  // Close ZIP
1697
0
  if (cache->zipOutput) {
1698
0
    zipClose(cache->zipOutput, finalInfo);
1699
0
    cache->zipOutput = NULL;
1700
0
  }
1701
0
}
1702
1703
0
int httpmirror(char *url1, httrackp *opt, hts_boolean *completed_out) {
1704
0
  char *primary = NULL;         // première page, contenant les liens à scanner
1705
0
  hash_struct hash;             // système de hachage, accélère la recherche dans les liens
1706
0
  hash_struct *const hashptr = &hash;
1707
0
  t_cookie BIGSTK cookie;       // gestion des cookies
1708
0
  int cookies_file_refused = 0; // cookie_load result for the jar to rewrite
1709
1710
0
  int ptr;                      // pointeur actuel sur les liens
1711
0
  int retcode = 1; // return code for the single exit; a bailout sets -1
1712
0
  hts_boolean rollback = HTS_FALSE;  // set to roll back the cache at cleanup
1713
0
  hts_boolean completed = HTS_FALSE; // set once the crawl loop reaches its end
1714
0
  hts_boolean aborted = HTS_FALSE; // set when it stops with links left instead
1715
1716
  //
1717
0
  int numero_passe = 0;         // deux passes pour html puis images
1718
0
  struct_back *sback = NULL;
1719
0
  htsblk BIGSTK r;              // retour de certaines fonctions
1720
1721
  // pour les stats, nombre de fichiers & octets écrits
1722
0
  LLint stat_fragment = 0;      // pour la fragmentation
1723
1724
0
  TStamp last_info_shell = 0;
1725
0
  int info_shell = 0;
1726
1727
  // filtres
1728
0
  char **filters = NULL;
1729
1730
0
  int filptr = 0;
1731
1732
  //
1733
0
  int makeindex_done = 0;       // lorsque l'index sera fait
1734
0
  FILE *makeindex_fp = NULL;
1735
0
  int makeindex_links = 0;
1736
0
  char BIGSTK makeindex_firstlink[HTS_URLMAXSIZE * 2];
1737
1738
  // statistiques (mode #Z)
1739
0
  FILE *makestat_fp = NULL;     // fichier de stats taux transfert
1740
0
  FILE *maketrack_fp = NULL;    // idem pour le tracking
1741
0
  TStamp makestat_time = 0;     // attente (secondes)
1742
0
  LLint makestat_total = 0;     // repère du nombre d'octets transférés depuis denrière stat
1743
0
  int makestat_lnk = 0;         // idem, pour le nombre de liens
1744
1745
  //
1746
0
  char BIGSTK codebase[HTS_URLMAXSIZE * 2];     // base pour applet java
1747
0
  char BIGSTK base[HTS_URLMAXSIZE * 2]; // base pour les autres fichiers
1748
1749
  //
1750
0
  cache_back BIGSTK cache;
1751
0
  robots_wizard BIGSTK robots;  // gestion robots.txt
1752
0
  coucal cache_hashtable = NULL;
1753
0
  coucal cache_tests = NULL;
1754
0
  coucal cache_kept = NULL;
1755
1756
  //
1757
0
  char *template_header = NULL, *template_body = NULL, *template_footer = NULL;
1758
0
  htsmoduleStruct BIGSTK str_base;          // see mirror_module_str()
1759
0
  htsmoduleStructExtended BIGSTK stre_base; // see mirror_module_stre()
1760
1761
  //
1762
0
  codebase[0] = '\0';
1763
0
  base[0] = '\0';
1764
  //
1765
0
  cookie.auth.next = NULL;
1766
0
  cookie.auth.auth[0] = cookie.auth.prefix[0] = '\0';
1767
  /* Before the first XH_extuninit, whose checkrobots_free() frees these. */
1768
0
  robots.adr = NULL; // list head, holds no rules
1769
0
  robots.token = NULL;
1770
0
  robots.next = NULL;
1771
0
  opt->robotsptr = &robots;
1772
  /* The first XH_extuninit may run before hash_init(), and frees it. */
1773
0
  memset(&hash, 0, sizeof(hash));
1774
  //
1775
1776
  /* per mirror, not per opt: an embedder reusing one opt would otherwise
1777
     carry the last run's verdict and never purge again */
1778
0
  opt->links_unqueued = HTS_FALSE;
1779
0
  opt->abort_left_partial = HTS_FALSE;
1780
0
  url_savename_refnames_start(opt);
1781
0
  opt->abort_lock_polled_at = 0;
1782
0
  opt->pause_lock_polled_at = 0;
1783
0
  opt->transport_failures = 0;
1784
0
  opt->mptcp_connections = 0;
1785
0
  opt->mptcp_fallbacks = 0;
1786
0
  opt->upper_links_refused = HTS_FALSE;
1787
  /* left over from a previous run */
1788
0
  hts_addurl_free(hts_addfilter_take(opt));
1789
0
  hts_addurl_free(hts_setfilters_take(opt));
1790
1791
  /* before the first bailout below, each of which leaves it false */
1792
0
  set_mirror_completed(opt, completed_out, HTS_FALSE);
1793
1794
  // noter heure actuelle de départ en secondes
1795
0
  memset(&HTS_STAT, 0, sizeof(HTS_STAT));
1796
0
  hts_mirror_clock_start();
1797
0
  HTS_STAT.istat_timestart[0] = HTS_STAT.istat_timestart[1] = mtime_monotonic();
1798
  /* reset stats */
1799
0
  hts_stat_recv_set(0);
1800
0
  HTS_STAT.istat_bytes[0] = HTS_STAT.istat_bytes[1] = 0;
1801
0
  mirror_stat_timers_start(opt, &last_info_shell, &makestat_time);
1802
  // init external modules
1803
0
  htspe_init();
1804
1805
  // initialiser cookie
1806
0
  if (opt->accept_cookie) {
1807
0
    opt->cookie = &cookie;
1808
0
    cookie.max_len = COOKIE_MAX_JAR; // max len
1809
0
    strcpybuff(cookie.data, "");
1810
0
    if (strnotempty(StringBuff(opt->cookies_file))) {
1811
      // loaded once the start URLs are known, and left alone until then
1812
0
      cookies_file_refused = COOKIE_LOAD_KEEP;
1813
0
    } else {
1814
0
      cookies_file_refused = cookie_load(
1815
0
          opt, opt->cookie, StringBuff(opt->path_log), "cookies.txt");
1816
0
      cookie_load(opt, opt->cookie, "", "cookies.txt");
1817
0
    }
1818
0
  } else {
1819
0
    opt->cookie = NULL;
1820
0
    if (strnotempty(StringBuff(opt->cookies_file)))
1821
0
      hts_log_print(opt, LOG_WARNING,
1822
0
                    "Cookies are disabled, so the cookies file %s is not read",
1823
0
                    StringBuff(opt->cookies_file));
1824
0
  }
1825
1826
0
  hts_store_release_int(&opt->state.exit_xh, 0);
1827
  /* a fault a previous mirror recovered from must not abort this one */
1828
0
  hts_worker_fault_clear();
1829
1830
  // initialiser usercommand
1831
0
  usercommand(opt, opt->sys_com_exec, StringBuff(opt->sys_com), "", "", "");
1832
1833
  // initialiser verif_backblue
1834
0
  verif_backblue(opt, NULL);
1835
0
  opt->state.verif_external_status = 0;
1836
1837
  // et templates html
1838
0
  template_header =
1839
0
    readfile_or(fconcat
1840
0
                (OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), StringBuff(opt->path_bin),
1841
0
                 "templates/index-header.html"), HTS_INDEX_HEADER);
1842
0
  template_body =
1843
0
    readfile_or(fconcat
1844
0
                (OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), StringBuff(opt->path_bin),
1845
0
                 "templates/index-body.html"), HTS_INDEX_BODY);
1846
0
  template_footer =
1847
0
    readfile_or(fconcat
1848
0
                (OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), StringBuff(opt->path_bin),
1849
0
                 "templates/index-footer.html"), HTS_INDEX_FOOTER);
1850
1851
  // Initialiser indexation
1852
0
  if (opt->kindex != HTS_KINDEX_OFF)
1853
0
    index_init(StringBuff(opt->path_html));
1854
1855
  // effacer bloc cache
1856
0
  memset(&cache, 0, sizeof(cache_back));
1857
0
  cache.type = opt->cache;      // cache?
1858
0
  cache.errlog = cache.log = opt->log;  // err log?
1859
0
  cache.ptr_ant = cache.ptr_last = 0;   // pointeur pour anticiper
1860
1861
  // initialiser hash cache
1862
0
  cache_hashtable = coucal_new(0);
1863
0
  cache_tests = coucal_new(0);
1864
0
  cache_kept = coucal_new(0);
1865
0
  if (cache_hashtable == NULL || cache_tests == NULL || cache_kept == NULL) {
1866
0
    printf("PANIC! : Not enough memory [%d]\n", __LINE__);
1867
0
    XH_extuninit;
1868
0
    return 0;
1869
0
  }
1870
0
  hts_set_hash_handler(cache_hashtable, opt);
1871
0
  hts_set_hash_handler(cache_tests, opt);
1872
0
  hts_set_hash_handler(cache_kept, opt);
1873
0
  coucal_set_name(cache_hashtable, "cache_hashtable");
1874
0
  coucal_set_name(cache_tests, "cache_tests");
1875
0
  coucal_set_name(cache_kept, "cache_kept");
1876
0
  coucal_value_is_malloc(cache_tests, 1);      /* malloc */
1877
0
  cache.hashtable = (void *) cache_hashtable;   /* copy backcache hash */
1878
0
  cache.cached_tests = (void *) cache_tests;    /* copy of cache_tests */
1879
0
  cache.kept = cache_kept;
1880
1881
  // effacer filters
1882
0
  opt->maxfilter = hts_max_int(opt->maxfilter, 128);
1883
0
  if (filters_init(&filters, opt->maxfilter, 0) == 0) {
1884
0
    printf("PANIC! : Not enough memory [%d]\n", __LINE__);
1885
0
    XH_extuninit;
1886
0
    return 0;
1887
0
  }
1888
0
  filters_bind(opt, &filters, &filptr);
1889
1890
  // hash table
1891
0
  opt->hash = &hash;
1892
1893
  // a change report left by a previous crawl on this opt is not this one's
1894
0
  hts_changes_free_opt(opt);
1895
1896
  // initialize link heap
1897
0
  if (!hts_record_init(opt)) {
1898
0
    printf("PANIC! : Not enough memory [%d]\n", __LINE__);
1899
0
    XH_extuninit;
1900
0
    return 0;
1901
0
  }
1902
1903
  // initialiser ptr et lien_tot
1904
0
  ptr = 0;
1905
1906
  // initialiser hachage
1907
0
  hash_init(opt, &hash, opt->urlhack);
1908
  // note: we need a cast because of the const
1909
0
  hash.liens = (const lien_url *const*const*) &opt->liens;
1910
1911
  // copier adresse(s) dans liste des adresses
1912
0
  {
1913
0
    const size_t url_len = strlen(url1);
1914
0
    const LLint list_sz = StringNotEmpty(opt->filelist)
1915
0
                              ? fsize_utf8(StringBuff(opt->filelist))
1916
0
                              : 0;
1917
    /* A one-byte token becomes "http://a\n", so reserve five bytes per input
1918
       byte. -1 refuses a size that would overflow. */
1919
0
    const LLint list_room =
1920
0
        list_sz > 0 ? (list_sz <= INT64_MAX / 5 ? list_sz * 5 : -1) : 0;
1921
0
    const size_t url_room = url_len <= (((size_t) -2) - 8192) / 5
1922
0
                                ? 8192 + url_len * 5
1923
0
                                : (size_t) -1;
1924
0
    const size_t primary_len = url_room != (size_t) -1
1925
0
                                   ? llint_grow_size_t(url_room, list_room, 0)
1926
0
                                   : (size_t) -1;
1927
1928
    // création de la première page, qui contient les liens de base à scanner
1929
    // c'est plus propre et plus logique que d'entrer à la main les liens dans la pile
1930
    // on bénéficie ainsi des vérifications et des tests du robot pour les liens "primaires"
1931
0
    primary = primary_len != (size_t) -1 ? (char *) malloct(primary_len) : NULL;
1932
0
    if (!primary) {
1933
0
      printf("PANIC! : Not enough memory [%d]\n", __LINE__);
1934
0
      XH_extuninit;
1935
0
      return 0;
1936
0
    }
1937
0
    htsbuff primarybuff = htsbuff_ptr(primary, primary_len);
1938
1939
0
    if (!seed_parse_args(opt, url1, &primarybuff, &filptr)) {
1940
0
      freet(primary);
1941
0
      XH_extuninit;
1942
0
      return 0;
1943
0
    }
1944
0
    opt->user_filters = filptr; /* everything so far came from the user */
1945
1946
    /* --why: print which filter rule decides for this URL, then stop */
1947
0
    if (StringNotEmpty(opt->why_url)) {
1948
0
      mirror_why(opt, filters, filptr);
1949
0
      freet(primary);
1950
      /* --why answered; no mirror was asked for. The store comes first
1951
         because the teardown below fires the end callback. */
1952
0
      set_mirror_completed(opt, completed_out, HTS_TRUE);
1953
0
      XH_extuninit;
1954
0
      return 1;
1955
0
    }
1956
1957
    /* load URL file list */
1958
    /* OPTIMIZED for fast load */
1959
    /* set when a -%L line named a login bundle that was refused */
1960
0
    const hts_boolean bundle_refused = StringNotEmpty(opt->filelist) &&
1961
0
                                       !seed_append_filelist(opt, &primarybuff);
1962
1963
    // the --cookies-file is the whole jar, because the crawl writes it back
1964
0
    if (opt->accept_cookie && strnotempty(StringBuff(opt->cookies_file))) {
1965
0
      char BIGSTK start_url[HTS_URLMAXSIZE * 2];
1966
0
      const size_t first = strcspn(primary, "\n");
1967
0
      const char *const seed =
1968
0
          hts_buf_put_span(HTS_BUF(start_url), hts_span_at(primary, first))
1969
0
              ? start_url
1970
0
              : "";
1971
1972
0
      cookies_file_refused = cookie_load_from(
1973
0
          opt, opt->cookie, "", StringBuff(opt->cookies_file), seed);
1974
0
    }
1975
1976
    // bundle url lines join the start URLs, and bundle cookies go to the jar
1977
0
    if (bundle_refused || !bundle_start(opt, &primary, &primarybuff)) {
1978
      /* the jar may hold half a bundle, so it is not saved */
1979
0
      cookies_file_refused = COOKIE_LOAD_KEEP;
1980
0
      freet(primary);
1981
0
      XH_extuninit;
1982
0
      return 0;
1983
0
    }
1984
1985
    // lien primaire
1986
0
    if (!hts_record_link(
1987
0
            opt, "primary", "/primary",
1988
0
            fslash(OPT_GET_HTS_BUF(opt),
1989
0
                   hts_optpath(opt, StringBuff(opt->path_html_utf8),
1990
0
                               "index.html")),
1991
0
            "", "", NULL)) {
1992
0
      freet(primary);
1993
0
      XH_extuninit;             // désallocation mémoire & buffers
1994
0
      return 0;
1995
0
    }
1996
0
    hts_link_set_self_parented(opt, opt->depth + 1, 0);
1997
1998
    /* --sitemap: queue the sitemap probe just after the seeds, so its URLs are
1999
       injected before the crawl gets far. */
2000
0
    hts_sitemap_free(opt); /* an earlier mirror may have left a doc list */
2001
0
    if (opt->sitemap || StringNotEmpty(opt->sitemap_url))
2002
0
      seed_sitemap(opt, primary);
2003
2004
    // Initialiser cache
2005
0
    {
2006
0
      opt->state._hts_in_html_parsing = 4;
2007
0
      if (!RUN_CALLBACK7(opt, loop, NULL, 0, 0, 0, opt->lien_tot, 0, NULL)) {
2008
0
        hts_store_release_int(&opt->state.exit_xh, 1); // exit requested
2009
0
      }
2010
0
      cache_init(&cache, opt);
2011
0
      opt->state._hts_in_html_parsing = 0;
2012
0
    }
2013
0
  }
2014
2015
  /* backing: at least one socket, or nothing is ever fetched */
2016
0
  if (opt->maxsoc <= 0)
2017
0
    opt->maxsoc = 1;
2018
0
  {
2019
    /* How many HTML files may sit in memory at once. Sized generously: HTML
2020
       takes little room and everything else is written straight to disk. */
2021
0
    const int back_max = back_max_slots(opt->maxsoc);
2022
2023
0
    sback = back_new(opt, back_max);
2024
0
    if (sback == NULL) {
2025
0
      hts_log_print(opt, LOG_PANIC,
2026
0
                    "Not enough memory, can not allocate %d backing slots",
2027
0
                    back_max);
2028
0
      freet(primary);
2029
0
      XH_extuninit;
2030
0
      return 0;
2031
0
    }
2032
    /* a killed run cannot clean up its own spool */
2033
0
    back_spool_sweep(opt);
2034
0
  }
2035
  // statistiques
2036
0
  if (opt->makestat) {
2037
0
    makestat_fp = FOPEN(hts_logpath(opt, "hts-stats.txt"), "wb");
2038
0
    if (makestat_fp != NULL) {
2039
0
      fprintf(makestat_fp, "HTTrack statistics report, every minutes" LF LF);
2040
0
      fflush(makestat_fp);
2041
0
    }
2042
0
  }
2043
  // tracking -- débuggage
2044
0
  if (opt->maketrack) {
2045
0
    maketrack_fp = FOPEN(hts_logpath(opt, "hts-track.txt"), "wb");
2046
0
    if (maketrack_fp != NULL) {
2047
0
      fprintf(maketrack_fp, "HTTrack tracking report, every minutes" LF LF);
2048
0
      fflush(maketrack_fp);
2049
0
    }
2050
0
  }
2051
  // on n'a pas de liens!! (exemple: httrack www.* impossible sans départ..)
2052
0
  if (opt->lien_tot <= 0) {
2053
0
    hts_log_print(opt, LOG_ERROR,
2054
0
                  "You MUST specify at least one complete URL, and not only wildcards!");
2055
0
  }
2056
2057
  /* Send options to callback functions */
2058
0
  RUN_CALLBACK0(opt, chopt);
2059
2060
0
  if (opt->waittime > 0)
2061
0
    mirror_wait_start_time(opt, sback, &last_info_shell, &makestat_time);
2062
  /* Info for wrappers */
2063
0
  hts_log_print(opt, LOG_INFO, "engine: start");
2064
0
  if (!RUN_CALLBACK0(opt, start)) {
2065
0
    freet(primary);
2066
0
    XH_extuninit;
2067
0
    return 1;
2068
0
  }
2069
  // ------------------------------------------------------------
2070
2071
  /* None of these change once the loop starts. */
2072
0
  memset(&str_base, 0, sizeof(str_base));
2073
0
  str_base.addLink = htsAddLink;
2074
0
  str_base.opt = opt;
2075
0
  str_base.sback = sback;
2076
0
  str_base.cache = &cache;
2077
0
  str_base.hashptr = hashptr;
2078
0
  str_base.ptr_ = &ptr;
2079
0
  memset(&stre_base, 0, sizeof(stre_base));
2080
0
  stre_base.exit_xh_ = &opt->state.exit_xh;
2081
0
  stre_base.base = base;
2082
0
  stre_base.codebase = codebase;
2083
0
  stre_base.filters_ = &filters;
2084
0
  stre_base.filptr_ = &filptr;
2085
0
  stre_base.robots_ = &robots;
2086
0
  stre_base.hash_ = &hash;
2087
0
  stre_base.makeindex_done_ = &makeindex_done;
2088
0
  stre_base.makeindex_fp_ = &makeindex_fp;
2089
0
  stre_base.makeindex_links_ = &makeindex_links;
2090
0
  stre_base.makeindex_firstlink_ = makeindex_firstlink;
2091
0
  stre_base.template_header_ = template_header;
2092
0
  stre_base.template_body_ = template_body;
2093
0
  stre_base.template_footer_ = template_footer;
2094
0
  stre_base.stat_fragment_ = &stat_fragment;
2095
0
  stre_base.makestat_time_ = &makestat_time;
2096
0
  stre_base.makestat_fp = makestat_fp;
2097
0
  stre_base.makestat_total_ = &makestat_total;
2098
0
  stre_base.makestat_lnk_ = &makestat_lnk;
2099
0
  stre_base.maketrack_fp = maketrack_fp;
2100
2101
  // ------------------------------------------------------------
2102
  // Boucle générale de parcours des liens
2103
  // ------------------------------------------------------------
2104
0
  do {
2105
0
    int error = 0;              // si error alors sauter
2106
0
    int store_errpage = 0;      // c'est une erreur mais on enregistre le html
2107
0
    hts_boolean is_binary = HTS_FALSE;
2108
    /* body read back from disk (implies is_write=1) */
2109
0
    hts_boolean is_loaded_from_file = HTS_FALSE;
2110
0
    char BIGSTK loc[HTS_LOCATION_SIZE]; // redirect target
2111
2112
    // Ici on charge le fichier (html, gif..) en mémoire
2113
    // Les HTMLs sont traités (si leur priorité est suffisante)
2114
2115
    // effacer r
2116
0
    mirror_request_init(opt, &r, loc);
2117
2118
0
    if (!error) {
2119
2120
      // Skip empty/invalid/done in background
2121
0
      if (heap(ptr)) {
2122
0
        ptr = mirror_skip_ready(opt, ptr);
2123
        // We're done!
2124
0
        if (ptr == opt->lien_tot) {
2125
0
          goto jump_if_done;
2126
0
        }
2127
0
      }
2128
0
      if (heap(ptr) != NULL) { // on a qq chose à récupérer?
2129
2130
0
        hts_log_print(opt, LOG_DEBUG, "Wait get: %s%s",
2131
0
                      adr_nologin(opt, urladr()), urlfil());
2132
0
        if (ptr == 0) {         // premier lien à parcourir: lien primaire construit avant
2133
0
          r.adr = primary;
2134
0
          primary = NULL;
2135
0
          r.statuscode = HTTP_OK;
2136
0
          r.size = strlen(r.adr);
2137
0
          r.soc = INVALID_SOCKET;
2138
0
          strcpybuff(r.contenttype, "text/html");
2139
0
        } else {                // backing, multiples sockets
2140
          /*
2141
           **************************************
2142
           Get the next link, waiting for other files, handling external callbacks
2143
           */
2144
0
          {
2145
0
            char BIGSTK buff_err_msg[1024];
2146
0
            htsmoduleStruct BIGSTK str;
2147
0
            htsmoduleStructExtended BIGSTK stre;
2148
2149
0
            mirror_module_str(&str, &str_base, buff_err_msg, numero_passe, &r);
2150
0
            mirror_module_stre(&stre, &stre_base, &r, &error, &store_errpage);
2151
            /* FUNCTION DEPENDANT */
2152
0
            stre.loc_ = loc;
2153
0
            stre.last_info_shell_ = &last_info_shell;
2154
0
            stre.info_shell_ = &info_shell;
2155
2156
            /* Parse */
2157
0
            if (hts_mirror_wait_for_next_file(&str, &stre) ==
2158
0
                HTS_NEXT_FILE_DONE)
2159
0
              goto jump_if_done;
2160
0
          }
2161
0
        }
2162
2163
0
      } else {                  // lien vide..
2164
0
        hts_log_print(opt, LOG_WARNING, "Warning, link #%d empty", ptr);
2165
0
        error = 1;
2166
0
        goto jump_if_done;
2167
0
      }                         // test si url existe (non vide!)
2168
2169
      // check the size after the fact
2170
0
      if (!error) {
2171
0
        if (hts_body_missing_unexpectedly(&r)) {
2172
          // maybe the file was too big?
2173
0
          if (istoobig(opt, r.totalsize, opt->maxfile_html,
2174
0
                       opt->maxfile_nonhtml, r.contenttype)) {
2175
0
            error = 0;
2176
0
            hts_log_print(
2177
0
                opt, LOG_WARNING,
2178
0
                "Big file cancelled according to user's preferences: %s%s",
2179
0
                adr_nologin(opt, urladr()), urlfil());
2180
0
          }
2181
0
        }
2182
0
      }
2183
2184
      // -------------------- 
2185
      // BOGUS MIME TYPE HACK
2186
      // Check if we have a bogus MIME type
2187
      // example: 
2188
      // Content-type="text/html"
2189
      // and 
2190
      // Content-disposition="foo.jpg"
2191
      // --------------------
2192
0
      if (!error) {
2193
0
        is_binary = fix_bogus_mime(opt, ptr, &r);
2194
2195
        /* Load file and decode if necessary, before content-binary check. (3.43) */
2196
0
        if (load_body_from_disk(opt, ptr, &r, store_errpage))
2197
0
          is_loaded_from_file = HTS_TRUE;
2198
2199
0
        is_binary = normalize_body_chars(opt, ptr, &r, is_binary, &error);
2200
0
      }
2201
2202
      /*
2203
       **************************************
2204
       Check "Moved permanently" and other similar errors, retrying URLs if necessary and handling
2205
       redirect pages.
2206
       */
2207
0
      if (!error) {
2208
0
        char BIGSTK buff_err_msg[1024];
2209
0
        htsmoduleStruct BIGSTK str;
2210
0
        htsmoduleStructExtended BIGSTK stre;
2211
2212
0
        mirror_module_str(&str, &str_base, buff_err_msg, numero_passe, &r);
2213
0
        mirror_module_stre(&stre, &stre_base, &r, &error, &store_errpage);
2214
2215
        /* Parse */
2216
0
        {
2217
0
          const int nlinks = opt->lien_tot;
2218
2219
0
          if (hts_mirror_check_moved(&str, &stre) != 0) {
2220
0
            retcode = -1;
2221
0
            goto cleanup;
2222
0
          }
2223
          /* A redirect re-queues the target as a fresh link; without carrying
2224
             the marking over, a moved sitemap is fetched and then ignored. */
2225
0
          if (opt->sitemap_state != NULL && opt->lien_tot > nlinks &&
2226
0
              hts_sitemap_pending(opt, urladr(), urlfil())) {
2227
0
            hts_sitemap_redirect(opt, urladr(), urlfil(), heap_top()->adr,
2228
0
                                 heap_top()->fil);
2229
0
          }
2230
0
        }
2231
0
      }
2232
2233
0
    }                           // if !error
2234
2235
0
    if (!error) {
2236
2237
      /* Load file and decode if necessary, after redirect check. */
2238
0
      if (load_body_from_disk(opt, ptr, &r, store_errpage))
2239
0
        is_loaded_from_file = HTS_TRUE;
2240
2241
0
      if (opt->sitemap_state != NULL &&
2242
0
          hts_sitemap_pending(opt, urladr(), urlfil()))
2243
0
        mirror_sitemap_ingest(opt, ptr, &str_base, numero_passe, &r);
2244
2245
0
      drop_foreign_asset_depth(opt, ptr, &r, is_binary);
2246
2247
0
      if (mirror_should_parse(opt, ptr, &r, is_binary, store_errpage)) {
2248
0
        char page_charset[32];
2249
2250
        /* Remove file if being processed */
2251
0
        if (is_loaded_from_file) {
2252
0
          (void) UNLINK(
2253
0
              fconv(OPT_GET_BUFF(opt), OPT_GET_BUFF_SIZE(opt), savename()));
2254
0
          is_loaded_from_file = HTS_FALSE;
2255
0
        }
2256
2257
        /* Detect charset to convert links into proper UTF8 filenames */
2258
0
        detect_page_charset(opt, ptr, &r, HTS_BUF(page_charset));
2259
2260
        /* Info for wrappers */
2261
0
        hts_log_print(opt, LOG_INFO, "engine: check-html: %s%s",
2262
0
                      adr_nologin(opt, urladr()), urlfil());
2263
0
        {
2264
0
          char BIGSTK buff_err_msg[1024];
2265
0
          htsmoduleStruct BIGSTK str;
2266
0
          htsmoduleStructExtended BIGSTK stre;
2267
2268
0
          mirror_module_str(&str, &str_base, buff_err_msg, numero_passe, &r);
2269
          /* NULL when conversion is off, empty when the document declared no
2270
             charset; the parser tells the two apart */
2271
0
          str.page_charset_ = opt->convert_utf8 ? page_charset : NULL;
2272
0
          mirror_module_stre(&stre, &stre_base, &r, &error, &store_errpage);
2273
2274
          /* Parse */
2275
0
          if (htsparse(&str, &stre) != 0) {
2276
0
            retcode = -1;
2277
0
            goto cleanup;
2278
0
          }
2279
0
        }
2280
0
      } else {                              // not parsed: save it as it is
2281
0
        if (strnotempty(savename()) == 0) { // no save path
2282
0
          if (strcmp(urlfil(), "/robots.txt") == 0) // robots.txt
2283
0
            mirror_robots_txt(opt, ptr, &robots, &r);
2284
0
        } else if (!r.is_write) {
2285
          // Not on disk yet: save it, with a readme beside unscanned HTML.
2286
0
          mirror_save_file(opt, ptr, &r, store_errpage);
2287
0
        }
2288
2289
        /* External modules */
2290
0
        mirror_parse_externals(opt, ptr, &str_base, numero_passe, &r);
2291
0
      }
2292
2293
      /* Post-processing */
2294
0
      if (fexist_utf8(savename())) {
2295
0
        usercommand(opt, 0, NULL, savename(), urladr(), urlfil());
2296
0
      }
2297
2298
0
    } // if !error
2299
2300
0
  jump_if_done:
2301
    // libérer les liens
2302
0
    if (r.adr) {
2303
0
      freet(r.adr);
2304
0
      r.adr = NULL;
2305
0
    }                           // libérer la mémoire!
2306
2307
0
    ptr = mirror_next_link(opt, ptr, &numero_passe);
2308
0
  } while(ptr < opt->lien_tot);
2309
2310
  /* Once more, for a worker that faulted after the loop's last check: the
2311
     verdict below and the exit status both read exit_xh. */
2312
0
  back_check_worker_fault(opt);
2313
2314
  /* A stop request cuts the mirror short whether or not the loop ran out of
2315
     links: with one pending, the parser stops queueing the links it finds. */
2316
0
  aborted = hts_load_acquire_int(&opt->state.stop) != 0 ||
2317
0
            hts_load_acquire_int(&opt->state.exit_xh) != 0;
2318
  //
2319
  //
2320
  //
2321
2322
  /*
2323
     Ensure the index is being closed
2324
   */
2325
0
  hts_finish_makeindex(opt, &makeindex_done, &makeindex_fp, makeindex_links,
2326
0
                       makeindex_firstlink, template_footer, "", "");
2327
2328
  /* 
2329
     updating-a-remotely-deteted-website hack
2330
     no much data transferred, no data saved
2331
     <no files successfulyl saved>
2332
     we assume that something was bad (no connection)
2333
     just backup old cache and restore everything
2334
   */
2335
0
  if ((HTS_STAT.stat_files <= 0) &&
2336
0
      (hts_stat_recv_get() < 32768) /* should be fine */
2337
0
  ) {
2338
    /* not a notice: the session is rolled back and the WARC aborted */
2339
0
    hts_log_print(opt, LOG_WARNING,
2340
0
                  "No data seems to have been transferred during this session! "
2341
0
                  ": restoring previous one!");
2342
    /* this run replaces nothing, so its archive must not be committed */
2343
0
    warc_abort_opt(opt);
2344
    /* 2 exits 0, so it must not overwrite an earlier abort, such as a crash on
2345
       the first fetch. */
2346
0
    if (hts_load_acquire_int(&opt->state.exit_xh) != -1) {
2347
      /* interrupted (no connection detected) */
2348
0
      hts_store_release_int(&opt->state.exit_xh, 2);
2349
0
    }
2350
0
    rollback = HTS_TRUE;
2351
0
    goto cleanup;
2352
0
  }
2353
  // info text  
2354
0
  if (cache.txt) {
2355
0
    fclose(cache.txt);
2356
0
    cache.txt = NULL;
2357
0
  }
2358
  // purger!
2359
0
  if (cache.lst) {
2360
0
    fclose(cache.lst);
2361
0
    cache.lst = opt->state.strc.lst = NULL;
2362
    /* old.lst minus new.lst is the set of files the previous mirror had and
2363
       this one does not. --changes reports it; only --purge-old acts on it.
2364
       For a stopped mirror it is mostly what the run never got to. */
2365
0
    if (aborted) {
2366
0
      if (opt->delete_old || opt->changes) {
2367
0
        hts_log_print(opt, LOG_WARNING,
2368
0
                      "Mirror aborted: keeping all previously mirrored files");
2369
0
      }
2370
0
    } else if (opt->delete_old || opt->changes) {
2371
0
      mirror_purge_old(opt);
2372
0
    }
2373
0
  }
2374
  // fin purge!
2375
2376
  /* --single-file: inline each page's assets now the tree is final, after the
2377
     purge has deleted whatever this run dropped. */
2378
0
  singlefile_process_mirror(opt);
2379
2380
  // Indexation
2381
0
  if (opt->kindex != HTS_KINDEX_OFF)
2382
0
    index_finish(StringBuff(opt->path_html), opt->kindex);
2383
2384
0
  if (opt->log != NULL)
2385
0
    mirror_log_summary(opt, aborted, &cache);
2386
2387
  // ending
2388
0
  usercommand(opt, 0, NULL, NULL, NULL, NULL);
2389
0
  completed = !aborted;
2390
2391
0
cleanup:
2392
  /* single exit: every bailout jumps here, so the closes below always run */
2393
  /* the summary above is skipped by every bailout, so the note goes here */
2394
0
  if (opt->log != NULL) {
2395
0
    char BIGSTK upperNote[256];
2396
2397
0
    if (hts_upper_links_note(opt, HTS_BUF(upperNote)))
2398
0
      fprintf(opt->log, "(%s)" LF, upperNote);
2399
0
  }
2400
  /* Set the verdict first, because XH_uninit below fires the end callback that
2401
     reads it. Nothing below this label assigns `completed`. */
2402
0
  set_mirror_completed(opt, completed_out, completed);
2403
0
  warc_close_opt(opt); /* a no-op once warc_abort_opt() has run */
2404
  /* An abort never ran hts_changes_indexed(), so its report would be false;
2405
     free it rather than overwrite the previous run's true one. */
2406
0
  if (completed)
2407
0
    hts_changes_close_opt(opt);
2408
0
  else
2409
0
    hts_changes_free_opt(opt);
2410
0
  hts_sitemap_free(opt);
2411
0
  url_savename_refnames_free(opt);
2412
2413
  // désallocation mémoire & buffers
2414
0
  freet(primary); /* NULL once the first link adopted it */
2415
0
  XH_uninit;
2416
  /* reconcile renames the cache files XH_uninit just closed, so it runs last */
2417
0
  if (rollback)
2418
0
    hts_cache_reconcile(opt, CACHE_RECONCILE_ROLLBACK);
2419
2420
0
  return retcode;
2421
0
}
2422
2423
// version 2 pour le reste
2424
2425
// Estimate transfer rate
2426
// a little bit complex, but not too much
2427
/*
2428
  .. : idle
2429
  ^  : event
2430
2431
  ----|----|----|----|----|----|----|----|---->
2432
   1    2    3    4    5    6    7    8    9   time (seconds)
2433
  ----|----|----|----|----|----|----|----|---->
2434
  ^........^.........^.........^.........^.... timer 0
2435
  ----^.........^.........^.........^......... timer 1
2436
           0    1    0    1    0    1    0     timer N sets its statistics
2437
      *         *         *         *          timer 0 resync timer 1
2438
2439
  Therefore, each seconds, we resync the transfer rate with 2-seconds
2440
2441
*/
2442
0
static void engine_stats_reset_counters(void) {
2443
0
  HTS_STAT.stat_nsocket = HTS_STAT.stat_errors = HTS_STAT.nbk = 0;
2444
0
  HTS_STAT.nb = 0;
2445
0
}
2446
2447
0
static hts_boolean engine_stats(void) {
2448
0
  const LLint recv = hts_stat_recv_publish();
2449
2450
0
  engine_stats_reset_counters();
2451
0
  if (recv > 2048) {
2452
0
    TStamp cdif = mtime_monotonic();
2453
0
    int i;
2454
2455
0
    for(i = 0; i < 2; i++) {
2456
0
      if ((cdif - HTS_STAT.istat_timestart[i]) >= 2000) {
2457
0
        TStamp dif;
2458
2459
0
        dif = cdif - HTS_STAT.istat_timestart[i];
2460
0
        if ((TStamp) (dif / 1000) > 0) {
2461
0
          LLint byt = (recv - HTS_STAT.istat_bytes[i]);
2462
2463
0
          HTS_STAT.rate = (LLint) ((TStamp) ((TStamp) byt / (dif / 1000)));
2464
0
          HTS_STAT.istat_idlasttimer = i;       // this timer recently sets the stats
2465
          //
2466
0
          HTS_STAT.istat_bytes[i] = recv;
2467
0
          HTS_STAT.istat_timestart[i] = cdif;
2468
0
        }
2469
0
        return HTS_TRUE; /* refreshed */
2470
0
      }
2471
0
    }
2472
2473
    // resynchronization between timer 0 (master) and 1 (slave)
2474
    // timer #0 resync timer #1 when reaching 1 second limit
2475
0
    if (HTS_STAT.istat_reference01 != HTS_STAT.istat_timestart[0]) {
2476
0
      if ((cdif - HTS_STAT.istat_timestart[0]) >= 1000) {
2477
0
        HTS_STAT.istat_bytes[1] = recv;
2478
0
        HTS_STAT.istat_timestart[1] = cdif;
2479
0
        HTS_STAT.istat_reference01 = HTS_STAT.istat_timestart[0];
2480
0
      }
2481
0
    }
2482
0
  }
2483
0
  return HTS_FALSE;
2484
0
}
2485
2486
0
hts_boolean engine_stats_tick(unsigned int *calls) {
2487
0
  if ((*calls)++ % HTS_STATS_TICK == 0)
2488
0
    return engine_stats();
2489
0
  engine_stats_reset_counters();
2490
0
  return HTS_FALSE;
2491
0
}
2492
2493
#define _FILTERS     (*opt->filters.filters)
2494
0
#define _FILTERS_PTR (opt->filters.filptr)
2495
#define _ROBOTS      ((robots_wizard*)opt->robotsptr)
2496
2497
// bannir host (trop lent etc)
2498
void host_ban(httrackp * opt, int ptr,
2499
0
              struct_back * sback, const char *host) {
2500
0
  lien_back *const back = sback->lnk;
2501
0
  const int back_max = sback->count;
2502
2503
0
  int i;
2504
2505
0
  if (host[0] == '!')
2506
0
    return;                     // erreur.. déja cancellé.. bizarre.. devrait pas arriver
2507
2508
0
  filters_make_room(opt, 1);
2509
  // ban the host
2510
0
  assertf((*_FILTERS_PTR) < opt->maxfilter);
2511
0
  if (*_FILTERS_PTR < opt->maxfilter) {
2512
0
    char BIGSTK rule[HTS_FILTER_SLOT_SIZE + 4];
2513
0
    htsbuff fb = htsbuff_array(rule);
2514
2515
0
    htsbuff_cpy(&fb, "-");
2516
0
    htsbuff_cat(&fb, host);
2517
0
    htsbuff_cat(&fb, "/*"); // forbid host/*
2518
0
    (void) !filters_insert(opt, *_FILTERS_PTR, rule); // it logs a drop
2519
0
  }
2520
  // oups
2521
0
  if (strlen(host) <= 1) {      // euhh?? longueur <= 1
2522
0
    if (strcmp(host, "file://")) {
2523
      //## if (host[0]!=lOCAL_CHAR) {  // pas local
2524
0
      hts_log_print(opt, LOG_PANIC,
2525
0
                    "PANIC! HostCancel detected memory leaks [char %d]",
2526
0
                    host[0]);
2527
0
      return;                   // purée
2528
0
    }
2529
0
  }
2530
  // couper connexion
2531
0
  for(i = 0; i < back_max; i++) {
2532
0
    if (back_holds_transfer(&back[i]))
2533
      /* host is a bare name and an FTP url_adr keeps its scheme, so no FTP slot
2534
         matches here, and none may, because its worker is still writing it. */
2535
0
      if (hts_streq_ci(back[i].url_adr, host)) {
2536
0
        back[i].status = 0;     // terminé
2537
0
        back_set_finished(opt, sback, i);
2538
0
        if (back[i].r.soc != INVALID_SOCKET)
2539
0
          deletehttp(&back[i].r);
2540
0
        back[i].r.soc = INVALID_SOCKET;
2541
0
        back[i].r.statuscode = STATUSCODE_TIMEOUT;      // timeout (peu importe si c'est un traffic jam)
2542
0
        strcpybuff(back[i].r.msg, "Link Cancelled by host control");
2543
0
        hts_log_print(opt, LOG_DEBUG, "Shutdown: %s%s",
2544
0
                      adr_nologin(opt, back[i].url_adr), back[i].url_fil);
2545
0
      }
2546
0
  }
2547
2548
  // cancel the host's links, whatever their address length
2549
0
  for (i = 0; i < opt->lien_tot; i++) {
2550
0
    if (hts_streq_ci(jump_identification_const(heap(i)->adr), host)) {
2551
0
      hts_log_print(opt, LOG_DEBUG, "Cancel: %s%s",
2552
0
                    adr_nologin(opt, heap(i)->adr), heap(i)->fil);
2553
      // keep the hash entry, so meeting the link again re-checks its save name
2554
0
      hts_invalidate_link(opt, i);
2555
0
    }
2556
0
  }
2557
0
}
2558
2559
0
hts_boolean filters_may_grow(int maxfilter) {
2560
0
  return maxfilter <= HTS_FILTERS_MAX;
2561
0
}
2562
2563
0
hts_boolean filters_grow(httrackp *opt, int n) {
2564
0
  if (*opt->filters.filptr + n >= opt->maxfilter &&
2565
0
      filters_may_grow(opt->maxfilter)) {
2566
0
    if (filters_init(opt->filters.filters, opt->maxfilter + HTS_FILTERSINC,
2567
0
                     HTS_FILTERSINC) == 0) {
2568
0
      printf("PANIC! : Too many filters : >%d [%d]\n", *opt->filters.filptr,
2569
0
             __LINE__);
2570
0
      fflush(stdout);
2571
0
      hts_log_print(opt, LOG_PANIC, "Too many filters, giving up..(>%d)",
2572
0
                    *opt->filters.filptr);
2573
0
      hts_log_print(
2574
0
          opt, LOG_INFO,
2575
0
          "To avoid that: use #F option for more filters (example: -#F5000)");
2576
0
      return HTS_FALSE;
2577
0
    }
2578
0
    opt->maxfilter += HTS_FILTERSINC;
2579
0
  }
2580
0
  return HTS_TRUE;
2581
0
}
2582
2583
0
void filters_make_room(httrackp *opt, int n) {
2584
0
  if (!filters_grow(opt, n))
2585
0
    assertf("too many filters - giving up" == NULL);
2586
0
}
2587
2588
void hts_url_forms(htsbuff *nologin, htsbuff *full, const char *adr,
2589
0
                   const char *fil) {
2590
0
  htsbuff_cpy(nologin, jump_identification_const(adr));
2591
0
  if (*fil != '/')
2592
0
    htsbuff_cat(nologin, "/");
2593
0
  htsbuff_cat(nologin, fil);
2594
0
  htsbuff_cpy(full, link_has_authority(adr) ? "" : "http://");
2595
0
  htsbuff_cat(full, adr);
2596
0
  if (*fil != '/')
2597
0
    htsbuff_cat(full, "/");
2598
0
  htsbuff_cat(full, fil);
2599
0
}
2600
2601
int filters_match_url(char **filters, int nfil, const char *adr,
2602
0
                      const char *fil, int *depth) {
2603
  /* adr and fil each come from a HTS_URLMAXSIZE * 2 array */
2604
0
  char BIGSTK l[HTS_URLMAXSIZE * 4 + 16], lfull[HTS_URLMAXSIZE * 4 + 16];
2605
0
  htsbuff lb = htsbuff_array(l), fb = htsbuff_array(lfull);
2606
2607
0
  hts_url_forms(&lb, &fb, adr, fil);
2608
0
  return fa_strjoker_dual(HTS_JOKER_URL, filters, nfil, lfull, l, NULL, NULL,
2609
0
                          depth);
2610
0
}
2611
2612
/* Does the whole rule array refuse queued link lpos? Sets *rule, if not NULL,
2613
   to the index of the rule that decides. */
2614
0
static hts_boolean queued_link_refused_(httrackp *opt, int lpos, int *rule) {
2615
0
  const lien_url *const link = heap(lpos);
2616
2617
  /* robots.txt is never filtered, as at startup */
2618
0
  return link->pass2 != -1 && strcmp(link->fil, "/robots.txt") != 0 &&
2619
0
         filters_match_url(*opt->filters.filters, *opt->filters.filptr,
2620
0
                           link->adr, link->fil, rule) == -1;
2621
0
}
2622
2623
/* Insert rule at the end of the user's rules. */
2624
0
static hts_boolean filters_append_user_(httrackp *opt, const char *rule) {
2625
0
  filters_make_room(opt, 1);
2626
0
  if (!filters_insert(opt, opt->wizard_filters + opt->user_filters, rule))
2627
0
    return HTS_FALSE;
2628
0
  opt->user_filters++;
2629
0
  return HTS_TRUE;
2630
0
}
2631
2632
/* Cancel queued link i, unless its transfer has started or it is written to
2633
   disk already. Returns HTS_TRUE if it was cancelled. */
2634
0
static hts_boolean live_cancel_link_(httrackp *opt, struct_back *sback, int i) {
2635
0
  int b = back_index_peek(opt, sback, heap(i)->adr, heap(i)->fil, heap(i)->sav);
2636
2637
  /* load a stored result only if a slot is free */
2638
0
  if (b == sback->count) {
2639
0
    if (back_search_quick(sback) < 0)
2640
0
      return HTS_FALSE;
2641
0
    b = back_index(opt, sback, heap(i)->adr, heap(i)->fil, heap(i)->sav);
2642
0
  }
2643
0
  if (b >= 0) {
2644
0
    const lien_back *const slot = &sback->lnk[b];
2645
2646
    /* the sav test rejects a slot matched on adr and fil alone */
2647
0
    if (back_status(slot) != STATUS_READY || slot->r.is_write ||
2648
0
        slot->testmode || strcmp(slot->url_sav, heap(i)->sav) != 0)
2649
0
      return HTS_FALSE;
2650
    /* no cache: a dropped page must not be recorded as fetched */
2651
0
    back_delete(opt, NULL, sback, b);
2652
0
  }
2653
0
  hts_log_print(opt, LOG_DEBUG, "Cancel: %s%s", adr_nologin(opt, heap(i)->adr),
2654
0
                heap(i)->fil);
2655
0
  hts_invalidate_link(opt, i);
2656
  /* the main loop takes every cancelled link out of this count */
2657
0
  HTS_STAT.stat_background++;
2658
0
  return HTS_TRUE;
2659
0
}
2660
2661
/* Is rule index r one this change brought in? A rule of a set that the old
2662
   user rules already held is not, so resending it drops nothing. */
2663
static hts_boolean live_rule_is_new_(httrackp *opt, int r, int first_new,
2664
0
                                     int first_add, char **old) {
2665
0
  const char *const rule = (*opt->filters.filters)[r];
2666
0
  size_t k;
2667
2668
0
  if (r < first_new || r >= opt->wizard_filters + opt->user_filters)
2669
0
    return HTS_FALSE;
2670
0
  if (r >= first_add)
2671
0
    return HTS_TRUE;
2672
  /* without the old rules, keep the link rather than guess */
2673
0
  for (k = 0; old != NULL && old[k] != NULL; k++) {
2674
0
    if (strcmp(old[k], rule) == 0)
2675
0
      return HTS_FALSE;
2676
0
  }
2677
0
  return old != NULL;
2678
0
}
2679
2680
0
void hts_apply_live_filters(httrackp *opt, struct_back *sback, int ptr) {
2681
0
  char **set, **rules, **old = NULL;
2682
0
  hts_boolean *was_refused = NULL;
2683
0
  const int queued = opt->lien_tot - (ptr + 1);
2684
0
  int added = 0, dropped = 0, first_new, first_add, i;
2685
0
  size_t k;
2686
2687
  /* take both under one lock, so a set lands before later adds */
2688
0
  hts_mutexlock(&opt->state.lock);
2689
0
  set = opt->live_filters_set;
2690
0
  opt->live_filters_set = NULL;
2691
0
  rules = opt->live_filters;
2692
0
  opt->live_filters = NULL;
2693
0
  hts_mutexrelease(&opt->state.lock);
2694
0
  if (set == NULL && rules == NULL)
2695
0
    return;
2696
  /* A start URL, added URL or +mime: accept may sit queued though the rules
2697
     refuse it. Only a new rule may drop it. ptr is being fetched or parsed. */
2698
0
  if (queued > 0) {
2699
0
    was_refused = calloct(queued, sizeof(*was_refused));
2700
0
    if (was_refused == NULL)
2701
0
      hts_log_print(opt, LOG_WARNING, "No memory to drop queued links");
2702
0
    for (i = 0; was_refused != NULL && i < queued; i++)
2703
0
      was_refused[i] = queued_link_refused_(opt, ptr + 1 + i, NULL);
2704
0
  }
2705
  /* the rules this change inserts end the user's rules */
2706
0
  first_new = opt->wizard_filters + (set != NULL ? 0 : opt->user_filters);
2707
0
  if (set != NULL) {
2708
    /* old user rules tell a resent rule from a new one */
2709
0
    old = (char **) calloct(opt->user_filters + 1, sizeof(char *));
2710
0
    for (i = 0; old != NULL && i < opt->user_filters; i++) {
2711
0
      old[i] = strdupt((*opt->filters.filters)[opt->wizard_filters + i]);
2712
0
      if (old[i] == NULL) {
2713
0
        hts_addurl_free(old); /* NULL-terminated, as calloct zeroed it */
2714
0
        old = NULL;
2715
0
      }
2716
0
    }
2717
0
    filters_remove(opt, opt->wizard_filters, opt->user_filters);
2718
0
    opt->user_filters = 0;
2719
0
    for (k = 0; set[k] != NULL; k++)
2720
0
      filters_append_user_(opt, set[k]);
2721
0
  }
2722
0
  first_add = opt->wizard_filters + opt->user_filters;
2723
0
  for (k = 0; rules != NULL && rules[k] != NULL; k++) {
2724
0
    if (filters_append_user_(opt, rules[k])) {
2725
0
      hts_log_print(opt, LOG_NOTICE, "Scan rule added by user: %s", rules[k]);
2726
0
      added++;
2727
0
    }
2728
0
  }
2729
0
  hts_addurl_free(set); /* frees any NULL-terminated string list */
2730
0
  hts_addurl_free(rules);
2731
0
  for (i = 0; was_refused != NULL && i < queued; i++) {
2732
0
    int rule = 0;
2733
2734
0
    if (queued_link_refused_(opt, ptr + 1 + i, &rule) &&
2735
0
        (!was_refused[i] ||
2736
0
         live_rule_is_new_(opt, rule, first_new, first_add, old)) &&
2737
0
        live_cancel_link_(opt, sback, ptr + 1 + i))
2738
0
      dropped++;
2739
0
  }
2740
0
  freet(was_refused);
2741
0
  hts_addurl_free(old);
2742
0
  if (set != NULL)
2743
0
    hts_log_print(opt, LOG_NOTICE,
2744
0
                  "%d scan rule(s) set and %d added by user, %d queued link(s) "
2745
0
                  "dropped",
2746
0
                  opt->user_filters - added, added, dropped);
2747
0
  else
2748
0
    hts_log_print(opt, LOG_NOTICE,
2749
0
                  "%d scan rule(s) added by user, %d queued link(s) dropped",
2750
0
                  added, dropped);
2751
0
}
2752
2753
0
void filters_bind(httrackp *opt, char ***ptrfilters, int *filptr) {
2754
0
  opt->filters.filters = ptrfilters;
2755
0
  opt->filters.filptr = filptr;
2756
0
  opt->wizard_filters = 0;
2757
0
  opt->user_filters = 0;
2758
0
}
2759
2760
/* A rule must fit both a slot and strjoker(), whatever the two caps become. */
2761
enum {
2762
  hts_filter_maxlen_matches = 1 / (HTS_FILTER_MAXLEN <= STRJOKER_MAXLEN),
2763
  hts_filter_maxlen_fits = 1 / (HTS_FILTER_MAXLEN < HTS_FILTER_SLOT_SIZE)
2764
};
2765
2766
0
hts_boolean filters_insert(httrackp *opt, int pos, const char *pattern) {
2767
0
  char **const filters = *opt->filters.filters;
2768
0
  const size_t len = strlen(pattern);
2769
0
  int i;
2770
2771
0
  assertf(pos >= 0 && pos <= *opt->filters.filptr);
2772
0
  if (len > HTS_FILTER_MAXLEN) {
2773
0
    hts_log_print(opt, LOG_WARNING,
2774
0
                  "Filter rule dropped: %d bytes is past the %d-byte limit, so "
2775
0
                  "it could never match: %s",
2776
0
                  (int) len, (int) HTS_FILTER_MAXLEN, pattern);
2777
0
    return HTS_FALSE;
2778
0
  }
2779
0
  if (*opt->filters.filptr + 1 >= opt->maxfilter) {
2780
0
    hts_log_print(
2781
0
        opt, LOG_WARNING,
2782
0
        "Filter rule dropped: the filter list is full at %d rules: %s",
2783
0
        *opt->filters.filptr, pattern);
2784
0
    return HTS_FALSE;
2785
0
  }
2786
0
  for (i = *opt->filters.filptr; i > pos; i--)
2787
0
    strlcpybuff(filters[i], filters[i - 1], HTS_FILTER_SLOT_SIZE);
2788
0
  strlcpybuff(filters[pos], pattern, HTS_FILTER_SLOT_SIZE);
2789
0
  (*opt->filters.filptr)++;
2790
0
  assertf((*opt->filters.filptr) < opt->maxfilter);
2791
0
  return HTS_TRUE;
2792
0
}
2793
2794
0
void filters_remove(httrackp *opt, int pos, int n) {
2795
0
  char **const filters = *opt->filters.filters;
2796
0
  int i;
2797
2798
0
  assertf(pos >= 0 && n >= 0 && n <= *opt->filters.filptr - pos);
2799
  /* copying a slot onto itself would empty it */
2800
0
  if (n == 0)
2801
0
    return;
2802
0
  for (i = pos; i + n < *opt->filters.filptr; i++)
2803
0
    strlcpybuff(filters[i], filters[i + n], HTS_FILTER_SLOT_SIZE);
2804
0
  *opt->filters.filptr -= n;
2805
0
}
2806
2807
0
int filters_init(char ***ptrfilters, int maxfilter, int filterinc) {
2808
0
  char **filters = *ptrfilters;
2809
0
  int filter_max = hts_max_int(maxfilter, 128);
2810
0
  int i;
2811
2812
0
  if (filters == NULL) {
2813
0
    filters = (char **) calloct(filter_max + 2, sizeof(char *));
2814
0
    if (filters == NULL)
2815
0
      return 0;
2816
0
    filters[0] = (char *) calloct(filter_max + 2, HTS_FILTER_SLOT_SIZE);
2817
0
    if (filters[0] == NULL) {
2818
0
      freet(filters);
2819
0
      return 0;
2820
0
    }
2821
0
  } else {
2822
0
    char **const grown =
2823
0
        (char **) realloct(filters, sizeof(char *) * (filter_max + 2));
2824
0
    char *slots;
2825
2826
0
    if (grown == NULL)
2827
0
      return 0;
2828
0
    filters = grown;
2829
0
    *ptrfilters = filters;
2830
0
    slots = (char *) realloct(filters[0],
2831
0
                              (size_t) (filter_max + 2) * HTS_FILTER_SLOT_SIZE);
2832
    // The old slots and their pointers stay valid, so the list is unchanged.
2833
0
    if (slots == NULL)
2834
0
      return 0;
2835
0
    filters[0] = slots;
2836
0
  }
2837
  // Slot filter_max is the guard.
2838
0
  for (i = 0; i <= filter_max; i++)
2839
0
    filters[i] = filters[0] + (size_t) i * HTS_FILTER_SLOT_SIZE;
2840
0
  for (i = filterinc == 0 || filterinc > filter_max ? 0
2841
0
                                                    : filter_max - filterinc;
2842
0
       i <= filter_max; i++)
2843
0
    filters[i][0] = '\0';
2844
0
  *ptrfilters = filters;
2845
0
  return filter_max;
2846
0
}
2847
2848
0
static int mkdir_compat(const char *pathname) {
2849
#ifdef _WIN32
2850
  return mkdir(pathname);
2851
#else
2852
0
  return mkdir(pathname, HTS_ACCESS_FOLDER);
2853
0
#endif
2854
0
}
2855
2856
/* path must end with "/" or with the finename (/tmp/bar/ or /tmp/bar/foo.zip) */
2857
/* Note: preserve errno */
2858
0
hts_boolean dir_exists(const char *path) {
2859
0
  const int err = errno;
2860
0
  STRUCT_STAT st;
2861
0
  char BIGSTK file[HTS_URLMAXSIZE * 2];
2862
0
  int i = 0;
2863
2864
0
  if (strnotempty(path) == 0) {
2865
0
    return 0;
2866
0
  }
2867
0
  if (strlen(path) > HTS_URLMAXSIZE) {
2868
0
    return 0;
2869
0
  }
2870
2871
  /* Get a copy */
2872
0
  strcpybuff(file, path);
2873
#ifdef _WIN32
2874
  /* To system name */
2875
  for(i = 0; file[i] != 0; i++) {
2876
    if (file[i] == '/') {
2877
      file[i] = PATH_SEPARATOR;
2878
    }
2879
  }
2880
#endif
2881
  /* Get prefix (note: file can not be empty here) */
2882
0
  for(i = (int) strlen(file) - 1; i > 0 && file[i] != PATH_SEPARATOR; i--) ;
2883
0
  for(; i > 0 && file[i] == PATH_SEPARATOR; i--) ;
2884
0
  file[i + 1] = '\0';
2885
2886
  /* Check the final dir */
2887
0
  if (STAT(file, &st) == 0 && S_ISDIR(st.st_mode)) {
2888
0
    return 1;                   /* EXISTS */
2889
0
  }
2890
0
  errno = err;
2891
0
  return 0;                     /* DOES NOT EXIST */
2892
0
}
2893
2894
/* Is there something at file? Sets *mode to its st_mode when there is. */
2895
static hts_boolean structcheck_stat(const char *file, hts_boolean utf8,
2896
0
                                    int *mode) {
2897
0
  STRUCT_STAT st;
2898
0
  struct stat st_ansi;
2899
2900
0
  if (utf8 ? STAT(file, &st) != 0 : stat(file, &st_ansi) != 0)
2901
0
    return HTS_FALSE;
2902
0
  *mode = (int) (utf8 ? st.st_mode : st_ansi.st_mode);
2903
0
  return HTS_TRUE;
2904
0
}
2905
2906
/* Finds a free "<file>.txt" or "<file>.N.txt"; sets errno when none fits. */
2907
static hts_boolean structcheck_aside(hts_buf aside, const char *file,
2908
0
                                     hts_boolean utf8) {
2909
0
  int i;
2910
2911
0
  for (i = 0; i < 100; i++) {
2912
0
    int mode;
2913
2914
0
    if (!(i == 0 ? hts_buf_printf(aside, "%s.txt", file)
2915
0
                 : hts_buf_printf(aside, "%s.%d.txt", file, i))) {
2916
0
      errno = ENAMETOOLONG;
2917
0
      return HTS_FALSE;
2918
0
    }
2919
0
    if (!structcheck_stat(aside.p, utf8, &mode))
2920
0
      return HTS_TRUE;
2921
0
  }
2922
0
  errno = EEXIST;
2923
0
  return HTS_FALSE;
2924
0
}
2925
2926
0
static int structcheck_mkdir(const char *file, hts_boolean utf8) {
2927
0
  return utf8 ? MKDIR(file) : mkdir_compat(file);
2928
0
}
2929
2930
/* path ends with "/" or a file name. utf8 selects UTF-8 calls over ANSI. */
2931
0
static int structcheck_impl(const char *path, hts_boolean utf8) {
2932
0
  int mode;
2933
0
  char BIGSTK tmpbuf[HTS_URLMAXSIZE * 2];
2934
0
  char BIGSTK file[HTS_URLMAXSIZE * 2];
2935
0
  int i = 0;
2936
0
  size_t top;
2937
2938
0
  if (strnotempty(path) == 0)
2939
0
    return 0;
2940
0
  if (strlen(path) > HTS_URLMAXSIZE) {
2941
0
    errno = EINVAL;
2942
0
    return -1;
2943
0
  }
2944
2945
  /* Get a copy */
2946
0
  strcpybuff(file, path);
2947
#ifdef _WIN32
2948
  /* To system name */
2949
  for(i = 0; file[i] != 0; i++) {
2950
    if (file[i] == '/') {
2951
      file[i] = PATH_SEPARATOR;
2952
    }
2953
  }
2954
#endif
2955
  /* Get prefix (note: file can not be empty here) */
2956
0
  for(i = (int) strlen(file) - 1; i > 0 && file[i] != PATH_SEPARATOR; i--) ;
2957
0
  if (file[i] != PATH_SEPARATOR) /* a bare file name has no directory */
2958
0
    return 0;
2959
0
  for(; i > 0 && file[i] == PATH_SEPARATOR; i--) ;
2960
0
  file[i + 1] = '\0';
2961
2962
  /* First check the final dir */
2963
0
  if (structcheck_stat(file, utf8, &mode) && S_ISDIR(mode)) {
2964
0
    return 0;                   /* OK */
2965
0
  }
2966
2967
  /* Start from the beginning */
2968
0
  i = 0;
2969
2970
  /* Skip irrelevant part (the root slash, or the drive path) */
2971
#ifdef _WIN32
2972
  if (file[0] != 0 && file[1] == ':') { /* f:\ */
2973
    i += 2;
2974
    if (file[i] == PATH_SEPARATOR) {    /* f:\ */
2975
      i++;
2976
    }
2977
  } else if (file[0] == PATH_SEPARATOR && file[1] == PATH_SEPARATOR) {  /* \\mch */
2978
    int j;
2979
2980
    i += 2;
2981
    // skip machine and first dir (share) or we'll have troubles (TomZ)
2982
    for(j = 0; j < 2; j++) {
2983
      // skip segment
2984
      for(; file[i] != '\0' && file[i] != PATH_SEPARATOR; i++) ;
2985
      // skip final separator
2986
      if (file[i] == PATH_SEPARATOR) {  /* f:\ */
2987
        i++;
2988
      }
2989
    }
2990
  }
2991
#endif
2992
2993
  /* Start the walk at the deepest existing component, not the root. */
2994
0
  for (top = strlen(file);;) {
2995
0
    size_t cut = top;
2996
0
    hts_boolean exists;
2997
2998
0
    while (cut > (size_t) i && file[cut - 1] != PATH_SEPARATOR)
2999
0
      cut--;
3000
0
    while (cut > (size_t) i && file[cut - 1] == PATH_SEPARATOR)
3001
0
      cut--;
3002
0
    if (cut <= (size_t) i)
3003
0
      break;
3004
0
    file[cut] = '\0';
3005
0
    exists = structcheck_stat(file, utf8, &mode);
3006
0
    file[cut] = PATH_SEPARATOR;
3007
0
    if (exists) {
3008
      /* walk a file again so it gets moved aside */
3009
0
      if (!S_ISDIR(mode))
3010
0
        while (cut > (size_t) i && file[cut - 1] != PATH_SEPARATOR)
3011
0
          cut--;
3012
0
      i = (int) cut;
3013
0
      break;
3014
0
    }
3015
0
    top = cut;
3016
0
  }
3017
3018
  /* Check paths */
3019
0
  for (;;) {
3020
0
    char end_char;
3021
3022
    /* Go to next path */
3023
3024
    /* Skip separator(s) */
3025
0
    for(; file[i] == PATH_SEPARATOR; i++) ;
3026
    /* Next separator */
3027
0
    for(; file[i] != 0 && file[i] != PATH_SEPARATOR; i++) ;
3028
3029
    /* Check */
3030
0
    end_char = file[i];
3031
0
    if (end_char != 0) {
3032
0
      file[i] = '\0';
3033
0
    }
3034
0
    if (structcheck_stat(file, utf8, &mode)) {
3035
0
      if (!S_ISDIR(mode)) {
3036
0
#if HTS_REMOVE_ANNOYING_INDEX
3037
        /* Regular file in place: move it and create directory */
3038
0
        if (S_ISREG(mode)) {
3039
          /* the path-length guard above does not bound this */
3040
0
          if (!structcheck_aside(HTS_BUF(tmpbuf), file, utf8))
3041
0
            return -1;
3042
0
          if ((utf8 ? RENAME(file, tmpbuf) : rename(file, tmpbuf)) != 0) {
3043
0
            return -1;
3044
0
          }
3045
0
          if (structcheck_mkdir(file, utf8) != 0) { /* Can't create directory */
3046
0
            return -1;
3047
0
          }
3048
0
        }
3049
#else
3050
#error Not implemented
3051
#endif
3052
0
      }
3053
0
    } else { /* Nothing exists ; create directory */
3054
0
      if (structcheck_mkdir(file, utf8) != 0) { /* Can't create directory */
3055
0
        return -1;
3056
0
      }
3057
0
    }
3058
0
    if (end_char == 0) {        /* End */
3059
0
      break;
3060
0
    } else {
3061
0
      file[i] = end_char;       /* Restore / */
3062
0
    }
3063
0
  }
3064
0
  return 0;
3065
0
}
3066
3067
/* path is ANSI. */
3068
0
HTSEXT_API int structcheck(const char *path) {
3069
0
  return structcheck_impl(path, HTS_FALSE);
3070
0
}
3071
3072
/* Note: UTF-8 */
3073
0
HTSEXT_API int structcheck_utf8(const char *path) {
3074
0
  return structcheck_impl(path, HTS_TRUE);
3075
0
}
3076
3077
/* Save body as s: 0 on success, -1 with errno set on failure. */
3078
int filesave(httrackp *opt, hts_span body, const char *s, const char *url_adr,
3079
0
             const char *url_fil) {
3080
0
  FILE *const fp = filecreate(&opt->state.strc, s);
3081
3082
0
  if (fp == NULL)
3083
0
    return -1;
3084
0
  return hts_write_and_close(fp, body) ? 0 : -1;
3085
0
}
3086
3087
/* We should stop */
3088
0
int check_fatal_io_errno(void) {
3089
0
  switch (errno) {
3090
0
#ifdef EMFILE
3091
0
  case EMFILE:                 /* Too many open files */
3092
0
#endif
3093
0
#ifdef ENOSPC
3094
0
  case ENOSPC:                 /* No space left on device */
3095
0
#endif
3096
0
#ifdef EROFS
3097
0
  case EROFS:                  /* Read-only file system */
3098
0
#endif
3099
0
#ifdef EDQUOT
3100
0
  case EDQUOT: /* Disk quota exceeded */
3101
0
#endif
3102
0
    return 1;
3103
0
    break;
3104
0
  }
3105
0
  return 0;
3106
0
}
3107
3108
0
void hts_io_fatal_abort(httrackp *opt) {
3109
0
  hts_log_print(opt, LOG_ERROR,
3110
0
                "Mirror aborted: disk full or filesystem problems");
3111
0
  hts_store_release_int(&opt->state.exit_xh, -1);
3112
0
}
3113
3114
/* Create the UTF-8 '/'-separated file s for writing, and list it in strc. An
3115
   over-long s fails to open rather than aborting. */
3116
0
FILE *filecreate(filenote_strc * strc, const char *s) {
3117
0
  char BIGSTK fname[HTS_URLMAXSIZE * 2];
3118
0
  FILE *fp;
3119
0
  int last_errno = 0;
3120
3121
0
  if (strc != NULL) {
3122
0
    filenote(strc, s, NULL);
3123
0
  }
3124
0
  fconv(fname, sizeof(fname), s);
3125
3126
  /* Try to open the file */
3127
0
  fp = FOPEN(fname, "wb");
3128
3129
  /* Error ? Check the directory structure and retry. */
3130
0
  if (fp == NULL) {
3131
0
    last_errno = errno;
3132
0
    if (structcheck_utf8(s) != 0) {
3133
0
      last_errno = errno;
3134
0
    } else {
3135
0
      last_errno = 0;
3136
0
    }
3137
0
    fp = FOPEN(fname, "wb");
3138
0
  }
3139
0
  if (fp == NULL && last_errno != 0) {
3140
0
    errno = last_errno;
3141
0
  }
3142
0
#ifndef _WIN32
3143
  /* fchmod, because a symlinked name would chmod its target */
3144
0
  if (fp != NULL)
3145
0
    (void) fchmod(fileno(fp), HTS_ACCESS_FILE);
3146
0
#endif
3147
0
  return fp;
3148
0
}
3149
3150
/* Open the '/'-separated file s for appending, and list it in strc. */
3151
0
FILE *fileappend(filenote_strc * strc, const char *s) {
3152
0
  char BIGSTK fname[HTS_URLMAXSIZE * 2];
3153
0
  FILE *fp;
3154
3155
0
  filenote(strc, s, NULL);
3156
0
  fconv(fname, sizeof(fname), s);
3157
0
  fp = FOPEN(fname, "ab");
3158
3159
0
#ifndef _WIN32
3160
0
  if (fp != NULL)
3161
0
    (void) fchmod(fileno(fp), HTS_ACCESS_FILE);
3162
0
#endif
3163
3164
0
  return fp;
3165
0
}
3166
3167
// create an empty file
3168
0
int filecreateempty(filenote_strc * strc, const char *filename) {
3169
0
  FILE *fp;
3170
3171
0
  fp = filecreate(strc, filename);      // filenote & co
3172
0
  if (fp) {
3173
0
    fclose(fp);
3174
0
    return 1;
3175
0
  } else
3176
0
    return 0;
3177
0
}
3178
3179
0
void hts_savename_listed(const char *root, const char *s, hts_buf dest) {
3180
0
  char catbuff[CATBUFF_SIZE];
3181
3182
0
  hts_buf_cpy(dest, fslash(HTS_BUF(catbuff), s));
3183
0
  if (strnotempty(root) &&
3184
0
      strncmp(fslash(HTS_BUF(catbuff), root), dest.p, strlen(root)) == 0) {
3185
0
    hts_buf_cpy(dest, s + strlen(root));
3186
0
  }
3187
0
}
3188
3189
// noter fichier
3190
0
void filenote(filenote_strc *strc, const char *s, filecreate_params *params) {
3191
0
  if (params) {
3192
0
    strcpybuff(strc->path, params->path);
3193
0
    strc->lst = params->lst;
3194
0
  } else if (strc->lst) {
3195
0
    char BIGSTK savelst[HTS_URLMAXSIZE * 2];
3196
3197
0
    hts_savename_listed(strc->path, s, HTS_BUF(savelst));
3198
0
    fprintf(strc->lst, "[%s]" LF, savelst);
3199
0
    fflush(strc->lst);
3200
0
  }
3201
0
}
3202
3203
/* Note: utf-8 */
3204
void file_notify(httrackp * opt, const char *adr, const char *fil,
3205
0
                 const char *save, int create, int modify, int not_updated) {
3206
0
  hts_changes_notify(opt, adr, fil, save,
3207
0
                     (create || modify) ? HTS_TRUE : HTS_FALSE,
3208
0
                     not_updated ? HTS_TRUE : HTS_FALSE);
3209
0
  RUN_CALLBACK6(opt, filesave2, adr, fil, save, create, modify, not_updated);
3210
0
}
3211
3212
// executer commande utilisateur
3213
void usercommand(httrackp * opt, int _exe, const char *_cmd, const char *file,
3214
0
                 const char *adr, const char *fil) {
3215
0
  usercommand_strc *strc = &opt->state.usercmd;
3216
3217
  /* Callback */
3218
0
  if (_exe) {
3219
0
    strcpybuff(strc->cmd, _cmd);
3220
0
    if (strnotempty(strc->cmd))
3221
0
      strc->exe = _exe;
3222
0
    else
3223
0
      strc->exe = 0;
3224
0
  }
3225
3226
0
  mimehtml_add_file(opt, file, adr, fil);
3227
3228
0
  if (file != NULL && strnotempty(file)) {
3229
0
    RUN_CALLBACK1(opt, filesave, file);
3230
0
  }
3231
3232
0
  if (strc->exe) {
3233
0
    if (file != NULL && strnotempty(file)) {
3234
0
      if (strnotempty(strc->cmd)) {
3235
0
        const int status = usercommand_exe(opt, strc->cmd, file);
3236
3237
        /* -1 was logged by usercommand_exe() */
3238
0
        if (status > 0)
3239
0
          hts_log_print(opt, LOG_WARNING,
3240
0
                        "User command exited with status %d: %.64s", status,
3241
0
                        strc->cmd);
3242
0
      }
3243
0
    }
3244
0
  }
3245
0
}
3246
3247
// Count one log event, whether or not a log file is open (#1681).
3248
0
void fspc_count(httrackp *opt, const char *type) {
3249
0
  fspc_strc *const strc = (opt != NULL) ? &opt->state.fspc : NULL;
3250
3251
0
  if (strc == NULL || type == NULL)
3252
0
    return;
3253
  /* any thread may log, while the crawl thread reads the counts */
3254
0
  if (strcmp(type, "warning") == 0)
3255
0
    hts_increment_int(&strc->warning);
3256
0
  else if (strcmp(type, "error") == 0 || strcmp(type, "panic") == 0)
3257
0
    hts_increment_int(&strc->error);
3258
0
  else if (strcmp(type, "info") == 0)
3259
0
    hts_increment_int(&strc->info);
3260
0
}
3261
3262
0
void fspc(FILE *fp, const char *type) {
3263
0
  char s[256];
3264
0
  time_t tt;
3265
0
  struct tm tmv;
3266
3267
0
  tt = time(NULL);
3268
0
  if (!hts_localtime(tt, &tmv)) {
3269
0
    int localtime_returned_null = 0;
3270
3271
0
    assertf(localtime_returned_null);
3272
0
  }
3273
0
  strftime(s, 250, "%H:%M:%S", &tmv);
3274
0
  if (strnotempty(type))
3275
0
    fprintf(fp, "%s\t%c%s: \t", s, hichar(*type), type + 1);
3276
0
  else
3277
0
    fprintf(fp, "%s\t \t", s);
3278
0
}
3279
3280
0
int fspc_get(httrackp *opt, const char *type) {
3281
0
  fspc_strc *const strc = (opt != NULL) ? &opt->state.fspc : NULL;
3282
3283
0
  if (strc == NULL || type == NULL)
3284
0
    return 0;
3285
0
  if (strcmp(type, "warning") == 0)
3286
0
    return hts_load_acquire_int(&strc->warning);
3287
0
  if (strcmp(type, "error") == 0)
3288
0
    return hts_load_acquire_int(&strc->error);
3289
0
  if (strcmp(type, "info") == 0)
3290
0
    return hts_load_acquire_int(&strc->info);
3291
0
  return 0;
3292
0
}
3293
3294
// ---
3295
// sous routines liées au moteur et au backing
3296
3297
// supplemental links ready (done) after ptr or ready in background
3298
static int backlinks_done(const struct_back *sback, lien_url **liens,
3299
0
                          int lien_tot, int ptr) {
3300
0
  int n = 0;
3301
3302
  // finalized in background
3303
0
  n += HTS_STAT.stat_background;
3304
0
  n += back_done_incache(sback);
3305
0
  return n;
3306
0
}
3307
3308
HTS_INLINE void back_fillmax(struct_back *sback, httrackp *opt,
3309
0
                             cache_back *cache, int ptr, int numero_passe) {
3310
0
  if (!hts_load_acquire_int(&opt->state.stop) &&
3311
0
      back_incache(sback) < opt->maxcache)
3312
0
    back_fill(sback, opt, cache, ptr, numero_passe);
3313
0
}
3314
3315
/* The seed keeps the target stable within a gap and new per launch, because a
3316
   per-call rand() biases the delay toward min_ms. It is not crypto. */
3317
0
int hts_pause_target_ms(TStamp seed, int min_ms, int max_ms) {
3318
0
  uint64_t z = (uint64_t) seed;
3319
3320
0
  if (max_ms <= min_ms)
3321
0
    return min_ms;
3322
  /* SplitMix64 finalizer: scrambles the low-entropy ms timestamp. */
3323
0
  z += 0x9E3779B97F4A7C15ULL;
3324
0
  z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
3325
0
  z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
3326
0
  z ^= z >> 31;
3327
0
  return min_ms + (int) (z % (uint64_t) (max_ms - min_ms + 1));
3328
0
}
3329
3330
0
void back_set_retry_after(struct_back *sback, httrackp *opt, int seconds) {
3331
0
  const int cap = opt->max_retry_after > 0 ? opt->max_retry_after : 0;
3332
0
  TStamp until;
3333
3334
0
  if (seconds > cap) {
3335
0
    hts_log_print(
3336
0
        opt, LOG_NOTICE,
3337
0
        "Server asked to retry after %ds, waiting %ds (--max-retry-after)",
3338
0
        seconds, cap);
3339
0
    seconds = cap;
3340
0
  } else if (seconds > 0) {
3341
0
    hts_log_print(opt, LOG_NOTICE, "Waiting %ds before retrying (Retry-After)",
3342
0
                  seconds);
3343
0
  }
3344
0
  if (seconds <= 0)
3345
0
    return;
3346
0
  until = mtime_local() + (TStamp) seconds * 1000;
3347
0
  if (until > sback->retry_after_until)
3348
0
    sback->retry_after_until = until;
3349
0
}
3350
3351
0
int hts_connect_pace(httrackp *opt, int n, hts_boolean may_wait) {
3352
  // connect limiter
3353
0
  if (n > 0 && opt->maxconn > 0 && HTS_STAT.last_connect > 0) {
3354
0
    TStamp opTime =
3355
0
      HTS_STAT.last_request ? HTS_STAT.last_request : HTS_STAT.last_connect;
3356
0
    TStamp cTime = mtime_local();
3357
0
    TStamp lap = (cTime - opTime);
3358
    /* floor the rate: the quotient must fit TStamp for any caller's value */
3359
0
    TStamp minLap =
3360
0
        (TStamp) (1000.0 / (opt->maxconn >= 1e-6f ? opt->maxconn : 1e-6f));
3361
3362
0
    if (lap < minLap) {
3363
0
      n = 0;
3364
0
    } else if (minLap != 0) {
3365
0
      int nMax = (int) (lap / minLap);
3366
3367
0
      n = hts_min_int(n, nMax);
3368
0
    }
3369
0
  }
3370
3371
  // #185 randomized inter-file pause: non-blocking, one launch per gap
3372
0
  if (n > 0 && may_wait && opt->pause_max_ms > 0 && HTS_STAT.last_connect > 0) {
3373
0
    TStamp opTime =
3374
0
        HTS_STAT.last_request ? HTS_STAT.last_request : HTS_STAT.last_connect;
3375
0
    TStamp lap = mtime_local() - opTime;
3376
3377
0
    if (lap < hts_pause_target_ms(opTime, opt->pause_min_ms, opt->pause_max_ms))
3378
0
      n = 0;
3379
0
    else
3380
0
      n = 1;
3381
0
  }
3382
3383
0
  return n;
3384
0
}
3385
3386
0
int back_pluggable_sockets_strict(struct_back *sback, httrackp *opt) {
3387
0
  int n = opt->maxsoc - back_nsoc(sback);
3388
  /* A stop outranks the delays below, which would otherwise swallow the user's
3389
     Ctrl-C for as long as the server or --pause asked us to wait. */
3390
0
  const hts_boolean may_wait = !hts_load_acquire_int(&opt->state.stop);
3391
3392
  // Retry-After: withhold launches until the delay the server asked for is up
3393
0
  if (n > 0 && may_wait && sback->retry_after_until > 0) {
3394
0
    if (mtime_local() < sback->retry_after_until)
3395
0
      return 0;
3396
0
    sback->retry_after_until = 0;
3397
0
  }
3398
3399
0
  return hts_connect_pace(opt, n, may_wait);
3400
0
}
3401
3402
/* One engine-loop tick: refresh the transfer stats and run the loop callback
3403
   for slot b (-1 = none). HTS_FALSE = the callback requested an abort. */
3404
0
hts_boolean hts_loop_tick(struct_back *sback, httrackp *opt, int b, int ptr) {
3405
0
  engine_stats();
3406
0
  HTS_STAT.stat_nsocket = back_nsoc(sback);
3407
0
  HTS_STAT.stat_errors = fspc_get(opt, "error");
3408
0
  HTS_STAT.stat_warnings = fspc_get(opt, "warning");
3409
0
  HTS_STAT.stat_infos = fspc_get(opt, "info");
3410
0
  HTS_STAT.stat_transport_failures = opt->transport_failures;
3411
0
  HTS_STAT.stat_mptcp_connections = opt->mptcp_connections;
3412
0
  HTS_STAT.stat_mptcp_fallbacks = opt->mptcp_fallbacks;
3413
0
  HTS_STAT.nbk = backlinks_done(sback, opt->liens, opt->lien_tot, ptr);
3414
0
  HTS_STAT.nb = back_transferred(HTS_STAT.stat_bytes, sback);
3415
0
  return RUN_CALLBACK7(
3416
0
             opt, loop, sback->lnk, sback->count, b, ptr, opt->lien_tot,
3417
0
             (int) (time_local() - HTS_STAT.stat_timestart), &HTS_STAT)
3418
0
             ? HTS_TRUE
3419
0
             : HTS_FALSE;
3420
0
}
3421
3422
/* Wait for a pluggable socket. */
3423
hts_boolean hts_wait_available_socket(struct_back *sback, httrackp *opt,
3424
0
                                      cache_back *cache, int ptr) {
3425
0
  const int prev = opt->state._hts_in_html_parsing;
3426
3427
0
  while (back_pluggable_sockets_strict(sback, opt) <= 0) {
3428
0
    opt->state._hts_in_html_parsing = 6;
3429
0
    back_wait(sback, opt, cache, 0);
3430
    /* time limit (-E) exceeded, or an exit: stop waiting for a socket (#481) */
3431
0
    if (!back_checkmirror(opt) || hts_is_exiting(opt))
3432
0
      break;
3433
0
    if (!hts_loop_tick(sback, opt, -1, ptr)) {
3434
0
      opt->state._hts_in_html_parsing = prev;
3435
0
      return HTS_FALSE;
3436
0
    }
3437
0
  }
3438
0
  opt->state._hts_in_html_parsing = prev;
3439
0
  return HTS_TRUE;
3440
0
}
3441
3442
/* Like back_pluggable_sockets_strict, but leaves room for naming tests. */
3443
0
static int back_pluggable_sockets(struct_back *sback, httrackp *opt) {
3444
0
  int n;
3445
3446
  // ajouter autant de socket qu'on peut ajouter
3447
0
  n = back_pluggable_sockets_strict(sback, opt);
3448
3449
  // vérifier qu'il restera assez de place pour les tests ensuite (en théorie, 1 entrée libre restante suffirait)
3450
0
  n = hts_min_int(n, back_available(sback) - 8);
3451
3452
  // no space left on backing stack - do not back anymore
3453
0
  if (back_available(sback) <= 2)
3454
0
    n = 0;
3455
3456
0
  return n;
3457
0
}
3458
3459
static void back_fill(struct_back *sback, httrackp *opt, cache_back *cache,
3460
0
                      int ptr, int numero_passe) {
3461
0
  int n = back_pluggable_sockets(sback, opt);
3462
3463
0
  if (opt->savename_delayed == HTS_SAVENAME_DELAYED_HARD &&
3464
0
      !opt->delayed_cached) /* cancel (always delayed) */
3465
0
    return;
3466
0
  if (n > 0) {
3467
0
    int p;
3468
3469
0
    if (ptr < cache->ptr_last) {        /* restart (2 scans: first html, then non html) */
3470
0
      cache->ptr_ant = 0;
3471
0
    }
3472
3473
0
    p = ptr + 1;
3474
    /* on a déja parcouru */
3475
0
    if (p < cache->ptr_ant)
3476
0
      p = cache->ptr_ant;
3477
0
    while (p < opt->lien_tot && n > 0 && back_checkmirror(opt)) {
3478
0
      int ok = 1;
3479
3480
      // on ne met pas le fichier en backing si il doit être traité après ou s'il a déja été traité
3481
0
      if (heap(p)->pass2) {    // 2è passe
3482
0
        if (numero_passe != 1)
3483
0
          ok = 0;
3484
0
      } else {
3485
0
        if (numero_passe != 0)
3486
0
          ok = 0;
3487
0
      }
3488
3489
0
      if (heap(p)->sav == NULL || heap(p)->sav[0] == '\0'
3490
0
          || hash_read(opt->hash, heap(p)->sav, NULL, HASH_STRUCT_FILENAME ) < 0) {
3491
0
        ok = 0;
3492
0
      }
3493
      // note: si un backing est fini, il reste en mémoire jusqu'à ce que
3494
      // le ptr l'atteigne
3495
0
      if (ok) {
3496
0
        if (!back_exist
3497
0
            (sback, opt, heap(p)->adr, heap(p)->fil, heap(p)->sav)) {
3498
0
          if (back_add(sback, opt, cache, heap(p)->adr, heap(p)->fil,
3499
0
                       heap(p)->sav, heap(heap(p)->precedent)->adr,
3500
0
                       heap(heap(p)->precedent)->fil, heap(p)->testmode,
3501
0
                       heap(p)->refetch_whole, &heap(p)->fetch) == -1) {
3502
0
            hts_log_print(opt, LOG_DEBUG,
3503
0
                          "error: unable to add more links through back_add "
3504
0
                          "for back_fill");
3505
0
            n = 0;              // sortir
3506
0
          } else {
3507
0
            n--;
3508
0
          }
3509
0
        }
3510
0
      }
3511
0
      p++;
3512
0
    } // while
3513
    /* sauver position dernière anticipation */
3514
0
    cache->ptr_ant = p;
3515
0
    cache->ptr_last = ptr;
3516
0
  }
3517
0
}
3518
3519
// ---
3520
3521
// Poll stdin.. si besoin
3522
#if HTS_POLL
3523
#ifdef _WIN32
3524
int check_stdin(void) {
3525
  /* Read the console queue, because stdin's EOF would read as a keystroke. */
3526
  return (_kbhit());
3527
}
3528
#else
3529
0
static int check_flot(T_SOC s) {
3530
0
  fd_set fds;
3531
0
  struct timeval tv;
3532
3533
0
  if (!hts_soc_selectable(s))
3534
0
    return 0;
3535
0
  FD_ZERO(&fds);
3536
0
  FD_SET((T_SOC) s, &fds);
3537
0
  tv.tv_sec = 0;
3538
0
  tv.tv_usec = 0;
3539
0
  select(s + 1, &fds, NULL, NULL, &tv);
3540
0
  return FD_ISSET(s, &fds);
3541
0
}
3542
0
int check_stdin(void) {
3543
0
  int c;
3544
3545
0
  fflush(stdout);
3546
0
  if (!check_flot(0))
3547
0
    return 0;
3548
  /* An stdin at EOF stays readable and reads as a keypress (#1072). Clear EOF
3549
     because a terminal can get input again after a ^D. */
3550
0
  clearerr(stdin);
3551
0
  if ((c = fgetc(stdin)) == EOF)
3552
0
    return 0;
3553
0
  ungetc(c, stdin);
3554
0
  return 1;
3555
0
}
3556
#endif
3557
#endif
3558
3559
0
int check_sockerror(T_SOC s) {
3560
0
  fd_set fds;
3561
0
  struct timeval tv;
3562
3563
0
  if (!hts_soc_selectable(s))
3564
0
    return 1;
3565
0
  FD_ZERO(&fds);
3566
0
  FD_SET((T_SOC) s, &fds);
3567
0
  tv.tv_sec = 0;
3568
0
  tv.tv_usec = 0;
3569
0
  select((int) s + 1, NULL, NULL, &fds, &tv);
3570
0
  return FD_ISSET(s, &fds);
3571
0
}
3572
3573
// Attente de touche
3574
0
int ask_continue(httrackp * opt) {
3575
0
  const char *s = RUN_CALLBACK1(opt, query2, opt->state.HTbuff);
3576
0
  int go = 1;
3577
3578
0
  if (s != NULL && strnotempty(s) &&
3579
0
      (hts_streq_ci(s, "N") || hts_streq_ci(s, "NO") || hts_streq_ci(s, "NON")))
3580
0
    go = 0;
3581
0
  if (HAS_CALLBACK(opt, query2)) /* nobody was asked otherwise */
3582
0
    hts_log_print(opt, LOG_NOTICE, "(wizard) answer '%s' to \"%.*s\": %s",
3583
0
                  s != NULL ? s : "", (int) strcspn(opt->state.HTbuff, "\r\n"),
3584
0
                  opt->state.HTbuff, go ? "continue" : "abort");
3585
0
  return go;
3586
0
}
3587
3588
// nombre de digits dans un nombre
3589
0
int nombre_digit(int n) {
3590
0
  int i = 1;
3591
3592
0
  while(n >= 10) {
3593
0
    n /= 10;
3594
0
    i++;
3595
0
  }
3596
0
  return i;
3597
0
}
3598
3599
0
static int hts_cancel_file_push_(httrackp * opt, const char *url) {
3600
0
  if (url != NULL && url[0] != '\0') {
3601
0
    htsoptstatecancel **cancel;
3602
0
    htsoptstatecancel *node;
3603
0
    char *copy;
3604
3605
    /* search for available place to store a new htsoptstatecancel* */
3606
0
    for(cancel = &opt->state.cancel; *cancel != NULL;
3607
0
        cancel = &((*cancel)->next)) {
3608
0
      if (strcmp((*cancel)->url, url) == 0) {
3609
0
        return 1;               /* already there */
3610
0
      }
3611
0
    }
3612
0
    node = malloct(sizeof(*node));
3613
0
    copy = strdupt(url);
3614
0
    if (node == NULL || copy == NULL) {
3615
0
      freet(node);
3616
0
      freet(copy);
3617
0
      return 1;
3618
0
    }
3619
0
    node->next = NULL;
3620
0
    node->url = copy;
3621
0
    *cancel = node;
3622
0
    return 0;
3623
0
  }
3624
0
  return 1;
3625
0
}
3626
3627
/* cancel a file (locked) */
3628
0
HTSEXT_API int hts_cancel_file_push(httrackp * opt, const char *url) {
3629
0
  int ret;
3630
3631
0
  hts_mutexlock(&opt->state.lock);
3632
0
  ret = hts_cancel_file_push_(opt, url);
3633
0
  hts_mutexrelease(&opt->state.lock);
3634
0
  return ret;
3635
0
}
3636
3637
0
static char *hts_cancel_file_pop_(httrackp * opt) {
3638
0
  if (opt->state.cancel != NULL) {
3639
0
    htsoptstatecancel **cancel;
3640
0
    htsoptstatecancel *ret;
3641
0
    char *url;
3642
3643
0
    for(cancel = &opt->state.cancel; (*cancel)->next != NULL;
3644
0
        cancel = &((*cancel)->next)) ;
3645
0
    ret = *cancel;
3646
0
    *cancel = NULL;
3647
    /* the string goes to the caller, the node does not outlive the pop */
3648
0
    url = ret->url;
3649
0
    freet(ret);
3650
0
    return url;
3651
0
  }
3652
0
  return NULL;                  /* no entry */
3653
0
}
3654
3655
0
char *hts_cancel_file_pop(httrackp * opt) {
3656
0
  char *ret;
3657
3658
0
  hts_mutexlock(&opt->state.lock);
3659
0
  ret = hts_cancel_file_pop_(opt);
3660
0
  hts_mutexrelease(&opt->state.lock);
3661
0
  return ret;
3662
0
}
3663
3664
0
HTSEXT_API void hts_cancel_test(httrackp * opt) {
3665
0
  if (opt->state._hts_in_html_parsing == 2)
3666
0
    opt->state._hts_cancel = 2;
3667
0
}
3668
0
HTSEXT_API void hts_cancel_parsing(httrackp * opt) {
3669
0
  if (opt->state._hts_in_html_parsing)
3670
0
    opt->state._hts_cancel = 1;
3671
0
}
3672
3673
// en train de parser un fichier html? réponse: % effectués
3674
// flag>0 : refresh demandé
3675
0
HTSEXT_API int hts_is_parsing(httrackp * opt, int flag) {
3676
0
  if (opt->state._hts_in_html_parsing) {        // parsing?
3677
0
    if (flag >= 0)
3678
0
      opt->state._hts_in_html_poll = 1; // faudrait un tit refresh
3679
0
    return hts_max_int(opt->state._hts_in_html_done, 1); // % effectués
3680
0
  } else {
3681
0
    return 0;                   // non
3682
0
  }
3683
0
}
3684
3685
0
HTSEXT_API int hts_is_testing(httrackp *opt) {
3686
  /* engine phases 2..6 report 1..5, named in httrack-library.h */
3687
0
  const int phase = opt->state._hts_in_html_parsing;
3688
3689
0
  return phase >= 2 && phase <= 6 ? phase - 1 : 0;
3690
0
}
3691
0
HTSEXT_API int hts_is_exiting(httrackp * opt) {
3692
0
  return hts_load_acquire_int(&opt->state.exit_xh);
3693
0
}
3694
3695
0
hts_boolean hts_run_is_ending(httrackp *opt) {
3696
0
  return hts_is_exiting(opt) || hts_load_acquire_int(&opt->state.stop);
3697
0
}
3698
3699
// message d'erreur?
3700
0
char *hts_errmsg(httrackp * opt) {
3701
0
  hts_hide_secrets(opt, opt->state._hts_errmsg, sizeof(opt->state._hts_errmsg));
3702
0
  return opt->state._hts_errmsg;
3703
0
}
3704
3705
// mode pause transfer
3706
0
HTSEXT_API int hts_setpause(httrackp * opt, int p) {
3707
0
  if (p >= 0)
3708
0
    opt->state._hts_setpause = p;
3709
0
  return opt->state._hts_setpause;
3710
0
}
3711
3712
// ask for termination
3713
0
HTSEXT_API int hts_request_stop(httrackp *opt, hts_boolean keep_resume) {
3714
0
  if (opt != NULL) {
3715
0
    hts_log_print(opt, LOG_ERROR, "Exit requested by shell or user");
3716
0
    hts_mutexlock(&opt->state.lock);
3717
0
    hts_store_release_int(&opt->state.stop, 1);
3718
    /* 1, as SIGTERM writes, spares hts-cache/ref for a later --continue */
3719
0
    if (keep_resume)
3720
0
      hts_store_release_int(&opt->state.exit_xh, 1);
3721
0
    hts_mutexrelease(&opt->state.lock);
3722
0
  }
3723
0
  return 0;
3724
0
}
3725
3726
0
HTSEXT_API hts_boolean hts_has_stopped(httrackp *opt) {
3727
0
  int ended;
3728
0
  hts_mutexlock(&opt->state.lock);
3729
0
  ended = opt->state.is_ended;
3730
0
  hts_mutexrelease(&opt->state.lock);
3731
0
  return ended;
3732
0
}
3733
3734
0
HTSEXT_API hts_tristate hts_mirror_completed(httrackp *opt) {
3735
0
  hts_tristate completed;
3736
0
  hts_mutexlock(&opt->state.lock);
3737
0
  completed = opt->mirror_completed;
3738
0
  hts_mutexrelease(&opt->state.lock);
3739
0
  return completed;
3740
0
}
3741
3742
// URLs injected into a running mirror
3743
0
void hts_addurl_free(char **url) {
3744
0
  if (url != NULL) {
3745
0
    size_t i;
3746
3747
0
    for (i = 0; url[i] != NULL; i++) {
3748
0
      freet(url[i]);
3749
0
    }
3750
0
    freet(url);
3751
0
  }
3752
0
}
3753
3754
/* Install url and return what it replaced (locked) */
3755
0
static char **hts_addurl_swap_(httrackp *opt, char **url) {
3756
0
  char **const old = opt->state._hts_addurl;
3757
3758
0
  opt->state._hts_addurl = url;
3759
0
  return old;
3760
0
}
3761
3762
0
char **hts_addurl_take(httrackp *opt) {
3763
0
  char **old;
3764
3765
0
  hts_mutexlock(&opt->state.lock);
3766
0
  old = hts_addurl_swap_(opt, NULL);
3767
0
  hts_mutexrelease(&opt->state.lock);
3768
0
  return old;
3769
0
}
3770
3771
/* Deep copy: the caller's array is typically a stack local, and the engine
3772
   thread reads the list long after the call returns. */
3773
0
HTSEXT_API hts_boolean hts_addurl(httrackp *opt, char **url) {
3774
0
  char **copy = NULL;
3775
0
  size_t n = 0, i;
3776
0
  hts_boolean ok;
3777
3778
0
  if (url != NULL) {
3779
0
    for (n = 0; url[n] != NULL; n++)
3780
0
      ;
3781
0
  }
3782
  /* An empty list adds nothing, like NULL. */
3783
0
  if (n != 0) {
3784
0
    copy = (char **) calloct(n + 1, sizeof(char *));
3785
0
    for (i = 0; copy != NULL && i < n; i++) {
3786
0
      if ((copy[i] = strdupt(url[i])) == NULL) {
3787
0
        hts_addurl_free(copy);
3788
0
        return HTS_FALSE;
3789
0
      }
3790
0
    }
3791
0
    if (copy == NULL)
3792
0
      return HTS_FALSE;
3793
0
  }
3794
  /* One critical section, so two racing callers both land in the list. */
3795
0
  hts_mutexlock(&opt->state.lock);
3796
0
  if (copy != NULL) {
3797
0
    char **const old = opt->state._hts_addurl;
3798
0
    size_t n_old = 0;
3799
0
    char **list;
3800
3801
0
    while (old != NULL && old[n_old] != NULL)
3802
0
      n_old++;
3803
0
    list = n <= SIZE_MAX / sizeof(char *) - 1 - n_old
3804
0
               ? (char **) realloct(old, (n_old + n + 1) * sizeof(char *))
3805
0
               : NULL;
3806
0
    if (list != NULL) {
3807
0
      memcpy(list + n_old, copy, (n + 1) * sizeof(char *));
3808
0
      opt->state._hts_addurl = list;
3809
0
      freet(copy); /* the strings now belong to list */
3810
0
    }
3811
0
    ok = list != NULL;
3812
0
  } else {
3813
0
    ok = opt->state._hts_addurl != NULL;
3814
0
  }
3815
0
  hts_mutexrelease(&opt->state.lock);
3816
0
  if (!ok)
3817
0
    hts_addurl_free(copy);
3818
0
  return ok;
3819
0
}
3820
3821
0
HTSEXT_API hts_boolean hts_resetaddurl(httrackp *opt) {
3822
0
  hts_addurl_free(hts_addurl_take(opt));
3823
0
  return HTS_FALSE;
3824
0
}
3825
3826
0
char **hts_addfilter_take(httrackp *opt) {
3827
0
  char **old;
3828
3829
0
  hts_mutexlock(&opt->state.lock);
3830
0
  old = opt->live_filters;
3831
0
  opt->live_filters = NULL;
3832
0
  hts_mutexrelease(&opt->state.lock);
3833
0
  return old;
3834
0
}
3835
3836
/* Writes rule, decoded, to norm (HTS_FILTER_MAXLEN + 1 bytes). Returns
3837
   HTS_FALSE if the rule is refused. */
3838
0
static hts_boolean filter_rule_normalize_(const char *rule, char *norm) {
3839
0
  size_t i;
3840
3841
0
  if (rule == NULL || (rule[0] != '+' && rule[0] != '-') || rule[1] == '\0')
3842
0
    return HTS_FALSE;
3843
0
  for (i = 0; rule[i] != '\0'; i++) {
3844
0
    if ((unsigned char) rule[i] < ' ')
3845
0
      return HTS_FALSE;
3846
0
  }
3847
0
  return filter_rule_decode_(rule, hts_buf_at(norm, HTS_FILTER_MAXLEN + 1));
3848
0
}
3849
3850
/* Returns a normalized copy, or NULL if refused or out of memory. */
3851
0
static char *filter_rule_dup_(const char *rule) {
3852
0
  char BIGSTK norm[HTS_FILTER_MAXLEN + 1];
3853
3854
0
  return filter_rule_normalize_(rule, norm) ? strdupt(norm) : NULL;
3855
0
}
3856
3857
0
HTSEXT_API hts_boolean hts_filter_rule_ok(const char *rule) {
3858
0
  char BIGSTK norm[HTS_FILTER_MAXLEN + 1];
3859
3860
0
  return filter_rule_normalize_(rule, norm);
3861
0
}
3862
3863
0
char **hts_setfilters_take(httrackp *opt) {
3864
0
  char **old;
3865
3866
0
  hts_mutexlock(&opt->state.lock);
3867
0
  old = opt->live_filters_set;
3868
0
  opt->live_filters_set = NULL;
3869
0
  hts_mutexrelease(&opt->state.lock);
3870
0
  return old;
3871
0
}
3872
3873
0
HTSEXT_API hts_boolean hts_setfilters(httrackp *opt, const char *const *rules) {
3874
0
  char **copy, **old_set, **old_adds;
3875
0
  size_t n, i;
3876
3877
0
  if (opt == NULL || rules == NULL)
3878
0
    return HTS_FALSE;
3879
0
  n = 0;
3880
0
  while (rules[n] != NULL)
3881
0
    n++;
3882
0
  if ((copy = (char **) calloct(n + 1, sizeof(char *))) == NULL)
3883
0
    return HTS_FALSE;
3884
0
  for (i = 0; i < n; i++) {
3885
0
    if ((copy[i] = filter_rule_dup_(rules[i])) == NULL) {
3886
0
      hts_addurl_free(copy);
3887
0
      return HTS_FALSE;
3888
0
    }
3889
0
  }
3890
  /* the new list supersedes rules added before it */
3891
0
  hts_mutexlock(&opt->state.lock);
3892
0
  old_set = opt->live_filters_set;
3893
0
  old_adds = opt->live_filters;
3894
0
  opt->live_filters_set = copy;
3895
0
  opt->live_filters = NULL;
3896
0
  hts_mutexrelease(&opt->state.lock);
3897
0
  hts_addurl_free(old_set);
3898
0
  hts_addurl_free(old_adds);
3899
0
  return HTS_TRUE;
3900
0
}
3901
3902
0
HTSEXT_API hts_boolean hts_addfilter(httrackp *opt, const char *rule) {
3903
0
  char *copy;
3904
0
  char **list;
3905
0
  size_t n = 0;
3906
3907
0
  if (opt == NULL || (copy = filter_rule_dup_(rule)) == NULL)
3908
0
    return HTS_FALSE;
3909
0
  hts_mutexlock(&opt->state.lock);
3910
0
  while (opt->live_filters != NULL && opt->live_filters[n] != NULL)
3911
0
    n++;
3912
0
  list = (char **) realloct(opt->live_filters, (n + 2) * sizeof(char *));
3913
0
  if (list != NULL) {
3914
0
    list[n] = copy;
3915
0
    list[n + 1] = NULL;
3916
0
    opt->live_filters = list;
3917
0
  }
3918
0
  hts_mutexrelease(&opt->state.lock);
3919
0
  if (list == NULL) {
3920
0
    freet(copy);
3921
0
    return HTS_FALSE;
3922
0
  }
3923
0
  return HTS_TRUE;
3924
0
}
3925
3926
// copier nouveaux paramètres si besoin
3927
0
HTSEXT_API int copy_htsopt(const httrackp * from, httrackp * to) {
3928
  /* the engine reads the strings below under this lock */
3929
0
  hts_mutexlock(&to->state.lock);
3930
0
  if (from->maxsite > -1)
3931
0
    to->maxsite = from->maxsite;
3932
3933
0
  if (from->maxfile_nonhtml > -1)
3934
0
    to->maxfile_nonhtml = from->maxfile_nonhtml;
3935
3936
0
  if (from->maxfile_html > -1)
3937
0
    to->maxfile_html = from->maxfile_html;
3938
3939
0
  if (from->maxsoc > 0)
3940
0
    to->maxsoc = from->maxsoc;
3941
3942
  /* hts_tristate fields use HTS_DEFAULT (-1) for "unspecified": copy_htsopt
3943
     skips them so the target keeps its value. */
3944
0
  if (from->nearlink > -1)
3945
0
    to->nearlink = from->nearlink;
3946
3947
0
  if (from->timeout > -1)
3948
0
    to->timeout = from->timeout;
3949
3950
0
  if (from->rateout > -1)
3951
0
    to->rateout = from->rateout;
3952
3953
0
  if (from->maxtime > -1)
3954
0
    to->maxtime = from->maxtime;
3955
3956
0
  if (from->maxrate > -1)
3957
0
    to->maxrate = from->maxrate;
3958
3959
0
  if (from->maxconn > 0)
3960
0
    to->maxconn = from->maxconn;
3961
  /* A fresh opt holds the default, so only another value is an edit. */
3962
0
  if (from->max_retry_after >= 0 &&
3963
0
      from->max_retry_after != HTS_DEFAULT_MAX_RETRY_AFTER)
3964
0
    to->max_retry_after = from->max_retry_after;
3965
3966
0
  if (from->mptcp > -1)
3967
0
    to->mptcp = from->mptcp;
3968
3969
0
  if (from->browser_headers > -1)
3970
0
    to->browser_headers = from->browser_headers;
3971
3972
0
  if (from->check_cert > -1)
3973
0
    to->check_cert = from->check_cert;
3974
3975
0
  if (StringNotEmpty(from->user_agent))
3976
0
    StringCopyS(to->user_agent, from->user_agent);
3977
3978
0
  if (StringNotEmpty(from->strip_query))
3979
0
    StringCopyS(to->strip_query, from->strip_query);
3980
3981
0
  if (StringNotEmpty(from->host_alias))
3982
0
    StringCopyS(to->host_alias, from->host_alias);
3983
3984
0
  if (StringNotEmpty(from->accept_kinds))
3985
0
    StringCopyS(to->accept_kinds, from->accept_kinds);
3986
3987
  /* An explicit -%a or -%l travels with its flag, so it stays explicit. */
3988
0
  if (from->accept_given) {
3989
0
    StringCopyS(to->accept, from->accept);
3990
0
    to->accept_given = HTS_TRUE;
3991
0
  }
3992
0
  if (from->lang_given) {
3993
0
    StringCopyS(to->lang_iso, from->lang_iso);
3994
0
    to->lang_given = HTS_TRUE;
3995
0
  }
3996
3997
0
  if (StringNotEmpty(from->cookies_file))
3998
0
    StringCopyS(to->cookies_file, from->cookies_file);
3999
4000
0
  if (StringNotEmpty(from->warc_file))
4001
0
    StringCopyS(to->warc_file, from->warc_file);
4002
0
  if (from->sitemap)
4003
0
    to->sitemap = from->sitemap;
4004
0
  if (StringNotEmpty(from->sitemap_url))
4005
0
    StringCopyS(to->sitemap_url, from->sitemap_url);
4006
4007
0
  if (from->pause_max_ms > 0) {
4008
0
    to->pause_min_ms = from->pause_min_ms;
4009
0
    to->pause_max_ms = from->pause_max_ms;
4010
0
  }
4011
4012
0
  if (from->retry > -1)
4013
0
    to->retry = from->retry;
4014
4015
0
  if (from->hostcontrol > -1)
4016
0
    to->hostcontrol = from->hostcontrol;
4017
4018
0
  if (from->errpage > -1)
4019
0
    to->errpage = from->errpage;
4020
4021
0
  if (from->parseall > -1)
4022
0
    to->parseall = from->parseall;
4023
4024
  /* delete_old is left alone, because shipped front ends send it inverted. */
4025
4026
0
  if (from->external > -1)
4027
0
    to->external = from->external;
4028
4029
0
  if (from->fragment > -1)
4030
0
    to->fragment = from->fragment;
4031
4032
  // test all: bit 8 de travel
4033
0
  if (from->travel > -1) {
4034
0
    if (from->travel & HTS_TRAVEL_TEST_ALL)
4035
0
      to->travel |= HTS_TRAVEL_TEST_ALL;
4036
0
    else
4037
0
      to->travel &= HTS_TRAVEL_SCOPE_MASK;
4038
0
  }
4039
4040
0
  hts_mutexrelease(&to->state.lock);
4041
0
  return 0;
4042
0
}
4043
4044
//
4045
4046
/* External modules callback */
4047
0
int htsAddLink(htsmoduleStruct * str, char *link) {
4048
0
  if (link != NULL && str != NULL && link[0] != '\0') {
4049
0
    ENGINE_LOAD_CONTEXT_BASE();
4050
    /* */
4051
0
    lien_adrfilsave afs;
4052
0
    char BIGSTK codebase[HTS_URLMAXSIZE * 2];
4053
4054
    /* */
4055
0
    int pass_fix, prio_fix;
4056
4057
    /* */
4058
0
    int forbidden_url = 1;
4059
4060
0
    codebase[0] = '\0';
4061
4062
0
    hts_log_print(opt, LOG_DEBUG, "(module): adding link : '%s'",
4063
0
                  url_nologin(opt, link));
4064
    // recopie de "creer le lien"
4065
    //    
4066
4067
0
    if (!RUN_CALLBACK1(opt, linkdetected, link)) {
4068
0
      hts_log_print(opt, LOG_ERROR, "Link %s refused by external wrapper",
4069
0
                    url_nologin(opt, link));
4070
0
      return 0;
4071
0
    }
4072
0
    if (!RUN_CALLBACK2(opt, linkdetected2, link, NULL)) {
4073
0
      hts_log_print(opt, LOG_ERROR, "Link %s refused by external wrapper(2)",
4074
0
                    url_nologin(opt, link));
4075
0
      return 0;
4076
0
    }
4077
    // adr = c'est la même
4078
    // fil et save: save2 et fil2
4079
0
    prio_fix = hts_max_int(heap(ptr)->depth - 1, 0);
4080
0
    pass_fix = hts_max_int(heap(ptr)->pass2, numero_passe);
4081
0
    if (heap(ptr)->cod)
4082
0
      strcpybuff(codebase, heap(ptr)->cod);    // codebase valable pour tt les classes descendantes
4083
0
    if (strnotempty(codebase) == 0) {   // pas de codebase, construire
4084
0
      char *a;
4085
4086
0
      if (str->relativeToHtmlLink == 0)
4087
0
        strcpybuff(codebase, heap(ptr)->fil);
4088
0
      else
4089
0
        strcpybuff(codebase, heap(heap(ptr)->precedent)->fil);
4090
0
      a = hts_lastcharptr(codebase);
4091
0
      while((*a) && (*a != '/') && (a > codebase))
4092
0
        a--;
4093
0
      if (*a == '/')
4094
0
        *(a + 1) = '\0';        // cut
4095
0
    } else {
4096
      // keep only the path of an absolute codebase
4097
0
      const char *host = codebase;
4098
4099
0
      if (hts_skip_prefix_ci(&host, "http://") ||
4100
0
          hts_skip_prefix_ci(&host, "https://")) {
4101
0
        char BIGSTK tempo[HTS_URLMAXSIZE * 2];
4102
0
        char *a = strchr(host, '/');
4103
4104
0
        if (a) {
4105
0
          strcpybuff(tempo, a);
4106
0
          strcpybuff(codebase, tempo);  // couper host
4107
0
        } else {
4108
0
          hts_log_print(opt, LOG_ERROR, "Unexpected strstr error in base %s",
4109
0
                        url_nologin(opt, codebase));
4110
0
        }
4111
0
      }
4112
0
    }
4113
4114
0
    if (strlen(codebase) >= HTS_URLMAXSIZE) {
4115
0
      hts_log_print(opt, LOG_ERROR, "Codebase too long, parsing skipped (%s)",
4116
0
                    url_nologin(opt, codebase));
4117
0
      return 0;
4118
0
    }
4119
4120
0
    {
4121
0
      char *lien = link;
4122
0
      int dejafait = 0;
4123
4124
0
      if (strnotempty(lien) && strlen(lien) < HTS_URLMAXSIZE) {
4125
4126
        // calculer les chemins et noms de sauvegarde
4127
0
        if (ident_url_relatif(lien, urladr(), codebase, &afs.af) >= 0) { // reformage selon chemin
4128
0
          int r;
4129
0
          int set_prio_to = 0;
4130
0
          int just_test_it = 0;
4131
4132
0
          forbidden_url =
4133
0
              hts_acceptlink(opt, ptr, afs.af.adr, afs.af.fil, NULL, NULL,
4134
0
                             HTS_FALSE, &set_prio_to, &just_test_it);
4135
0
          hts_log_print(opt, LOG_DEBUG,
4136
0
                        "result for wizard external module link: %d",
4137
0
                        forbidden_url);
4138
4139
          /* Link accepted */
4140
0
          if (!forbidden_url) {
4141
0
            char BIGSTK tempo[HTS_URLMAXSIZE * 2];
4142
0
            int a, b;
4143
4144
0
            tempo[0] = '\0';
4145
0
            a = opt->savename_type;
4146
0
            b = opt->savename_83;
4147
0
            opt->savename_type = 0;
4148
0
            opt->savename_83 = HTS_SAVENAME_83_LONG;
4149
            // note: adr,fil peuvent être patchés
4150
0
            r =
4151
0
              url_savename(&afs, NULL, NULL, NULL, opt, sback, cache, hashptr, ptr, numero_passe,
4152
0
                           NULL);
4153
            // resolve unresolved type
4154
0
            if (r != -1 && forbidden_url == 0 && IS_DELAYED_EXT(afs.save)
4155
0
              ) {               // pas d'erreur, on continue
4156
0
              lien_adrfil former;
4157
4158
0
              former.adr[0] = former.fil[0] = '\0';
4159
0
              r = hts_wait_delayed(str, &afs, NULL, NULL, &former,
4160
0
                                   &forbidden_url, NULL);
4161
0
            }
4162
            // end resolve unresolved type
4163
0
            opt->savename_type = a;
4164
0
            opt->savename_83 = b;
4165
0
            if (r != -1 && !forbidden_url) {
4166
0
              if (savename()) {
4167
0
                if (lienrelatif(HTS_BUF(tempo), afs.save, savename()) == 0) {
4168
0
                  hts_log_print(
4169
0
                      opt, LOG_DEBUG,
4170
0
                      "(module): relative link at %s build with %s and %s: %s",
4171
0
                      adr_nologin(opt, afs.af.adr), afs.save, savename(),
4172
0
                      tempo);
4173
0
                  if (str->localLink
4174
0
                      && str->localLinkSize > (int) strlen(tempo) + 1) {
4175
0
                    strlcpybuff(str->localLink, tempo, str->localLinkSize);
4176
0
                  }
4177
0
                }
4178
0
              }
4179
0
            }
4180
0
          }
4181
4182
0
          if (forbidden_url) {
4183
0
            hts_log_print(opt, LOG_DEBUG, "(module): file not caught: %s",
4184
0
                          url_nologin(opt, lien));
4185
0
            if (str->localLink
4186
0
                && str->localLinkSize > (int) (strlen(afs.af.adr) + strlen(afs.af.fil) + 8)) {
4187
0
              htsbuff lb = htsbuff_ptr(str->localLink, str->localLinkSize);
4188
0
              if (!link_has_authority(afs.af.adr))
4189
0
                htsbuff_cat(&lb, "http://");
4190
0
              htsbuff_cat(&lb, afs.af.adr);
4191
0
              htsbuff_cat(&lb, afs.af.fil);
4192
0
            }
4193
0
            r = -1;
4194
0
          }
4195
          //
4196
0
          if (r != -1) {
4197
0
            hts_log_print(opt, LOG_DEBUG, "(module): %s%s -> %s (base %s)",
4198
0
                          adr_nologin(opt, afs.af.adr), afs.af.fil, afs.save,
4199
0
                          url_nologin(opt, codebase));
4200
4201
            // modifié par rapport à l'autre version (cf prio_fix notamment et save2)
4202
4203
            // vérifier que le lien n'a pas déja été noté
4204
            // si c'est le cas, alors il faut s'assurer que la priorité associée
4205
            // au fichier est la plus grande des deux priorités
4206
            //
4207
            // On part de la fin et on essaye de se presser (économise temps machine)
4208
0
            {
4209
0
              int i = hash_read(hashptr, afs.save, NULL, HASH_STRUCT_FILENAME );    // lecture type 0 (sav)
4210
4211
0
              if (i >= 0) {
4212
0
                heap(i)->depth = hts_max_int(heap(i)->depth, prio_fix);
4213
0
                dejafait = 1;
4214
0
              }
4215
0
            }
4216
4217
0
            if (!dejafait) {
4218
              //
4219
              // >>>> CREER LE LIEN JAVA <<<<
4220
4221
              // enregistrer fichier (MACRO)
4222
0
              if (!hts_record_link(opt, afs.af.adr, afs.af.fil, afs.save, "", "", "")) {    // erreur, pas de place réservée
4223
                /* fatal error -> exit */
4224
0
                hts_store_release_int(&opt->state.exit_xh, -1);
4225
0
                return 0;
4226
0
              }
4227
              // mode test?                          
4228
0
              heap_top()->testmode = 0;    // pas mode test
4229
0
              heap_top()->link_import = 0; // pas mode import
4230
4231
              // écrire autres paramètres de la structure-lien
4232
0
              heap_top()->premier = heap(ptr)->premier;
4233
4234
0
              heap_top()->precedent = ptr;
4235
              // noter la priorité
4236
0
              if (!set_prio_to)
4237
0
                heap_top()->depth = prio_fix;
4238
0
              else
4239
                /* lowest priority (catch page) */
4240
0
                heap_top()->depth = hts_max_int(
4241
0
                    0, hts_min_int(heap(ptr)->depth - 1, set_prio_to - 1));
4242
0
              heap_top()->pass2 = hts_max_int(pass_fix, numero_passe);
4243
0
              heap_top()->retry = opt->retry;
4244
4245
0
              hts_log_print(opt, LOG_DEBUG, "(module): OK, NOTE: %s%s -> %s",
4246
0
                            adr_nologin(opt, heap_top()->adr), heap_top()->fil,
4247
0
                            heap_top()->sav);
4248
0
            }
4249
0
          }
4250
0
        }
4251
0
      }
4252
0
    }
4253
4254
0
    return (forbidden_url == 0);
4255
0
  }
4256
0
  return 0;
4257
0
}
4258
4259
// HTTrack Website Copier Copyright (C) 1998 Xavier Roche and other contributors
4260
//