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 printf("%llu %llu ", tf
->size
, tf
->atime
);
60 for (p
= pathname
; *p
; p
++) {
61 if (*p
>= ' ' && *p
< 127 && *p
!= '%')
64 printf("%%%02x", (unsigned char)*p
);
69 static int gotdata(void *vctx
, const char *pathname
, const STRUCT_STAT
*st
)
71 struct ctx
*ctx
= (struct ctx
*)vctx
;
72 struct trie_file file
;
78 * Filter out our own data file.
80 if (st
->st_dev
== ctx
->datafile_dev
&& st
->st_ino
== ctx
->datafile_ino
)
84 * Don't cross the streams^W^Wany file system boundary.
86 if (!ctx
->crossfs
&& st
->st_dev
!= ctx
->filesystem_dev
)
89 file
.size
= (unsigned long long)512 * st
->st_blocks
;
90 if (ctx
->usemtime
|| (ctx
->fakeatimes
&& S_ISDIR(st
->st_mode
)))
91 file
.atime
= st
->st_mtime
;
93 file
.atime
= max(st
->st_mtime
, st
->st_atime
);
96 * Filter based on wildcards.
99 filename
= strrchr(pathname
, pathsep
);
104 for (i
= 0; i
< ctx
->ninex
; i
++) {
105 if (fnmatch(ctx
->inex
[i
].wildcard
,
106 ctx
->inex
[i
].path ? pathname
: filename
, 0) == 0)
107 include
= ctx
->inex
[i
].type
;
110 return 0; /* ignore this entry and any subdirs */
113 * Here we are supposed to be filtering an entry out, but
114 * still recursing into it if it's a directory. However,
115 * we can't actually leave out any directory whose
116 * subdirectories we then look at. So we cheat, in that
117 * case, by setting the size to zero.
119 if (!S_ISDIR(st
->st_mode
))
120 return 0; /* just ignore */
125 if (ctx
->straight_to_dump
)
126 dump_line(pathname
, &file
);
128 triebuild_add(ctx
->tb
, pathname
, &file
);
132 if (t
!= ctx
->last_output_update
) {
133 fprintf(stderr
, "%-*.*s\r", ctx
->progwidth
, ctx
->progwidth
,
136 ctx
->last_output_update
= t
;
143 static void scan_error(void *vctx
, const char *fmt
, ...)
145 struct ctx
*ctx
= (struct ctx
*)vctx
;
149 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
153 fprintf(stderr
, "%s: ", PNAME
);
155 vfprintf(stderr
, fmt
, ap
);
158 ctx
->last_output_update
--; /* force a progress report next time */
161 static void text_query(const void *mappedfile
, const char *querydir
,
162 time_t t
, int showfiles
, int depth
)
166 unsigned long xi1
, xi2
;
167 unsigned long long size
;
169 maxpathlen
= trie_maxpathlen(mappedfile
);
170 pathbuf
= snewn(maxpathlen
+ 1, char);
173 * We want to query everything between the supplied filename
174 * (inclusive) and that filename with a ^A on the end
175 * (exclusive). So find the x indices for each.
177 strcpy(pathbuf
, querydir
);
178 make_successor(pathbuf
);
179 xi1
= trie_before(mappedfile
, querydir
);
180 xi2
= trie_before(mappedfile
, pathbuf
);
182 if (!showfiles
&& xi2
- xi1
== 1)
183 return; /* file, or empty dir => no display */
186 * Now do the lookups in the age index.
188 if (xi2
- xi1
== 1) {
190 * We are querying an individual file, so we should not
191 * depend on the index entries either side of the node,
192 * since they almost certainly don't both exist. Instead,
193 * just look up the file's size and atime in the main trie.
195 const struct trie_file
*f
= trie_getfile(mappedfile
, xi1
);
201 unsigned long long s1
, s2
;
202 s1
= index_query(mappedfile
, xi1
, t
);
203 s2
= index_query(mappedfile
, xi2
, t
);
208 return; /* no space taken up => no display */
212 * Now scan for first-level subdirectories and report
217 trie_getpath(mappedfile
, xi1
, pathbuf
);
218 text_query(mappedfile
, pathbuf
, t
, showfiles
, depth
-1);
219 make_successor(pathbuf
);
220 xi1
= trie_before(mappedfile
, pathbuf
);
224 /* Display in units of 1Kb */
225 printf("%-11llu %s\n", (size
) / 1024, querydir
);
229 * Largely frivolous way to define all my command-line options. I
230 * present here a parametric macro which declares a series of
231 * _logical_ option identifiers, and for each one declares zero or
232 * more short option characters and zero or more long option
233 * words. Then I repeatedly invoke that macro with its arguments
234 * defined to be various other macros, which allows me to
237 * - define an enum allocating a distinct integer value to each
239 * - define a string consisting of precisely all the short option
241 * - define a string array consisting of all the long option
243 * - define (with help from auxiliary enums) integer arrays
244 * parallel to both of the above giving the logical option id
245 * for each physical short and long option
246 * - define an array indexed by logical option id indicating
247 * whether the option in question takes a value
248 * - define a function which prints out brief online help for all
251 * It's not at all clear to me that this trickery is actually
252 * particularly _efficient_ - it still, after all, requires going
253 * linearly through the option list at run time and doing a
254 * strcmp, whereas in an ideal world I'd have liked the lists of
255 * long and short options to be pre-sorted so that a binary search
256 * or some other more efficient lookup was possible. (Not that
257 * asymptotic algorithmic complexity is remotely vital in option
258 * parsing, but if I were doing this in, say, Lisp or something
259 * with an equivalently powerful preprocessor then once I'd had
260 * the idea of preparing the option-parsing data structures at
261 * compile time I would probably have made the effort to prepare
262 * them _properly_. I could have Perl generate me a source file
263 * from some sort of description, I suppose, but that would seem
264 * like overkill. And in any case, it's more of a challenge to
265 * achieve as much as possible by cunning use of cpp and enum than
266 * to just write some sensible and logical code in a Turing-
267 * complete language. I said it was largely frivolous :-)
269 * This approach does have the virtue that it brings together the
270 * option ids, option spellings and help text into a single
271 * combined list and defines them all in exactly one place. If I
272 * want to add a new option, or a new spelling for an option, I
273 * only have to modify the main OPTHELP macro below and then add
274 * code to process the new logical id.
276 * (Though, really, even that isn't ideal, since it still involves
277 * modifying the source file in more than one place. In a
278 * _properly_ ideal world, I'd be able to interleave the option
279 * definitions with the code fragments that process them. And then
280 * not bother defining logical identifiers for them at all - those
281 * would be automatically generated, since I wouldn't have any
282 * need to specify them manually in another part of the code.)
284 * One other helpful consequence of the enum-based structure here
285 * is that it causes a compiler error if I accidentally try to
286 * define the same option (short or long) twice.
289 #define OPTHELP(NOVAL, VAL, SHORT, LONG, HELPPFX, HELPARG, HELPLINE, HELPOPT) \
290 HELPPFX("usage") HELPLINE(PNAME " [options] action [action...]") \
292 VAL(SCAN) SHORT(s) LONG(scan) \
293 HELPARG("directory") HELPOPT("scan and index a directory") \
294 NOVAL(HTTPD) SHORT(w) LONG(web) LONG(server) LONG(httpd) \
295 HELPOPT("serve HTML reports from a temporary web server") \
296 VAL(TEXT) SHORT(t) LONG(text) \
297 HELPARG("subdir") HELPOPT("print a plain text report on a subdirectory") \
298 NOVAL(REMOVE) SHORT(R) LONG(remove) LONG(delete) LONG(unlink) \
299 HELPOPT("remove the index file") \
300 NOVAL(DUMP) SHORT(D) LONG(dump) HELPOPT("dump the index file on stdout") \
301 NOVAL(LOAD) SHORT(L) LONG(load) \
302 HELPOPT("load and index a dump file") \
303 VAL(SCANDUMP) SHORT(S) LONG(scan_dump) \
304 HELPARG("directory") HELPOPT("scan only, generating a dump") \
305 VAL(HTML) SHORT(H) LONG(html) \
306 HELPARG("subdir") HELPOPT("print an HTML report on a subdirectory") \
308 VAL(DATAFILE) SHORT(f) LONG(file) \
309 HELPARG("filename") HELPOPT("[most modes] specify index file") \
310 NOVAL(CROSSFS) LONG(cross_fs) \
311 HELPOPT("[--scan] cross filesystem boundaries") \
312 NOVAL(NOCROSSFS) LONG(no_cross_fs) \
313 HELPOPT("[--scan] stick to one filesystem") \
314 VAL(PRUNE) LONG(prune) \
315 HELPARG("wildcard") HELPOPT("[--scan] prune files matching pattern") \
316 VAL(PRUNEPATH) LONG(prune_path) \
317 HELPARG("wildcard") HELPOPT("[--scan] prune pathnames matching pattern") \
318 VAL(EXCLUDE) LONG(exclude) \
319 HELPARG("wildcard") HELPOPT("[--scan] exclude files matching pattern") \
320 VAL(EXCLUDEPATH) LONG(exclude_path) \
321 HELPARG("wildcard") HELPOPT("[--scan] exclude pathnames matching pattern") \
322 VAL(INCLUDE) LONG(include) \
323 HELPARG("wildcard") HELPOPT("[--scan] include files matching pattern") \
324 VAL(INCLUDEPATH) LONG(include_path) \
325 HELPARG("wildcard") HELPOPT("[--scan] include pathnames matching pattern") \
326 NOVAL(PROGRESS) LONG(progress) LONG(scan_progress) \
327 HELPOPT("[--scan] report progress on stderr") \
328 NOVAL(NOPROGRESS) LONG(no_progress) LONG(no_scan_progress) \
329 HELPOPT("[--scan] do not report progress") \
330 NOVAL(TTYPROGRESS) LONG(tty_progress) LONG(tty_scan_progress) \
331 LONG(progress_tty) LONG(scan_progress_tty) \
332 HELPOPT("[--scan] report progress if stderr is a tty") \
333 NOVAL(DIRATIME) LONG(dir_atime) LONG(dir_atimes) \
334 HELPOPT("[--scan,--load] keep real atimes on directories") \
335 NOVAL(NODIRATIME) LONG(no_dir_atime) LONG(no_dir_atimes) \
336 HELPOPT("[--scan,--load] fake atimes on directories") \
337 NOVAL(MTIME) LONG(mtime) \
338 HELPOPT("[--scan] use mtime instead of atime") \
339 NOVAL(SHOWFILES) LONG(files) \
340 HELPOPT("[--web,--html,--text] list individual files") \
341 VAL(AGERANGE) SHORT(r) LONG(age_range) LONG(range) LONG(ages) \
342 HELPARG("age[-age]") HELPOPT("[--web,--html] set limits of colour coding") \
343 VAL(SERVERADDR) LONG(address) LONG(addr) LONG(server_address) \
345 HELPARG("addr[:port]") HELPOPT("[--web] specify HTTP server address") \
346 VAL(AUTH) LONG(auth) LONG(http_auth) LONG(httpd_auth) \
347 LONG(server_auth) LONG(web_auth) \
348 HELPARG("type") HELPOPT("[--web] specify HTTP authentication method") \
349 VAL(AUTHFILE) LONG(auth_file) \
350 HELPARG("filename") HELPOPT("[--web] read HTTP Basic user/pass from file") \
351 VAL(AUTHFD) LONG(auth_fd) \
352 HELPARG("fd") HELPOPT("[--web] read HTTP Basic user/pass from fd") \
353 VAL(TQDEPTH) SHORT(d) LONG(depth) LONG(max_depth) LONG(maximum_depth) \
354 HELPARG("levels") HELPOPT("[--text] recurse to this many levels") \
355 VAL(MINAGE) SHORT(a) LONG(age) LONG(min_age) LONG(minimum_age) \
356 HELPARG("age") HELPOPT("[--text] include only files older than this") \
358 NOVAL(HELP) SHORT(h) LONG(help) HELPOPT("display this help text") \
359 NOVAL(VERSION) SHORT(V) LONG(version) HELPOPT("report version number") \
360 NOVAL(LICENCE) LONG(licence) LONG(license) \
361 HELPOPT("display (MIT) licence text") \
364 #define DEFENUM(x) OPT_ ## x,
367 #define STRING(x) #x ,
368 #define STRINGNOCOMMA(x) #x
369 #define SHORTNEWOPT(x) SHORTtmp_ ## x = OPT_ ## x,
370 #define SHORTTHISOPT(x) SHORTtmp2_ ## x, SHORTVAL_ ## x = SHORTtmp2_ ## x - 1,
371 #define SHORTOPTVAL(x) SHORTVAL_ ## x,
372 #define SHORTTMP(x) SHORTtmp3_ ## x,
373 #define LONGNEWOPT(x) LONGtmp_ ## x = OPT_ ## x,
374 #define LONGTHISOPT(x) LONGtmp2_ ## x, LONGVAL_ ## x = LONGtmp2_ ## x - 1,
375 #define LONGOPTVAL(x) LONGVAL_ ## x,
376 #define LONGTMP(x) SHORTtmp3_ ## x,
378 #define OPTIONS(NOVAL, VAL, SHORT, LONG) \
379 OPTHELP(NOVAL, VAL, SHORT, LONG, IGNORE, IGNORE, IGNORE, IGNORE)
381 enum { OPTIONS(DEFENUM
,DEFENUM
,IGNORE
,IGNORE
) NOPTIONS
};
382 enum { OPTIONS(IGNORE
,IGNORE
,SHORTTMP
,IGNORE
) NSHORTOPTS
};
383 enum { OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGTMP
) NLONGOPTS
};
384 static const int opthasval
[NOPTIONS
] = {OPTIONS(ZERO
,ONE
,IGNORE
,IGNORE
)};
385 static const char shortopts
[] = {OPTIONS(IGNORE
,IGNORE
,STRINGNOCOMMA
,IGNORE
)};
386 static const char *const longopts
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,STRING
)};
387 enum { OPTIONS(SHORTNEWOPT
,SHORTNEWOPT
,SHORTTHISOPT
,IGNORE
) };
388 enum { OPTIONS(LONGNEWOPT
,LONGNEWOPT
,IGNORE
,LONGTHISOPT
) };
389 static const int shortvals
[] = {OPTIONS(IGNORE
,IGNORE
,SHORTOPTVAL
,IGNORE
)};
390 static const int longvals
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGOPTVAL
)};
392 static void usage(FILE *fp
)
395 const char *prefix
, *shortopt
, *longopt
, *optarg
;
398 #define HELPRESET prefix = shortopt = longopt = optarg = NULL, optex = -1
399 #define HELPNOVAL(s) optex = 0;
400 #define HELPVAL(s) optex = 1;
401 #define HELPSHORT(s) if (!shortopt) shortopt = "-" #s;
402 #define HELPLONG(s) if (!longopt) { \
403 strcpy(longbuf, "--" #s); longopt = longbuf; \
404 for (i = 0; longbuf[i]; i++) if (longbuf[i] == '_') longbuf[i] = '-'; }
405 #define HELPPFX(s) prefix = s;
406 #define HELPARG(s) optarg = s;
407 #define HELPLINE(s) assert(optex == -1); \
408 fprintf(fp, "%7s%c %s\n", prefix?prefix:"", prefix?':':' ', s); \
410 #define HELPOPT(s) assert((optex == 1 && optarg) || (optex == 0 && !optarg)); \
411 assert(shortopt || longopt); \
412 i = fprintf(fp, "%7s%c %s%s%s%s%s", prefix?prefix:"", prefix?':':' ', \
413 shortopt?shortopt:"", shortopt&&longopt?", ":"", longopt?longopt:"", \
414 optarg?" ":"", optarg?optarg:""); \
415 fprintf(fp, "%*s %s\n", i<32?32-i:0,"",s); HELPRESET;
418 OPTHELP(HELPNOVAL
, HELPVAL
, HELPSHORT
, HELPLONG
,
419 HELPPFX
, HELPARG
, HELPLINE
, HELPOPT
);
432 static time_t parse_age(time_t now
, const char *agestr
)
441 if (2 != sscanf(agestr
, "%d%1[DdWwMmYy]", &nunits
, unit
)) {
442 fprintf(stderr
, "%s: age specification should be a number followed by"
443 " one of d,w,m,y\n", PNAME
);
447 if (unit
[0] == 'd') {
449 } else if (unit
[0] == 'w') {
450 t
-= 86400 * 7 * nunits
;
455 ym
= tm
.tm_year
* 12 + tm
.tm_mon
;
462 tm
.tm_year
= ym
/ 12;
471 int main(int argc
, char **argv
)
474 struct ctx actx
, *ctx
= &actx
;
476 off_t totalsize
, realsize
;
480 const struct trie_file
*tf
, *prevtf
;
481 char *filename
= PNAME
".dat";
483 enum { TEXT
, HTML
, SCAN
, DUMP
, SCANDUMP
, LOAD
, HTTPD
, REMOVE
};
488 int nactions
= 0, actionsize
= 0, action
;
489 time_t now
= time(NULL
);
490 time_t textcutoff
= now
, htmlnewest
= now
, htmloldest
= now
;
491 int htmlautoagerange
= 1;
492 const char *httpserveraddr
= NULL
;
493 int httpserverport
= 0;
494 const char *httpauthdata
= NULL
;
495 int auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
497 struct inclusion_exclusion
*inex
= NULL
;
498 int ninex
= 0, inexsize
= 0;
501 int fakediratimes
= 1;
505 #ifdef DEBUG_MAD_OPTION_PARSING_MACROS
507 static const char *const optnames
[NOPTIONS
] = {
508 OPTIONS(STRING
,STRING
,IGNORE
,IGNORE
)
511 for (i
= 0; i
< NSHORTOPTS
; i
++)
512 printf("-%c == %s [%s]\n", shortopts
[i
], optnames
[shortvals
[i
]],
513 opthasval
[shortvals
[i
]] ?
"value" : "no value");
514 for (i
= 0; i
< NLONGOPTS
; i
++)
515 printf("--%s == %s [%s]\n", longopts
[i
], optnames
[longvals
[i
]],
516 opthasval
[longvals
[i
]] ?
"value" : "no value");
523 if (doing_opts
&& *p
== '-') {
526 if (!strcmp(p
, "--")) {
537 if (wordstart
&& *p
== '-') {
539 * GNU-style long option.
542 optval
= strchr(p
, '=');
546 for (i
= 0; i
< NLONGOPTS
; i
++) {
547 const char *opt
= longopts
[i
], *s
= p
;
550 * The underscores in the option names
551 * defined above may be given by the user
552 * as underscores or dashes, or omitted
557 if (*s
== '-' || *s
== '_')
575 fprintf(stderr
, "%s: unrecognised option '--%s'\n",
580 if (!opthasval
[optid
]) {
582 fprintf(stderr
, "%s: unexpected argument to option"
583 " '--%s'\n", PNAME
, p
);
591 fprintf(stderr
, "%s: option '--%s' expects"
592 " an argument\n", PNAME
, p
);
598 p
+= strlen(p
); /* finished with this argument word */
605 for (i
= 0; i
< NSHORTOPTS
; i
++)
606 if (c
== shortopts
[i
]) {
607 optid
= shortvals
[i
];
612 fprintf(stderr
, "%s: unrecognised option '-%c'\n",
617 if (opthasval
[optid
]) {
621 } else if (--argc
> 0) {
624 fprintf(stderr
, "%s: option '-%c' expects"
625 " an argument\n", PNAME
, c
);
636 * Now actually process the option.
643 #ifdef PACKAGE_VERSION
644 printf("%s, revision %s\n", PNAME
, PACKAGE_VERSION
);
646 printf("%s: version number not available when not built"
647 " via automake\n", PNAME
);
652 extern const char *const licence
[];
655 for (i
= 0; licence
[i
]; i
++)
656 fputs(licence
[i
], stdout
);
662 if (nactions
>= actionsize
) {
663 actionsize
= nactions
* 3 / 2 + 16;
664 actions
= sresize(actions
, actionsize
, struct action
);
666 actions
[nactions
].mode
= SCAN
;
667 actions
[nactions
].arg
= optval
;
671 if (nactions
>= actionsize
) {
672 actionsize
= nactions
* 3 / 2 + 16;
673 actions
= sresize(actions
, actionsize
, struct action
);
675 actions
[nactions
].mode
= SCANDUMP
;
676 actions
[nactions
].arg
= optval
;
680 if (nactions
>= actionsize
) {
681 actionsize
= nactions
* 3 / 2 + 16;
682 actions
= sresize(actions
, actionsize
, struct action
);
684 actions
[nactions
].mode
= DUMP
;
685 actions
[nactions
].arg
= NULL
;
689 if (nactions
>= actionsize
) {
690 actionsize
= nactions
* 3 / 2 + 16;
691 actions
= sresize(actions
, actionsize
, struct action
);
693 actions
[nactions
].mode
= LOAD
;
694 actions
[nactions
].arg
= NULL
;
698 if (nactions
>= actionsize
) {
699 actionsize
= nactions
* 3 / 2 + 16;
700 actions
= sresize(actions
, actionsize
, struct action
);
702 actions
[nactions
].mode
= TEXT
;
703 actions
[nactions
].arg
= optval
;
707 if (nactions
>= actionsize
) {
708 actionsize
= nactions
* 3 / 2 + 16;
709 actions
= sresize(actions
, actionsize
, struct action
);
711 actions
[nactions
].mode
= HTML
;
712 actions
[nactions
].arg
= optval
;
716 if (nactions
>= actionsize
) {
717 actionsize
= nactions
* 3 / 2 + 16;
718 actions
= sresize(actions
, actionsize
, struct action
);
720 actions
[nactions
].mode
= HTTPD
;
721 actions
[nactions
].arg
= NULL
;
725 if (nactions
>= actionsize
) {
726 actionsize
= nactions
* 3 / 2 + 16;
727 actions
= sresize(actions
, actionsize
, struct action
);
729 actions
[nactions
].mode
= REMOVE
;
730 actions
[nactions
].arg
= NULL
;
739 case OPT_TTYPROGRESS
:
764 tqdepth
= atoi(optval
);
767 textcutoff
= parse_age(now
, optval
);
770 if (!strcmp(optval
, "auto")) {
771 htmlautoagerange
= 1;
773 char *q
= optval
+ strcspn(optval
, "-:");
776 htmloldest
= parse_age(now
, optval
);
777 htmlnewest
= *q ?
parse_age(now
, q
) : now
;
778 htmlautoagerange
= 0;
784 if (optval
[0] == '[' &&
785 (port
= strchr(optval
, ']')) != NULL
)
789 port
+= strcspn(port
, ":");
792 httpserveraddr
= optval
;
793 httpserverport
= atoi(port
);
797 if (!strcmp(optval
, "magic"))
798 auth
= HTTPD_AUTH_MAGIC
;
799 else if (!strcmp(optval
, "basic"))
800 auth
= HTTPD_AUTH_BASIC
;
801 else if (!strcmp(optval
, "none"))
802 auth
= HTTPD_AUTH_NONE
;
803 else if (!strcmp(optval
, "default"))
804 auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
805 else if (!strcmp(optval
, "help") ||
806 !strcmp(optval
, "list")) {
807 printf(PNAME
": supported HTTP authentication types"
809 " magic use Linux /proc/net/tcp to"
810 " determine owner of peer socket\n"
811 " basic HTTP Basic username and"
812 " password authentication\n"
813 " default use 'magic' if possible, "
814 " otherwise fall back to 'basic'\n"
815 " none unauthenticated HTTP (if"
816 " the data file is non-confidential)\n");
819 fprintf(stderr
, "%s: unrecognised authentication"
820 " type '%s'\n%*s options are 'magic',"
821 " 'basic', 'none', 'default'\n",
822 PNAME
, optval
, (int)strlen(PNAME
), "");
833 int authlen
, authsize
;
836 if (optid
== OPT_AUTHFILE
) {
837 fd
= open(optval
, O_RDONLY
);
839 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
,
840 optval
, strerror(errno
));
847 sprintf(namebuf
, "fd %d", fd
);
852 authbuf
= snewn(authsize
, char);
853 while ((ret
= read(fd
, authbuf
+authlen
,
854 authsize
-authlen
)) > 0) {
856 if ((authsize
- authlen
) < (authsize
/ 16)) {
857 authsize
= authlen
* 3 / 2 + 4096;
858 authbuf
= sresize(authbuf
, authsize
, char);
862 fprintf(stderr
, "%s: %s: read: %s\n", PNAME
,
863 name
, strerror(errno
));
866 if (optid
== OPT_AUTHFILE
)
868 httpauthdata
= authbuf
;
872 case OPT_INCLUDEPATH
:
874 case OPT_EXCLUDEPATH
:
877 if (ninex
>= inexsize
) {
878 inexsize
= ninex
* 3 / 2 + 16;
879 inex
= sresize(inex
, inexsize
,
880 struct inclusion_exclusion
);
882 inex
[ninex
].path
= (optid
== OPT_INCLUDEPATH
||
883 optid
== OPT_EXCLUDEPATH
||
884 optid
== OPT_PRUNEPATH
);
885 inex
[ninex
].type
= (optid
== OPT_INCLUDE ?
1 :
886 optid
== OPT_INCLUDEPATH ?
1 :
887 optid
== OPT_EXCLUDE ?
0 :
888 optid
== OPT_EXCLUDEPATH ?
0 :
889 optid
== OPT_PRUNE ?
-1 :
890 /* optid == OPT_PRUNEPATH ? */ -1);
891 inex
[ninex
].wildcard
= optval
;
897 fprintf(stderr
, "%s: unexpected argument '%s'\n", PNAME
, p
);
907 for (action
= 0; action
< nactions
; action
++) {
908 int mode
= actions
[action
].mode
;
910 if (mode
== SCAN
|| mode
== SCANDUMP
|| mode
== LOAD
) {
911 const char *scandir
= actions
[action
].arg
;
914 char *buf
= fgetline(stdin
);
916 buf
[strcspn(buf
, "\r\n")] = '\0';
917 if (1 != sscanf(buf
, DUMPHDR
"%x",
919 fprintf(stderr
, "%s: header in dump file not recognised\n",
923 pathsep
= (char)newpathsep
;
927 if (mode
== SCAN
|| mode
== LOAD
) {
929 * Prepare to write out the index file.
931 fd
= open(filename
, O_RDWR
| O_TRUNC
| O_CREAT
,
934 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
938 if (fstat(fd
, &st
) < 0) {
939 perror(PNAME
": fstat");
942 ctx
->datafile_dev
= st
.st_dev
;
943 ctx
->datafile_ino
= st
.st_ino
;
944 ctx
->straight_to_dump
= 0;
946 ctx
->datafile_dev
= -1;
947 ctx
->datafile_ino
= -1;
948 ctx
->straight_to_dump
= 1;
951 if (mode
== SCAN
|| mode
== SCANDUMP
) {
952 if (stat(scandir
, &st
) < 0) {
953 fprintf(stderr
, "%s: %s: stat: %s\n", PNAME
, scandir
,
957 ctx
->filesystem_dev
= crossfs ?
0 : st
.st_dev
;
962 ctx
->crossfs
= crossfs
;
963 ctx
->fakeatimes
= fakediratimes
;
964 ctx
->usemtime
= mtime
;
966 ctx
->last_output_update
= time(NULL
);
968 /* progress==1 means report progress only if stderr is a tty */
970 progress
= isatty(2) ?
2 : 0;
971 ctx
->progress
= progress
;
975 ioctl(2, TIOCGWINSZ
, &ws
) == 0 &&
977 ctx
->progwidth
= ws
.ws_col
- 1;
982 if (mode
== SCANDUMP
)
983 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
986 * Scan the directory tree, and write out the trie component
989 if (mode
!= SCANDUMP
) {
990 ctx
->tb
= triebuild_new(fd
);
995 while ((buf
= fgetline(stdin
)) != NULL
) {
999 buf
[strcspn(buf
, "\r\n")] = '\0';
1003 while (*p
&& *p
!= ' ') p
++;
1005 fprintf(stderr
, "%s: dump file line %d: expected at least"
1006 " three fields\n", PNAME
, line
);
1010 tf
.size
= strtoull(q
, NULL
, 10);
1012 while (*p
&& *p
!= ' ') p
++;
1014 fprintf(stderr
, "%s: dump file line %d: expected at least"
1015 " three fields\n", PNAME
, line
);
1019 tf
.atime
= strtoull(q
, NULL
, 10);
1027 for (i
= 0; i
< 2; i
++) {
1029 if (*p
>= '0' && *p
<= '9')
1031 else if (*p
>= 'A' && *p
<= 'F')
1032 c
+= *p
- ('A' - 10);
1033 else if (*p
>= 'a' && *p
<= 'f')
1034 c
+= *p
- ('a' - 10);
1036 fprintf(stderr
, "%s: dump file line %d: unable"
1037 " to parse hex escape\n", PNAME
, line
);
1046 triebuild_add(ctx
->tb
, buf
, &tf
);
1051 du(scandir
, gotdata
, scan_error
, ctx
);
1053 if (mode
!= SCANDUMP
) {
1056 char *buf
, *prevbuf
;
1058 count
= triebuild_finish(ctx
->tb
);
1059 triebuild_free(ctx
->tb
);
1061 if (ctx
->progress
) {
1062 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
1067 * Work out how much space the cumulative index trees
1068 * will take; enlarge the file, and memory-map it.
1070 if (fstat(fd
, &st
) < 0) {
1071 perror(PNAME
": fstat");
1075 printf("Built pathname index, %d entries,"
1076 " %llu bytes of index\n", count
,
1077 (unsigned long long)st
.st_size
);
1079 totalsize
= index_initial_size(st
.st_size
, count
);
1080 totalsize
+= totalsize
/ 10;
1082 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1083 perror(PNAME
": lseek");
1086 if (write(fd
, "\0", 1) < 1) {
1087 perror(PNAME
": write");
1091 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1093 perror(PNAME
": mmap");
1097 if (fakediratimes
) {
1098 printf("Faking directory atimes\n");
1099 trie_fake_dir_atimes(mappedfile
);
1102 printf("Building index\n");
1103 ib
= indexbuild_new(mappedfile
, st
.st_size
, count
, &delta
);
1104 maxpathlen
= trie_maxpathlen(mappedfile
);
1105 buf
= snewn(maxpathlen
, char);
1106 prevbuf
= snewn(maxpathlen
, char);
1107 tw
= triewalk_new(mappedfile
);
1109 tf
= triewalk_next(tw
, buf
);
1114 if (totalsize
- indexbuild_realsize(ib
) < delta
) {
1115 const void *oldfile
= mappedfile
;
1119 * Unmap the file, grow it, and remap it.
1121 munmap(mappedfile
, totalsize
);
1124 totalsize
+= totalsize
/ 10;
1126 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1127 perror(PNAME
": lseek");
1130 if (write(fd
, "\0", 1) < 1) {
1131 perror(PNAME
": write");
1135 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1137 perror(PNAME
": mmap");
1141 indexbuild_rebase(ib
, mappedfile
);
1142 triewalk_rebase(tw
, mappedfile
);
1143 diff
= (const unsigned char *)mappedfile
-
1144 (const unsigned char *)oldfile
;
1146 prevtf
= (const struct trie_file
*)
1147 (((const unsigned char *)prevtf
) + diff
);
1149 tf
= (const struct trie_file
*)
1150 (((const unsigned char *)tf
) + diff
);
1154 * Get the next file from the index. So we are
1155 * currently holding, and have not yet
1156 * indexed, prevtf (with pathname prevbuf) and
1157 * tf (with pathname buf).
1160 memcpy(prevbuf
, buf
, maxpathlen
);
1161 tf
= triewalk_next(tw
, buf
);
1167 * Find the first differing character position
1168 * between our two pathnames.
1170 for (i
= 0; prevbuf
[i
] && prevbuf
[i
] == buf
[i
]; i
++);
1173 * If prevbuf was a directory name and buf is
1174 * something inside that directory, then
1175 * trie_before() will be called on prevbuf
1176 * itself. Hence we must drop a tag before it,
1177 * so that the resulting index is usable.
1179 if ((!prevbuf
[i
] && (buf
[i
] == pathsep
||
1180 (i
> 0 && buf
[i
-1] == pathsep
))))
1184 * Add prevtf to the index.
1186 indexbuild_add(ib
, prevtf
);
1190 * Drop an unconditional final tag, and
1191 * get out of this loop.
1198 * If prevbuf was a filename inside some
1199 * directory which buf is outside, then
1200 * trie_before() will be called on some
1201 * pathname either equal to buf or epsilon
1202 * less than it. Either way, we're going to
1203 * need to drop a tag after prevtf.
1205 if (strchr(prevbuf
+i
, pathsep
) || !tf
)
1210 realsize
= indexbuild_realsize(ib
);
1211 indexbuild_free(ib
);
1213 munmap(mappedfile
, totalsize
);
1214 ftruncate(fd
, realsize
);
1216 printf("Final index file size = %llu bytes\n",
1217 (unsigned long long)realsize
);
1219 } else if (mode
== TEXT
) {
1220 char *querydir
= actions
[action
].arg
;
1223 fd
= open(filename
, O_RDONLY
);
1225 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1229 if (fstat(fd
, &st
) < 0) {
1230 perror(PNAME
": fstat");
1233 totalsize
= st
.st_size
;
1234 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1236 perror(PNAME
": mmap");
1239 pathsep
= trie_pathsep(mappedfile
);
1242 * Trim trailing slash, just in case.
1244 pathlen
= strlen(querydir
);
1245 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1246 querydir
[--pathlen
] = '\0';
1248 text_query(mappedfile
, querydir
, textcutoff
, showfiles
, tqdepth
);
1250 munmap(mappedfile
, totalsize
);
1251 } else if (mode
== HTML
) {
1252 char *querydir
= actions
[action
].arg
;
1253 size_t pathlen
, maxpathlen
;
1255 struct html_config cfg
;
1259 fd
= open(filename
, O_RDONLY
);
1261 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1265 if (fstat(fd
, &st
) < 0) {
1266 perror(PNAME
": fstat");
1269 totalsize
= st
.st_size
;
1270 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1272 perror(PNAME
": mmap");
1275 pathsep
= trie_pathsep(mappedfile
);
1277 maxpathlen
= trie_maxpathlen(mappedfile
);
1278 pathbuf
= snewn(maxpathlen
, char);
1281 * Trim trailing slash, just in case.
1283 pathlen
= strlen(querydir
);
1284 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1285 querydir
[--pathlen
] = '\0';
1287 xi
= trie_before(mappedfile
, querydir
);
1288 if (xi
>= trie_count(mappedfile
) ||
1289 (trie_getpath(mappedfile
, xi
, pathbuf
),
1290 strcmp(pathbuf
, querydir
))) {
1291 fprintf(stderr
, "%s: pathname '%s' does not exist in index\n"
1292 "%*s(check it is spelled exactly as it is in the "
1293 "index, including\n%*sany leading './')\n",
1295 (int)(1+sizeof(PNAME
)), "",
1296 (int)(1+sizeof(PNAME
)), "");
1297 } else if (!index_has_root(mappedfile
, xi
)) {
1298 fprintf(stderr
, "%s: pathname '%s' is"
1299 " a file, not a directory\n", PNAME
, querydir
);
1302 cfg
.autoage
= htmlautoagerange
;
1303 cfg
.oldest
= htmloldest
;
1304 cfg
.newest
= htmlnewest
;
1305 cfg
.showfiles
= showfiles
;
1306 html
= html_query(mappedfile
, xi
, &cfg
);
1307 fputs(html
, stdout
);
1310 munmap(mappedfile
, totalsize
);
1312 } else if (mode
== DUMP
) {
1316 fd
= open(filename
, O_RDONLY
);
1318 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1322 if (fstat(fd
, &st
) < 0) {
1323 perror(PNAME
": fstat");
1326 totalsize
= st
.st_size
;
1327 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1329 perror(PNAME
": mmap");
1332 pathsep
= trie_pathsep(mappedfile
);
1334 maxpathlen
= trie_maxpathlen(mappedfile
);
1335 buf
= snewn(maxpathlen
, char);
1337 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
1338 tw
= triewalk_new(mappedfile
);
1339 while ((tf
= triewalk_next(tw
, buf
)) != NULL
)
1343 munmap(mappedfile
, totalsize
);
1344 } else if (mode
== HTTPD
) {
1345 struct html_config pcfg
;
1346 struct httpd_config dcfg
;
1348 fd
= open(filename
, O_RDONLY
);
1350 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1354 if (fstat(fd
, &st
) < 0) {
1355 perror(PNAME
": fstat");
1358 totalsize
= st
.st_size
;
1359 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1361 perror(PNAME
": mmap");
1364 pathsep
= trie_pathsep(mappedfile
);
1366 dcfg
.address
= httpserveraddr
;
1367 dcfg
.port
= httpserverport
;
1368 dcfg
.basicauthdata
= httpauthdata
;
1370 pcfg
.autoage
= htmlautoagerange
;
1371 pcfg
.oldest
= htmloldest
;
1372 pcfg
.newest
= htmlnewest
;
1373 pcfg
.showfiles
= showfiles
;
1374 run_httpd(mappedfile
, auth
, &dcfg
, &pcfg
);
1375 munmap(mappedfile
, totalsize
);
1376 } else if (mode
== REMOVE
) {
1377 if (remove(filename
) < 0) {
1378 fprintf(stderr
, "%s: %s: remove: %s\n", PNAME
, filename
,