Coverage Report

Created: 2026-12-01 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/httrack/src/htscoremain.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: opt->c subroutines:                                 */
30
/*       main routine (first called)                            */
31
/* Author: Xavier Roche                                         */
32
/* ------------------------------------------------------------ */
33
34
#include "htscoremain.h"
35
36
#include "httrack-library.h"
37
#include "htsglobal.h"
38
#include "htscore.h"
39
#include "htsio.h"
40
#include "htsdefines.h"
41
#include "htsalias.h"
42
#include "htscmdline.h"
43
#include "htslines.h"
44
#include "htswarc.h"
45
#include "htschanges.h"
46
#include "htsbauth.h"
47
#include "htswrap.h"
48
#include "htsmodules.h"
49
#include <limits.h>
50
#include <float.h>
51
#include <stdint.h>
52
#include "htszlib.h"
53
#include "htscharset.h"
54
#include "htsselftest.h"
55
#include "htscrashtest.h"
56
#include "htsmd5.h"
57
#include "htsthread.h"
58
#include "htsfetch.h"
59
#include "htsbundle.h"
60
61
/* hts_self_path() */
62
#ifdef __APPLE__
63
#include <mach-o/dyld.h>
64
#endif
65
/* These BSDs name the running binary through sysctl, which needs no /proc.
66
   OpenBSD has no equivalent and stays on argv[0]. */
67
#if defined(HAVE_SYS_SYSCTL_H) &&                                              \
68
    (defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__))
69
#include <sys/types.h>
70
#include <sys/sysctl.h>
71
#ifdef KERN_PROC_PATHNAME
72
#define HTS_SELF_PATH_SYSCTL 1
73
#endif
74
#endif
75
#ifdef HAVE_UNISTD_H
76
#include <unistd.h>
77
#endif
78
#ifdef _WIN32
79
#include <process.h>
80
#endif
81
#ifdef _WIN32
82
#else
83
#ifndef HTS_DO_NOT_USE_UID
84
/* setuid */
85
#include <pwd.h>
86
#ifdef HAVE_UNISTD_H
87
#include <unistd.h>
88
#endif
89
#endif
90
#endif
91
92
/* Resolver */
93
extern int IPV6_resolver;
94
95
/* Set the error hts_errmsg() returns; aborts when msg does not fit. */
96
0
static void cmdl_panic(httrackp *opt, const char *msg) {
97
0
  strcpybuff(opt->state._hts_errmsg, msg);
98
0
}
99
100
/* Append s to the request in opt->state.HTbuff. Aborts on overflow. */
101
0
static void ht_print(httrackp *opt, const char *s) {
102
0
  strcatbuff(opt->state.HTbuff, s);
103
0
}
104
105
/* A data directory is one that carries the templates path_bin is read for. */
106
0
static int datadir_has_templates(const char *dir) {
107
0
  char catbuff[CATBUFF_SIZE];
108
109
0
  return dir != NULL && *dir != '\0' &&
110
0
         hts_fpath_join(HTS_BUF(catbuff), dir, "templates/index-header.html") &&
111
0
         fexist(catbuff);
112
0
}
113
114
/* htsbacktrace.c copies the Linux branch: it is program-side and cannot reach
115
   this hidden symbol, so a fix here belongs there too (#997). */
116
0
const char *hts_self_path(hts_buf dst) {
117
  /* An empty dst holds no terminator, and readlink() would get SIZE_MAX. */
118
0
  if (dst.size == 0)
119
0
    return NULL;
120
#if defined(_WIN32)
121
  const DWORD n = GetModuleFileNameA(NULL, dst.p, (DWORD) dst.size);
122
123
  /* Pre-Win8 returns nSize on truncation without terminating: a full buffer
124
     is a failure, not a path. */
125
  if (n > 0 && (size_t) n < dst.size)
126
    return dst.p;
127
#elif defined(__APPLE__)
128
  uint32_t n = (uint32_t) dst.size;
129
130
  if (_NSGetExecutablePath(dst.p, &n) == 0)
131
    return dst.p;
132
#elif defined(HTS_SELF_PATH_SYSCTL)
133
  /* FreeBSD and DragonFly put the pid last, NetBSD puts it third, and 9 is the
134
     pathname on DragonFly but KERN_PROC_SV_NAME on FreeBSD (#1506). */
135
#if defined(__NetBSD__)
136
  int mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
137
#else
138
  int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
139
#endif
140
  size_t n = dst.size;
141
142
  /* All three report strlen + 1, so 1 is the empty path and dst.p[n - 1] is the
143
     kernel's own terminator. */
144
  if (sysctl(mib, 4, dst.p, &n, NULL, 0) == 0 && n > 1 && n <= dst.size &&
145
      dst.p[n - 1] == '\0')
146
    return dst.p;
147
#else
148
  /* Linux; anywhere else this is simply absent and argv[0] has to do. */
149
0
  const ssize_t n = readlink("/proc/self/exe", dst.p, dst.size - 1);
150
151
0
  if (n > 0 && (size_t) n < dst.size - 1) {
152
0
    dst.p[n] = '\0';
153
0
    return dst.p;
154
0
  }
155
0
#endif
156
  /* GetModuleFileNameA() and sysctl() leave a clipped path on failure, so
157
     empty dst. */
158
0
  dst.p[0] = '\0';
159
0
  return NULL;
160
0
}
161
162
/* Directory part of path, trailing '/' kept, or NULL when it carries none: a
163
   bare name came from a PATH lookup and locates nothing. */
164
0
static const char *dirname_of(hts_buf dst, const char *path) {
165
0
  char catbuff[CATBUFF_SIZE];
166
0
  const char *slashed, *sep;
167
0
  size_t len;
168
169
0
  if (path == NULL)
170
0
    return NULL;
171
0
  slashed = fslash(HTS_BUF(catbuff), path);
172
0
  if ((sep = strrchr(slashed, '/')) == NULL)
173
0
    return NULL;
174
0
  len = (size_t) (sep - slashed) + 1;
175
0
  return hts_buf_put_span(dst, hts_span_at(slashed, len)) ? dst.p : NULL;
176
0
}
177
178
void hts_resolve_datadir(hts_buf dst, const char *selfpath,
179
0
                         const char *builtin) {
180
  /* An installed tree that was moved, then a flat one with templates/ beside
181
     the binary. */
182
0
  static const char *const layout[] = {"../share/httrack/", ""};
183
0
  char exedir[HTS_URLMAXSIZE * 2];
184
0
  const char *base = NULL;
185
0
  const char *fallback;
186
187
0
  if (!datadir_has_templates(builtin)) {
188
0
    base = dirname_of(HTS_BUF(exedir), selfpath);
189
0
  }
190
0
  if (base != NULL) {
191
0
    size_t i;
192
193
0
    for (i = 0; i < sizeof(layout) / sizeof(layout[0]); i++) {
194
0
      char cand[HTS_URLMAXSIZE * 2];
195
196
      /* A long argv[0] can overflow cand, so skip a clipped path. */
197
0
      if (!hts_buf_printf(HTS_BUF(cand), "%s%s", base, layout[i]))
198
0
        continue;
199
0
      if (datadir_has_templates(cand)) {
200
0
        hts_buf_cpy_clip(dst, cand);
201
0
        return;
202
0
      }
203
0
    }
204
0
  }
205
  /* Windows has no compiled-in data directory, so there the executable's own
206
     is all we have. */
207
0
  fallback = (builtin != NULL && *builtin != '\0') ? builtin
208
0
             : (base != NULL)                      ? base
209
0
                                                   : "";
210
0
  hts_buf_cpy_clip(dst, fallback);
211
0
}
212
213
/* Append CMD's arguments to the pending request, each behind a space, ending
214
   in " ..." if they do not all fit. Clipped rather than bounded because
215
   ht_print() aborts on overflow and a command line outgrows HTbuff easily. */
216
0
static void cmdl_print_args(httrackp *opt, const cmdl_argv *cmd) {
217
  /* what the caller still has to append: "?", the line break, the NUL */
218
0
  static const size_t tail = sizeof("?" LF);
219
0
  int i;
220
221
0
  for (i = 1; i < cmd->argc; i++) {
222
0
    const size_t spare = sizeof(opt->state.HTbuff) - tail - sizeof(" ...");
223
0
    const size_t used = strlen(opt->state.HTbuff);
224
225
0
    if (used >= spare || strlen(cmd->argv[i]) >= spare - used) {
226
      /* clipped rather than ht_print()ed, so the mark fits whatever the caller
227
         wrote before it */
228
0
      strlncatbuff(opt->state.HTbuff, " ...", sizeof(opt->state.HTbuff),
229
0
                   sizeof(opt->state.HTbuff) - 1 - used);
230
0
      return;
231
0
    }
232
0
    ht_print(opt, " ");
233
0
    ht_print(opt, cmd->argv[i]);
234
0
  }
235
0
}
236
237
/* Grow the url buffer to at least size, or panic and return HTS_FALSE. */
238
static hts_boolean ensure_url_capacity(httrackp *opt, char **url,
239
0
                                       size_t *urlsize, size_t size) {
240
0
  if (*urlsize < size || *url == NULL) {
241
0
    *urlsize = size;
242
0
    if (*url == NULL) {
243
0
      *url = (char *) malloct(*urlsize);
244
0
      if (*url != NULL)
245
0
        (*url)[0] = '\0';
246
0
    } else {
247
0
      *url = (char *) realloct(*url, *urlsize);
248
0
    }
249
0
    if (*url == NULL) {
250
0
      cmdl_panic(opt, "* memory exhausted");
251
0
      return HTS_FALSE;
252
0
    }
253
0
  }
254
0
  return HTS_TRUE;
255
0
}
256
257
/* glued_int() for an enum, narrower than an int under -fshort-enums. A read
258
   level is >= 0, so -1 means no digits. A refusal returns -1. */
259
#define readGluedEnum(at, field, max)                                          \
260
0
  do {                                                                         \
261
0
    int level_ = -1;                                                           \
262
0
                                                                               \
263
0
    if (!glued_int((at), &level_, (max)))                                      \
264
0
      return -1;                                                               \
265
0
    if (level_ >= 0)                                                           \
266
0
      (field) = level_;                                                        \
267
0
  } while (0)
268
269
0
hts_scan_result cmdl_glued_llint(char **com, LLint min, LLint max, LLint *out) {
270
0
  const char *const digits = *com + 1;
271
0
  const char *end;
272
0
  const hts_boolean ok = hts_parse_llint(digits, &end, min, max, out);
273
274
0
  if (end == digits)
275
0
    return HTS_SCAN_NONE;
276
0
  *com += end - digits; // Onto the last digit, which the caller steps past.
277
0
  return ok ? HTS_SCAN_OK : HTS_SCAN_REFUSED;
278
0
}
279
280
0
hts_scan_result cmdl_glued_int(char **com, int min, int max, int *out) {
281
0
  LLint value;
282
0
  const hts_scan_result got = cmdl_glued_llint(com, min, max, &value);
283
284
0
  if (got == HTS_SCAN_OK)
285
0
    *out = (int) value;
286
0
  return got;
287
0
}
288
289
/* The option being read: its argument argv[*na] and the cursor *com in it. */
290
typedef struct cmdl_at {
291
  httrackp *opt;
292
  char **com;
293
  char **argv;
294
  const int *na;
295
} cmdl_at;
296
297
/* Panic on a glued value above its maximum, and return HTS_FALSE. */
298
0
static hts_boolean glued_refuse(const cmdl_at *at) {
299
0
  char s[256];
300
301
0
  snprintf(s, sizeof(s), "Value out of range in option %s", at->argv[*at->na]);
302
0
  cmdl_panic(at->opt, s);
303
0
  return HTS_FALSE;
304
0
}
305
306
/* Read the glued digits at the cursor into *out, up to max. With no digits,
307
 *out is unchanged. Returns HTS_FALSE after a panic when above max. */
308
0
static hts_boolean glued_int(const cmdl_at *at, int *out, int max) {
309
0
  return cmdl_glued_int(at->com, 0, max, out) != HTS_SCAN_REFUSED ||
310
0
         glued_refuse(at);
311
0
}
312
313
/* glued_int() for a 64-bit field. */
314
0
static hts_boolean glued_llint(const cmdl_at *at, LLint *out, LLint max) {
315
0
  return cmdl_glued_llint(at->com, 0, max, out) != HTS_SCAN_REFUSED ||
316
0
         glued_refuse(at);
317
0
}
318
319
/* Is the on/off option at com on? A glued 0 turns it off and is consumed. */
320
0
static hts_boolean glued_onoff(char **com) {
321
0
  if ((*com)[1] != '0')
322
0
    return HTS_TRUE;
323
0
  (*com)++;
324
0
  return HTS_FALSE;
325
0
}
326
327
/* Panic with msg, and ask to remove the quotes of value if it has any. */
328
static void cmdl_panic_value(httrackp *opt, const char *msg,
329
0
                             const char *value) {
330
0
  char s[HTS_CDLMAXSIZE * 2 + 256];
331
332
0
  char shown[HTS_CDLMAXSIZE];
333
334
0
  if (hts_is_quoted(hts_span_of(value)))
335
0
    snprintf(s, sizeof(s), "%s: \"%s " HTS_QUOTED_HINT, msg,
336
0
             adr_nologin_r(HTS_BUF(shown), value + 1));
337
0
  else
338
0
    snprintf(s, sizeof(s), "%s", msg);
339
0
  cmdl_panic(opt, s);
340
0
}
341
342
/* Prints a --host-alias rule with the login of each of its names masked. */
343
0
static void print_rule_nologin(const char *rule) {
344
0
  while (*rule != '\0') {
345
0
    char tok[HTS_CDLMAXSIZE];
346
0
    char shown[HTS_CDLMAXSIZE + 8];
347
0
    size_t n = strcspn(rule, ",=");
348
349
0
    if (n >= sizeof(tok))
350
0
      n = sizeof(tok) - 1;
351
0
    memcpy(tok, rule, n);
352
0
    tok[n] = '\0';
353
0
    fputs(adr_nologin_r(HTS_BUF(shown), tok), stdout);
354
0
    rule += n;
355
0
    if (*rule == ',' || *rule == '=')
356
0
      putchar(*rule++);
357
0
  }
358
0
  putchar('\n');
359
0
}
360
361
/* Panic on com, the end of option arg that no option takes. When com is
362
   quoted, the message names the option before it. */
363
static void cmdl_bad_option(httrackp *opt, const char *arg, const char *prefix,
364
0
                            const char *com) {
365
0
  char s[HTS_CDLMAXSIZE * 2 + 256];
366
367
0
  if (hts_is_quoted(hts_span_of(com)))
368
0
    snprintf(s, sizeof(s), "Option %.*s: %s " HTS_QUOTED_HINT,
369
0
             (int) (com - arg), arg, com);
370
0
  else
371
0
    snprintf(s, sizeof(s), "invalid option %s%c\n", prefix, *com);
372
0
  cmdl_panic(opt, s);
373
0
}
374
375
0
HTSEXT_API int hts_main(int argc, char **argv) {
376
0
  httrackp *opt = hts_create_opt();
377
0
  int ret = hts_main2(argc, argv, opt);
378
379
0
  hts_free_opt(opt);
380
0
  return ret;
381
0
}
382
383
/* Write the progress lock at PATH, dated one second back so a request written
384
   the instant the file appears sorts after it. False when it could not be
385
   written at all. */
386
static hts_boolean write_progress_lock(httrackp *opt, const char *path,
387
0
                                       const char *t, int argc, char **argv) {
388
0
  FILE *fp = hts_fopen_private(path, "wb"); /* it echoes argv */
389
0
  int i;
390
391
0
  if (fp == NULL)
392
0
    return HTS_FALSE;
393
0
  fprintf(fp, "Mirror in progress since %s .. please wait!" LF, t);
394
0
  for (i = 0; i < argc; i++) {
395
0
    if (strchr(argv[i], ' ') == NULL)
396
0
      fprintf(fp, "%s ", argv[i]);
397
0
    else // entre ""
398
0
      fprintf(fp, "\"%s\" ", argv[i]);
399
0
  }
400
0
  fprintf(fp, LF);
401
0
  fprintf(fp, "To pause the engine: create an empty file named "
402
0
              "'" HTS_PAUSE_LOCKNAME "' (an earlier run's copy is"
403
0
              " ignored, so create it again)" LF);
404
0
  fprintf(fp, "To stop it and keep the mirror: create an empty file named "
405
0
              "'" HTS_ABORT_LOCKNAME "' (an earlier run's copy is"
406
0
              " ignored, so create it again)" LF);
407
0
  fprintf(fp, "PID=%d\n", (int) getpid());
408
0
#ifndef _WIN32
409
0
  fprintf(fp, "UID=%d\n", (int) getuid());
410
0
  fprintf(fp, "GID=%d\n", (int) getgid());
411
0
#endif
412
0
  fprintf(fp, "START=" LLintP "\n", (LLint) time(NULL));
413
0
  fclose(fp);
414
  /* Whole-second filesystems tie two files written in the same second, and the
415
     backdate is what breaks that tie. */
416
0
  if (!hts_file_backdate(path, 1) && opt->log != NULL)
417
0
    hts_log_print(opt, LOG_WARNING,
418
0
                  "engine: could not date hts-in_progress.lock back, so a"
419
0
                  " stop request written in this first second is ignored");
420
0
  return HTS_TRUE;
421
0
}
422
423
/* Deletes dir + name when it exists. */
424
0
static void unlink_if_exists(httrackp *opt, const char *dir, const char *name) {
425
0
  const char *const path = hts_optpath(opt, dir, name);
426
427
0
  if (fexist_utf8(path))
428
0
    UNLINK(path);
429
0
}
430
431
/* Removes the entries of hts-cache/ref, then the directory. A symlinked ref is
432
   left alone, so it cannot reach cookies.txt or winprofile.ini. */
433
0
static void purge_ref_dir(httrackp *opt) {
434
0
  const char *const refdir = hts_logpath(opt, CACHE_REFNAME);
435
0
  DIR *dir = NULL;
436
0
  struct dirent *entry;
437
0
#ifndef _WIN32
438
0
  struct stat st;
439
440
0
  if (lstat(refdir, &st) != 0 || !S_ISDIR(st.st_mode))
441
0
    return;
442
0
#endif
443
0
  dir = opendir(refdir);
444
0
  while (dir != NULL && (entry = readdir(dir)) != NULL) {
445
0
    if (entry->d_name[0] != '\0' && entry->d_name[0] != '.') {
446
0
      char rel[HTS_URLMAXSIZE];
447
448
0
      if (snprintf(rel, sizeof(rel), "%s/%s", CACHE_REFNAME, entry->d_name) <
449
0
          (int) sizeof(rel)) {
450
0
        const char *const path = hts_logpath(opt, rel);
451
0
        (void) UNLINK(path);
452
0
      }
453
0
    }
454
0
  }
455
0
  if (dir != NULL)
456
0
    (void) closedir(dir);
457
0
  (void) RMDIR(hts_logpath(opt, CACHE_REFNAME));
458
0
}
459
460
static int hts_main_run(int argc, char **argv, httrackp *opt, cmdl_argv *x_cmd,
461
                        char **url);
