#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1993\
The Regents of the University of California. All rights reserved.");
#endif
#ifndef lint
#if 0
static char sccsid[] = "@(#)whereis.c 8.3 (Berkeley) 5/4/95";
#endif
__RCSID("$NetBSD: whereis.c,v 1.22 2025/06/01 15:45:31 jschauma Exp $");
#endif
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void usage(void) __dead;
int
main(int argc, char *argv[])
{
struct stat sb;
size_t len;
int ch, mib[2];
char *p, *std, path[MAXPATHLEN];
const char *t;
int which = strcmp(getprogname(), "which") == 0;
int useenvpath = which, found = 0;
gid_t egid = getegid();
uid_t euid = geteuid();
if (setregid(egid, egid) == -1)
err(1, "Can't set gid to %lu", (unsigned long)egid);
if (setreuid(euid, euid) == -1)
err(1, "Can't set uid to %lu", (unsigned long)euid);
while ((ch = getopt(argc, argv, "ap")) != -1)
switch (ch) {
case 'a':
which = 0;
break;
case 'p':
useenvpath = 1;
break;
case '?':
default:
usage();
}
argc -= optind;
argv += optind;
if (argc == 0)
usage();
if (useenvpath) {
if ((std = getenv("PATH")) == NULL)
errx(1, "PATH environment variable is not set");
} else {
mib[0] = CTL_USER;
mib[1] = USER_CS_PATH;
if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1)
err(1, "sysctl: user.cs_path");
if (len == 0)
errx(1, "sysctl: user.cs_path (zero length)");
if ((std = malloc(len)) == NULL)
err(1, NULL);
if (sysctl(mib, 2, std, &len, NULL, 0) == -1)
err(1, "sysctl: user.cs_path");
}
for (; *argv; ++argv) {
if (**argv == '/') {
if (stat(*argv, &sb) == -1)
continue;
if (!S_ISREG(sb.st_mode))
continue;
if (access(*argv, X_OK) == -1)
continue;
(void)printf("%s\n", *argv);
found++;
if (which)
continue;
} else for (p = std; p; ) {
t = p;
if ((p = strchr(p, ':')) != NULL) {
*p = '\0';
if (t == p)
t = ".";
} else
if (strlen(t) == 0)
t = ".";
(void)snprintf(path, sizeof(path), "%s/%s", t, *argv);
len = snprintf(path, sizeof(path), "%s/%s", t, *argv);
if (p)
*p++ = ':';
if (len >= sizeof(path))
continue;
if (stat(path, &sb) == -1)
continue;
if (!S_ISREG(sb.st_mode))
continue;
if (access(path, X_OK) == -1)
continue;
(void)printf("%s\n", path);
found++;
if (which)
break;
}
}
return ((found == 0) ? 3 : ((found >= argc) ? 0 : 2));
}
static void
usage(void)
{
(void)fprintf(stderr, "Usage: %s [-ap] program [...]\n", getprogname());
exit(1);
}