Merge from vendor branch CVS:
[dragonfly.git] / usr.bin / whereis / whereis.c
1 /*
2  * Copyright © 2002, Jörg Wunsch
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
17  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
21  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
22  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
23  * POSSIBILITY OF SUCH DAMAGE.
24  * $FreeBSD: src/usr.bin/whereis/whereis.c,v 1.12 2002/08/22 01:50:51 johan Exp $
25  * $DragonFly: src/usr.bin/whereis/whereis.c,v 1.2 2004/07/23 06:24:27 hmp Exp $
26  */
27
28 /*
29  * 4.3BSD UI-compatible whereis(1) utility.  Rewritten from scratch
30  * since the original 4.3BSD version suffers legal problems that
31  * prevent it from being redistributed, and since the 4.4BSD version
32  * was pretty inferior in functionality.
33  */
34
35 #include <sys/types.h>
36
37
38 #include <sys/stat.h>
39 #include <sys/sysctl.h>
40
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <locale.h>
45 #include <regex.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sysexits.h>
50 #include <unistd.h>
51
52 #include "pathnames.h"
53
54 #define NO_BIN_FOUND    1
55 #define NO_MAN_FOUND    2
56 #define NO_SRC_FOUND    4
57
58 typedef const char *ccharp;
59
60 int opt_a, opt_b, opt_m, opt_q, opt_s, opt_u, opt_x;
61 ccharp *bindirs, *mandirs, *sourcedirs;
62 char **query;
63
64 const char *sourcepath = PATH_SOURCES;
65
66 char    *colonify(ccharp *);
67 int      contains(ccharp *, const char *);
68 void     decolonify(char *, ccharp **, int *);
69 void     defaults(void);
70 void     scanopts(int, char **);
71 void     usage(void);
72
73 /*
74  * Throughout this program, a number of strings are dynamically
75  * allocated but never freed.  Their memory is written to when
76  * splitting the strings into string lists which will later be
77  * processed.  Since it's important that those string lists remain
78  * valid even after the functions allocating the memory returned,
79  * those functions cannot free them.  They could be freed only at end
80  * of main(), which is pretty pointless anyway.
81  *
82  * The overall amount of memory to be allocated for processing the
83  * strings is not expected to exceed a few kilobytes.  For that
84  * reason, allocation can usually always be assumed to succeed (within
85  * a virtual memory environment), thus we simply bail out using
86  * abort(3) in case of an allocation failure.
87  */
88
89 void
90 usage(void)
91 {
92         errx(EX_USAGE,
93              "usage: whereis [-abmqsux] [-BMS dir... -f] name ...");
94 }
95
96 /*
97  * Scan options passed to program.
98  *
99  * Note that the -B/-M/-S options expect a list of directory
100  * names that must be terminated with -f.
101  */
102 void
103 scanopts(int argc, char **argv)
104 {
105         int c, i, opt_f;
106         ccharp **dirlist;
107
108         opt_f = 0;
109         while ((c = getopt(argc, argv, "BMSabfmqsux")) != -1)
110                 switch (c) {
111                 case 'B':
112                         dirlist = &bindirs;
113                         goto dolist;
114
115                 case 'M':
116                         dirlist = &mandirs;
117                         goto dolist;
118
119                 case 'S':
120                         dirlist = &sourcedirs;
121                   dolist:
122                         i = 0;
123                         *dirlist = realloc(*dirlist, (i + 1) * sizeof(char *));
124                         (*dirlist)[i] = NULL;
125                         while (optind < argc &&
126                                strcmp(argv[optind], "-f") != 0 &&
127                                strcmp(argv[optind], "-B") != 0 &&
128                                strcmp(argv[optind], "-M") != 0 &&
129                                strcmp(argv[optind], "-S") != 0) {
130                                 decolonify(argv[optind], dirlist, &i);
131                                 optind++;
132                         }
133                         break;
134
135                 case 'a':
136                         opt_a = 1;
137                         break;
138
139                 case 'b':
140                         opt_b = 1;
141                         break;
142
143                 case 'f':
144                         goto breakout;
145
146                 case 'm':
147                         opt_m = 1;
148                         break;
149
150                 case 'q':
151                         opt_q = 1;
152                         break;
153
154                 case 's':
155                         opt_s = 1;
156                         break;
157
158                 case 'u':
159                         opt_u = 1;
160                         break;
161
162                 case 'x':
163                         opt_x = 1;
164                         break;
165
166                 default:
167                         usage();
168                 }
169   breakout:
170         if (optind == argc)
171                 usage();
172         query = argv + optind;
173 }
174
175 /*
176  * Find out whether string `s' is contained in list `cpp'.
177  */
178 int
179 contains(ccharp *cpp, const char *s)
180 {
181         ccharp cp;
182
183         if (cpp == NULL)
184                 return (0);
185
186         while ((cp = *cpp) != NULL) {
187                 if (strcmp(cp, s) == 0)
188                         return (1);
189                 cpp++;
190         }
191         return (0);
192 }
193
194 /*
195  * Split string `s' at colons, and pass it to the string list pointed
196  * to by `cppp' (which has `*ip' elements).  Note that the original
197  * string is modified by replacing the colon with a NUL byte.  The
198  * partial string is only added if it has a length greater than 0, and
199  * if it's not already contained in the string list.
200  */
201 void
202 decolonify(char *s, ccharp **cppp, int *ip)
203 {
204         char *cp;
205
206         while ((cp = strchr(s, ':')), *s != '\0') {
207                 if (cp)
208                         *cp = '\0';
209                 if (strlen(s) && !contains(*cppp, s)) {
210                         *cppp = realloc(*cppp, (*ip + 2) * sizeof(char *));
211                         if (cppp == NULL)
212                                 abort();
213                         (*cppp)[*ip] = s;
214                         (*cppp)[*ip + 1] = NULL;
215                         (*ip)++;
216                 }
217                 if (cp)
218                         s = cp + 1;
219                 else
220                         break;
221         }
222 }
223
224 /*
225  * Join string list `cpp' into a colon-separated string.
226  */
227 char *
228 colonify(ccharp *cpp)
229 {
230         size_t s;
231         char *cp;
232         int i;
233
234         if (cpp == NULL)
235                 return (0);
236
237         for (s = 0, i = 0; cpp[i] != NULL; i++)
238                 s += strlen(cpp[i]) + 1;
239         if ((cp = malloc(s + 1)) == NULL)
240                 abort();
241         for (i = 0, *cp = '\0'; cpp[i] != NULL; i++) {
242                 strcat(cp, cpp[i]);
243                 strcat(cp, ":");
244         }
245         cp[s - 1] = '\0';               /* eliminate last colon */
246
247         return (cp);
248 }
249
250 /*
251  * Provide defaults for all options and directory lists.
252  */
253 void
254 defaults(void)
255 {
256         size_t s;
257         char *b, buf[BUFSIZ], *cp;
258         int nele;
259         FILE *p;
260         DIR *dir;
261         struct stat sb;
262         struct dirent *dirp;
263
264         /* default to -bms if none has been specified */
265         if (!opt_b && !opt_m && !opt_s)
266                 opt_b = opt_m = opt_s = 1;
267
268         /* -b defaults to default path + /usr/libexec +
269          * /usr/games + user's path */
270         if (!bindirs) {
271                 if (sysctlbyname("user.cs_path", (void *)NULL, &s,
272                                  (void *)NULL, 0) == -1)
273                         err(EX_OSERR, "sysctlbyname(\"user.cs_path\")");
274                 if ((b = malloc(s + 1)) == NULL)
275                         abort();
276                 if (sysctlbyname("user.cs_path", b, &s, (void *)NULL, 0) == -1)
277                         err(EX_OSERR, "sysctlbyname(\"user.cs_path\")");
278                 nele = 0;
279                 decolonify(b, &bindirs, &nele);
280                 bindirs = realloc(bindirs, (nele + 3) * sizeof(char *));
281                 if (bindirs == NULL)
282                         abort();
283                 bindirs[nele++] = PATH_LIBEXEC;
284                 bindirs[nele++] = PATH_GAMES;
285                 bindirs[nele] = NULL;
286                 if ((cp = getenv("PATH")) != NULL) {
287                         /* don't destroy the original environment... */
288                         if ((b = malloc(strlen(cp) + 1)) == NULL)
289                                 abort();
290                         strcpy(b, cp);
291                         decolonify(b, &bindirs, &nele);
292                 }
293         }
294
295         /* -m defaults to $(manpath) */
296         if (!mandirs) {
297                 if ((p = popen(MANPATHCMD, "r")) == NULL)
298                         err(EX_OSERR, "cannot execute manpath command");
299                 if (fgets(buf, BUFSIZ - 1, p) == NULL ||
300                     pclose(p))
301                         err(EX_OSERR, "error processing manpath results");
302                 if ((b = strchr(buf, '\n')) != NULL)
303                         *b = '\0';
304                 if ((b = malloc(strlen(buf) + 1)) == NULL)
305                         abort();
306                 strcpy(b, buf);
307                 nele = 0;
308                 decolonify(b, &mandirs, &nele);
309         }
310
311         /* -s defaults to precompiled list, plus subdirs of /usr/ports */
312         if (!sourcedirs) {
313                 if ((b = malloc(strlen(sourcepath) + 1)) == NULL)
314                         abort();
315                 strcpy(b, sourcepath);
316                 nele = 0;
317                 decolonify(b, &sourcedirs, &nele);
318
319                 if (stat(PATH_PORTS, &sb) == -1) {
320                         if (errno == ENOENT)
321                                 /* no /usr/ports, we are done */
322                                 return;
323                         err(EX_OSERR, "stat(" PATH_PORTS ")");
324                 }
325                 if ((sb.st_mode & S_IFMT) != S_IFDIR)
326                         /* /usr/ports is not a directory, ignore */
327                         return;
328                 if (access(PATH_PORTS, R_OK | X_OK) != 0)
329                         return;
330                 if ((dir = opendir(PATH_PORTS)) == NULL)
331                         err(EX_OSERR, "opendir" PATH_PORTS ")");
332                 while ((dirp = readdir(dir)) != NULL) {
333                         if (dirp->d_name[0] == '.' ||
334                             strcmp(dirp->d_name, "CVS") == 0)
335                                 /* ignore dot entries and CVS subdir */
336                                 continue;
337                         if ((b = malloc(sizeof PATH_PORTS + 1 + dirp->d_namlen))
338                             == NULL)
339                                 abort();
340                         strcpy(b, PATH_PORTS);
341                         strcat(b, "/");
342                         strcat(b, dirp->d_name);
343                         if (stat(b, &sb) == -1 ||
344                             (sb.st_mode & S_IFMT) != S_IFDIR ||
345                             access(b, R_OK | X_OK) != 0) {
346                                 free(b);
347                                 continue;
348                         }
349                         sourcedirs = realloc(sourcedirs,
350                                              (nele + 2) * sizeof(char *));
351                         if (sourcedirs == NULL)
352                                 abort();
353                         sourcedirs[nele++] = b;
354                         sourcedirs[nele] = NULL;
355                 }
356                 closedir(dir);
357         }
358 }
359
360 int
361 main(int argc, char **argv)
362 {
363         int unusual, i, printed;
364         char *bin, buf[BUFSIZ], *cp, *cp2, *man, *name, *src;
365         ccharp *dp;
366         size_t nlen, olen, s;
367         struct stat sb;
368         regex_t re, re2;
369         regmatch_t matches[2];
370         regoff_t rlen;
371         FILE *p;
372
373         setlocale(LC_ALL, "");
374         scanopts(argc, argv);
375         defaults();
376
377         if (mandirs == NULL)
378                 opt_m = 0;
379         if (bindirs == NULL)
380                 opt_b = 0;
381         if (sourcedirs == NULL)
382                 opt_s = 0;
383         if (opt_m + opt_b + opt_s == 0)
384                 errx(EX_DATAERR, "no directories to search");
385
386         if (opt_m) {
387                 setenv("MANPATH", colonify(mandirs), 1);
388                 if ((i = regcomp(&re, MANWHEREISMATCH, REG_EXTENDED)) != 0) {
389                         regerror(i, &re, buf, BUFSIZ - 1);
390                         errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s",
391                              MANWHEREISMATCH, buf);
392                 }
393         }
394
395         for (; (name = *query) != NULL; query++) {
396                 /* strip leading path name component */
397                 if ((cp = strrchr(name, '/')) != NULL)
398                         name = cp + 1;
399                 /* strip SCCS or RCS suffix/prefix */
400                 if (strlen(name) > 2 && strncmp(name, "s.", 2) == 0)
401                         name += 2;
402                 if ((s = strlen(name)) > 2 && strcmp(name + s - 2, ",v") == 0)
403                         name[s - 2] = '\0';
404                 /* compression suffix */
405                 s = strlen(name);
406                 if (s > 2 &&
407                     (strcmp(name + s - 2, ".z") == 0 ||
408                      strcmp(name + s - 2, ".Z") == 0))
409                         name[s - 2] = '\0';
410                 else if (s > 3 &&
411                          strcmp(name + s - 3, ".gz") == 0)
412                         name[s - 3] = '\0';
413                 else if (s > 4 &&
414                          strcmp(name + s - 4, ".bz2") == 0)
415                         name[s - 4] = '\0';
416
417                 unusual = 0;
418                 bin = man = src = NULL;
419                 s = strlen(name);
420
421                 if (opt_b) {
422                         /*
423                          * Binaries have to match exactly, and must be regular
424                          * executable files.
425                          */
426                         unusual = unusual | NO_BIN_FOUND;
427                         for (dp = bindirs; *dp != NULL; dp++) {
428                                 cp = malloc(strlen(*dp) + 1 + s + 1);
429                                 if (cp == NULL)
430                                         abort();
431                                 strcpy(cp, *dp);
432                                 strcat(cp, "/");
433                                 strcat(cp, name);
434                                 if (stat(cp, &sb) == 0 &&
435                                     (sb.st_mode & S_IFMT) == S_IFREG &&
436                                     (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
437                                     != 0) {
438                                         unusual = unusual & ~NO_BIN_FOUND;
439                                         if (bin == NULL) {
440                                                 bin = strdup(cp);
441                                         } else {
442                                                 olen = strlen(bin);
443                                                 nlen = strlen(cp);
444                                                 bin = realloc(bin, 
445                                                               olen + nlen + 2);
446                                                 if (bin == 0)
447                                                         abort();
448                                                 strcat(bin, " ");
449                                                 strcat(bin, cp);
450                                         }
451                                         if (!opt_a) {
452                                                 free(cp);
453                                                 break;
454                                         }
455                                 }
456                                 free(cp);
457                         }
458                 }
459
460                 if (opt_m) {
461                         /*
462                          * Ask the man command to perform the search for us.
463                          */
464                         unusual = unusual | NO_MAN_FOUND;
465                         if (opt_a)
466                                 cp = malloc(sizeof MANWHEREISALLCMD - 2 + s);
467                         else
468                                 cp = malloc(sizeof MANWHEREISCMD - 2 + s);
469
470                         if (cp == NULL)
471                                 abort();
472
473                         if (opt_a)
474                                 sprintf(cp, MANWHEREISALLCMD, name);
475                         else
476                                 sprintf(cp, MANWHEREISCMD, name);
477
478                         if ((p = popen(cp, "r")) != NULL) {
479                             
480                                 while (fgets(buf, BUFSIZ - 1, p) != NULL) {
481                                         unusual = unusual & ~NO_MAN_FOUND;
482                                 
483                                         if ((cp2 = strchr(buf, '\n')) != NULL)
484                                                 *cp2 = '\0';
485                                         if (regexec(&re, buf, 2, 
486                                                     matches, 0) == 0 &&
487                                             (rlen = matches[1].rm_eo - 
488                                              matches[1].rm_so) > 0) {
489                                                 /*
490                                                  * man -w found formated
491                                                  * page, need to pick up
492                                                  * source page name.
493                                                  */
494                                                 cp2 = malloc(rlen + 1);
495                                                 if (cp2 == NULL)
496                                                         abort();
497                                                 memcpy(cp2, 
498                                                        buf + matches[1].rm_so,
499                                                        rlen);
500                                                 cp2[rlen] = '\0';
501                                         } else {
502                                                 /*
503                                                  * man -w found plain source
504                                                  * page, use it.
505                                                  */
506                                                 s = strlen(buf);
507                                                 cp2 = malloc(s + 1);
508                                                 if (cp2 == NULL)
509                                                         abort();
510                                                 strcpy(cp2, buf);
511                                         }
512
513                                         if (man == NULL) {
514                                                 man = strdup(cp2);
515                                         } else {
516                                                 olen = strlen(man);
517                                                 nlen = strlen(cp2);
518                                                 man = realloc(man, 
519                                                               olen + nlen + 2);
520                                                 if (man == 0)
521                                                         abort();
522                                                 strcat(man, " ");
523                                                 strcat(man, cp2);
524                                         }
525
526                                         free(cp2);
527                                         
528                                         if (!opt_a)
529                                                 break;
530                                 }
531                                 pclose(p);
532                                 free(cp);
533                         }
534                 }
535
536                 if (opt_s) {
537                         /*
538                          * Sources match if a subdir with the exact
539                          * name is found.
540                          */
541                         unusual = unusual | NO_SRC_FOUND;
542                         for (dp = sourcedirs; *dp != NULL; dp++) {
543                                 cp = malloc(strlen(*dp) + 1 + s + 1);
544                                 if (cp == NULL)
545                                         abort();
546                                 strcpy(cp, *dp);
547                                 strcat(cp, "/");
548                                 strcat(cp, name);
549                                 if (stat(cp, &sb) == 0 &&
550                                     (sb.st_mode & S_IFMT) == S_IFDIR) {
551                                         unusual = unusual & ~NO_SRC_FOUND;
552                                         if (src == NULL) {
553                                                 src = strdup(cp);
554                                         } else {
555                                                 olen = strlen(src);
556                                                 nlen = strlen(cp);
557                                                 src = realloc(src, 
558                                                               olen + nlen + 2);
559                                                 if (src == 0)
560                                                         abort();
561                                                 strcat(src, " ");
562                                                 strcat(src, cp);
563                                         }
564                                         if (!opt_a) {
565                                                 free(cp);
566                                                 break;
567                                         }
568                                 }
569                                 free(cp);
570                         }
571                         /*
572                          * If still not found, ask locate to search it
573                          * for us.  This will find sources for things
574                          * like lpr that are well hidden in the
575                          * /usr/src tree, but takes a lot longer.
576                          * Thus, option -x (`expensive') prevents this
577                          * search.
578                          *
579                          * Do only match locate output that starts
580                          * with one of our source directories, and at
581                          * least one further level of subdirectories.
582                          */
583                         if (opt_x || (src && !opt_a))
584                                 goto done_sources;
585
586                         cp = malloc(sizeof LOCATECMD - 2 + s);
587                         if (cp == NULL)
588                                 abort();
589                         sprintf(cp, LOCATECMD, name);
590                         if ((p = popen(cp, "r")) == NULL)
591                                 goto done_sources;
592                         while ((src == NULL || opt_a) &&
593                                (fgets(buf, BUFSIZ - 1, p)) != NULL) {
594                                 if ((cp2 = strchr(buf, '\n')) != NULL)
595                                         *cp2 = '\0';
596                                 for (dp = sourcedirs;
597                                      (src == NULL || opt_a) && *dp != NULL;
598                                      dp++) {
599                                         cp2 = malloc(strlen(*dp) + 9);
600                                         if (cp2 == NULL)
601                                                 abort();
602                                         strcpy(cp2, "^");
603                                         strcat(cp2, *dp);
604                                         strcat(cp2, "/[^/]+/");
605                                         if ((i = regcomp(&re2, cp2,
606                                                          REG_EXTENDED|REG_NOSUB))
607                                             != 0) {
608                                                 regerror(i, &re, buf,
609                                                          BUFSIZ - 1);
610                                                 errx(EX_UNAVAILABLE,
611                                                      "regcomp(%s) failed: %s",
612                                                      cp2, buf);
613                                         }
614                                         free(cp2);
615                                         if (regexec(&re2, buf, 0,
616                                                     (regmatch_t *)NULL, 0)
617                                             == 0) {
618                                                 unusual = unusual & 
619                                                           ~NO_SRC_FOUND;
620                                                 if (src == NULL) {
621                                                         src = strdup(buf);
622                                                 } else {
623                                                         olen = strlen(src);
624                                                         nlen = strlen(buf);
625                                                         src = realloc(src, 
626                                                                       olen + 
627                                                                       nlen + 2);
628                                                         if (src == 0)
629                                                                 abort();
630                                                         strcat(src, " ");
631                                                         strcat(src, buf);
632                                                 }
633                                         }
634                                         regfree(&re2);
635                                 }
636                         }
637                         pclose(p);
638                         free(cp);
639                 }
640           done_sources:
641
642                 if (opt_u && !unusual)
643                         continue;
644
645                 printed = 0;
646                 if (!opt_q) {
647                         printf("%s:", name);
648                         printed++;
649                 }
650                 if (bin) {
651                         if (printed++)
652                                 putchar(' ');
653                         fputs(bin, stdout);
654                 }
655                 if (man) {
656                         if (printed++)
657                                 putchar(' ');
658                         fputs(man, stdout);
659                 }
660                 if (src) {
661                         if (printed++)
662                                 putchar(' ');
663                         fputs(src, stdout);
664                 }
665                 if (printed)
666                         putchar('\n');
667         }
668
669         if (opt_m)
670                 regfree(&re);
671
672         return (0);
673 }