462
static hts_boolean cmdl_shortopt_has(const char *s, char c);
463
static hts_boolean cmdl_shortopt_named(const char *s, const char *opt);
464
static void cmdl_doit_line(String *line, const cmdl_argv *cmd);
465
static int check_path(String *s, char *defaultname);
466
467
// Main, récupère les paramètres et appelle le robot
468
0
HTSEXT_API int hts_main2(int argc, char **argv, httrackp * opt) {
469
0
  cmdl_argv x_cmd = {NULL, NULL, NULL, 0, 0, {NULL, 0, 0}};
470
0
  char *url = NULL;
471
0
  int code;
472
473
  // Set ended state (3.48-14)
474
0
  hts_mutexlock(&opt->state.lock);
475
0
  opt->state.is_ended = 0;
476
0
  hts_mutexrelease(&opt->state.lock);
477
478
0
  code = hts_main_run(argc, argv, opt, &x_cmd, &url);
479
0
  freet(url);
480
0
  cmdl_free(&x_cmd);
481
482
  // Set ended state (3.48-14)
483
0
  hts_mutexlock(&opt->state.lock);
484
0
  opt->state.is_ended = 1;
485
0
  hts_mutexrelease(&opt->state.lock);
486
487
0
  return code;
488
0
}
489
490
/* Counts one more URL; a -1 count (-i, --continue) restarts from zero. */
491
0
static void cmdl_count_url(int *count) {
492
0
  if (*count < 0)
493
0
    *count = 0;
494
0
  (*count)++;
495
0
}
496
497
/* Steps *AT through cluster WORD as optcluster_next() does, setting *VALUE to
498
   the index of the word the option takes from *NEXT on (-qO <path>), or -1.
499
   PARAM, or NULL, marks the words taken as a value even when they begin with
500
   '-'. */
501
static hts_boolean cmdl_cluster_step(const char *word, size_t *at, hts_buf name,
502
                                     int argc, char *const *argv,
503
                                     const hts_boolean *param, int *next,
504
0
                                     int *value) {
505
0
  int pos;
506
507
0
  if (!optcluster_next(word, at, name))
508
0
    return HTS_FALSE;
509
0
  pos = optreal_find(name.p);
510
0
  *value = -1;
511
  /* only a lone -N reads the next word; a clustered one reads its digits */
512
0
  if (pos < 0 || optclass_of(pos) != HTS_OPT_PARAM1 ||
513
0
      strcmp(name.p, "-N") == 0 || *next >= argc ||
514
0
      (argv[*next][0] == '-' && (param == NULL || !param[*next])))
515
0
    return HTS_TRUE;
516
0
  *value = (*next)++;
517
0
  return HTS_TRUE;
518
0
}
519
520
/* Copies to CMD each word, from ARGV[FIRST] on, that an option of cluster WORD
521
   takes as its value (-qO <path>), counting a list's (-q%L) as URLs. Returns
522
   how many, or -1 out of memory. */
523
static int cmdl_cluster_params(cmdl_argv *cmd, const char *word, int argc,
524
0
                               char **argv, int first, int *argv_url) {
525
0
  char name[8];
526
0
  size_t at = 1;
527
0
  int next = first;
528
0
  int value;
529
530
0
  while (cmdl_cluster_step(word, &at, HTS_BUF(name), argc, argv, NULL, &next,
531
0
                           &value)) {
532
0
    if (value < 0)
533
0
      continue;
534
0
    if (!cmdl_add(cmd, argv[value]))
535
0
      return -1;
536
0
    cmdl_mark_param(cmd, cmd->argc - 1);
537
0
    if (strcmp(name, "-%L") == 0)
538
0
      cmdl_count_url(argv_url);
539
0
  }
540
0
  return next - first;
541
0
}
542
543
/* May the option at NA take a '-' word that optalias_check() put there as its
544
   parameter? A clustered or quoted spelling may not (#1425). */
545
0
static hts_boolean optparam_dash_ok(const cmdl_argv *cmd, int na) {
546
0
  return na + 1 < cmd->argc && cmd->param[na + 1];
547
0
}
548
549
/* Advances *NA to the word after the option, its value. HTS_FALSE after a panic
550
   with MSG and EXAMPLE (NULL for none) when that word is missing or reads as an
551
   option. */
552
static hts_boolean cmdl_take_value(httrackp *opt, const cmdl_argv *cmd, int *na,
553
0
                                   const char *msg, const char *example) {
554
0
  if (*na + 1 >= cmd->argc ||
555
0
      (cmd->argv[*na + 1][0] == '-' && !optparam_dash_ok(cmd, *na))) {
556
0
    cmdl_panic(opt, msg);
557
0
    if (example != NULL)
558
0
      printf("Example: %s\n", example);
559
0
    return HTS_FALSE;
560
0
  }
561
0
  (*na)++;
562
0
  return HTS_TRUE;
563
0
}
564
565
/* Store the --bundle-dir at na in opt and cmd as an absolute path, so doit.log
566
   finds it from anywhere. HTS_FALSE after a panic. */
567
0
static hts_boolean bundle_dir_set(httrackp *opt, cmdl_argv *cmd, int na) {
568
0
  const char *const dir = na + 1 < cmd->argc ? cmd->argv[na + 1] : NULL;
569
0
  const hts_boolean relative = dir != NULL && dir[0] != '/' && dir[0] != '\\' &&
570
0
                               !(dir[0] != '\0' && dir[1] == ':');
571
0
  char cwd[HTS_URLMAXSIZE] = "";
572
0
  char abs[HTS_URLMAXSIZE];
573
0
  char *copy;
574
575
0
  if (dir == NULL || (dir[0] == '-' && !optparam_dash_ok(cmd, na)) ||
576
0
      (relative && getcwd(cwd, sizeof(cwd)) == NULL) ||
577
0
      !slprintfbuff(abs, sizeof(abs), "%s%s%s", cwd, relative ? "/" : "",
578
0
                    dir) ||
579
0
      (copy = hts_arena_strdup(&cmd->tokens, abs)) == NULL) {
580
0
    cmdl_panic(opt, "Option bundle-dir needs a blank space and a folder");
581
0
    return HTS_FALSE;
582
0
  }
583
0
  cmd->argv[na + 1] = copy;
584
0
  StringCopy(opt->bundle_dir, abs);
585
0
  return HTS_TRUE;
586
0
}
587
588
/* Print the headers -#C lists for `url`, read back out of the ZIP cache. */
589
static void cmdl_print_cache_entry(httrackp *opt, cache_back *cache,
590
0
                                   const char *url, int sendb) {
591
0
  lien_adrfilsave afs;
592
0
  htsblk r;
593
0
  char msg[256], cdate[256];
594
595
0
  memset(&afs, 0, sizeof(afs));
596
  /* the entry name is read back from the cache: list an unparsable or
597
     unreadable one anyway, since its presence is what -#C is asked about */
598
0
  if (ident_url_absolute(url, &afs.af) == -1) {
599
0
    fprintf(stdout, "X-URL: %s\r\nX-Cache-Entry-Unreadable: yes\r\n\r\n", url);
600
0
    return;
601
0
  }
602
0
  r = cache_read_ro(opt, cache, afs.af.adr, afs.af.fil, "", hts_buf_none());
603
0
  if (r.statuscode == STATUSCODE_INVALID) {
604
0
    fprintf(stdout, "X-URL: %s\r\nX-Cache-Entry-Unreadable: yes\r\n\r\n", url);
605
0
    freet(r.adr);
606
0
    return;
607
0
  }
608
609
0
  infostatuscode_sized(HTS_SIZED(msg), r.statuscode);
610
0
  time_gmt_rfc822(HTS_BUF(cdate));
611
612
0
  fprintf(stdout, "HTTP/1.1 %d %s\r\n", r.statuscode, r.msg[0] ? r.msg : msg);
613
0
  fprintf(stdout, "X-Host: %s\r\n", afs.af.adr);
614
0
  fprintf(stdout, "X-File: %s\r\n", afs.af.fil);
615
0
  fprintf(stdout, "X-URL: %s\r\n", url);
616
0
  if (url_savename(&afs, /*former */ NULL, /*referer_adr */ NULL,
617
0
                   /*referer_fil */ NULL, /*opt */ opt, /*sback */ NULL,
618
0
                   /*cache */ cache, /*hash */ NULL, /*ptr */ 0,
619
0
                   /*numero_passe */ 0, /*mime_type */ NULL) != -1) {
620
0
    if (fexist_utf8(afs.save)) {
621
0
      fprintf(stdout, "Content-location: %s\r\n", afs.save);
622
0
    }
623
0
  }
624
0
  fprintf(stdout, "Date: %s\r\n", cdate);
625
0
  fprintf(stdout, "Server: HTTrack Website Copier/" HTTRACK_VERSION "\r\n");
626
0
  if (r.lastmodified[0]) {
627
0
    fprintf(stdout, "Last-Modified: %s\r\n", r.lastmodified);
628
0
  }
629
0
  if (r.etag[0]) {
630
0
    fprintf(stdout, "Etag: %s\r\n", r.etag);
631
0
  }
632
0
  if (r.totalsize >= 0) {
633
0
    fprintf(stdout, "Content-Length: " LLintP "\r\n", r.totalsize);
634
0
  }
635
0
  fprintf(stdout, "X-Content-Length: " LLintP "\r\n",
636
0
          (r.size >= 0) ? r.size : (-r.size));
637
0
  if (r.contenttype[0]) {
638
0
    fprintf(stdout, "Content-Type: %s\r\n", hts_effective_mime(r.contenttype));
639
0
  }
640
0
  if (r.cdispo[0]) {
641
0
    fprintf(stdout, "Content-Disposition: %s\r\n", r.cdispo);
642
0
  }
643
0
  if (r.contentencoding[0]) {
644
0
    fprintf(stdout, "Content-Encoding: %s\r\n", r.contentencoding);
645
0
  }
646
0
  if (r.is_chunk) {
647
0
    fprintf(stdout, "Transfer-Encoding: chunked\r\n");
648
0
  }
649
#if HTS_USEOPENSSL
650
  if (r.ssl) {
651
    fprintf(stdout, "X-SSL: yes\r\n");
652
  }
653
#endif
654
0
  if (r.is_write) {
655
0
    fprintf(stdout, "X-Direct-To-Disk: yes\r\n");
656
0
  }
657
0
  if (r.compressed) {
658
0
    fprintf(stdout, "X-Compressed: yes\r\n");
659
0
  }
660
0
  if (r.notmodified) {
661
0
    fprintf(stdout, "X-Not-Modified: yes\r\n");
662
0
  }
663
0
  if (r.is_chunk) {
664
0
    fprintf(stdout, "X-Chunked: yes\r\n");
665
0
  }
666
0
  fprintf(stdout, "\r\n");
667
  /* Send the body */
668
0
  if (sendb && r.adr) {
669
0
    fprintf(stdout, "%s\r\n", r.adr);
670
0
  }
671
0
  freet(r.adr);
672
0
}
673
674
/* Feeds the log backstop the passwords of the blank-separated start URLs,
675
   but not of the +/- filters among them, of the proxy and --why, and the
676
   secret -%X values. */
677
0
static void hts_secret_learn_options(httrackp *opt, const char *urls) {
678
0
  const char *u = urls;
679
680
0
  while (*u != '\0') {
681
0
    const size_t n = strcspn(u, HTS_BLANKS);
682
0
    char word[HTS_URLMAXSIZE * 2];
683
684
    // a start URL never exceeds the URL buffers, so a longer word is no URL
685
0
    if (n != 0 && *u != '+' && *u != '-' &&
686
0
        hts_buf_put_span(HTS_BUF(word), hts_span_at(u, n)))
687
0
      hts_secret_add_login(opt, word);
688
0
    u += n != 0 ? n : 1;
689
0
  }
690
0
  hts_secret_add_login(opt, StringBuff(opt->proxy.name));
691
0
  hts_secret_add_login(opt, StringBuff(opt->why_url));
692
0
  hts_secret_add_headers(opt, StringBuff(opt->headers));
693
0
}
694
695
/* Rewrites each blank-separated start URL of *url, which holds *url_sz bytes,
696
   but not the +/- filters, with hts_escape_typed_login(). Returns HTS_FALSE
697
   when out of memory. */
