xref: /freebsd/sbin/ldconfig/elfhints.c (revision 2a63c3be158216222d89a073dcbd6a72ee4aab5a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1998 John D. Polstra
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/mman.h>
31 #include <sys/stat.h>
32 
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <elf-hints.h>
36 #include <err.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #include "ldconfig.h"
45 
46 #define MAXDIRS		1024		/* Maximum directories in path */
47 #define MAXFILESIZE	(16*1024)	/* Maximum hints file size */
48 
49 static void	add_dir(const char *, const char *, bool);
50 static void	read_dirs_from_file(const char *, const char *);
51 static void	read_elf_hints(const char *, bool);
52 static void	write_elf_hints(const char *);
53 
54 static const char	*dirs[MAXDIRS];
55 static int		 ndirs;
56 bool			 insecure;
57 
58 static void
59 add_dir(const char *hintsfile, const char *name, bool trusted)
60 {
61 	struct stat 	stbuf;
62 	int		i;
63 
64 	/* Do some security checks */
65 	if (!trusted && !insecure) {
66 		if (stat(name, &stbuf) == -1) {
67 			warn("%s", name);
68 			return;
69 		}
70 		if (stbuf.st_uid != 0) {
71 			warnx("%s: ignoring directory not owned by root", name);
72 			return;
73 		}
74 		if ((stbuf.st_mode & S_IWOTH) != 0) {
75 			warnx("%s: ignoring world-writable directory", name);
76 			return;
77 		}
78 		if ((stbuf.st_mode & S_IWGRP) != 0) {
79 			warnx("%s: ignoring group-writable directory", name);
80 			return;
81 		}
82 	}
83 
84 	for (i = 0;  i < ndirs;  i++)
85 		if (strcmp(dirs[i], name) == 0)
86 			return;
87 	if (ndirs >= MAXDIRS)
88 		errx(1, "\"%s\": Too many directories in path", hintsfile);
89 	dirs[ndirs++] = name;
90 }
91 
92 void
93 list_elf_hints(const char *hintsfile)
94 {
95 	int	i;
96 	int	nlibs;
97 
98 	read_elf_hints(hintsfile, 1);
99 	printf("%s:\n", hintsfile);
100 	printf("\tsearch directories:");
101 	for (i = 0;  i < ndirs;  i++)
102 		printf("%c%s", i == 0 ? ' ' : ':', dirs[i]);
103 	printf("\n");
104 
105 	nlibs = 0;
106 	for (i = 0;  i < ndirs;  i++) {
107 		DIR		*dirp;
108 		struct dirent	*dp;
109 
110 		if ((dirp = opendir(dirs[i])) == NULL)
111 			continue;
112 		while ((dp = readdir(dirp)) != NULL) {
113 			int		 len;
114 			int		 namelen;
115 			const char	*name;
116 			const char	*vers;
117 
118 			/* Name can't be shorter than "libx.so.0" */
119 			if ((len = strlen(dp->d_name)) < 9 ||
120 			    strncmp(dp->d_name, "lib", 3) != 0)
121 				continue;
122 			name = dp->d_name + 3;
123 			vers = dp->d_name + len;
124 			while (vers > dp->d_name && isdigit(*(vers-1)))
125 				vers--;
126 			if (vers == dp->d_name + len)
127 				continue;
128 			if (vers < dp->d_name + 4 ||
129 			    strncmp(vers - 4, ".so.", 4) != 0)
130 				continue;
131 
132 			/* We have a valid shared library name. */
133 			namelen = (vers - 4) - name;
134 			printf("\t%d:-l%.*s.%s => %s/%s\n", nlibs,
135 			    namelen, name, vers, dirs[i], dp->d_name);
136 			nlibs++;
137 		}
138 		closedir(dirp);
139 	}
140 }
141 
142 static void
143 read_dirs_from_file(const char *hintsfile, const char *listfile)
144 {
145 	FILE	*fp;
146 	char	 buf[MAXPATHLEN];
147 	int	 linenum;
148 
149 	if ((fp = fopen(listfile, "r")) == NULL)
150 		err(1, "%s", listfile);
151 
152 	linenum = 0;
153 	while (fgets(buf, sizeof buf, fp) != NULL) {
154 		char	*cp, *sp;
155 
156 		linenum++;
157 		cp = buf;
158 		/* Skip leading white space. */
159 		while (isspace(*cp))
160 			cp++;
161 		if (*cp == '#' || *cp == '\0')
162 			continue;
163 		sp = cp;
164 		/* Advance over the directory name. */
165 		while (!isspace(*cp) && *cp != '\0')
166 			cp++;
167 		/* Terminate the string and skip trailing white space. */
168 		if (*cp != '\0') {
169 			*cp++ = '\0';
170 			while (isspace(*cp))
171 				cp++;
172 		}
173 		/* Now we had better be at the end of the line. */
174 		if (*cp != '\0')
175 			warnx("%s:%d: trailing characters ignored",
176 			    listfile, linenum);
177 
178 		if ((sp = strdup(sp)) == NULL)
179 			errx(1, "Out of memory");
180 		add_dir(hintsfile, sp, 0);
181 	}
182 
183 	fclose(fp);
184 }
185 
186 static void
187 read_elf_hints(const char *hintsfile, bool must_exist)
188 {
189 	int	 		 fd;
190 	struct stat		 s;
191 	void			*mapbase;
192 	struct elfhints_hdr	*hdr;
193 	char			*strtab;
194 	char			*dirlist;
195 	char			*p;
196 
197 	if ((fd = open(hintsfile, O_RDONLY)) == -1) {
198 		if (errno == ENOENT && !must_exist)
199 			return;
200 		err(1, "Cannot open \"%s\"", hintsfile);
201 	}
202 	if (fstat(fd, &s) == -1)
203 		err(1, "Cannot stat \"%s\"", hintsfile);
204 	if (s.st_size > MAXFILESIZE)
205 		errx(1, "\"%s\" is unreasonably large", hintsfile);
206 	/*
207 	 * We use a read-write, private mapping so that we can null-terminate
208 	 * some strings in it without affecting the underlying file.
209 	 */
210 	mapbase = mmap(NULL, s.st_size, PROT_READ|PROT_WRITE,
211 	    MAP_PRIVATE, fd, 0);
212 	if (mapbase == MAP_FAILED)
213 		err(1, "Cannot mmap \"%s\"", hintsfile);
214 	close(fd);
215 
216 	hdr = (struct elfhints_hdr *)mapbase;
217 	if (hdr->magic != ELFHINTS_MAGIC)
218 		errx(1, "\"%s\": invalid file format", hintsfile);
219 	if (hdr->version != 1)
220 		errx(1, "\"%s\": unrecognized file version (%d)", hintsfile,
221 		    hdr->version);
222 
223 	strtab = (char *)mapbase + hdr->strtab;
224 	dirlist = strtab + hdr->dirlist;
225 
226 	if (*dirlist != '\0')
227 		while ((p = strsep(&dirlist, ":")) != NULL)
228 			add_dir(hintsfile, p, 1);
229 }
230 
231 void
232 update_elf_hints(const char *hintsfile, int argc, char **argv, bool merge)
233 {
234 	struct stat s;
235 	int i;
236 
237 	if (merge)
238 		read_elf_hints(hintsfile, false);
239 	for (i = 0;  i < argc;  i++) {
240 		if (stat(argv[i], &s) == -1)
241 			warn("warning: %s", argv[i]);
242 		else if (S_ISREG(s.st_mode))
243 			read_dirs_from_file(hintsfile, argv[i]);
244 		else
245 			add_dir(hintsfile, argv[i], 0);
246 	}
247 	write_elf_hints(hintsfile);
248 }
249 
250 static void
251 write_elf_hints(const char *hintsfile)
252 {
253 	struct elfhints_hdr	 hdr;
254 	char			*tempname;
255 	int			 fd;
256 	FILE			*fp;
257 	int			 i;
258 
259 	if (asprintf(&tempname, "%s.XXXXXX", hintsfile) == -1)
260 		errx(1, "Out of memory");
261 	if ((fd = mkstemp(tempname)) ==  -1)
262 		err(1, "mkstemp(%s)", tempname);
263 	if (fchmod(fd, 0444) == -1)
264 		err(1, "fchmod(%s)", tempname);
265 	if ((fp = fdopen(fd, "wb")) == NULL)
266 		err(1, "fdopen(%s)", tempname);
267 
268 	hdr.magic = ELFHINTS_MAGIC;
269 	hdr.version = 1;
270 	hdr.strtab = sizeof hdr;
271 	hdr.strsize = 0;
272 	hdr.dirlist = 0;
273 	memset(hdr.spare, 0, sizeof hdr.spare);
274 
275 	/* Count up the size of the string table. */
276 	if (ndirs > 0) {
277 		hdr.strsize += strlen(dirs[0]);
278 		for (i = 1;  i < ndirs;  i++)
279 			hdr.strsize += 1 + strlen(dirs[i]);
280 	}
281 	hdr.dirlistlen = hdr.strsize;
282 	hdr.strsize++;	/* For the null terminator */
283 
284 	/* Write the header. */
285 	if (fwrite(&hdr, 1, sizeof hdr, fp) != sizeof hdr)
286 		err(1, "%s: write error", tempname);
287 	/* Write the strings. */
288 	if (ndirs > 0) {
289 		if (fputs(dirs[0], fp) == EOF)
290 			err(1, "%s: write error", tempname);
291 		for (i = 1;  i < ndirs;  i++)
292 			if (fprintf(fp, ":%s", dirs[i]) < 0)
293 				err(1, "%s: write error", tempname);
294 	}
295 	if (putc('\0', fp) == EOF || fclose(fp) == EOF)
296 		err(1, "%s: write error", tempname);
297 
298 	if (rename(tempname, hintsfile) == -1)
299 		err(1, "rename %s to %s", tempname, hintsfile);
300 	free(tempname);
301 }
302