b253f184f08c3eba9f4b49c93d6d071db10a476a
2 * Main program for agedu.
16 * Path separator. This global variable affects the behaviour of
17 * various parts of the code when they need to deal with path
18 * separators. The path separator appropriate to a particular data
19 * set is encoded in the index file storing that data set; data
20 * sets generated on Unix will of course have the default '/', but
21 * foreign data sets are conceivable and must be handled correctly.
25 void fatal(const char *fmt
, ...)
28 fprintf(stderr
, "%s: ", PNAME
);
30 vfprintf(stderr
, fmt
, ap
);
32 fprintf(stderr
, "\n");
36 struct inclusion_exclusion
{
44 dev_t datafile_dev
, filesystem_dev
;
46 time_t last_output_update
;
47 int progress
, progwidth
;
49 struct inclusion_exclusion
*inex
;
56 static void dump_line(const char *pathname
, const struct trie_file
*tf
)
59 if (printf("%llu %llu ", tf
->size
, tf
->atime
) < 0) goto error
;
60 for (p
= pathname
; *p
; p
++) {
61 if (*p
>= ' ' && *p
< 127 && *p
!= '%') {
62 if (putchar(*p
) == EOF
) goto error
;
64 if (printf("%%%02x", (unsigned char)*p
) < 0) goto error
;
67 if (putchar('\n') == EOF
) goto error
;
70 fatal("standard output: %s", strerror(errno
));
73 static int gotdata(void *vctx
, const char *pathname
, const STRUCT_STAT
*st
)
75 struct ctx
*ctx
= (struct ctx
*)vctx
;
76 struct trie_file file
;
82 * Filter out our own data file.
84 if (st
->st_dev
== ctx
->datafile_dev
&& st
->st_ino
== ctx
->datafile_ino
)
88 * Don't cross the streams^W^Wany file system boundary.
90 if (!ctx
->crossfs
&& st
->st_dev
!= ctx
->filesystem_dev
)
93 file
.size
= (unsigned long long)512 * st
->st_blocks
;
94 if (ctx
->usemtime
|| (ctx
->fakeatimes
&& S_ISDIR(st
->st_mode
)))
95 file
.atime
= st
->st_mtime
;
97 file
.atime
= max(st
->st_mtime
, st
->st_atime
);
100 * Filter based on wildcards.
103 filename
= strrchr(pathname
, pathsep
);
108 for (i
= 0; i
< ctx
->ninex
; i
++) {
109 if (fnmatch(ctx
->inex
[i
].wildcard
,
110 ctx
->inex
[i
].path ? pathname
: filename
, 0) == 0)
111 include
= ctx
->inex
[i
].type
;
114 return 0; /* ignore this entry and any subdirs */
117 * Here we are supposed to be filtering an entry out, but
118 * still recursing into it if it's a directory. However,
119 * we can't actually leave out any directory whose
120 * subdirectories we then look at. So we cheat, in that
121 * case, by setting the size to zero.
123 if (!S_ISDIR(st
->st_mode
))
124 return 0; /* just ignore */
129 if (ctx
->straight_to_dump
)
130 dump_line(pathname
, &file
);
132 triebuild_add(ctx
->tb
, pathname
, &file
);
136 if (t
!= ctx
->last_output_update
) {
137 fprintf(stderr
, "%-*.*s\r", ctx
->progwidth
, ctx
->progwidth
,
140 ctx
->last_output_update
= t
;
147 static void scan_error(void *vctx
, const char *fmt
, ...)
149 struct ctx
*ctx
= (struct ctx
*)vctx
;
153 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
157 fprintf(stderr
, "%s: ", PNAME
);
159 vfprintf(stderr
, fmt
, ap
);
162 ctx
->last_output_update
--; /* force a progress report next time */
165 static void text_query(const void *mappedfile
, const char *querydir
,
166 time_t t
, int showfiles
, int depth
)
170 unsigned long xi1
, xi2
;
171 unsigned long long size
;
173 maxpathlen
= trie_maxpathlen(mappedfile
);
174 pathbuf
= snewn(maxpathlen
+ 1, char);
177 * We want to query everything between the supplied filename
178 * (inclusive) and that filename with a ^A on the end
179 * (exclusive). So find the x indices for each.
181 strcpy(pathbuf
, querydir
);
182 make_successor(pathbuf
);
183 xi1
= trie_before(mappedfile
, querydir
);
184 xi2
= trie_before(mappedfile
, pathbuf
);
186 if (!showfiles
&& xi2
- xi1
== 1)
187 return; /* file, or empty dir => no display */
190 * Now do the lookups in the age index.
192 if (xi2
- xi1
== 1) {
194 * We are querying an individual file, so we should not
195 * depend on the index entries either side of the node,
196 * since they almost certainly don't both exist. Instead,
197 * just look up the file's size and atime in the main trie.
199 const struct trie_file
*f
= trie_getfile(mappedfile
, xi1
);
205 unsigned long long s1
, s2
;
206 s1
= index_query(mappedfile
, xi1
, t
);
207 s2
= index_query(mappedfile
, xi2
, t
);
212 return; /* no space taken up => no display */
216 * Now scan for first-level subdirectories and report
221 trie_getpath(mappedfile
, xi1
, pathbuf
);
222 text_query(mappedfile
, pathbuf
, t
, showfiles
, depth
-1);
223 make_successor(pathbuf
);
224 xi1
= trie_before(mappedfile
, pathbuf
);
228 /* Display in units of 1Kb */
229 printf("%-11llu %s\n", (size
) / 1024, querydir
);
233 * Largely frivolous way to define all my command-line options. I
234 * present here a parametric macro which declares a series of
235 * _logical_ option identifiers, and for each one declares zero or
236 * more short option characters and zero or more long option
237 * words. Then I repeatedly invoke that macro with its arguments
238 * defined to be various other macros, which allows me to
241 * - define an enum allocating a distinct integer value to each
243 * - define a string consisting of precisely all the short option
245 * - define a string array consisting of all the long option
247 * - define (with help from auxiliary enums) integer arrays
248 * parallel to both of the above giving the logical option id
249 * for each physical short and long option
250 * - define an array indexed by logical option id indicating
251 * whether the option in question takes a value
252 * - define a function which prints out brief online help for all
255 * It's not at all clear to me that this trickery is actually
256 * particularly _efficient_ - it still, after all, requires going
257 * linearly through the option list at run time and doing a
258 * strcmp, whereas in an ideal world I'd have liked the lists of
259 * long and short options to be pre-sorted so that a binary search
260 * or some other more efficient lookup was possible. (Not that
261 * asymptotic algorithmic complexity is remotely vital in option
262 * parsing, but if I were doing this in, say, Lisp or something
263 * with an equivalently powerful preprocessor then once I'd had
264 * the idea of preparing the option-parsing data structures at
265 * compile time I would probably have made the effort to prepare
266 * them _properly_. I could have Perl generate me a source file
267 * from some sort of description, I suppose, but that would seem
268 * like overkill. And in any case, it's more of a challenge to
269 * achieve as much as possible by cunning use of cpp and enum than
270 * to just write some sensible and logical code in a Turing-
271 * complete language. I said it was largely frivolous :-)
273 * This approach does have the virtue that it brings together the
274 * option ids, option spellings and help text into a single
275 * combined list and defines them all in exactly one place. If I
276 * want to add a new option, or a new spelling for an option, I
277 * only have to modify the main OPTHELP macro below and then add
278 * code to process the new logical id.
280 * (Though, really, even that isn't ideal, since it still involves
281 * modifying the source file in more than one place. In a
282 * _properly_ ideal world, I'd be able to interleave the option
283 * definitions with the code fragments that process them. And then
284 * not bother defining logical identifiers for them at all - those
285 * would be automatically generated, since I wouldn't have any
286 * need to specify them manually in another part of the code.)
288 * One other helpful consequence of the enum-based structure here
289 * is that it causes a compiler error if I accidentally try to
290 * define the same option (short or long) twice.
293 #define OPTHELP(NOVAL, VAL, SHORT, LONG, HELPPFX, HELPARG, HELPLINE, HELPOPT) \
294 HELPPFX("usage") HELPLINE(PNAME " [options] action [action...]") \
296 VAL(SCAN) SHORT(s) LONG(scan) \
297 HELPARG("directory") HELPOPT("scan and index a directory") \
298 NOVAL(HTTPD) SHORT(w) LONG(web) LONG(server) LONG(httpd) \
299 HELPOPT("serve HTML reports from a temporary web server") \
300 VAL(TEXT) SHORT(t) LONG(text) \
301 HELPARG("subdir") HELPOPT("print a plain text report on a subdirectory") \
302 NOVAL(REMOVE) SHORT(R) LONG(remove) LONG(delete) LONG(unlink) \
303 HELPOPT("remove the index file") \
304 NOVAL(DUMP) SHORT(D) LONG(dump) HELPOPT("dump the index file on stdout") \
305 NOVAL(LOAD) SHORT(L) LONG(load) \
306 HELPOPT("load and index a dump file") \
307 VAL(SCANDUMP) SHORT(S) LONG(scan_dump) \
308 HELPARG("directory") HELPOPT("scan only, generating a dump") \
309 VAL(HTML) SHORT(H) LONG(html) \
310 HELPARG("subdir") HELPOPT("print an HTML report on a subdirectory") \
312 VAL(DATAFILE) SHORT(f) LONG(file) \
313 HELPARG("filename") HELPOPT("[most modes] specify index file") \
314 NOVAL(CROSSFS) LONG(cross_fs) \
315 HELPOPT("[--scan] cross filesystem boundaries") \
316 NOVAL(NOCROSSFS) LONG(no_cross_fs) \
317 HELPOPT("[--scan] stick to one filesystem") \
318 VAL(PRUNE) LONG(prune) \
319 HELPARG("wildcard") HELPOPT("[--scan] prune files matching pattern") \
320 VAL(PRUNEPATH) LONG(prune_path) \
321 HELPARG("wildcard") HELPOPT("[--scan] prune pathnames matching pattern") \
322 VAL(EXCLUDE) LONG(exclude) \
323 HELPARG("wildcard") HELPOPT("[--scan] exclude files matching pattern") \
324 VAL(EXCLUDEPATH) LONG(exclude_path) \
325 HELPARG("wildcard") HELPOPT("[--scan] exclude pathnames matching pattern") \
326 VAL(INCLUDE) LONG(include) \
327 HELPARG("wildcard") HELPOPT("[--scan] include files matching pattern") \
328 VAL(INCLUDEPATH) LONG(include_path) \
329 HELPARG("wildcard") HELPOPT("[--scan] include pathnames matching pattern") \
330 NOVAL(PROGRESS) LONG(progress) LONG(scan_progress) \
331 HELPOPT("[--scan] report progress on stderr") \
332 NOVAL(NOPROGRESS) LONG(no_progress) LONG(no_scan_progress) \
333 HELPOPT("[--scan] do not report progress") \
334 NOVAL(TTYPROGRESS) LONG(tty_progress) LONG(tty_scan_progress) \
335 LONG(progress_tty) LONG(scan_progress_tty) \
336 HELPOPT("[--scan] report progress if stderr is a tty") \
337 NOVAL(DIRATIME) LONG(dir_atime) LONG(dir_atimes) \
338 HELPOPT("[--scan,--load] keep real atimes on directories") \
339 NOVAL(NODIRATIME) LONG(no_dir_atime) LONG(no_dir_atimes) \
340 HELPOPT("[--scan,--load] fake atimes on directories") \
341 NOVAL(MTIME) LONG(mtime) \
342 HELPOPT("[--scan] use mtime instead of atime") \
343 NOVAL(SHOWFILES) LONG(files) \
344 HELPOPT("[--web,--html,--text] list individual files") \
345 VAL(AGERANGE) SHORT(r) LONG(age_range) LONG(range) LONG(ages) \
346 HELPARG("age[-age]") HELPOPT("[--web,--html] set limits of colour coding") \
347 VAL(SERVERADDR) LONG(address) LONG(addr) LONG(server_address) \
349 HELPARG("addr[:port]") HELPOPT("[--web] specify HTTP server address") \
350 VAL(AUTH) LONG(auth) LONG(http_auth) LONG(httpd_auth) \
351 LONG(server_auth) LONG(web_auth) \
352 HELPARG("type") HELPOPT("[--web] specify HTTP authentication method") \
353 VAL(AUTHFILE) LONG(auth_file) \
354 HELPARG("filename") HELPOPT("[--web] read HTTP Basic user/pass from file") \
355 VAL(AUTHFD) LONG(auth_fd) \
356 HELPARG("fd") HELPOPT("[--web] read HTTP Basic user/pass from fd") \
357 VAL(TQDEPTH) SHORT(d) LONG(depth) LONG(max_depth) LONG(maximum_depth) \
358 HELPARG("levels") HELPOPT("[--text] recurse to this many levels") \
359 VAL(MINAGE) SHORT(a) LONG(age) LONG(min_age) LONG(minimum_age) \
360 HELPARG("age") HELPOPT("[--text] include only files older than this") \
362 NOVAL(HELP) SHORT(h) LONG(help) HELPOPT("display this help text") \
363 NOVAL(VERSION) SHORT(V) LONG(version) HELPOPT("report version number") \
364 NOVAL(LICENCE) LONG(licence) LONG(license) \
365 HELPOPT("display (MIT) licence text") \
368 #define DEFENUM(x) OPT_ ## x,
371 #define STRING(x) #x ,
372 #define STRINGNOCOMMA(x) #x
373 #define SHORTNEWOPT(x) SHORTtmp_ ## x = OPT_ ## x,
374 #define SHORTTHISOPT(x) SHORTtmp2_ ## x, SHORTVAL_ ## x = SHORTtmp2_ ## x - 1,
375 #define SHORTOPTVAL(x) SHORTVAL_ ## x,
376 #define SHORTTMP(x) SHORTtmp3_ ## x,
377 #define LONGNEWOPT(x) LONGtmp_ ## x = OPT_ ## x,
378 #define LONGTHISOPT(x) LONGtmp2_ ## x, LONGVAL_ ## x = LONGtmp2_ ## x - 1,
379 #define LONGOPTVAL(x) LONGVAL_ ## x,
380 #define LONGTMP(x) SHORTtmp3_ ## x,
382 #define OPTIONS(NOVAL, VAL, SHORT, LONG) \
383 OPTHELP(NOVAL, VAL, SHORT, LONG, IGNORE, IGNORE, IGNORE, IGNORE)
385 enum { OPTIONS(DEFENUM
,DEFENUM
,IGNORE
,IGNORE
) NOPTIONS
};
386 enum { OPTIONS(IGNORE
,IGNORE
,SHORTTMP
,IGNORE
) NSHORTOPTS
};
387 enum { OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGTMP
) NLONGOPTS
};
388 static const int opthasval
[NOPTIONS
] = {OPTIONS(ZERO
,ONE
,IGNORE
,IGNORE
)};
389 static const char shortopts
[] = {OPTIONS(IGNORE
,IGNORE
,STRINGNOCOMMA
,IGNORE
)};
390 static const char *const longopts
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,STRING
)};
391 enum { OPTIONS(SHORTNEWOPT
,SHORTNEWOPT
,SHORTTHISOPT
,IGNORE
) };
392 enum { OPTIONS(LONGNEWOPT
,LONGNEWOPT
,IGNORE
,LONGTHISOPT
) };
393 static const int shortvals
[] = {OPTIONS(IGNORE
,IGNORE
,SHORTOPTVAL
,IGNORE
)};
394 static const int longvals
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGOPTVAL
)};
396 static void usage(FILE *fp
)
399 const char *prefix
, *shortopt
, *longopt
, *optarg
;
402 #define HELPRESET prefix = shortopt = longopt = optarg = NULL, optex = -1
403 #define HELPNOVAL(s) optex = 0;
404 #define HELPVAL(s) optex = 1;
405 #define HELPSHORT(s) if (!shortopt) shortopt = "-" #s;
406 #define HELPLONG(s) if (!longopt) { \
407 strcpy(longbuf, "--" #s); longopt = longbuf; \
408 for (i = 0; longbuf[i]; i++) if (longbuf[i] == '_') longbuf[i] = '-'; }
409 #define HELPPFX(s) prefix = s;
410 #define HELPARG(s) optarg = s;
411 #define HELPLINE(s) assert(optex == -1); \
412 fprintf(fp, "%7s%c %s\n", prefix?prefix:"", prefix?':':' ', s); \
414 #define HELPOPT(s) assert((optex == 1 && optarg) || (optex == 0 && !optarg)); \
415 assert(shortopt || longopt); \
416 i = fprintf(fp, "%7s%c %s%s%s%s%s", prefix?prefix:"", prefix?':':' ', \
417 shortopt?shortopt:"", shortopt&&longopt?", ":"", longopt?longopt:"", \
418 optarg?" ":"", optarg?optarg:""); \
419 fprintf(fp, "%*s %s\n", i<32?32-i:0,"",s); HELPRESET;
422 OPTHELP(HELPNOVAL
, HELPVAL
, HELPSHORT
, HELPLONG
,
423 HELPPFX
, HELPARG
, HELPLINE
, HELPOPT
);
436 static time_t parse_age(time_t now
, const char *agestr
)
445 if (2 != sscanf(agestr
, "%d%1[DdWwMmYy]", &nunits
, unit
)) {
446 fprintf(stderr
, "%s: age specification should be a number followed by"
447 " one of d,w,m,y\n", PNAME
);
451 if (unit
[0] == 'd') {
453 } else if (unit
[0] == 'w') {
454 t
-= 86400 * 7 * nunits
;
459 ym
= tm
.tm_year
* 12 + tm
.tm_mon
;
466 tm
.tm_year
= ym
/ 12;
475 int main(int argc
, char **argv
)
478 struct ctx actx
, *ctx
= &actx
;
480 off_t totalsize
, realsize
;
484 const struct trie_file
*tf
, *prevtf
;
485 char *filename
= PNAME
".dat";
487 enum { TEXT
, HTML
, SCAN
, DUMP
, SCANDUMP
, LOAD
, HTTPD
, REMOVE
};
492 int nactions
= 0, actionsize
= 0, action
;
493 time_t now
= time(NULL
);
494 time_t textcutoff
= now
, htmlnewest
= now
, htmloldest
= now
;
495 int htmlautoagerange
= 1;
496 const char *httpserveraddr
= NULL
;
497 int httpserverport
= 0;
498 const char *httpauthdata
= NULL
;
499 int auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
501 struct inclusion_exclusion
*inex
= NULL
;
502 int ninex
= 0, inexsize
= 0;
505 int fakediratimes
= 1;
509 #ifdef DEBUG_MAD_OPTION_PARSING_MACROS
511 static const char *const optnames
[NOPTIONS
] = {
512 OPTIONS(STRING
,STRING
,IGNORE
,IGNORE
)
515 for (i
= 0; i
< NSHORTOPTS
; i
++)
516 printf("-%c == %s [%s]\n", shortopts
[i
], optnames
[shortvals
[i
]],
517 opthasval
[shortvals
[i
]] ?
"value" : "no value");
518 for (i
= 0; i
< NLONGOPTS
; i
++)
519 printf("--%s == %s [%s]\n", longopts
[i
], optnames
[longvals
[i
]],
520 opthasval
[longvals
[i
]] ?
"value" : "no value");
527 if (doing_opts
&& *p
== '-') {
530 if (!strcmp(p
, "--")) {
541 if (wordstart
&& *p
== '-') {
543 * GNU-style long option.
546 optval
= strchr(p
, '=');
550 for (i
= 0; i
< NLONGOPTS
; i
++) {
551 const char *opt
= longopts
[i
], *s
= p
;
554 * The underscores in the option names
555 * defined above may be given by the user
556 * as underscores or dashes, or omitted
561 if (*s
== '-' || *s
== '_')
579 fprintf(stderr
, "%s: unrecognised option '--%s'\n",
584 if (!opthasval
[optid
]) {
586 fprintf(stderr
, "%s: unexpected argument to option"
587 " '--%s'\n", PNAME
, p
);
595 fprintf(stderr
, "%s: option '--%s' expects"
596 " an argument\n", PNAME
, p
);
602 p
+= strlen(p
); /* finished with this argument word */
609 for (i
= 0; i
< NSHORTOPTS
; i
++)
610 if (c
== shortopts
[i
]) {
611 optid
= shortvals
[i
];
616 fprintf(stderr
, "%s: unrecognised option '-%c'\n",
621 if (opthasval
[optid
]) {
625 } else if (--argc
> 0) {
628 fprintf(stderr
, "%s: option '-%c' expects"
629 " an argument\n", PNAME
, c
);
640 * Now actually process the option.
647 #ifdef PACKAGE_VERSION
648 printf("%s, revision %s\n", PNAME
, PACKAGE_VERSION
);
650 printf("%s: version number not available when not built"
651 " via automake\n", PNAME
);
656 extern const char *const licence
[];
659 for (i
= 0; licence
[i
]; i
++)
660 fputs(licence
[i
], stdout
);
666 if (nactions
>= actionsize
) {
667 actionsize
= nactions
* 3 / 2 + 16;
668 actions
= sresize(actions
, actionsize
, struct action
);
670 actions
[nactions
].mode
= SCAN
;
671 actions
[nactions
].arg
= optval
;
675 if (nactions
>= actionsize
) {
676 actionsize
= nactions
* 3 / 2 + 16;
677 actions
= sresize(actions
, actionsize
, struct action
);
679 actions
[nactions
].mode
= SCANDUMP
;
680 actions
[nactions
].arg
= optval
;
684 if (nactions
>= actionsize
) {
685 actionsize
= nactions
* 3 / 2 + 16;
686 actions
= sresize(actions
, actionsize
, struct action
);
688 actions
[nactions
].mode
= DUMP
;
689 actions
[nactions
].arg
= NULL
;
693 if (nactions
>= actionsize
) {
694 actionsize
= nactions
* 3 / 2 + 16;
695 actions
= sresize(actions
, actionsize
, struct action
);
697 actions
[nactions
].mode
= LOAD
;
698 actions
[nactions
].arg
= NULL
;
702 if (nactions
>= actionsize
) {
703 actionsize
= nactions
* 3 / 2 + 16;
704 actions
= sresize(actions
, actionsize
, struct action
);
706 actions
[nactions
].mode
= TEXT
;
707 actions
[nactions
].arg
= optval
;
711 if (nactions
>= actionsize
) {
712 actionsize
= nactions
* 3 / 2 + 16;
713 actions
= sresize(actions
, actionsize
, struct action
);
715 actions
[nactions
].mode
= HTML
;
716 actions
[nactions
].arg
= optval
;
720 if (nactions
>= actionsize
) {
721 actionsize
= nactions
* 3 / 2 + 16;
722 actions
= sresize(actions
, actionsize
, struct action
);
724 actions
[nactions
].mode
= HTTPD
;
725 actions
[nactions
].arg
= NULL
;
729 if (nactions
>= actionsize
) {
730 actionsize
= nactions
* 3 / 2 + 16;
731 actions
= sresize(actions
, actionsize
, struct action
);
733 actions
[nactions
].mode
= REMOVE
;
734 actions
[nactions
].arg
= NULL
;
743 case OPT_TTYPROGRESS
:
768 tqdepth
= atoi(optval
);
771 textcutoff
= parse_age(now
, optval
);
774 if (!strcmp(optval
, "auto")) {
775 htmlautoagerange
= 1;
777 char *q
= optval
+ strcspn(optval
, "-:");
780 htmloldest
= parse_age(now
, optval
);
781 htmlnewest
= *q ?
parse_age(now
, q
) : now
;
782 htmlautoagerange
= 0;
788 if (optval
[0] == '[' &&
789 (port
= strchr(optval
, ']')) != NULL
)
793 port
+= strcspn(port
, ":");
796 httpserveraddr
= optval
;
797 httpserverport
= atoi(port
);
801 if (!strcmp(optval
, "magic"))
802 auth
= HTTPD_AUTH_MAGIC
;
803 else if (!strcmp(optval
, "basic"))
804 auth
= HTTPD_AUTH_BASIC
;
805 else if (!strcmp(optval
, "none"))
806 auth
= HTTPD_AUTH_NONE
;
807 else if (!strcmp(optval
, "default"))
808 auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
809 else if (!strcmp(optval
, "help") ||
810 !strcmp(optval
, "list")) {
811 printf(PNAME
": supported HTTP authentication types"
813 " magic use Linux /proc/net/tcp to"
814 " determine owner of peer socket\n"
815 " basic HTTP Basic username and"
816 " password authentication\n"
817 " default use 'magic' if possible, "
818 " otherwise fall back to 'basic'\n"
819 " none unauthenticated HTTP (if"
820 " the data file is non-confidential)\n");
823 fprintf(stderr
, "%s: unrecognised authentication"
824 " type '%s'\n%*s options are 'magic',"
825 " 'basic', 'none', 'default'\n",
826 PNAME
, optval
, (int)strlen(PNAME
), "");
837 int authlen
, authsize
;
840 if (optid
== OPT_AUTHFILE
) {
841 fd
= open(optval
, O_RDONLY
);
843 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
,
844 optval
, strerror(errno
));
851 sprintf(namebuf
, "fd %d", fd
);
856 authbuf
= snewn(authsize
, char);
857 while ((ret
= read(fd
, authbuf
+authlen
,
858 authsize
-authlen
)) > 0) {
860 if ((authsize
- authlen
) < (authsize
/ 16)) {
861 authsize
= authlen
* 3 / 2 + 4096;
862 authbuf
= sresize(authbuf
, authsize
, char);
866 fprintf(stderr
, "%s: %s: read: %s\n", PNAME
,
867 name
, strerror(errno
));
870 if (optid
== OPT_AUTHFILE
)
872 httpauthdata
= authbuf
;
876 case OPT_INCLUDEPATH
:
878 case OPT_EXCLUDEPATH
:
881 if (ninex
>= inexsize
) {
882 inexsize
= ninex
* 3 / 2 + 16;
883 inex
= sresize(inex
, inexsize
,
884 struct inclusion_exclusion
);
886 inex
[ninex
].path
= (optid
== OPT_INCLUDEPATH
||
887 optid
== OPT_EXCLUDEPATH
||
888 optid
== OPT_PRUNEPATH
);
889 inex
[ninex
].type
= (optid
== OPT_INCLUDE ?
1 :
890 optid
== OPT_INCLUDEPATH ?
1 :
891 optid
== OPT_EXCLUDE ?
0 :
892 optid
== OPT_EXCLUDEPATH ?
0 :
893 optid
== OPT_PRUNE ?
-1 :
894 /* optid == OPT_PRUNEPATH ? */ -1);
895 inex
[ninex
].wildcard
= optval
;
901 fprintf(stderr
, "%s: unexpected argument '%s'\n", PNAME
, p
);
911 for (action
= 0; action
< nactions
; action
++) {
912 int mode
= actions
[action
].mode
;
914 if (mode
== SCAN
|| mode
== SCANDUMP
|| mode
== LOAD
) {
915 const char *scandir
= actions
[action
].arg
;
918 char *buf
= fgetline(stdin
);
920 buf
[strcspn(buf
, "\r\n")] = '\0';
921 if (1 != sscanf(buf
, DUMPHDR
"%x",
923 fprintf(stderr
, "%s: header in dump file not recognised\n",
927 pathsep
= (char)newpathsep
;
931 if (mode
== SCAN
|| mode
== LOAD
) {
933 * Prepare to write out the index file.
935 fd
= open(filename
, O_RDWR
| O_TRUNC
| O_CREAT
,
938 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
942 if (fstat(fd
, &st
) < 0) {
943 perror(PNAME
": fstat");
946 ctx
->datafile_dev
= st
.st_dev
;
947 ctx
->datafile_ino
= st
.st_ino
;
948 ctx
->straight_to_dump
= 0;
950 ctx
->datafile_dev
= -1;
951 ctx
->datafile_ino
= -1;
952 ctx
->straight_to_dump
= 1;
955 if (mode
== SCAN
|| mode
== SCANDUMP
) {
956 if (stat(scandir
, &st
) < 0) {
957 fprintf(stderr
, "%s: %s: stat: %s\n", PNAME
, scandir
,
961 ctx
->filesystem_dev
= crossfs ?
0 : st
.st_dev
;
966 ctx
->crossfs
= crossfs
;
967 ctx
->fakeatimes
= fakediratimes
;
968 ctx
->usemtime
= mtime
;
970 ctx
->last_output_update
= time(NULL
);
972 /* progress==1 means report progress only if stderr is a tty */
974 progress
= isatty(2) ?
2 : 0;
975 ctx
->progress
= progress
;
979 ioctl(2, TIOCGWINSZ
, &ws
) == 0 &&
981 ctx
->progwidth
= ws
.ws_col
- 1;
986 if (mode
== SCANDUMP
)
987 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
990 * Scan the directory tree, and write out the trie component
993 if (mode
!= SCANDUMP
) {
994 ctx
->tb
= triebuild_new(fd
);
999 while ((buf
= fgetline(stdin
)) != NULL
) {
1000 struct trie_file tf
;
1003 buf
[strcspn(buf
, "\r\n")] = '\0';
1007 while (*p
&& *p
!= ' ') p
++;
1009 fprintf(stderr
, "%s: dump file line %d: expected at least"
1010 " three fields\n", PNAME
, line
);
1014 tf
.size
= strtoull(q
, NULL
, 10);
1016 while (*p
&& *p
!= ' ') p
++;
1018 fprintf(stderr
, "%s: dump file line %d: expected at least"
1019 " three fields\n", PNAME
, line
);
1023 tf
.atime
= strtoull(q
, NULL
, 10);
1031 for (i
= 0; i
< 2; i
++) {
1033 if (*p
>= '0' && *p
<= '9')
1035 else if (*p
>= 'A' && *p
<= 'F')
1036 c
+= *p
- ('A' - 10);
1037 else if (*p
>= 'a' && *p
<= 'f')
1038 c
+= *p
- ('a' - 10);
1040 fprintf(stderr
, "%s: dump file line %d: unable"
1041 " to parse hex escape\n", PNAME
, line
);
1051 triebuild_add(ctx
->tb
, buf
, &tf
);
1056 du(scandir
, gotdata
, scan_error
, ctx
);
1058 if (mode
!= SCANDUMP
) {
1061 char *buf
, *prevbuf
;
1063 count
= triebuild_finish(ctx
->tb
);
1064 triebuild_free(ctx
->tb
);
1066 if (ctx
->progress
) {
1067 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
1072 * Work out how much space the cumulative index trees
1073 * will take; enlarge the file, and memory-map it.
1075 if (fstat(fd
, &st
) < 0) {
1076 perror(PNAME
": fstat");
1080 printf("Built pathname index, %d entries,"
1081 " %llu bytes of index\n", count
,
1082 (unsigned long long)st
.st_size
);
1084 totalsize
= index_initial_size(st
.st_size
, count
);
1085 totalsize
+= totalsize
/ 10;
1087 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1088 perror(PNAME
": lseek");
1091 if (write(fd
, "\0", 1) < 1) {
1092 perror(PNAME
": write");
1096 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1098 perror(PNAME
": mmap");
1102 if (fakediratimes
) {
1103 printf("Faking directory atimes\n");
1104 trie_fake_dir_atimes(mappedfile
);
1107 printf("Building index\n");
1108 ib
= indexbuild_new(mappedfile
, st
.st_size
, count
, &delta
);
1109 maxpathlen
= trie_maxpathlen(mappedfile
);
1110 buf
= snewn(maxpathlen
, char);
1111 prevbuf
= snewn(maxpathlen
, char);
1112 tw
= triewalk_new(mappedfile
);
1114 tf
= triewalk_next(tw
, buf
);
1119 if (totalsize
- indexbuild_realsize(ib
) < delta
) {
1120 const void *oldfile
= mappedfile
;
1124 * Unmap the file, grow it, and remap it.
1126 munmap(mappedfile
, totalsize
);
1129 totalsize
+= totalsize
/ 10;
1131 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1132 perror(PNAME
": lseek");
1135 if (write(fd
, "\0", 1) < 1) {
1136 perror(PNAME
": write");
1140 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1142 perror(PNAME
": mmap");
1146 indexbuild_rebase(ib
, mappedfile
);
1147 triewalk_rebase(tw
, mappedfile
);
1148 diff
= (const unsigned char *)mappedfile
-
1149 (const unsigned char *)oldfile
;
1151 prevtf
= (const struct trie_file
*)
1152 (((const unsigned char *)prevtf
) + diff
);
1154 tf
= (const struct trie_file
*)
1155 (((const unsigned char *)tf
) + diff
);
1159 * Get the next file from the index. So we are
1160 * currently holding, and have not yet
1161 * indexed, prevtf (with pathname prevbuf) and
1162 * tf (with pathname buf).
1165 memcpy(prevbuf
, buf
, maxpathlen
);
1166 tf
= triewalk_next(tw
, buf
);
1172 * Find the first differing character position
1173 * between our two pathnames.
1175 for (i
= 0; prevbuf
[i
] && prevbuf
[i
] == buf
[i
]; i
++);
1178 * If prevbuf was a directory name and buf is
1179 * something inside that directory, then
1180 * trie_before() will be called on prevbuf
1181 * itself. Hence we must drop a tag before it,
1182 * so that the resulting index is usable.
1184 if ((!prevbuf
[i
] && (buf
[i
] == pathsep
||
1185 (i
> 0 && buf
[i
-1] == pathsep
))))
1189 * Add prevtf to the index.
1191 indexbuild_add(ib
, prevtf
);
1195 * Drop an unconditional final tag, and
1196 * get out of this loop.
1203 * If prevbuf was a filename inside some
1204 * directory which buf is outside, then
1205 * trie_before() will be called on some
1206 * pathname either equal to buf or epsilon
1207 * less than it. Either way, we're going to
1208 * need to drop a tag after prevtf.
1210 if (strchr(prevbuf
+i
, pathsep
) || !tf
)
1215 realsize
= indexbuild_realsize(ib
);
1216 indexbuild_free(ib
);
1218 munmap(mappedfile
, totalsize
);
1219 ftruncate(fd
, realsize
);
1221 printf("Final index file size = %llu bytes\n",
1222 (unsigned long long)realsize
);
1224 } else if (mode
== TEXT
) {
1225 char *querydir
= actions
[action
].arg
;
1228 fd
= open(filename
, O_RDONLY
);
1230 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1234 if (fstat(fd
, &st
) < 0) {
1235 perror(PNAME
": fstat");
1238 totalsize
= st
.st_size
;
1239 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1241 perror(PNAME
": mmap");
1244 pathsep
= trie_pathsep(mappedfile
);
1247 * Trim trailing slash, just in case.
1249 pathlen
= strlen(querydir
);
1250 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1251 querydir
[--pathlen
] = '\0';
1253 text_query(mappedfile
, querydir
, textcutoff
, showfiles
, tqdepth
);
1255 munmap(mappedfile
, totalsize
);
1256 } else if (mode
== HTML
) {
1257 char *querydir
= actions
[action
].arg
;
1258 size_t pathlen
, maxpathlen
;
1260 struct html_config cfg
;
1264 fd
= open(filename
, O_RDONLY
);
1266 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1270 if (fstat(fd
, &st
) < 0) {
1271 perror(PNAME
": fstat");
1274 totalsize
= st
.st_size
;
1275 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1277 perror(PNAME
": mmap");
1280 pathsep
= trie_pathsep(mappedfile
);
1282 maxpathlen
= trie_maxpathlen(mappedfile
);
1283 pathbuf
= snewn(maxpathlen
, char);
1286 * Trim trailing slash, just in case.
1288 pathlen
= strlen(querydir
);
1289 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1290 querydir
[--pathlen
] = '\0';
1292 xi
= trie_before(mappedfile
, querydir
);
1293 if (xi
>= trie_count(mappedfile
) ||
1294 (trie_getpath(mappedfile
, xi
, pathbuf
),
1295 strcmp(pathbuf
, querydir
))) {
1296 fprintf(stderr
, "%s: pathname '%s' does not exist in index\n"
1297 "%*s(check it is spelled exactly as it is in the "
1298 "index, including\n%*sany leading './')\n",
1300 (int)(1+sizeof(PNAME
)), "",
1301 (int)(1+sizeof(PNAME
)), "");
1302 } else if (!index_has_root(mappedfile
, xi
)) {
1303 fprintf(stderr
, "%s: pathname '%s' is"
1304 " a file, not a directory\n", PNAME
, querydir
);
1307 cfg
.autoage
= htmlautoagerange
;
1308 cfg
.oldest
= htmloldest
;
1309 cfg
.newest
= htmlnewest
;
1310 cfg
.showfiles
= showfiles
;
1311 html
= html_query(mappedfile
, xi
, &cfg
);
1312 fputs(html
, stdout
);
1315 munmap(mappedfile
, totalsize
);
1317 } else if (mode
== DUMP
) {
1321 fd
= open(filename
, O_RDONLY
);
1323 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1327 if (fstat(fd
, &st
) < 0) {
1328 perror(PNAME
": fstat");
1331 totalsize
= st
.st_size
;
1332 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1334 perror(PNAME
": mmap");
1337 pathsep
= trie_pathsep(mappedfile
);
1339 maxpathlen
= trie_maxpathlen(mappedfile
);
1340 buf
= snewn(maxpathlen
, char);
1342 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
1343 tw
= triewalk_new(mappedfile
);
1344 while ((tf
= triewalk_next(tw
, buf
)) != NULL
)
1348 munmap(mappedfile
, totalsize
);
1349 } else if (mode
== HTTPD
) {
1350 struct html_config pcfg
;
1351 struct httpd_config dcfg
;
1353 fd
= open(filename
, O_RDONLY
);
1355 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1359 if (fstat(fd
, &st
) < 0) {
1360 perror(PNAME
": fstat");
1363 totalsize
= st
.st_size
;
1364 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1366 perror(PNAME
": mmap");
1369 pathsep
= trie_pathsep(mappedfile
);
1371 dcfg
.address
= httpserveraddr
;
1372 dcfg
.port
= httpserverport
;
1373 dcfg
.basicauthdata
= httpauthdata
;
1375 pcfg
.autoage
= htmlautoagerange
;
1376 pcfg
.oldest
= htmloldest
;
1377 pcfg
.newest
= htmlnewest
;
1378 pcfg
.showfiles
= showfiles
;
1379 run_httpd(mappedfile
, auth
, &dcfg
, &pcfg
);
1380 munmap(mappedfile
, totalsize
);
1381 } else if (mode
== REMOVE
) {
1382 if (remove(filename
) < 0) {
1383 fprintf(stderr
, "%s: %s: remove: %s\n", PNAME
, filename
,