698
0
static hts_boolean hts_escape_start_logins(char **url, size_t *url_sz) {
699
0
  char *u = *url;
700
0
  const size_t cap = strlen(u) * 3 + 1; // an escape is three bytes
701
0
  char *const out = (char *) malloct(cap);
702
0
  size_t len = 0;
703
704
0
  if (out == NULL)
705
0
    return HTS_FALSE;
706
0
  while (*u != '\0') {
707
0
    const size_t n = strcspn(u, HTS_BLANKS);
708
709
0
    if (n == 0) {
710
0
      out[len++] = *u++;
711
0
    } else if (*u == '+' || *u == '-') {
712
0
      memcpy(out + len, u, n);
713
0
      len += n;
714
0
      u += n;
715
0
    } else {
716
0
      const char c = u[n];
717
718
0
      u[n] = '\0';
719
      // cap holds three bytes per input byte, so the escape cannot clip
720
0
      (void) hts_escape_typed_login(u, hts_buf_at(out + len, cap - len));
721
0
      len += strlen(out + len);
722
0
      u[n] = c;
723
0
      u += n;
724
0
    }
725
0
  }
726
0
  out[len] = '\0';
727
0
  freet(*url);
728
0
  *url = out;
729
0
  *url_sz = cap;
730
0
  return HTS_TRUE;
731
0
}
732
733
/* The caller frees x_cmd and *url, the start URLs, on every return. */
734
static int hts_main_run(int argc, char **argv, httrackp *opt, cmdl_argv *x_cmd,
735
0
                        char **url) {
736
0
  int argv_url = -1;          // 0: use the cache and doit.log
737
0
  char *argv_firsturl = NULL; // names the project by default
738
0
  size_t url_sz = 65535;
739
740
  /* 0, HTS_EXIT_MIRROR_ABORTED or HTS_EXIT_WARC_INCOMPLETE */
741
0
  int exit_code = 0;
742
743
  // the parametres
744
0
  int httrack_logmode = 3;      // ONE log file
745
746
0
  if (!ensure_url_capacity(opt, url, &url_sz, 65536))
747
0
    return -1;
748
  /* a library caller may run twice on one opt */
749
0
  hts_bundle_free(opt);
750
0
  StringCopy(opt->bundle_dir, "");
751
752
  // Create options
753
0
  _DEBUG_HEAD = 0;              // pas de debuggage en têtes
754
755
  /* command max-size check (3.43 ; 3.42-4) */
756
0
  {
757
0
    int i;
758
759
0
    for(i = 0; i < argc; i++) {
760
0
      if (strlen(argv[i]) >= HTS_CDLMAXSIZE) {
761
0
        cmdl_panic(opt, "argument too long");
762
0
        return -1;
763
0
      }
764
0
    }
765
0
  }
766
767
  /* Init root dir */
768
0
  hts_rootdir(argv[0]);
769
770
#ifdef _WIN32
771
#else
772
  /* Terminal is a tty, may ask questions and display funny information */
773
0
  if (hts_stdout_isterminal()) {
774
0
    opt->quiet = HTS_FALSE;
775
0
    opt->verbosedisplay = HTS_VERBOSE_SIMPLE;
776
0
  }
777
  /* Not a tty, no stdin input or funny output! */
778
0
  else {
779
0
    opt->quiet = HTS_TRUE;
780
0
    opt->verbosedisplay = HTS_VERBOSE_NONE;
781
0
  }
782
0
#endif
783
784
  // Data directory holding the HTML templates
785
0
  {
786
0
    char datadir[HTS_URLMAXSIZE * 2];
787
0
    char selfbuff[HTS_URLMAXSIZE * 2];
788
0
    const char *self = hts_self_path(HTS_BUF(selfbuff));
789
790
0
#ifdef HTS_HTTRACKDIR
791
0
    const char *const builtin = HTS_HTTRACKDIR;
792
#else
793
    const char *const builtin = "";
794
#endif
795
796
0
    if (self == NULL && argc > 0) {
797
0
      self = argv[0];
798
0
    }
799
0
    hts_resolve_datadir(HTS_BUF(datadir), self, builtin);
800
0
    StringCopy(opt->path_bin, datadir);
801
0
  }
802
803
  /* filter CR, LF, TAB.. */
804
0
  {
805
0
    int na;
806
807
0
    for(na = 1; na < argc; na++) {
808
0
      char *a;
809
810
0
      while((a = strchr(argv[na], '\x0d')))
811
0
        *a = ' ';
812
0
      while((a = strchr(argv[na], '\x0a')))
813
0
        *a = ' ';
814
0
      while((a = strchr(argv[na], 9)))
815
0
        *a = ' ';
816
      /* equivalent to "empty parameter" */
817
0
      if ((strcmp(argv[na], HTS_NOPARAM) == 0) || (strcmp(argv[na], HTS_NOPARAM2) == 0))        // (none)
818
        /* replacing "(none)"/"\"(none)\"" with "\"\"" always fits in place */
819
0
        strlcpybuff(argv[na], "\"\"", strlen(argv[na]) + 1);
820
0
      if (strncmp(argv[na], "-&", 2) == 0)
821
0
        argv[na][1] = '%';
822
0
    }
823
0
  }
824
825
  /* create the token block for the transformed command line */
826
0
  if (!cmdl_init(x_cmd, argc)) {
827
0
    cmdl_panic(opt, "Error, not enough memory");
828
0
    return -1;
829
0
  }
830
831
  /* Create new argc/argv, replace alias, count URLs, treat -h, -q, -i */
832
0
  {
833
0
    char BIGSTK _tmp_argv[2][HTS_CDLMAXSIZE];
834
0
    char BIGSTK tmp_error[HTS_CDLMAXSIZE];
835
0
    char *tmp_argv[2];
836
0
    int tmp_argc;
837
0
    int na;
838
839
0
    tmp_argv[0] = _tmp_argv[0];
840
0
    tmp_argv[1] = _tmp_argv[1];
841
    //
842
0
    argv_url = 0;               /* pour comptage */
843
    //
844
0
    if (!cmdl_add(x_cmd, argv[0])) {
845
0
      cmdl_panic(opt, "Error, not enough memory");
846
0
      return -1;
847
0
    }
848
0
    na = 1;                     /* commencer après nom_prg */
849
0
    while(na < argc) {
850
0
      int result = 1;
851
852
0
      tmp_argv[0][0] = tmp_argv[1][0] = '\0';
853
854
      /* Vérifier argv[] non vide */
855
0
      if (strnotempty(argv[na])) {
856
857
        /* Resolve an option alias, if any */
858
0
        result = optalias_check(argc, (const char *const *) argv, na, &tmp_argc,
859
0
                                (char **) tmp_argv, sizeof(_tmp_argv[0]),
860
0
                                HTS_BUF(tmp_error));
861
0
        if (!result) {
862
0
          cmdl_panic(opt, tmp_error);
863
0
          return -1;
864
0
        }
865
        /* an option that parsed, but not as asked (a --wide-/--tiny- prefix
866
           the alias cannot carry) */
867
0
        if (tmp_error[0] != '\0')
868
0
          fprintf(stderr, "* %s\n", tmp_error);
869
870
        /* Copier */
871
0
        if (!cmdl_add(x_cmd, tmp_argv[0]) ||
872
0
            (tmp_argc > 1 && !cmdl_add(x_cmd, tmp_argv[1]))) {
873
0
          cmdl_panic(opt, "Error, not enough memory");
874
0
          return -1;
875
0
        }
876
0
        if (tmp_argc > 1)
877
0
          cmdl_mark_param(x_cmd, x_cmd->argc - 1);
878
879
        /* Compter URLs et détecter -i,-q.. */
880
0
        if (tmp_argc == 1) {    /* pas -P & co */
881
0
          if (!hts_rule_would_be_read_as_opt(tmp_argv[0])) { /* not -c0 & co */
882
0
            cmdl_count_url(&argv_url);
883
0
            if (!argv_firsturl)
884
0
              argv_firsturl = x_cmd->argv[x_cmd->argc - 1];
885
0
          } else {
886
0
            if (strcmp(tmp_argv[0], "-h") == 0) {
887
0
              help(argv[0], !opt->quiet);
888
0
              return 0;
889
0
            } else if (strcmp(tmp_argv[0], "-#h") == 0) {
890
0
              printf("HTTrack version " HTTRACK_VERSION "%s\n",
891
0
                     hts_get_version_info(opt));
892
0
              return 0;
893
0
            } else {
894
0
              if (strncmp(tmp_argv[0], "--", 2)) { /* not a long option */
895
0
                if (cmdl_shortopt_has(tmp_argv[0], 'q'))
896
0
                  opt->quiet = HTS_TRUE; // never ask questions (nohup)
897
0
                if (cmdl_shortopt_has(tmp_argv[0], 'i')) { // doit.log!
898
0
                  argv_url = -1;
899
0
                  opt->quiet = HTS_TRUE;
900
0
                }
901
0
                if (optreal_find(tmp_argv[0]) < 0) {
902
0
                  const int taken = cmdl_cluster_params(
903
0
                      x_cmd, tmp_argv[0], argc, argv, na + result, &argv_url);
904
905
0
                  if (taken < 0) {
906
0
                    cmdl_panic(opt, "Error, not enough memory");
907
0
                    return -1;
908
0
                  }
909
0
                  result += taken;
910
0
                }
911
0
              } else if (strcmp(tmp_argv[0] + 2, "quiet") == 0) {
912
0
                opt->quiet = HTS_TRUE; // never prompt, for example under nohup
913
0
              } else if (strcmp(tmp_argv[0] + 2, "continue") == 0) {
914
0
                argv_url = -1;  /* forcer */
915
0
                opt->quiet = HTS_TRUE;
916
0
              }
917
0
            }
918
0
          }
919
0
        } else if (tmp_argc == 2) {
920
0
          if ((strcmp(tmp_argv[0], "-%L") == 0)) // URL list
921
0
            cmdl_count_url(&argv_url);
922
0
        }
923
0
      }
924
925
0
      na += result;
926
0
    }
927
0
    if (argv_url < 0)
928
0
      argv_url = 0;
929
930
    /* Nouveaux argc et argv */
931
0
    argv = x_cmd->argv;
932
0
    argc = x_cmd->argc;
933
0
  }
934
935
  // Option O and includerc
936
0
  {
937
0
    int loops = 0;
938
939
0
    while (loops < 2) {
940
0
      int na;
941
942
0
      for(na = 1; na < argc; na++) {
943
944
        /* another option's value is not an option (--user-agent -Oz) */
945
0
        if (hts_rule_would_be_read_as_opt(argv[na]) &&
946
0
            !x_cmd->param[na]) { // option
947
0
          const char *const word = argv[na];
948
0
          char name[8];
949
0
          size_t at = 1;
950
0
          int next = na + 1;
951
0
          int value;
952
953
          /* the word the parse loop gives -O, past -P's in -PO */
954
0
          while (cmdl_cluster_step(word, &at, HTS_BUF(name), argc, argv,
955
0
                                   x_cmd->param, &next, &value)) {
956
0
            if (strcmp(name, "-O") == 0) {
957
0
              if (value < 0) {
958
0
                cmdl_panic(opt, "Option O needs to be followed by a blank "
959
0
                                "space, and a path (or path,path)");
960
0
                printf("Example: -O /binary/\n");
961
0
                printf("Example: -O /binary/,/log/\n");
962
0
                return -1;
963
0
              } else {
964
0
                int i /*, j */ ;
965
0
                int inQuote;
966
0
                String *path;
967
0
                hts_boolean one_path = HTS_FALSE;
968
969
0
                if (word[at] == '1') /* only 1 arg */
970
0
                  one_path = HTS_TRUE;
971
0
                StringClear(opt->path_html);
972
0
                StringClear(opt->path_log);
973
0
                for (i = 0 /*, j = 0 */, inQuote = 0, path = &opt->path_html;
974
0
                     argv[value][i] != 0; i++) {
975
                  /* a plain -O strips quotes, which group a comma */
976
0
                  if (!one_path && argv[value][i] == '"') {
977
0
                    inQuote = !inQuote;
978
0
                  } else if (!inQuote && !one_path && argv[value][i] == ',') {
979
0
                    path = &opt->path_log;
980
0
                  } else {
981
0
                    StringAddchar(*path, argv[value][i]);
982
0
                  }
983
0
                }
984
0
                if (StringLength(opt->path_log) == 0) {
985
0
                  StringCopyS(opt->path_log, opt->path_html);
986
0
                }
987
988
0
                check_path(&opt->path_log, argv_firsturl);
989
0
                if (check_path(&opt->path_html, argv_firsturl)) {
990
0
                  opt->dir_topindex = HTS_TRUE; // rebuilt top index
991
0
                }
992
0
              }
993
0
            }
994
0
          }
995
996
0
        } // arg
997
998
0
      }                         // for
999
1000
      // path_html is already UTF-8 (argv is UTF-8 on Windows via
1001
      // hts_argv_utf8), so no re-encoding.
1002
0
      StringCopyN(opt->path_html_utf8, StringBuff(opt->path_html),
1003
0
                  StringLength(opt->path_html));
1004
      /* url_savename() would abort on the first long name under it */
1005
0
      if (StringLength(opt->path_html_utf8) >= HTS_SAVENAME_CAP) {
1006
0
        char msg[256];
1007
1008
0
        snprintf(msg, sizeof(msg),
1009
0
                 "Error, the mirror path is too long (%d bytes, at most %d)",
1010
                 /* not counting the slash check_path() appended */
1011
0
                 (int) StringLength(opt->path_html_utf8) - 1,
1012
0
                 HTS_SAVENAME_CAP - 2);
1013
0
        cmdl_panic(opt, msg);
1014
0
        return -1;
1015
0
      }
1016
1017
      /* if doit.log exists, or if new URL(s) defined, 
1018
         then DO NOT load standard config files */
1019
      /* (config files are added in doit.log) */
1020
      /* recreate a doit.log (no old doit.log or new URLs (and parameters)) */
1021
0
      if ((strnotempty(StringBuff(opt->path_log)))
1022
0
          || (strnotempty(StringBuff(opt->path_html))))
1023
0
        loops++;                // do not loop once again and do not include rc file (O option exists)
1024
0
      else {
1025
        /* Pass 2 only looks for an -O the rc file gave, so read it once. */
1026
0
        if (loops == 0 &&
1027
0
            ((!fexist_utf8(hts_logpath(opt, "hts-cache/doit.log"))) ||
1028
0
             (argv_url > 0))) {
1029
          /* first rc file that exists wins */
1030
0
          const hts_buf rcbuf = OPT_GET_HTS_BUF(opt);
1031
0
          cmdl_file_result res =
1032
0
              optinclude_file(hts_logpath(opt, HTS_HTTRACKRC), x_cmd);
1033
1034
0
          if (res == CMDL_FILE_MISSING)
1035
0
            res = optinclude_file(HTS_HTTRACKRC, x_cmd);
1036
          /* $HOME is not ours to bound, so a long one skips this rc */
1037
0
          if (res == CMDL_FILE_MISSING &&
1038
0
              hts_fpath_join(rcbuf, hts_gethome(), "/" HTS_HTTRACKRC))
1039
0
            res = optinclude_file(rcbuf.p, x_cmd);
1040
0
#ifdef HTS_HTTRACKCNF
1041
0
          if (res == CMDL_FILE_MISSING)
1042
0
            res = optinclude_file(HTS_HTTRACKCNF, x_cmd);
1043
0
#endif
1044
0
          if (res == CMDL_FILE_NOMEM) {
1045
0
            cmdl_panic(opt, "Error, not enough memory");
1046
0
            return -1;
1047
0
          }
1048
          /* the array may have been grown and moved */
1049
0
          argv = x_cmd->argv;
1050
0
          argc = x_cmd->argc;
1051
0
        } else
1052
0
          loops++;              // do not loop once again
1053
0
      }
1054
1055
0
      loops++;
1056
0
    } // while
1057
1058
0
  }                             // traiter -O
1059
1060
  /* load doit.log and insert in current command line */
1061
0
  if (fexist_utf8(hts_logpath(opt, "hts-cache/doit.log")) && (argv_url <= 0)) {
1062
0
    FILE *fp = FOPEN(hts_logpath(opt, "hts-cache/doit.log"), "rb");
1063
0
    if (fp) {
1064
0
      int insert_after = 1; /* insert after the program name */
1065
1066
0
      String buff = STRING_EMPTY;
1067
0
      char **tokens;
1068
0
      int ntokens = 0;
1069
0
      int i;
1070
0
      hts_boolean ok;
1071
      /* a TAB is argument data, since the writer leaves it unquoted */
1072
0
      const hts_boolean cut = hts_readline_alloc(
1073
0
          fp, &buff, HTS_READLINE_ALLOC_MAX, HTS_LINE_DROP_FF);
1074
1075
0
      fclose(fp);
1076
0
      fp = NULL;
1077
      /* any argument dropped would resume a different mirror */
1078
0
      if (cut) {
1079
0
        StringFree(buff);
1080
0
        cmdl_panic(opt, "Error, hts-cache/doit.log is too long to resume "
1081
0
                        "the mirror");
1082
0
        return -1;
1083
0
      }
1084
      /* "" unquotes to empty but is still a real token (#106) */
1085
0
      tokens = hts_split_args(StringBuffRW(buff), &ntokens,
1086
0
                              HTS_SPLIT_STRIP_QUOTES | HTS_SPLIT_DROP_EMPTY);
1087
0
      for (i = 0; tokens != NULL && i < ntokens; i++) {
1088
        /* inserted in order, after the program name */
1089
0
        if (!cmdl_ins(x_cmd, tokens[i], insert_after))
1090
0
          break;
1091
        /* this engine wrote the line and parsed it once already */
1092
0
        cmdl_mark_param(x_cmd, insert_after);
1093
0
        insert_after++;
1094
0
      }
1095
0
      ok = tokens != NULL && i == ntokens;
1096
0
      freet(tokens);
1097
0
      StringFree(buff);
1098
0
      if (!ok) {
1099
0
        cmdl_panic(opt, "Error, not enough memory");
1100
0
        return -1;
1101
0
      }
1102
      /* the array may have been grown and moved */
1103
0
      argv = x_cmd->argv;
1104
0
      argc = x_cmd->argc;
1105
0
    }
1106
0
  }
1107
1108
  /* Must run before the tree is created. */
1109
0
  opt->html_tree_new = hts_path_absent(StringBuff(opt->path_html));
1110
1111
  // No new cache but an old one? promote it
1112
0
  hts_cache_reconcile(opt, CACHE_RECONCILE_PROMOTE);
1113
1114
  /* Interrupted mirror over a pre-3.31 (2003) cache: cache_init() refuses that
1115
     .dat/.ndx pair, so say so rather than send the user restoring it. */
1116
0
  if (!opt->quiet) {
1117
0
    if (fexist_utf8(hts_logpath(opt, "hts-in_progress.lock"))) {
1118
0
      if ((fexist_utf8(hts_logpath(opt, "hts-cache/old.dat"))) &&
1119
0
          (fexist_utf8(hts_logpath(opt, "hts-cache/old.ndx")))) {
1120
0
        if (opt->log != NULL) {
1121
0
          fprintf(opt->log, "Warning!\n");
1122
0
          fprintf(opt->log,
1123
0
                  "An aborted mirror has been detected, over a cache this "
1124
0
                  "version can no longer read: hts-cache/old.dat and old.ndx "
1125
0
                  "are the pre-3.31 format, dropped in 2003.\n");
1126
0
          fprintf(opt->log,
1127
0
                  "Restart HTTrack with --continue (-iC1) to go on; the site "
1128
0
                  "will be mirrored again from scratch.\n");
1129
0
        }
1130
0
        return 0;
1131
0
      }
1132
0
    }
1133
0
  }
1134
  // remplacer "macros" comme --spider
1135
  // permet de lancer httrack sans a avoir à se rappeler de syntaxes comme
1136
  // p0C0I0Qc32 ..
1137
0
  {
1138
0
    int i;
1139
1140
0
    for (i = 0; i < argc; i++) {
1141
0
      if (argv[i][0] == '-') {
1142
0
        if (argv[i][1] == '-') {        // --xxx
1143
0
          if (hts_streq_ci(argv[i] + 2, "clean") ||
1144
0
              hts_streq_ci(argv[i] + 2, "tide")) {
1145
0
            argv[i][1] = '\0';
1146
0
            {
1147
0
              static const char *const log_names[] = {
1148
0
                  "hts-log.txt",           "hts-err.txt",
1149
0
                  "hts-cache/new.zip",     "hts-cache/old.zip",
1150
0
                  "hts-cache/new.dat",     "hts-cache/new.ndx",
1151
0
                  "hts-cache/old.dat",     "hts-cache/old.ndx",
1152
0
                  "hts-cache/new.lst",     "hts-cache/old.lst",
1153
0
                  "hts-cache/new.txt",     "hts-cache/old.txt",
1154
0
                  "hts-cache/damaged.zip", "hts-cache/damaged.lst",
1155
0
                  "hts-cache/damaged.txt", "hts-cache/readme.txt",
1156
0
                  "hts-cache/repair.zip",  "hts-cache/doit.log",
1157
0
                  "hts-in_progress.lock"};
1158
0
              size_t i;
1159
1160
0
              unlink_if_exists(opt, StringBuff(opt->path_html), "index.html");
1161
0
              for (i = 0; i < sizeof(log_names) / sizeof(log_names[0]); i++)
1162
0
                unlink_if_exists(opt, StringBuff(opt->path_log), log_names[i]);
1163
0
            }
1164
0
            purge_ref_dir(opt);
1165
0
            RMDIR(hts_logpath(opt, "hts-cache"));
1166
            //
1167
0
          } else if (hts_streq_ci(argv[i] + 2, "catchurl")) {
1168
            /* capture a URL through a temporary proxy */
1169
0
            argv_url = 1; // the URL arguments must still be passed on
1170
            /* argv[i] is "--catchurl"; "#P" fits after its first char */
1171
0
            strlcpybuff(argv[i] + 1, "#P", strlen(argv[i] + 1) + 1);
1172
            //
1173
0
          } else if (hts_streq_ci(argv[i] + 2, "updatehttrack")) {
1174
            /* Never implemented anywhere, and refusing it stops the untouched
1175
               string being re-walked as the cluster -u -p -d -a -t -e -h, whose
1176
               h exits 0 with an empty mirror. */
1177
0
            char s[HTS_CDLMAXSIZE + 256];
1178
1179
0
            slprintfbuff_clip(s, sizeof(s), "%s is not implemented", argv[i]);
1180
0
            cmdl_panic(opt, s);
1181
0
            return -1;
1182
0
          } else if (hts_streq_ci(argv[i] + 2, "bundle-dir")) {
1183
0
            i++; /* The option parser reads its value. */
1184
0
          }
1185
          //
1186
0
          else {
1187
0
            char s[HTS_CDLMAXSIZE + 256];
1188
1189
0
            slprintfbuff_clip(s, sizeof(s), "%s not recognized", argv[i]);
1190
0
            cmdl_panic(opt, s);
1191
0
            return -1;
1192
0
          }
1193
0
        }
1194
0
      }
1195
0
    }
1196
0
  }
1197
1198
  /* Engine self-tests: -#test lists them, -#test=NAME [args] runs one. Handled
1199
     here, ahead of the no-URL usage gate below, so they need no dummy URL. */
1200
0
  {
1201
0
    int k;
1202
1203
0
    for (k = 1; k < argc; k++) {
1204
0
      const char *const a = argv[k];
1205
1206
0
      if (a[0] == '-' && a[1] == '#' && strncmp(a + 2, "test", 4) == 0 &&
1207
0
          (a[6] == '\0' || a[6] == '=')) {
1208
#ifdef HTS_NO_SELFTEST
1209
        const int code = 1;
1210
1211
        fprintf(stderr, "httrack: this build has no engine self-tests "
1212
                        "(built with HTS_NO_SELFTEST)\n");
1213
#else
1214
0
        const char *const name = a[6] == '=' ? a + 7 : NULL;
1215
0
        const int code = hts_selftest(opt, name, argc - (k + 1), &argv[k + 1]);
1216
0
#endif
1217
1218
0
        return code;
1219
0
      }
1220
0
    }
1221
0
  }
1222
1223
  /* -#c[=KIND]: crash on purpose, to test crash handlers only (see
1224
     htscrashtest.h). Handled here so it needs no dummy URL either. */
1225
0
#ifdef HTS_CRASH_TEST
1226
0
  {
1227
0
    int k;
1228
1229
0
    for (k = 1; k < argc; k++) {
1230
0
      const char *const a = argv[k];
1231
1232
0
      if (a[0] == '-' && a[1] == '#' && a[2] == 'c' &&
1233
0
          (a[3] == '\0' || a[3] == '=')) {
1234
0
        const hts_crash_test_result done =
1235
0
            hts_crash_test(a[3] == '=' ? a + 4 : NULL);
1236
1237
0
        if (done == HTS_CRASH_UNKNOWN) {
1238
0
          char s[256];
1239
1240
0
          snprintf(s, sizeof(s), "Option #c expects one of: %s",
1241
0
                   hts_crash_test_kinds());
1242
0
          cmdl_panic(opt, s);
1243
0
          return -1;
1244
0
        }
1245
0
        if (done == HTS_CRASH_RAN) {
1246
0
          return -1;
1247
0
        }
1248
        /* Armed: the fault waits for a worker, so the mirror has to run. The
1249
           option parser below takes the argument again, and skips it. */
1250
0
        break;
1251
0
      }
1252
0
    }
1253
0
  }
1254
0
#endif
1255
1256
  // Pas d'URL
1257
0
  if (argv_url == 0) {
1258
    /* A previous cache exists: rename it. */
1259
0
    if (fexist_utf8(hts_logpath(opt, "hts-cache/new.zip")) ||
1260
0
        (fexist_utf8(hts_logpath(opt, "hts-cache/new.dat")) &&
1261
0
         fexist_utf8(hts_logpath(opt, "hts-cache/new.ndx")))) {
1262
      /* A cache is present. */
1263
0
      if (fexist_utf8(hts_logpath(opt, "hts-cache/doit.log"))) {
1264
0
        if (x_cmd->tokens.chunks != NULL) {
1265
0
          int m;
1266
1267
          // mode 1: valid cache (lock file exists), 2: cache to check
1268
0
          if (fexist_utf8(hts_logpath(opt, "hts-in_progress.lock"))) {
1269
0
            m = 1;
1270
0
          } else {
1271
0
            m = 2;
1272
0
          }
1273
0
          opt->cache = m;
1274
1275
0
          if (opt->quiet == 0) {        // sinon on continue automatiquement
1276
0
            HT_REQUEST_START;
1277
0
            ht_print(opt,
1278
0
                     "A cache (hts-cache/) has been found in the directory ");
1279
0
            ht_print(opt, StringBuff(opt->path_log));
1280
0
            ht_print(opt, LF);
1281
0
            if (m == 1) {
1282
0
              ht_print(opt, "That means that a transfer has been aborted" LF);
1283
0
              ht_print(opt, "OK to Continue ");
1284
0
            } else {
1285
0
              ht_print(
1286
0
                  opt,
1287
0
                  "That means you can update faster the remote site(s)" LF);
1288
0
              ht_print(opt, "OK to Update ");
1289
0
            }
1290
0
            ht_print(opt, "httrack");
1291
0
            cmdl_print_args(opt, x_cmd);
1292
0
            ht_print(opt, "?" LF);
1293
0
            HT_REQUEST_END;
1294
0
            if (!ask_continue(opt)) {
1295
0
              return 0;
1296
0
            }
1297
0
          }
1298
1299
0
        } else {
1300
0
          cmdl_panic(opt, "Error, not enough memory");
1301
0
          return -1;
1302
0
        }
1303
0
      } else { // log existe pas
1304
0
        cmdl_panic(opt, "A cache has been found, but no command line");
1305
0
        printf("Please launch httrack with proper parameters to reuse the "
1306
0
               "cache\n");
1307
0
        return -1;
1308
0
      }
1309
1310
0
    } else { // no URL given and no cache to resume
1311
0
      cmdl_panic(opt, "No URL to mirror, and no cache to resume from");
1312
0
      if (opt->quiet) {
1313
0
        help(argv[0], !opt->quiet);
1314
0
        return -1;
1315
0
      } else {
1316
0
        help_wizard(opt);
1317
0
        return -1;
1318
0
      }
1319
0
      return 0;
1320
0
    }
1321
0
  } else {                      // plus de 2 paramètres
1322
    // Does a lock file exist?
1323
0
    if (fexist_utf8(hts_logpath(opt, "hts-in_progress.lock"))) {
1324
1325
0
      opt->cache = HTS_CACHE_PRIORITY; // cache prioritaire
1326
0
      if (opt->quiet == 0) {
1327
0
        if ((fexist_utf8(hts_logpath(opt, "hts-cache/new.zip"))) ||
1328
0
            (fexist_utf8(hts_logpath(opt, "hts-cache/new.dat")) &&
1329
0
             fexist_utf8(hts_logpath(opt, "hts-cache/new.ndx")))) {
1330
0
          HT_REQUEST_START;
1331
0
          ht_print(opt, "There is a lock-file in the directory ");
1332
0
          ht_print(opt, StringBuff(opt->path_log));
1333
0
          ht_print(opt,
1334
0
                   LF "That means that a mirror has not been terminated" LF);
1335
0
          ht_print(opt, "Be sure you call httrack with proper parameters" LF);
1336
0
          ht_print(opt,
1337
0
                   "(The cache allows you to restart faster the transfer)" LF);
1338
0
          HT_REQUEST_END;
1339
0
          if (!ask_continue(opt)) {
1340
0
            return 0;
1341
0
          }
1342
0
        }
1343
0
      }
1344
0
    } else if (fexist_utf8(hts_optpath(opt, StringBuff(opt->path_html),
1345
0
                                       "index.html"))) {
1346
0
      opt->cache = HTS_CACHE_TEST_UPDATE;
1347
0
      if (opt->quiet == 0) {
1348
0
        if ((fexist_utf8(hts_logpath(opt, "hts-cache/new.zip"))) ||
1349
0
            (fexist_utf8(hts_logpath(opt, "hts-cache/new.dat")) &&
1350
0
             fexist_utf8(hts_logpath(opt, "hts-cache/new.ndx")))) {
1351
0
          HT_REQUEST_START;
1352
0
          ht_print(opt, "There is an index.html and a hts-cache folder in the "
1353
0
                        "directory ");
1354
0
          ht_print(opt, StringBuff(opt->path_log));
1355
0
          ht_print(opt, LF "A site may have been mirrored here, that could "
1356
0
                           "mean that you want to update it" LF);
1357
0
          ht_print(opt, "Be sure parameters are ok" LF);
1358
0
          HT_REQUEST_END;
1359
0
          if (!ask_continue(opt)) {
1360
0
            return 0;
1361
0
          }
1362
0
        } else {
1363
0
          HT_REQUEST_START;
1364
0
          ht_print(opt, "There is an index.html in the directory ");
1365
0
          ht_print(opt, StringBuff(opt->path_log));
1366
0
          ht_print(opt, " but no cache" LF);
1367
0
          ht_print(opt,
1368
0
                   "There is an index.html in the directory, but no cache" LF);
1369
0
          ht_print(opt, "A site may have been mirrored here, and erased.." LF);
1370
0
          ht_print(opt, "Be sure parameters are ok" LF);
1371
0
          HT_REQUEST_END;
1372
0
          if (!ask_continue(opt)) {
1373
0
            return 0;
1374
0
          }
1375
0
        }
1376
0
      }
1377
0
    }
1378
0
  }
1379
1380
  // Treat parameters
1381
  // Traiter les paramètres
1382
0
  {
1383
0
    char *com;
1384
0
    int na;
1385
0
    int prev_opt = 0;
1386
1387
    /* the flags below are indexed with argv, which still aliases x_cmd */
1388
0
    assertf(argv == x_cmd->argv && argc == x_cmd->argc);
1389
1390
0
    for(na = 1; na < argc; na++) {
1391
      /* the tokens the loop stepped over were the previous option's */
1392
0
      if (prev_opt != 0)
1393
0
        x_cmd->span[prev_opt] = na - prev_opt;
1394
0
      prev_opt = hts_rule_would_be_read_as_opt(argv[na]) ? na : 0;
1395
1396
0
      if (strcmp(argv[na], "--bundle-dir") == 0) {
1397
0
        if (!bundle_dir_set(opt, x_cmd, na)) {
1398
0
          return -1;
1399
0
        }
1400
0
        na++;
1401
0
        continue;
1402
0
      }
1403
0
      if (hts_rule_would_be_read_as_opt(argv[na])) { // option
1404
0
        const cmdl_at at = {opt, &com, argv, &na};
1405
1406
0
        com = argv[na] + 1;
1407
0
        while(*com) {
1408
0
          switch (*com) {
1409
0
          case ' ':
1410
0
          case 9:
1411
0
          case '-':
1412
0
          case '\0':
1413
0
            break;
1414
            //
1415
0
          case 'h':
1416
0
            help(argv[0], 0);
1417
0
            return 0;           // déja fait normalement
1418
            //
1419
0
          case 'g':            // récupérer un (ou plusieurs) fichiers isolés
1420
0
            opt->wizard = HTS_WIZARD_AUTO;
1421
0
            opt->cache = HTS_CACHE_NONE; // ni de cache
1422
0
            opt->makeindex = HTS_FALSE;  // no index either
1423
0
            httrack_logmode = 1;        // erreurs à l'écran
1424
0
            opt->savename_type = 1003;  // mettre dans le répertoire courant
1425
0
            opt->depth = 0;     // ne pas explorer la page
1426
0
            opt->accept_cookie = HTS_FALSE; // no cookies
1427
0
            opt->robots = HTS_ROBOTS_NEVER; // pas de robots
1428
0
            break;
1429
0
          case 'w':
1430
0
            opt->wizard = HTS_WIZARD_AUTO;
1431
0
            opt->travel = HTS_TRAVEL_SAME_ADDRESS;
1432
0
            opt->seeker = HTS_SEEKER_DOWN;
1433
0
            break;
1434
0
          case 'W':
1435
0
            opt->wizard = HTS_WIZARD_ASK; // Wizard-Help (pose des questions)
1436
0
            opt->travel = HTS_TRAVEL_SAME_ADDRESS;
1437
0
            opt->seeker = HTS_SEEKER_DOWN;
1438
0
            break;
1439
0
          case 'r':            // n'est plus le recurse get bestial mais wizard itou!
1440
0
            if (hts_isdigit((unsigned char) *(com + 1))) {
1441
              // One short of INT_MAX, as the seed is queued at depth + 1.
1442
0
              if (!glued_int(&at, &opt->depth, INT_MAX - 1))
1443
0
                return -1;
1444
0
            } else
1445
0
              opt->depth = 3;
1446
0
            break;
1447
            //
1448
            // note: les tests opt->depth sont pour éviter de faire
1449
            // un miroir du web (:-O) accidentelement ;-)
1450
0
          case 'a':            /*if (opt->depth==9999) opt->depth=3; */
1451
0
            opt->travel =
1452
0
                HTS_TRAVEL_SAME_ADDRESS + (opt->travel & HTS_TRAVEL_TEST_ALL);
1453
0
            break;
1454
0
          case 'd':            /*if (opt->depth==9999) opt->depth=3; */
1455
0
            opt->travel =
1456
0
                HTS_TRAVEL_SAME_DOMAIN + (opt->travel & HTS_TRAVEL_TEST_ALL);
1457
0
            break;
1458
0
          case 'l':            /*if (opt->depth==9999) opt->depth=3; */
1459
0
            opt->travel =
1460
0
                HTS_TRAVEL_SAME_TLD + (opt->travel & HTS_TRAVEL_TEST_ALL);
1461
0
            break;
1462
0
          case 'e':            /*if (opt->depth==9999) opt->depth=3; */
1463
0
            opt->travel =
1464
0
                HTS_TRAVEL_EVERYWHERE + (opt->travel & HTS_TRAVEL_TEST_ALL);
1465
0
            break;
1466
0
          case 't':
1467
0
            opt->travel |= HTS_TRAVEL_TEST_ALL;
1468
0
            break;
1469
0
          case 'n':
1470
0
            opt->nearlink = HTS_TRUE;
1471
0
            break;
1472
0
          case 'x':
1473
0
            opt->external = HTS_TRUE;
1474
0
            break;
1475
            //
1476
0
          case 'U':
1477
0
            opt->seeker = HTS_SEEKER_UP;
1478
0
            break;
1479
0
          case 'D':
1480
0
            opt->seeker = HTS_SEEKER_DOWN;
1481
0
            break;
1482
0
          case 'S':
1483
0
            opt->seeker = 0;
1484
0
            break;
1485
0
          case 'B':
1486
0
            opt->seeker = HTS_SEEKER_DOWN | HTS_SEEKER_UP;
1487
0
            break;
1488
            //
1489
0
          case 'Y':
1490
0
            opt->mirror_first_page = HTS_TRUE;
1491
0
            break;
1492
            //
1493
0
          case 'q':
1494
0
          case 'i':
1495
0
            opt->quiet = HTS_TRUE;
1496
0
            break;
1497
            //
1498
0
          case 'Q':
1499
0
            httrack_logmode = 0;
1500
0
            opt->debug = LOG_NOTICE;
1501
0
            break;
1502
0
          case 'v':
1503
0
            httrack_logmode = 1;
1504
0
            break;
1505
0
          case 'f':
1506
0
            httrack_logmode = 2;
1507
0
            if (*(com + 1) == '2')
1508
0
              httrack_logmode = 3;
1509
0
            while (hts_isdigit((unsigned char) *(com + 1)))
1510
0
              com++;
1511
0
            break;
1512
0
          case 'K':
1513
0
            opt->urlmode = HTS_URLMODE_ABSOLUTE;
1514
0
            if (hts_isdigit((unsigned char) *(com + 1))) {
1515
0
              readGluedEnum(&at, opt->urlmode, HTS_URLMODE_TRANSPARENT_PROXY);
1516
0
              if (opt->urlmode == HTS_URLMODE_ABSOLUTE) { // in fact K0 ==> K2
1517
                // and K ==> K0
1518
0
                opt->urlmode = HTS_URLMODE_RELATIVE;
1519
0
              }
1520
0
            }
1521
0
            break;
1522
0
          case 'c':
1523
0
            if (hts_isdigit((unsigned char) *(com + 1))) {
1524
0
              if (!glued_int(&at, &opt->maxsoc, INT_MAX))
1525
0
                return -1;
1526
0
              opt->maxsoc = hts_max_int(opt->maxsoc, 1); // At least one socket.
1527
0
            } else
1528
0
              opt->maxsoc = 4;
1529
1530
0
            break;
1531
            //
1532
0
          case 'p':
1533
0
            if (!glued_int(&at, &opt->getmode, INT_MAX))
1534
0
              return -1;
1535
0
            break;
1536
            //        
1537
0
          case 'G':
1538
0
            if (!glued_llint(&at, &opt->fragment, INT64_MAX))
1539
0
              return -1;
1540
0
            break;
1541
0
          case 'M':
1542
0
            if (!glued_llint(&at, &opt->maxsite, INT64_MAX))
1543
0
              return -1;
1544
0
            break;
1545
0
          case 'm':
1546
            // -m,10000 variant
1547
0
            if (*(com + 1) != ',') {
1548
0
              if (!glued_llint(&at, &opt->maxfile_nonhtml, INT64_MAX))
1549
0
                return -1;
1550
0
            }
1551
0
            if (*(com + 1) == ',' && hts_isdigit((unsigned char) *(com + 2))) {
1552
0
              com++;
1553
0
              if (!glued_llint(&at, &opt->maxfile_html, INT64_MAX))
1554
0
                return -1;
1555
0
            } else
1556
0
              opt->maxfile_html = -1;
1557
0
            break;
1558
            //
1559
0
          case 'T':
1560
0
            if (!glued_int(&at, &opt->timeout, INT_MAX))
1561
0
              return -1;
1562
0
            break;
1563
0
          case 'J':
1564
0
            if (!glued_int(&at, &opt->rateout, INT_MAX))
1565
0
              return -1;
1566
0
            break;
1567
0
          case 'R':
1568
0
            if (!glued_int(&at, &opt->retry, INT_MAX))
1569
0
              return -1;
1570
0
            break;
1571
0
          case 'E':
1572
0
            if (!glued_int(&at, &opt->maxtime, INT_MAX))
1573
0
              return -1;
1574
0
            break;
1575
0
          case 'H':
1576
0
            if (!glued_int(&at, &opt->hostcontrol, INT_MAX))
1577
0
              return -1;
1578
0
            break;
1579
0
          case 'A':
1580
0
            if (!glued_int(&at, &opt->maxrate, INT_MAX))
1581
0
              return -1;
1582
0
            break;
1583
1584
0
          case 'j':
1585
0
            opt->parsejava = HTSPARSE_DEFAULT;
1586
0
            if (!glued_int(&at, &opt->parsejava, INT_MAX))
1587
0
              return -1;
1588
0
            break;
1589
            //
1590
0
          case 'I':
1591
0
            opt->makeindex = glued_onoff(&com);
1592
0
            break;
1593
            //
1594
0
          case 'X':
1595
0
            opt->delete_old = glued_onoff(&com);
1596
0
            break;
1597
            //
1598
0
          case 'y':
1599
0
            opt->background_on_suspend = glued_onoff(&com);
1600
0
            break;
1601
            //
1602
0
          case 'b':
1603
0
            if (!glued_int(&at, &opt->accept_cookie, HTS_TRUE))
1604
0
              return -1;
1605
0
            break;
1606
            //
1607
0
          case 'N':
1608
0
            if (strcmp(argv[na], "-N") == 0) {  // Tout seul
1609
0
              if (!cmdl_take_value(opt, x_cmd, &na,
1610
0
                                   "Option N needs a number, or needs to be "
1611
0
                                   "followed by a blank space, and a string",
1612
0
                                   "-N4")) {
1613
0
                return -1;
1614
0
              } else {
1615
0
                if (strlen(argv[na]) >= 127) {
1616
0
                  cmdl_panic(opt, "Userdef structure string too long");
1617
0
                  return -1;
1618
0
                }
1619
0
                StringCopy(opt->savename_userdef, argv[na]);
1620
0
                if (StringLength(opt->savename_userdef) > 0)
1621
0
                  opt->savename_type = -1;      // userdef!
1622
0
                else
1623
0
                  opt->savename_type = 0;       // -N "" : par défaut
1624
0
              }
1625
0
            } else {
1626
              /* A glued run is a preset, never userdef, because sscanf("%d")
1627
                 past INT_MAX differs between LP64 and ILP32. */
1628
0
              const char *digits = com + 1;
1629
0
              int ndigits;
1630
1631
0
              for (ndigits = 0; hts_isdigit((unsigned char) *(com + 1));
1632
0
                   ndigits++)
1633
0
                com++;
1634
0
              if (ndigits > 0)
1635
0
                opt->savename_type =
1636
0
                    optalias_digits_fit(hts_span_at(digits, ndigits))
1637
0
                        ? atoi(digits)
1638
0
                        : 0;
1639
0
            }
1640
0
            break;
1641
0
          case 'L': {
1642
            /* L1 is the starred default, and what a bare -L selects; a run
1643
               too long to convert lands there too. */
1644
0
            const char *const digits = com + 1;
1645
0
            int ndigits, level = 1;
1646
1647
0
            for (ndigits = 0; hts_isdigit((unsigned char) *(com + 1));
1648
0
                 ndigits++)
1649
0
              com++;
1650
0
            if (ndigits > 0 &&
1651
0
                optalias_digits_fit(hts_span_at(digits, ndigits)))
1652
0
              level = atoi(digits);
1653
0
            switch (level) {
1654
0
            case 0: // 8-3 (ISO9660 L1)
1655
0
              opt->savename_83 = HTS_SAVENAME_83_DOS;
1656
0
              break;
1657
0
            case 1:
1658
0
              opt->savename_83 = HTS_SAVENAME_83_LONG;
1659
0
              break;
1660
0
            default: // 2 == ISO9660 (ISO9660 L2)
1661
0
              opt->savename_83 = HTS_SAVENAME_83_ISO9660;
1662
0
              break;
1663
0
            }
1664
0
          } break;
1665
0
          case 's':
1666
0
            if (hts_isdigit((unsigned char) *(com + 1))) {
1667
0
              readGluedEnum(&at, opt->robots, HTS_ROBOTS_ALWAYS_STRICT);
1668
0
            } else
1669
0
              opt->robots = HTS_ROBOTS_SOMETIMES;
1670
0
            break;
1671
0
          case 'o':
1672
0
            if (!glued_int(&at, &opt->errpage, HTS_TRUE))
1673
0
              return -1;
1674
0
            break;
1675
0
          case 'u':
1676
0
            if (!glued_int(&at, &opt->check_type, 2))
1677
0
              return -1;
1678
0
            break;
1679
            //
1680
0
          case 'C':
1681
0
            if (hts_isdigit((unsigned char) *(com + 1))) {
1682
0
              readGluedEnum(&at, opt->cache, HTS_CACHE_TEST_UPDATE);
1683
0
            } else
1684
0
              opt->cache = HTS_CACHE_PRIORITY;
1685
0
            break;
1686
0
          case 'k':
1687
0
            opt->all_in_cache = 1;
1688
0
            break;
1689
            //
1690
0
          case 'z':
1691
0
            if (opt->debug > LOG_INFO) {
1692
0
              opt->debug = LOG_DEBUG;  /* -Zz */
1693
0
            } else {
1694
0
              opt->debug = LOG_INFO;
1695
0
            }
1696
0
            break;              // petit debug
1697
0
          case 'Z':
1698
0
            if (opt->debug >= LOG_DEBUG) {
1699
0
              opt->debug = LOG_TRACE;  /* -Zz */
1700
0
            } else {
1701
0
              opt->debug = LOG_DEBUG;
1702
0
            }
1703
0
            break;              // GROS debug
1704
            //
1705
0
          case '&':
1706
0
          case '%':{           // deuxième jeu d'options
1707
0
              com++;
1708
0
              switch (*com) {
1709
0
              case 'M':
1710
0
                opt->mimehtml = glued_onoff(&com);
1711
0
                if (opt->mimehtml && opt->single_file) {
1712
0
                  cmdl_panic(
1713
0
                      opt,
1714
0
                      "-%M and --single-file are two ways to make one "
1715
0
                      "self-contained file, so pick one: MIME (-%M) carries "
1716
0
                      "text parts without the base64 tax and stores a shared "
1717
0
                      "asset once; single-file HTML opens anywhere by "
1718
0
                      "double-click.");
1719
0
                  return -1;
1720
0
                }
1721
0
                break;
1722
0
              case 'k':
1723
0
                opt->nokeepalive = !glued_onoff(&com);
1724
0
                break;
1725
0
              case 'x':
1726
0
                opt->passprivacy = glued_onoff(&com);
1727
0
                break;          // No passwords in html files
1728
0
              case 'q':
1729
0
                opt->includequery = glued_onoff(&com);
1730
0
                break;          // No passwords in html files
1731
0
              case 'Q':
1732
0
                opt->browser_headers = glued_onoff(&com);
1733
0
                break;
1734
0
              case 'I':
1735
0
                opt->kindex = HTS_KINDEX_TEXT;
1736
0
                if (hts_isdigit((unsigned char) *(com + 1))) {
1737
0
                  readGluedEnum(&at, opt->kindex, HTS_KINDEX_HTML);
1738
0
                }
1739
0
                break;          // Keyword Index
1740
0
              case 'c': {
1741
                /* GUIs pass this field as typed, so a bad one only warns */
1742
0
                const char *const val = com + 1;
1743
0
                double v;
1744
0
                const size_t span = optrate_read(val, &v);
1745
1746
0
                if (v < 0) {
1747
0
                  fprintf(stderr,
1748
0
                          "* Warning: connection-per-second rate \"%s\" "
1749
0
                          "ignored\n",
1750
0
                          val);
1751
0
                } else if (v > 0 && v < 1e-6) {
1752
0
                  fprintf(stderr,
1753
0
                          "* Warning: connection-per-second rate \"%.*s\" "
1754
0
                          "raised to 0.000001\n",
1755
0
                          (int) span, val);
1756
0
                  opt->maxconn = 1e-6f;
1757
0
                } else {
1758
0
                  opt->maxconn = (float) v;
1759
0
                }
1760
0
                com += span;
1761
0
              } break;
1762
0
              case 'e':
1763
0
                if (!glued_int(&at, &opt->extdepth, INT_MAX))
1764
0
                  return -1;
1765
0
                break;
1766
0
              case 'B':
1767
0
                opt->tolerant = glued_onoff(&com);
1768
0
                break;          // HTTP/1.0 notamment
1769
0
              case 'h':
1770
0
                opt->http10 = glued_onoff(&com);
1771
0
                break;          // HTTP/1.0
1772
0
              case 'z':
1773
0
                opt->nocompression = glued_onoff(&com);
1774
0
                break;          // pas de compression
1775
0
              case 'f':
1776
0
                opt->ftp_proxy = glued_onoff(&com);
1777
0
                break;          // proxy http pour ftp
1778
0
              case 'P':
1779
0
                opt->parseall = glued_onoff(&com);
1780
0
                break;          // tout parser
1781
0
              case 'n':
1782
0
                opt->norecatch = glued_onoff(&com);
1783
0
                break;          // ne pas reprendre fichiers effacés localement
1784
0
              case 's':
1785
0
                opt->sizehack = glued_onoff(&com);
1786
0
                break;          // hack sur content-length
1787
0
              case 'u':
1788
0
                opt->urlhack = glued_onoff(&com);
1789
0
                break;          // url hack
1790
0
              case 'j':         // --keep-www-prefix: keep www.X != X
1791
0
                opt->no_www_dedup = glued_onoff(&com);
1792
0
                break;
1793
0
              case 'o': // --keep-double-slashes: keep //
1794
0
                opt->no_slash_dedup = glued_onoff(&com);
1795
0
                break;
1796
0
              case 'y': // --keep-query-order: keep ?b&a order
1797
0
                opt->no_query_dedup = glued_onoff(&com);
1798
0
                break;
1799
0
              case 'v':
1800
0
                opt->verbosedisplay = HTS_VERBOSE_FULL;
1801
0
                if (hts_isdigit((unsigned char) *(com + 1))) {
1802
0
                  readGluedEnum(&at, opt->verbosedisplay, HTS_VERBOSE_FULL);
1803
0
                }
1804
0
                break;
1805
0
              case 'i':
1806
0
                opt->dir_topindex = glued_onoff(&com);
1807
0
                break;
1808
0
              case 'N':
1809
0
                opt->savename_delayed = HTS_SAVENAME_DELAYED_HARD;
1810
0
                if (hts_isdigit((unsigned char) *(com + 1))) {
1811
0
                  readGluedEnum(&at, opt->savename_delayed,
1812
0
                                HTS_SAVENAME_DELAYED_HARD);
1813
0
                }
1814
0
                break;
1815
0
              case 'D':
1816
0
                opt->delayed_cached = glued_onoff(&com);
1817
0
                break;          // url hack
1818
0
              case 'T':
1819
0
                opt->convert_utf8 = glued_onoff(&com);
1820
0
                break;          // convert to utf-8
1821
0
              case '!':
1822
0
                opt->bypass_limits = glued_onoff(&com);
1823
0
                break;
1824
0
              case 'w':        // disable specific plugin
1825
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1826
0
                                     "Option %w needs to be followed by a "
1827
0
                                     "blank space, and a module name",
1828
0
                                     "-%w httrack-plugin")) {
1829
0
                  return -1;
1830
0
                } else {
1831
0
                  StringCat(opt->mod_blacklist, argv[na]);
1832
0
                  StringCat(opt->mod_blacklist, "\n");
1833
0
                }
1834
0
                break;
1835
1836
                // preserve: no footer, original links
1837
0
              case 'p':
1838
0
                StringClear(opt->footer);
1839
0
                opt->urlmode = HTS_URLMODE_KEEP_ORIGINAL;
1840
0
                break;
1841
0
              case 'L':        // URL list
1842
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1843
0
                                     "Option %L needs to be followed by a "
1844
0
                                     "blank space, and a text filename",
1845
0
                                     "-%L \"mylist.txt\"")) {
1846
0
                  return -1;
1847
0
                } else {
1848
0
                  if (strlen(argv[na]) >= HTS_FILELIST_MAXSIZE) {
1849
0
                    cmdl_panic(opt, "File list string too long");
1850
0
                    return -1;
1851
0
                  }
1852
0
                  StringCopy(opt->filelist, argv[na]);
1853
0
                }
1854
0
                break;
1855
0
              case 'b':        // bind
1856
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1857
0
                                     "Option %b needs to be followed by a "
1858
0
                                     "blank space, and a local hostname",
1859
0
                                     "-%b \"ip4.localhost\"")) {
1860
0
                  return -1;
1861
0
                } else {
1862
0
                  if (strlen(argv[na]) >= HTS_BINDHOST_MAXSIZE) {
1863
0
                    cmdl_panic(opt, "Hostname string too long");
1864
0
                    return -1;
1865
0
                  }
1866
0
                  StringCopy(opt->proxy.bindhost, argv[na]);
1867
0
                }
1868
0
                break;
1869
0
              case 'S':        // Scan Rules list
1870
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1871
0
                                     "Option %S needs to be followed by a "
1872
0
                                     "blank space, and a text filename",
1873
0
                                     "-%S \"myfilterlist.txt\"")) {
1874
0
                  return -1;
1875
0
                } else {
1876
0
                  LLint fz;
1877
1878
0
                  fz = fsize_utf8(argv[na]);
1879
0
                  if (fz < 0) {
1880
0
                    cmdl_panic(opt, "File url list could not be opened");
1881
0
                    return -1;
1882
0
                  } else {
1883
0
                    FILE *fp = FOPEN(argv[na], "rb");
1884
1885
0
                    if (fp != NULL) {
1886
0
                      size_t cl = strlen(*url);
1887
0
                      const size_t fzs = llint_to_size_t(fz);
1888
0
                      const size_t capa = llint_grow_size_t(cl, fz, 8192);
1889
1890
0
                      if (capa == (size_t) -1) {
1891
0
                        fclose(fp);
1892
0
                        cmdl_panic(opt, "File url list too large");
1893
0
                        return -1;
1894
0
                      }
1895
0
                      if (!ensure_url_capacity(opt, url, &url_sz, capa)) {
1896
0
                        fclose(fp);
1897
0
                        return -1;
1898
0
                      }
1899
0
                      if (cl > 0) {     /* don't stick! (3.43) */
1900
0
                        (*url)[cl] = ' ';
1901
0
                        cl++;
1902
0
                      }
1903
0
                      if (!hts_fread_exact(*url + cl, (size_t) fzs, fp)) {
1904
0
                        fclose(fp);
1905
0
                        cmdl_panic(opt, "File url list could not be read");
1906
0
                        return -1;
1907
0
                      }
1908
0
                      fclose(fp);
1909
0
                      (*url)[cl + fzs] = '\0';
1910
0
                    }
1911
0
                  }
1912
0
                }
