xref: /freebsd/usr.bin/whereis/whereis.c (revision b0b1dbdd)
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  */
25 
26 /*
27  * 4.3BSD UI-compatible whereis(1) utility.  Rewritten from scratch
28  * since the original 4.3BSD version suffers legal problems that
29  * prevent it from being redistributed, and since the 4.4BSD version
30  * was pretty inferior in functionality.
31  */
32 
33 #include <sys/types.h>
34 
35 __FBSDID("$FreeBSD$");
36 
37 #include <sys/stat.h>
38 #include <sys/sysctl.h>
39 
40 #include <dirent.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <locale.h>
44 #include <regex.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <sysexits.h>
49 #include <unistd.h>
50 
51 #include "pathnames.h"
52 
53 #define	NO_BIN_FOUND	1
54 #define	NO_MAN_FOUND	2
55 #define	NO_SRC_FOUND	4
56 
57 typedef const char *ccharp;
58 
59 static int opt_a, opt_b, opt_m, opt_q, opt_s, opt_u, opt_x;
60 static ccharp *bindirs, *mandirs, *sourcedirs;
61 static char **query;
62 
63 static const char *sourcepath = PATH_SOURCES;
64 
65 static char	*colonify(ccharp *);
66 static int	 contains(ccharp *, const char *);
67 static void	 decolonify(char *, ccharp **, int *);
68 static void	 defaults(void);
69 static void	 scanopts(int, char **);
70 static void	 usage(void);
71 
72 /*
73  * Throughout this program, a number of strings are dynamically
74  * allocated but never freed.  Their memory is written to when
75  * splitting the strings into string lists which will later be
76  * processed.  Since it's important that those string lists remain
77  * valid even after the functions allocating the memory returned,
78  * those functions cannot free them.  They could be freed only at end
79  * of main(), which is pretty pointless anyway.
80  *
81  * The overall amount of memory to be allocated for processing the
82  * strings is not expected to exceed a few kilobytes.  For that
83  * reason, allocation can usually always be assumed to succeed (within
84  * a virtual memory environment), thus we simply bail out using
85  * abort(3) in case of an allocation failure.
86  */
87 
88 static void
89 usage(void)
90 {
91 	(void)fprintf(stderr,
92 	     "usage: whereis [-abmqsux] [-BMS dir ... -f] program ...\n");
93 	exit(EX_USAGE);
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 static 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 static 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 static 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 static 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 static 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 	 * user's path */
269 	if (!bindirs) {
270 		if (sysctlbyname("user.cs_path", (void *)NULL, &s,
271 				 (void *)NULL, 0) == -1)
272 			err(EX_OSERR, "sysctlbyname(\"user.cs_path\")");
273 		if ((b = malloc(s + 1)) == NULL)
274 			abort();
275 		if (sysctlbyname("user.cs_path", b, &s, (void *)NULL, 0) == -1)
276 			err(EX_OSERR, "sysctlbyname(\"user.cs_path\")");
277 		nele = 0;
278 		decolonify(b, &bindirs, &nele);
279 		bindirs = realloc(bindirs, (nele + 2) * sizeof(char *));
280 		if (bindirs == NULL)
281 			abort();
282 		bindirs[nele++] = PATH_LIBEXEC;
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/ports */
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_PORTS, &sb) == -1) {
318 			if (errno == ENOENT)
319 				/* no /usr/ports, we are done */
320 				return;
321 			err(EX_OSERR, "stat(" PATH_PORTS ")");
322 		}
323 		if ((sb.st_mode & S_IFMT) != S_IFDIR)
324 			/* /usr/ports is not a directory, ignore */
325 			return;
326 		if (access(PATH_PORTS, R_OK | X_OK) != 0)
327 			return;
328 		if ((dir = opendir(PATH_PORTS)) == NULL)
329 			err(EX_OSERR, "opendir" PATH_PORTS ")");
330 		while ((dirp = readdir(dir)) != NULL) {
331 			/*
332 			 * Not everything below PATH_PORTS is of
333 			 * interest.  First, all dot files and
334 			 * directories (e. g. .snap) can be ignored.
335 			 * Also, all subdirectories starting with a
336 			 * capital letter are not going to be
337 			 * examined, as they are used for internal
338 			 * purposes (Mk, Tools, ...).  This also
339 			 * matches a possible CVS subdirectory.
340 			 * Finally, the distfiles subdirectory is also
341 			 * special, and should not be considered to
342 			 * avoid false matches.
343 			 */
344 			if (dirp->d_name[0] == '.' ||
345 			    /*
346 			     * isupper() not used on purpose: the
347 			     * check is supposed to default to the C
348 			     * locale instead of the current user's
349 			     * locale.
350 			     */
351 			    (dirp->d_name[0] >= 'A' && dirp->d_name[0] <= 'Z') ||
352 			    strcmp(dirp->d_name, "distfiles") == 0)
353 				continue;
354 			if ((b = malloc(sizeof PATH_PORTS + 1 + dirp->d_namlen))
355 			    == NULL)
356 				abort();
357 			strcpy(b, PATH_PORTS);
358 			strcat(b, "/");
359 			strcat(b, dirp->d_name);
360 			if (stat(b, &sb) == -1 ||
361 			    (sb.st_mode & S_IFMT) != S_IFDIR ||
362 			    access(b, R_OK | X_OK) != 0) {
363 				free(b);
364 				continue;
365 			}
366 			sourcedirs = realloc(sourcedirs,
367 					     (nele + 2) * sizeof(char *));
368 			if (sourcedirs == NULL)
369 				abort();
370 			sourcedirs[nele++] = b;
371 			sourcedirs[nele] = NULL;
372 		}
373 		closedir(dir);
374 	}
375 }
376 
377 int
378 main(int argc, char **argv)
379 {
380 	int unusual, i, printed;
381 	char *bin, buf[BUFSIZ], *cp, *cp2, *man, *name, *src;
382 	ccharp *dp;
383 	size_t nlen, olen, s;
384 	struct stat sb;
385 	regex_t re, re2;
386 	regmatch_t matches[2];
387 	regoff_t rlen;
388 	FILE *p;
389 
390 	setlocale(LC_ALL, "");
391 
392 	scanopts(argc, argv);
393 	defaults();
394 
395 	if (mandirs == NULL)
396 		opt_m = 0;
397 	if (bindirs == NULL)
398 		opt_b = 0;
399 	if (sourcedirs == NULL)
400 		opt_s = 0;
401 	if (opt_m + opt_b + opt_s == 0)
402 		errx(EX_DATAERR, "no directories to search");
403 
404 	if (opt_m) {
405 		setenv("MANPATH", colonify(mandirs), 1);
406 		if ((i = regcomp(&re, MANWHEREISMATCH, REG_EXTENDED)) != 0) {
407 			regerror(i, &re, buf, BUFSIZ - 1);
408 			errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s",
409 			     MANWHEREISMATCH, buf);
410 		}
411 	}
412 
413 	for (; (name = *query) != NULL; query++) {
414 		/* strip leading path name component */
415 		if ((cp = strrchr(name, '/')) != NULL)
416 			name = cp + 1;
417 		/* strip SCCS or RCS suffix/prefix */
418 		if (strlen(name) > 2 && strncmp(name, "s.", 2) == 0)
419 			name += 2;
420 		if ((s = strlen(name)) > 2 && strcmp(name + s - 2, ",v") == 0)
421 			name[s - 2] = '\0';
422 		/* compression suffix */
423 		s = strlen(name);
424 		if (s > 2 &&
425 		    (strcmp(name + s - 2, ".z") == 0 ||
426 		     strcmp(name + s - 2, ".Z") == 0))
427 			name[s - 2] = '\0';
428 		else if (s > 3 &&
429 			 strcmp(name + s - 3, ".gz") == 0)
430 			name[s - 3] = '\0';
431 		else if (s > 4 &&
432 			 strcmp(name + s - 4, ".bz2") == 0)
433 			name[s - 4] = '\0';
434 
435 		unusual = 0;
436 		bin = man = src = NULL;
437 		s = strlen(name);
438 
439 		if (opt_b) {
440 			/*
441 			 * Binaries have to match exactly, and must be regular
442 			 * executable files.
443 			 */
444 			unusual = unusual | NO_BIN_FOUND;
445 			for (dp = bindirs; *dp != NULL; dp++) {
446 				cp = malloc(strlen(*dp) + 1 + s + 1);
447 				if (cp == NULL)
448 					abort();
449 				strcpy(cp, *dp);
450 				strcat(cp, "/");
451 				strcat(cp, name);
452 				if (stat(cp, &sb) == 0 &&
453 				    (sb.st_mode & S_IFMT) == S_IFREG &&
454 				    (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
455 				    != 0) {
456 					unusual = unusual & ~NO_BIN_FOUND;
457 					if (bin == NULL) {
458 						bin = strdup(cp);
459 					} else {
460 						olen = strlen(bin);
461 						nlen = strlen(cp);
462 						bin = realloc(bin,
463 							      olen + nlen + 2);
464 						if (bin == NULL)
465 							abort();
466 						strcat(bin, " ");
467 						strcat(bin, cp);
468 					}
469 					if (!opt_a) {
470 						free(cp);
471 						break;
472 					}
473 				}
474 				free(cp);
475 			}
476 		}
477 
478 		if (opt_m) {
479 			/*
480 			 * Ask the man command to perform the search for us.
481 			 */
482 			unusual = unusual | NO_MAN_FOUND;
483 			if (opt_a)
484 				cp = malloc(sizeof MANWHEREISALLCMD - 2 + s);
485 			else
486 				cp = malloc(sizeof MANWHEREISCMD - 2 + s);
487 
488 			if (cp == NULL)
489 				abort();
490 
491 			if (opt_a)
492 				sprintf(cp, MANWHEREISALLCMD, name);
493 			else
494 				sprintf(cp, MANWHEREISCMD, name);
495 
496 			if ((p = popen(cp, "r")) != NULL) {
497 
498 				while (fgets(buf, BUFSIZ - 1, p) != NULL) {
499 					unusual = unusual & ~NO_MAN_FOUND;
500 
501 					if ((cp2 = strchr(buf, '\n')) != NULL)
502 						*cp2 = '\0';
503 					if (regexec(&re, buf, 2,
504 						    matches, 0) == 0 &&
505 					    (rlen = matches[1].rm_eo -
506 					     matches[1].rm_so) > 0) {
507 						/*
508 						 * man -w found formatted
509 						 * page, need to pick up
510 						 * source page name.
511 						 */
512 						cp2 = malloc(rlen + 1);
513 						if (cp2 == NULL)
514 							abort();
515 						memcpy(cp2,
516 						       buf + matches[1].rm_so,
517 						       rlen);
518 						cp2[rlen] = '\0';
519 					} else {
520 						/*
521 						 * man -w found plain source
522 						 * page, use it.
523 						 */
524 						s = strlen(buf);
525 						cp2 = malloc(s + 1);
526 						if (cp2 == NULL)
527 							abort();
528 						strcpy(cp2, buf);
529 					}
530 
531 					if (man == NULL) {
532 						man = strdup(cp2);
533 					} else {
534 						olen = strlen(man);
535 						nlen = strlen(cp2);
536 						man = realloc(man,
537 							      olen + nlen + 2);
538 						if (man == NULL)
539 							abort();
540 						strcat(man, " ");
541 						strcat(man, cp2);
542 					}
543 
544 					free(cp2);
545 
546 					if (!opt_a)
547 						break;
548 				}
549 				pclose(p);
550 				free(cp);
551 			}
552 		}
553 
554 		if (opt_s) {
555 			/*
556 			 * Sources match if a subdir with the exact
557 			 * name is found.
558 			 */
559 			unusual = unusual | NO_SRC_FOUND;
560 			for (dp = sourcedirs; *dp != NULL; dp++) {
561 				cp = malloc(strlen(*dp) + 1 + s + 1);
562 				if (cp == NULL)
563 					abort();
564 				strcpy(cp, *dp);
565 				strcat(cp, "/");
566 				strcat(cp, name);
567 				if (stat(cp, &sb) == 0 &&
568 				    (sb.st_mode & S_IFMT) == S_IFDIR) {
569 					unusual = unusual & ~NO_SRC_FOUND;
570 					if (src == NULL) {
571 						src = strdup(cp);
572 					} else {
573 						olen = strlen(src);
574 						nlen = strlen(cp);
575 						src = realloc(src,
576 							      olen + nlen + 2);
577 						if (src == NULL)
578 							abort();
579 						strcat(src, " ");
580 						strcat(src, cp);
581 					}
582 					if (!opt_a) {
583 						free(cp);
584 						break;
585 					}
586 				}
587 				free(cp);
588 			}
589 			/*
590 			 * If still not found, ask locate to search it
591 			 * for us.  This will find sources for things
592 			 * like lpr that are well hidden in the
593 			 * /usr/src tree, but takes a lot longer.
594 			 * Thus, option -x (`expensive') prevents this
595 			 * search.
596 			 *
597 			 * Do only match locate output that starts
598 			 * with one of our source directories, and at
599 			 * least one further level of subdirectories.
600 			 */
601 			if (opt_x || (src && !opt_a))
602 				goto done_sources;
603 
604 			cp = malloc(sizeof LOCATECMD - 2 + s);
605 			if (cp == NULL)
606 				abort();
607 			sprintf(cp, LOCATECMD, name);
608 			if ((p = popen(cp, "r")) == NULL)
609 				goto done_sources;
610 			while ((src == NULL || opt_a) &&
611 			       (fgets(buf, BUFSIZ - 1, p)) != NULL) {
612 				if ((cp2 = strchr(buf, '\n')) != NULL)
613 					*cp2 = '\0';
614 				for (dp = sourcedirs;
615 				     (src == NULL || opt_a) && *dp != NULL;
616 				     dp++) {
617 					cp2 = malloc(strlen(*dp) + 9);
618 					if (cp2 == NULL)
619 						abort();
620 					strcpy(cp2, "^");
621 					strcat(cp2, *dp);
622 					strcat(cp2, "/[^/]+/");
623 					if ((i = regcomp(&re2, cp2,
624 							 REG_EXTENDED|REG_NOSUB))
625 					    != 0) {
626 						regerror(i, &re, buf,
627 							 BUFSIZ - 1);
628 						errx(EX_UNAVAILABLE,
629 						     "regcomp(%s) failed: %s",
630 						     cp2, buf);
631 					}
632 					free(cp2);
633 					if (regexec(&re2, buf, 0,
634 						    (regmatch_t *)NULL, 0)
635 					    == 0) {
636 						unusual = unusual &
637 						          ~NO_SRC_FOUND;
638 						if (src == NULL) {
639 							src = strdup(buf);
640 						} else {
641 							olen = strlen(src);
642 							nlen = strlen(buf);
643 							src = realloc(src,
644 								      olen +
645 								      nlen + 2);
646 							if (src == NULL)
647 								abort();
648 							strcat(src, " ");
649 							strcat(src, buf);
650 						}
651 					}
652 					regfree(&re2);
653 				}
654 			}
655 			pclose(p);
656 			free(cp);
657 		}
658 	  done_sources:
659 
660 		if (opt_u && !unusual)
661 			continue;
662 
663 		printed = 0;
664 		if (!opt_q) {
665 			printf("%s:", name);
666 			printed++;
667 		}
668 		if (bin) {
669 			if (printed++)
670 				putchar(' ');
671 			fputs(bin, stdout);
672 		}
673 		if (man) {
674 			if (printed++)
675 				putchar(' ');
676 			fputs(man, stdout);
677 		}
678 		if (src) {
679 			if (printed++)
680 				putchar(' ');
681 			fputs(src, stdout);
682 		}
683 		if (printed)
684 			putchar('\n');
685 	}
686 
687 	if (opt_m)
688 		regfree(&re);
689 
690 	return (0);
691 }
692