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