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