6e3a2e5d4fc77a48fceccaeca985797c975d846f
2 * Main program for agedu.
16 #include <sys/types.h>
20 #include <sys/ioctl.h>
32 #define lenof(x) (sizeof((x))/sizeof(*(x)))
34 void fatal(const char *fmt
, ...)
37 fprintf(stderr
, "%s: ", PNAME
);
39 vfprintf(stderr
, fmt
, ap
);
41 fprintf(stderr
, "\n");
45 struct inclusion_exclusion
{
53 dev_t datafile_dev
, filesystem_dev
;
55 time_t last_output_update
;
56 int progress
, progwidth
;
57 struct inclusion_exclusion
*inex
;
62 static int gotdata(void *vctx
, const char *pathname
, const struct stat64
*st
)
64 struct ctx
*ctx
= (struct ctx
*)vctx
;
65 struct trie_file file
;
71 * Filter out our own data file.
73 if (st
->st_dev
== ctx
->datafile_dev
&& st
->st_ino
== ctx
->datafile_ino
)
77 * Don't cross the streams^W^Wany file system boundary.
79 if (!ctx
->crossfs
&& st
->st_dev
!= ctx
->filesystem_dev
)
83 * Filter based on wildcards.
86 filename
= strrchr(pathname
, '/');
91 for (i
= 0; i
< ctx
->ninex
; i
++) {
92 if (fnmatch(ctx
->inex
[i
].wildcard
,
93 ctx
->inex
[i
].path ? pathname
: filename
,
95 include
= ctx
->inex
[i
].include
;
98 return 1; /* filter, but don't prune */
100 file
.blocks
= st
->st_blocks
;
101 file
.atime
= st
->st_atime
;
102 triebuild_add(ctx
->tb
, pathname
, &file
);
105 if (t
!= ctx
->last_output_update
) {
107 fprintf(stderr
, "%-*.*s\r", ctx
->progwidth
, ctx
->progwidth
,
111 ctx
->last_output_update
= t
;
117 static void text_query(const void *mappedfile
, const char *querydir
,
122 unsigned long xi1
, xi2
;
123 unsigned long long s1
, s2
;
125 maxpathlen
= trie_maxpathlen(mappedfile
);
126 pathbuf
= snewn(maxpathlen
+ 1, char);
129 * We want to query everything between the supplied filename
130 * (inclusive) and that filename with a ^A on the end
131 * (exclusive). So find the x indices for each.
133 sprintf(pathbuf
, "%s\001", querydir
);
134 xi1
= trie_before(mappedfile
, querydir
);
135 xi2
= trie_before(mappedfile
, pathbuf
);
138 * Now do the lookups in the age index.
140 s1
= index_query(mappedfile
, xi1
, t
);
141 s2
= index_query(mappedfile
, xi2
, t
);
143 /* Display in units of 2 512-byte blocks = 1Kb */
144 printf("%-11llu %s\n", (s2
- s1
) / 2, querydir
);
148 * Now scan for first-level subdirectories and report
153 trie_getpath(mappedfile
, xi1
, pathbuf
);
154 text_query(mappedfile
, pathbuf
, t
, depth
-1);
155 strcat(pathbuf
, "\001");
156 xi1
= trie_before(mappedfile
, pathbuf
);
162 * Largely frivolous way to define all my command-line options. I
163 * present here a parametric macro which declares a series of
164 * _logical_ option identifiers, and for each one declares zero or
165 * more short option characters and zero or more long option
166 * words. Then I repeatedly invoke that macro with its arguments
167 * defined to be various other macros, which allows me to
170 * - define an enum allocating a distinct integer value to each
172 * - define a string consisting of precisely all the short option
174 * - define a string array consisting of all the long option
176 * - define (with help from auxiliary enums) integer arrays
177 * parallel to both of the above giving the logical option id
178 * for each physical short and long option
179 * - define an array indexed by logical option id indicating
180 * whether the option in question takes a value
181 * - define a function which prints out brief online help for all
184 * It's not at all clear to me that this trickery is actually
185 * particularly _efficient_ - it still, after all, requires going
186 * linearly through the option list at run time and doing a
187 * strcmp, whereas in an ideal world I'd have liked the lists of
188 * long and short options to be pre-sorted so that a binary search
189 * or some other more efficient lookup was possible. (Not that
190 * asymptotic algorithmic complexity is remotely vital in option
191 * parsing, but if I were doing this in, say, Lisp or something
192 * with an equivalently powerful preprocessor then once I'd had
193 * the idea of preparing the option-parsing data structures at
194 * compile time I would probably have made the effort to prepare
195 * them _properly_. I could have Perl generate me a source file
196 * from some sort of description, I suppose, but that would seem
197 * like overkill. And in any case, it's more of a challenge to
198 * achieve as much as possible by cunning use of cpp and enum than
199 * to just write some sensible and logical code in a Turing-
200 * complete language. I said it was largely frivolous :-)
202 * This approach does have the virtue that it brings together the
203 * option ids, option spellings and help text into a single
204 * combined list and defines them all in exactly one place. If I
205 * want to add a new option, or a new spelling for an option, I
206 * only have to modify the main OPTHELP macro below and then add
207 * code to process the new logical id.
209 * (Though, really, even that isn't ideal, since it still involves
210 * modifying the source file in more than one place. In a
211 * _properly_ ideal world, I'd be able to interleave the option
212 * definitions with the code fragments that process them. And then
213 * not bother defining logical identifiers for them at all - those
214 * would be automatically generated, since I wouldn't have any
215 * need to specify them manually in another part of the code.)
218 #define OPTHELP(NOVAL, VAL, SHORT, LONG, HELPPFX, HELPARG, HELPLINE, HELPOPT) \
219 HELPPFX("usage") HELPLINE("agedu [options] action") \
221 VAL(SCAN) SHORT(s) LONG(scan) \
222 HELPARG("directory") HELPOPT("scan and index a directory") \
223 NOVAL(DUMP) SHORT(d) LONG(dump) HELPOPT("dump the index file") \
224 VAL(TEXT) SHORT(t) LONG(text) \
225 HELPARG("subdir") HELPOPT("print a plain text report on a subdirectory") \
226 VAL(HTML) SHORT(H) LONG(html) \
227 HELPARG("subdir") HELPOPT("print an HTML report on a subdirectory") \
228 NOVAL(HTTPD) SHORT(w) LONG(web) LONG(server) LONG(httpd) \
229 HELPOPT("serve reports from a temporary web server") \
231 VAL(DATAFILE) SHORT(f) LONG(file) \
232 HELPARG("filename") HELPOPT("[all modes] specify index file") \
233 NOVAL(PROGRESS) LONG(progress) LONG(scan_progress) \
234 HELPOPT("[--scan] report progress on stderr") \
235 NOVAL(NOPROGRESS) LONG(no_progress) LONG(no_scan_progress) \
236 HELPOPT("[--scan] do not report progress") \
237 NOVAL(TTYPROGRESS) LONG(tty_progress) LONG(tty_scan_progress) \
238 LONG(progress_tty) LONG(scan_progress_tty) \
239 HELPOPT("[--scan] report progress if stderr is a tty") \
240 NOVAL(CROSSFS) LONG(cross_fs) \
241 HELPOPT("[--scan] cross filesystem boundaries") \
242 NOVAL(NOCROSSFS) LONG(no_cross_fs) \
243 HELPOPT("[--scan] stick to one filesystem") \
244 VAL(INCLUDE) LONG(include) \
245 HELPARG("wildcard") HELPOPT("[--scan] include files matching pattern") \
246 VAL(INCLUDEPATH) LONG(include_path) \
247 HELPARG("wildcard") HELPOPT("[--scan] include pathnames matching pattern") \
248 VAL(EXCLUDE) LONG(exclude) \
249 HELPARG("wildcard") HELPOPT("[--scan] exclude files matching pattern") \
250 VAL(EXCLUDEPATH) LONG(exclude_path) \
251 HELPARG("wildcard") HELPOPT("[--scan] exclude pathnames matching pattern") \
252 VAL(MINAGE) SHORT(a) LONG(age) LONG(min_age) LONG(minimum_age) \
253 HELPARG("age") HELPOPT("[--text] include only files older than this") \
254 VAL(AUTH) LONG(auth) LONG(http_auth) LONG(httpd_auth) \
255 LONG(server_auth) LONG(web_auth) \
256 HELPARG("type") HELPOPT("[--web] specify HTTP authentication method") \
258 NOVAL(HELP) SHORT(h) LONG(help) HELPOPT("display this help text") \
259 NOVAL(VERSION) SHORT(V) LONG(version) HELPOPT("report version number") \
260 NOVAL(LICENCE) LONG(licence) LONG(license) \
261 HELPOPT("display (MIT) licence text") \
264 #define DEFENUM(x) OPT_ ## x,
267 #define STRING(x) #x ,
268 #define STRINGNOCOMMA(x) #x
269 #define SHORTNEWOPT(x) SHORTtmp_ ## x = OPT_ ## x,
270 #define SHORTTHISOPT(x) SHORTtmp2_ ## x, SHORTVAL_ ## x = SHORTtmp2_ ## x - 1,
271 #define SHORTOPTVAL(x) SHORTVAL_ ## x,
272 #define SHORTTMP(x) SHORTtmp3_ ## x,
273 #define LONGNEWOPT(x) LONGtmp_ ## x = OPT_ ## x,
274 #define LONGTHISOPT(x) LONGtmp2_ ## x, LONGVAL_ ## x = LONGtmp2_ ## x - 1,
275 #define LONGOPTVAL(x) LONGVAL_ ## x,
276 #define LONGTMP(x) SHORTtmp3_ ## x,
278 #define OPTIONS(NOVAL, VAL, SHORT, LONG) \
279 OPTHELP(NOVAL, VAL, SHORT, LONG, IGNORE, IGNORE, IGNORE, IGNORE)
281 enum { OPTIONS(DEFENUM
,DEFENUM
,IGNORE
,IGNORE
) NOPTIONS
};
282 enum { OPTIONS(IGNORE
,IGNORE
,SHORTTMP
,IGNORE
) NSHORTOPTS
};
283 enum { OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGTMP
) NLONGOPTS
};
284 static const int opthasval
[NOPTIONS
] = {OPTIONS(ZERO
,ONE
,IGNORE
,IGNORE
)};
285 static const char shortopts
[] = {OPTIONS(IGNORE
,IGNORE
,STRINGNOCOMMA
,IGNORE
)};
286 static const char *const longopts
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,STRING
)};
287 enum { OPTIONS(SHORTNEWOPT
,SHORTNEWOPT
,SHORTTHISOPT
,IGNORE
) };
288 enum { OPTIONS(LONGNEWOPT
,LONGNEWOPT
,IGNORE
,LONGTHISOPT
) };
289 static const int shortvals
[] = {OPTIONS(IGNORE
,IGNORE
,SHORTOPTVAL
,IGNORE
)};
290 static const int longvals
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGOPTVAL
)};
292 static void usage(FILE *fp
)
295 const char *prefix
, *shortopt
, *longopt
, *optarg
;
298 #define HELPRESET prefix = shortopt = longopt = optarg = NULL, optex = -1
299 #define HELPNOVAL(s) optex = 0;
300 #define HELPVAL(s) optex = 1;
301 #define HELPSHORT(s) if (!shortopt) shortopt = "-" #s;
302 #define HELPLONG(s) if (!longopt) { \
303 strcpy(longbuf, "--" #s); longopt = longbuf; \
304 for (i = 0; longbuf[i]; i++) if (longbuf[i] == '_') longbuf[i] = '-'; }
305 #define HELPPFX(s) prefix = s;
306 #define HELPARG(s) optarg = s;
307 #define HELPLINE(s) assert(optex == -1); \
308 fprintf(fp, "%7s%c %s\n", prefix?prefix:"", prefix?':':' ', s); \
310 #define HELPOPT(s) assert((optex == 1 && optarg) || (optex == 0 && !optarg)); \
311 assert(shortopt || longopt); \
312 i = fprintf(fp, "%7s%c %s%s%s%s%s", prefix?prefix:"", prefix?':':' ', \
313 shortopt?shortopt:"", shortopt&&longopt?", ":"", longopt?longopt:"", \
314 optarg?" ":"", optarg?optarg:""); \
315 fprintf(fp, "%*s %s\n", i<32?32-i:0,"",s); HELPRESET;
318 OPTHELP(HELPNOVAL
, HELPVAL
, HELPSHORT
, HELPLONG
,
319 HELPPFX
, HELPARG
, HELPLINE
, HELPOPT
);
332 int main(int argc
, char **argv
)
335 struct ctx actx
, *ctx
= &actx
;
337 off_t totalsize
, realsize
;
341 const struct trie_file
*tf
;
342 char *filename
= "agedu.dat";
343 char *scandir
= NULL
;
344 char *querydir
= NULL
;
346 enum { USAGE
, TEXT
, HTML
, SCAN
, DUMP
, HTTPD
} mode
= USAGE
;
348 int auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
350 struct inclusion_exclusion
*inex
= NULL
;
351 int ninex
= 0, inexsize
= 0;
354 #ifdef DEBUG_MAD_OPTION_PARSING_MACROS
356 static const char *const optnames
[NOPTIONS
] = {
357 OPTIONS(STRING
,STRING
,IGNORE
,IGNORE
)
360 for (i
= 0; i
< NSHORTOPTS
; i
++)
361 printf("-%c == %s [%s]\n", shortopts
[i
], optnames
[shortvals
[i
]],
362 opthasval
[shortvals
[i
]] ?
"value" : "no value");
363 for (i
= 0; i
< NLONGOPTS
; i
++)
364 printf("--%s == %s [%s]\n", longopts
[i
], optnames
[longvals
[i
]],
365 opthasval
[longvals
[i
]] ?
"value" : "no value");
372 if (doing_opts
&& *p
== '-') {
375 if (!strcmp(p
, "--")) {
386 if (wordstart
&& *p
== '-') {
388 * GNU-style long option.
391 optval
= strchr(p
, '=');
395 for (i
= 0; i
< NLONGOPTS
; i
++) {
396 const char *opt
= longopts
[i
], *s
= p
;
399 * The underscores in the option names
400 * defined above may be given by the user
401 * as underscores or dashes, or omitted
406 if (*s
== '-' || *s
== '_')
424 fprintf(stderr
, "%s: unrecognised option '--%s'\n",
429 if (!opthasval
[optid
]) {
431 fprintf(stderr
, "%s: unexpected argument to option"
432 " '--%s'\n", PNAME
, p
);
440 fprintf(stderr
, "%s: option '--%s' expects"
441 " an argument\n", PNAME
, p
);
447 p
+= strlen(p
); /* finished with this argument word */
454 for (i
= 0; i
< NSHORTOPTS
; i
++)
455 if (c
== shortopts
[i
]) {
456 optid
= shortvals
[i
];
461 fprintf(stderr
, "%s: unrecognised option '-%c'\n",
466 if (opthasval
[optid
]) {
470 } else if (--argc
> 0) {
473 fprintf(stderr
, "%s: option '-%c' expects"
474 " an argument\n", PNAME
, c
);
485 * Now actually process the option.
492 printf("FIXME: version();\n");
495 printf("FIXME: licence();\n");
521 case OPT_TTYPROGRESS
:
537 if (!strcmp(optval
, "magic"))
538 auth
= HTTPD_AUTH_MAGIC
;
539 else if (!strcmp(optval
, "basic"))
540 auth
= HTTPD_AUTH_BASIC
;
541 else if (!strcmp(optval
, "none"))
542 auth
= HTTPD_AUTH_NONE
;
543 else if (!strcmp(optval
, "default"))
544 auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
546 fprintf(stderr
, "%s: unrecognised authentication"
547 " type '%s'\n%*s options are 'magic',"
548 " 'basic', 'none', 'default'\n",
549 PNAME
, optval
, (int)strlen(PNAME
), "");
554 case OPT_INCLUDEPATH
:
556 case OPT_EXCLUDEPATH
:
557 if (ninex
>= inexsize
) {
558 inexsize
= ninex
* 3 / 2 + 16;
559 inex
= sresize(inex
, inexsize
,
560 struct inclusion_exclusion
);
562 inex
[ninex
].path
= (optid
== OPT_INCLUDEPATH
||
563 optid
== OPT_EXCLUDEPATH
);
564 inex
[ninex
].include
= (optid
== OPT_INCLUDE
||
565 optid
== OPT_INCLUDEPATH
);
566 inex
[ninex
].wildcard
= optval
;
572 fprintf(stderr
, "%s: unexpected argument '%s'\n", PNAME
, p
);
580 } else if (mode
== SCAN
) {
582 fd
= open(filename
, O_RDWR
| O_TRUNC
| O_CREAT
, S_IRWXU
);
584 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
589 if (stat(scandir
, &st
) < 0) {
590 fprintf(stderr
, "%s: %s: stat: %s\n", PNAME
, scandir
,
594 ctx
->filesystem_dev
= crossfs ?
0 : st
.st_dev
;
596 if (fstat(fd
, &st
) < 0) {
597 perror("agedu: fstat");
600 ctx
->datafile_dev
= st
.st_dev
;
601 ctx
->datafile_ino
= st
.st_ino
;
604 ctx
->crossfs
= crossfs
;
606 ctx
->last_output_update
= time(NULL
);
608 /* progress==1 means report progress only if stderr is a tty */
610 progress
= isatty(2) ?
2 : 0;
611 ctx
->progress
= progress
;
614 if (progress
&& ioctl(2, TIOCGWINSZ
, &ws
) == 0)
615 ctx
->progwidth
= ws
.ws_col
- 1;
621 * Scan the directory tree, and write out the trie component
624 ctx
->tb
= triebuild_new(fd
);
625 du(scandir
, gotdata
, ctx
);
626 count
= triebuild_finish(ctx
->tb
);
627 triebuild_free(ctx
->tb
);
630 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
635 * Work out how much space the cumulative index trees will
636 * take; enlarge the file, and memory-map it.
638 if (fstat(fd
, &st
) < 0) {
639 perror("agedu: fstat");
643 printf("Built pathname index, %d entries, %ju bytes\n", count
,
644 (intmax_t)st
.st_size
);
646 totalsize
= index_compute_size(st
.st_size
, count
);
648 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
649 perror("agedu: lseek");
652 if (write(fd
, "\0", 1) < 1) {
653 perror("agedu: write");
657 printf("Upper bound on index file size = %ju bytes\n",
658 (intmax_t)totalsize
);
660 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
662 perror("agedu: mmap");
666 ib
= indexbuild_new(mappedfile
, st
.st_size
, count
);
667 tw
= triewalk_new(mappedfile
);
668 while ((tf
= triewalk_next(tw
, NULL
)) != NULL
)
669 indexbuild_add(ib
, tf
);
671 realsize
= indexbuild_realsize(ib
);
674 munmap(mappedfile
, totalsize
);
675 ftruncate(fd
, realsize
);
677 printf("Actual index file size = %ju bytes\n", (intmax_t)realsize
);
678 } else if (mode
== TEXT
) {
687 if (2 != sscanf(minage
, "%d%1[DdWwMmYy]", &nunits
, unit
)) {
688 fprintf(stderr
, "%s: minimum age should be a number followed by"
689 " one of d,w,m,y\n", PNAME
);
693 if (unit
[0] == 'd') {
695 } else if (unit
[0] == 'w') {
696 t
-= 86400 * 7 * nunits
;
701 ym
= tm
.tm_year
* 12 + tm
.tm_mon
;
708 tm
.tm_year
= ym
/ 12;
714 fd
= open(filename
, O_RDONLY
);
716 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
720 if (fstat(fd
, &st
) < 0) {
721 perror("agedu: fstat");
724 totalsize
= st
.st_size
;
725 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
727 perror("agedu: mmap");
732 * Trim trailing slash, just in case.
734 pathlen
= strlen(querydir
);
735 if (pathlen
> 0 && querydir
[pathlen
-1] == '/')
736 querydir
[--pathlen
] = '\0';
738 text_query(mappedfile
, querydir
, t
, 1);
739 } else if (mode
== HTML
) {
744 fd
= open(filename
, O_RDONLY
);
746 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
750 if (fstat(fd
, &st
) < 0) {
751 perror("agedu: fstat");
754 totalsize
= st
.st_size
;
755 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
757 perror("agedu: mmap");
762 * Trim trailing slash, just in case.
764 pathlen
= strlen(querydir
);
765 if (pathlen
> 0 && querydir
[pathlen
-1] == '/')
766 querydir
[--pathlen
] = '\0';
768 xi
= trie_before(mappedfile
, querydir
);
769 html
= html_query(mappedfile
, xi
, NULL
);
771 } else if (mode
== DUMP
) {
775 fd
= open(filename
, O_RDONLY
);
777 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
781 if (fstat(fd
, &st
) < 0) {
782 perror("agedu: fstat");
785 totalsize
= st
.st_size
;
786 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
788 perror("agedu: mmap");
792 maxpathlen
= trie_maxpathlen(mappedfile
);
793 buf
= snewn(maxpathlen
, char);
795 tw
= triewalk_new(mappedfile
);
796 while ((tf
= triewalk_next(tw
, buf
)) != NULL
) {
797 printf("%s: %llu %llu\n", buf
, tf
->blocks
, tf
->atime
);
800 } else if (mode
== HTTPD
) {
801 fd
= open(filename
, O_RDONLY
);
803 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
807 if (fstat(fd
, &st
) < 0) {
808 perror("agedu: fstat");
811 totalsize
= st
.st_size
;
812 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
814 perror("agedu: mmap");
818 run_httpd(mappedfile
, auth
);