xref: /freebsd/sbin/ldconfig/elfhints.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
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/endian.h>
31 #include <sys/mman.h>
32 #include <sys/stat.h>
33 
34 #include <ctype.h>
35 #include <dirent.h>
36 #include <elf-hints.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
45 #include "ldconfig.h"
46 
47 #define MAXDIRS		1024		/* Maximum directories in path */
48 #define MAXFILESIZE	(16*1024)	/* Maximum hints file size */
49 
50 static void	add_dir(const char *, const char *, bool);
51 static void	read_dirs_from_file(const char *, const char *);
52 static void	read_elf_hints(const char *, bool, bool);
53 static void	write_elf_hints(const char *);
54 
55 static const char	*dirs[MAXDIRS];
56 static int		 ndirs;
57 static bool		 is_be;
58 bool			 insecure;
59 
60 static void
61 add_dir(const char *hintsfile, const char *name, bool trusted)
62 {
63 	struct stat 	stbuf;
64 	int		i;
65 
66 	/* Do some security checks */
67 	if (!trusted && !insecure) {
68 		if (stat(name, &stbuf) == -1) {
69 			warn("%s", name);
70 			return;
71 		}
72 		if (stbuf.st_uid != 0) {
73 			warnx("%s: ignoring directory not owned by root", name);
74 			return;
75 		}
76 		if ((stbuf.st_mode & S_IWOTH) != 0) {
77 			warnx("%s: ignoring world-writable directory", name);
78 			return;
79 		}
80 		if ((stbuf.st_mode & S_IWGRP) != 0) {
81 			warnx("%s: ignoring group-writable directory", name);
82 			return;
83 		}
84 	}
85 
86 	for (i = 0;  i < ndirs;  i++)
87 		if (strcmp(dirs[i], name) == 0)
88 			return;
89 	if (ndirs >= MAXDIRS)
90 		errx(1, "\"%s\": Too many directories in path", hintsfile);
91 	dirs[ndirs++] = name;
92 }
93 
94 void
95 list_elf_hints(const char *hintsfile)
96 {
97 	int	i;
98 	int	nlibs;
99 
100 	read_elf_hints(hintsfile, true, false);
101 	printf("%s:\n", hintsfile);
102 	printf("\tsearch directories:");
103 	for (i = 0;  i < ndirs;  i++)
104 		printf("%c%s", i == 0 ? ' ' : ':', dirs[i]);
105 	printf("\n");
106 
107 	nlibs = 0;
108 	for (i = 0;  i < ndirs;  i++) {
109 		DIR		*dirp;
110 		struct dirent	*dp;
111 
112 		if ((dirp = opendir(dirs[i])) == NULL)
113 			continue;
114 		while ((dp = readdir(dirp)) != NULL) {
115 			int		 len;
116 			int		 namelen;
117 			const char	*name;
118 			const char	*vers;
119 
120 			/* Name can't be shorter than "libx.so.0" */
121 			if ((len = strlen(dp->d_name)) < 9 ||
122 			    strncmp(dp->d_name, "lib", 3) != 0)
123 				continue;
124 			name = dp->d_name + 3;
125 			vers = dp->d_name + len;
126 			while (vers > dp->d_name && isdigit(*(vers-1)))
127 				vers--;
128 			if (vers == dp->d_name + len)
129 				continue;
130 			if (vers < dp->d_name + 4 ||
131 			    strncmp(vers - 4, ".so.", 4) != 0)
132 				continue;
133 
134 			/* We have a valid shared library name. */
135 			namelen = (vers - 4) - name;
136 			printf("\t%d:-l%.*s.%s => %s/%s\n", nlibs,
137 			    namelen, name, vers, dirs[i], dp->d_name);
138 			nlibs++;
139 		}
140 		closedir(dirp);
141 	}
142 }
143 
144 static void
145 read_dirs_from_file(const char *hintsfile, const char *listfile)
146 {
147 	FILE	*fp;
148 	char	 buf[MAXPATHLEN];
149 	int	 linenum;
150 
151 	if ((fp = fopen(listfile, "r")) == NULL)
152 		err(1, "%s", listfile);
153 
154 	linenum = 0;
155 	while (fgets(buf, sizeof buf, fp) != NULL) {
156 		char	*cp, *sp;
157 
158 		linenum++;
159 		cp = buf;
160 		/* Skip leading white space. */
161 		while (isspace(*cp))
162 			cp++;
163 		if (*cp == '#' || *cp == '\0')
164 			continue;
165 		sp = cp;
166 		/* Advance over the directory name. */
167 		while (!isspace(*cp) && *cp != '\0')
168 			cp++;
169 		/* Terminate the string and skip trailing white space. */
170 		if (*cp != '\0') {
171 			*cp++ = '\0';
172 			while (isspace(*cp))
173 				cp++;
174 		}
175 		/* Now we had better be at the end of the line. */
176 		if (*cp != '\0')
177 			warnx("%s:%d: trailing characters ignored",
178 			    listfile, linenum);
179 
180 		if ((sp = strdup(sp)) == NULL)
181 			errx(1, "Out of memory");
182 		add_dir(hintsfile, sp, 0);
183 	}
184 
185 	fclose(fp);
186 }
187 
188 /* Convert between native byte order and forced little resp. big endian. */
189 #define COND_SWAP(n) (is_be ? be32toh(n) : le32toh(n))
190 
191 static void
192 read_elf_hints(const char *hintsfile, bool must_exist, bool force_be)
193 {
194 	int	 		 fd;
195 	struct stat		 s;
196 	void			*mapbase;
197 	struct elfhints_hdr	*hdr;
198 	char			*strtab;
199 	char			*dirlist;
200 	char			*p;
201 	int			 hdr_version;
202 
203 	if ((fd = open(hintsfile, O_RDONLY)) == -1) {
204 		if (errno == ENOENT && !must_exist)
205 			return;
206 		err(1, "Cannot open \"%s\"", hintsfile);
207 	}
208 	if (fstat(fd, &s) == -1)
209 		err(1, "Cannot stat \"%s\"", hintsfile);
210 	if (s.st_size > MAXFILESIZE)
211 		errx(1, "\"%s\" is unreasonably large", hintsfile);
212 	/*
213 	 * We use a read-write, private mapping so that we can null-terminate
214 	 * some strings in it without affecting the underlying file.
215 	 */
216 	mapbase = mmap(NULL, s.st_size, PROT_READ|PROT_WRITE,
217 	    MAP_PRIVATE, fd, 0);
218 	if (mapbase == MAP_FAILED)
219 		err(1, "Cannot mmap \"%s\"", hintsfile);
220 	close(fd);
221 
222 	hdr = (struct elfhints_hdr *)mapbase;
223 	is_be = hdr->magic == htobe32(ELFHINTS_MAGIC);
224 	if (COND_SWAP(hdr->magic) != ELFHINTS_MAGIC)
225 		errx(1, "\"%s\": invalid file format", hintsfile);
226 	if (force_be && !is_be)
227 		errx(1, "\"%s\": incompatible endianness requested", hintsfile);
228 	hdr_version = COND_SWAP(hdr->version);
229 	if (hdr_version != 1)
230 		errx(1, "\"%s\": unrecognized file version (%d)", hintsfile,
231 		    hdr_version);
232 
233 	strtab = (char *)mapbase + COND_SWAP(hdr->strtab);
234 	dirlist = strtab + COND_SWAP(hdr->dirlist);
235 
236 	if (*dirlist != '\0')
237 		while ((p = strsep(&dirlist, ":")) != NULL)
238 			add_dir(hintsfile, p, 1);
239 }
240 
241 void
242 update_elf_hints(const char *hintsfile, int argc, char **argv, bool merge,
243     bool force_be)
244 {
245 	struct stat s;
246 	int i;
247 
248 	/*
249 	 * Create little-endian hints files on all architectures unless
250 	 * ldconfig has been invoked with the -B option.
251 	 */
252 	is_be = force_be;
253 	if (merge)
254 		read_elf_hints(hintsfile, false, force_be);
255 	for (i = 0;  i < argc;  i++) {
256 		if (stat(argv[i], &s) == -1)
257 			warn("warning: %s", argv[i]);
258 		else if (S_ISREG(s.st_mode))
259 			read_dirs_from_file(hintsfile, argv[i]);
260 		else
261 			add_dir(hintsfile, argv[i], 0);
262 	}
263 	write_elf_hints(hintsfile);
264 }
265 
266 static void
267 write_elf_hints(const char *hintsfile)
268 {
269 	struct elfhints_hdr	 hdr;
270 	char			*tempname;
271 	int			 fd;
272 	FILE			*fp;
273 	int			 i;
274 
275 	if (asprintf(&tempname, "%s.XXXXXX", hintsfile) == -1)
276 		errx(1, "Out of memory");
277 	if ((fd = mkstemp(tempname)) ==  -1)
278 		err(1, "mkstemp(%s)", tempname);
279 	if (fchmod(fd, 0444) == -1)
280 		err(1, "fchmod(%s)", tempname);
281 	if ((fp = fdopen(fd, "wb")) == NULL)
282 		err(1, "fdopen(%s)", tempname);
283 
284 	hdr.magic = COND_SWAP(ELFHINTS_MAGIC);
285 	hdr.version = COND_SWAP(1);
286 	hdr.strtab = COND_SWAP(sizeof hdr);
287 	hdr.strsize = 0;
288 	hdr.dirlist = 0;
289 	memset(hdr.spare, 0, sizeof hdr.spare);
290 
291 	/* Count up the size of the string table. */
292 	if (ndirs > 0) {
293 		hdr.strsize += strlen(dirs[0]);
294 		for (i = 1;  i < ndirs;  i++)
295 			hdr.strsize += 1 + strlen(dirs[i]);
296 	}
297 	hdr.dirlistlen = COND_SWAP(hdr.strsize);
298 	hdr.strsize++;	/* For the null terminator */
299 	/* convert in-place from native to target endianness */
300 	hdr.strsize = COND_SWAP(hdr.strsize);
301 
302 	/* Write the header. */
303 	if (fwrite(&hdr, 1, sizeof hdr, fp) != sizeof hdr)
304 		err(1, "%s: write error", tempname);
305 	/* Write the strings. */
306 	if (ndirs > 0) {
307 		if (fputs(dirs[0], fp) == EOF)
308 			err(1, "%s: write error", tempname);
309 		for (i = 1;  i < ndirs;  i++)
310 			if (fprintf(fp, ":%s", dirs[i]) < 0)
311 				err(1, "%s: write error", tempname);
312 	}
313 	if (putc('\0', fp) == EOF || fclose(fp) == EOF)
314 		err(1, "%s: write error", tempname);
315 
316 	if (rename(tempname, hintsfile) == -1)
317 		err(1, "rename %s to %s", tempname, hintsfile);
318 	free(tempname);
319 }
320