2018-08-15 04:07:33 +03:00
|
|
|
/* vim: tabstop=4 shiftwidth=4 noexpandtab
|
|
|
|
* This file is part of ToaruOS and is released under the terms
|
2018-05-04 07:01:55 +03:00
|
|
|
* of the NCSA / University of Illinois License - see LICENSE.md
|
2018-05-04 07:11:06 +03:00
|
|
|
* Copyright (C) 2013-2014 K. Lange
|
2018-05-04 07:01:55 +03:00
|
|
|
*
|
2018-08-15 04:07:33 +03:00
|
|
|
* which - Figure out which binary will be used
|
2018-05-04 07:01:55 +03:00
|
|
|
*
|
2018-08-15 04:07:33 +03:00
|
|
|
* Searches through $PATH to find a matching binary, just like
|
|
|
|
* how execp* family does it. (Except does our execp actually
|
|
|
|
* bother checking permissions? Look into this...)
|
2018-05-04 07:01:55 +03:00
|
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
|
2018-08-15 04:07:33 +03:00
|
|
|
#define DEFAULT_PATH "/bin:/usr/bin"
|
2018-05-04 07:01:55 +03:00
|
|
|
|
|
|
|
int main(int argc, char * argv[]) {
|
|
|
|
|
|
|
|
if (argc < 2) {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (strstr(argv[1], "/")) {
|
|
|
|
struct stat t;
|
|
|
|
if (!stat(argv[1], &t)) {
|
|
|
|
if ((t.st_mode & 0111)) {
|
|
|
|
printf("%s\n", argv[1]);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
char * file = argv[1];
|
|
|
|
char * path = getenv("PATH");
|
|
|
|
if (!path) {
|
|
|
|
path = DEFAULT_PATH;
|
|
|
|
}
|
|
|
|
|
|
|
|
char * xpath = strdup(path);
|
|
|
|
char * p, * last;
|
|
|
|
for ((p = strtok_r(xpath, ":", &last)); p; p = strtok_r(NULL, ":", &last)) {
|
|
|
|
int r;
|
|
|
|
struct stat stat_buf;
|
|
|
|
char * exe = malloc(strlen(p) + strlen(file) + 2);
|
|
|
|
strcpy(exe, p);
|
|
|
|
strcat(exe, "/");
|
|
|
|
strcat(exe, file);
|
|
|
|
|
|
|
|
r = stat(exe, &stat_buf);
|
|
|
|
if (r != 0) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (!(stat_buf.st_mode & 0111)) {
|
|
|
|
continue; /* XXX not technically correct; need to test perms */
|
|
|
|
}
|
|
|
|
printf("%s\n", exe);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
free(xpath);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
return 1;
|
|
|
|
}
|