New operation mode to remove the data file. Now you can get a nicely
[sgt/agedu] / agedu.c
CommitLineData
70322ae3 1/*
2 * Main program for agedu.
3 */
4
5#define _GNU_SOURCE
6#include <stdio.h>
7#include <errno.h>
8#include <stdarg.h>
9#include <stdlib.h>
10#include <stdint.h>
11#include <string.h>
12#include <time.h>
e9e7a1bf 13#include <assert.h>
70322ae3 14
15#include <unistd.h>
16#include <sys/types.h>
17#include <fcntl.h>
18#include <sys/mman.h>
8b1f55d6 19#include <termios.h>
20#include <sys/ioctl.h>
9d0b9596 21#include <fnmatch.h>
70322ae3 22
353bc75d 23#include "agedu.h"
70322ae3 24#include "du.h"
25#include "trie.h"
26#include "index.h"
27#include "malloc.h"
28#include "html.h"
29#include "httpd.h"
84849cbd 30#include "fgetline.h"
70322ae3 31
373a02e5 32/*
33 * Path separator. This global variable affects the behaviour of
34 * various parts of the code when they need to deal with path
35 * separators. The path separator appropriate to a particular data
36 * set is encoded in the index file storing that data set; data
37 * sets generated on Unix will of course have the default '/', but
38 * foreign data sets are conceivable and must be handled correctly.
39 */
40char pathsep = '/';
41
70322ae3 42void fatal(const char *fmt, ...)
43{
44 va_list ap;
45 fprintf(stderr, "%s: ", PNAME);
46 va_start(ap, fmt);
47 vfprintf(stderr, fmt, ap);
48 va_end(ap);
49 fprintf(stderr, "\n");
50 exit(1);
51}
52
9d0b9596 53struct inclusion_exclusion {
0ba55302 54 int type;
9d0b9596 55 const char *wildcard;
56 int path;
57};
58
70322ae3 59struct ctx {
60 triebuild *tb;
61 dev_t datafile_dev, filesystem_dev;
62 ino_t datafile_ino;
63 time_t last_output_update;
8b1f55d6 64 int progress, progwidth;
84849cbd 65 int straight_to_dump;
9d0b9596 66 struct inclusion_exclusion *inex;
67 int ninex;
68 int crossfs;
05b0f827 69 int fakeatimes;
70322ae3 70};
71
84849cbd 72static void dump_line(const char *pathname, const struct trie_file *tf)
73{
74 const char *p;
75 printf("%llu %llu ", tf->size, tf->atime);
76 for (p = pathname; *p; p++) {
77 if (*p >= ' ' && *p < 127 && *p != '%')
78 putchar(*p);
79 else
80 printf("%%%02x", (unsigned char)*p);
81 }
82 putchar('\n');
83}
84
70322ae3 85static int gotdata(void *vctx, const char *pathname, const struct stat64 *st)
86{
87 struct ctx *ctx = (struct ctx *)vctx;
88 struct trie_file file;
89 time_t t;
9d0b9596 90 int i, include;
91 const char *filename;
70322ae3 92
93 /*
94 * Filter out our own data file.
95 */
96 if (st->st_dev == ctx->datafile_dev && st->st_ino == ctx->datafile_ino)
97 return 0;
98
99 /*
100 * Don't cross the streams^W^Wany file system boundary.
70322ae3 101 */
9d0b9596 102 if (!ctx->crossfs && st->st_dev != ctx->filesystem_dev)
70322ae3 103 return 0;
104
84849cbd 105 file.size = (unsigned long long)512 * st->st_blocks;
05b0f827 106 if (ctx->fakeatimes && S_ISDIR(st->st_mode))
107 file.atime = st->st_mtime;
108 else
109 file.atime = st->st_atime;
0ba55302 110
70322ae3 111 /*
9d0b9596 112 * Filter based on wildcards.
70322ae3 113 */
9d0b9596 114 include = 1;
373a02e5 115 filename = strrchr(pathname, pathsep);
9d0b9596 116 if (!filename)
117 filename = pathname;
118 else
119 filename++;
120 for (i = 0; i < ctx->ninex; i++) {
121 if (fnmatch(ctx->inex[i].wildcard,
0ba55302 122 ctx->inex[i].path ? pathname : filename, 0) == 0)
123 include = ctx->inex[i].type;
124 }
125 if (include == -1)
126 return 0; /* ignore this entry and any subdirs */
127 if (include == 0) {
128 /*
129 * Here we are supposed to be filtering an entry out, but
130 * still recursing into it if it's a directory. However,
131 * we can't actually leave out any directory whose
132 * subdirectories we then look at. So we cheat, in that
133 * case, by setting the size to zero.
134 */
135 if (!S_ISDIR(st->st_mode))
136 return 0; /* just ignore */
137 else
84849cbd 138 file.size = 0;
9d0b9596 139 }
70322ae3 140
84849cbd 141 if (ctx->straight_to_dump)
142 dump_line(pathname, &file);
143 else
144 triebuild_add(ctx->tb, pathname, &file);
70322ae3 145
84849cbd 146 if (ctx->progress) {
147 t = time(NULL);
148 if (t != ctx->last_output_update) {
8b1f55d6 149 fprintf(stderr, "%-*.*s\r", ctx->progwidth, ctx->progwidth,
150 pathname);
151 fflush(stderr);
84849cbd 152 ctx->last_output_update = t;
8b1f55d6 153 }
70322ae3 154 }
155
156 return 1;
157}
158
e9e7a1bf 159static void text_query(const void *mappedfile, const char *querydir,
7cf11b75 160 time_t t, int depth)
70322ae3 161{
162 size_t maxpathlen;
163 char *pathbuf;
164 unsigned long xi1, xi2;
165 unsigned long long s1, s2;
166
167 maxpathlen = trie_maxpathlen(mappedfile);
168 pathbuf = snewn(maxpathlen + 1, char);
169
170 /*
171 * We want to query everything between the supplied filename
172 * (inclusive) and that filename with a ^A on the end
173 * (exclusive). So find the x indices for each.
174 */
256c29a2 175 strcpy(pathbuf, querydir);
176 make_successor(pathbuf);
e9e7a1bf 177 xi1 = trie_before(mappedfile, querydir);
70322ae3 178 xi2 = trie_before(mappedfile, pathbuf);
179
0313b788 180 if (xi2 - xi1 == 1)
181 return; /* file, or empty dir => no display */
182
70322ae3 183 /*
184 * Now do the lookups in the age index.
185 */
186 s1 = index_query(mappedfile, xi1, t);
187 s2 = index_query(mappedfile, xi2, t);
188
010dd2a2 189 if (s1 == s2)
190 return; /* no space taken up => no display */
191
70322ae3 192 if (depth > 0) {
193 /*
194 * Now scan for first-level subdirectories and report
195 * those too.
196 */
197 xi1++;
198 while (xi1 < xi2) {
199 trie_getpath(mappedfile, xi1, pathbuf);
7cf11b75 200 text_query(mappedfile, pathbuf, t, depth-1);
256c29a2 201 make_successor(pathbuf);
70322ae3 202 xi1 = trie_before(mappedfile, pathbuf);
203 }
204 }
16e591d6 205
206 /* Display in units of 1Kb */
207 printf("%-11llu %s\n", (s2 - s1) / 1024, querydir);
70322ae3 208}
209
56fa1896 210/*
211 * Largely frivolous way to define all my command-line options. I
212 * present here a parametric macro which declares a series of
213 * _logical_ option identifiers, and for each one declares zero or
214 * more short option characters and zero or more long option
215 * words. Then I repeatedly invoke that macro with its arguments
216 * defined to be various other macros, which allows me to
217 * variously:
218 *
219 * - define an enum allocating a distinct integer value to each
220 * logical option id
221 * - define a string consisting of precisely all the short option
222 * characters
223 * - define a string array consisting of all the long option
224 * strings
225 * - define (with help from auxiliary enums) integer arrays
226 * parallel to both of the above giving the logical option id
227 * for each physical short and long option
228 * - define an array indexed by logical option id indicating
e9e7a1bf 229 * whether the option in question takes a value
230 * - define a function which prints out brief online help for all
231 * the options.
56fa1896 232 *
233 * It's not at all clear to me that this trickery is actually
234 * particularly _efficient_ - it still, after all, requires going
235 * linearly through the option list at run time and doing a
236 * strcmp, whereas in an ideal world I'd have liked the lists of
237 * long and short options to be pre-sorted so that a binary search
238 * or some other more efficient lookup was possible. (Not that
239 * asymptotic algorithmic complexity is remotely vital in option
240 * parsing, but if I were doing this in, say, Lisp or something
241 * with an equivalently powerful preprocessor then once I'd had
242 * the idea of preparing the option-parsing data structures at
243 * compile time I would probably have made the effort to prepare
244 * them _properly_. I could have Perl generate me a source file
245 * from some sort of description, I suppose, but that would seem
246 * like overkill. And in any case, it's more of a challenge to
247 * achieve as much as possible by cunning use of cpp and enum than
248 * to just write some sensible and logical code in a Turing-
249 * complete language. I said it was largely frivolous :-)
250 *
251 * This approach does have the virtue that it brings together the
e9e7a1bf 252 * option ids, option spellings and help text into a single
253 * combined list and defines them all in exactly one place. If I
254 * want to add a new option, or a new spelling for an option, I
255 * only have to modify the main OPTHELP macro below and then add
256 * code to process the new logical id.
56fa1896 257 *
258 * (Though, really, even that isn't ideal, since it still involves
259 * modifying the source file in more than one place. In a
260 * _properly_ ideal world, I'd be able to interleave the option
261 * definitions with the code fragments that process them. And then
262 * not bother defining logical identifiers for them at all - those
263 * would be automatically generated, since I wouldn't have any
264 * need to specify them manually in another part of the code.)
c5c3510f 265 *
266 * One other helpful consequence of the enum-based structure here
267 * is that it causes a compiler error if I accidentally try to
268 * define the same option (short or long) twice.
56fa1896 269 */
270
e9e7a1bf 271#define OPTHELP(NOVAL, VAL, SHORT, LONG, HELPPFX, HELPARG, HELPLINE, HELPOPT) \
bf53e756 272 HELPPFX("usage") HELPLINE(PNAME " [options] action [action...]") \
e9e7a1bf 273 HELPPFX("actions") \
274 VAL(SCAN) SHORT(s) LONG(scan) \
275 HELPARG("directory") HELPOPT("scan and index a directory") \
c5c3510f 276 NOVAL(DUMP) SHORT(D) LONG(dump) HELPOPT("dump the index file on stdout") \
84849cbd 277 VAL(SCANDUMP) SHORT(S) LONG(scan_dump) \
278 HELPARG("directory") HELPOPT("scan only, generating a dump") \
c5c3510f 279 NOVAL(LOAD) SHORT(L) LONG(load) \
84849cbd 280 HELPOPT("load and index a dump file") \
e9e7a1bf 281 VAL(TEXT) SHORT(t) LONG(text) \
282 HELPARG("subdir") HELPOPT("print a plain text report on a subdirectory") \
283 VAL(HTML) SHORT(H) LONG(html) \
284 HELPARG("subdir") HELPOPT("print an HTML report on a subdirectory") \
56fa1896 285 NOVAL(HTTPD) SHORT(w) LONG(web) LONG(server) LONG(httpd) \
84849cbd 286 HELPOPT("serve HTML reports from a temporary web server") \
355c3af7 287 NOVAL(REMOVE) SHORT(R) LONG(remove) LONG(delete) LONG(unlink) \
288 HELPOPT("remove the index file") \
e9e7a1bf 289 HELPPFX("options") \
290 VAL(DATAFILE) SHORT(f) LONG(file) \
c5c3510f 291 HELPARG("filename") HELPOPT("[most modes] specify index file") \
56fa1896 292 NOVAL(PROGRESS) LONG(progress) LONG(scan_progress) \
e9e7a1bf 293 HELPOPT("[--scan] report progress on stderr") \
56fa1896 294 NOVAL(NOPROGRESS) LONG(no_progress) LONG(no_scan_progress) \
e9e7a1bf 295 HELPOPT("[--scan] do not report progress") \
56fa1896 296 NOVAL(TTYPROGRESS) LONG(tty_progress) LONG(tty_scan_progress) \
297 LONG(progress_tty) LONG(scan_progress_tty) \
e9e7a1bf 298 HELPOPT("[--scan] report progress if stderr is a tty") \
56fa1896 299 NOVAL(CROSSFS) LONG(cross_fs) \
e9e7a1bf 300 HELPOPT("[--scan] cross filesystem boundaries") \
56fa1896 301 NOVAL(NOCROSSFS) LONG(no_cross_fs) \
e9e7a1bf 302 HELPOPT("[--scan] stick to one filesystem") \
56fa1896 303 VAL(INCLUDE) LONG(include) \
e9e7a1bf 304 HELPARG("wildcard") HELPOPT("[--scan] include files matching pattern") \
56fa1896 305 VAL(INCLUDEPATH) LONG(include_path) \
e9e7a1bf 306 HELPARG("wildcard") HELPOPT("[--scan] include pathnames matching pattern") \
56fa1896 307 VAL(EXCLUDE) LONG(exclude) \
e9e7a1bf 308 HELPARG("wildcard") HELPOPT("[--scan] exclude files matching pattern") \
309 VAL(EXCLUDEPATH) LONG(exclude_path) \
310 HELPARG("wildcard") HELPOPT("[--scan] exclude pathnames matching pattern") \
0ba55302 311 VAL(PRUNE) LONG(prune) \
312 HELPARG("wildcard") HELPOPT("[--scan] prune files matching pattern") \
313 VAL(PRUNEPATH) LONG(prune_path) \
314 HELPARG("wildcard") HELPOPT("[--scan] prune pathnames matching pattern") \
05b0f827 315 NOVAL(DIRATIME) LONG(dir_atime) LONG(dir_atimes) \
316 HELPOPT("[--scan] keep real atimes on directories") \
317 NOVAL(NODIRATIME) LONG(no_dir_atime) LONG(no_dir_atimes) \
318 HELPOPT("[--scan] fake atimes on directories") \
c5c3510f 319 VAL(TQDEPTH) SHORT(d) LONG(depth) LONG(max_depth) LONG(maximum_depth) \
16e591d6 320 HELPARG("levels") HELPOPT("[--text] recurse to this many levels") \
e9e7a1bf 321 VAL(MINAGE) SHORT(a) LONG(age) LONG(min_age) LONG(minimum_age) \
322 HELPARG("age") HELPOPT("[--text] include only files older than this") \
f2e52893 323 VAL(AGERANGE) SHORT(r) LONG(age_range) LONG(range) LONG(ages) \
324 HELPARG("age[-age]") HELPOPT("[--html,--web] set limits of colour coding") \
1e8d78b9 325 VAL(SERVERADDR) LONG(address) LONG(addr) LONG(server_address) \
326 LONG(server_addr) \
327 HELPARG("addr[:port]") HELPOPT("[--web] specify HTTP server address") \
e9e7a1bf 328 VAL(AUTH) LONG(auth) LONG(http_auth) LONG(httpd_auth) \
329 LONG(server_auth) LONG(web_auth) \
330 HELPARG("type") HELPOPT("[--web] specify HTTP authentication method") \
1e8d78b9 331 VAL(AUTHFILE) LONG(auth_file) \
332 HELPARG("filename") HELPOPT("[--web] read HTTP Basic user/pass from file") \
333 VAL(AUTHFD) LONG(auth_fd) \
334 HELPARG("fd") HELPOPT("[--web] read HTTP Basic user/pass from fd") \
e9e7a1bf 335 HELPPFX("also") \
336 NOVAL(HELP) SHORT(h) LONG(help) HELPOPT("display this help text") \
337 NOVAL(VERSION) SHORT(V) LONG(version) HELPOPT("report version number") \
338 NOVAL(LICENCE) LONG(licence) LONG(license) \
339 HELPOPT("display (MIT) licence text") \
56fa1896 340
341#define IGNORE(x)
342#define DEFENUM(x) OPT_ ## x,
343#define ZERO(x) 0,
344#define ONE(x) 1,
345#define STRING(x) #x ,
346#define STRINGNOCOMMA(x) #x
347#define SHORTNEWOPT(x) SHORTtmp_ ## x = OPT_ ## x,
348#define SHORTTHISOPT(x) SHORTtmp2_ ## x, SHORTVAL_ ## x = SHORTtmp2_ ## x - 1,
349#define SHORTOPTVAL(x) SHORTVAL_ ## x,
350#define SHORTTMP(x) SHORTtmp3_ ## x,
351#define LONGNEWOPT(x) LONGtmp_ ## x = OPT_ ## x,
352#define LONGTHISOPT(x) LONGtmp2_ ## x, LONGVAL_ ## x = LONGtmp2_ ## x - 1,
353#define LONGOPTVAL(x) LONGVAL_ ## x,
354#define LONGTMP(x) SHORTtmp3_ ## x,
355
e9e7a1bf 356#define OPTIONS(NOVAL, VAL, SHORT, LONG) \
357 OPTHELP(NOVAL, VAL, SHORT, LONG, IGNORE, IGNORE, IGNORE, IGNORE)
358
56fa1896 359enum { OPTIONS(DEFENUM,DEFENUM,IGNORE,IGNORE) NOPTIONS };
360enum { OPTIONS(IGNORE,IGNORE,SHORTTMP,IGNORE) NSHORTOPTS };
361enum { OPTIONS(IGNORE,IGNORE,IGNORE,LONGTMP) NLONGOPTS };
362static const int opthasval[NOPTIONS] = {OPTIONS(ZERO,ONE,IGNORE,IGNORE)};
363static const char shortopts[] = {OPTIONS(IGNORE,IGNORE,STRINGNOCOMMA,IGNORE)};
364static const char *const longopts[] = {OPTIONS(IGNORE,IGNORE,IGNORE,STRING)};
365enum { OPTIONS(SHORTNEWOPT,SHORTNEWOPT,SHORTTHISOPT,IGNORE) };
366enum { OPTIONS(LONGNEWOPT,LONGNEWOPT,IGNORE,LONGTHISOPT) };
367static const int shortvals[] = {OPTIONS(IGNORE,IGNORE,SHORTOPTVAL,IGNORE)};
368static const int longvals[] = {OPTIONS(IGNORE,IGNORE,IGNORE,LONGOPTVAL)};
369
e9e7a1bf 370static void usage(FILE *fp)
371{
372 char longbuf[80];
373 const char *prefix, *shortopt, *longopt, *optarg;
374 int i, optex;
375
376#define HELPRESET prefix = shortopt = longopt = optarg = NULL, optex = -1
377#define HELPNOVAL(s) optex = 0;
378#define HELPVAL(s) optex = 1;
379#define HELPSHORT(s) if (!shortopt) shortopt = "-" #s;
380#define HELPLONG(s) if (!longopt) { \
381 strcpy(longbuf, "--" #s); longopt = longbuf; \
382 for (i = 0; longbuf[i]; i++) if (longbuf[i] == '_') longbuf[i] = '-'; }
383#define HELPPFX(s) prefix = s;
384#define HELPARG(s) optarg = s;
385#define HELPLINE(s) assert(optex == -1); \
386 fprintf(fp, "%7s%c %s\n", prefix?prefix:"", prefix?':':' ', s); \
387 HELPRESET;
388#define HELPOPT(s) assert((optex == 1 && optarg) || (optex == 0 && !optarg)); \
389 assert(shortopt || longopt); \
390 i = fprintf(fp, "%7s%c %s%s%s%s%s", prefix?prefix:"", prefix?':':' ', \
391 shortopt?shortopt:"", shortopt&&longopt?", ":"", longopt?longopt:"", \
392 optarg?" ":"", optarg?optarg:""); \
393 fprintf(fp, "%*s %s\n", i<32?32-i:0,"",s); HELPRESET;
394
395 HELPRESET;
396 OPTHELP(HELPNOVAL, HELPVAL, HELPSHORT, HELPLONG,
397 HELPPFX, HELPARG, HELPLINE, HELPOPT);
398
399#undef HELPRESET
400#undef HELPNOVAL
401#undef HELPVAL
402#undef HELPSHORT
403#undef HELPLONG
404#undef HELPPFX
405#undef HELPARG
406#undef HELPLINE
407#undef HELPOPT
408}
409
f2e52893 410static time_t parse_age(time_t now, const char *agestr)
411{
412 time_t t;
413 struct tm tm;
414 int nunits;
415 char unit[2];
416
417 t = now;
418
419 if (2 != sscanf(agestr, "%d%1[DdWwMmYy]", &nunits, unit)) {
420 fprintf(stderr, "%s: age specification should be a number followed by"
421 " one of d,w,m,y\n", PNAME);
422 exit(1);
423 }
424
425 if (unit[0] == 'd') {
426 t -= 86400 * nunits;
427 } else if (unit[0] == 'w') {
428 t -= 86400 * 7 * nunits;
429 } else {
430 int ym;
431
432 tm = *localtime(&t);
433 ym = tm.tm_year * 12 + tm.tm_mon;
434
435 if (unit[0] == 'm')
436 ym -= nunits;
437 else
438 ym -= 12 * nunits;
439
440 tm.tm_year = ym / 12;
441 tm.tm_mon = ym % 12;
442
443 t = mktime(&tm);
444 }
445
446 return t;
447}
448
70322ae3 449int main(int argc, char **argv)
450{
451 int fd, count;
452 struct ctx actx, *ctx = &actx;
453 struct stat st;
454 off_t totalsize, realsize;
455 void *mappedfile;
456 triewalk *tw;
457 indexbuild *ib;
458 const struct trie_file *tf;
bf53e756 459 char *filename = PNAME ".dat";
70322ae3 460 int doing_opts = 1;
355c3af7 461 enum { TEXT, HTML, SCAN, DUMP, SCANDUMP, LOAD, HTTPD, REMOVE };
444c684c 462 struct action {
463 int mode;
464 char *arg;
465 } *actions = NULL;
466 int nactions = 0, actionsize = 0, action;
f2e52893 467 time_t now = time(NULL);
468 time_t textcutoff = now, htmlnewest = now, htmloldest = now;
469 int htmlautoagerange = 1;
1e8d78b9 470 const char *httpserveraddr = NULL;
471 int httpserverport = 0;
472 const char *httpauthdata = NULL;
812e4bf2 473 int auth = HTTPD_AUTH_MAGIC | HTTPD_AUTH_BASIC;
8b1f55d6 474 int progress = 1;
9d0b9596 475 struct inclusion_exclusion *inex = NULL;
476 int ninex = 0, inexsize = 0;
477 int crossfs = 0;
16e591d6 478 int tqdepth = 1;
05b0f827 479 int fakediratimes = 1;
70322ae3 480
56fa1896 481#ifdef DEBUG_MAD_OPTION_PARSING_MACROS
482 {
483 static const char *const optnames[NOPTIONS] = {
484 OPTIONS(STRING,STRING,IGNORE,IGNORE)
485 };
486 int i;
487 for (i = 0; i < NSHORTOPTS; i++)
488 printf("-%c == %s [%s]\n", shortopts[i], optnames[shortvals[i]],
489 opthasval[shortvals[i]] ? "value" : "no value");
490 for (i = 0; i < NLONGOPTS; i++)
491 printf("--%s == %s [%s]\n", longopts[i], optnames[longvals[i]],
492 opthasval[longvals[i]] ? "value" : "no value");
493 }
494#endif
495
70322ae3 496 while (--argc > 0) {
497 char *p = *++argv;
70322ae3 498
499 if (doing_opts && *p == '-') {
56fa1896 500 int wordstart = 1;
501
70322ae3 502 if (!strcmp(p, "--")) {
503 doing_opts = 0;
56fa1896 504 continue;
505 }
506
507 p++;
508 while (*p) {
509 int optid = -1;
510 int i;
511 char *optval;
512
513 if (wordstart && *p == '-') {
70322ae3 514 /*
56fa1896 515 * GNU-style long option.
70322ae3 516 */
56fa1896 517 p++;
518 optval = strchr(p, '=');
519 if (optval)
520 *optval++ = '\0';
521
522 for (i = 0; i < NLONGOPTS; i++) {
523 const char *opt = longopts[i], *s = p;
524 int match = 1;
525 /*
526 * The underscores in the option names
527 * defined above may be given by the user
528 * as underscores or dashes, or omitted
529 * entirely.
530 */
531 while (*opt) {
532 if (*opt == '_') {
533 if (*s == '-' || *s == '_')
534 s++;
535 } else {
536 if (*opt != *s) {
537 match = 0;
538 break;
539 }
540 s++;
541 }
542 opt++;
543 }
544 if (match && !*s) {
545 optid = longvals[i];
546 break;
70322ae3 547 }
548 }
56fa1896 549
550 if (optid < 0) {
551 fprintf(stderr, "%s: unrecognised option '--%s'\n",
552 PNAME, p);
553 return 1;
554 }
555
556 if (!opthasval[optid]) {
557 if (optval) {
558 fprintf(stderr, "%s: unexpected argument to option"
559 " '--%s'\n", PNAME, p);
812e4bf2 560 return 1;
561 }
56fa1896 562 } else {
563 if (!optval) {
564 if (--argc > 0) {
565 optval = *++argv;
566 } else {
567 fprintf(stderr, "%s: option '--%s' expects"
568 " an argument\n", PNAME, p);
569 return 1;
570 }
9d0b9596 571 }
70322ae3 572 }
56fa1896 573
574 p += strlen(p); /* finished with this argument word */
70322ae3 575 } else {
56fa1896 576 /*
577 * Short option.
578 */
70322ae3 579 char c = *p++;
580
56fa1896 581 for (i = 0; i < NSHORTOPTS; i++)
582 if (c == shortopts[i]) {
583 optid = shortvals[i];
584 break;
585 }
586
587 if (optid < 0) {
588 fprintf(stderr, "%s: unrecognised option '-%c'\n",
589 PNAME, c);
590 return 1;
591 }
592
593 if (opthasval[optid]) {
70322ae3 594 if (*p) {
595 optval = p;
596 p += strlen(p);
597 } else if (--argc > 0) {
598 optval = *++argv;
599 } else {
56fa1896 600 fprintf(stderr, "%s: option '-%c' expects"
70322ae3 601 " an argument\n", PNAME, c);
602 return 1;
603 }
56fa1896 604 } else {
605 optval = NULL;
606 }
607 }
608
609 wordstart = 0;
610
611 /*
612 * Now actually process the option.
613 */
614 switch (optid) {
615 case OPT_HELP:
e9e7a1bf 616 usage(stdout);
56fa1896 617 return 0;
618 case OPT_VERSION:
619 printf("FIXME: version();\n");
620 return 0;
621 case OPT_LICENCE:
5a29503d 622 {
623 extern const char *const licence[];
624 int i;
625
626 for (i = 0; licence[i]; i++)
627 fputs(licence[i], stdout);
628
629 return 0;
630 }
56fa1896 631 return 0;
632 case OPT_SCAN:
444c684c 633 if (nactions >= actionsize) {
634 actionsize = nactions * 3 / 2 + 16;
635 actions = sresize(actions, actionsize, struct action);
636 }
637 actions[nactions].mode = SCAN;
638 actions[nactions].arg = optval;
639 nactions++;
56fa1896 640 break;
84849cbd 641 case OPT_SCANDUMP:
444c684c 642 if (nactions >= actionsize) {
643 actionsize = nactions * 3 / 2 + 16;
644 actions = sresize(actions, actionsize, struct action);
645 }
646 actions[nactions].mode = SCANDUMP;
647 actions[nactions].arg = optval;
648 nactions++;
84849cbd 649 break;
56fa1896 650 case OPT_DUMP:
444c684c 651 if (nactions >= actionsize) {
652 actionsize = nactions * 3 / 2 + 16;
653 actions = sresize(actions, actionsize, struct action);
654 }
655 actions[nactions].mode = DUMP;
656 actions[nactions].arg = NULL;
657 nactions++;
56fa1896 658 break;
84849cbd 659 case OPT_LOAD:
444c684c 660 if (nactions >= actionsize) {
661 actionsize = nactions * 3 / 2 + 16;
662 actions = sresize(actions, actionsize, struct action);
663 }
664 actions[nactions].mode = LOAD;
665 actions[nactions].arg = NULL;
666 nactions++;
84849cbd 667 break;
56fa1896 668 case OPT_TEXT:
444c684c 669 if (nactions >= actionsize) {
670 actionsize = nactions * 3 / 2 + 16;
671 actions = sresize(actions, actionsize, struct action);
672 }
673 actions[nactions].mode = TEXT;
674 actions[nactions].arg = optval;
675 nactions++;
56fa1896 676 break;
677 case OPT_HTML:
444c684c 678 if (nactions >= actionsize) {
679 actionsize = nactions * 3 / 2 + 16;
680 actions = sresize(actions, actionsize, struct action);
681 }
682 actions[nactions].mode = HTML;
683 actions[nactions].arg = optval;
684 nactions++;
56fa1896 685 break;
686 case OPT_HTTPD:
444c684c 687 if (nactions >= actionsize) {
688 actionsize = nactions * 3 / 2 + 16;
689 actions = sresize(actions, actionsize, struct action);
690 }
691 actions[nactions].mode = HTTPD;
692 actions[nactions].arg = NULL;
693 nactions++;
56fa1896 694 break;
355c3af7 695 case OPT_REMOVE:
696 if (nactions >= actionsize) {
697 actionsize = nactions * 3 / 2 + 16;
698 actions = sresize(actions, actionsize, struct action);
699 }
700 actions[nactions].mode = REMOVE;
701 actions[nactions].arg = NULL;
702 nactions++;
703 break;
56fa1896 704 case OPT_PROGRESS:
705 progress = 2;
706 break;
707 case OPT_NOPROGRESS:
708 progress = 0;
709 break;
710 case OPT_TTYPROGRESS:
711 progress = 1;
712 break;
713 case OPT_CROSSFS:
714 crossfs = 1;
715 break;
716 case OPT_NOCROSSFS:
717 crossfs = 0;
718 break;
05b0f827 719 case OPT_DIRATIME:
720 fakediratimes = 0;
721 break;
722 case OPT_NODIRATIME:
723 fakediratimes = 1;
724 break;
56fa1896 725 case OPT_DATAFILE:
726 filename = optval;
727 break;
16e591d6 728 case OPT_TQDEPTH:
729 tqdepth = atoi(optval);
730 break;
56fa1896 731 case OPT_MINAGE:
f2e52893 732 textcutoff = parse_age(now, optval);
733 break;
734 case OPT_AGERANGE:
735 if (!strcmp(optval, "auto")) {
736 htmlautoagerange = 1;
737 } else {
738 char *q = optval + strcspn(optval, "-:");
739 if (*q)
740 *q++ = '\0';
741 htmloldest = parse_age(now, optval);
742 htmlnewest = *q ? parse_age(now, q) : now;
743 htmlautoagerange = 0;
744 }
56fa1896 745 break;
1e8d78b9 746 case OPT_SERVERADDR:
747 {
748 char *port;
749 if (optval[0] == '[' &&
750 (port = strchr(optval, ']')) != NULL)
751 port++;
752 else
753 port = optval;
754 port += strcspn(port, ":");
755 if (port)
756 *port++ = '\0';
757 httpserveraddr = optval;
758 httpserverport = atoi(port);
759 }
760 break;
56fa1896 761 case OPT_AUTH:
762 if (!strcmp(optval, "magic"))
763 auth = HTTPD_AUTH_MAGIC;
764 else if (!strcmp(optval, "basic"))
765 auth = HTTPD_AUTH_BASIC;
766 else if (!strcmp(optval, "none"))
767 auth = HTTPD_AUTH_NONE;
768 else if (!strcmp(optval, "default"))
769 auth = HTTPD_AUTH_MAGIC | HTTPD_AUTH_BASIC;
f2e52893 770 else if (!strcmp(optval, "help") ||
771 !strcmp(optval, "list")) {
bf53e756 772 printf(PNAME ": supported HTTP authentication types"
f2e52893 773 " are:\n"
774 " magic use Linux /proc/net/tcp to"
775 " determine owner of peer socket\n"
776 " basic HTTP Basic username and"
777 " password authentication\n"
778 " default use 'magic' if possible, "
779 " otherwise fall back to 'basic'\n"
780 " none unauthenticated HTTP (if"
781 " the data file is non-confidential)\n");
782 return 0;
783 } else {
56fa1896 784 fprintf(stderr, "%s: unrecognised authentication"
785 " type '%s'\n%*s options are 'magic',"
786 " 'basic', 'none', 'default'\n",
787 PNAME, optval, (int)strlen(PNAME), "");
788 return 1;
789 }
790 break;
1e8d78b9 791 case OPT_AUTHFILE:
792 case OPT_AUTHFD:
793 {
794 int fd;
795 char namebuf[40];
796 const char *name;
797 char *authbuf;
798 int authlen, authsize;
799 int ret;
800
801 if (optid == OPT_AUTHFILE) {
802 fd = open(optval, O_RDONLY);
803 if (fd < 0) {
804 fprintf(stderr, "%s: %s: open: %s\n", PNAME,
805 optval, strerror(errno));
806 return 1;
807 }
808 name = optval;
809 } else {
810 fd = atoi(optval);
811 name = namebuf;
812 sprintf(namebuf, "fd %d", fd);
813 }
814
815 authlen = 0;
816 authsize = 256;
817 authbuf = snewn(authsize, char);
818 while ((ret = read(fd, authbuf+authlen,
819 authsize-authlen)) > 0) {
820 authlen += ret;
821 if ((authsize - authlen) < (authsize / 16)) {
822 authsize = authlen * 3 / 2 + 4096;
823 authbuf = sresize(authbuf, authsize, char);
824 }
825 }
826 if (ret < 0) {
827 fprintf(stderr, "%s: %s: read: %s\n", PNAME,
828 name, strerror(errno));
829 return 1;
830 }
831 if (optid == OPT_AUTHFILE)
832 close(fd);
833 httpauthdata = authbuf;
834 }
835 break;
56fa1896 836 case OPT_INCLUDE:
837 case OPT_INCLUDEPATH:
838 case OPT_EXCLUDE:
839 case OPT_EXCLUDEPATH:
0ba55302 840 case OPT_PRUNE:
841 case OPT_PRUNEPATH:
56fa1896 842 if (ninex >= inexsize) {
843 inexsize = ninex * 3 / 2 + 16;
844 inex = sresize(inex, inexsize,
845 struct inclusion_exclusion);
846 }
847 inex[ninex].path = (optid == OPT_INCLUDEPATH ||
0ba55302 848 optid == OPT_EXCLUDEPATH ||
849 optid == OPT_PRUNEPATH);
850 inex[ninex].type = (optid == OPT_INCLUDE ? 1 :
851 optid == OPT_INCLUDEPATH ? 1 :
852 optid == OPT_EXCLUDE ? 0 :
853 optid == OPT_EXCLUDEPATH ? 0 :
854 optid == OPT_PRUNE ? -1 :
855 /* optid == OPT_PRUNEPATH ? */ -1);
56fa1896 856 inex[ninex].wildcard = optval;
857 ninex++;
858 break;
859 }
860 }
70322ae3 861 } else {
e9e7a1bf 862 fprintf(stderr, "%s: unexpected argument '%s'\n", PNAME, p);
863 return 1;
70322ae3 864 }
865 }
866
444c684c 867 if (nactions == 0) {
e9e7a1bf 868 usage(stderr);
869 return 1;
444c684c 870 }
871
872 for (action = 0; action < nactions; action++) {
873 int mode = actions[action].mode;
874
875 if (mode == SCAN || mode == SCANDUMP || mode == LOAD) {
876 const char *scandir = actions[action].arg;
877 if (mode == LOAD) {
878 char *buf = fgetline(stdin);
879 unsigned newpathsep;
880 buf[strcspn(buf, "\r\n")] = '\0';
bf53e756 881 if (1 != sscanf(buf, DUMPHDR "%x",
444c684c 882 &newpathsep)) {
883 fprintf(stderr, "%s: header in dump file not recognised\n",
884 PNAME);
885 return 1;
886 }
887 pathsep = (char)newpathsep;
888 sfree(buf);
84849cbd 889 }
70322ae3 890
444c684c 891 if (mode == SCAN || mode == LOAD) {
892 /*
893 * Prepare to write out the index file.
894 */
895 fd = open(filename, O_RDWR | O_TRUNC | O_CREAT, S_IRWXU);
896 if (fd < 0) {
897 fprintf(stderr, "%s: %s: open: %s\n", PNAME, filename,
898 strerror(errno));
899 return 1;
900 }
901 if (fstat(fd, &st) < 0) {
bf53e756 902 perror(PNAME ": fstat");
444c684c 903 return 1;
904 }
905 ctx->datafile_dev = st.st_dev;
906 ctx->datafile_ino = st.st_ino;
907 ctx->straight_to_dump = 0;
908 } else {
909 ctx->datafile_dev = -1;
910 ctx->datafile_ino = -1;
911 ctx->straight_to_dump = 1;
84849cbd 912 }
444c684c 913
914 if (mode == SCAN || mode == SCANDUMP) {
915 if (stat(scandir, &st) < 0) {
916 fprintf(stderr, "%s: %s: stat: %s\n", PNAME, scandir,
917 strerror(errno));
918 return 1;
919 }
920 ctx->filesystem_dev = crossfs ? 0 : st.st_dev;
84849cbd 921 }
70322ae3 922
444c684c 923 ctx->inex = inex;
924 ctx->ninex = ninex;
925 ctx->crossfs = crossfs;
05b0f827 926 ctx->fakeatimes = fakediratimes;
444c684c 927
928 ctx->last_output_update = time(NULL);
929
930 /* progress==1 means report progress only if stderr is a tty */
931 if (progress == 1)
932 progress = isatty(2) ? 2 : 0;
933 ctx->progress = progress;
934 {
935 struct winsize ws;
936 if (progress && ioctl(2, TIOCGWINSZ, &ws) == 0)
937 ctx->progwidth = ws.ws_col - 1;
938 else
939 ctx->progwidth = 79;
84849cbd 940 }
84849cbd 941
444c684c 942 if (mode == SCANDUMP)
bf53e756 943 printf(DUMPHDR "%02x\n", (unsigned char)pathsep);
8b1f55d6 944
444c684c 945 /*
946 * Scan the directory tree, and write out the trie component
947 * of the data file.
948 */
949 if (mode != SCANDUMP) {
950 ctx->tb = triebuild_new(fd);
951 }
952 if (mode == LOAD) {
953 char *buf;
954 int line = 2;
955 while ((buf = fgetline(stdin)) != NULL) {
956 struct trie_file tf;
957 char *p, *q;
958
959 buf[strcspn(buf, "\r\n")] = '\0';
960
961 p = buf;
962 q = p;
963 while (*p && *p != ' ') p++;
964 if (!*p) {
965 fprintf(stderr, "%s: dump file line %d: expected at least"
966 " three fields\n", PNAME, line);
967 return 1;
968 }
969 *p++ = '\0';
970 tf.size = strtoull(q, NULL, 10);
971 q = p;
972 while (*p && *p != ' ') p++;
973 if (!*p) {
974 fprintf(stderr, "%s: dump file line %d: expected at least"
975 " three fields\n", PNAME, line);
976 return 1;
977 }
978 *p++ = '\0';
979 tf.atime = strtoull(q, NULL, 10);
980 q = buf;
981 while (*p) {
982 int c = *p;
983 if (*p == '%') {
984 int i;
985 p++;
986 c = 0;
987 for (i = 0; i < 2; i++) {
de693987 988 c *= 16;
444c684c 989 if (*p >= '0' && *p <= '9')
990 c += *p - '0';
991 else if (*p >= 'A' && *p <= 'F')
992 c += *p - ('A' - 10);
993 else if (*p >= 'a' && *p <= 'f')
994 c += *p - ('a' - 10);
995 else {
996 fprintf(stderr, "%s: dump file line %d: unable"
997 " to parse hex escape\n", PNAME, line);
998 }
999 p++;
1000 }
1001 }
1002 *q++ = c;
1003 p++;
1004 }
1005 *q = '\0';
1006 triebuild_add(ctx->tb, buf, &tf);
1007 sfree(buf);
de693987 1008 line++;
444c684c 1009 }
1010 } else {
1011 du(scandir, gotdata, ctx);
1012 }
1013 if (mode != SCANDUMP) {
1014 count = triebuild_finish(ctx->tb);
1015 triebuild_free(ctx->tb);
84849cbd 1016
444c684c 1017 if (ctx->progress) {
1018 fprintf(stderr, "%-*s\r", ctx->progwidth, "");
1019 fflush(stderr);
1020 }
84849cbd 1021
444c684c 1022 /*
1023 * Work out how much space the cumulative index trees
1024 * will take; enlarge the file, and memory-map it.
1025 */
1026 if (fstat(fd, &st) < 0) {
bf53e756 1027 perror(PNAME ": fstat");
444c684c 1028 return 1;
1029 }
84849cbd 1030
444c684c 1031 printf("Built pathname index, %d entries, %ju bytes\n", count,
1032 (intmax_t)st.st_size);
1033
1034 totalsize = index_compute_size(st.st_size, count);
1035
1036 if (lseek(fd, totalsize-1, SEEK_SET) < 0) {
bf53e756 1037 perror(PNAME ": lseek");
84849cbd 1038 return 1;
1039 }
444c684c 1040 if (write(fd, "\0", 1) < 1) {
bf53e756 1041 perror(PNAME ": write");
84849cbd 1042 return 1;
1043 }
444c684c 1044
1045 printf("Upper bound on index file size = %ju bytes\n",
1046 (intmax_t)totalsize);
1047
1048 mappedfile = mmap(NULL, totalsize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0);
1049 if (!mappedfile) {
bf53e756 1050 perror(PNAME ": mmap");
444c684c 1051 return 1;
84849cbd 1052 }
444c684c 1053
05b0f827 1054 if (fakediratimes) {
1055 printf("Faking directory atimes\n");
1056 trie_fake_dir_atimes(mappedfile);
1057 }
1058
1059 printf("Building index\n");
444c684c 1060 ib = indexbuild_new(mappedfile, st.st_size, count);
1061 tw = triewalk_new(mappedfile);
1062 while ((tf = triewalk_next(tw, NULL)) != NULL)
1063 indexbuild_add(ib, tf);
1064 triewalk_free(tw);
1065 realsize = indexbuild_realsize(ib);
1066 indexbuild_free(ib);
1067
1068 munmap(mappedfile, totalsize);
1069 ftruncate(fd, realsize);
1070 close(fd);
1071 printf("Actual index file size = %ju bytes\n", (intmax_t)realsize);
84849cbd 1072 }
444c684c 1073 } else if (mode == TEXT) {
1074 char *querydir = actions[action].arg;
1075 size_t pathlen;
70322ae3 1076
444c684c 1077 fd = open(filename, O_RDONLY);
1078 if (fd < 0) {
1079 fprintf(stderr, "%s: %s: open: %s\n", PNAME, filename,
1080 strerror(errno));
1081 return 1;
1082 }
1083 if (fstat(fd, &st) < 0) {
bf53e756 1084 perror(PNAME ": fstat");
444c684c 1085 return 1;
1086 }
1087 totalsize = st.st_size;
1088 mappedfile = mmap(NULL, totalsize, PROT_READ, MAP_SHARED, fd, 0);
1089 if (!mappedfile) {
bf53e756 1090 perror(PNAME ": mmap");
444c684c 1091 return 1;
84849cbd 1092 }
444c684c 1093 pathsep = trie_pathsep(mappedfile);
70322ae3 1094
84849cbd 1095 /*
444c684c 1096 * Trim trailing slash, just in case.
84849cbd 1097 */
444c684c 1098 pathlen = strlen(querydir);
1099 if (pathlen > 0 && querydir[pathlen-1] == pathsep)
1100 querydir[--pathlen] = '\0';
1101
16e591d6 1102 text_query(mappedfile, querydir, textcutoff, tqdepth);
444c684c 1103 } else if (mode == HTML) {
1104 char *querydir = actions[action].arg;
1105 size_t pathlen;
1106 struct html_config cfg;
1107 unsigned long xi;
1108 char *html;
1109
1110 fd = open(filename, O_RDONLY);
1111 if (fd < 0) {
1112 fprintf(stderr, "%s: %s: open: %s\n", PNAME, filename,
1113 strerror(errno));
1114 return 1;
1115 }
84849cbd 1116 if (fstat(fd, &st) < 0) {
bf53e756 1117 perror(PNAME ": fstat");
84849cbd 1118 return 1;
1119 }
444c684c 1120 totalsize = st.st_size;
1121 mappedfile = mmap(NULL, totalsize, PROT_READ, MAP_SHARED, fd, 0);
1122 if (!mappedfile) {
bf53e756 1123 perror(PNAME ": mmap");
444c684c 1124 return 1;
1125 }
1126 pathsep = trie_pathsep(mappedfile);
70322ae3 1127
444c684c 1128 /*
1129 * Trim trailing slash, just in case.
1130 */
1131 pathlen = strlen(querydir);
1132 if (pathlen > 0 && querydir[pathlen-1] == pathsep)
1133 querydir[--pathlen] = '\0';
1134
1135 xi = trie_before(mappedfile, querydir);
1136 cfg.format = NULL;
1137 cfg.autoage = htmlautoagerange;
1138 cfg.oldest = htmloldest;
1139 cfg.newest = htmlnewest;
1140 html = html_query(mappedfile, xi, &cfg);
1141 fputs(html, stdout);
1142 } else if (mode == DUMP) {
1143 size_t maxpathlen;
1144 char *buf;
70322ae3 1145
444c684c 1146 fd = open(filename, O_RDONLY);
1147 if (fd < 0) {
1148 fprintf(stderr, "%s: %s: open: %s\n", PNAME, filename,
1149 strerror(errno));
84849cbd 1150 return 1;
1151 }
444c684c 1152 if (fstat(fd, &st) < 0) {
bf53e756 1153 perror(PNAME ": fstat");
84849cbd 1154 return 1;
1155 }
444c684c 1156 totalsize = st.st_size;
1157 mappedfile = mmap(NULL, totalsize, PROT_READ, MAP_SHARED, fd, 0);
84849cbd 1158 if (!mappedfile) {
bf53e756 1159 perror(PNAME ": mmap");
84849cbd 1160 return 1;
1161 }
444c684c 1162 pathsep = trie_pathsep(mappedfile);
1163
1164 maxpathlen = trie_maxpathlen(mappedfile);
1165 buf = snewn(maxpathlen, char);
84849cbd 1166
bf53e756 1167 printf(DUMPHDR "%02x\n", (unsigned char)pathsep);
84849cbd 1168 tw = triewalk_new(mappedfile);
444c684c 1169 while ((tf = triewalk_next(tw, buf)) != NULL)
1170 dump_line(buf, tf);
84849cbd 1171 triewalk_free(tw);
444c684c 1172 } else if (mode == HTTPD) {
1173 struct html_config pcfg;
1174 struct httpd_config dcfg;
70322ae3 1175
444c684c 1176 fd = open(filename, O_RDONLY);
1177 if (fd < 0) {
1178 fprintf(stderr, "%s: %s: open: %s\n", PNAME, filename,
1179 strerror(errno));
1180 return 1;
1181 }
1182 if (fstat(fd, &st) < 0) {
bf53e756 1183 perror(PNAME ": fstat");
444c684c 1184 return 1;
1185 }
1186 totalsize = st.st_size;
1187 mappedfile = mmap(NULL, totalsize, PROT_READ, MAP_SHARED, fd, 0);
1188 if (!mappedfile) {
bf53e756 1189 perror(PNAME ": mmap");
444c684c 1190 return 1;
1191 }
1192 pathsep = trie_pathsep(mappedfile);
1193
1194 dcfg.address = httpserveraddr;
1195 dcfg.port = httpserverport;
1196 dcfg.basicauthdata = httpauthdata;
1197 pcfg.format = NULL;
1198 pcfg.autoage = htmlautoagerange;
1199 pcfg.oldest = htmloldest;
1200 pcfg.newest = htmlnewest;
1201 run_httpd(mappedfile, auth, &dcfg, &pcfg);
355c3af7 1202 } else if (mode == REMOVE) {
1203 if (remove(filename) < 0) {
1204 fprintf(stderr, "%s: %s: remove: %s\n", PNAME, filename,
1205 strerror(errno));
1206 return 1;
1207 }
70322ae3 1208 }
70322ae3 1209 }
1210
1211 return 0;
1212}