1913
0
                break;
1914
0
              case 'A':        // assume
1915
0
                if (!cmdl_take_value(
1916
0
                        opt, x_cmd, &na,
1917
0
                        "Option %A needs to be followed by a blank space, and "
1918
0
                        "a filesystemtype=mimetype/mimesubtype parameters",
1919
0
                        "-%A php3=text/html,asp=text/html")) {
1920
0
                  return -1;
1921
0
                } else {
1922
                  // --assume standard
1923
0
                  if (strcmp(argv[na], "standard") == 0) {
1924
0
                    StringCopy(opt->mimedefs, "\n");
1925
0
                    StringCat(opt->mimedefs, HTS_ASSUME_STANDARD);
1926
0
                    StringCat(opt->mimedefs, "\n");
1927
0
                  } else {
1928
0
                    char *a;
1929
1930
0
                    for(a = argv[na]; *a != '\0'; a++) {
1931
0
                      if (*a == ';') {  /* next one */
1932
0
                        StringAddchar(opt->mimedefs, '\n');
1933
0
                      } else if (*a == ',' || *a == '\n' || *a == '\r'
1934
0
                                 || *a == '\t') {
1935
0
                        StringAddchar(opt->mimedefs, ' ');
1936
0
                      } else {
1937
0
                        StringAddchar(opt->mimedefs, *a);
1938
0
                      }
1939
0
                    }
1940
0
                    StringAddchar(opt->mimedefs, '\n');
1941
0
                  }
1942
0
                }
