2 * Copyright (c) 2002 John Rochester
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer,
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/utsname.h>
51 #define DEFAULT_MANPATH "/usr/share/man"
53 #define TOP_LEVEL_DIR 0 /* signifies a top-level man directory */
54 #define MAN_SECTION_DIR 1 /* signifies a man section directory */
55 #define UNKNOWN 2 /* signifies an unclassifiable directory */
57 #define TEST_EXISTS 0x01
59 #define TEST_FILE 0x04
60 #define TEST_READABLE 0x08
61 #define TEST_WRITABLE 0x10
63 static int verbose; /* -v flag: be verbose with warnings */
64 static int pretend; /* -n, -p flags: print out what would be done
65 instead of actually doing it */
66 static int force; /* -f flag: force overwriting all cat pages */
67 static int rm_junk; /* -r flag: remove garbage pages */
68 static char *locale; /* user's locale if -L is used */
69 static char *lang_locale; /* short form of locale */
70 static const char *machine, *machine_arch;
71 static int exit_code; /* exit code to use when finished */
74 * -T argument for nroff
76 static const char *nroff_device = "ascii";
79 * Mapping from locale to nroff device
81 static const char *locale_device[] = {
83 "ISO8859-1", "latin1",
84 "ISO8859-15", "latin1",
88 #define BZ2_CMD "bzip2"
89 #define BZ2_EXT ".bz2"
90 #define BZ2CAT_CMD "bz"
94 enum Ziptype {NONE, BZIP, GZIP};
97 static int starting_dir;
98 static char tmp_file[MAXPATHLEN];
99 static struct stat test_st;
102 * A hashtable is an array of chains composed of this entry structure.
108 struct hash_entry *next;
111 #define HASHTABLE_ALLOC 16384 /* allocation for hashtable (power of 2) */
112 #define HASH_MASK (HASHTABLE_ALLOC - 1)
114 static struct hash_entry *visited[HASHTABLE_ALLOC];
115 static struct hash_entry *links[HASHTABLE_ALLOC];
118 * Inserts a string into a hashtable keyed by inode & device number.
121 insert_hashtable(struct hash_entry **table,
126 struct hash_entry *new_entry;
127 struct hash_entry **chain;
129 new_entry = (struct hash_entry *) malloc(sizeof(struct hash_entry));
130 if (new_entry == NULL)
131 err(1, "can't insert into hashtable");
132 chain = &table[inode_number & HASH_MASK];
133 new_entry->inode_number = inode_number;
134 new_entry->device_number = device_number;
135 new_entry->data = data;
136 new_entry->next = *chain;
141 * Finds a string in a hashtable keyed by inode & device number.
144 find_hashtable(struct hash_entry **table,
148 struct hash_entry *chain;
150 chain = table[inode_number & HASH_MASK];
151 while (chain != NULL) {
152 if (chain->inode_number == inode_number &&
153 chain->device_number == device_number)
161 trap_signal(int sig __unused)
163 if (tmp_file[0] != '\0')
169 * Deals with junk files in the man or cat section directories.
172 junk(const char *mandir, const char *name, const char *reason)
175 fprintf(stderr, "%s/%s: %s\n", mandir, name, reason);
177 fprintf(stderr, "rm %s/%s\n", mandir, name);
178 if (!pretend && unlink(name) < 0)
179 warn("%s/%s", mandir, name);
184 * Returns TOP_LEVEL_DIR for .../man, MAN_SECTION_DIR for .../manXXX,
185 * and UNKNOWN for everything else.
188 directory_type(char *dir)
193 p = strrchr(dir, '/');
194 if (p == NULL || p[1] != '\0')
202 if (strncmp(p, "man", 3) == 0) {
205 return TOP_LEVEL_DIR;
206 while (isalnum((unsigned char)*p) || *p == '_') {
208 return MAN_SECTION_DIR;
215 * Tests whether the given file name (without a preceding path)
216 * is a proper man page name (like "mk-amd-map.8.gz").
217 * Only alphanumerics and '_' are allowed after the last '.' and
218 * the last '.' can't be the first or last characters.
221 is_manpage_name(char *name)
223 char *lastdot = NULL;
227 if (!isalnum((unsigned char)*n)) {
246 return lastdot > name && lastdot + 1 < n;
250 is_bzipped(char *name)
252 int len = strlen(name);
253 return len >= 5 && strcmp(&name[len - 4], BZ2_EXT) == 0;
257 is_gzipped(char *name)
259 int len = strlen(name);
260 return len >= 4 && strcmp(&name[len - 3], GZ_EXT) == 0;
264 * Converts manXXX to catXXX.
267 get_cat_section(char *section)
271 cat_section = strdup(section);
272 assert(strlen(section) > 3 && strncmp(section, "man", 3) == 0);
273 memcpy(cat_section, "cat", 3);
278 * Tests to see if the given directory has already been visited.
281 already_visited(char *mandir, char *dir, int count_visit)
285 if (stat(dir, &st) < 0) {
287 warn("%s/%s", mandir, dir);
293 if (find_hashtable(visited, st.st_ino, st.st_dev) != NULL) {
295 warnx("already visited %s/%s", mandir, dir);
297 warnx("already visited %s", dir);
301 insert_hashtable(visited, st.st_ino, st.st_dev, "");
306 * Returns a set of TEST_* bits describing a file's type and permissions.
307 * If mod_time isn't NULL, it will contain the file's modification time.
310 test_path(char *name, time_t *mod_time)
314 if (stat(name, &test_st) < 0)
316 result = TEST_EXISTS;
317 if (mod_time != NULL)
318 *mod_time = test_st.st_mtime;
319 if (S_ISDIR(test_st.st_mode))
321 else if (S_ISREG(test_st.st_mode))
323 if (access(name, R_OK))
324 result |= TEST_READABLE;
325 if (access(name, W_OK))
326 result |= TEST_WRITABLE;
331 * Checks whether a file is a symbolic link.
334 is_symlink(char *path)
338 return lstat(path, &st) >= 0 && S_ISLNK(st.st_mode);
342 * Tests to see if the given directory can be written to.
345 check_writable(char *mandir)
347 if (verbose && !(test_path(mandir, NULL) & TEST_WRITABLE))
348 fprintf(stderr, "%s: not writable - will only be able to write to existing cat directories\n", mandir);
352 * If the directory exists, attempt to make it writable, otherwise
353 * attempt to create it.
356 make_writable_dir(char *mandir, char *dir)
360 if ((test = test_path(dir, NULL)) != 0) {
361 if (!(test & TEST_WRITABLE) && chmod(dir, 0755) < 0) {
362 warn("%s/%s: chmod", mandir, dir);
367 if (verbose || pretend)
368 fprintf(stderr, "mkdir %s\n", dir);
371 if (mkdir(dir, 0755) < 0) {
372 warn("%s/%s: mkdir", mandir, dir);
382 * Processes a single man page source by using nroff to create
383 * the preformatted cat page.
386 process_page(char *mandir, char *src, char *cat, enum Ziptype zipped)
388 int src_test, cat_test;
389 time_t src_mtime, cat_mtime;
390 char cmd[MAXPATHLEN];
393 const char *link_name;
395 src_test = test_path(src, &src_mtime);
396 if (!(src_test & (TEST_FILE|TEST_READABLE))) {
397 if (!(src_test & TEST_DIR)) {
398 warnx("%s/%s: unreadable", mandir, src);
400 if (rm_junk && is_symlink(src))
401 junk(mandir, src, "bogus symlink");
405 src_dev = test_st.st_dev;
406 src_ino = test_st.st_ino;
407 cat_test = test_path(cat, &cat_mtime);
408 if (cat_test & (TEST_FILE|TEST_READABLE)) {
409 if (!force && cat_mtime >= src_mtime) {
411 fprintf(stderr, "\t%s/%s: up to date\n",
418 * Is the man page a link to one we've already processed?
420 if ((link_name = find_hashtable(links, src_ino, src_dev)) != NULL) {
421 if (verbose || pretend) {
422 fprintf(stderr, "%slink %s -> %s\n",
423 verbose ? "\t" : "", cat, link_name);
427 if (link(link_name, cat) < 0)
428 warn("%s %s: link", link_name, cat);
432 insert_hashtable(links, src_ino, src_dev, strdup(cat));
433 if (verbose || pretend) {
434 fprintf(stderr, "%sformat %s -> %s\n",
435 verbose ? "\t" : "", src, cat);
439 snprintf(tmp_file, sizeof tmp_file, "%s.tmp", cat);
440 snprintf(cmd, sizeof cmd,
441 "%scat %s | tbl | nroff -c -T%s -man | %s > %s.tmp",
442 zipped == BZIP ? BZ2CAT_CMD : zipped == GZIP ? GZCAT_CMD : "",
444 zipped == BZIP ? BZ2_CMD : zipped == GZIP ? GZ_CMD : "cat",
446 if (system(cmd) != 0)
447 err(1, "formatting pipeline");
448 if (rename(tmp_file, cat) < 0)
454 * Scan the man section directory for pages and process each one,
455 * then check for junk in the corresponding cat section.
458 scan_section(char *mandir, char *section, char *cat_section)
460 struct dirent **entries;
461 char **expected = NULL;
467 char page_path[MAXPATHLEN];
468 char cat_path[MAXPATHLEN];
469 char zip_path[MAXPATHLEN];
472 * scan the man section directory for pages
474 npages = scandir(section, &entries, NULL, alphasort);
476 warn("%s/%s", mandir, section);
480 if (verbose || rm_junk) {
482 * Maintain a list of all cat pages that should exist,
483 * corresponding to existing man pages.
485 expected = (char **) calloc(npages, sizeof(char *));
487 for (i = 0; i < npages; free(entries[i++])) {
488 page_name = entries[i]->d_name;
489 snprintf(page_path, sizeof page_path, "%s/%s", section,
491 if (!is_manpage_name(page_name)) {
492 if (!(test_path(page_path, NULL) & TEST_DIR)) {
493 junk(mandir, page_path,
494 "invalid man page name");
498 zipped = is_bzipped(page_name) ? BZIP :
499 is_gzipped(page_name) ? GZIP : NONE;
500 if (zipped != NONE) {
501 snprintf(cat_path, sizeof cat_path, "%s/%s",
502 cat_section, page_name);
503 if (expected != NULL)
504 expected[nexpected++] = strdup(page_name);
505 process_page(mandir, page_path, cat_path, zipped);
508 * We've got an uncompressed man page,
509 * check to see if there's a (preferred)
512 snprintf(zip_path, sizeof zip_path, "%s%s",
514 if (test_path(zip_path, NULL) != 0) {
515 junk(mandir, page_path,
516 "man page unused due to existing " GZ_EXT);
520 "warning, %s is uncompressed\n",
523 snprintf(cat_path, sizeof cat_path, "%s/%s",
524 cat_section, page_name);
525 if (expected != NULL) {
526 asprintf(&expected[nexpected++],
529 process_page(mandir, page_path, cat_path, NONE);
534 if (expected == NULL)
537 * scan cat sections for junk
539 npages = scandir(cat_section, &entries, NULL, alphasort);
541 for (i = 0; i < npages; free(entries[i++])) {
542 const char *junk_reason;
545 page_name = entries[i]->d_name;
546 if (strcmp(page_name, ".") == 0 || strcmp(page_name, "..") == 0)
549 * Keep the index into the expected cat page list
550 * ahead of the name we've found.
552 while (e < nexpected &&
553 (cmp = strcmp(page_name, expected[e])) > 0)
557 /* we have an unexpected page */
558 snprintf(cat_path, sizeof cat_path, "%s/%s", cat_section,
560 if (!is_manpage_name(page_name)) {
561 if (test_path(cat_path, NULL) & TEST_DIR)
563 junk_reason = "invalid cat page name";
564 } else if (!is_gzipped(page_name) && e + 1 < nexpected &&
565 strncmp(page_name, expected[e + 1], strlen(page_name)) == 0 &&
566 strlen(expected[e + 1]) == strlen(page_name) + 3) {
567 junk_reason = "cat page unused due to existing " GZ_EXT;
569 junk_reason = "cat page without man page";
570 junk(mandir, cat_path, junk_reason);
573 while (e < nexpected)
580 * Processes a single man section.
583 process_section(char *mandir, char *section)
587 if (already_visited(mandir, section, 1))
590 fprintf(stderr, " section %s\n", section);
591 cat_section = get_cat_section(section);
592 if (make_writable_dir(mandir, cat_section))
593 scan_section(mandir, section, cat_section);
598 select_sections(const struct dirent *entry)
603 name = strdup(entry->d_name);
604 ret = directory_type(name) == MAN_SECTION_DIR;
610 * Processes a single top-level man directory. If section isn't NULL,
611 * it will only process that section sub-directory, otherwise it will
612 * process all of them.
615 process_mandir(char *dir_name, char *section)
617 if (fchdir(starting_dir) < 0)
619 if (already_visited(NULL, dir_name, section == NULL))
621 check_writable(dir_name);
623 fprintf(stderr, "man directory %s\n", dir_name);
625 fprintf(stderr, "cd %s\n", dir_name);
626 if (chdir(dir_name) < 0) {
627 warn("%s: chdir", dir_name);
631 if (section != NULL) {
632 process_section(dir_name, section);
634 struct dirent **entries;
635 char *machine_dir, *arch_dir;
639 nsections = scandir(".", &entries, select_sections, alphasort);
641 warn("%s", dir_name);
645 for (i = 0; i < nsections; i++) {
646 process_section(dir_name, entries[i]->d_name);
647 asprintf(&machine_dir, "%s/%s", entries[i]->d_name,
649 if (test_path(machine_dir, NULL) & TEST_DIR)
650 process_section(dir_name, machine_dir);
652 if (strcmp(machine_arch, machine) != 0) {
653 asprintf(&arch_dir, "%s/%s", entries[i]->d_name,
655 if (test_path(arch_dir, NULL) & TEST_DIR)
656 process_section(dir_name, arch_dir);
666 * Processes one argument, which may be a colon-separated list of
670 process_argument(const char *arg)
679 err(1, "out of memory");
680 while ((dir = strsep(&parg, ":")) != NULL) {
681 switch (directory_type(dir)) {
683 if (locale != NULL) {
684 asprintf(&mandir, "%s/%s", dir, locale);
685 process_mandir(mandir, NULL);
687 if (lang_locale != NULL) {
688 asprintf(&mandir, "%s/%s", dir,
690 process_mandir(mandir, NULL);
694 process_mandir(dir, NULL);
697 case MAN_SECTION_DIR: {
698 mandir = strdup(dirname(dir));
699 section = strdup(basename(dir));
700 process_mandir(mandir, section);
706 warnx("%s: directory name not in proper man form", dir);
714 determine_locale(void)
718 if ((locale = setlocale(LC_CTYPE, "")) == NULL) {
719 warnx("-L option used, but no locale found\n");
722 sep = strchr(locale, '_');
723 if (sep != NULL && isupper((unsigned char)sep[1])
724 && isupper((unsigned char)sep[2])) {
725 asprintf(&lang_locale, "%.*s%s", (int)(sep - locale),
728 sep = nl_langinfo(CODESET);
729 if (sep != NULL && *sep != '\0' && strcmp(sep, "US-ASCII") != 0) {
732 for (i = 0; locale_device[i] != NULL; i += 2) {
733 if (strcmp(sep, locale_device[i]) == 0) {
734 nroff_device = locale_device[i + 1];
740 if (lang_locale != NULL)
741 fprintf(stderr, "short locale is %s\n", lang_locale);
742 fprintf(stderr, "nroff device is %s\n", nroff_device);
749 fprintf(stderr, "usage: %s [-fLnrv] [directories ...]\n",
755 main(int argc, char **argv)
759 if ((uid = getuid()) == 0) {
760 fprintf(stderr, "don't run %s as root, use:\n echo", argv[0]);
761 for (optind = 0; optind < argc; optind++) {
762 fprintf(stderr, " %s", argv[optind]);
764 fprintf(stderr, " | nice -5 su -m man\n");
767 while ((opt = getopt(argc, argv, "vnfLrh")) != -1) {
789 if ((starting_dir = open(".", 0)) < 0) {
793 signal(SIGINT, trap_signal);
794 signal(SIGHUP, trap_signal);
795 signal(SIGQUIT, trap_signal);
796 signal(SIGTERM, trap_signal);
798 if ((machine = getenv("MACHINE")) == NULL) {
799 static struct utsname utsname;
801 if (uname(&utsname) == -1)
803 machine = utsname.machine;
806 if ((machine_arch = getenv("MACHINE_ARCH")) == NULL)
807 machine_arch = MACHINE_ARCH;
809 if (optind == argc) {
810 const char *manpath = getenv("MANPATH");
812 manpath = DEFAULT_MANPATH;
813 process_argument(manpath);
815 while (optind < argc)
816 process_argument(argv[optind++]);