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