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