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
= 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
,
166 unsigned long xi1
, xi2
;
167 unsigned long long s1
, s2
;
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
);
183 return; /* file, or empty dir => no display */
186 * Now do the lookups in the age index.
188 s1
= index_query(mappedfile
, xi1
, t
);
189 s2
= index_query(mappedfile
, xi2
, t
);
192 return; /* no space taken up => no display */
196 * Now scan for first-level subdirectories and report
201 trie_getpath(mappedfile
, xi1
, pathbuf
);
202 text_query(mappedfile
, pathbuf
, t
, depth
-1);
203 make_successor(pathbuf
);
204 xi1
= trie_before(mappedfile
, pathbuf
);
208 /* Display in units of 1Kb */
209 printf("%-11llu %s\n", (s2
- s1
) / 1024, querydir
);
213 * Largely frivolous way to define all my command-line options. I
214 * present here a parametric macro which declares a series of
215 * _logical_ option identifiers, and for each one declares zero or
216 * more short option characters and zero or more long option
217 * words. Then I repeatedly invoke that macro with its arguments
218 * defined to be various other macros, which allows me to
221 * - define an enum allocating a distinct integer value to each
223 * - define a string consisting of precisely all the short option
225 * - define a string array consisting of all the long option
227 * - define (with help from auxiliary enums) integer arrays
228 * parallel to both of the above giving the logical option id
229 * for each physical short and long option
230 * - define an array indexed by logical option id indicating
231 * whether the option in question takes a value
232 * - define a function which prints out brief online help for all
235 * It's not at all clear to me that this trickery is actually
236 * particularly _efficient_ - it still, after all, requires going
237 * linearly through the option list at run time and doing a
238 * strcmp, whereas in an ideal world I'd have liked the lists of
239 * long and short options to be pre-sorted so that a binary search
240 * or some other more efficient lookup was possible. (Not that
241 * asymptotic algorithmic complexity is remotely vital in option
242 * parsing, but if I were doing this in, say, Lisp or something
243 * with an equivalently powerful preprocessor then once I'd had
244 * the idea of preparing the option-parsing data structures at
245 * compile time I would probably have made the effort to prepare
246 * them _properly_. I could have Perl generate me a source file
247 * from some sort of description, I suppose, but that would seem
248 * like overkill. And in any case, it's more of a challenge to
249 * achieve as much as possible by cunning use of cpp and enum than
250 * to just write some sensible and logical code in a Turing-
251 * complete language. I said it was largely frivolous :-)
253 * This approach does have the virtue that it brings together the
254 * option ids, option spellings and help text into a single
255 * combined list and defines them all in exactly one place. If I
256 * want to add a new option, or a new spelling for an option, I
257 * only have to modify the main OPTHELP macro below and then add
258 * code to process the new logical id.
260 * (Though, really, even that isn't ideal, since it still involves
261 * modifying the source file in more than one place. In a
262 * _properly_ ideal world, I'd be able to interleave the option
263 * definitions with the code fragments that process them. And then
264 * not bother defining logical identifiers for them at all - those
265 * would be automatically generated, since I wouldn't have any
266 * need to specify them manually in another part of the code.)
268 * One other helpful consequence of the enum-based structure here
269 * is that it causes a compiler error if I accidentally try to
270 * define the same option (short or long) twice.
273 #define OPTHELP(NOVAL, VAL, SHORT, LONG, HELPPFX, HELPARG, HELPLINE, HELPOPT) \
274 HELPPFX("usage") HELPLINE(PNAME " [options] action [action...]") \
276 VAL(SCAN) SHORT(s) LONG(scan) \
277 HELPARG("directory") HELPOPT("scan and index a directory") \
278 NOVAL(HTTPD) SHORT(w) LONG(web) LONG(server) LONG(httpd) \
279 HELPOPT("serve HTML reports from a temporary web server") \
280 VAL(TEXT) SHORT(t) LONG(text) \
281 HELPARG("subdir") HELPOPT("print a plain text report on a subdirectory") \
282 NOVAL(REMOVE) SHORT(R) LONG(remove) LONG(delete) LONG(unlink) \
283 HELPOPT("remove the index file") \
284 NOVAL(DUMP) SHORT(D) LONG(dump) HELPOPT("dump the index file on stdout") \
285 NOVAL(LOAD) SHORT(L) LONG(load) \
286 HELPOPT("load and index a dump file") \
287 VAL(SCANDUMP) SHORT(S) LONG(scan_dump) \
288 HELPARG("directory") HELPOPT("scan only, generating a dump") \
289 VAL(HTML) SHORT(H) LONG(html) \
290 HELPARG("subdir") HELPOPT("print an HTML report on a subdirectory") \
292 VAL(DATAFILE) SHORT(f) LONG(file) \
293 HELPARG("filename") HELPOPT("[most modes] specify index file") \
294 NOVAL(CROSSFS) LONG(cross_fs) \
295 HELPOPT("[--scan] cross filesystem boundaries") \
296 NOVAL(NOCROSSFS) LONG(no_cross_fs) \
297 HELPOPT("[--scan] stick to one filesystem") \
298 VAL(PRUNE) LONG(prune) \
299 HELPARG("wildcard") HELPOPT("[--scan] prune files matching pattern") \
300 VAL(PRUNEPATH) LONG(prune_path) \
301 HELPARG("wildcard") HELPOPT("[--scan] prune pathnames matching pattern") \
302 VAL(EXCLUDE) LONG(exclude) \
303 HELPARG("wildcard") HELPOPT("[--scan] exclude files matching pattern") \
304 VAL(EXCLUDEPATH) LONG(exclude_path) \
305 HELPARG("wildcard") HELPOPT("[--scan] exclude pathnames matching pattern") \
306 VAL(INCLUDE) LONG(include) \
307 HELPARG("wildcard") HELPOPT("[--scan] include files matching pattern") \
308 VAL(INCLUDEPATH) LONG(include_path) \
309 HELPARG("wildcard") HELPOPT("[--scan] include pathnames matching pattern") \
310 NOVAL(PROGRESS) LONG(progress) LONG(scan_progress) \
311 HELPOPT("[--scan] report progress on stderr") \
312 NOVAL(NOPROGRESS) LONG(no_progress) LONG(no_scan_progress) \
313 HELPOPT("[--scan] do not report progress") \
314 NOVAL(TTYPROGRESS) LONG(tty_progress) LONG(tty_scan_progress) \
315 LONG(progress_tty) LONG(scan_progress_tty) \
316 HELPOPT("[--scan] report progress if stderr is a tty") \
317 NOVAL(DIRATIME) LONG(dir_atime) LONG(dir_atimes) \
318 HELPOPT("[--scan,--load] keep real atimes on directories") \
319 NOVAL(NODIRATIME) LONG(no_dir_atime) LONG(no_dir_atimes) \
320 HELPOPT("[--scan,--load] fake atimes on directories") \
321 NOVAL(MTIME) LONG(mtime) \
322 HELPOPT("[--scan] use mtime instead of atime") \
323 VAL(AGERANGE) SHORT(r) LONG(age_range) LONG(range) LONG(ages) \
324 HELPARG("age[-age]") HELPOPT("[--web,--html] set limits of colour coding") \
325 VAL(SERVERADDR) LONG(address) LONG(addr) LONG(server_address) \
327 HELPARG("addr[:port]") HELPOPT("[--web] specify HTTP server address") \
328 VAL(AUTH) LONG(auth) LONG(http_auth) LONG(httpd_auth) \
329 LONG(server_auth) LONG(web_auth) \
330 HELPARG("type") HELPOPT("[--web] specify HTTP authentication method") \
331 VAL(AUTHFILE) LONG(auth_file) \
332 HELPARG("filename") HELPOPT("[--web] read HTTP Basic user/pass from file") \
333 VAL(AUTHFD) LONG(auth_fd) \
334 HELPARG("fd") HELPOPT("[--web] read HTTP Basic user/pass from fd") \
335 VAL(TQDEPTH) SHORT(d) LONG(depth) LONG(max_depth) LONG(maximum_depth) \
336 HELPARG("levels") HELPOPT("[--text] recurse to this many levels") \
337 VAL(MINAGE) SHORT(a) LONG(age) LONG(min_age) LONG(minimum_age) \
338 HELPARG("age") HELPOPT("[--text] include only files older than this") \
340 NOVAL(HELP) SHORT(h) LONG(help) HELPOPT("display this help text") \
341 NOVAL(VERSION) SHORT(V) LONG(version) HELPOPT("report version number") \
342 NOVAL(LICENCE) LONG(licence) LONG(license) \
343 HELPOPT("display (MIT) licence text") \
346 #define DEFENUM(x) OPT_ ## x,
349 #define STRING(x) #x ,
350 #define STRINGNOCOMMA(x) #x
351 #define SHORTNEWOPT(x) SHORTtmp_ ## x = OPT_ ## x,
352 #define SHORTTHISOPT(x) SHORTtmp2_ ## x, SHORTVAL_ ## x = SHORTtmp2_ ## x - 1,
353 #define SHORTOPTVAL(x) SHORTVAL_ ## x,
354 #define SHORTTMP(x) SHORTtmp3_ ## x,
355 #define LONGNEWOPT(x) LONGtmp_ ## x = OPT_ ## x,
356 #define LONGTHISOPT(x) LONGtmp2_ ## x, LONGVAL_ ## x = LONGtmp2_ ## x - 1,
357 #define LONGOPTVAL(x) LONGVAL_ ## x,
358 #define LONGTMP(x) SHORTtmp3_ ## x,
360 #define OPTIONS(NOVAL, VAL, SHORT, LONG) \
361 OPTHELP(NOVAL, VAL, SHORT, LONG, IGNORE, IGNORE, IGNORE, IGNORE)
363 enum { OPTIONS(DEFENUM
,DEFENUM
,IGNORE
,IGNORE
) NOPTIONS
};
364 enum { OPTIONS(IGNORE
,IGNORE
,SHORTTMP
,IGNORE
) NSHORTOPTS
};
365 enum { OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGTMP
) NLONGOPTS
};
366 static const int opthasval
[NOPTIONS
] = {OPTIONS(ZERO
,ONE
,IGNORE
,IGNORE
)};
367 static const char shortopts
[] = {OPTIONS(IGNORE
,IGNORE
,STRINGNOCOMMA
,IGNORE
)};
368 static const char *const longopts
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,STRING
)};
369 enum { OPTIONS(SHORTNEWOPT
,SHORTNEWOPT
,SHORTTHISOPT
,IGNORE
) };
370 enum { OPTIONS(LONGNEWOPT
,LONGNEWOPT
,IGNORE
,LONGTHISOPT
) };
371 static const int shortvals
[] = {OPTIONS(IGNORE
,IGNORE
,SHORTOPTVAL
,IGNORE
)};
372 static const int longvals
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGOPTVAL
)};
374 static void usage(FILE *fp
)
377 const char *prefix
, *shortopt
, *longopt
, *optarg
;
380 #define HELPRESET prefix = shortopt = longopt = optarg = NULL, optex = -1
381 #define HELPNOVAL(s) optex = 0;
382 #define HELPVAL(s) optex = 1;
383 #define HELPSHORT(s) if (!shortopt) shortopt = "-" #s;
384 #define HELPLONG(s) if (!longopt) { \
385 strcpy(longbuf, "--" #s); longopt = longbuf; \
386 for (i = 0; longbuf[i]; i++) if (longbuf[i] == '_') longbuf[i] = '-'; }
387 #define HELPPFX(s) prefix = s;
388 #define HELPARG(s) optarg = s;
389 #define HELPLINE(s) assert(optex == -1); \
390 fprintf(fp, "%7s%c %s\n", prefix?prefix:"", prefix?':':' ', s); \
392 #define HELPOPT(s) assert((optex == 1 && optarg) || (optex == 0 && !optarg)); \
393 assert(shortopt || longopt); \
394 i = fprintf(fp, "%7s%c %s%s%s%s%s", prefix?prefix:"", prefix?':':' ', \
395 shortopt?shortopt:"", shortopt&&longopt?", ":"", longopt?longopt:"", \
396 optarg?" ":"", optarg?optarg:""); \
397 fprintf(fp, "%*s %s\n", i<32?32-i:0,"",s); HELPRESET;
400 OPTHELP(HELPNOVAL
, HELPVAL
, HELPSHORT
, HELPLONG
,
401 HELPPFX
, HELPARG
, HELPLINE
, HELPOPT
);
414 static time_t parse_age(time_t now
, const char *agestr
)
423 if (2 != sscanf(agestr
, "%d%1[DdWwMmYy]", &nunits
, unit
)) {
424 fprintf(stderr
, "%s: age specification should be a number followed by"
425 " one of d,w,m,y\n", PNAME
);
429 if (unit
[0] == 'd') {
431 } else if (unit
[0] == 'w') {
432 t
-= 86400 * 7 * nunits
;
437 ym
= tm
.tm_year
* 12 + tm
.tm_mon
;
444 tm
.tm_year
= ym
/ 12;
453 int main(int argc
, char **argv
)
456 struct ctx actx
, *ctx
= &actx
;
458 off_t totalsize
, realsize
;
462 const struct trie_file
*tf
, *prevtf
;
463 char *filename
= PNAME
".dat";
465 enum { TEXT
, HTML
, SCAN
, DUMP
, SCANDUMP
, LOAD
, HTTPD
, REMOVE
};
470 int nactions
= 0, actionsize
= 0, action
;
471 time_t now
= time(NULL
);
472 time_t textcutoff
= now
, htmlnewest
= now
, htmloldest
= now
;
473 int htmlautoagerange
= 1;
474 const char *httpserveraddr
= NULL
;
475 int httpserverport
= 0;
476 const char *httpauthdata
= NULL
;
477 int auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
479 struct inclusion_exclusion
*inex
= NULL
;
480 int ninex
= 0, inexsize
= 0;
483 int fakediratimes
= 1;
486 #ifdef DEBUG_MAD_OPTION_PARSING_MACROS
488 static const char *const optnames
[NOPTIONS
] = {
489 OPTIONS(STRING
,STRING
,IGNORE
,IGNORE
)
492 for (i
= 0; i
< NSHORTOPTS
; i
++)
493 printf("-%c == %s [%s]\n", shortopts
[i
], optnames
[shortvals
[i
]],
494 opthasval
[shortvals
[i
]] ?
"value" : "no value");
495 for (i
= 0; i
< NLONGOPTS
; i
++)
496 printf("--%s == %s [%s]\n", longopts
[i
], optnames
[longvals
[i
]],
497 opthasval
[longvals
[i
]] ?
"value" : "no value");
504 if (doing_opts
&& *p
== '-') {
507 if (!strcmp(p
, "--")) {
518 if (wordstart
&& *p
== '-') {
520 * GNU-style long option.
523 optval
= strchr(p
, '=');
527 for (i
= 0; i
< NLONGOPTS
; i
++) {
528 const char *opt
= longopts
[i
], *s
= p
;
531 * The underscores in the option names
532 * defined above may be given by the user
533 * as underscores or dashes, or omitted
538 if (*s
== '-' || *s
== '_')
556 fprintf(stderr
, "%s: unrecognised option '--%s'\n",
561 if (!opthasval
[optid
]) {
563 fprintf(stderr
, "%s: unexpected argument to option"
564 " '--%s'\n", PNAME
, p
);
572 fprintf(stderr
, "%s: option '--%s' expects"
573 " an argument\n", PNAME
, p
);
579 p
+= strlen(p
); /* finished with this argument word */
586 for (i
= 0; i
< NSHORTOPTS
; i
++)
587 if (c
== shortopts
[i
]) {
588 optid
= shortvals
[i
];
593 fprintf(stderr
, "%s: unrecognised option '-%c'\n",
598 if (opthasval
[optid
]) {
602 } else if (--argc
> 0) {
605 fprintf(stderr
, "%s: option '-%c' expects"
606 " an argument\n", PNAME
, c
);
617 * Now actually process the option.
624 #ifdef PACKAGE_VERSION
625 printf("%s, revision %s\n", PNAME
, PACKAGE_VERSION
);
627 printf("%s: version number not available when not built"
628 " via automake\n", PNAME
);
633 extern const char *const licence
[];
636 for (i
= 0; licence
[i
]; i
++)
637 fputs(licence
[i
], stdout
);
643 if (nactions
>= actionsize
) {
644 actionsize
= nactions
* 3 / 2 + 16;
645 actions
= sresize(actions
, actionsize
, struct action
);
647 actions
[nactions
].mode
= SCAN
;
648 actions
[nactions
].arg
= optval
;
652 if (nactions
>= actionsize
) {
653 actionsize
= nactions
* 3 / 2 + 16;
654 actions
= sresize(actions
, actionsize
, struct action
);
656 actions
[nactions
].mode
= SCANDUMP
;
657 actions
[nactions
].arg
= optval
;
661 if (nactions
>= actionsize
) {
662 actionsize
= nactions
* 3 / 2 + 16;
663 actions
= sresize(actions
, actionsize
, struct action
);
665 actions
[nactions
].mode
= DUMP
;
666 actions
[nactions
].arg
= NULL
;
670 if (nactions
>= actionsize
) {
671 actionsize
= nactions
* 3 / 2 + 16;
672 actions
= sresize(actions
, actionsize
, struct action
);
674 actions
[nactions
].mode
= LOAD
;
675 actions
[nactions
].arg
= NULL
;
679 if (nactions
>= actionsize
) {
680 actionsize
= nactions
* 3 / 2 + 16;
681 actions
= sresize(actions
, actionsize
, struct action
);
683 actions
[nactions
].mode
= TEXT
;
684 actions
[nactions
].arg
= optval
;
688 if (nactions
>= actionsize
) {
689 actionsize
= nactions
* 3 / 2 + 16;
690 actions
= sresize(actions
, actionsize
, struct action
);
692 actions
[nactions
].mode
= HTML
;
693 actions
[nactions
].arg
= optval
;
697 if (nactions
>= actionsize
) {
698 actionsize
= nactions
* 3 / 2 + 16;
699 actions
= sresize(actions
, actionsize
, struct action
);
701 actions
[nactions
].mode
= HTTPD
;
702 actions
[nactions
].arg
= NULL
;
706 if (nactions
>= actionsize
) {
707 actionsize
= nactions
* 3 / 2 + 16;
708 actions
= sresize(actions
, actionsize
, struct action
);
710 actions
[nactions
].mode
= REMOVE
;
711 actions
[nactions
].arg
= NULL
;
720 case OPT_TTYPROGRESS
:
742 tqdepth
= atoi(optval
);
745 textcutoff
= parse_age(now
, optval
);
748 if (!strcmp(optval
, "auto")) {
749 htmlautoagerange
= 1;
751 char *q
= optval
+ strcspn(optval
, "-:");
754 htmloldest
= parse_age(now
, optval
);
755 htmlnewest
= *q ?
parse_age(now
, q
) : now
;
756 htmlautoagerange
= 0;
762 if (optval
[0] == '[' &&
763 (port
= strchr(optval
, ']')) != NULL
)
767 port
+= strcspn(port
, ":");
770 httpserveraddr
= optval
;
771 httpserverport
= atoi(port
);
775 if (!strcmp(optval
, "magic"))
776 auth
= HTTPD_AUTH_MAGIC
;
777 else if (!strcmp(optval
, "basic"))
778 auth
= HTTPD_AUTH_BASIC
;
779 else if (!strcmp(optval
, "none"))
780 auth
= HTTPD_AUTH_NONE
;
781 else if (!strcmp(optval
, "default"))
782 auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
783 else if (!strcmp(optval
, "help") ||
784 !strcmp(optval
, "list")) {
785 printf(PNAME
": supported HTTP authentication types"
787 " magic use Linux /proc/net/tcp to"
788 " determine owner of peer socket\n"
789 " basic HTTP Basic username and"
790 " password authentication\n"
791 " default use 'magic' if possible, "
792 " otherwise fall back to 'basic'\n"
793 " none unauthenticated HTTP (if"
794 " the data file is non-confidential)\n");
797 fprintf(stderr
, "%s: unrecognised authentication"
798 " type '%s'\n%*s options are 'magic',"
799 " 'basic', 'none', 'default'\n",
800 PNAME
, optval
, (int)strlen(PNAME
), "");
811 int authlen
, authsize
;
814 if (optid
== OPT_AUTHFILE
) {
815 fd
= open(optval
, O_RDONLY
);
817 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
,
818 optval
, strerror(errno
));
825 sprintf(namebuf
, "fd %d", fd
);
830 authbuf
= snewn(authsize
, char);
831 while ((ret
= read(fd
, authbuf
+authlen
,
832 authsize
-authlen
)) > 0) {
834 if ((authsize
- authlen
) < (authsize
/ 16)) {
835 authsize
= authlen
* 3 / 2 + 4096;
836 authbuf
= sresize(authbuf
, authsize
, char);
840 fprintf(stderr
, "%s: %s: read: %s\n", PNAME
,
841 name
, strerror(errno
));
844 if (optid
== OPT_AUTHFILE
)
846 httpauthdata
= authbuf
;
850 case OPT_INCLUDEPATH
:
852 case OPT_EXCLUDEPATH
:
855 if (ninex
>= inexsize
) {
856 inexsize
= ninex
* 3 / 2 + 16;
857 inex
= sresize(inex
, inexsize
,
858 struct inclusion_exclusion
);
860 inex
[ninex
].path
= (optid
== OPT_INCLUDEPATH
||
861 optid
== OPT_EXCLUDEPATH
||
862 optid
== OPT_PRUNEPATH
);
863 inex
[ninex
].type
= (optid
== OPT_INCLUDE ?
1 :
864 optid
== OPT_INCLUDEPATH ?
1 :
865 optid
== OPT_EXCLUDE ?
0 :
866 optid
== OPT_EXCLUDEPATH ?
0 :
867 optid
== OPT_PRUNE ?
-1 :
868 /* optid == OPT_PRUNEPATH ? */ -1);
869 inex
[ninex
].wildcard
= optval
;
875 fprintf(stderr
, "%s: unexpected argument '%s'\n", PNAME
, p
);
885 for (action
= 0; action
< nactions
; action
++) {
886 int mode
= actions
[action
].mode
;
888 if (mode
== SCAN
|| mode
== SCANDUMP
|| mode
== LOAD
) {
889 const char *scandir
= actions
[action
].arg
;
892 char *buf
= fgetline(stdin
);
894 buf
[strcspn(buf
, "\r\n")] = '\0';
895 if (1 != sscanf(buf
, DUMPHDR
"%x",
897 fprintf(stderr
, "%s: header in dump file not recognised\n",
901 pathsep
= (char)newpathsep
;
905 if (mode
== SCAN
|| mode
== LOAD
) {
907 * Prepare to write out the index file.
909 fd
= open(filename
, O_RDWR
| O_TRUNC
| O_CREAT
,
912 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
916 if (fstat(fd
, &st
) < 0) {
917 perror(PNAME
": fstat");
920 ctx
->datafile_dev
= st
.st_dev
;
921 ctx
->datafile_ino
= st
.st_ino
;
922 ctx
->straight_to_dump
= 0;
924 ctx
->datafile_dev
= -1;
925 ctx
->datafile_ino
= -1;
926 ctx
->straight_to_dump
= 1;
929 if (mode
== SCAN
|| mode
== SCANDUMP
) {
930 if (stat(scandir
, &st
) < 0) {
931 fprintf(stderr
, "%s: %s: stat: %s\n", PNAME
, scandir
,
935 ctx
->filesystem_dev
= crossfs ?
0 : st
.st_dev
;
940 ctx
->crossfs
= crossfs
;
941 ctx
->fakeatimes
= fakediratimes
;
942 ctx
->usemtime
= mtime
;
944 ctx
->last_output_update
= time(NULL
);
946 /* progress==1 means report progress only if stderr is a tty */
948 progress
= isatty(2) ?
2 : 0;
949 ctx
->progress
= progress
;
952 if (progress
&& ioctl(2, TIOCGWINSZ
, &ws
) == 0)
953 ctx
->progwidth
= ws
.ws_col
- 1;
958 if (mode
== SCANDUMP
)
959 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
962 * Scan the directory tree, and write out the trie component
965 if (mode
!= SCANDUMP
) {
966 ctx
->tb
= triebuild_new(fd
);
971 while ((buf
= fgetline(stdin
)) != NULL
) {
975 buf
[strcspn(buf
, "\r\n")] = '\0';
979 while (*p
&& *p
!= ' ') p
++;
981 fprintf(stderr
, "%s: dump file line %d: expected at least"
982 " three fields\n", PNAME
, line
);
986 tf
.size
= strtoull(q
, NULL
, 10);
988 while (*p
&& *p
!= ' ') p
++;
990 fprintf(stderr
, "%s: dump file line %d: expected at least"
991 " three fields\n", PNAME
, line
);
995 tf
.atime
= strtoull(q
, NULL
, 10);
1003 for (i
= 0; i
< 2; i
++) {
1005 if (*p
>= '0' && *p
<= '9')
1007 else if (*p
>= 'A' && *p
<= 'F')
1008 c
+= *p
- ('A' - 10);
1009 else if (*p
>= 'a' && *p
<= 'f')
1010 c
+= *p
- ('a' - 10);
1012 fprintf(stderr
, "%s: dump file line %d: unable"
1013 " to parse hex escape\n", PNAME
, line
);
1022 triebuild_add(ctx
->tb
, buf
, &tf
);
1027 du(scandir
, gotdata
, scan_error
, ctx
);
1029 if (mode
!= SCANDUMP
) {
1032 char *buf
, *prevbuf
;
1034 count
= triebuild_finish(ctx
->tb
);
1035 triebuild_free(ctx
->tb
);
1037 if (ctx
->progress
) {
1038 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
1043 * Work out how much space the cumulative index trees
1044 * will take; enlarge the file, and memory-map it.
1046 if (fstat(fd
, &st
) < 0) {
1047 perror(PNAME
": fstat");
1051 printf("Built pathname index, %d entries,"
1052 " %llu bytes of index\n", count
,
1053 (unsigned long long)st
.st_size
);
1055 totalsize
= index_initial_size(st
.st_size
, count
);
1056 totalsize
+= totalsize
/ 10;
1058 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1059 perror(PNAME
": lseek");
1062 if (write(fd
, "\0", 1) < 1) {
1063 perror(PNAME
": write");
1067 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1069 perror(PNAME
": mmap");
1073 if (fakediratimes
) {
1074 printf("Faking directory atimes\n");
1075 trie_fake_dir_atimes(mappedfile
);
1078 printf("Building index\n");
1079 ib
= indexbuild_new(mappedfile
, st
.st_size
, count
, &delta
);
1080 maxpathlen
= trie_maxpathlen(mappedfile
);
1081 buf
= snewn(maxpathlen
, char);
1082 prevbuf
= snewn(maxpathlen
, char);
1083 tw
= triewalk_new(mappedfile
);
1085 tf
= triewalk_next(tw
, buf
);
1090 if (totalsize
- indexbuild_realsize(ib
) < delta
) {
1092 * Unmap the file, grow it, and remap it.
1094 munmap(mappedfile
, totalsize
);
1097 totalsize
+= totalsize
/ 10;
1099 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1100 perror(PNAME
": lseek");
1103 if (write(fd
, "\0", 1) < 1) {
1104 perror(PNAME
": write");
1108 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1110 perror(PNAME
": mmap");
1114 indexbuild_rebase(ib
, mappedfile
);
1115 triewalk_rebase(tw
, mappedfile
);
1119 * Get the next file from the index. So we are
1120 * currently holding, and have not yet
1121 * indexed, prevtf (with pathname prevbuf) and
1122 * tf (with pathname buf).
1125 memcpy(prevbuf
, buf
, maxpathlen
);
1126 tf
= triewalk_next(tw
, buf
);
1132 * Find the first differing character position
1133 * between our two pathnames.
1135 for (i
= 0; prevbuf
[i
] && prevbuf
[i
] == buf
[i
]; i
++);
1138 * If prevbuf was a directory name and buf is
1139 * something inside that directory, then
1140 * trie_before() will be called on prevbuf
1141 * itself. Hence we must drop a tag before it,
1142 * so that the resulting index is usable.
1144 if ((!prevbuf
[i
] && (buf
[i
] == pathsep
||
1145 (i
> 0 && buf
[i
-1] == pathsep
))))
1149 * Add prevtf to the index.
1151 indexbuild_add(ib
, prevtf
);
1155 * Drop an unconditional final tag, and
1156 * get out of this loop.
1163 * If prevbuf was a filename inside some
1164 * directory which buf is outside, then
1165 * trie_before() will be called on some
1166 * pathname either equal to buf or epsilon
1167 * less than it. Either way, we're going to
1168 * need to drop a tag after prevtf.
1170 if (strchr(prevbuf
+i
, pathsep
) || !tf
)
1175 realsize
= indexbuild_realsize(ib
);
1176 indexbuild_free(ib
);
1178 munmap(mappedfile
, totalsize
);
1179 ftruncate(fd
, realsize
);
1181 printf("Final index file size = %llu bytes\n",
1182 (unsigned long long)realsize
);
1184 } else if (mode
== TEXT
) {
1185 char *querydir
= actions
[action
].arg
;
1188 fd
= open(filename
, O_RDONLY
);
1190 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1194 if (fstat(fd
, &st
) < 0) {
1195 perror(PNAME
": fstat");
1198 totalsize
= st
.st_size
;
1199 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1201 perror(PNAME
": mmap");
1204 pathsep
= trie_pathsep(mappedfile
);
1207 * Trim trailing slash, just in case.
1209 pathlen
= strlen(querydir
);
1210 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1211 querydir
[--pathlen
] = '\0';
1213 text_query(mappedfile
, querydir
, textcutoff
, tqdepth
);
1215 munmap(mappedfile
, totalsize
);
1216 } else if (mode
== HTML
) {
1217 char *querydir
= actions
[action
].arg
;
1219 struct html_config cfg
;
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 xi
= trie_before(mappedfile
, querydir
);
1250 cfg
.autoage
= htmlautoagerange
;
1251 cfg
.oldest
= htmloldest
;
1252 cfg
.newest
= htmlnewest
;
1253 html
= html_query(mappedfile
, xi
, &cfg
);
1254 fputs(html
, stdout
);
1256 munmap(mappedfile
, totalsize
);
1257 } else if (mode
== DUMP
) {
1261 fd
= open(filename
, O_RDONLY
);
1263 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1267 if (fstat(fd
, &st
) < 0) {
1268 perror(PNAME
": fstat");
1271 totalsize
= st
.st_size
;
1272 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1274 perror(PNAME
": mmap");
1277 pathsep
= trie_pathsep(mappedfile
);
1279 maxpathlen
= trie_maxpathlen(mappedfile
);
1280 buf
= snewn(maxpathlen
, char);
1282 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
1283 tw
= triewalk_new(mappedfile
);
1284 while ((tf
= triewalk_next(tw
, buf
)) != NULL
)
1288 munmap(mappedfile
, totalsize
);
1289 } else if (mode
== HTTPD
) {
1290 struct html_config pcfg
;
1291 struct httpd_config dcfg
;
1293 fd
= open(filename
, O_RDONLY
);
1295 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1299 if (fstat(fd
, &st
) < 0) {
1300 perror(PNAME
": fstat");
1303 totalsize
= st
.st_size
;
1304 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1306 perror(PNAME
": mmap");
1309 pathsep
= trie_pathsep(mappedfile
);
1311 dcfg
.address
= httpserveraddr
;
1312 dcfg
.port
= httpserverport
;
1313 dcfg
.basicauthdata
= httpauthdata
;
1315 pcfg
.autoage
= htmlautoagerange
;
1316 pcfg
.oldest
= htmloldest
;
1317 pcfg
.newest
= htmlnewest
;
1318 run_httpd(mappedfile
, auth
, &dcfg
, &pcfg
);
1319 munmap(mappedfile
, totalsize
);
1320 } else if (mode
== REMOVE
) {
1321 if (remove(filename
) < 0) {
1322 fprintf(stderr
, "%s: %s: remove: %s\n", PNAME
, filename
,