2 * Main program for agedu.
16 #include <sys/types.h>
20 #include <sys/ioctl.h>
33 * Path separator. This global variable affects the behaviour of
34 * various parts of the code when they need to deal with path
35 * separators. The path separator appropriate to a particular data
36 * set is encoded in the index file storing that data set; data
37 * sets generated on Unix will of course have the default '/', but
38 * foreign data sets are conceivable and must be handled correctly.
42 void fatal(const char *fmt
, ...)
45 fprintf(stderr
, "%s: ", PNAME
);
47 vfprintf(stderr
, fmt
, ap
);
49 fprintf(stderr
, "\n");
53 struct inclusion_exclusion
{
61 dev_t datafile_dev
, filesystem_dev
;
63 time_t last_output_update
;
64 int progress
, progwidth
;
66 struct inclusion_exclusion
*inex
;
71 static void dump_line(const char *pathname
, const struct trie_file
*tf
)
74 printf("%llu %llu ", tf
->size
, tf
->atime
);
75 for (p
= pathname
; *p
; p
++) {
76 if (*p
>= ' ' && *p
< 127 && *p
!= '%')
79 printf("%%%02x", (unsigned char)*p
);
84 static int gotdata(void *vctx
, const char *pathname
, const struct stat64
*st
)
86 struct ctx
*ctx
= (struct ctx
*)vctx
;
87 struct trie_file file
;
93 * Filter out our own data file.
95 if (st
->st_dev
== ctx
->datafile_dev
&& st
->st_ino
== ctx
->datafile_ino
)
99 * Don't cross the streams^W^Wany file system boundary.
101 if (!ctx
->crossfs
&& st
->st_dev
!= ctx
->filesystem_dev
)
104 file
.size
= (unsigned long long)512 * st
->st_blocks
;
105 file
.atime
= st
->st_atime
;
108 * Filter based on wildcards.
111 filename
= strrchr(pathname
, pathsep
);
116 for (i
= 0; i
< ctx
->ninex
; i
++) {
117 if (fnmatch(ctx
->inex
[i
].wildcard
,
118 ctx
->inex
[i
].path ? pathname
: filename
, 0) == 0)
119 include
= ctx
->inex
[i
].type
;
122 return 0; /* ignore this entry and any subdirs */
125 * Here we are supposed to be filtering an entry out, but
126 * still recursing into it if it's a directory. However,
127 * we can't actually leave out any directory whose
128 * subdirectories we then look at. So we cheat, in that
129 * case, by setting the size to zero.
131 if (!S_ISDIR(st
->st_mode
))
132 return 0; /* just ignore */
137 if (ctx
->straight_to_dump
)
138 dump_line(pathname
, &file
);
140 triebuild_add(ctx
->tb
, pathname
, &file
);
144 if (t
!= ctx
->last_output_update
) {
145 fprintf(stderr
, "%-*.*s\r", ctx
->progwidth
, ctx
->progwidth
,
148 ctx
->last_output_update
= t
;
155 static void text_query(const void *mappedfile
, const char *querydir
,
160 unsigned long xi1
, xi2
;
161 unsigned long long s1
, s2
;
163 maxpathlen
= trie_maxpathlen(mappedfile
);
164 pathbuf
= snewn(maxpathlen
+ 1, char);
167 * We want to query everything between the supplied filename
168 * (inclusive) and that filename with a ^A on the end
169 * (exclusive). So find the x indices for each.
171 strcpy(pathbuf
, querydir
);
172 make_successor(pathbuf
);
173 xi1
= trie_before(mappedfile
, querydir
);
174 xi2
= trie_before(mappedfile
, pathbuf
);
177 * Now do the lookups in the age index.
179 s1
= index_query(mappedfile
, xi1
, t
);
180 s2
= index_query(mappedfile
, xi2
, t
);
183 return; /* file, or empty dir => no display */
186 return; /* no space taken up => no display */
190 * Now scan for first-level subdirectories and report
195 trie_getpath(mappedfile
, xi1
, pathbuf
);
196 text_query(mappedfile
, pathbuf
, t
, depth
-1);
197 make_successor(pathbuf
);
198 xi1
= trie_before(mappedfile
, pathbuf
);
202 /* Display in units of 1Kb */
203 printf("%-11llu %s\n", (s2
- s1
) / 1024, querydir
);
207 * Largely frivolous way to define all my command-line options. I
208 * present here a parametric macro which declares a series of
209 * _logical_ option identifiers, and for each one declares zero or
210 * more short option characters and zero or more long option
211 * words. Then I repeatedly invoke that macro with its arguments
212 * defined to be various other macros, which allows me to
215 * - define an enum allocating a distinct integer value to each
217 * - define a string consisting of precisely all the short option
219 * - define a string array consisting of all the long option
221 * - define (with help from auxiliary enums) integer arrays
222 * parallel to both of the above giving the logical option id
223 * for each physical short and long option
224 * - define an array indexed by logical option id indicating
225 * whether the option in question takes a value
226 * - define a function which prints out brief online help for all
229 * It's not at all clear to me that this trickery is actually
230 * particularly _efficient_ - it still, after all, requires going
231 * linearly through the option list at run time and doing a
232 * strcmp, whereas in an ideal world I'd have liked the lists of
233 * long and short options to be pre-sorted so that a binary search
234 * or some other more efficient lookup was possible. (Not that
235 * asymptotic algorithmic complexity is remotely vital in option
236 * parsing, but if I were doing this in, say, Lisp or something
237 * with an equivalently powerful preprocessor then once I'd had
238 * the idea of preparing the option-parsing data structures at
239 * compile time I would probably have made the effort to prepare
240 * them _properly_. I could have Perl generate me a source file
241 * from some sort of description, I suppose, but that would seem
242 * like overkill. And in any case, it's more of a challenge to
243 * achieve as much as possible by cunning use of cpp and enum than
244 * to just write some sensible and logical code in a Turing-
245 * complete language. I said it was largely frivolous :-)
247 * This approach does have the virtue that it brings together the
248 * option ids, option spellings and help text into a single
249 * combined list and defines them all in exactly one place. If I
250 * want to add a new option, or a new spelling for an option, I
251 * only have to modify the main OPTHELP macro below and then add
252 * code to process the new logical id.
254 * (Though, really, even that isn't ideal, since it still involves
255 * modifying the source file in more than one place. In a
256 * _properly_ ideal world, I'd be able to interleave the option
257 * definitions with the code fragments that process them. And then
258 * not bother defining logical identifiers for them at all - those
259 * would be automatically generated, since I wouldn't have any
260 * need to specify them manually in another part of the code.)
263 #define OPTHELP(NOVAL, VAL, SHORT, LONG, HELPPFX, HELPARG, HELPLINE, HELPOPT) \
264 HELPPFX("usage") HELPLINE(PNAME " [options] action [action...]") \
266 VAL(SCAN) SHORT(s) LONG(scan) \
267 HELPARG("directory") HELPOPT("scan and index a directory") \
268 NOVAL(DUMP) SHORT(d) LONG(dump) HELPOPT("dump the index file on stdout") \
269 VAL(SCANDUMP) SHORT(S) LONG(scan_dump) \
270 HELPARG("directory") HELPOPT("scan only, generating a dump") \
271 NOVAL(LOAD) SHORT(l) LONG(load) \
272 HELPOPT("load and index a dump file") \
273 VAL(TEXT) SHORT(t) LONG(text) \
274 HELPARG("subdir") HELPOPT("print a plain text report on a subdirectory") \
275 VAL(HTML) SHORT(H) LONG(html) \
276 HELPARG("subdir") HELPOPT("print an HTML report on a subdirectory") \
277 NOVAL(HTTPD) SHORT(w) LONG(web) LONG(server) LONG(httpd) \
278 HELPOPT("serve HTML reports from a temporary web server") \
280 VAL(DATAFILE) SHORT(f) LONG(file) \
281 HELPARG("filename") HELPOPT("[all modes] specify index file") \
282 NOVAL(PROGRESS) LONG(progress) LONG(scan_progress) \
283 HELPOPT("[--scan] report progress on stderr") \
284 NOVAL(NOPROGRESS) LONG(no_progress) LONG(no_scan_progress) \
285 HELPOPT("[--scan] do not report progress") \
286 NOVAL(TTYPROGRESS) LONG(tty_progress) LONG(tty_scan_progress) \
287 LONG(progress_tty) LONG(scan_progress_tty) \
288 HELPOPT("[--scan] report progress if stderr is a tty") \
289 NOVAL(CROSSFS) LONG(cross_fs) \
290 HELPOPT("[--scan] cross filesystem boundaries") \
291 NOVAL(NOCROSSFS) LONG(no_cross_fs) \
292 HELPOPT("[--scan] stick to one filesystem") \
293 VAL(INCLUDE) LONG(include) \
294 HELPARG("wildcard") HELPOPT("[--scan] include files matching pattern") \
295 VAL(INCLUDEPATH) LONG(include_path) \
296 HELPARG("wildcard") HELPOPT("[--scan] include pathnames matching pattern") \
297 VAL(EXCLUDE) LONG(exclude) \
298 HELPARG("wildcard") HELPOPT("[--scan] exclude files matching pattern") \
299 VAL(EXCLUDEPATH) LONG(exclude_path) \
300 HELPARG("wildcard") HELPOPT("[--scan] exclude pathnames matching pattern") \
301 VAL(PRUNE) LONG(prune) \
302 HELPARG("wildcard") HELPOPT("[--scan] prune files matching pattern") \
303 VAL(PRUNEPATH) LONG(prune_path) \
304 HELPARG("wildcard") HELPOPT("[--scan] prune pathnames matching pattern") \
305 VAL(TQDEPTH) LONG(depth) LONG(max_depth) LONG(maximum_depth) \
306 HELPARG("levels") HELPOPT("[--text] recurse to this many levels") \
307 VAL(MINAGE) SHORT(a) LONG(age) LONG(min_age) LONG(minimum_age) \
308 HELPARG("age") HELPOPT("[--text] include only files older than this") \
309 VAL(AGERANGE) SHORT(r) LONG(age_range) LONG(range) LONG(ages) \
310 HELPARG("age[-age]") HELPOPT("[--html,--web] set limits of colour coding") \
311 VAL(SERVERADDR) LONG(address) LONG(addr) LONG(server_address) \
313 HELPARG("addr[:port]") HELPOPT("[--web] specify HTTP server address") \
314 VAL(AUTH) LONG(auth) LONG(http_auth) LONG(httpd_auth) \
315 LONG(server_auth) LONG(web_auth) \
316 HELPARG("type") HELPOPT("[--web] specify HTTP authentication method") \
317 VAL(AUTHFILE) LONG(auth_file) \
318 HELPARG("filename") HELPOPT("[--web] read HTTP Basic user/pass from file") \
319 VAL(AUTHFD) LONG(auth_fd) \
320 HELPARG("fd") HELPOPT("[--web] read HTTP Basic user/pass from fd") \
322 NOVAL(HELP) SHORT(h) LONG(help) HELPOPT("display this help text") \
323 NOVAL(VERSION) SHORT(V) LONG(version) HELPOPT("report version number") \
324 NOVAL(LICENCE) LONG(licence) LONG(license) \
325 HELPOPT("display (MIT) licence text") \
328 #define DEFENUM(x) OPT_ ## x,
331 #define STRING(x) #x ,
332 #define STRINGNOCOMMA(x) #x
333 #define SHORTNEWOPT(x) SHORTtmp_ ## x = OPT_ ## x,
334 #define SHORTTHISOPT(x) SHORTtmp2_ ## x, SHORTVAL_ ## x = SHORTtmp2_ ## x - 1,
335 #define SHORTOPTVAL(x) SHORTVAL_ ## x,
336 #define SHORTTMP(x) SHORTtmp3_ ## x,
337 #define LONGNEWOPT(x) LONGtmp_ ## x = OPT_ ## x,
338 #define LONGTHISOPT(x) LONGtmp2_ ## x, LONGVAL_ ## x = LONGtmp2_ ## x - 1,
339 #define LONGOPTVAL(x) LONGVAL_ ## x,
340 #define LONGTMP(x) SHORTtmp3_ ## x,
342 #define OPTIONS(NOVAL, VAL, SHORT, LONG) \
343 OPTHELP(NOVAL, VAL, SHORT, LONG, IGNORE, IGNORE, IGNORE, IGNORE)
345 enum { OPTIONS(DEFENUM
,DEFENUM
,IGNORE
,IGNORE
) NOPTIONS
};
346 enum { OPTIONS(IGNORE
,IGNORE
,SHORTTMP
,IGNORE
) NSHORTOPTS
};
347 enum { OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGTMP
) NLONGOPTS
};
348 static const int opthasval
[NOPTIONS
] = {OPTIONS(ZERO
,ONE
,IGNORE
,IGNORE
)};
349 static const char shortopts
[] = {OPTIONS(IGNORE
,IGNORE
,STRINGNOCOMMA
,IGNORE
)};
350 static const char *const longopts
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,STRING
)};
351 enum { OPTIONS(SHORTNEWOPT
,SHORTNEWOPT
,SHORTTHISOPT
,IGNORE
) };
352 enum { OPTIONS(LONGNEWOPT
,LONGNEWOPT
,IGNORE
,LONGTHISOPT
) };
353 static const int shortvals
[] = {OPTIONS(IGNORE
,IGNORE
,SHORTOPTVAL
,IGNORE
)};
354 static const int longvals
[] = {OPTIONS(IGNORE
,IGNORE
,IGNORE
,LONGOPTVAL
)};
356 static void usage(FILE *fp
)
359 const char *prefix
, *shortopt
, *longopt
, *optarg
;
362 #define HELPRESET prefix = shortopt = longopt = optarg = NULL, optex = -1
363 #define HELPNOVAL(s) optex = 0;
364 #define HELPVAL(s) optex = 1;
365 #define HELPSHORT(s) if (!shortopt) shortopt = "-" #s;
366 #define HELPLONG(s) if (!longopt) { \
367 strcpy(longbuf, "--" #s); longopt = longbuf; \
368 for (i = 0; longbuf[i]; i++) if (longbuf[i] == '_') longbuf[i] = '-'; }
369 #define HELPPFX(s) prefix = s;
370 #define HELPARG(s) optarg = s;
371 #define HELPLINE(s) assert(optex == -1); \
372 fprintf(fp, "%7s%c %s\n", prefix?prefix:"", prefix?':':' ', s); \
374 #define HELPOPT(s) assert((optex == 1 && optarg) || (optex == 0 && !optarg)); \
375 assert(shortopt || longopt); \
376 i = fprintf(fp, "%7s%c %s%s%s%s%s", prefix?prefix:"", prefix?':':' ', \
377 shortopt?shortopt:"", shortopt&&longopt?", ":"", longopt?longopt:"", \
378 optarg?" ":"", optarg?optarg:""); \
379 fprintf(fp, "%*s %s\n", i<32?32-i:0,"",s); HELPRESET;
382 OPTHELP(HELPNOVAL
, HELPVAL
, HELPSHORT
, HELPLONG
,
383 HELPPFX
, HELPARG
, HELPLINE
, HELPOPT
);
396 static time_t parse_age(time_t now
, const char *agestr
)
405 if (2 != sscanf(agestr
, "%d%1[DdWwMmYy]", &nunits
, unit
)) {
406 fprintf(stderr
, "%s: age specification should be a number followed by"
407 " one of d,w,m,y\n", PNAME
);
411 if (unit
[0] == 'd') {
413 } else if (unit
[0] == 'w') {
414 t
-= 86400 * 7 * nunits
;
419 ym
= tm
.tm_year
* 12 + tm
.tm_mon
;
426 tm
.tm_year
= ym
/ 12;
435 int main(int argc
, char **argv
)
438 struct ctx actx
, *ctx
= &actx
;
440 off_t totalsize
, realsize
;
444 const struct trie_file
*tf
;
445 char *filename
= PNAME
".dat";
447 enum { TEXT
, HTML
, SCAN
, DUMP
, SCANDUMP
, LOAD
, HTTPD
};
452 int nactions
= 0, actionsize
= 0, action
;
453 time_t now
= time(NULL
);
454 time_t textcutoff
= now
, htmlnewest
= now
, htmloldest
= now
;
455 int htmlautoagerange
= 1;
456 const char *httpserveraddr
= NULL
;
457 int httpserverport
= 0;
458 const char *httpauthdata
= NULL
;
459 int auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
461 struct inclusion_exclusion
*inex
= NULL
;
462 int ninex
= 0, inexsize
= 0;
466 #ifdef DEBUG_MAD_OPTION_PARSING_MACROS
468 static const char *const optnames
[NOPTIONS
] = {
469 OPTIONS(STRING
,STRING
,IGNORE
,IGNORE
)
472 for (i
= 0; i
< NSHORTOPTS
; i
++)
473 printf("-%c == %s [%s]\n", shortopts
[i
], optnames
[shortvals
[i
]],
474 opthasval
[shortvals
[i
]] ?
"value" : "no value");
475 for (i
= 0; i
< NLONGOPTS
; i
++)
476 printf("--%s == %s [%s]\n", longopts
[i
], optnames
[longvals
[i
]],
477 opthasval
[longvals
[i
]] ?
"value" : "no value");
484 if (doing_opts
&& *p
== '-') {
487 if (!strcmp(p
, "--")) {
498 if (wordstart
&& *p
== '-') {
500 * GNU-style long option.
503 optval
= strchr(p
, '=');
507 for (i
= 0; i
< NLONGOPTS
; i
++) {
508 const char *opt
= longopts
[i
], *s
= p
;
511 * The underscores in the option names
512 * defined above may be given by the user
513 * as underscores or dashes, or omitted
518 if (*s
== '-' || *s
== '_')
536 fprintf(stderr
, "%s: unrecognised option '--%s'\n",
541 if (!opthasval
[optid
]) {
543 fprintf(stderr
, "%s: unexpected argument to option"
544 " '--%s'\n", PNAME
, p
);
552 fprintf(stderr
, "%s: option '--%s' expects"
553 " an argument\n", PNAME
, p
);
559 p
+= strlen(p
); /* finished with this argument word */
566 for (i
= 0; i
< NSHORTOPTS
; i
++)
567 if (c
== shortopts
[i
]) {
568 optid
= shortvals
[i
];
573 fprintf(stderr
, "%s: unrecognised option '-%c'\n",
578 if (opthasval
[optid
]) {
582 } else if (--argc
> 0) {
585 fprintf(stderr
, "%s: option '-%c' expects"
586 " an argument\n", PNAME
, c
);
597 * Now actually process the option.
604 printf("FIXME: version();\n");
608 extern const char *const licence
[];
611 for (i
= 0; licence
[i
]; i
++)
612 fputs(licence
[i
], stdout
);
618 if (nactions
>= actionsize
) {
619 actionsize
= nactions
* 3 / 2 + 16;
620 actions
= sresize(actions
, actionsize
, struct action
);
622 actions
[nactions
].mode
= SCAN
;
623 actions
[nactions
].arg
= optval
;
627 if (nactions
>= actionsize
) {
628 actionsize
= nactions
* 3 / 2 + 16;
629 actions
= sresize(actions
, actionsize
, struct action
);
631 actions
[nactions
].mode
= SCANDUMP
;
632 actions
[nactions
].arg
= optval
;
636 if (nactions
>= actionsize
) {
637 actionsize
= nactions
* 3 / 2 + 16;
638 actions
= sresize(actions
, actionsize
, struct action
);
640 actions
[nactions
].mode
= DUMP
;
641 actions
[nactions
].arg
= NULL
;
645 if (nactions
>= actionsize
) {
646 actionsize
= nactions
* 3 / 2 + 16;
647 actions
= sresize(actions
, actionsize
, struct action
);
649 actions
[nactions
].mode
= LOAD
;
650 actions
[nactions
].arg
= NULL
;
654 if (nactions
>= actionsize
) {
655 actionsize
= nactions
* 3 / 2 + 16;
656 actions
= sresize(actions
, actionsize
, struct action
);
658 actions
[nactions
].mode
= TEXT
;
659 actions
[nactions
].arg
= optval
;
663 if (nactions
>= actionsize
) {
664 actionsize
= nactions
* 3 / 2 + 16;
665 actions
= sresize(actions
, actionsize
, struct action
);
667 actions
[nactions
].mode
= HTML
;
668 actions
[nactions
].arg
= optval
;
672 if (nactions
>= actionsize
) {
673 actionsize
= nactions
* 3 / 2 + 16;
674 actions
= sresize(actions
, actionsize
, struct action
);
676 actions
[nactions
].mode
= HTTPD
;
677 actions
[nactions
].arg
= NULL
;
686 case OPT_TTYPROGRESS
:
699 tqdepth
= atoi(optval
);
702 textcutoff
= parse_age(now
, optval
);
705 if (!strcmp(optval
, "auto")) {
706 htmlautoagerange
= 1;
708 char *q
= optval
+ strcspn(optval
, "-:");
711 htmloldest
= parse_age(now
, optval
);
712 htmlnewest
= *q ?
parse_age(now
, q
) : now
;
713 htmlautoagerange
= 0;
719 if (optval
[0] == '[' &&
720 (port
= strchr(optval
, ']')) != NULL
)
724 port
+= strcspn(port
, ":");
727 httpserveraddr
= optval
;
728 httpserverport
= atoi(port
);
732 if (!strcmp(optval
, "magic"))
733 auth
= HTTPD_AUTH_MAGIC
;
734 else if (!strcmp(optval
, "basic"))
735 auth
= HTTPD_AUTH_BASIC
;
736 else if (!strcmp(optval
, "none"))
737 auth
= HTTPD_AUTH_NONE
;
738 else if (!strcmp(optval
, "default"))
739 auth
= HTTPD_AUTH_MAGIC
| HTTPD_AUTH_BASIC
;
740 else if (!strcmp(optval
, "help") ||
741 !strcmp(optval
, "list")) {
742 printf(PNAME
": supported HTTP authentication types"
744 " magic use Linux /proc/net/tcp to"
745 " determine owner of peer socket\n"
746 " basic HTTP Basic username and"
747 " password authentication\n"
748 " default use 'magic' if possible, "
749 " otherwise fall back to 'basic'\n"
750 " none unauthenticated HTTP (if"
751 " the data file is non-confidential)\n");
754 fprintf(stderr
, "%s: unrecognised authentication"
755 " type '%s'\n%*s options are 'magic',"
756 " 'basic', 'none', 'default'\n",
757 PNAME
, optval
, (int)strlen(PNAME
), "");
768 int authlen
, authsize
;
771 if (optid
== OPT_AUTHFILE
) {
772 fd
= open(optval
, O_RDONLY
);
774 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
,
775 optval
, strerror(errno
));
782 sprintf(namebuf
, "fd %d", fd
);
787 authbuf
= snewn(authsize
, char);
788 while ((ret
= read(fd
, authbuf
+authlen
,
789 authsize
-authlen
)) > 0) {
791 if ((authsize
- authlen
) < (authsize
/ 16)) {
792 authsize
= authlen
* 3 / 2 + 4096;
793 authbuf
= sresize(authbuf
, authsize
, char);
797 fprintf(stderr
, "%s: %s: read: %s\n", PNAME
,
798 name
, strerror(errno
));
801 if (optid
== OPT_AUTHFILE
)
803 httpauthdata
= authbuf
;
807 case OPT_INCLUDEPATH
:
809 case OPT_EXCLUDEPATH
:
812 if (ninex
>= inexsize
) {
813 inexsize
= ninex
* 3 / 2 + 16;
814 inex
= sresize(inex
, inexsize
,
815 struct inclusion_exclusion
);
817 inex
[ninex
].path
= (optid
== OPT_INCLUDEPATH
||
818 optid
== OPT_EXCLUDEPATH
||
819 optid
== OPT_PRUNEPATH
);
820 inex
[ninex
].type
= (optid
== OPT_INCLUDE ?
1 :
821 optid
== OPT_INCLUDEPATH ?
1 :
822 optid
== OPT_EXCLUDE ?
0 :
823 optid
== OPT_EXCLUDEPATH ?
0 :
824 optid
== OPT_PRUNE ?
-1 :
825 /* optid == OPT_PRUNEPATH ? */ -1);
826 inex
[ninex
].wildcard
= optval
;
832 fprintf(stderr
, "%s: unexpected argument '%s'\n", PNAME
, p
);
842 for (action
= 0; action
< nactions
; action
++) {
843 int mode
= actions
[action
].mode
;
845 if (mode
== SCAN
|| mode
== SCANDUMP
|| mode
== LOAD
) {
846 const char *scandir
= actions
[action
].arg
;
848 char *buf
= fgetline(stdin
);
850 buf
[strcspn(buf
, "\r\n")] = '\0';
851 if (1 != sscanf(buf
, DUMPHDR
"%x",
853 fprintf(stderr
, "%s: header in dump file not recognised\n",
857 pathsep
= (char)newpathsep
;
861 if (mode
== SCAN
|| mode
== LOAD
) {
863 * Prepare to write out the index file.
865 fd
= open(filename
, O_RDWR
| O_TRUNC
| O_CREAT
, S_IRWXU
);
867 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
871 if (fstat(fd
, &st
) < 0) {
872 perror(PNAME
": fstat");
875 ctx
->datafile_dev
= st
.st_dev
;
876 ctx
->datafile_ino
= st
.st_ino
;
877 ctx
->straight_to_dump
= 0;
879 ctx
->datafile_dev
= -1;
880 ctx
->datafile_ino
= -1;
881 ctx
->straight_to_dump
= 1;
884 if (mode
== SCAN
|| mode
== SCANDUMP
) {
885 if (stat(scandir
, &st
) < 0) {
886 fprintf(stderr
, "%s: %s: stat: %s\n", PNAME
, scandir
,
890 ctx
->filesystem_dev
= crossfs ?
0 : st
.st_dev
;
895 ctx
->crossfs
= crossfs
;
897 ctx
->last_output_update
= time(NULL
);
899 /* progress==1 means report progress only if stderr is a tty */
901 progress
= isatty(2) ?
2 : 0;
902 ctx
->progress
= progress
;
905 if (progress
&& ioctl(2, TIOCGWINSZ
, &ws
) == 0)
906 ctx
->progwidth
= ws
.ws_col
- 1;
911 if (mode
== SCANDUMP
)
912 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
915 * Scan the directory tree, and write out the trie component
918 if (mode
!= SCANDUMP
) {
919 ctx
->tb
= triebuild_new(fd
);
924 while ((buf
= fgetline(stdin
)) != NULL
) {
928 buf
[strcspn(buf
, "\r\n")] = '\0';
932 while (*p
&& *p
!= ' ') p
++;
934 fprintf(stderr
, "%s: dump file line %d: expected at least"
935 " three fields\n", PNAME
, line
);
939 tf
.size
= strtoull(q
, NULL
, 10);
941 while (*p
&& *p
!= ' ') p
++;
943 fprintf(stderr
, "%s: dump file line %d: expected at least"
944 " three fields\n", PNAME
, line
);
948 tf
.atime
= strtoull(q
, NULL
, 10);
956 for (i
= 0; i
< 2; i
++) {
957 if (*p
>= '0' && *p
<= '9')
959 else if (*p
>= 'A' && *p
<= 'F')
960 c
+= *p
- ('A' - 10);
961 else if (*p
>= 'a' && *p
<= 'f')
962 c
+= *p
- ('a' - 10);
964 fprintf(stderr
, "%s: dump file line %d: unable"
965 " to parse hex escape\n", PNAME
, line
);
974 triebuild_add(ctx
->tb
, buf
, &tf
);
978 du(scandir
, gotdata
, ctx
);
980 if (mode
!= SCANDUMP
) {
981 count
= triebuild_finish(ctx
->tb
);
982 triebuild_free(ctx
->tb
);
985 fprintf(stderr
, "%-*s\r", ctx
->progwidth
, "");
990 * Work out how much space the cumulative index trees
991 * will take; enlarge the file, and memory-map it.
993 if (fstat(fd
, &st
) < 0) {
994 perror(PNAME
": fstat");
998 printf("Built pathname index, %d entries, %ju bytes\n", count
,
999 (intmax_t)st
.st_size
);
1001 totalsize
= index_compute_size(st
.st_size
, count
);
1003 if (lseek(fd
, totalsize
-1, SEEK_SET
) < 0) {
1004 perror(PNAME
": lseek");
1007 if (write(fd
, "\0", 1) < 1) {
1008 perror(PNAME
": write");
1012 printf("Upper bound on index file size = %ju bytes\n",
1013 (intmax_t)totalsize
);
1015 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
|PROT_WRITE
,MAP_SHARED
, fd
, 0);
1017 perror(PNAME
": mmap");
1021 ib
= indexbuild_new(mappedfile
, st
.st_size
, count
);
1022 tw
= triewalk_new(mappedfile
);
1023 while ((tf
= triewalk_next(tw
, NULL
)) != NULL
)
1024 indexbuild_add(ib
, tf
);
1026 realsize
= indexbuild_realsize(ib
);
1027 indexbuild_free(ib
);
1029 munmap(mappedfile
, totalsize
);
1030 ftruncate(fd
, realsize
);
1032 printf("Actual index file size = %ju bytes\n", (intmax_t)realsize
);
1034 } else if (mode
== TEXT
) {
1035 char *querydir
= actions
[action
].arg
;
1038 fd
= open(filename
, O_RDONLY
);
1040 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1044 if (fstat(fd
, &st
) < 0) {
1045 perror(PNAME
": fstat");
1048 totalsize
= st
.st_size
;
1049 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1051 perror(PNAME
": mmap");
1054 pathsep
= trie_pathsep(mappedfile
);
1057 * Trim trailing slash, just in case.
1059 pathlen
= strlen(querydir
);
1060 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1061 querydir
[--pathlen
] = '\0';
1063 text_query(mappedfile
, querydir
, textcutoff
, tqdepth
);
1064 } else if (mode
== HTML
) {
1065 char *querydir
= actions
[action
].arg
;
1067 struct html_config cfg
;
1071 fd
= open(filename
, O_RDONLY
);
1073 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1077 if (fstat(fd
, &st
) < 0) {
1078 perror(PNAME
": fstat");
1081 totalsize
= st
.st_size
;
1082 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1084 perror(PNAME
": mmap");
1087 pathsep
= trie_pathsep(mappedfile
);
1090 * Trim trailing slash, just in case.
1092 pathlen
= strlen(querydir
);
1093 if (pathlen
> 0 && querydir
[pathlen
-1] == pathsep
)
1094 querydir
[--pathlen
] = '\0';
1096 xi
= trie_before(mappedfile
, querydir
);
1098 cfg
.autoage
= htmlautoagerange
;
1099 cfg
.oldest
= htmloldest
;
1100 cfg
.newest
= htmlnewest
;
1101 html
= html_query(mappedfile
, xi
, &cfg
);
1102 fputs(html
, stdout
);
1103 } else if (mode
== DUMP
) {
1107 fd
= open(filename
, O_RDONLY
);
1109 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1113 if (fstat(fd
, &st
) < 0) {
1114 perror(PNAME
": fstat");
1117 totalsize
= st
.st_size
;
1118 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1120 perror(PNAME
": mmap");
1123 pathsep
= trie_pathsep(mappedfile
);
1125 maxpathlen
= trie_maxpathlen(mappedfile
);
1126 buf
= snewn(maxpathlen
, char);
1128 printf(DUMPHDR
"%02x\n", (unsigned char)pathsep
);
1129 tw
= triewalk_new(mappedfile
);
1130 while ((tf
= triewalk_next(tw
, buf
)) != NULL
)
1133 } else if (mode
== HTTPD
) {
1134 struct html_config pcfg
;
1135 struct httpd_config dcfg
;
1137 fd
= open(filename
, O_RDONLY
);
1139 fprintf(stderr
, "%s: %s: open: %s\n", PNAME
, filename
,
1143 if (fstat(fd
, &st
) < 0) {
1144 perror(PNAME
": fstat");
1147 totalsize
= st
.st_size
;
1148 mappedfile
= mmap(NULL
, totalsize
, PROT_READ
, MAP_SHARED
, fd
, 0);
1150 perror(PNAME
": mmap");
1153 pathsep
= trie_pathsep(mappedfile
);
1155 dcfg
.address
= httpserveraddr
;
1156 dcfg
.port
= httpserverport
;
1157 dcfg
.basicauthdata
= httpauthdata
;
1159 pcfg
.autoage
= htmlautoagerange
;
1160 pcfg
.oldest
= htmloldest
;
1161 pcfg
.newest
= htmlnewest
;
1162 run_httpd(mappedfile
, auth
, &dcfg
, &pcfg
);