xref: /freebsd/usr.bin/whereis/whereis.c (revision e7b019fbf1a0f02386a8d02eac4a691f112cc242)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright © 2002, Jörg Wunsch
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
19  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
23  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
24  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
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 #include <sys/param.h>
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 char	*colonify(ccharp *);
64 static int	 contains(ccharp *, const char *);
65 static void	 decolonify(char *, ccharp **, int *);
66 static void	 defaults(void);
67 static void	 scanopts(int, char **);
68 static void	 usage(void);
69 
70 /*
71  * Throughout this program, a number of strings are dynamically
72  * allocated but never freed.  Their memory is written to when
73  * splitting the strings into string lists which will later be
74  * processed.  Since it's important that those string lists remain
75  * valid even after the functions allocating the memory returned,
76  * those functions cannot free them.  They could be freed only at end
77  * of main(), which is pretty pointless anyway.
78  *
79  * The overall amount of memory to be allocated for processing the
80  * strings is not expected to exceed a few kilobytes.  For that
81  * reason, allocation can usually always be assumed to succeed (within
82  * a virtual memory environment), thus we simply bail out using
83  * abort(3) in case of an allocation failure.
84  */
85 
86 static void
87 usage(void)
88 {
89 	(void)fprintf(stderr,
90 	     "usage: whereis [-abmqsux] [-BMS dir ... -f] program ...\n");
91 	exit(EX_USAGE);
92 }
93 
94 /*
95  * Scan options passed to program.
96  *
97  * Note that the -B/-M/-S options expect a list of directory
98  * names that must be terminated with -f.
99  */
100 static void
101 scanopts(int argc, char **argv)
102 {
103 	int c, i;
104 	ccharp **dirlist;
105 
106 	while ((c = getopt(argc, argv, "BMSabfmqsux")) != -1)
107 		switch (c) {
108 		case 'B':
109 			dirlist = &bindirs;
110 			goto dolist;
111 
112 		case 'M':
113 			dirlist = &mandirs;
114 			goto dolist;
115 
116 		case 'S':
117 			dirlist = &sourcedirs;
118 		  dolist:
119 			i = 0;
120 			*dirlist = realloc(*dirlist, (i + 1) * sizeof(char *));
121 			(*dirlist)[i] = NULL;
122 			while (optind < argc &&
123 			       strcmp(argv[optind], "-f") != 0 &&
124 			       strcmp(argv[optind], "-B") != 0 &&
125 			       strcmp(argv[optind], "-M") != 0 &&
126 			       strcmp(argv[optind], "-S") != 0) {
127 				decolonify(argv[optind], dirlist, &i);
128 				optind++;
129 			}
130 			break;
131 
132 		case 'a':
133 			opt_a = 1;
134 			break;
135 
136 		case 'b':
137 			opt_b = 1;
138 			break;
139 
140 		case 'f':
141 			goto breakout;
142 
143 		case 'm':
144 			opt_m = 1;
145 			break;
146 
147 		case 'q':
148 			opt_q = 1;
149 			break;
150 
151 		case 's':
152 			opt_s = 1;
153 			break;
154 
155 		case 'u':
156 			opt_u = 1;
157 			break;
158 
159 		case 'x':
160 			opt_x = 1;
161 			break;
162 
163 		default:
164 			usage();
165 		}
166   breakout:
167 	if (optind == argc)
168 		usage();
169 	query = argv + optind;
170 }
171 
172 /*
173  * Find out whether string `s' is contained in list `cpp'.
174  */
175 static int
176 contains(ccharp *cpp, const char *s)
177 {
178 	ccharp cp;
179 
180 	if (cpp == NULL)
181 		return (0);
182 
183 	while ((cp = *cpp) != NULL) {
184 		if (strcmp(cp, s) == 0)
185 			return (1);
186 		cpp++;
187 	}
188 	return (0);
189 }
190 
191 /*
192  * Split string `s' at colons, and pass it to the string list pointed
193  * to by `cppp' (which has `*ip' elements).  Note that the original
194  * string is modified by replacing the colon with a NUL byte.  The
195  * partial string is only added if it has a length greater than 0, and
196  * if it's not already contained in the string list.
197  */
198 static void
199 decolonify(char *s, ccharp **cppp, int *ip)
200 {
201 	char *cp;
202 
203 	while ((cp = strchr(s, ':')), *s != '\0') {
204 		if (cp)
205 			*cp = '\0';
206 		if (strlen(s) && !contains(*cppp, s)) {
207 			*cppp = realloc(*cppp, (*ip + 2) * sizeof(char *));
208 			if (*cppp == NULL)
209 				abort();
210 			(*cppp)[*ip] = s;
211 			(*cppp)[*ip + 1] = NULL;
212 			(*ip)++;
213 		}
214 		if (cp)
215 			s = cp + 1;
216 		else
217 			break;
218 	}
219 }
220 
221 /*
222  * Join string list `cpp' into a colon-separated string.
223  */
224 static char *
225 colonify(ccharp *cpp)
226 {
227 	size_t s;
228 	char *cp;
229 	int i;
230 
231 	if (cpp == NULL)
232 		return (0);
233 
234 	for (s = 0, i = 0; cpp[i] != NULL; i++)
235 		s += strlen(cpp[i]) + 1;
236 	if ((cp = malloc(s + 1)) == NULL)
237 		abort();
238 	for (i = 0, *cp = '\0'; cpp[i] != NULL; i++) {
239 		strcat(cp, cpp[i]);
240 		strcat(cp, ":");
241 	}
242 	cp[s - 1] = '\0';		/* eliminate last colon */
243 
244 	return (cp);
245 }
246 
247 /*
248  * Provide defaults for all options and directory lists.
249  */
250 static void
251 defaults(void)
252 {
253 	size_t i, s;
254 	char *b, buf[BUFSIZ], *cp;
255 	const char *path_ports;
256 	int nele;
257 	FILE *p;
258 	DIR *dir;
259 	struct stat sb;
260 	struct dirent *dirp;
261 	const int oid[2] = {CTL_USER, USER_CS_PATH};
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 (sysctl(oid, 2, NULL, &s, NULL, 0) == -1)
271 			err(EX_OSERR, "sysctl(\"user.cs_path\")");
272 		if ((b = malloc(s + 1)) == NULL)
273 			abort();
274 		if (sysctl(oid, 2, b, &s, NULL, 0) == -1)
275 			err(EX_OSERR, "sysctl(\"user.cs_path\")");
276 		nele = 0;
277 		decolonify(b, &bindirs, &nele);
278 		bindirs = realloc(bindirs, (nele + 2) * sizeof(char *));
279 		if (bindirs == NULL)
280 			abort();
281 		bindirs[nele++] = PATH_LIBEXEC;
282 		bindirs[nele] = NULL;
283 		if ((cp = getenv("PATH")) != NULL) {
284 			/* don't destroy the original environment... */
285 			b = strdup(cp);
286 			if (b == NULL)
287 				abort();
288 			decolonify(b, &bindirs, &nele);
289 		}
290 	}
291 
292 	/* -m defaults to $(manpath) */
293 	if (!mandirs) {
294 		if ((p = popen(MANPATHCMD, "r")) == NULL)
295 			err(EX_OSERR, "cannot execute manpath command");
296 		if (fgets(buf, BUFSIZ - 1, p) == NULL ||
297 		    pclose(p))
298 			err(EX_OSERR, "error processing manpath results");
299 		if ((b = strchr(buf, '\n')) != NULL)
300 			*b = '\0';
301 		b = strdup(buf);
302 		if (b == NULL)
303 			abort();
304 		nele = 0;
305 		decolonify(b, &mandirs, &nele);
306 	}
307 
308 	/* -s defaults to precompiled list, plus subdirs of
309 	 * $PORTSDIR. If not set, it defaults to /usr/ports */
310 	if (!sourcedirs) {
311 		s = nitems(sourcepaths);
312 		sourcedirs = malloc(s * sizeof(char *));
313 		if (sourcedirs == NULL)
314 			abort();
315 		for (i = 0; i < s; i++)
316 			sourcedirs[i] = sourcepaths[i];
317 
318 		path_ports = getenv("PORTSDIR");
319 		if (path_ports == NULL)
320 			path_ports = PATH_PORTS;
321 
322 		if (stat(path_ports, &sb) == -1) {
323 			if (errno == ENOENT)
324 				/* no ports directory, we are done */
325 				return;
326 			err(EX_OSERR, "stat(%s)", path_ports);
327 		}
328 		if ((sb.st_mode & S_IFMT) != S_IFDIR)
329 			/* path_ports is not a directory, ignore */
330 			return;
331 		if (access(path_ports, R_OK | X_OK) != 0)
332 			return;
333 		if ((dir = opendir(path_ports)) == NULL)
334 			err(EX_OSERR, "opendir(%s)", path_ports);
335 
336 		/*
337 		 * Move the index one element back so if we end up adding some
338 		 * port directories, we place them back to back to the
339 		 * sourcepaths and the NULL element shows only at the end (used
340 		 * later on as end-o-array marker)
341 		 */
342 		--i;
343 
344 		while ((dirp = readdir(dir)) != NULL) {
345 			/*
346 			 * Not everything below path_ports is of
347 			 * interest.  First, all dot files and
348 			 * directories (e. g. .snap) can be ignored.
349 			 * Also, all subdirectories starting with a
350 			 * capital letter are not going to
351 			 * examined, as they are used for internal
352 			 * purposes (Mk, Tools, ...).  Finally, the distfiles
353 			 * subdirectory is also special, and should not be
354 			 * considered to avoid false matches.
355 			 */
356 			if (dirp->d_name[0] == '.' ||
357 			    /*
358 			     * isupper() not used on purpose: the
359 			     * check is supposed to default to the C
360 			     * locale instead of the current user's
361 			     * locale.
362 			     */
363 			    (dirp->d_name[0] >= 'A' && dirp->d_name[0] <= 'Z') ||
364 			    strcmp(dirp->d_name, "distfiles") == 0)
365 				continue;
366 			if (asprintf(&b, "%s/%s", path_ports, dirp->d_name) < 0)
367 				abort();
368 			if (stat(b, &sb) == -1 ||
369 			    (sb.st_mode & S_IFMT) != S_IFDIR ||
370 			    access(b, R_OK | X_OK) != 0) {
371 				free(b);
372 				continue;
373 			}
374 			sourcedirs = realloc(sourcedirs,
375 					     (i + 2) * sizeof(char *));
376 			if (sourcedirs == NULL)
377 				abort();
378 			sourcedirs[i++] = b;
379 			sourcedirs[i] = NULL;
380 		}
381 		closedir(dir);
382 	}
383 }
384 
385 int
386 main(int argc, char **argv)
387 {
388 	int unusual, i, printed;
389 	char *bin, buf[BUFSIZ], *cp, *cp2, *man, *name, *src;
390 	ccharp *dp;
391 	size_t nlen, olen, s;
392 	struct stat sb;
393 	regex_t re, re2;
394 	regmatch_t matches[2];
395 	regoff_t rlen;
396 	FILE *p;
397 
398 	setlocale(LC_ALL, "");
399 
400 	scanopts(argc, argv);
401 	defaults();
402 
403 	if (mandirs == NULL)
404 		opt_m = 0;
405 	if (bindirs == NULL)
406 		opt_b = 0;
407 	if (sourcedirs == NULL)
408 		opt_s = 0;
409 	if (opt_m + opt_b + opt_s == 0)
410 		errx(EX_DATAERR, "no directories to search");
411 
412 	if (opt_m) {
413 		char *mp = colonify(mandirs);
414 		setenv("MANPATH", mp, 1);
415 		free(mp);
416 		if ((i = regcomp(&re, MANWHEREISMATCH, REG_EXTENDED)) != 0) {
417 			regerror(i, &re, buf, BUFSIZ - 1);
418 			errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s",
419 			     MANWHEREISMATCH, buf);
420 		}
421 	}
422 
423 	for (; (name = *query) != NULL; query++) {
424 		/* strip leading path name component */
425 		if ((cp = strrchr(name, '/')) != NULL)
426 			name = cp + 1;
427 		/* strip SCCS or RCS suffix/prefix */
428 		if (strlen(name) > 2 && strncmp(name, "s.", 2) == 0)
429 			name += 2;
430 		if ((s = strlen(name)) > 2 && strcmp(name + s - 2, ",v") == 0)
431 			name[s - 2] = '\0';
432 		/* compression suffix */
433 		s = strlen(name);
434 		if (s > 2 &&
435 		    (strcmp(name + s - 2, ".z") == 0 ||
436 		     strcmp(name + s - 2, ".Z") == 0))
437 			name[s - 2] = '\0';
438 		else if (s > 3 &&
439 			 strcmp(name + s - 3, ".gz") == 0)
440 			name[s - 3] = '\0';
441 		else if (s > 4 &&
442 			 strcmp(name + s - 4, ".bz2") == 0)
443 			name[s - 4] = '\0';
444 
445 		unusual = 0;
446 		bin = man = src = NULL;
447 		s = strlen(name);
448 
449 		if (opt_b) {
450 			/*
451 			 * Binaries have to match exactly, and must be regular
452 			 * executable files.
453 			 */
454 			unusual = unusual | NO_BIN_FOUND;
455 			for (dp = bindirs; *dp != NULL; dp++) {
456 				if (asprintf(&cp, "%s/%s", *dp, name) < 0)
457 					abort();
458 				if (stat(cp, &sb) == 0 &&
459 				    (sb.st_mode & S_IFMT) == S_IFREG &&
460 				    (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
461 				    != 0) {
462 					unusual = unusual & ~NO_BIN_FOUND;
463 					if (bin == NULL) {
464 						bin = strdup(cp);
465 					} else {
466 						olen = strlen(bin);
467 						nlen = strlen(cp);
468 						bin = realloc(bin,
469 							      olen + nlen + 2);
470 						if (bin == NULL)
471 							abort();
472 						strcat(bin, " ");
473 						strcat(bin, cp);
474 					}
475 					if (!opt_a) {
476 						free(cp);
477 						break;
478 					}
479 				}
480 				free(cp);
481 			}
482 		}
483 
484 		if (opt_m) {
485 			/*
486 			 * Ask the man command to perform the search for us.
487 			 */
488 			unusual = unusual | NO_MAN_FOUND;
489 			if (opt_a)
490 				cp = malloc(sizeof MANWHEREISALLCMD - 2 + s);
491 			else
492 				cp = malloc(sizeof MANWHEREISCMD - 2 + s);
493 
494 			if (cp == NULL)
495 				abort();
496 
497 			if (opt_a)
498 				sprintf(cp, MANWHEREISALLCMD, name);
499 			else
500 				sprintf(cp, MANWHEREISCMD, name);
501 
502 			if ((p = popen(cp, "r")) != NULL) {
503 
504 				while (fgets(buf, BUFSIZ - 1, p) != NULL) {
505 					unusual = unusual & ~NO_MAN_FOUND;
506 
507 					if ((cp2 = strchr(buf, '\n')) != NULL)
508 						*cp2 = '\0';
509 					if (regexec(&re, buf, 2,
510 						    matches, 0) == 0 &&
511 					    (rlen = matches[1].rm_eo -
512 					     matches[1].rm_so) > 0) {
513 						/*
514 						 * man -w found formatted
515 						 * page, need to pick up
516 						 * source page name.
517 						 */
518 						cp2 = malloc(rlen + 1);
519 						if (cp2 == NULL)
520 							abort();
521 						memcpy(cp2,
522 						       buf + matches[1].rm_so,
523 						       rlen);
524 						cp2[rlen] = '\0';
525 					} else {
526 						/*
527 						 * man -w found plain source
528 						 * page, use it.
529 						 */
530 						cp2 = strdup(buf);
531 						if (cp2 == NULL)
532 							abort();
533 					}
534 
535 					if (man == NULL) {
536 						man = strdup(cp2);
537 					} else {
538 						olen = strlen(man);
539 						nlen = strlen(cp2);
540 						man = realloc(man,
541 							      olen + nlen + 2);
542 						if (man == NULL)
543 							abort();
544 						strcat(man, " ");
545 						strcat(man, cp2);
546 					}
547 
548 					free(cp2);
549 
550 					if (!opt_a)
551 						break;
552 				}
553 				pclose(p);
554 				free(cp);
555 			}
556 		}
557 
558 		if (opt_s) {
559 			/*
560 			 * Sources match if a subdir with the exact
561 			 * name is found.
562 			 */
563 			unusual = unusual | NO_SRC_FOUND;
564 			for (dp = sourcedirs; *dp != NULL; dp++) {
565 				if (asprintf(&cp, "%s/%s", *dp, name) < 0)
566 					abort();
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 					if (asprintf(&cp2, "^%s/[^/]+/", *dp) < 0)
618 						abort();
619 					if ((i = regcomp(&re2, cp2,
620 							 REG_EXTENDED|REG_NOSUB))
621 					    != 0) {
622 						regerror(i, &re, buf,
623 							 BUFSIZ - 1);
624 						errx(EX_UNAVAILABLE,
625 						     "regcomp(%s) failed: %s",
626 						     cp2, buf);
627 					}
628 					free(cp2);
629 					if (regexec(&re2, buf, 0,
630 						    (regmatch_t *)NULL, 0)
631 					    == 0) {
632 						unusual = unusual &
633 						          ~NO_SRC_FOUND;
634 						if (src == NULL) {
635 							src = strdup(buf);
636 						} else {
637 							olen = strlen(src);
638 							nlen = strlen(buf);
639 							src = realloc(src,
640 								      olen +
641 								      nlen + 2);
642 							if (src == NULL)
643 								abort();
644 							strcat(src, " ");
645 							strcat(src, buf);
646 						}
647 					}
648 					regfree(&re2);
649 				}
650 			}
651 			pclose(p);
652 			free(cp);
653 		}
654 	  done_sources:
655 
656 		if (opt_u && !unusual)
657 			continue;
658 
659 		printed = 0;
660 		if (!opt_q) {
661 			printf("%s:", name);
662 			printed++;
663 		}
664 		if (bin) {
665 			if (printed++)
666 				putchar(' ');
667 			fputs(bin, stdout);
668 		}
669 		if (man) {
670 			if (printed++)
671 				putchar(' ');
672 			fputs(man, stdout);
673 		}
674 		if (src) {
675 			if (printed++)
676 				putchar(' ');
677 			fputs(src, stdout);
678 		}
679 		if (printed)
680 			putchar('\n');
681 	}
682 
683 	if (opt_m)
684 		regfree(&re);
685 
686 	return (0);
687 }
688