1943
0
                break;
1944
                //
1945
0
              case 'l': // Accept-language
1946
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1947
0
                                     "Option %l needs to be followed by a "
1948
0
                                     "blank space, and an ISO language code",
1949
0
                                     "-%l \"en\"")) {
1950
0
                  return -1;
1951
0
                } else {
1952
0
                  if (strlen(argv[na]) >= HTS_LANGISO_MAXSIZE) {
1953
0
                    cmdl_panic(opt, "Lang list string too long");
1954
0
                    return -1;
1955
0
                  }
1956
0
                  StringCopy(opt->lang_iso, argv[na]);
1957
0
                  opt->lang_given = HTS_TRUE;
1958
0
                }
1959
0
                break;
1960
                //
1961
0
              case 'a':  // Accept
1962
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1963
0
                                     "Option %a needs to be followed by a "
1964
0
                                     "blank space, and a list of formats",
1965
0
                                     "-%a \"text/html,*/*;q=0.1\"")) {
1966
0
                  return -1;
1967
0
                } else {
1968
0
                  const int kind = hts_accept_kind_of(argv[na]);
1969
0
                  const char *const value =
1970
0
                      kind >= 0 ? strchr(argv[na], '=') + 1 : argv[na];
1971
1972
0
                  if (strlen(value) >= HTS_ACCEPT_MAXSIZE) {
1973
0
                    cmdl_panic(opt, "Accept list string too long");
1974
0
                    return -1;
1975
0
                  }
1976
0
                  if (kind < 0) {
1977
0
                    StringCopy(opt->accept, argv[na]);
1978
0
                    opt->accept_given = HTS_TRUE;
1979
0
                  } else {
1980
0
                    if (StringNotEmpty(opt->accept_kinds))
1981
0
                      StringCat(opt->accept_kinds, "\n");
1982
0
                    StringCat(opt->accept_kinds, argv[na]);
1983
0
                  }
1984
0
                }
1985
0
                break;
1986
                //
1987
0
              case 'X':  // HTTP header line
1988
0
                if (!cmdl_take_value(opt, x_cmd, &na,
1989
0
                                     "Option %X needs to be followed by a "
1990
0
                                     "blank space, and a raw HTTP header line",
1991
0
                                     "-%X \"X-Magic: 42\"")) {
1992
0
                  return -1;
1993
0
                } else {
1994
0
                  if (argv[na][0] == '\0') {
1995
0
                    cmdl_panic(opt, "Empty string given");
1996
0
                    return -1;
1997
0
                  }
1998
0
                  {
1999
0
                    const char *const why = http_custom_header_warning(
2000
0
                        StringBuff(opt->headers), argv[na]);
2001
2002
                    // redact a login header as the -%H log does
2003
0
                    if (why != NULL) {
2004
0
                      char shown[HTS_URLMAXSIZE * 2];
2005
2006
                      /* one write, so a merged stdout cannot split it */
2007
0
                      fprintf(stderr, "warning: -%%X %s: %s\n", why,
2008
0
                              hts_header_shown(opt, argv[na], HTS_BUF(shown)));
2009
0
                    }
2010
0
                  }
2011
                  /* A refused line goes in, so the request drops its folds. */
2012
0
                  if (StringNotEmpty(opt->headers) ||
2013
0
                      (argv[na][0] != ' ' && argv[na][0] != '\t')) {
2014
0
                    StringCat(opt->headers, argv[na]);
2015
0
                    StringCat(opt->headers, "\r\n"); /* separator */
2016
0
                  }
2017
0
                }
2018
0
                break;
2019
                //
2020
0
              case 'F':        // footer id
2021
0
                if (!cmdl_take_value(opt, x_cmd, &na,
2022
0
                                     "Option %F needs to be followed by a "
2023
0
                                     "blank space, and a footer string",
2024
0
                                     "-%F \"<!-- Mirrored from {addr}{path} by "
2025
0
                                     "HTTrack Website Copier/"
2026
0
                                     "{version} " HTTRACK_AFF_AUTHORS
2027
0
                                     ", {date} -->\"")) {
2028
0
                  return -1;
2029
0
                } else {
2030
0
                  if (strlen(argv[na]) >= HTS_FOOTER_MAXSIZE) {
2031
0
                    cmdl_panic(opt, "Footer string too long");
2032
0
                    return -1;
2033
0
                  }
2034
0
                  StringCopy(opt->footer, argv[na]);
2035
0
                }
2036
0
                break;
2037
0
              case 'H':        // debug headers
2038
0
                _DEBUG_HEAD = 1;
2039
0
                break;
2040
0
              case 'O':
2041
0
                printf
2042
0
                  ("Warning option -%%O is no longer supported\n");
2043
0
                break;
2044
0
              case 'U':        // setuid ; removed because insane
2045
0
                cmdl_panic(opt, "Option %U is no longer supported");
2046
0
                return -1;
2047
0
                break;
2048
2049
0
              case 'W':        // Wrapper callback
2050
                // --wrapper check-link=obj.so:check_link
2051
0
                if (!cmdl_take_value(
2052
0
                        opt, x_cmd, &na,
2053
0
                        "Option %W needs to be followed by a blank space, and "
2054
0
                        "a <callback-name>=<myfile.so>:<function-name> field",
2055
0
                        "-%W check-link=checklink.so:check")) {
2056
0
                  return -1;
2057
0
                } else {
2058
0
                  char *pos;
2059
2060
0
                  for(pos = argv[na];
2061
0
                      *pos != '\0' && *pos != '=' && *pos != ',' && *pos != ':';
2062
0
                      pos++) ;
2063
                  /* httrack --wrapper callback[,foo] */
2064
0
                  if (*pos == 0 || *pos == ',' || *pos == ':') {
2065
0
                    int ret;
2066
0
                    char *moduleName;
2067
2068
0
                    moduleName = hts_span_dup(hts_span_between(argv[na], pos));
2069
0
                    if (moduleName == NULL) {
2070
0
                      cmdl_panic(opt, "option %%W : out of memory");
2071
0
                      return -1;
2072
0
                    }
2073
0
                    if (*pos != '\0')
2074
0
                      *pos = ','; /* force the separator to ',' */
2075
0
                    ret = plug_wrapper(opt, moduleName, argv[na]);
2076
0
                    freet(moduleName);
2077
0
                    if (ret == 0) {
2078
0
                      char BIGSTK tmp[1024 * 2];
2079
2080
0
                      slprintfbuff_clip(tmp, sizeof(tmp),
2081
0
                                        "option %%W : unable to plug the "
2082
0
                                        "module %s (returncode != 1)",
2083
0
                                        argv[na]);
2084
0
                      cmdl_panic(opt, tmp);
2085
0
                      return -1;
2086
0
                    } else if (ret == -1) {
2087
0
                      char BIGSTK tmp[1024 * 2];
2088
0
                      char errbuf[HTS_STRERROR_SIZE];
2089
0
                      const int last_errno = errno;
2090
2091
0
                      slprintfbuff_clip(
2092
0
                          tmp, sizeof(tmp),
2093
0
                          "option %%W : unable to load the module %s: %s "
2094
0
                          "(check the library path ?)",
2095
0
                          argv[na], hts_strerror(last_errno, HTS_BUF(errbuf)));
2096
0
                      cmdl_panic(opt, tmp);
2097
0
                      return -1;
2098
0
                    }
2099
0
                  }
2100
                  /* Old style */
2101
                  /* httrack --wrapper save-name=callback:process,string */
2102
0
                  else if (*pos == '=') {
2103
0
                    fprintf(stderr,
2104
0
                            "Syntax error in option %%W : the old (<3.41) API is no more supported!\n");
2105
0
                    cmdl_panic(opt, "Syntax error in option %W : the old "
2106
0
                                    "(<3.41) API is no more supported!");
2107
0
                    printf("Example: -%%W check-link=checklink.so:check\n");
2108
0
                    return -1;
2109
0
                  } else {
2110
0
                    cmdl_panic(
2111
0
                        opt,
2112
0
                        "Syntax error in option %W : this function needs to be "
2113
0
                        "followed by a blank space, and a module name");
2114
0
                    printf("Example: -%%W check-link=checklink.so:check\n");
2115
0
                    return -1;
2116
0
                  }
2117
0
                }
