* Fix some cases where NULL was used but 0 was meant (and vice versa).
[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.6 2008/06/05 18:06:33 swildner 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;
106         ccharp **dirlist;
107
108         while ((c = getopt(argc, argv, "BMSabfmqsux")) != -1)
109                 switch (c) {
110                 case 'B':
111                         dirlist = &bindirs;
112                         goto dolist;
113
114                 case 'M':
115                         dirlist = &mandirs;
116                         goto dolist;
117
118                 case 'S':
119                         dirlist = &sourcedirs;
120                   dolist:
121                         i = 0;
122                         *dirlist = realloc(*dirlist, (i + 1) * sizeof(char *));
123                         (*dirlist)[i] = NULL;
124                         while (optind < argc &&
125                                strcmp(argv[optind], "-f") != 0 &&
126                                strcmp(argv[optind], "-B") != 0 &&
127                                strcmp(argv[optind], "-M") != 0 &&
128                                strcmp(argv[optind], "-S") != 0) {
129                                 decolonify(argv[optind], dirlist, &i);
130                                 optind++;
131                         }
132                         break;
133
134                 case 'a':
135                         opt_a = 1;
136                         break;
137
138                 case 'b':
139                         opt_b = 1;
140                         break;
141
142                 case 'f':
143                         goto breakout;
144
145                 case 'm':
146                         opt_m = 1;
147                         break;
148
149                 case 'q':
150                         opt_q = 1;
151                         break;
152
153                 case 's':
154                         opt_s = 1;
155                         break;
156
157                 case 'u':
158                         opt_u = 1;
159                         break;
160
161                 case 'x':
162                         opt_x = 1;
163                         break;
164
165                 default:
166                         usage();
167                 }
168   breakout:
169         if (optind == argc)
170                 usage();
171         query = argv + optind;
172 }
173
174 /*
175  * Find out whether string `s' is contained in list `cpp'.
176  */
177 int
178 contains(ccharp *cpp, const char *s)
179 {
180         ccharp cp;
181
182         if (cpp == NULL)
183                 return (0);
184
185         while ((cp = *cpp) != NULL) {
186                 if (strcmp(cp, s) == 0)
187                         return (1);
188                 cpp++;
189         }
190         return (0);
191 }
192
193 /*
194  * Split string `s' at colons, and pass it to the string list pointed
195  * to by `cppp' (which has `*ip' elements).  Note that the original
196  * string is modified by replacing the colon with a NUL byte.  The
197  * partial string is only added if it has a length greater than 0, and
198  * if it's not already contained in the string list.
199  */
200 void
201 decolonify(char *s, ccharp **cppp, int *ip)
202 {
203         char *cp;
204
205         while ((cp = strchr(s, ':')), *s != '\0') {
206                 if (cp)
207                         *cp = '\0';
208                 if (strlen(s) && !contains(*cppp, s)) {
209                         *cppp = realloc(*cppp, (*ip + 2) * sizeof(char *));
210                         if (cppp == NULL)
211                                 abort();
212                         (*cppp)[*ip] = s;
213                         (*cppp)[*ip + 1] = NULL;
214                         (*ip)++;
215                 }
216                 if (cp)
217                         s = cp + 1;
218                 else
219                         break;
220         }
221 }
222
223 /*
224  * Join string list `cpp' into a colon-separated string.
225  */
226 char *
227 colonify(ccharp *cpp)
228 {
229         size_t s;
230         char *cp;
231         int i;
232
233         if (cpp == NULL)
234                 return (0);
235
236         for (s = 0, i = 0; cpp[i] != NULL; i++)
237                 s += strlen(cpp[i]) + 1;
238         if ((cp = malloc(s + 1)) == NULL)
239                 abort();
240         for (i = 0, *cp = '\0'; cpp[i] != NULL; i++) {
241                 strcat(cp, cpp[i]);
242                 strcat(cp, ":");
243         }
244         cp[s - 1] = '\0';               /* eliminate last colon */
245
246         return (cp);
247 }
248
249 /*
250  * Provide defaults for all options and directory lists.
251  */
252 void
253 defaults(void)
254 {
255         size_t s;
256         char *b, buf[BUFSIZ], *cp;
257         int nele;
258         FILE *p;
259         DIR *dir;
260         struct stat sb;
261         struct dirent *dirp;
262
263         /* default to -bms if none has been specified */
264         if (!opt_b && !opt_m && !opt_s)
265                 opt_b = opt_m = opt_s = 1;
266
267         /* -b defaults to default path + /usr/libexec +
268          * /usr/games + user's path */
269         if (!bindirs) {
270                 if (sysctlbyname("user.cs_path", NULL, &s, NULL, 0) == -1)
271                         err(EX_OSERR, "sysctlbyname(\"user.cs_path\")");
272                 if ((b = malloc(s + 1)) == NULL)
273                         abort();
274                 if (sysctlbyname("user.cs_path", b, &s, NULL, 0) == -1)
275                         err(EX_OSERR, "sysctlbyname(\"user.cs_path\")");
276                 nele = 0;
277                 decolonify(b, &bindirs, &nele);
278                 bindirs = realloc(bindirs, (nele + 3) * sizeof(char *));
279                 if (bindirs == NULL)
280                         abort();
281                 bindirs[nele++] = PATH_LIBEXEC;
282                 bindirs[nele++] = PATH_GAMES;
283                 bindirs[nele] = NULL;
284                 if ((cp = getenv("PATH")) != NULL) {
285                         /* don't destroy the original environment... */
286                         if ((b = malloc(strlen(cp) + 1)) == NULL)
287                                 abort();
288                         strcpy(b, cp);
289                         decolonify(b, &bindirs, &nele);
290                 }
291         }
292
293         /* -m defaults to $(manpath) */
294         if (!mandirs) {
295                 if ((p = popen(MANPATHCMD, "r")) == NULL)
296                         err(EX_OSERR, "cannot execute manpath command");
297                 if (fgets(buf, BUFSIZ - 1, p) == NULL ||
298                     pclose(p))
299                         err(EX_OSERR, "error processing manpath results");
300                 if ((b = strchr(buf, '\n')) != NULL)
301                         *b = '\0';
302                 if ((b = malloc(strlen(buf) + 1)) == NULL)
303                         abort();
304                 strcpy(b, buf);
305                 nele = 0;
306                 decolonify(b, &mandirs, &nele);
307         }
308
309         /* -s defaults to precompiled list, plus subdirs of /usr/pkgsrc */
310         if (!sourcedirs) {
311                 if ((b = malloc(strlen(sourcepath) + 1)) == NULL)
312                         abort();
313                 strcpy(b, sourcepath);
314                 nele = 0;
315                 decolonify(b, &sourcedirs, &nele);
316
317                 if (stat(PATH_PKGSRC, &sb) == -1) {
318                         if (errno == ENOENT)
319                                 /* no /usr/pkgsrc, we are done */
320                                 return;
321                         err(EX_OSERR, "stat(" PATH_PKGSRC ")");
322                 }
323                 if ((sb.st_mode & S_IFMT) != S_IFDIR)
324                         /* /usr/pkgsrc is not a directory, ignore */
325                         return;
326                 if (access(PATH_PKGSRC, R_OK | X_OK) != 0)
327                         return;
328                 if ((dir = opendir(PATH_PKGSRC)) == NULL)
329                         err(EX_OSERR, "opendir" PATH_PKGSRC ")");
330                 while ((dirp = readdir(dir)) != NULL) {
331                         if (dirp->d_name[0] == '.' ||
332                             strcmp(dirp->d_name, "CVS") == 0)
333                                 /* ignore dot entries and CVS subdir */
334                                 continue;
335                         if ((b = malloc(sizeof PATH_PKGSRC + 1 + dirp->d_namlen))
336                             == NULL)
337                                 abort();
338                         strcpy(b, PATH_PKGSRC);
339                         strcat(b, "/");
340                         strcat(b, dirp->d_name);
341                         if (stat(b, &sb) == -1 ||
342                             (sb.st_mode & S_IFMT) != S_IFDIR ||
343                             access(b, R_OK | X_OK) != 0) {
344                                 free(b);
345                                 continue;
346                         }
347                         sourcedirs = realloc(sourcedirs,
348                                              (nele + 2) * sizeof(char *));
349                         if (sourcedirs == NULL)
350                                 abort();
351                         sourcedirs[nele++] = b;
352                         sourcedirs[nele] = NULL;
353                 }
354                 closedir(dir);
355         }
356 }
357
358 int
359 main(int argc, char **argv)
360 {
361         int unusual, i, printed;
362         char *bin, buf[BUFSIZ], *cp, *cp2, *man, *name, *src;
363         ccharp *dp;
364         size_t nlen, olen, s;
365         struct stat sb;
366         regex_t re, re2;
367         regmatch_t matches[2];
368         regoff_t rlen;
369         FILE *p;
370
371         setlocale(LC_ALL, "");
372         scanopts(argc, argv);
373         defaults();
374
375         if (mandirs == NULL)
376                 opt_m = 0;
377         if (bindirs == NULL)
378                 opt_b = 0;
379         if (sourcedirs == NULL)
380                 opt_s = 0;
381         if (opt_m + opt_b + opt_s == 0)
382                 errx(EX_DATAERR, "no directories to search");
383
384         if (opt_m) {
385                 if (setenv("MANPATH", colonify(mandirs), 1) == -1)
386                         err(1, "setenv: cannot set MANPATH=%s", colonify(mandirs));
387                 if ((i = regcomp(&re, MANWHEREISMATCH, REG_EXTENDED)) != 0) {
388                         regerror(i, &re, buf, BUFSIZ - 1);
389                         errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s",
390                              MANWHEREISMATCH, buf);
391                 }
392         }
393
394         for (; (name = *query) != NULL; query++) {
395                 /* strip leading path name component */
396                 if ((cp = strrchr(name, '/')) != NULL)
397                         name = cp + 1;
398                 /* strip SCCS or RCS suffix/prefix */
399                 if (strlen(name) > 2 && strncmp(name, "s.", 2) == 0)
400                         name += 2;
401                 if ((s = strlen(name)) > 2 && strcmp(name + s - 2, ",v") == 0)
402                         name[s - 2] = '\0';
403                 /* compression suffix */
404                 s = strlen(name);
405                 if (s > 2 &&
406                     (strcmp(name + s - 2, ".z") == 0 ||
407                      strcmp(name + s - 2, ".Z") == 0))
408                         name[s - 2] = '\0';
409                 else if (s > 3 &&
410                          strcmp(name + s - 3, ".gz") == 0)
411                         name[s - 3] = '\0';
412                 else if (s > 4 &&
413                          strcmp(name + s - 4, ".bz2") == 0)
414                         name[s - 4] = '\0';
415
416                 unusual = 0;
417                 bin = man = src = NULL;
418                 s = strlen(name);
419
420                 if (opt_b) {
421                         /*
422                          * Binaries have to match exactly, and must be regular
423                          * executable files.
424                          */
425                         unusual = unusual | NO_BIN_FOUND;
426                         for (dp = bindirs; *dp != NULL; dp++) {
427                                 cp = malloc(strlen(*dp) + 1 + s + 1);
428                                 if (cp == NULL)
429                                         abort();
430                                 strcpy(cp, *dp);
431                                 strcat(cp, "/");
432                                 strcat(cp, name);
433                                 if (stat(cp, &sb) == 0 &&
434                                     (sb.st_mode & S_IFMT) == S_IFREG &&
435                                     (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
436                                     != 0) {
437                                         unusual = unusual & ~NO_BIN_FOUND;
438                                         if (bin == NULL) {
439                                                 bin = strdup(cp);
440                                         } else {
441                                                 olen = strlen(bin);
442                                                 nlen = strlen(cp);
443                                                 bin = realloc(bin, 
444                                                               olen + nlen + 2);
445                                                 if (bin == 0)
446                                                         abort();
447                                                 strcat(bin, " ");
448                                                 strcat(bin, cp);
449                                         }
450                                         if (!opt_a) {
451                                                 free(cp);
452                                                 break;
453                                         }
454                                 }
455                                 free(cp);
456                         }
457                 }
458
459                 if (opt_m) {
460                         /*
461                          * Ask the man command to perform the search for us.
462                          */
463                         unusual = unusual | NO_MAN_FOUND;
464                         if (opt_a)
465                                 cp = malloc(sizeof MANWHEREISALLCMD - 2 + s);
466                         else
467                                 cp = malloc(sizeof MANWHEREISCMD - 2 + s);
468
469                         if (cp == NULL)
470                                 abort();
471
472                         if (opt_a)
473                                 sprintf(cp, MANWHEREISALLCMD, name);
474                         else
475                                 sprintf(cp, MANWHEREISCMD, name);
476
477                         if ((p = popen(cp, "r")) != NULL) {
478                             
479                                 while (fgets(buf, BUFSIZ - 1, p) != NULL) {
480                                         unusual = unusual & ~NO_MAN_FOUND;
481                                 
482                                         if ((cp2 = strchr(buf, '\n')) != NULL)
483                                                 *cp2 = '\0';
484                                         if (regexec(&re, buf, 2, 
485                                                     matches, 0) == 0 &&
486                                             (rlen = matches[1].rm_eo - 
487                                              matches[1].rm_so) > 0) {
488                                                 /*
489                                                  * man -w found formated
490                                                  * page, need to pick up
491                                                  * source page name.
492                                                  */
493                                                 cp2 = malloc(rlen + 1);
494                                                 if (cp2 == NULL)
495                                                         abort();
496                                                 memcpy(cp2, 
497                                                        buf + matches[1].rm_so,
498                                                        rlen);
499                                                 cp2[rlen] = '\0';
500                                         } else {
501                                                 /*
502                                                  * man -w found plain source
503                                                  * page, use it.
504                                                  */
505                                                 s = strlen(buf);
506                                                 cp2 = malloc(s + 1);
507                                                 if (cp2 == NULL)
508                                                         abort();
509                                                 strcpy(cp2, buf);
510                                         }
511
512                                         if (man == NULL) {
513                                                 man = strdup(cp2);
514                                         } else {
515                                                 olen = strlen(man);
516                                                 nlen = strlen(cp2);
517                                                 man = realloc(man, 
518                                                               olen + nlen + 2);
519                                                 if (man == 0)
520                                                         abort();
521                                                 strcat(man, " ");
522                                                 strcat(man, cp2);
523                                         }
524
525                                         free(cp2);
526                                         
527                                         if (!opt_a)
528                                                 break;
529                                 }
530                                 pclose(p);
531                                 free(cp);
532                         }
533                 }
534
535                 if (opt_s) {
536                         /*
537                          * Sources match if a subdir with the exact
538                          * name is found.
539                          */
540                         unusual = unusual | NO_SRC_FOUND;
541                         for (dp = sourcedirs; *dp != NULL; dp++) {
542                                 cp = malloc(strlen(*dp) + 1 + s + 1);
543                                 if (cp == NULL)
544                                         abort();
545                                 strcpy(cp, *dp);
546                                 strcat(cp, "/");
547                                 strcat(cp, name);
548                                 if (stat(cp, &sb) == 0 &&
549                                     (sb.st_mode & S_IFMT) == S_IFDIR) {
550                                         unusual = unusual & ~NO_SRC_FOUND;
551                                         if (src == NULL) {
552                                                 src = strdup(cp);
553                                         } else {
554                                                 olen = strlen(src);
555                                                 nlen = strlen(cp);
556                                                 src = realloc(src, 
557                                                               olen + nlen + 2);
558                                                 if (src == 0)
559                                                         abort();
560                                                 strcat(src, " ");
561                                                 strcat(src, cp);
562                                         }
563                                         if (!opt_a) {
564                                                 free(cp);
565                                                 break;
566                                         }
567                                 }
568                                 free(cp);
569                         }
570                         /*
571                          * If still not found, ask locate to search it
572                          * for us.  This will find sources for things
573                          * like lpr that are well hidden in the
574                          * /usr/src tree, but takes a lot longer.
575                          * Thus, option -x (`expensive') prevents this
576                          * search.
577                          *
578                          * Do only match locate output that starts
579                          * with one of our source directories, and at
580                          * least one further level of subdirectories.
581                          */
582                         if (opt_x || (src && !opt_a))
583                                 goto done_sources;
584
585                         cp = malloc(sizeof LOCATECMD - 2 + s);
586                         if (cp == NULL)
587                                 abort();
588                         sprintf(cp, LOCATECMD, name);
589                         if ((p = popen(cp, "r")) == NULL)
590                                 goto done_sources;
591                         while ((src == NULL || opt_a) &&
592                                (fgets(buf, BUFSIZ - 1, p)) != NULL) {
593                                 if ((cp2 = strchr(buf, '\n')) != NULL)
594                                         *cp2 = '\0';
595                                 for (dp = sourcedirs;
596                                      (src == NULL || opt_a) && *dp != NULL;
597                                      dp++) {
598                                         cp2 = malloc(strlen(*dp) + 9);
599                                         if (cp2 == NULL)
600                                                 abort();
601                                         strcpy(cp2, "^");
602                                         strcat(cp2, *dp);
603                                         strcat(cp2, "/[^/]+/");
604                                         if ((i = regcomp(&re2, cp2,
605                                                          REG_EXTENDED|REG_NOSUB))
606                                             != 0) {
607                                                 regerror(i, &re, buf,
608                                                          BUFSIZ - 1);
609                                                 errx(EX_UNAVAILABLE,
610                                                      "regcomp(%s) failed: %s",
611                                                      cp2, buf);
612                                         }
613                                         free(cp2);
614                                         if (regexec(&re2, buf, 0,
615                                                     (regmatch_t *)NULL, 0)
616                                             == 0) {
617                                                 unusual = unusual & 
618                                                           ~NO_SRC_FOUND;
619                                                 if (src == NULL) {
620                                                         src = strdup(buf);
621                                                 } else {
622                                                         olen = strlen(src);
623                                                         nlen = strlen(buf);
624                                                         src = realloc(src, 
625                                                                       olen + 
626                                                                       nlen + 2);
627                                                         if (src == 0)
628                                                                 abort();
629                                                         strcat(src, " ");
630                                                         strcat(src, buf);
631                                                 }
632                                         }
633                                         regfree(&re2);
634                                 }
635                         }
636                         pclose(p);
637                         free(cp);
638                 }
639           done_sources:
640
641                 if (opt_u && !unusual)
642                         continue;
643
644                 printed = 0;
645                 if (!opt_q) {
646                         printf("%s:", name);
647                         printed++;
648                 }
649                 if (bin) {
650                         if (printed++)
651                                 putchar(' ');
652                         fputs(bin, stdout);
653                 }
654                 if (man) {
655                         if (printed++)
656                                 putchar(' ');
657                         fputs(man, stdout);
658                 }
659                 if (src) {
660                         if (printed++)
661                                 putchar(' ');
662                         fputs(src, stdout);
663                 }
664                 if (printed)
665                         putchar('\n');
666         }
667
668         if (opt_m)
669                 regfree(&re);
670
671         return (0);
672 }