pkg.c revision 234322
1/*-
2 * Copyright (c) 2012 Baptiste Daroussin <bapt@FreeBSD.org>
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
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/usr.sbin/pkg/pkg.c 234322 2012-04-15 18:32:14Z bapt $");
29
30#include <sys/param.h>
31#include <sys/elf_common.h>
32#include <sys/endian.h>
33#include <sys/wait.h>
34
35#include <archive.h>
36#include <archive_entry.h>
37#include <ctype.h>
38#include <err.h>
39#include <errno.h>
40#include <fcntl.h>
41#include <fetch.h>
42#include <gelf.h>
43#include <stdlib.h>
44#include <stdio.h>
45#include <string.h>
46#include <time.h>
47#include <unistd.h>
48
49#include "elf_tables.h"
50
51#define _LOCALBASE "/usr/local"
52#define _PKGS_URL "http://pkgbeta.FreeBSD.org"
53#define _DEFAULT_TMP "/tmp"
54
55static const char *
56elf_corres_to_string(struct _elf_corres *m, int e)
57{
58	int i;
59
60	for (i = 0; m[i].string != NULL; i++)
61		if (m[i].elf_nb == e)
62			return (m[i].string);
63
64	return ("unknown");
65}
66
67static int
68pkg_get_myabi(char *dest, size_t sz)
69{
70	Elf *elf;
71	GElf_Ehdr elfhdr;
72	GElf_Shdr shdr;
73	Elf_Data *data;
74	Elf_Note note;
75	Elf_Scn *scn;
76	char *src, *osname;
77	const char *abi;
78	int fd, i, ret;
79	uint32_t version;
80
81	version = 0;
82	ret = 0;
83	scn = NULL;
84	abi = NULL;
85
86	if (elf_version(EV_CURRENT) == EV_NONE) {
87		warnx("ELF library initialization failed: %s",
88		    elf_errmsg(-1));
89		return (-1);
90	}
91
92	if ((fd = open("/bin/sh", O_RDONLY)) < 0) {
93		warn("open()");
94		return (-1);
95	}
96
97	if ((elf = elf_begin(fd, ELF_C_READ, NULL)) == NULL) {
98		ret = -1;
99		warnx("elf_begin() failed: %s.", elf_errmsg(-1));
100		goto cleanup;
101	}
102
103	if (gelf_getehdr(elf, &elfhdr) == NULL) {
104		ret = -1;
105		warn("getehdr() failed: %s.", elf_errmsg(-1));
106		goto cleanup;
107	}
108
109	while ((scn = elf_nextscn(elf, scn)) != NULL) {
110		if (gelf_getshdr(scn, &shdr) != &shdr) {
111			ret = -1;
112			warn("getshdr() failed: %s.", elf_errmsg(-1));
113			goto cleanup;
114		}
115
116		if (shdr.sh_type == SHT_NOTE)
117			break;
118	}
119
120	if (scn == NULL) {
121		ret = -1;
122		warn("fail to get the note section");
123		goto cleanup;
124	}
125
126	data = elf_getdata(scn, NULL);
127	src = data->d_buf;
128	for (;;) {
129		memcpy(&note, src, sizeof(Elf_Note));
130		src += sizeof(Elf_Note);
131		if (note.n_type == NT_VERSION)
132			break;
133		src += note.n_namesz + note.n_descsz;
134	}
135	osname = src;
136	src += note.n_namesz;
137	if (elfhdr.e_ident[EI_DATA] == ELFDATA2MSB)
138		version = be32dec(src);
139	else
140		version = le32dec(src);
141
142	for (i = 0; osname[i] != '\0'; i++)
143		osname[i] = (char)tolower(osname[i]);
144
145	snprintf(dest, sz, "%s:%d:%s:%s",
146	    osname, version / 100000,
147	    elf_corres_to_string(mach_corres, (int)elfhdr.e_machine),
148	    elf_corres_to_string(wordsize_corres,
149	    (int)elfhdr.e_ident[EI_CLASS]));
150
151	switch (elfhdr.e_machine) {
152		case EM_ARM:
153			snprintf(dest + strlen(dest), sz - strlen(dest),
154			    ":%s:%s:%s", elf_corres_to_string(endian_corres,
155			    (int)elfhdr.e_ident[EI_DATA]),
156			    (elfhdr.e_flags & EF_ARM_NEW_ABI) > 0 ?
157			    "eabi" : "oabi",
158			    (elfhdr.e_flags & EF_ARM_VFP_FLOAT) > 0 ?
159			    "softfp" : "vfp");
160			break;
161		case EM_MIPS:
162			/*
163			 * this is taken from binutils sources:
164			 * include/elf/mips.h
165			 * mapping is figured out from binutils:
166			 * gas/config/tc-mips.c
167			 */
168			switch (elfhdr.e_flags & EF_MIPS_ABI) {
169				case E_MIPS_ABI_O32:
170					abi = "o32";
171					break;
172				case E_MIPS_ABI_N32:
173					abi = "n32";
174					break;
175				default:
176					if (elfhdr.e_ident[EI_DATA] ==
177					    ELFCLASS32)
178						abi = "o32";
179					else if (elfhdr.e_ident[EI_DATA] ==
180					    ELFCLASS64)
181						abi = "n64";
182					break;
183			}
184			snprintf(dest + strlen(dest), sz - strlen(dest),
185			    ":%s:%s", elf_corres_to_string(endian_corres,
186			    (int)elfhdr.e_ident[EI_DATA]), abi);
187			break;
188	}
189
190cleanup:
191	if (elf != NULL)
192		elf_end(elf);
193
194	close(fd);
195	return (ret);
196}
197
198static int
199extract_pkg_static(int fd, char *p, int sz)
200{
201	struct archive *a;
202	struct archive_entry *ae;
203	char *end;
204	int ret, r;
205
206	ret = 0;
207	a = archive_read_new();
208	archive_read_support_compression_all(a);
209	archive_read_support_format_tar(a);
210
211	lseek(fd, 0, 0);
212
213	if (archive_read_open_fd(a, fd, 4096) != ARCHIVE_OK) {
214		warnx("archive_read_open_fd: %s",
215		    archive_error_string(a));
216		ret = -1;
217		goto cleanup;
218	}
219
220	ae = NULL;
221	while ((r = archive_read_next_header(a, &ae)) == ARCHIVE_OK) {
222		end = strrchr(archive_entry_pathname(ae), '/');
223		if (end == NULL)
224			continue;
225
226		if (strcmp(end, "/pkg-static") == 0) {
227			r = archive_read_extract(a, ae,
228			    ARCHIVE_EXTRACT_OWNER | ARCHIVE_EXTRACT_PERM |
229			    ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_ACL |
230			    ARCHIVE_EXTRACT_FFLAGS | ARCHIVE_EXTRACT_XATTR);
231			snprintf(p, sz, archive_entry_pathname(ae));
232			break;
233		}
234	}
235
236	if (r != ARCHIVE_OK) {
237		warnx("fail to extract pkg-static");
238		ret = -1;
239	}
240
241cleanup:
242	archive_read_finish(a);
243	return (ret);
244
245}
246
247static int
248install_pkg_static(char *path, char *pkgpath)
249{
250	int pstat;
251	pid_t pid;
252
253	switch ((pid = fork())) {
254		case -1:
255			return (-1);
256		case 0:
257			execl(path, "pkg-static", "add", pkgpath,
258			    (char *)NULL);
259			_exit(1);
260		default:
261			break;
262	}
263
264	while (waitpid(pid, &pstat, 0) == -1) {
265		if (errno != EINTR)
266			return (-1);
267	}
268
269	return (WEXITSTATUS(pstat));
270}
271
272static int
273bootstrap_pkg(void)
274{
275	struct url_stat st;
276	FILE *remote;
277	time_t begin_dl;
278	time_t now;
279	time_t last = 0;
280	char url[MAXPATHLEN];
281	char abi[BUFSIZ];
282	char tmppkg[MAXPATHLEN];
283	char buf[10240];
284	char pkgstatic[MAXPATHLEN];
285	int fd, retry, ret;
286	off_t done, r;
287
288	done = 0;
289	ret = 0;
290	retry = 3;
291	remote = NULL;
292
293	printf("Bootstraping pkg please wait\n");
294
295	if (pkg_get_myabi(abi, MAXPATHLEN) != 0) {
296		warnx("fail to determine my abi");
297		return (-1);
298	}
299
300	if (getenv("PACKAGESITE") != NULL) {
301		snprintf(url, MAXPATHLEN, "%s/pkg.txz",
302		    getenv("PACKAGESITE"));
303	} else {
304		snprintf(url, MAXPATHLEN, "%s/%s/latest/Latest/pkg.txz",
305		    getenv("PACKAGEROOT") ? getenv("PACKAGEROOT") : _PKGS_URL,
306		    getenv("ABI") ? getenv("ABI") : abi);
307	}
308
309	snprintf(tmppkg, MAXPATHLEN, "%s/pkg.txz.XXXXXX",
310	    getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
311
312	if ((fd = mkstemp(tmppkg)) == -1) {
313		warn("mkstemp()");
314		return (-1);
315	}
316
317	while (remote == NULL) {
318		remote = fetchXGetURL(url, &st, "");
319		if (remote == NULL) {
320			--retry;
321			if (retry == 0) {
322				warnx("Error fetching %s: %s", url,
323				    fetchLastErrString);
324				ret = 1;
325				goto cleanup;
326			}
327			sleep(1);
328		}
329	}
330
331	begin_dl = time(NULL);
332	while (done < st.size) {
333		if ((r = fread(buf, 1, sizeof(buf), remote)) < 1)
334			break;
335
336		if (write(fd, buf, r) != r) {
337			warn("write()");
338			ret = -1;
339			goto cleanup;
340		}
341
342		done += r;
343		now = time(NULL);
344		if (now > last || done == st.size) {
345			last = now;
346		}
347	}
348
349	if (ferror(remote)) {
350		warnx("Error fetching %s: %s", url,
351		    fetchLastErrString);
352		ret = 1;
353		goto cleanup;
354	}
355
356	if ((ret = extract_pkg_static(fd, pkgstatic, MAXPATHLEN)) == 0)
357		ret = install_pkg_static(pkgstatic, tmppkg);
358
359cleanup:
360	close(fd);
361	unlink(tmppkg);
362
363	return (0);
364}
365
366int
367main(__unused int argc, char *argv[])
368{
369	char pkgpath[MAXPATHLEN];
370
371	snprintf(pkgpath, MAXPATHLEN, "%s/sbin/pkg",
372	    getenv("LOCALBASE") ? getenv("LOCALBASE") : _LOCALBASE);
373
374	if (access(pkgpath, X_OK) == -1)
375		bootstrap_pkg();
376
377	execv(pkgpath, argv);
378
379	return (EXIT_FAILURE);
380}
381