2118
0
                break;
2119
2120
0
              case 'R':        // Referer
2121
0
                if (!cmdl_take_value(opt, x_cmd, &na,
2122
0
                                     "Option %R needs to be followed by a "
2123
0
                                     "blank space, and a referer URL",
2124
0
                                     "-%R \"http://www.example.com/\"")) {
2125
0
                  return -1;
2126
0
                } else {
2127
0
                  if (strlen(argv[na]) >= HTS_REFERER_MAXSIZE) {
2128
0
                    cmdl_panic(opt, "Referer URL too long");
2129
0
                    return -1;
2130
0
                  }
2131
0
                  StringCopy(opt->referer, argv[na]);
2132
0
                }
2133
0
                break;
2134
0
              case 'E':        // From Email address
2135
0
                if (!cmdl_take_value(opt, x_cmd, &na,
2136
0
                                     "Option %E needs to be followed by a "
2137
0
                                     "blank space, and an email",
2138
0
                                     "-%E \"postmaster@example.com\"")) {
2139
0
                  return -1;
2140
0
                } else {
2141
0
                  if (strlen(argv[na]) >= HTS_FROMEMAIL_MAXSIZE) {
2142
0
                    cmdl_panic(opt, "From email too long");
2143
0
                    return -1;
2144
0
                  }
2145
0
                  StringCopy(opt->from, argv[na]);
2146
0
                }
2147
0
                break;
2148
2149
0
              case 'g': // strip-query: accumulate "[pattern=]keys" entries
2150
0
                if (!cmdl_take_value(
2151
0
                        opt, x_cmd, &na,
2152
0
                        "Option strip-query needs a blank space and "
2153
0
                        "[host/pattern=]key1,key2,...",
2154
0
                        "--strip-query "
2155
0
                        "\"www.example.com/*=utm_source,sid\"")) {
2156
0
                  return -1;
2157
0
                } else {
2158
0
                  if (StringNotEmpty(opt->strip_query))
2159
0
                    StringCat(opt->strip_query, "\n");
2160
0
                  StringCat(opt->strip_query, argv[na]);
2161
0
                }
2162
0
                break;
2163
2164
0
              case 'C': // host-alias: accumulate "alias[,alias...]=host" rules
2165
0
                if (!cmdl_take_value(
2166
0
                        opt, x_cmd, &na,
2167
0
                        "Option host-alias needs a blank space and "
2168
0
                        "alias[,alias...]=canonical-host",
2169
0
                        "--host-alias "
2170
0
                        "\"www2.example.com,m.example.com=example.com\""
2171
0
                        "\nExample: "
2172
0
                        "--host-alias "
2173
0
                        "\"legacy.example.com=https://example.com\"")) {
2174
0
                  return -1;
2175
0
                } else {
2176
0
                  if (!hts_host_alias_rule_ok(argv[na])) {
2177
0
                    cmdl_panic(opt, "Invalid host-alias rule: expected "
2178
0
                                    "alias[,alias...]=canonical-host");
2179
0
                    printf("Rejected: ");
2180
0
                    print_rule_nologin(argv[na]);
2181
0
                    printf("Each side names a host, optionally behind its "
2182
0
                           "scheme; a path is not part of an address\n");
2183
0
                    return -1;
2184
0
                  }
2185
0
                  if (StringNotEmpty(opt->host_alias))
2186
0
                    StringCat(opt->host_alias, "\n");
2187
0
                  StringCat(opt->host_alias, argv[na]);
2188
0
                }
2189
0
                break;
2190
0
              case 'K': // cookies-file: the Netscape jar, rewritten at the end
2191
0
                if (!cmdl_take_value(
2192
0
                        opt, x_cmd, &na,
2193
0
                        "Option cookies-file needs a blank space and "
2194
0
                        "a cookies.txt path",
2195
0
                        "--cookies-file \"/home/me/cookies.txt\"")) {
2196
0
                  return -1;
2197
0
                } else {
2198
0
                  if (strlen(argv[na]) >= 1024) {
2199
0
                    cmdl_panic(opt, "Cookie file path too long");
2200
0
                    return -1;
2201
0
                  }
2202
0
                  StringCopy(opt->cookies_file, argv[na]);
2203
0
                }
2204
0
                break;
2205
0
              case 'd': // --changes: report what this crawl changed
2206
0
                opt->changes = glued_onoff(&com);
2207
0
                break;
2208
0
              case 'r': // warc / warc-file: write an ISO-28500 WARC archive
2209
0
                if (*(com + 1) == 'f') { // --warc-file NAME: explicit basename
2210
0
                  com++;
2211
0
                  if (!cmdl_take_value(opt, x_cmd, &na,
2212
0
                                       "Option warc-file needs a blank space "
2213
0
                                       "and a WARC name",
2214
0
                                       NULL))
2215
0
                    return -1;
2216
0
                  if (strlen(argv[na]) >= 1024) {
2217
0
                    cmdl_panic(opt, "WARC file name too long");
2218
0
                    return -1;
2219
0
                  }
2220
0
                  StringCopy(opt->warc_file, argv[na]);
2221
0
                } else if (*(com + 1) == 's') { // --warc-max-size N: rotation
2222
0
                  com++;
2223
0
                  if (!cmdl_take_value(
2224
0
                          opt, x_cmd, &na,
2225
0
                          "Option warc-max-size needs a blank space and a size",
2226
0
                          NULL))
2227
0
                    return -1;
2228
0
                  if (hts_is_quoted(hts_span_of(argv[na]))) {
2229
0
                    cmdl_panic_value(opt, "Option warc-max-size needs a size",
2230
0
                                     argv[na]);
2231
0
                    return -1;
2232
0
                  }
2233
0
                  { // reject non-numeric/negative/overflow; keep default 0
2234
                    // (single file)
2235
0
                    char *end;
2236
0
                    LLint v;
2237
0
                    const char *num = argv[na];
2238
2239
0
                    while (hts_isspace((unsigned char) *num))
2240
0
                      num++;
2241
0
                    errno = 0;
2242
0
                    v = strtoll(num, &end, 10);
2243
0
                    while (hts_isspace((unsigned char) *end))
2244
0
                      end++;
2245
0
                    if (hts_isdigit((unsigned char) *num) && *end == '\0' &&
2246
0
                        errno != ERANGE) {
2247
0
                      opt->warc_max_size = v;
2248
0
                    } else {
2249
0
                      cmdl_panic(
2250
0
                          opt,
2251
0
                          "Option warc-max-size needs a non-negative number");
2252
0
                      return -1;
2253
0
                    }
2254
0
                  }
2255
0
                } else if (*(com + 1) == 'c') { // --warc-cdx: sorted CDXJ index
2256
0
                  com++;
2257
0
                  opt->warc_cdx = HTS_TRUE;
2258
0
                } else if (*(com + 1) == 'z') { // --wacz: WACZ package
2259
0
                  com++;
2260
0
                  opt->warc_wacz = HTS_TRUE;
2261
0
                  opt->warc_cdx = HTS_TRUE; // WACZ embeds the CDXJ index
2262
0
                  if (!StringNotEmpty(opt->warc_file))
2263
0
                    StringCopy(opt->warc_file, WARC_AUTONAME);
2264
0
                } else { // --warc: auto-named archive under the output dir
2265
0
                  StringCopy(opt->warc_file, WARC_AUTONAME);
2266
0
                }
2267
0
                break;
2268
0
              case 'Z': // single-file: inline each page's assets as data: URIs
2269
0
                if (*(com + 1) == 's') { // --single-file-max-size N
2270
0
                  com++;
2271
0
                  if (!cmdl_take_value(
2272
0
                          opt, x_cmd, &na,
2273
0
                          "Option single-file-max-size needs a blank "
2274
0
                          "space and a size",
2275
0
                          NULL))
2276
0
                    return -1;
2277
0
                  { // a typo must not enable single-file on the default cap
2278
0
                    char *end;
2279
0
                    LLint v;
2280
2281
0
                    errno = 0;
2282
0
                    v = strtoll(argv[na], &end, 10);
2283
0
                    if (!hts_isdigit((unsigned char) argv[na][0]) ||
2284
0
                        *end != '\0' || errno == ERANGE || v <= 0) {
2285
0
                      cmdl_panic_value(
2286
0
                          opt,
2287
0
                          "Option single-file-max-size needs a positive size",
2288
0
                          argv[na]);
2289
0
                      return -1;
2290
0
                    }
2291
0
                    opt->single_file_max_size = v;
2292
0
                  }
2293
0
                  opt->single_file = HTS_TRUE;
2294
0
                } else {
2295
0
                  opt->single_file = glued_onoff(&com);
2296
0
                }
2297
0
                if (opt->single_file && opt->mimehtml) {
2298
0
                  cmdl_panic(
2299
0
                      opt,
2300
0
                      "-%M and --single-file are two ways to make one "
2301
0
                      "self-contained file, so pick one: MIME (-%M) carries "
2302
0
                      "text parts without the base64 tax and stores a shared "
2303
0
                      "asset once; single-file HTML opens anywhere by "
2304
0
                      "double-click.");
2305
0
                  return -1;
2306
0
                }
2307
0
                break;
2308
0
              case 'm': // sitemap / sitemap-url: seed the crawl from sitemaps
2309
0
                if (*(com + 1) == 'u') { // --sitemap-url URL: explicit sitemap
2310
0
                  com++;
2311
0
                  if (!cmdl_take_value(
2312
0
                          opt, x_cmd, &na,
2313
0
                          "Option sitemap-url needs a blank space and a URL",
2314
0
                          NULL))
2315
0
                    return -1;
2316
0
                  if (strlen(argv[na]) >= HTS_URLMAXSIZE) {
2317
0
                    cmdl_panic(opt, "Sitemap URL too long");
2318
0
                    return -1;
2319
0
                  }
2320
0
                  StringCopy(opt->sitemap_url, argv[na]);
2321
0
                } else { // --sitemap: robots.txt probe, then /sitemap.xml
2322
0
                  opt->sitemap = HTS_TRUE;
2323
0
                }
2324
0
                break;
2325
0
              case 'Y': // why: explain the filter verdict for a URL, no crawl
2326
0
                if (!cmdl_take_value(
2327
0
                        opt, x_cmd, &na,
2328
0
                        "Option why needs a blank space and a URL",
2329
0
                        "--why \"http://www.example.com/file.zip\"")) {
2330
0
                  return -1;
2331
0
                } else {
2332
0
                  if (strlen(argv[na]) >= HTS_URLMAXSIZE) {
2333
0
                    cmdl_panic(opt, "why URL too long");
2334
0
                    return -1;
2335
0
                  }
2336
0
                  StringCopy(opt->why_url, argv[na]);
2337
0
                }
2338
0
                break;
2339
0
              case 'J': // --max-retry-after: cap on an obeyed Retry-After
2340
0
              {
2341
0
                char *end;
2342
0
                LLint secs;
2343
2344
                /* strtoll reports overflow, which sscanf("%d") would clip. */
2345
0
                errno = 0;
2346
0
                secs = strtoll(com + 1, &end, 10);
2347
0
                if (end == com + 1 || errno == ERANGE || secs < 0) {
2348
0
                  cmdl_panic_value(opt,
2349
0
                                   "Invalid --max-retry-after (expected a "
2350
0
                                   "non-negative delay in seconds)",
2351
0
                                   com + 1);
2352
0
                  return -1;
2353
0
                }
2354
                /* Clip rather than abort, as back_set_retry_after does for the
2355
                   server's own value. */
2356
0
                if (secs > HTS_MAX_RETRY_AFTER_LIMIT) {
2357
0
                  opt->max_retry_after = HTS_MAX_RETRY_AFTER_LIMIT;
2358
                  /* Report what was stored, so a test can see the clip. */
2359
0
                  hts_log_print(opt, LOG_NOTICE,
2360
0
                                "--max-retry-after " LLintP
2361
0
                                "s is above the limit, using %ds",
2362
0
                                secs, opt->max_retry_after);
2363
0
                } else {
2364
0
                  opt->max_retry_after = (int) secs;
2365
0
                }
2366
0
                while (hts_isdigit((unsigned char) *(com + 1)))
2367
0
                  com++;
2368
0
              } break;
2369
0
              case 'G': // pause: randomized inter-file delay MIN[:MAX] seconds
2370
0
                if (!cmdl_take_value(opt, x_cmd, &na,
2371
0
                                     "Option pause needs a blank space and a "
2372
0
                                     "delay in seconds (MIN[:MAX])",
2373
0
                                     "--pause 5:10")) {
2374
0
                  return -1;
2375
0
                } else {
2376
0
                  double pmin = 0, pmax = 0;
2377
0
                  int nf;
2378
2379
0
                  nf = optpause_read(argv[na], &pmin, &pmax);
2380
0
                  if (nf < 2)
2381
0
                    pmax = pmin; /* a single value means a fixed delay */
2382
                  /* positive-form bounds: NaN fails every comparison, so this
2383
                     rejects it before the undefined (int)(NaN*1000) cast */
2384
0
                  if (nf < 1 || !(pmin >= 0 && pmax >= pmin && pmax <= 86400)) {
2385
0
                    cmdl_panic_value(opt,
2386
0
                                     "Invalid --pause range (expected "
2387
0
                                     "MIN[:MAX] seconds, 0<=MIN<=MAX<=86400)",
2388
0
                                     argv[na]);
2389
0
                    return -1;
2390
0
                  }
2391
0
                  opt->pause_min_ms = (int) (pmin * 1000.0);
2392
0
                  opt->pause_max_ms = (int) (pmax * 1000.0);
2393
0
                }
2394
0
                break;
2395
0
              case 't':        /* do not change type (ending) of filenames according to the MIME type */
2396
0
                opt->no_type_change = glued_onoff(&com);
2397
0
                break;
2398
2399
0
              default:{
2400
0
                cmdl_bad_option(opt, argv[na], "%", com);
2401
0
                return -1;
2402
0
                }
2403
0
                break;
2404
2405
0
              }
2406
0
            }
2407
0
            break;
2408
            //
2409
0
          case '@':{           // troisième jeu d'options
2410
0
              com++;
2411
0
              switch (*com) {
2412
0
              case 'i':
2413
#if HTS_INET6==0
2414
                /* Or -@i2's 2 is read as an option and refused (#615). */
2415
                while (hts_isdigit((unsigned char) *(com + 1)))
2416
                  com++;
2417
                printf
2418
                  ("Warning, option @i has no effect (v6 routines not compiled)\n");
2419
#else
2420
0
                {
2421
0
                  int res = 0;
2422
2423
0
                  if (!glued_int(&at, &res, INT_MAX))
2424
0
                    return -1;
2425
0
                  switch (res) {
2426
0
                  case 1:
2427
0
                  case 4:
2428
0
                    IPV6_resolver = 1;
2429
0
                    break;
2430
0
                  case 2:
2431
0
                  case 6:
2432
0
                    IPV6_resolver = 2;
2433
0
                    break;
2434
0
                  case 0:
2435
0
                    IPV6_resolver = 0;
2436
0
                    break;
2437
0
                  default: {
2438
0
                    char s[64];
2439
2440
0
                    snprintf(s, sizeof(s), "Unknown value for -@i: %d", res);
2441
0
                    cmdl_panic(opt, s);
2442
0
                    return -1;
2443
0
                  } break;
2444
0
                  }
2445
0
                }
2446
0
#endif
2447
0
                break;
2448
2449
0
              case 'm': { // --mptcp: Multipath TCP where the system has it
2450
0
                int on = 1;
2451
2452
0
                if (!glued_int(&at, &on, INT_MAX))
2453
0
                  return -1;
2454
0
                if (on != 0 && on != 1) {
2455
0
                  char s[64];
2456
2457
0
                  snprintf(s, sizeof(s), "Unknown value for -@m: %d", on);
2458
0
                  cmdl_panic(opt, s);
2459
0
                  return -1;
2460
0
                }
2461
0
                opt->mptcp = on != 0 ? HTS_TRUE : HTS_FALSE;
2462
0
                if (on != 0 && !hts_mptcp_available())
2463
0
                  printf("Warning, option @m has no effect "
2464
0
                         "(no Multipath TCP on this system)\n");
2465
0
              } break;
2466
2467
0
              case 'c': { // --check-cert: verify https certificates
2468
0
                int on = 1;
2469
2470
0
                if (!glued_int(&at, &on, INT_MAX))
2471
0
                  return -1;
2472
0
                if (on != 0 && on != 1) {
2473
0
                  char s[64];
2474
2475
0
                  snprintf(s, sizeof(s), "Unknown value for -@c: %d", on);
2476
0
                  cmdl_panic(opt, s);
2477
0
                  return -1;
2478
0
                }
2479
#ifdef _WIN32
2480
                // no system CA store is wired up for OpenSSL here yet
2481
                if (on != 0) {
2482
                  cmdl_panic(opt, "--check-cert is not supported on Windows "
2483
                                  "yet");
2484
                  return -1;
2485
                }
2486
#endif
2487
0
                opt->check_cert = on != 0 ? HTS_TRUE : HTS_FALSE;
2488
0
#if !HTS_USEOPENSSL
2489
0
                if (on != 0)
2490
0
                  printf("Warning, option @c has no effect "
2491
0
                         "(no https support compiled)\n");
2492
0
#endif
2493
0
              } break;
2494
2495
0
              default:{
2496
0
                cmdl_bad_option(opt, argv[na], "@", com);
2497
0
                return -1;
2498
0
              } break;
2499
0
              }
2500
0
            }
2501
0
            break;
2502
2503
            //
