xref: /freebsd/usr.bin/whereis/whereis.c (revision 1f05bc6c92b037a24315c8408aab875bbd6453b8)
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 <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 int opt_a, opt_b, opt_m, opt_q, opt_s, opt_u, opt_x;
59 ccharp *bindirs, *mandirs, *sourcedirs;
60 char **query;
61 
62 const char *sourcepath = PATH_SOURCES;
63 
64 char	*colonify(ccharp *);
65 int	 contains(ccharp *, const char *);
66 void	 decolonify(char *, ccharp **, int *);
67 void	 defaults(void);
68 void	 scanopts(int, char **);
69 void	 usage(void);
70 
71 /*
72  * Throughout this program, a number of strings are dynamically
73  * allocated but never freed.  Their memory is written to when
74  * splitting the strings into string lists which will later be
75  * processed.  Since it's important that those string lists remain
76  * valid even after the functions allocating the memory returned,
77  * those functions cannot free them.  They could be freed only at end
78  * of main(), which is pretty pointless anyway.
79  *
80  * The overall amount of memory to be allocated for processing the
81  * strings is not expected to exceed a few kilobytes.  For that
82  * reason, allocation can usually always be assumed to succeed (within
83  * a virtual memory environment), thus we simply bail out using
84  * abort(3) in case of an allocation failure.
85  */
86 
87 void
88 usage(void)
89 {
90 	errx(EX_USAGE,
91 	     "usage: whereis [-abmqsux] [-BMS dir... -f] name ...");
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 void
101 scanopts(int argc, char **argv)
102 {
103 	int c, i, opt_f;
104 	ccharp **dirlist;
105 
106 	opt_f = 0;
107 	while ((c = getopt(argc, argv, "BMSabfmqsux")) != -1)
108 		switch (c) {
109 		case 'B':
110 			dirlist = &bindirs;
111 			goto dolist;
112 
113 		case 'M':
114 			dirlist = &mandirs;
115 			goto dolist;
116 
117 		case 'S':
118 			dirlist = &sourcedirs;
119 		  dolist:
120 			i = 0;
121 			*dirlist = realloc(*dirlist, (i + 1) * sizeof(char *));
122 			(*dirlist)[i] = NULL;
123 			while (optind < argc &&
124 			       strcmp(argv[optind], "-f") != 0 &&
125 			       strcmp(argv[optind], "-B") != 0 &&
126 			       strcmp(argv[optind], "-M") != 0 &&
127 			       strcmp(argv[optind], "-S") != 0) {
128 				decolonify(argv[optind], dirlist, &i);
129 				optind++;
130 			}
131 			break;
132 
133 		case 'a':
134 			opt_a = 1;
135 			break;
136 
137 		case 'b':
138 			opt_b = 1;
139 			break;
140 
141 		case 'f':
142 			goto breakout;
143 
144 		case 'm':
145 			opt_m = 1;
146 			break;
147 
148 		case 'q':
149 			opt_q = 1;
150 			break;
151 
152 		case 's':
153 			opt_s = 1;
154 			break;
155 
156 		case 'u':
157 			opt_u = 1;
158 			break;
159 
160 		case 'x':
161 			opt_x = 1;
162 			break;
163 
164 		default:
165 			usage();
166 		}
167   breakout:
168 	if (optind == argc)
169 		usage();
170 	query = argv + optind;
171 }
172 
173 /*
174  * Find out whether string `s' is contained in list `cpp'.
175  */
176 int
177 contains(ccharp *cpp, const char *s)
178 {
179 	ccharp cp;
180 
181 	if (cpp == NULL)
182 		return (0);
183 
184 	while ((cp = *cpp) != NULL) {
185 		if (strcmp(cp, s) == 0)
186 			return (1);
187 		cpp++;
188 	}
189 	return (0);
190 }
191 
192 /*
193  * Split string `s' at colons, and pass it to the string list pointed
194  * to by `cppp' (which has `*ip' elements).  Note that the original
195  * string is modified by replacing the colon with a NUL byte.  The
196  * partial string is only added if it has a length greater than 0, and
197  * if it's not already contained in the string list.
198  */
199 void
200 decolonify(char *s, ccharp **cppp, int *ip)
201 {
202 	char *cp;
203 
204 	while ((cp = strchr(s, ':')), *s != '\0') {
205 		if (cp)
206 			*cp = '\0';
207 		if (strlen(s) && !contains(*cppp, s)) {
208 			*cppp = realloc(*cppp, (*ip + 2) * sizeof(char *));
209 			if (cppp == NULL)
210 				abort();
211 			(*cppp)[*ip] = s;
212 			(*cppp)[*ip + 1] = NULL;
213 			(*ip)++;
214 		}
215 		if (cp)
216 			s = cp + 1;
217 		else
218 			break;
219 	}
220 }
221 
222 /*
223  * Join string list `cpp' into a colon-separated string.
224  */
225 char *
226 colonify(ccharp *cpp)
227 {
228 	size_t s;
229 	char *cp;
230 	int i;
231 
232 	if (cpp == NULL)
233 		return (0);
234 
235 	for (s = 0, i = 0; cpp[i] != NULL; i++)
236 		s += strlen(cpp[i]) + 1;
237 	if ((cp = malloc(s + 1)) == NULL)
238 		abort();
239 	for (i = 0, *cp = '\0'; cpp[i] != NULL; i++) {
240 		strcat(cp, cpp[i]);
241 		strcat(cp, ":");
242 	}
243 	cp[s - 1] = '\0';		/* eliminate last colon */
244 
245 	return (cp);
246 }
247 
248 /*
249  * Provide defaults for all options and directory lists.
250  */
251 void
252 defaults(void)
253 {
254 	size_t s;
255 	char *b, buf[BUFSIZ], *cp;
256 	int nele;
257 	FILE *p;
258 	DIR *dir;
259 	struct stat sb;
260 	struct dirent *dirp;
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 	 * /usr/games + user's path */
268 	if (!bindirs) {
269 		if (sysctlbyname("user.cs_path", (void *)NULL, &s,
270 				 (void *)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, (void *)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/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 			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_PORTS + 1 + dirp->d_namlen))
336 			    == NULL)
337 				abort();
338 			strcpy(b, PATH_PORTS);
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 	scanopts(argc, argv);
372 	defaults();
373 
374 	if (mandirs == NULL)
375 		opt_m = 0;
376 	if (bindirs == NULL)
377 		opt_b = 0;
378 	if (sourcedirs == NULL)
379 		opt_s = 0;
380 	if (opt_m + opt_b + opt_s == 0)
381 		errx(EX_DATAERR, "no directories to search");
382 
383 	if (opt_m) {
384 		setenv("MANPATH", colonify(mandirs), 1);
385 		if ((i = regcomp(&re, MANWHEREISMATCH, REG_EXTENDED)) != 0) {
386 			regerror(i, &re, buf, BUFSIZ - 1);
387 			errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s",
388 			     MANWHEREISMATCH, buf);
389 		}
390 	}
391 
392 	for (; (name = *query) != NULL; query++) {
393 		/* strip leading path name component */
394 		if ((cp = strrchr(name, '/')) != NULL)
395 			name = cp + 1;
396 		/* strip SCCS or RCS suffix/prefix */
397 		if (strlen(name) > 2 && strncmp(name, "s.", 2) == 0)
398 			name += 2;
399 		if ((s = strlen(name)) > 2 && strcmp(name + s - 2, ",v") == 0)
400 			name[s - 2] = '\0';
401 		/* compression suffix */
402 		s = strlen(name);
403 		if (s > 2 &&
404 		    (strcmp(name + s - 2, ".z") == 0 ||
405 		     strcmp(name + s - 2, ".Z") == 0))
406 			name[s - 2] = '\0';
407 		else if (s > 3 &&
408 			 strcmp(name + s - 3, ".gz") == 0)
409 			name[s - 3] = '\0';
410 		else if (s > 4 &&
411 			 strcmp(name + s - 4, ".bz2") == 0)
412 			name[s - 4] = '\0';
413 
414 		unusual = 0;
415 		bin = man = src = NULL;
416 		s = strlen(name);
417 
418 		if (opt_b) {
419 			/*
420 			 * Binaries have to match exactly, and must be regular
421 			 * executable files.
422 			 */
423 			unusual = unusual | NO_BIN_FOUND;
424 			for (dp = bindirs; *dp != NULL; dp++) {
425 				cp = malloc(strlen(*dp) + 1 + s + 1);
426 				if (cp == NULL)
427 					abort();
428 				strcpy(cp, *dp);
429 				strcat(cp, "/");
430 				strcat(cp, name);
431 				if (stat(cp, &sb) == 0 &&
432 				    (sb.st_mode & S_IFMT) == S_IFREG &&
433 				    (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
434 				    != 0) {
435 					unusual = unusual & ~NO_BIN_FOUND;
436 					if (bin == NULL) {
437 						bin = strdup(cp);
438 					} else {
439 						olen = strlen(bin);
440 						nlen = strlen(cp);
441 						bin = realloc(bin,
442 							      olen + nlen + 2);
443 						if (bin == 0)
444 							abort();
445 						strcat(bin, " ");
446 						strcat(bin, cp);
447 					}
448 					if (!opt_a) {
449 						free(cp);
450 						break;
451 					}
452 				}
453 				free(cp);
454 			}
455 		}
456 
457 		if (opt_m) {
458 			/*
459 			 * Ask the man command to perform the search for us.
460 			 */
461 			unusual = unusual | NO_MAN_FOUND;
462 			if (opt_a)
463 				cp = malloc(sizeof MANWHEREISALLCMD - 2 + s);
464 			else
465 				cp = malloc(sizeof MANWHEREISCMD - 2 + s);
466 
467 			if (cp == NULL)
468 				abort();
469 
470 			if (opt_a)
471 				sprintf(cp, MANWHEREISALLCMD, name);
472 			else
473 				sprintf(cp, MANWHEREISCMD, name);
474 
475 			if ((p = popen(cp, "r")) != NULL) {
476 
477 				while (fgets(buf, BUFSIZ - 1, p) != NULL) {
478 					unusual = unusual & ~NO_MAN_FOUND;
479 
480 					if ((cp2 = strchr(buf, '\n')) != NULL)
481 						*cp2 = '\0';
482 					if (regexec(&re, buf, 2,
483 						    matches, 0) == 0 &&
484 					    (rlen = matches[1].rm_eo -
485 					     matches[1].rm_so) > 0) {
486 						/*
487 						 * man -w found formated
488 						 * page, need to pick up
489 						 * source page name.
490 						 */
491 						cp2 = malloc(rlen + 1);
492 						if (cp2 == NULL)
493 							abort();
494 						memcpy(cp2,
495 						       buf + matches[1].rm_so,
496 						       rlen);
497 						cp2[rlen] = '\0';
498 					} else {
499 						/*
500 						 * man -w found plain source
501 						 * page, use it.
502 						 */
503 						s = strlen(buf);
504 						cp2 = malloc(s + 1);
505 						if (cp2 == NULL)
506 							abort();
507 						strcpy(cp2, buf);
508 					}
509 
510 					if (man == NULL) {
511 						man = strdup(cp2);
512 					} else {
513 						olen = strlen(man);
514 						nlen = strlen(cp2);
515 						man = realloc(man,
516 							      olen + nlen + 2);
517 						if (man == 0)
518 							abort();
519 						strcat(man, " ");
520 						strcat(man, cp2);
521 					}
522 
523 					free(cp2);
524 
525 					if (!opt_a)
526 						break;
527 				}
528 				pclose(p);
529 				free(cp);
530 			}
531 		}
532 
533 		if (opt_s) {
534 			/*
535 			 * Sources match if a subdir with the exact
536 			 * name is found.
537 			 */
538 			unusual = unusual | NO_SRC_FOUND;
539 			for (dp = sourcedirs; *dp != NULL; dp++) {
540 				cp = malloc(strlen(*dp) + 1 + s + 1);
541 				if (cp == NULL)
542 					abort();
543 				strcpy(cp, *dp);
544 				strcat(cp, "/");
545 				strcat(cp, name);
546 				if (stat(cp, &sb) == 0 &&
547 				    (sb.st_mode & S_IFMT) == S_IFDIR) {
548 					unusual = unusual & ~NO_SRC_FOUND;
549 					if (src == NULL) {
550 						src = strdup(cp);
551 					} else {
552 						olen = strlen(src);
553 						nlen = strlen(cp);
554 						src = realloc(src,
555 							      olen + nlen + 2);
556 						if (src == 0)
557 							abort();
558 						strcat(src, " ");
559 						strcat(src, cp);
560 					}
561 					if (!opt_a) {
562 						free(cp);
563 						break;
564 					}
565 				}
566 				free(cp);
567 			}
568 			/*
569 			 * If still not found, ask locate to search it
570 			 * for us.  This will find sources for things
571 			 * like lpr that are well hidden in the
572 			 * /usr/src tree, but takes a lot longer.
573 			 * Thus, option -x (`expensive') prevents this
574 			 * search.
575 			 *
576 			 * Do only match locate output that starts
577 			 * with one of our source directories, and at
578 			 * least one further level of subdirectories.
579 			 */
580 			if (opt_x || (src && !opt_a))
581 				goto done_sources;
582 
583 			cp = malloc(sizeof LOCATECMD - 2 + s);
584 			if (cp == NULL)
585 				abort();
586 			sprintf(cp, LOCATECMD, name);
587 			if ((p = popen(cp, "r")) == NULL)
588 				goto done_sources;
589 			while ((src == NULL || opt_a) &&
590 			       (fgets(buf, BUFSIZ - 1, p)) != NULL) {
591 				if ((cp2 = strchr(buf, '\n')) != NULL)
592 					*cp2 = '\0';
593 				for (dp = sourcedirs;
594 				     (src == NULL || opt_a) && *dp != NULL;
595 				     dp++) {
596 					cp2 = malloc(strlen(*dp) + 9);
597 					if (cp2 == NULL)
598 						abort();
599 					strcpy(cp2, "^");
600 					strcat(cp2, *dp);
601 					strcat(cp2, "/[^/]+/");
602 					if ((i = regcomp(&re2, cp2,
603 							 REG_EXTENDED|REG_NOSUB))
604 					    != 0) {
605 						regerror(i, &re, buf,
606 							 BUFSIZ - 1);
607 						errx(EX_UNAVAILABLE,
608 						     "regcomp(%s) failed: %s",
609 						     cp2, buf);
610 					}
611 					free(cp2);
612 					if (regexec(&re2, buf, 0,
613 						    (regmatch_t *)NULL, 0)
614 					    == 0) {
615 						unusual = unusual &
616 						          ~NO_SRC_FOUND;
617 						if (src == NULL) {
618 							src = strdup(buf);
619 						} else {
620 							olen = strlen(src);
621 							nlen = strlen(buf);
622 							src = realloc(src,
623 								      olen +
624 								      nlen + 2);
625 							if (src == 0)
626 								abort();
627 							strcat(src, " ");
628 							strcat(src, buf);
629 						}
630 					}
631 					regfree(&re2);
632 				}
633 			}
634 			pclose(p);
635 			free(cp);
636 		}
637 	  done_sources:
638 
639 		if (opt_u && !unusual)
640 			continue;
641 
642 		printed = 0;
643 		if (!opt_q) {
644 			printf("%s:", name);
645 			printed++;
646 		}
647 		if (bin) {
648 			if (printed++)
649 				putchar(' ');
650 			fputs(bin, stdout);
651 		}
652 		if (man) {
653 			if (printed++)
654 				putchar(' ');
655 			fputs(man, stdout);
656 		}
657 		if (src) {
658 			if (printed++)
659 				putchar(' ');
660 			fputs(src, stdout);
661 		}
662 		if (printed)
663 			putchar('\n');
664 	}
665 
666 	if (opt_m)
667 		regfree(&re);
668 
669 	return (0);
670 }
671