2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2000 Dan Papasian. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
41 static void usage(void);
42 static int print_matches(char *, char *);
48 main(int argc, char **argv)
54 status = EXIT_SUCCESS;
56 while ((opt = getopt(argc, argv, "as")) != -1) {
76 if ((p = getenv("PATH")) == NULL)
78 pathlen = strlen(p) + 1;
79 path = malloc(pathlen);
81 err(EXIT_FAILURE, NULL);
84 memcpy(path, p, pathlen);
86 if (strlen(*argv) >= FILENAME_MAX ||
87 print_matches(path, *argv) == -1)
88 status = EXIT_FAILURE;
101 (void)fprintf(stderr, "usage: which [-as] program ...\n");
106 is_there(char *candidate)
110 /* XXX work around access(2) false positives for superuser */
111 if (access(candidate, X_OK) == 0 &&
112 stat(candidate, &fin) == 0 &&
113 S_ISREG(fin.st_mode) &&
115 (fin.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0)) {
117 printf("%s\n", candidate);
124 print_matches(char *path, char *filename)
126 char candidate[PATH_MAX];
130 if (strchr(filename, '/') != NULL)
131 return (is_there(filename) ? 0 : -1);
133 while ((d = strsep(&path, ":")) != NULL) {
136 if (snprintf(candidate, sizeof(candidate), "%s/%s", d,
137 filename) >= (int)sizeof(candidate))
139 if (is_there(candidate)) {
145 return (found ? 0 : -1);