2504
0
          case '#':{           // non documenté
2505
0
              com++;
2506
0
              switch (*com) {
2507
0
#ifdef HTS_CRASH_TEST
2508
0
              case 'c':
2509
                /* The -#c pre-pass above already read this exact form and may
2510
                   have armed a worker. Other forms never reached it. */
2511
0
                if (com == argv[na] + 2 && (com[1] == '\0' || com[1] == '=')) {
2512
0
                  while (com[1] != '\0')
2513
0
                    com++;
2514
0
                }
2515
0
                break;
2516
0
#endif
2517
0
              case 'C':        // list cache files : httrack -#C '*spid*.gif' will attempt to find the matching file
2518
0
                {
2519
0
                  int hasFilter = 0;
2520
0
                  int found = 0;
2521
0
                  char *filter = NULL;
2522
0
                  cache_back cache;
2523
0
                  coucal cache_hashtable = coucal_new(0);
2524
0
                  int sendb = 0;
2525
2526
0
                  if (!glued_int(&at, &sendb, INT_MAX))
2527
0
                    return -1;
2528
0
                  if (!((na + 1 >= argc) || (argv[na + 1][0] == '-' &&
2529
0
                                             !optparam_dash_ok(x_cmd, na)))) {
2530
0
                    na++;
2531
0
                    hasFilter = 1;
2532
0
                    filter = argv[na];
2533
0
                  }
2534
2535
0
                  memset(&cache, 0, sizeof(cache_back));
2536
0
                  cache.type = 1;       // cache?
2537
0
                  cache.log = stdout;   // log?
2538
0
                  cache.errlog = stderr;        // err log?
2539
0
                  cache.ptr_ant = cache.ptr_last = 0;   // pointeur pour anticiper
2540
0
                  cache.hashtable = (void *) cache_hashtable;   /* copy backcache hash */
2541
0
                  cache.ro = 1; /* read only */
2542
0
                  if (cache.hashtable) {
2543
                    /* CACHE_ENTRYNAME_SIZE bounds a stored entry name; the
2544
                       "http://" a schemeless one gets back needs the slack */
2545
0
                    char BIGSTK url[CACHE_ENTRYNAME_SIZE + 8];
2546
2547
0
                    cache_init(&cache, opt);    /* load cache */
2548
                    /* Walk cache.hashtable, where cache_init() indexed every
2549
                       ZIP member by entry name minus any "http://". */
2550
0
                    if (cache.zipInput != NULL) {
2551
0
                      struct_coucal_enum e = coucal_enum_new(cache.hashtable);
2552
0
                      coucal_item *item;
2553
2554
0
                      while ((item = coucal_enum_next(&e)) != NULL) {
2555
0
                        const char *const key = (const char *) item->name;
2556
2557
                        /* a name read back from the cache can be anything, and
2558
                           strlncatbuff aborts rather than truncates: bound each
2559
                           append by what is left so an over-long one clips */
2560
0
                        url[0] = '\0';
2561
0
                        if (!link_has_authority(key))
2562
0
                          strlncatbuff(url, "http://", sizeof(url),
2563
0
                                       sizeof(url) - 1);
2564
0
                        strlncatbuff(url, key, sizeof(url),
2565
0
                                     sizeof(url) - 1 - strlen(url));
2566
0
                        if (hasFilter &&
2567
0
                            strjoker(url, filter, NULL, NULL) == NULL)
2568
0
                          continue;
2569
0
                        found++;
2570
0
                        if (!hasFilter) {
2571
0
                          fprintf(stdout, "%s\r\n", url);
2572
0
                        } else {
2573
0
                          cmdl_print_cache_entry(opt, &cache, url, sendb);
2574
0
                        }
2575
0
                      }
2576
0
                    }
2577
0
                  }
2578
0
                  if (!found) {
2579
0
                    fprintf(stderr, "No cache entry found%s%s%s\r\n",
2580
0
                            (hasFilter) ? " for '" : "",
2581
0
                            (hasFilter) ? filter : "", (hasFilter) ? "'" : "");
2582
0
                  }
2583
0
                  if (cache.zipInput != NULL)
2584
0
                    unzClose(cache.zipInput);
2585
0
                  coucal_delete(&cache_hashtable);
2586
0
                  return 0;
2587
0
                }
2588
0
                break;
2589
0
              case 'E':        // extract cache
2590
0
                if (!hts_extract_meta(StringBuff(opt->path_log))) {
2591
0
                  fprintf(stderr, "* error extracting meta-data\n");
2592
0
                  return 1;
2593
0
                }
2594
0
                fprintf(stderr, "* successfully extracted meta-data\n");
2595
0
                return 0;
2596
0
                break;
2597
0
              case 'X':
2598
0
                fprintf(stderr, "warning: option has no effect\n");
2599
0
                if (*(com + 1) == '0') {
2600
0
                  com++;
2601
0
                }
2602
0
                break;
2603
0
              case 'R':
2604
0
                {
2605
0
                  char *name;
2606
0
                  const char *why;
2607
0
                  unsigned long repaired = 0;
2608
0
                  unsigned long repairedBytes = 0;
2609
2610
0
                  if (fexist_utf8(hts_logpath(opt, "hts-cache/new.zip"))) {
2611
0
                    name = hts_logpath(opt, "hts-cache/new.zip");
2612
0
                  } else if (fexist_utf8(
2613
0
                                 hts_logpath(opt, "hts-cache/old.zip"))) {
2614
0
                    name = hts_logpath(opt, "hts-cache/old.zip");
2615
0
                  } else {
2616
0
                    fprintf(stderr, "* error: no cache found in %s\n",
2617
0
                            hts_logpath(opt, "hts-cache/new.zip"));
2618
0
                    return 1;
2619
0
                  }
2620
0
                  fprintf(stderr, "Cache: trying to repair %s\n", name);
2621
0
                  why = cache_repair(opt, name, &repaired, &repairedBytes);
2622
0
                  if (why != NULL) {
2623
0
                    fprintf(stderr, "Cache: %s\n", why);
2624
0
                    return 1;
2625
0
                  }
2626
0
                  fprintf(
2627
0
                      stderr,
2628
0
                      "Cache: %d bytes successfully recovered in %d entries\n",
2629
0
                      (int) repairedBytes, (int) repaired);
2630
0
                }
2631
0
                return 0;
2632
0
                break;
2633
0
              case '~':        /* internal lib test */
2634
0
                cmdl_panic(opt, "Option #~ is disabled for security reasons");
2635
0
                break;
2636
0
              case 'f':
2637
0
                opt->flush = HTS_TRUE;
2638
0
                break;
2639
0
              case 'h':
2640
0
                printf("HTTrack version " HTTRACK_VERSION "%s\n",
2641
0
                       hts_get_version_info(opt));
2642
0
                return 0;
2643
0
                break;
2644
0
              case 'p':        /* opt->aff_progress=1; deprecated */
2645
0
                break;
2646
0
              case 'S':
2647
0
                opt->shell = HTS_TRUE;
2648
0
                break;          // stdin sur un shell
2649
0
              case 'K':
2650
0
                opt->keyboard = HTS_TRUE;
2651
0
                break;          // vérifier stdin
2652
                //
2653
0
              case 'L':
2654
0
                if (!glued_int(&at, &opt->maxlink, INT_MAX))
2655
0
                  return -1;
2656
0
                break;
2657
0
              case 'F':
2658
0
                if (!glued_int(&at, &opt->maxfilter, HTS_FILTERS_MAX))
2659
0
                  return -1;
2660
0
                break;
2661
0
              case 'Z':
2662
0
                opt->makestat = HTS_TRUE;
2663
0
                break;
2664
0
              case 'T':
2665
0
                opt->maketrack = HTS_TRUE;
2666
0
                break;
2667
0
              case 'u':
2668
0
                if (!glued_int(&at, &opt->waittime, INT_MAX))
2669
0
                  return -1;
2670
0
                break;
2671
2672
0
              case 'P':{       // catchurl
2673
0
                help_catchurl(StringBuff(opt->path_log));
2674
0
                return 0;
2675
0
                }
2676
0
                break;
2677
2678
0
              case '!':
2679
0
                cmdl_panic(opt, "Option #! is disabled for security reasons");
2680
0
                return -1;
2681
0
                break;
2682
0
              case 'd':
2683
0
                opt->parsedebug = HTS_TRUE;
2684
0
                break;
2685
2686
                /* autotest */
2687
0
              case 't':        /* not yet implemented */
2688
0
                fprintf(stderr, "** AUTOCHECK OK\n");
2689
0
                return 0;
2690
0
                break;
2691
2692
0
              default:
2693
0
                printf("Internal option %c not recognized\n", *com);
2694
0
                break;
2695
0
              }
2696
0
            }
2697
0
            break;
2698
0
          case 'O':            // output path
2699
0
            while (hts_isdigit((unsigned char) com[1])) {
2700
0
              com++;
2701
0
            }
2702
0
            na++; // skip, already handled
2703
0
            break;
2704
0
          case 'P':            // proxy
2705
0
            if (!cmdl_take_value(
2706
0
                    opt, x_cmd, &na,
2707
0
                    "Option P needs to be followed by a blank space, and a "
2708
0
                    "proxy proxy:port or user:id@proxy:port",
2709
0
                    "-P proxy.example.com:8080")) {
2710
0
              return -1;
2711
0
            } else {
2712
0
              char BIGSTK pname[HTS_URLMAXSIZE * 2];
2713
2714
0
              opt->proxy.active = 1;
2715
0
              hts_parse_proxy(argv[na], HTS_BUF(pname), &opt->proxy.port);
2716
0
              StringCopy(opt->proxy.name, pname);
2717
0
            }
2718
0
            break;
2719
0
          case 'F':            // user-agent field
2720
0
            if (!cmdl_take_value(opt, x_cmd, &na,
2721
0
                                 "Option F needs to be followed by a blank "
2722
0
                                 "space, and a user-agent name",
2723
0
                                 "-F \"my_user_agent/1.0\"")) {
2724
0
              return -1;
2725
0
            } else {
2726
0
              StringCopy(opt->user_agent, argv[na]);
2727
0
              if (StringNotEmpty(opt->user_agent))
2728
0
                opt->user_agent_send = 1;
2729
0
              else
2730
0
                opt->user_agent_send = 0;       // -F "" désactive l'option
2731
0
            }
2732
0
            break;
2733
            //
2734
0
          case 'V':            // execute command
2735
0
            if (!cmdl_take_value(
2736
0
                    opt, x_cmd, &na,
2737
0
                    "Option V needs to be followed by a system-command string",
2738
0
                    "-V \"tar uvf some.tar \\$0\"")) {
2739
0
              return -1;
2740
0
            } else {
2741
0
              if (strlen(argv[na]) >= 2048) {
2742
0
                cmdl_panic(opt, "System-command length too long");
2743
0
                return -1;
2744
0
              }
2745
0
              StringCopy(opt->sys_com, argv[na]);
2746
0
              if (StringNotEmpty(opt->sys_com))
2747
0
                opt->sys_com_exec = HTS_TRUE;
2748
0
              else
2749
0
                opt->sys_com_exec = HTS_FALSE; // -V "" turns it off
2750
0
            }
2751
0
            break;
2752
            //
2753
0
          default:{
2754
0
            cmdl_bad_option(opt, argv[na], "", com);
2755
0
            return -1;
2756
0
            }
2757
0
            break;
2758
0
          }                     // switch
2759
0
          com++;
2760
0
        }                       // while
2761
2762
0
      } else { // URL/filters
2763
0
        char catbuff[CATBUFF_SIZE];
2764
        /* doit.log keeps argv, so the bundle suffix is cut from a copy */
2765
0
        char word[HTS_CDLMAXSIZE];
2766
0
        const size_t urlSize = strlen(argv[na]);
2767
0
        const size_t capa = strlen(*url) + urlSize + 32;
2768
2769
0
        if (hts_is_quoted(hts_span_at(argv[na], urlSize))) {
2770
0
          cmdl_panic_value(opt, "Argument refused", argv[na]);
2771
0
          return -1;
2772
0
        }
2773
        /* a filter may hold a quote on purpose, but usually it is a leftover */
2774
0
        if ((argv[na][0] == '+' || argv[na][0] == '-') &&
2775
0
            strchr(argv[na], '"') != NULL)
2776
0
          fprintf(stderr, "* Warning: filter %s holds a quote, kept as is\n",
2777
0
                  argv[na]);
2778
0
        assertf(urlSize < HTS_URLMAXSIZE);
2779
0
        strcpybuff(word, argv[na]);
2780
0
        if (argv[na][0] != '+' && argv[na][0] != '-') {
2781
0
          const char *const why = hts_bundle_take(opt, word);
2782
2783
0
          if (why != NULL) {
2784
0
            cmdl_panic_value(opt, why, argv[na]);
2785
0
            return -1;
2786
0
          }
2787
0
        }
2788
0
        if (urlSize < HTS_URLMAXSIZE) {
2789
0
          if (!ensure_url_capacity(opt, url, &url_sz, capa))
2790
0
            return -1;
2791
0
          if (strnotempty(*url))
2792
0
            strlcatbuff(*url, " ", url_sz); // separator space
2793
          /* a rule is decoded once, where the engine splits the rules */
2794
0
          append_escape_spc_url(
2795
0
              word[0] == '+' || word[0] == '-'
2796
0
                  ? word
2797
0
                  : unescape_http_unharm(catbuff, sizeof(catbuff), word, 1),
2798
0
              hts_buf_at(*url, url_sz));
2799
0
        }
2800
0
      } // if argv=- etc.
2801
2802
0
    }                           // for
2803
0
    if (prev_opt != 0)
2804
0
      x_cmd->span[prev_opt] = na - prev_opt;
2805
0
  }
2806
  // a typed login reads up to the last '@' before the first '/'
2807
0
  if (!hts_escape_start_logins(url, &url_sz)) {
2808
0
    cmdl_panic(opt, "Not enough memory");
2809
0
    return -1;
2810
0
  }
2811
2812
#ifdef _WIN32
2813
#else
2814
0
#ifndef HTS_DO_NOT_USE_UID
2815
  /* Check we do not run as r00t */
2816
0
  {
2817
0
    uid_t userid = getuid();
2818
2819
0
    if (userid == 0) {              /* running as r00t */
2820
0
      printf("WARNING! You are running this program as root!\n");
2821
0
      printf
2822
0
        ("It might be a good idea to run as a different user\n");
2823
0
    }
2824
0
  }
2825
0
#endif
2826
0
#endif
2827
2828
0
  io_flush;
2829
2830
  // If both cache generations exist, keep the most complete one
2831
0
  hts_cache_reconcile(opt, CACHE_RECONCILE_INTERRUPTED);
