]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/makewhatis/makewhatis.c
MFC of 1.11
[FreeBSD/FreeBSD.git] / usr.bin / makewhatis / makewhatis.c
1 /*-
2  * Copyright (c) 2002 John Rochester
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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
16  *
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.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/param.h>
35 #include <sys/queue.h>
36
37 #include <ctype.h>
38 #include <dirent.h>
39 #include <err.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <stringlist.h>
44 #include <unistd.h>
45 #include <zlib.h>
46
47 #define DEFAULT_MANPATH         "/usr/share/man"
48 #define LINE_ALLOC              4096
49
50 static char blank[] =           "";
51
52 /*
53  * Information collected about each man page in a section.
54  */
55 struct page_info {
56         char *  filename;
57         char *  name;
58         char *  suffix;
59         int     gzipped;
60         ino_t   inode;
61 };
62
63 /*
64  * An entry kept for each visited directory.
65  */
66 struct visited_dir {
67         dev_t           device;
68         ino_t           inode;
69         SLIST_ENTRY(visited_dir)        next;
70 };
71
72 /*
73  * an expanding string
74  */
75 struct sbuf {
76         char *  content;                /* the start of the buffer */
77         char *  end;                    /* just past the end of the content */
78         char *  last;                   /* the last allocated character */
79 };
80
81 /*
82  * Removes the last amount characters from the sbuf.
83  */
84 #define sbuf_retract(sbuf, amount)      \
85         ((sbuf)->end -= (amount))
86 /*
87  * Returns the length of the sbuf content.
88  */
89 #define sbuf_length(sbuf)               \
90         ((sbuf)->end - (sbuf)->content)
91
92 typedef char *edited_copy(char *from, char *to, int length);
93
94 static int append;                      /* -a flag: append to existing whatis */
95 static int verbose;                     /* -v flag: be verbose with warnings */
96 static int indent = 24;                 /* -i option: description indentation */
97 static const char *whatis_name="whatis";/* -n option: the name */
98 static char *common_output;             /* -o option: the single output file */
99 static char *locale;                    /* user's locale if -L is used */
100 static char *lang_locale;               /* short form of locale */
101 static const char *machine;
102
103 static int exit_code;                   /* exit code to use when finished */
104 static SLIST_HEAD(, visited_dir) visited_dirs =
105     SLIST_HEAD_INITIALIZER(visited_dirs);
106
107 /*
108  * While the whatis line is being formed, it is stored in whatis_proto.
109  * When finished, it is reformatted into whatis_final and then appended
110  * to whatis_lines.
111  */
112 static struct sbuf *whatis_proto;
113 static struct sbuf *whatis_final;
114 static StringList *whatis_lines;        /* collected output lines */
115
116 static char tmp_file[MAXPATHLEN];       /* path of temporary file, if any */
117
118 /* A set of possible names for the NAME man page section */
119 static const char *name_section_titles[] = {
120         "NAME", "Name", "NAMN", "BEZEICHNUNG", "\xcc\xbe\xbe\xce",
121         "\xee\xe1\xfa\xf7\xe1\xee\xe9\xe5", NULL
122 };
123
124 /* A subset of the mdoc(7) commands to ignore */
125 static char mdoc_commands[] = "ArDvErEvFlLiNmPa";
126
127 /*
128  * Frees a struct page_info and its content.
129  */
130 static void
131 free_page_info(struct page_info *info)
132 {
133         free(info->filename);
134         free(info->name);
135         free(info->suffix);
136         free(info);
137 }
138
139 /*
140  * Allocates and fills in a new struct page_info given the
141  * name of the man section directory and the dirent of the file.
142  * If the file is not a man page, returns NULL.
143  */
144 static struct page_info *
145 new_page_info(char *dir, struct dirent *dirent)
146 {
147         struct page_info *info;
148         int basename_length;
149         char *suffix;
150         struct stat st;
151
152         info = (struct page_info *) malloc(sizeof(struct page_info));
153         if (info == NULL)
154                 err(1, "malloc");
155         basename_length = strlen(dirent->d_name);
156         suffix = &dirent->d_name[basename_length];
157         asprintf(&info->filename, "%s/%s", dir, dirent->d_name);
158         if ((info->gzipped = basename_length >= 4 && strcmp(&dirent->d_name[basename_length - 3], ".gz") == 0)) {
159                 suffix -= 3;
160                 *suffix = '\0';
161         }
162         for (;;) {
163                 if (--suffix == dirent->d_name || !isalnum(*suffix)) {
164                         if (*suffix == '.')
165                                 break;
166                         if (verbose)
167                                 warnx("%s: invalid man page name", info->filename);
168                         free(info->filename);
169                         free(info);
170                         return NULL;
171                 }
172         }
173         *suffix++ = '\0';
174         info->name = strdup(dirent->d_name);
175         info->suffix = strdup(suffix);
176         if (stat(info->filename, &st) < 0) {
177                 warn("%s", info->filename);
178                 free_page_info(info);
179                 return NULL;
180         }
181         if (!S_ISREG(st.st_mode)) {
182                 if (verbose && !S_ISDIR(st.st_mode))
183                         warnx("%s: not a regular file", info->filename);
184                 free_page_info(info);
185                 return NULL;
186         }
187         info->inode = st.st_ino;
188         return info;
189 }
190
191 /*
192  * Reset an sbuf's length to 0.
193  */
194 static void
195 sbuf_clear(struct sbuf *sbuf)
196 {
197         sbuf->end = sbuf->content;
198 }
199
200 /*
201  * Allocate a new sbuf.
202  */
203 static struct sbuf *
204 new_sbuf(void)
205 {
206         struct sbuf *sbuf = (struct sbuf *) malloc(sizeof(struct sbuf));
207         sbuf->content = (char *) malloc(LINE_ALLOC);
208         sbuf->last = sbuf->content + LINE_ALLOC - 1;
209         sbuf_clear(sbuf);
210         return sbuf;
211 }
212
213 /*
214  * Ensure that there is enough room in the sbuf for nchars more characters.
215  */
216 static void
217 sbuf_need(struct sbuf *sbuf, int nchars)
218 {
219         char *new_content;
220         size_t size, cntsize;
221
222         /* double the size of the allocation until the buffer is big enough */
223         while (sbuf->end + nchars > sbuf->last) {
224                 size = sbuf->last + 1 - sbuf->content;
225                 size *= 2;
226                 cntsize = sbuf->end - sbuf->content;
227
228                 new_content = (char *)malloc(size);
229                 memcpy(new_content, sbuf->content, cntsize);
230                 free(sbuf->content);
231                 sbuf->content = new_content;
232                 sbuf->end = new_content + cntsize;
233                 sbuf->last = new_content + size - 1;
234         }
235 }
236
237 /*
238  * Appends a string of a given length to the sbuf.
239  */
240 static void
241 sbuf_append(struct sbuf *sbuf, const char *text, int length)
242 {
243         if (length > 0) {
244                 sbuf_need(sbuf, length);
245                 memcpy(sbuf->end, text, length);
246                 sbuf->end += length;
247         }
248 }
249
250 /*
251  * Appends a null-terminated string to the sbuf.
252  */
253 static void
254 sbuf_append_str(struct sbuf *sbuf, char *text)
255 {
256         sbuf_append(sbuf, text, strlen(text));
257 }
258
259 /*
260  * Appends an edited null-terminated string to the sbuf.
261  */
262 static void
263 sbuf_append_edited(struct sbuf *sbuf, char *text, edited_copy copy)
264 {
265         int length = strlen(text);
266         if (length > 0) {
267                 sbuf_need(sbuf, length);
268                 sbuf->end = copy(text, sbuf->end, length);
269         }
270 }
271
272 /*
273  * Strips any of a set of chars from the end of the sbuf.
274  */
275 static void
276 sbuf_strip(struct sbuf *sbuf, const char *set)
277 {
278         while (sbuf->end > sbuf->content && strchr(set, sbuf->end[-1]) != NULL)
279                 sbuf->end--;
280 }
281
282 /*
283  * Returns the null-terminated string built by the sbuf.
284  */
285 static char *
286 sbuf_content(struct sbuf *sbuf)
287 {
288         *sbuf->end = '\0';
289         return sbuf->content;
290 }
291
292 /*
293  * Returns true if no man page exists in the directory with
294  * any of the names in the StringList.
295  */
296 static int
297 no_page_exists(char *dir, StringList *names, char *suffix)
298 {
299         char path[MAXPATHLEN];
300         size_t i;
301
302         for (i = 0; i < names->sl_cur; i++) {
303                 snprintf(path, sizeof path, "%s/%s.%s.gz", dir, names->sl_str[i], suffix);
304                 if (access(path, F_OK) < 0) {
305                         path[strlen(path) - 3] = '\0';
306                         if (access(path, F_OK) < 0)
307                                 continue;
308                 }
309                 return 0;
310         }
311         return 1;
312 }
313
314 static void
315 trap_signal(int sig __unused)
316 {
317         if (tmp_file[0] != '\0')
318                 unlink(tmp_file);
319         exit(1);
320 }
321
322 /*
323  * Attempts to open an output file.  Returns NULL if unsuccessful.
324  */
325 static FILE *
326 open_output(char *name)
327 {
328         FILE *output;
329
330         whatis_lines = sl_init();
331         if (append) {
332                 char line[LINE_ALLOC];
333
334                 output = fopen(name, "r");
335                 if (output == NULL) {
336                         warn("%s", name);
337                         exit_code = 1;
338                         return NULL;
339                 }
340                 while (fgets(line, sizeof line, output) != NULL) {
341                         line[strlen(line) - 1] = '\0';
342                         sl_add(whatis_lines, strdup(line));
343                 }
344         }
345         if (common_output == NULL) {
346                 snprintf(tmp_file, sizeof tmp_file, "%s.tmp", name);
347                 name = tmp_file;
348         }
349         output = fopen(name, "w");
350         if (output == NULL) {
351                 warn("%s", name);
352                 exit_code = 1;
353                 return NULL;
354         }
355         return output;
356 }
357
358 static int
359 linesort(const void *a, const void *b)
360 {
361         return strcmp((*(const char * const *)a), (*(const char * const *)b));
362 }
363
364 /*
365  * Writes the unique sorted lines to the output file.
366  */
367 static void
368 finish_output(FILE *output, char *name)
369 {
370         size_t i;
371         char *prev = NULL;
372
373         qsort(whatis_lines->sl_str, whatis_lines->sl_cur, sizeof(char *), linesort);
374         for (i = 0; i < whatis_lines->sl_cur; i++) {
375                 char *line = whatis_lines->sl_str[i];
376                 if (i > 0 && strcmp(line, prev) == 0)
377                         continue;
378                 prev = line;
379                 fputs(line, output);
380                 putc('\n', output);
381         }
382         fclose(output);
383         sl_free(whatis_lines, 1);
384         if (common_output == NULL) {
385                 rename(tmp_file, name);
386                 unlink(tmp_file);
387         }
388 }
389
390 static FILE *
391 open_whatis(char *mandir)
392 {
393         char filename[MAXPATHLEN];
394
395         snprintf(filename, sizeof filename, "%s/%s", mandir, whatis_name);
396         return open_output(filename);
397 }
398
399 static void
400 finish_whatis(FILE *output, char *mandir)
401 {
402         char filename[MAXPATHLEN];
403
404         snprintf(filename, sizeof filename, "%s/%s", mandir, whatis_name);
405         finish_output(output, filename);
406 }
407
408 /*
409  * Tests to see if the given directory has already been visited.
410  */
411 static int
412 already_visited(char *dir)
413 {
414         struct stat st;
415         struct visited_dir *visit;
416
417         if (stat(dir, &st) < 0) {
418                 warn("%s", dir);
419                 exit_code = 1;
420                 return 1;
421         }
422         SLIST_FOREACH(visit, &visited_dirs, next) {
423                 if (visit->inode == st.st_ino &&
424                     visit->device == st.st_dev) {
425                         warnx("already visited %s", dir);
426                         return 1;
427                 }
428         }
429         visit = (struct visited_dir *) malloc(sizeof(struct visited_dir));
430         visit->device = st.st_dev;
431         visit->inode = st.st_ino;
432         SLIST_INSERT_HEAD(&visited_dirs, visit, next);
433         return 0;
434 }
435
436 /*
437  * Removes trailing spaces from a string, returning a pointer to just
438  * beyond the new last character.
439  */
440 static char *
441 trim_rhs(char *str)
442 {
443         char *rhs = &str[strlen(str)];
444         while (--rhs > str && isspace(*rhs))
445                 ;
446         *++rhs = '\0';
447         return rhs;
448 }
449
450 /*
451  * Returns a pointer to the next non-space character in the string.
452  */
453 static char *
454 skip_spaces(char *s)
455 {
456         while (*s != '\0' && isspace(*s))
457                 s++;
458         return s;
459 }
460
461 /*
462  * Returns whether the string contains only digits.
463  */
464 static int
465 only_digits(char *line)
466 {
467         if (!isdigit(*line++))
468                 return 0;
469         while (isdigit(*line))
470                 line++;
471         return *line == '\0';
472 }
473
474 /*
475  * Returns whether the line is of one of the forms:
476  *      .Sh NAME
477  *      .Sh "NAME"
478  *      etc.
479  * assuming that section_start is ".Sh".
480  */
481 static int
482 name_section_line(char *line, const char *section_start)
483 {
484         char *rhs;
485         const char **title;
486
487         if (strncmp(line, section_start, 3) != 0)
488                 return 0;
489         line = skip_spaces(line + 3);
490         rhs = trim_rhs(line);
491         if (*line == '"') {
492                 line++;
493                 if (*--rhs == '"')
494                         *rhs = '\0';
495         }
496         for (title = name_section_titles; *title != NULL; title++)
497                 if (strcmp(*title, line) == 0)
498                         return 1;
499         return 0;
500 }
501
502 /*
503  * Copies characters while removing the most common nroff/troff
504  * markup:
505  *      \(em, \(mi, \s[+-N], \&
506  *      \fF, \f(fo, \f[font]
507  *      \*s, \*(st, \*[stringvar]
508  */
509 static char *
510 de_nroff_copy(char *from, char *to, int fromlen)
511 {
512         char *from_end = &from[fromlen];
513         while (from < from_end) {
514                 switch (*from) {
515                 case '\\':
516                         switch (*++from) {
517                         case '(':
518                                 if (strncmp(&from[1], "em", 2) == 0 ||
519                                                 strncmp(&from[1], "mi", 2) == 0) {
520                                         from += 3;
521                                         continue;
522                                 }
523                                 break;
524                         case 's':
525                                 if (*++from == '-')
526                                         from++;
527                                 while (isdigit(*from))
528                                         from++;
529                                 continue;
530                         case 'f':
531                         case '*':
532                                 if (*++from == '(')
533                                         from += 3;
534                                 else if (*from == '[') {
535                                         while (*++from != ']' && from < from_end);
536                                         from++;
537                                 } else
538                                         from++;
539                                 continue;
540                         case '&':
541                                 from++;
542                                 continue;
543                         }
544                         break;
545                 }
546                 *to++ = *from++;
547         }
548         return to;
549 }
550
551 /*
552  * Appends a string with the nroff formatting removed.
553  */
554 static void
555 add_nroff(char *text)
556 {
557         sbuf_append_edited(whatis_proto, text, de_nroff_copy);
558 }
559
560 /*
561  * Appends "name(suffix), " to whatis_final.
562  */
563 static void
564 add_whatis_name(char *name, char *suffix)
565 {
566         if (*name != '\0') {
567                 sbuf_append_str(whatis_final, name);
568                 sbuf_append(whatis_final, "(", 1);
569                 sbuf_append_str(whatis_final, suffix);
570                 sbuf_append(whatis_final, "), ", 3);
571         }
572 }
573
574 /*
575  * Processes an old-style man(7) line.  This ignores commands with only
576  * a single number argument.
577  */
578 static void
579 process_man_line(char *line)
580 {
581         if (*line == '.') {
582                 while (isalpha(*++line))
583                         ;
584                 line = skip_spaces(line);
585                 if (only_digits(line))
586                         return;
587         } else
588                 line = skip_spaces(line);
589         if (*line != '\0') {
590                 add_nroff(line);
591                 sbuf_append(whatis_proto, " ", 1);
592         }
593 }
594
595 /*
596  * Processes a new-style mdoc(7) line.
597  */
598 static void
599 process_mdoc_line(char *line)
600 {
601         int xref;
602         int arg = 0;
603         char *line_end = &line[strlen(line)];
604         int orig_length = sbuf_length(whatis_proto);
605         char *next;
606
607         if (*line == '\0')
608                 return;
609         if (line[0] != '.' || !isupper(line[1]) || !islower(line[2])) {
610                 add_nroff(skip_spaces(line));
611                 sbuf_append(whatis_proto, " ", 1);
612                 return;
613         }
614         xref = strncmp(line, ".Xr", 3) == 0;
615         line += 3;
616         while ((line = skip_spaces(line)) < line_end) {
617                 if (*line == '"') {
618                         next = ++line;
619                         for (;;) {
620                                 next = strchr(next, '"');
621                                 if (next == NULL)
622                                         break;
623                                 memmove(next, next + 1, strlen(next));
624                                 line_end--;
625                                 if (*next != '"')
626                                         break;
627                                 next++;
628                         }
629                 } else
630                         next = strpbrk(line, " \t");
631                 if (next != NULL)
632                         *next++ = '\0';
633                 else
634                         next = line_end;
635                 if (isupper(*line) && islower(line[1]) && line[2] == '\0') {
636                         if (strcmp(line, "Ns") == 0) {
637                                 arg = 0;
638                                 line = next;
639                                 continue;
640                         }
641                         if (strstr(mdoc_commands, line) != NULL) {
642                                 line = next;
643                                 continue;
644                         }
645                 }
646                 if (arg > 0 && strchr(",.:;?!)]", *line) == 0) {
647                         if (xref) {
648                                 sbuf_append(whatis_proto, "(", 1);
649                                 add_nroff(line);
650                                 sbuf_append(whatis_proto, ")", 1);
651                                 xref = 0;
652                                 line = blank;
653                         } else
654                                 sbuf_append(whatis_proto, " ", 1);
655                 }
656                 add_nroff(line);
657                 arg++;
658                 line = next;
659         }
660         if (sbuf_length(whatis_proto) > orig_length)
661                 sbuf_append(whatis_proto, " ", 1);
662 }
663
664 /*
665  * Collects a list of comma-separated names from the text.
666  */
667 static void
668 collect_names(StringList *names, char *text)
669 {
670         char *arg;
671
672         for (;;) {
673                 arg = text;
674                 text = strchr(text, ',');
675                 if (text != NULL)
676                         *text++ = '\0';
677                 sl_add(names, arg);
678                 if (text == NULL)
679                         return;
680                 if (*text == ' ')
681                         text++;
682         }
683 }
684
685 enum { STATE_UNKNOWN, STATE_MANSTYLE, STATE_MDOCNAME, STATE_MDOCDESC };
686
687 /*
688  * Processes a man page source into a single whatis line and adds it
689  * to whatis_lines.
690  */
691 static void
692 process_page(struct page_info *page, char *section_dir)
693 {
694         gzFile *in;
695         char buffer[4096];
696         char *line;
697         StringList *names;
698         char *descr;
699         int state = STATE_UNKNOWN;
700         size_t i;
701
702         sbuf_clear(whatis_proto);
703         if ((in = gzopen(page->filename, "r")) == NULL) {
704                 warn("%s", page->filename);
705                 exit_code = 1;
706                 return;
707         }
708         while (gzgets(in, buffer, sizeof buffer) != NULL) {
709                 line = buffer;
710                 if (strncmp(line, ".\\\"", 3) == 0)             /* ignore comments */
711                         continue;
712                 switch (state) {
713                 /*
714                  * haven't reached the NAME section yet.
715                  */
716                 case STATE_UNKNOWN:
717                         if (name_section_line(line, ".SH"))
718                                 state = STATE_MANSTYLE;
719                         else if (name_section_line(line, ".Sh"))
720                                 state = STATE_MDOCNAME;
721                         continue;
722                 /*
723                  * Inside an old-style .SH NAME section.
724                  */
725                 case STATE_MANSTYLE:
726                         if (strncmp(line, ".SH", 3) == 0)
727                                 break;
728                         if (strncmp(line, ".SS", 3) == 0)
729                                 break;
730                         trim_rhs(line);
731                         if (strcmp(line, ".") == 0)
732                                 continue;
733                         if (strncmp(line, ".IX", 3) == 0) {
734                                 line += 3;
735                                 line = skip_spaces(line);
736                         }
737                         process_man_line(line);
738                         continue;
739                 /*
740                  * Inside a new-style .Sh NAME section (the .Nm part).
741                  */
742                 case STATE_MDOCNAME:
743                         trim_rhs(line);
744                         if (strncmp(line, ".Nm", 3) == 0) {
745                                 process_mdoc_line(line);
746                                 continue;
747                         } else {
748                                 if (strcmp(line, ".") == 0)
749                                         continue;
750                                 sbuf_append(whatis_proto, "- ", 2);
751                                 state = STATE_MDOCDESC;
752                         }
753                         /* fall through */
754                 /*
755                  * Inside a new-style .Sh NAME section (after the .Nm-s).
756                  */
757                 case STATE_MDOCDESC:
758                         if (strncmp(line, ".Sh", 3) == 0)
759                                 break;
760                         trim_rhs(line);
761                         if (strcmp(line, ".") == 0)
762                                 continue;
763                         process_mdoc_line(line);
764                         continue;
765                 }
766                 break;
767         }
768         gzclose(in);
769         sbuf_strip(whatis_proto, " \t.-");
770         line = sbuf_content(whatis_proto);
771         /*
772          * line now contains the appropriate data, but without
773          * the proper indentation or the section appended to each name.
774          */
775         descr = strstr(line, " - ");
776         if (descr == NULL) {
777                 descr = strchr(line, ' ');
778                 if (descr == NULL) {
779                         if (verbose)
780                                 fprintf(stderr, "       ignoring junk description \"%s\"\n", line);
781                         return;
782                 }
783                 *descr++ = '\0';
784         } else {
785                 *descr = '\0';
786                 descr += 3;
787         }
788         names = sl_init();
789         collect_names(names, line);
790         sbuf_clear(whatis_final);
791         if (!sl_find(names, page->name) && no_page_exists(section_dir, names, page->suffix)) {
792                 /*
793                  * Add the page name since that's the only thing that
794                  * man(1) will find.
795                  */
796                 add_whatis_name(page->name, page->suffix);
797         }
798         for (i = 0; i < names->sl_cur; i++)
799                 add_whatis_name(names->sl_str[i], page->suffix);
800         sl_free(names, 0);
801         sbuf_retract(whatis_final, 2);          /* remove last ", " */
802         while (sbuf_length(whatis_final) < indent)
803                 sbuf_append(whatis_final, " ", 1);
804         sbuf_append(whatis_final, " - ", 3);
805         sbuf_append_str(whatis_final, skip_spaces(descr));
806         sl_add(whatis_lines, strdup(sbuf_content(whatis_final)));
807 }
808
809 /*
810  * Sorts pages first by inode number, then by name.
811  */
812 static int
813 pagesort(const void *a, const void *b)
814 {
815         const struct page_info *p1 = *(struct page_info * const *) a;
816         const struct page_info *p2 = *(struct page_info * const *) b;
817         if (p1->inode == p2->inode)
818                 return strcmp(p1->name, p2->name);
819         return p1->inode - p2->inode;
820 }
821
822 /*
823  * Processes a single man section.
824  */
825 static void
826 process_section(char *section_dir)
827 {
828         struct dirent **entries;
829         int nentries;
830         struct page_info **pages;
831         int npages = 0;
832         int i;
833         ino_t prev_inode = 0;
834
835         if (verbose)
836                 fprintf(stderr, "  %s\n", section_dir);
837
838         /*
839          * scan the man section directory for pages
840          */
841         nentries = scandir(section_dir, &entries, NULL, alphasort);
842         if (nentries < 0) {
843                 warn("%s", section_dir);
844                 exit_code = 1;
845                 return;
846         }
847         /*
848          * collect information about man pages
849          */
850         pages = (struct page_info **) calloc(nentries, sizeof(struct page_info *));
851         for (i = 0; i < nentries; i++) {
852                 struct page_info *info = new_page_info(section_dir, entries[i]);
853                 if (info != NULL)
854                         pages[npages++] = info;
855                 free(entries[i]);
856         }
857         free(entries);
858         qsort(pages, npages, sizeof(struct page_info *), pagesort);
859         /*
860          * process each unique page
861          */
862         for (i = 0; i < npages; i++) {
863                 struct page_info *page = pages[i];
864                 if (page->inode != prev_inode) {
865                         prev_inode = page->inode;
866                         if (verbose)
867                                 fprintf(stderr, "       reading %s\n", page->filename);
868                         process_page(page, section_dir);
869                 } else if (verbose)
870                         fprintf(stderr, "       skipping %s, duplicate\n", page->filename);
871                 free_page_info(page);
872         }
873         free(pages);
874 }
875
876 /*
877  * Returns whether the directory entry is a man page section.
878  */
879 static int
880 select_sections(struct dirent *entry)
881 {
882         char *p = &entry->d_name[3];
883
884         if (strncmp(entry->d_name, "man", 3) != 0)
885                 return 0;
886         while (*p != '\0') {
887                 if (!isalnum(*p++))
888                         return 0;
889         }
890         return 1;
891 }
892
893 /*
894  * Processes a single top-level man directory by finding all the
895  * sub-directories named man* and processing each one in turn.
896  */
897 static void
898 process_mandir(char *dir_name)
899 {
900         struct dirent **entries;
901         int nsections;
902         FILE *fp = NULL;
903         int i;
904         struct stat st;
905
906         if (already_visited(dir_name))
907                 return;
908         if (verbose)
909                 fprintf(stderr, "man directory %s\n", dir_name);
910         nsections = scandir(dir_name, &entries, select_sections, alphasort);
911         if (nsections < 0) {
912                 warn("%s", dir_name);
913                 exit_code = 1;
914                 return;
915         }
916         if (common_output == NULL && (fp = open_whatis(dir_name)) == NULL)
917                 return;
918         for (i = 0; i < nsections; i++) {
919                 char section_dir[MAXPATHLEN];
920                 snprintf(section_dir, sizeof section_dir, "%s/%s", dir_name, entries[i]->d_name);
921                 process_section(section_dir);
922                 snprintf(section_dir, sizeof section_dir, "%s/%s/%s", dir_name,
923                     entries[i]->d_name, machine);
924                 if (stat(section_dir, &st) == 0 && S_ISDIR(st.st_mode))
925                         process_section(section_dir);
926                 free(entries[i]);
927         }
928         free(entries);
929         if (common_output == NULL)
930                 finish_whatis(fp, dir_name);
931 }
932
933 /*
934  * Processes one argument, which may be a colon-separated list of
935  * directories.
936  */
937 static void
938 process_argument(const char *arg)
939 {
940         char *dir;
941         char *mandir;
942         char *parg;
943
944         parg = strdup(arg);
945         if (parg == NULL)
946                 err(1, "out of memory");
947         while ((dir = strsep(&parg, ":")) != NULL) {
948                 if (locale != NULL) {
949                         asprintf(&mandir, "%s/%s", dir, locale);
950                         process_mandir(mandir);
951                         free(mandir);
952                         if (lang_locale != NULL) {
953                                 asprintf(&mandir, "%s/%s", dir, lang_locale);
954                                 process_mandir(mandir);
955                                 free(mandir);
956                         }
957                 } else {
958                         process_mandir(dir);
959                 }
960         }
961         free(parg);
962 }
963
964
965 int
966 main(int argc, char **argv)
967 {
968         int opt;
969         FILE *fp = NULL;
970
971         while ((opt = getopt(argc, argv, "ai:n:o:vL")) != -1) {
972                 switch (opt) {
973                 case 'a':
974                         append++;
975                         break;
976                 case 'i':
977                         indent = atoi(optarg);
978                         break;
979                 case 'n':
980                         whatis_name = optarg;
981                         break;
982                 case 'o':
983                         common_output = optarg;
984                         break;
985                 case 'v':
986                         verbose++;
987                         break;
988                 case 'L':
989                         locale = getenv("LC_ALL");
990                         if (locale == NULL)
991                                 locale = getenv("LC_CTYPE");
992                         if (locale == NULL)
993                                 locale = getenv("LANG");
994                         if (locale != NULL) {
995                                 char *sep = strchr(locale, '_');
996                                 if (sep != NULL && isupper(sep[1]) &&
997                                     isupper(sep[2])) {
998                                         asprintf(&lang_locale, "%.*s%s", sep - locale, locale, &sep[3]);
999                                 }
1000                         }
1001                         break;
1002                 default:
1003                         fprintf(stderr, "usage: %s [-a] [-i indent] [-n name] [-o output_file] [-v] [-L] [directories...]\n", argv[0]);
1004                         exit(1);
1005                 }
1006         }
1007
1008         signal(SIGINT, trap_signal);
1009         signal(SIGHUP, trap_signal);
1010         signal(SIGQUIT, trap_signal);
1011         signal(SIGTERM, trap_signal);
1012         SLIST_INIT(&visited_dirs);
1013         whatis_proto = new_sbuf();
1014         whatis_final = new_sbuf();
1015
1016         if ((machine = getenv("MACHINE")) == NULL)
1017                 machine = MACHINE;
1018
1019         if (common_output != NULL && (fp = open_output(common_output)) == NULL)
1020                 err(1, "%s", common_output);
1021         if (optind == argc) {
1022                 const char *manpath = getenv("MANPATH");
1023                 if (manpath == NULL)
1024                         manpath = DEFAULT_MANPATH;
1025                 process_argument(manpath);
1026         } else {
1027                 while (optind < argc)
1028                         process_argument(argv[optind++]);
1029         }
1030         if (common_output != NULL)
1031                 finish_output(fp, common_output);
1032         exit(exit_code);
1033 }