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/queue.h>
36 #include <sys/utsname.h>
44 #include <stringlist.h>
48 #define DEFAULT_MANPATH "/usr/share/man"
49 #define LINE_ALLOC 4096
51 static char blank[] = "";
54 * Information collected about each man page in a section.
65 * An entry kept for each visited directory.
70 SLIST_ENTRY(visited_dir) next;
77 char * content; /* the start of the buffer */
78 char * end; /* just past the end of the content */
79 char * last; /* the last allocated character */
83 * Removes the last amount characters from the sbuf.
85 #define sbuf_retract(sbuf, amount) \
86 ((sbuf)->end -= (amount))
88 * Returns the length of the sbuf content.
90 #define sbuf_length(sbuf) \
91 ((sbuf)->end - (sbuf)->content)
93 typedef char *edited_copy(char *from, char *to, int length);
95 static int append; /* -a flag: append to existing whatis */
96 static int verbose; /* -v flag: be verbose with warnings */
97 static int indent = 24; /* -i option: description indentation */
98 static const char *whatis_name="whatis";/* -n option: the name */
99 static char *common_output; /* -o option: the single output file */
100 static char *locale; /* user's locale if -L is used */
101 static char *lang_locale; /* short form of locale */
102 static const char *machine, *machine_arch;
104 static int exit_code; /* exit code to use when finished */
105 static SLIST_HEAD(, visited_dir) visited_dirs =
106 SLIST_HEAD_INITIALIZER(visited_dirs);
109 * While the whatis line is being formed, it is stored in whatis_proto.
110 * When finished, it is reformatted into whatis_final and then appended
113 static struct sbuf *whatis_proto;
114 static struct sbuf *whatis_final;
115 static StringList *whatis_lines; /* collected output lines */
117 static char tmp_file[MAXPATHLEN]; /* path of temporary file, if any */
119 /* A set of possible names for the NAME man page section */
120 static const char *name_section_titles[] = {
121 "NAME", "Name", "NAMN", "BEZEICHNUNG", "\xcc\xbe\xbe\xce",
122 "\xee\xe1\xfa\xf7\xe1\xee\xe9\xe5", NULL
125 /* A subset of the mdoc(7) commands to ignore */
126 static char mdoc_commands[] = "ArDvErEvFlLiNmPa";
129 * Frees a struct page_info and its content.
132 free_page_info(struct page_info *info)
134 free(info->filename);
141 * Allocates and fills in a new struct page_info given the
142 * name of the man section directory and the dirent of the file.
143 * If the file is not a man page, returns NULL.
145 static struct page_info *
146 new_page_info(char *dir, struct dirent *dirent)
148 struct page_info *info;
153 info = (struct page_info *) malloc(sizeof(struct page_info));
156 basename_length = strlen(dirent->d_name);
157 suffix = &dirent->d_name[basename_length];
158 asprintf(&info->filename, "%s/%s", dir, dirent->d_name);
159 if ((info->gzipped = basename_length >= 4 && strcmp(&dirent->d_name[basename_length - 3], ".gz") == 0)) {
164 if (--suffix == dirent->d_name || !isalnum(*suffix)) {
168 warnx("%s: invalid man page name", info->filename);
169 free(info->filename);
175 info->name = strdup(dirent->d_name);
176 info->suffix = strdup(suffix);
177 if (stat(info->filename, &st) < 0) {
178 warn("%s", info->filename);
179 free_page_info(info);
182 if (!S_ISREG(st.st_mode)) {
183 if (verbose && !S_ISDIR(st.st_mode))
184 warnx("%s: not a regular file", info->filename);
185 free_page_info(info);
188 info->inode = st.st_ino;
193 * Reset an sbuf's length to 0.
196 sbuf_clear(struct sbuf *sbuf)
198 sbuf->end = sbuf->content;
202 * Allocate a new sbuf.
207 struct sbuf *sbuf = (struct sbuf *) malloc(sizeof(struct sbuf));
208 sbuf->content = (char *) malloc(LINE_ALLOC);
209 sbuf->last = sbuf->content + LINE_ALLOC - 1;
215 * Ensure that there is enough room in the sbuf for nchars more characters.
218 sbuf_need(struct sbuf *sbuf, int nchars)
221 size_t size, cntsize;
223 /* double the size of the allocation until the buffer is big enough */
224 while (sbuf->end + nchars > sbuf->last) {
225 size = sbuf->last + 1 - sbuf->content;
227 cntsize = sbuf->end - sbuf->content;
229 new_content = (char *)malloc(size);
230 memcpy(new_content, sbuf->content, cntsize);
232 sbuf->content = new_content;
233 sbuf->end = new_content + cntsize;
234 sbuf->last = new_content + size - 1;
239 * Appends a string of a given length to the sbuf.
242 sbuf_append(struct sbuf *sbuf, const char *text, int length)
245 sbuf_need(sbuf, length);
246 memcpy(sbuf->end, text, length);
252 * Appends a null-terminated string to the sbuf.
255 sbuf_append_str(struct sbuf *sbuf, char *text)
257 sbuf_append(sbuf, text, strlen(text));
261 * Appends an edited null-terminated string to the sbuf.
264 sbuf_append_edited(struct sbuf *sbuf, char *text, edited_copy copy)
266 int length = strlen(text);
268 sbuf_need(sbuf, length);
269 sbuf->end = copy(text, sbuf->end, length);
274 * Strips any of a set of chars from the end of the sbuf.
277 sbuf_strip(struct sbuf *sbuf, const char *set)
279 while (sbuf->end > sbuf->content && strchr(set, sbuf->end[-1]) != NULL)
284 * Returns the null-terminated string built by the sbuf.
287 sbuf_content(struct sbuf *sbuf)
290 return sbuf->content;
294 * Returns true if no man page exists in the directory with
295 * any of the names in the StringList.
298 no_page_exists(char *dir, StringList *names, char *suffix)
300 char path[MAXPATHLEN];
303 for (i = 0; i < names->sl_cur; i++) {
304 snprintf(path, sizeof path, "%s/%s.%s.gz", dir, names->sl_str[i], suffix);
305 if (access(path, F_OK) < 0) {
306 path[strlen(path) - 3] = '\0';
307 if (access(path, F_OK) < 0)
316 trap_signal(int sig __unused)
318 if (tmp_file[0] != '\0')
324 * Attempts to open an output file. Returns NULL if unsuccessful.
327 open_output(char *name)
331 whatis_lines = sl_init();
333 char line[LINE_ALLOC];
335 output = fopen(name, "r");
336 if (output == NULL) {
341 while (fgets(line, sizeof line, output) != NULL) {
342 line[strlen(line) - 1] = '\0';
343 sl_add(whatis_lines, strdup(line));
346 if (common_output == NULL) {
347 snprintf(tmp_file, sizeof tmp_file, "%s.tmp", name);
350 output = fopen(name, "w");
351 if (output == NULL) {
360 linesort(const void *a, const void *b)
362 return strcmp((*(const char * const *)a), (*(const char * const *)b));
366 * Writes the unique sorted lines to the output file.
369 finish_output(FILE *output, char *name)
374 qsort(whatis_lines->sl_str, whatis_lines->sl_cur, sizeof(char *), linesort);
375 for (i = 0; i < whatis_lines->sl_cur; i++) {
376 char *line = whatis_lines->sl_str[i];
377 if (i > 0 && strcmp(line, prev) == 0)
384 sl_free(whatis_lines, 1);
385 if (common_output == NULL) {
386 rename(tmp_file, name);
392 open_whatis(char *mandir)
394 char filename[MAXPATHLEN];
396 snprintf(filename, sizeof filename, "%s/%s", mandir, whatis_name);
397 return open_output(filename);
401 finish_whatis(FILE *output, char *mandir)
403 char filename[MAXPATHLEN];
405 snprintf(filename, sizeof filename, "%s/%s", mandir, whatis_name);
406 finish_output(output, filename);
410 * Tests to see if the given directory has already been visited.
413 already_visited(char *dir)
416 struct visited_dir *visit;
418 if (stat(dir, &st) < 0) {
423 SLIST_FOREACH(visit, &visited_dirs, next) {
424 if (visit->inode == st.st_ino &&
425 visit->device == st.st_dev) {
426 warnx("already visited %s", dir);
430 visit = (struct visited_dir *) malloc(sizeof(struct visited_dir));
431 visit->device = st.st_dev;
432 visit->inode = st.st_ino;
433 SLIST_INSERT_HEAD(&visited_dirs, visit, next);
438 * Removes trailing spaces from a string, returning a pointer to just
439 * beyond the new last character.
444 char *rhs = &str[strlen(str)];
445 while (--rhs > str && isspace(*rhs))
452 * Returns a pointer to the next non-space character in the string.
457 while (*s != '\0' && isspace(*s))
463 * Returns whether the string contains only digits.
466 only_digits(char *line)
468 if (!isdigit(*line++))
470 while (isdigit(*line))
472 return *line == '\0';
476 * Returns whether the line is of one of the forms:
480 * assuming that section_start is ".Sh".
483 name_section_line(char *line, const char *section_start)
488 if (strncmp(line, section_start, 3) != 0)
490 line = skip_spaces(line + 3);
491 rhs = trim_rhs(line);
497 for (title = name_section_titles; *title != NULL; title++)
498 if (strcmp(*title, line) == 0)
504 * Copies characters while removing the most common nroff/troff
506 * \(em, \(mi, \s[+-N], \&
507 * \fF, \f(fo, \f[font]
508 * \*s, \*(st, \*[stringvar]
511 de_nroff_copy(char *from, char *to, int fromlen)
513 char *from_end = &from[fromlen];
514 while (from < from_end) {
519 if (strncmp(&from[1], "em", 2) == 0 ||
520 strncmp(&from[1], "mi", 2) == 0) {
528 while (isdigit(*from))
535 else if (*from == '[') {
536 while (*++from != ']' && from < from_end);
553 * Appends a string with the nroff formatting removed.
556 add_nroff(char *text)
558 sbuf_append_edited(whatis_proto, text, de_nroff_copy);
562 * Appends "name(suffix), " to whatis_final.
565 add_whatis_name(char *name, char *suffix)
568 sbuf_append_str(whatis_final, name);
569 sbuf_append(whatis_final, "(", 1);
570 sbuf_append_str(whatis_final, suffix);
571 sbuf_append(whatis_final, "), ", 3);
576 * Processes an old-style man(7) line. This ignores commands with only
577 * a single number argument.
580 process_man_line(char *line)
583 while (isalpha(*++line))
585 line = skip_spaces(line);
586 if (only_digits(line))
589 line = skip_spaces(line);
592 sbuf_append(whatis_proto, " ", 1);
597 * Processes a new-style mdoc(7) line.
600 process_mdoc_line(char *line)
604 char *line_end = &line[strlen(line)];
605 int orig_length = sbuf_length(whatis_proto);
610 if (line[0] != '.' || !isupper(line[1]) || !islower(line[2])) {
611 add_nroff(skip_spaces(line));
612 sbuf_append(whatis_proto, " ", 1);
615 xref = strncmp(line, ".Xr", 3) == 0;
617 while ((line = skip_spaces(line)) < line_end) {
621 next = strchr(next, '"');
624 memmove(next, next + 1, strlen(next));
631 next = strpbrk(line, " \t");
636 if (isupper(*line) && islower(line[1]) && line[2] == '\0') {
637 if (strcmp(line, "Ns") == 0) {
642 if (strstr(mdoc_commands, line) != NULL) {
647 if (arg > 0 && strchr(",.:;?!)]", *line) == 0) {
649 sbuf_append(whatis_proto, "(", 1);
651 sbuf_append(whatis_proto, ")", 1);
655 sbuf_append(whatis_proto, " ", 1);
661 if (sbuf_length(whatis_proto) > orig_length)
662 sbuf_append(whatis_proto, " ", 1);
666 * Collects a list of comma-separated names from the text.
669 collect_names(StringList *names, char *text)
675 text = strchr(text, ',');
686 enum { STATE_UNKNOWN, STATE_MANSTYLE, STATE_MDOCNAME, STATE_MDOCDESC };
689 * Processes a man page source into a single whatis line and adds it
693 process_page(struct page_info *page, char *section_dir)
700 int state = STATE_UNKNOWN;
703 sbuf_clear(whatis_proto);
704 if ((in = gzopen(page->filename, "r")) == NULL) {
705 warn("%s", page->filename);
709 while (gzgets(in, buffer, sizeof buffer) != NULL) {
711 if (strncmp(line, ".\\\"", 3) == 0) /* ignore comments */
715 * haven't reached the NAME section yet.
718 if (name_section_line(line, ".SH"))
719 state = STATE_MANSTYLE;
720 else if (name_section_line(line, ".Sh"))
721 state = STATE_MDOCNAME;
724 * Inside an old-style .SH NAME section.
727 if (strncmp(line, ".SH", 3) == 0)
729 if (strncmp(line, ".SS", 3) == 0)
732 if (strcmp(line, ".") == 0)
734 if (strncmp(line, ".IX", 3) == 0) {
736 line = skip_spaces(line);
738 process_man_line(line);
741 * Inside a new-style .Sh NAME section (the .Nm part).
745 if (strncmp(line, ".Nm", 3) == 0) {
746 process_mdoc_line(line);
749 if (strcmp(line, ".") == 0)
751 sbuf_append(whatis_proto, "- ", 2);
752 state = STATE_MDOCDESC;
756 * Inside a new-style .Sh NAME section (after the .Nm-s).
759 if (strncmp(line, ".Sh", 3) == 0)
762 if (strcmp(line, ".") == 0)
764 process_mdoc_line(line);
770 sbuf_strip(whatis_proto, " \t.-");
771 line = sbuf_content(whatis_proto);
773 * line now contains the appropriate data, but without
774 * the proper indentation or the section appended to each name.
776 descr = strstr(line, " - ");
778 descr = strchr(line, ' ');
781 fprintf(stderr, " ignoring junk description \"%s\"\n", line);
790 collect_names(names, line);
791 sbuf_clear(whatis_final);
792 if (!sl_find(names, page->name) && no_page_exists(section_dir, names, page->suffix)) {
794 * Add the page name since that's the only thing that
797 add_whatis_name(page->name, page->suffix);
799 for (i = 0; i < names->sl_cur; i++)
800 add_whatis_name(names->sl_str[i], page->suffix);
802 sbuf_retract(whatis_final, 2); /* remove last ", " */
803 while (sbuf_length(whatis_final) < indent)
804 sbuf_append(whatis_final, " ", 1);
805 sbuf_append(whatis_final, " - ", 3);
806 sbuf_append_str(whatis_final, skip_spaces(descr));
807 sl_add(whatis_lines, strdup(sbuf_content(whatis_final)));
811 * Sorts pages first by inode number, then by name.
814 pagesort(const void *a, const void *b)
816 const struct page_info *p1 = *(struct page_info * const *) a;
817 const struct page_info *p2 = *(struct page_info * const *) b;
818 if (p1->inode == p2->inode)
819 return strcmp(p1->name, p2->name);
820 return p1->inode - p2->inode;
824 * Processes a single man section.
827 process_section(char *section_dir)
829 struct dirent **entries;
831 struct page_info **pages;
834 ino_t prev_inode = 0;
837 fprintf(stderr, " %s\n", section_dir);
840 * scan the man section directory for pages
842 nentries = scandir(section_dir, &entries, NULL, alphasort);
844 warn("%s", section_dir);
849 * collect information about man pages
851 pages = (struct page_info **) calloc(nentries, sizeof(struct page_info *));
852 for (i = 0; i < nentries; i++) {
853 struct page_info *info = new_page_info(section_dir, entries[i]);
855 pages[npages++] = info;
859 qsort(pages, npages, sizeof(struct page_info *), pagesort);
861 * process each unique page
863 for (i = 0; i < npages; i++) {
864 struct page_info *page = pages[i];
865 if (page->inode != prev_inode) {
866 prev_inode = page->inode;
868 fprintf(stderr, " reading %s\n", page->filename);
869 process_page(page, section_dir);
871 fprintf(stderr, " skipping %s, duplicate\n", page->filename);
872 free_page_info(page);
878 * Returns whether the directory entry is a man page section.
881 select_sections(struct dirent *entry)
883 char *p = &entry->d_name[3];
885 if (strncmp(entry->d_name, "man", 3) != 0)
895 * Processes a single top-level man directory by finding all the
896 * sub-directories named man* and processing each one in turn.
899 process_mandir(char *dir_name)
901 struct dirent **entries;
907 if (already_visited(dir_name))
910 fprintf(stderr, "man directory %s\n", dir_name);
911 nsections = scandir(dir_name, &entries, select_sections, alphasort);
913 warn("%s", dir_name);
917 if (common_output == NULL && (fp = open_whatis(dir_name)) == NULL)
919 for (i = 0; i < nsections; i++) {
920 char section_dir[MAXPATHLEN];
921 snprintf(section_dir, sizeof section_dir, "%s/%s", dir_name, entries[i]->d_name);
922 process_section(section_dir);
923 snprintf(section_dir, sizeof section_dir, "%s/%s/%s", dir_name,
924 entries[i]->d_name, machine);
925 if (stat(section_dir, &st) == 0 && S_ISDIR(st.st_mode))
926 process_section(section_dir);
927 if (strcmp(machine_arch, machine) != 0) {
928 snprintf(section_dir, sizeof section_dir, "%s/%s/%s",
929 dir_name, entries[i]->d_name, machine_arch);
930 if (stat(section_dir, &st) == 0 && S_ISDIR(st.st_mode))
931 process_section(section_dir);
936 if (common_output == NULL)
937 finish_whatis(fp, dir_name);
941 * Processes one argument, which may be a colon-separated list of
945 process_argument(const char *arg)
953 err(1, "out of memory");
954 while ((dir = strsep(&parg, ":")) != NULL) {
955 if (locale != NULL) {
956 asprintf(&mandir, "%s/%s", dir, locale);
957 process_mandir(mandir);
959 if (lang_locale != NULL) {
960 asprintf(&mandir, "%s/%s", dir, lang_locale);
961 process_mandir(mandir);
973 main(int argc, char **argv)
978 while ((opt = getopt(argc, argv, "ai:n:o:vL")) != -1) {
984 indent = atoi(optarg);
987 whatis_name = optarg;
990 common_output = optarg;
996 locale = getenv("LC_ALL");
998 locale = getenv("LC_CTYPE");
1000 locale = getenv("LANG");
1001 if (locale != NULL) {
1002 char *sep = strchr(locale, '_');
1003 if (sep != NULL && isupper(sep[1]) &&
1005 asprintf(&lang_locale, "%.*s%s", sep - locale, locale, &sep[3]);
1010 fprintf(stderr, "usage: %s [-a] [-i indent] [-n name] [-o output_file] [-v] [-L] [directories...]\n", argv[0]);
1015 signal(SIGINT, trap_signal);
1016 signal(SIGHUP, trap_signal);
1017 signal(SIGQUIT, trap_signal);
1018 signal(SIGTERM, trap_signal);
1019 SLIST_INIT(&visited_dirs);
1020 whatis_proto = new_sbuf();
1021 whatis_final = new_sbuf();
1023 if ((machine = getenv("MACHINE")) == NULL) {
1024 static struct utsname utsname;
1026 if (uname(&utsname) == -1)
1028 machine = utsname.machine;
1031 if ((machine_arch = getenv("MACHINE_ARCH")) == NULL)
1032 machine_arch = MACHINE_ARCH;
1034 if (common_output != NULL && (fp = open_output(common_output)) == NULL)
1035 err(1, "%s", common_output);
1036 if (optind == argc) {
1037 const char *manpath = getenv("MANPATH");
1038 if (manpath == NULL)
1039 manpath = DEFAULT_MANPATH;
1040 process_argument(manpath);
1042 while (optind < argc)
1043 process_argument(argv[optind++]);
1045 if (common_output != NULL)
1046 finish_output(fp, common_output);