2832
0
  {
2833
    /* Sized to the concat-buffer capacity so it can always hold the lock-file
2834
       path produced by fconcat(), even with a long log path (issue #183). */
2835
0
    char n_lock[OPT_GET_BUFF_SIZE(opt)];
2836
2837
0
    char n_lock_staged[OPT_GET_BUFF_SIZE(opt)];
2838
2839
    // on peut pas avoir un affichage ET un fichier log
2840
    // ca sera pour la version 2
2841
0
    if (httrack_logmode == 1) {
2842
0
      opt->log = stdout;
2843
0
      opt->errlog = stderr;
2844
0
    } else if (httrack_logmode >= 2) {
2845
      // deux fichiers log
2846
      // path_log holds UTF-8 bytes (argv is UTF-8): the ANSI file calls would
2847
      // read them as the codepage and drop the logs into a mangled twin (#630).
2848
0
      structcheck_utf8(StringBuff(opt->path_log));
2849
0
      unlink_if_exists(opt, StringBuff(opt->path_log), "hts-log.txt");
2850
0
      unlink_if_exists(opt, StringBuff(opt->path_log), "hts-err.txt");
2851
2852
      /* Check FS directory structure created */
2853
0
      structcheck_utf8(StringBuff(opt->path_log));
2854
2855
      /* owner-only: the log echoes the command line and URLs with passwords */
2856
0
      opt->log = hts_fopen_private(hts_logpath(opt, "hts-log.txt"), "w");
2857
0
      if (httrack_logmode == 2)
2858
0
        opt->errlog = hts_fopen_private(hts_logpath(opt, "hts-err.txt"), "w");
2859
0
      else
2860
0
        opt->errlog = opt->log;
2861
0
      if (opt->log == NULL) {
2862
        /* path_log is not argv-gated: ~ expansion admits 2047 bytes */
2863
0
        char s[HTS_CDLMAXSIZE + 256];
2864
2865
0
        snprintf(s, sizeof(s), "Unable to create log file %s",
2866
0
                 hts_logpath(opt, "hts-log.txt"));
2867
0
        cmdl_panic(opt, s);
2868
0
        return -1;
2869
0
      } else if (opt->errlog == NULL) {
2870
0
        char s[HTS_CDLMAXSIZE + 256];
2871
2872
0
        snprintf(s, sizeof(s), "Unable to create log file %s",
2873
0
                 hts_logpath(opt, "hts-err.txt"));
2874
0
        cmdl_panic(opt, s);
2875
0
        return -1;
2876
0
      }
2877
2878
0
    } else {
2879
0
      opt->log = NULL;
2880
0
      opt->errlog = NULL;
2881
0
    }
2882
2883
    // -%H may run before path_log exists, so create it first.
2884
0
    if (_DEBUG_HEAD) {
2885
0
      structcheck_utf8(StringBuff(opt->path_log));
2886
      /* owner-only: it records request headers, Authorization included */
2887
0
      ioinfo = hts_fopen_private(hts_logpath(opt, "hts-ioinfo.txt"), "wb");
2888
0
      if (ioinfo == NULL)
2889
0
        hts_log_print(opt, LOG_WARNING | LOG_ERRNO,
2890
0
                      "unable to create header debug file %s",
2891
0
                      hts_logpath(opt, "hts-ioinfo.txt"));
2892
0
    }
2893
2894
    // un petit lock-file pour indiquer un miroir en cours, ainsi qu'un éventuel fichier log
2895
0
    {
2896
0
      char t[256];
2897
0
      char *masked_url;
2898
0
      const char *shown_url;
2899
2900
0
      time_local_rfc822(HTS_BUF(t)); // stamps the generated file below
2901
2902
      /* readme for information purpose */
2903
0
      {
2904
0
        FILE *fp = FOPEN(hts_logpath(opt, "hts-cache/readme.txt"), "wb");
2905
0
        if (fp) {
2906
0
          fprintf(fp, "What's in this folder?" LF);
2907
0
          fprintf(fp, "" LF);
2908
0
          fprintf(fp,
2909
0
                  "This folder (hts-cache) has been generated by WinHTTrack "
2910
0
                  HTTRACK_VERSION "%s" LF, hts_get_version_info(opt));
2911
0
          fprintf(fp, "and is used for updating this website." LF);
2912
0
          fprintf(fp,
2913
0
                  "(The HTML website structure is stored here to allow fast updates)"
2914
0
                  LF "" LF);
2915
0
          fprintf(fp,
2916
0
                  "DO NOT delete this folder unless you do not want to update the mirror in the future!!"
2917
0
                  LF);
2918
0
          fprintf(fp,
2919
0
                  "(you can safely delete old.zip and old.lst files, however)"
2920
0
                  LF);
2921
0
          fprintf(fp, "" LF);
2922
0
          fprintf(fp, HTS_LOG_SECURITY_WARNING);
2923
0
          fclose(fp);
2924
0
        }
2925
0
      }
2926
2927
0
      strcpybuff(n_lock, hts_logpath(opt, "hts-in_progress.lock"));
2928
2929
      // vérifier existence de la structure (path_html/path_log are UTF-8, use
2930
      // the UTF-8 mkdir path)
2931
0
      structcheck_utf8(hts_optpath(opt, StringBuff(opt->path_html), "/"));
2932
0
      structcheck_utf8(hts_logpath(opt, "/"));
2933
2934
      // reprise/update
2935
0
      if (opt->cache) {
2936
0
        FILE *fp;
2937
2938
#ifdef _WIN32
2939
        hts_mkdir_utf8(hts_logpath(opt, "hts-cache"));
2940
#else
2941
0
        mkdir(hts_logpath(opt, "hts-cache"), HTS_PROTECT_FOLDER);
2942
0
#endif
2943
        /* owner-only: the command line may carry credentials */
2944
0
        fp = hts_fopen_private(hts_logpath(opt, "hts-cache/doit.log"), "wb");
2945
0
        if (fp) {
2946
0
          String line = STRING_EMPTY;
2947
2948
0
          cmdl_doit_line(&line, x_cmd);
2949
0
          if (StringLength(line) != 0)
2950
0
            fwrite(StringBuff(line), 1, StringLength(line), fp);
2951
0
          StringFree(line);
2952
0
          fprintf(fp, LF);
2953
0
          fprintf(fp, "File generated automatically on %s, do NOT edit" LF, t);
2954
0
          fprintf(fp, LF);
2955
0
          fprintf(fp,
2956
0
                  "To update a mirror, just launch httrack without any parameters"
2957
0
                  LF);
2958
0
          fprintf(fp, "The existing cache will be used (and modified)" LF);
2959
0
          fprintf(fp,
2960
0
                  "To have other options, retype all parameters and launch HTTrack"
2961
0
                  LF);
2962
0
          fprintf(fp,
2963
0
                  "To continue an interrupted mirror, just launch httrack without any parameters"
2964
0
                  LF);
2965
0
          fprintf(fp, LF);
2966
0
          fclose(fp);
2967
0
          fp = NULL;
2968
0
        }
2969
0
      }
2970
      // petit message dans le lock
2971
0
      strcpybuff(n_lock_staged, hts_logpath(opt, "hts-in_progress.tmp"));
2972
      /* Write the lock aside and move it on, so it is already dated back when
2973
         scripts see it. A failed move falls back to writing it in place. */
2974
0
      if (!write_progress_lock(opt, n_lock_staged, t, argc, argv) ||
2975
0
          !hts_rename_over(opt, n_lock_staged, n_lock)) {
2976
0
        UNLINK(n_lock_staged);
2977
0
        if (!write_progress_lock(opt, n_lock, t, argc, argv) &&
2978
0
            opt->log != NULL)
2979
0
          hts_log_print(opt, LOG_WARNING,
2980
0
                        "engine: could not create hts-in_progress.lock, so"
2981
0
                        " this mirror cannot be stopped or paused by a file");
2982
0
      }
2983
0
      hts_secret_learn_options(opt, *url);
2984
0
      masked_url = hts_mask_passwords(*url, HTS_MASK_LIST);
2985
0
      shown_url = masked_url != NULL ? masked_url : "(out of memory)";
2986
      // hts-log.txt
2987
0
      if (opt->log) {
2988
0
        int i, opt_at = 0;
2989
2990
0
        fprintf(opt->log,
2991
0
                "HTTrack" HTTRACK_VERSION "%s launched on %s at %s" LF,
2992
0
                hts_get_version_info(opt), t, shown_url);
2993
0
        fprintf(opt->log, "(");
2994
0
        for(i = 0; i < argc; i++) {
2995
0
          const char *arg = argv[i]; // already UTF-8 on every platform
2996
          // quoted if it holds a blank and no quote
2997
0
          const hts_boolean quote =
2998
0
              strchr(arg, ' ') != NULL && strchr(arg, '\"') == NULL;
2999
          // a start URL, or a -P, -%mu, -%R or --why value, is one address
3000
0
          hts_boolean addr;
3001
0
          char *masked;
3002
3003
0
          if (x_cmd->span[i] != 0) {
3004
0
            opt_at = x_cmd->span[i] > 1 ? i : 0;
3005
0
            addr = HTS_FALSE;
3006
0
          } else if (opt_at != 0 && i < opt_at + x_cmd->span[opt_at]) {
3007
0
            addr = cmdl_shortopt_has(argv[opt_at], 'P') ||
3008
0
                   cmdl_shortopt_named(argv[opt_at], "-%mu") ||
3009
0
                   cmdl_shortopt_named(argv[opt_at], "-%R") ||
3010
0
                   cmdl_shortopt_named(argv[opt_at], "-%Y");
3011
0
          } else {
3012
0
            opt_at = 0;
3013
0
            addr = i != 0 && arg[0] != '+' && arg[0] != '-';
3014
0
          }
3015
0
          masked = addr ? hts_mask_passwords(arg, HTS_MASK_ADDR) : NULL;
3016
3017
0
          if (quote)
3018
0
            fputc('"', opt->log);
3019
          // a -%X login header gets the -%H log's redaction
3020
0
          if (!addr || masked != NULL)
3021
0
            fprintfio(opt->log, addr ? masked : arg, "", opt);
3022
0
          fputs(quote ? "\" " : " ", opt->log);
3023
0
          freet(masked);
3024
0
        }
3025
0
        fprintf(opt->log, ")" LF);
3026
0
        fprintf(opt->log, LF);
3027
0
        fprintf(opt->log,
3028
0
                "Information, Warnings and Errors reported for this mirror:"
3029
0
                LF);
3030
0
        fprintf(opt->log, HTS_LOG_SECURITY_WARNING);
3031
0
        fprintf(opt->log, LF);
3032
0
      }
3033
3034
0
      if (httrack_logmode) {
3035
0
        printf("Mirror launched on %s by HTTrack Website Copier/"
3036
0
               HTTRACK_VERSION "%s " HTTRACK_AFF_AUTHORS "" LF, t,
3037
0
               hts_get_version_info(opt));
3038
0
        if (opt->wizard == HTS_WIZARD_NONE) {
3039
0
          printf("mirroring %s with %d levels, %d "
3040
0
                 "sockets,t=%d,s=%d,logm=%d,lnk=%d,mdg=%d\n",
3041
0
                 shown_url, opt->depth, opt->maxsoc, opt->travel, opt->seeker,
3042
0
                 httrack_logmode, opt->urlmode, opt->getmode);
3043
0
        } else { // the magic wizard
3044
0
          printf("mirroring %s with the wizard help..\n", shown_url);
3045
0
        }
3046
0
      }
3047
0
      freet(masked_url);
3048
0
    }
3049
3050
0
    io_flush;
3051
3052
    /* Enforce limits to avoid bandwidth abuse. The bypass_limits should only be used by administrators and experts. */
3053
0
    if (!opt->bypass_limits) {
3054
0
      if (opt->maxsoc <= 0 || opt->maxsoc > 8) {
3055
0
        opt->maxsoc = 8;
3056
0
        hts_log_print(opt, LOG_WARNING,
3057
0
                      "* security warning: maximum number of simultaneous connections limited to %d to avoid server overload",
3058
0
                      (int) opt->maxsoc);
3059
0
      }
3060
0
      if (opt->maxrate <= 0 || opt->maxrate > 10000000) {
3061
0
        opt->maxrate = 10000000;
3062
0
        hts_log_print(opt, LOG_WARNING,
3063
0
                      "* security warning: maximum bandwidth limited to %d to avoid server overload",
3064
0
                      (int) opt->maxrate);
3065
0
      }
3066
0
      if (opt->maxconn <= 0 || opt->maxconn > 5.0) {
3067
0
        opt->maxconn = 5.0;
3068
0
        hts_log_print(opt, LOG_WARNING,
3069
0
                      "* security warning: maximum number of connections per "
3070
0
                      "second limited to %d to avoid server overload",
3071
0
                      (int) opt->maxconn);
3072
0
      }
3073
0
    } else {
3074
0
      hts_log_print(opt, LOG_WARNING,
3075
0
                    "* security warning: !!! BYPASSING SECURITY LIMITS - MONITOR THIS SESSION WITH EXTREME CARE !!!");
3076
0
    }
3077
3078
    /* --host-alias rules pointing in a circle have no canonical host */
3079
0
    {
3080
0
      char BIGSTK looping[HTS_URLMAXSIZE * 2];
3081
3082
0
      if (hts_host_alias_looping(hts_host_alias_rules(opt),
3083
0
                                 hts_host_alias_collapse_www(opt),
3084
0
                                 HTS_BUF(looping)) != NULL) {
3085
0
        hts_log_print(opt, LOG_WARNING,
3086
0
                      "* host-alias rules for '%s' point in a circle: those "
3087
0
                      "hosts are left alone, point them all at one host",
3088
0
                      looping);
3089
0
      }
3090
0
    }
3091
3092
    /* httpmirror()'s own verdict on whether the mirror ran to the end; the
3093
       cache reconcile below is the only reader outside the mirror block. */
3094
0
    hts_boolean completed = HTS_FALSE;
3095
3096
    /* Info for wrappers */
3097
0
    hts_log_print(opt, LOG_DEBUG, "engine: init");
3098
3099
    /* Init external */
3100
0
    RUN_CALLBACK_NOARG(opt, init);
3101
3102
    // détourner SIGHUP etc.
3103
3104
    // Lancement du miroir
3105
    // ------------------------------------------------------------
3106
0
    opt->state._hts_in_mirror = 1;
3107
0
    {
3108
0
      const int mirrored = httpmirror(*url, opt, &completed);
3109
3110
0
      if (mirrored == 0) {
3111
0
        printf("Error during operation (see log file), site has not been "
3112
0
               "successfully mirrored\n");
3113
0
        exit_code = HTS_EXIT_MIRROR_ABORTED;
3114
0
      } else if (opt->shell) {
3115
        /* Inert: TRANSFER DONE goes to the scratch buffer, never to stdout. */
3116
0
        HTT_REQUEST_START;
3117
0
        ht_print(opt, "TRANSFER DONE" LF);
3118
0
        HTT_REQUEST_END
3119
0
      } else if (completed) {
3120
0
        printf("Done.\n");
3121
0
      } else {
3122
        /* The engine's verdict, so every kind of abort reads alike. */
3123
0
        printf("Mirror not completed (see log file)\n");
3124
0
      }
3125
      /* -v and -g put the log on stdout, where a reprint would double it */
3126
0
      if (!opt->shell && opt->log != stdout) {
3127
0
        char BIGSTK note[256];
3128
3129
0
        if (hts_upper_links_note(opt, HTS_BUF(note)))
3130
0
          printf("%s\n", note);
3131
0
      }
3132
0
    }
3133
0
    opt->state._hts_in_mirror = 0;
3134
    // ------------------------------------------------------------
3135
3136
    //
3137
    // Build top index
3138
0
    if (opt->dir_topindex) {
3139
0
      char BIGSTK rpath[1024 * 2];
3140
0
      char *a;
3141
3142
0
      strcpybuff(rpath, StringBuff(opt->path_html));
3143
0
      hts_striplastchar(rpath, '/');
3144
0
      a = strrchr(rpath, '/');
3145
0
      if (a) {
3146
0
        *a = '\0';
3147
0
        hts_buildtopindex(opt, rpath, StringBuff(opt->path_bin));
3148
0
        hts_log_print(opt, LOG_INFO, "Top index rebuilt (done)");
3149
0
      }
3150
0
    }
3151
3152
    /* Also read the fault flag, as a user stop may overwrite exit_xh's -1. */
3153
0
    if (hts_load_acquire_int(&opt->state.exit_xh) == -1 ||
3154
0
        hts_worker_faulted()) {
3155
0
      exit_code = HTS_EXIT_MIRROR_ABORTED;
3156
0
      cmdl_panic(opt, "mirror aborted before completion, see the log file");
3157
0
    }
3158
0
    if (exit_code == 0 && warc_lost_opt(opt)) {
3159
0
      exit_code = HTS_EXIT_WARC_INCOMPLETE;
3160
0
      cmdl_panic(opt,
3161
0
                 "the WARC archive is incomplete or missing, see the log file");
3162
0
    }
3163
3164
    /* Not after a fault: that mirror is not resumable. */
3165
0
    if (hts_load_acquire_int(&opt->state.exit_xh) == 1 &&
3166
0
        !hts_worker_faulted()) {
3167
0
      if (opt->log) {
3168
0
        fprintf(opt->log,
3169
0
                "* * MIRROR ABORTED! * *\nThe mirror stopped before the end. "
3170
0
                "Start it again with --continue to resume it.\nThe cache is "
3171
0
                "kept: nothing has to be restored or deleted by hand.\n");
3172
0
      }
3173
0
    }
3174
3175
    /* Reconcile before the lock goes at the end of this block, as the startup
3176
       arm needs it. A cap or a ^C leaves exit_xh at 0, so test `completed`. */
3177
0
    if (!completed)
3178
0
      hts_cache_reconcile(opt, CACHE_RECONCILE_INTERRUPTED);
3179
3180
    /* Erase the hts-cache/ref temporary directory unless a ^C or a cap cut a
3181
       transfer mid-body (#1595). */
3182
0
    if (hts_load_acquire_int(&opt->state.exit_xh) == 0 &&
3183
0
        !opt->abort_left_partial) {
3184
0
      purge_ref_dir(opt);
3185
0
    }
3186
3187
    /* Info for wrappers */
3188
0
    hts_log_print(opt, LOG_DEBUG, "engine: free");
3189
3190
    /* UnInit */
3191
0
    RUN_CALLBACK_NOARG(opt, uninit);
3192
3193
0
    if (httrack_logmode != 1) {
3194
0
      if (opt->errlog == opt->log)
3195
0
        opt->errlog = NULL;
3196
0
      if (opt->log) {
3197
0
        fclose(opt->log);
3198
0
        opt->log = NULL;
3199
0
      }
3200
0
      if (opt->errlog) {
3201
0
        fclose(opt->errlog);
3202
0
        opt->errlog = NULL;
3203
0
      }
3204
0
    }
3205
    // Débuggage des en têtes
3206
0
    if (_DEBUG_HEAD) {
3207
0
      if (ioinfo) {
3208
0
        fclose(ioinfo);
3209
0
        ioinfo = NULL;
3210
0
      }
3211
0
    }
3212
    // supprimer lock
3213
0
    UNLINK(n_lock);
3214
0
  }
3215
3216
0
  printf("Thanks for using HTTrack!\n");
3217
0
  io_flush;
3218
0
  return exit_code;
3219
0
}
3220
3221
// main() subroutines
3222
3223
// vérifier chemin path
3224
0
static int check_path(String *s, char *defaultname) {
3225
0
  int i;
3226
0
  int return_value = 0;
3227
3228
  // Replace name: ~/mywebsites/# -> /home/foo/mywebsites/#
3229
0
  expand_home(s);
3230
0
  for(i = 0; i < (int) StringLength(*s); i++)   // conversion \ -> /
3231
0
    if (StringSub(*s, i) == '\\')
3232
0
      StringSubRW(*s, i) = '/';
3233
3234
  // remove ending /
3235
0
  if (StringNotEmpty(*s) && StringRight(*s, 1) == '/')
3236
0
    StringPopRight(*s);
3237
3238
  // Replace name: /home/foo/mywebsites/# -> /home/foo/mywebsites/wonderfulsite
3239
0
  if (StringNotEmpty(*s)) {
3240
0
    if (StringRight(*s, 1) == '#') {
3241
0
      if (strnotempty((defaultname ? defaultname : ""))) {
3242
0
        char *a = strchr(defaultname, '#');     // we never know..
3243
3244
0
        if (a)
3245
0
          *a = '\0';
3246
0
        StringPopRight(*s);
3247
0
        StringCat(*s, defaultname);
3248
0
      } else {
3249
0
        StringClear(*s);        // Clear path (no name/default url given)
3250
0
      }
3251
0
      return_value = 1;         // expanded
3252
0
    }
3253
0
  }
3254
  // ending /
3255
0
  if (StringNotEmpty(*s) && StringRight(*s, 1) != '/')  // ajouter slash à la fin
3256
0
    StringCat(*s, "/");
3257
3258
0
  return return_value;
3259
0
}
3260
3261
/* Append the token at i, with its parameters, quoted as doit.log holds it. */
3262
0
static void cmdl_quote_unit(String *out, const cmdl_argv *cmd, int i) {
3263
0
  const int span = cmd->span[i] > 1 ? cmd->span[i] : 1;
3264
0
  const int end = span < cmd->argc - i ? i + span : cmd->argc;
3265
3266
0
  for (; i < end; i++) {
3267
0
    if (StringLength(*out) != 0)
3268
0
      StringAddchar(*out, ' ');
3269
    /* argv[] is final, so a leading quote is data */
3270
0
    hts_quote_arg(out, cmd->argv[i]);
3271
0
  }
3272
0
}
3273
3274
/* Append cmd's arguments as doit.log's line, leaving out an option an
3275
   identical later one repeats, so each resume's -iC2 does not pile up. */
3276
0
static void cmdl_doit_line(String *line, const cmdl_argv *cmd) {
3277
0
  hts_boolean *drop =
3278
0
      (hts_boolean *) calloct((size_t) cmd->argc, sizeof(hts_boolean));
3279
0
  coucal seen = drop != NULL ? coucal_new(0) : NULL;
3280
0
  String unit = STRING_EMPTY;
3281
0
  int i;
3282
3283
0
  for (i = cmd->argc - 1; seen != NULL && i > 0; i--) {
3284
0
    if (cmd->span[i] == 0)
3285
0
      continue;
3286
0
    StringClear(unit);
3287
0
    cmdl_quote_unit(&unit, cmd, i);
3288
0
    if (coucal_exists(seen, StringBuff(unit)))
3289
0
      drop[i] = HTS_TRUE;
3290
0
    else
3291
0
      coucal_write(seen, StringBuff(unit), 0);
3292
0
  }
3293
0
  for (i = 1; i < cmd->argc; i++) {
3294
0
    if (seen == NULL || !drop[i])
3295
0
      cmdl_quote_unit(line, cmd, i);
3296
0
    if (cmd->span[i] > 1)
3297
0
      i += cmd->span[i] - 1;
3298
0
  }
3299
0
  StringFree(unit);
3300
0
  if (seen != NULL)
3301
0
    coucal_delete(&seen);
3302
0
  freet(drop);
3303
0
}
3304
3305
/* Does the short-option cluster s carry c from the main option set (-i, -iC2,
3306
   -%Mi)? The i of -%i belongs to another set. */
3307
0
static hts_boolean cmdl_shortopt_has(const char *s, char c) {
3308
0
  const char opt[3] = {'-', c, '\0'};
3309
3310
0
  return cmdl_shortopt_named(s, opt);
3311
0
}
3312
3313
/* Does the short option cluster s hold the option opt, such as "-%mu"? */
3314
0
static hts_boolean cmdl_shortopt_named(const char *s, const char *opt) {
3315
0
  char name[8];
3316
0
  size_t at = 1;
3317
3318
0
  if (s[0] != '-' || s[1] == '-')
3319
0
    return HTS_FALSE;
3320
0
  while (optcluster_next(s, &at, HTS_BUF(name)))
3321
0
    if (strcmp(name, opt) == 0)
3322
0
      return HTS_TRUE;
3323
0
  return HTS_FALSE;
3324
0
}
3325
3326
0
HTSEXT_API hts_boolean hts_rule_would_be_read_as_opt(const char *arg) {
3327
0
  if (arg == NULL || arg[0] != '-')
3328
0
    return HTS_FALSE;
3329
  // A dot means a host (-www.a.com), but any '%' keeps -%c0.5 an option.
3330
0
  if (strchr(arg, '.') != NULL && strchr(arg, '%') == NULL)
3331
0
    return HTS_FALSE;
3332
0
  return strchr(arg, '/') == NULL && strchr(arg, '*') == NULL;
3333
0
}