932f0b79447d51b2a2e88fc95fc8e86b1475c878
[oweals/busybox.git] / miscutils / man.c
1 /* mini man implementation for busybox
2  * Copyright (C) 2008 Denys Vlasenko <vda.linux@googlemail.com>
3  * Licensed under GPLv2, see file LICENSE in this source tree.
4  */
5
6 //usage:#define man_trivial_usage
7 //usage:       "[-aw] [MANPAGE]..."
8 //usage:#define man_full_usage "\n\n"
9 //usage:       "Format and display manual page\n"
10 //usage:     "\n        -a      Display all pages"
11 //usage:     "\n        -w      Show page locations"
12 //usage:     "\n"
13 //usage:     "\n$COLUMNS overrides output width"
14
15 #include "libbb.h"
16 #include "common_bufsiz.h"
17
18 enum {
19         OPT_a = 1, /* all */
20         OPT_w = 2, /* print path */
21 };
22
23 /* This is what I see on my desktop system being executed:
24 (
25 echo ".ll 12.4i"
26 echo ".nr LL 12.4i"
27 echo ".pl 1100i"
28 gunzip -c '/usr/man/man1/bzip2.1.gz'
29 echo ".\\\""
30 echo ".pl \n(nlu+10"
31 ) | gtbl | nroff -Tlatin1 -mandoc | less
32
33 Some systems use -Tascii.
34
35 On another system I see this:
36
37 ... | tbl | nroff -mandoc -rLL=<NNN>n -rLT=<NNN>n -Tutf8 | less
38
39 where <NNN> is screen width minus 5.
40 Replacing "DEFINE nroff nroff -mandoc" in /etc/man_db.conf
41 changes "nroff -mandoc" part; -rLL=<NNN>n, -rLT=<NNN>n and -Tutf8 parts are
42 appended to the user-specified command.
43
44 Redirecting to a pipe or file sets GROFF_NO_SGR=1 to prevent color escapes,
45 and uses "col -b -p -x" instead of pager, this filters out backspace
46 and underscore tricks.
47 */
48
49 struct globals {
50         const char *col;
51         const char *tbl;
52         const char *nroff;
53         const char *pager;
54 } FIX_ALIASING;
55 #define G (*(struct globals*)bb_common_bufsiz1)
56 #define INIT_G() do { \
57         setup_common_bufsiz(); \
58         G.col = "col"; \
59         G.tbl = "tbl"; \
60         /* Removed -Tlatin1. Assuming system nroff has suitable default */ \
61         G.nroff = "nroff -mandoc"; \
62         G.pager = ENABLE_LESS ? "less" : "more"; \
63 } while (0)
64
65 static int show_manpage(char *man_filename, int man, int level);
66
67 static int run_pipe(char *man_filename, int man, int level)
68 {
69         char *cmd;
70
71         /* Prevent man page link loops */
72         if (level > 10)
73                 return 0;
74
75         if (access(man_filename, R_OK) != 0)
76                 return 0;
77
78         if (option_mask32 & OPT_w) {
79                 puts(man_filename);
80                 return 1;
81         }
82
83         if (man) { /* man page, not cat page */
84                 /* Is this a link to another manpage? */
85                 /* The link has the following on the first line: */
86                 /* ".so another_man_page" */
87
88                 struct stat sb;
89                 char *line;
90                 char *linkname, *p;
91
92                 /* On my system:
93                  * man1/genhostid.1.gz: 203 bytes - smallest real manpage
94                  * man2/path_resolution.2.gz: 114 bytes - largest link
95                  */
96                 xstat(man_filename, &sb);
97                 if (sb.st_size > 300) /* err on the safe side */
98                         goto ordinary_manpage;
99
100                 line = xmalloc_open_zipped_read_close(man_filename, NULL);
101                 if (!line || !is_prefixed_with(line, ".so ")) {
102                         free(line);
103                         goto ordinary_manpage;
104                 }
105                 /* Example: man2/path_resolution.2.gz contains
106                  * ".so man7/path_resolution.7\n<junk>"
107                  */
108                 *strchrnul(line, '\n') = '\0';
109                 linkname = skip_whitespace(&line[4]);
110
111                 /* If link has no slashes, we just replace man page name.
112                  * If link has slashes (however many), we go back *once*.
113                  * ".so zzz/ggg/page.3" does NOT go back two levels. */
114                 p = strrchr(man_filename, '/');
115                 if (!p)
116                         goto ordinary_manpage;
117                 *p = '\0';
118                 if (strchr(linkname, '/')) {
119                         p = strrchr(man_filename, '/');
120                         if (!p)
121                                 goto ordinary_manpage;
122                         *p = '\0';
123                 }
124
125                 /* Links do not have .gz extensions, even if manpage
126                  * is compressed */
127                 man_filename = xasprintf("%s/%s", man_filename, linkname);
128                 free(line);
129                 /* Note: we leak "new" man_filename string as well... */
130                 if (show_manpage(man_filename, man, level + 1))
131                         return 1;
132                 /* else: show the link, it's better than nothing */
133         }
134
135  ordinary_manpage:
136         close(STDIN_FILENO);
137         open_zipped(man_filename, /*fail_if_not_compressed:*/ 0); /* guaranteed to use fd 0 (STDIN_FILENO) */
138         if (man) {
139                 int w = get_terminal_width(-1);
140                 if (w > 10)
141                         w -= 2;
142                 /* "2>&1" is added so that nroff errors are shown in pager too.
143                  * Otherwise it may show just empty screen.
144                  */
145                 cmd = xasprintf("%s | %s -rLL=%un -rLT=%un 2>&1 | %s",
146                                 G.tbl, G.nroff, w, w,
147                                 G.pager);
148         } else {
149                 cmd = xstrdup(G.pager);
150         }
151         system(cmd);
152         free(cmd);
153         return 1;
154 }
155
156 /* man_filename is of the form "/dir/dir/dir/name.s" */
157 static int show_manpage(char *man_filename, int man, int level)
158 {
159 #if SEAMLESS_COMPRESSION
160         /* We leak this allocation... */
161         char *filename_with_zext = xasprintf("%s.lzma", man_filename);
162         char *ext = strrchr(filename_with_zext, '.') + 1;
163 #endif
164
165 #if ENABLE_FEATURE_SEAMLESS_LZMA
166         if (run_pipe(filename_with_zext, man, level))
167                 return 1;
168 #endif
169 #if ENABLE_FEATURE_SEAMLESS_XZ
170         strcpy(ext, "xz");
171         if (run_pipe(filename_with_zext, man, level))
172                 return 1;
173 #endif
174 #if ENABLE_FEATURE_SEAMLESS_BZ2
175         strcpy(ext, "bz2");
176         if (run_pipe(filename_with_zext, man, level))
177                 return 1;
178 #endif
179 #if ENABLE_FEATURE_SEAMLESS_GZ
180         strcpy(ext, "gz");
181         if (run_pipe(filename_with_zext, man, level))
182                 return 1;
183 #endif
184
185         return run_pipe(man_filename, man, level);
186 }
187
188 static char **add_MANPATH(char **man_path_list, int *count_mp, char *path)
189 {
190         if (path) while (*path) {
191                 char *next_path;
192                 char **path_element;
193
194                 next_path = strchr(path, ':');
195                 if (next_path) {
196                         if (next_path == path) /* "::"? */
197                                 goto next;
198                         *next_path = '\0';
199                 }
200                 /* Do we already have path? */
201                 path_element = man_path_list;
202                 if (path_element) while (*path_element) {
203                         if (strcmp(*path_element, path) == 0)
204                                 goto skip;
205                         path_element++;
206                 }
207                 man_path_list = xrealloc_vector(man_path_list, 4, *count_mp);
208                 man_path_list[*count_mp] = xstrdup(path);
209                 (*count_mp)++;
210                 /* man_path_list is NULL terminated */
211                 /* man_path_list[*count_mp] = NULL; - xrealloc_vector did it */
212  skip:
213                 if (!next_path)
214                         break;
215                 /* "path" may be a result of getenv(), be nice and don't mangle it */
216                 *next_path = ':';
217  next:
218                 path = next_path + 1;
219         }
220         return man_path_list;
221 }
222
223 static const char *if_redefined(const char *var, const char *key, const char *line)
224 {
225         if (!is_prefixed_with(line, key))
226                 return var;
227         line += strlen(key);
228         if (!isspace(line[0]))
229                 return var;
230         return xstrdup(skip_whitespace(line));
231 }
232
233 int man_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
234 int man_main(int argc UNUSED_PARAM, char **argv)
235 {
236         parser_t *parser;
237         char *sec_list;
238         char *cur_path, *cur_sect;
239         char **man_path_list;
240         int count_mp;
241         int cur_mp;
242         int opt, not_found;
243         char *token[2];
244
245         INIT_G();
246
247         opt_complementary = "-1"; /* at least one argument */
248         opt = getopt32(argv, "+aw");
249         argv += optind;
250
251         sec_list = xstrdup("0p:1:1p:2:3:3p:4:5:6:7:8:9");
252
253         count_mp = 0;
254         man_path_list = add_MANPATH(NULL, &count_mp,
255                         getenv("MANDATORY_MANPATH"+10) /* "MANPATH" */
256         );
257         if (!man_path_list) {
258                 /* default, may be overridden by /etc/man.conf */
259                 man_path_list = xzalloc(2 * sizeof(man_path_list[0]));
260                 man_path_list[0] = (char*)"/usr/man";
261                 /* count_mp stays 0.
262                  * Thus, man.conf will overwrite man_path_list[0]
263                  * if a path is defined there.
264                  */
265         }
266
267         /* Parse man.conf[ig] or man_db.conf */
268         /* man version 1.6f uses man.config */
269         /* man-db implementation of man uses man_db.conf */
270         parser = config_open2("/etc/man.config", fopen_for_read);
271         if (!parser)
272                 parser = config_open2("/etc/man.conf", fopen_for_read);
273         if (!parser)
274                 parser = config_open2("/etc/man_db.conf", fopen_for_read);
275
276         while (config_read(parser, token, 2, 0, "# \t", PARSE_NORMAL)) {
277                 if (!token[1])
278                         continue;
279                 if (strcmp("DEFINE", token[0]) == 0) {
280                         G.col   = if_redefined(G.tbl  , "col",   token[1]);
281                         G.tbl   = if_redefined(G.tbl  , "tbl",   token[1]);
282                         G.nroff = if_redefined(G.nroff, "nroff", token[1]);
283                         G.pager = if_redefined(G.pager, "pager", token[1]);
284                 } else
285                 if (strcmp("MANDATORY_MANPATH"+10, token[0]) == 0 /* "MANPATH"? */
286                  || strcmp("MANDATORY_MANPATH", token[0]) == 0
287                 ) {
288                         man_path_list = add_MANPATH(man_path_list, &count_mp, token[1]);
289                 }
290                 if (strcmp("MANSECT", token[0]) == 0) {
291                         free(sec_list);
292                         sec_list = xstrdup(token[1]);
293                 }
294         }
295         config_close(parser);
296
297         {
298                 /* environment overrides setting from man.config */
299                 char *env_pager = getenv("MANPAGER");
300                 if (!env_pager)
301                         env_pager = getenv("PAGER");
302                 if (env_pager)
303                         G.pager = env_pager;
304         }
305
306         if (!isatty(STDOUT_FILENO)) {
307                 putenv((char*)"GROFF_NO_SGR=1");
308                 G.pager = xasprintf("%s -b -p -x", G.col);
309         }
310
311         not_found = 0;
312         do { /* for each argv[] */
313                 int found = 0;
314                 cur_mp = 0;
315
316                 if (strchr(*argv, '/')) {
317                         found = show_manpage(*argv, /*man:*/ 1, 0);
318                         goto check_found;
319                 }
320                 while ((cur_path = man_path_list[cur_mp++]) != NULL) {
321                         /* for each MANPATH */
322                         cur_sect = sec_list;
323                         do { /* for each section */
324                                 char *next_sect = strchrnul(cur_sect, ':');
325                                 int sect_len = next_sect - cur_sect;
326                                 char *man_filename;
327                                 int cat0man1 = 0;
328
329                                 /* Search for cat, then man page */
330                                 while (cat0man1 < 2) {
331                                         int found_here;
332                                         man_filename = xasprintf("%s/%s%.*s/%s.%.*s",
333                                                         cur_path,
334                                                         "cat\0man" + (cat0man1 * 4),
335                                                         sect_len, cur_sect,
336                                                         *argv,
337                                                         sect_len, cur_sect);
338                                         found_here = show_manpage(man_filename, cat0man1, 0);
339                                         found |= found_here;
340                                         cat0man1 += found_here + 1;
341                                         free(man_filename);
342                                 }
343
344                                 if (found && !(opt & OPT_a))
345                                         goto next_arg;
346                                 cur_sect = next_sect;
347                                 while (*cur_sect == ':')
348                                         cur_sect++;
349                         } while (*cur_sect);
350                 }
351  check_found:
352                 if (!found) {
353                         bb_error_msg("no manual entry for '%s'", *argv);
354                         not_found = 1;
355                 }
356  next_arg:
357                 argv++;
358         } while (*argv);
359
360         return not_found;
361 }