xref: /titanic_50/usr/src/lib/libtnfctl/prb_findexec.c (revision 174bc6499d233e329ecd3d98a880a7b07df16bfa)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 1994, by Sun Microsytems, Inc.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * interfaces to find an executable (from libc code)
30  */
31 
32 /* Copyright (c) 1988 AT&T */
33 /* All Rights Reserved   */
34 
35 
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <limits.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 
44 #include "prb_proc_int.h"
45 
46 static const char *exec_cat(const char *s1, const char *s2, char *si);
47 
48 prb_status_t
49 find_executable(const char *name, char *ret_path)
50 {
51 	const char	 *pathstr;
52 	char		fname[PATH_MAX + 2];
53 	const char	 *cp;
54 	struct stat	 stat_buf;
55 
56 	if (*name == '\0') {
57 		return (prb_status_map(ENOENT));
58 	}
59 	if ((pathstr = getenv("PATH")) == NULL) {
60 		if (geteuid() == 0 || getuid() == 0)
61 			pathstr = "/usr/sbin:/usr/bin";
62 		else
63 			pathstr = "/usr/bin:";
64 	}
65 	cp = strchr(name, '/') ? (const char *) "" : pathstr;
66 
67 	do {
68 		cp = exec_cat(cp, name, fname);
69 		if (stat(fname, &stat_buf) != -1) {
70 			/* successful find of the file */
71 			(void) strncpy(ret_path, fname, PATH_MAX + 2);
72 			return (PRB_STATUS_OK);
73 		}
74 	} while (cp);
75 
76 	return (prb_status_map(ENOENT));
77 }
78 
79 
80 
81 static const char *
82 exec_cat(const char *s1, const char *s2, char *si)
83 {
84 	char		   *s;
85 	/* number of characters in s2 */
86 	int			 cnt = PATH_MAX + 1;
87 
88 	s = si;
89 	while (*s1 && *s1 != ':') {
90 		if (cnt > 0) {
91 			*s++ = *s1++;
92 			cnt--;
93 		} else
94 			s1++;
95 	}
96 	if (si != s && cnt > 0) {
97 		*s++ = '/';
98 		cnt--;
99 	}
100 	while (*s2 && cnt > 0) {
101 		*s++ = *s2++;
102 		cnt--;
103 	}
104 	*s = '\0';
105 	return (*s1 ? ++s1 : 0);
106 }
107