1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright 2003-2005 Colin Percival
5 * All rights reserved
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted providing 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 ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
20 * 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,
24 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30#ifndef WITHOUT_CAPSICUM
31#include <sys/capsicum.h>
32#endif
33
34#include <bzlib.h>
35#include <err.h>
36#include <fcntl.h>
37#include <libgen.h>
38#include <limits.h>
39#include <stdckdint.h>
40#include <stdint.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45#include <sys/mman.h>
46
47#ifndef O_BINARY
48#define O_BINARY 0
49#endif
50#define HEADER_SIZE 32
51
52static char *newfile;
53static int dirfd = -1;
54
55static void
56exit_cleanup(void)
57{
58
59	if (dirfd != -1 && newfile != NULL)
60		if (unlinkat(dirfd, newfile, 0))
61			warn("unlinkat");
62}
63
64static inline off_t
65add_off_t(off_t a, off_t b)
66{
67	off_t result;
68
69	if (ckd_add(&result, a, b))
70		errx(1, "Corrupt patch");
71	return result;
72}
73
74static off_t offtin(u_char *buf)
75{
76	off_t y;
77
78	y = buf[7] & 0x7F;
79	y = y * 256; y += buf[6];
80	y = y * 256; y += buf[5];
81	y = y * 256; y += buf[4];
82	y = y * 256; y += buf[3];
83	y = y * 256; y += buf[2];
84	y = y * 256; y += buf[1];
85	y = y * 256; y += buf[0];
86
87	if (buf[7] & 0x80)
88		y = -y;
89
90	return (y);
91}
92
93static void
94usage(void)
95{
96
97	fprintf(stderr, "usage: bspatch oldfile newfile patchfile\n");
98	exit(1);
99}
100
101int main(int argc, char *argv[])
102{
103	FILE *f, *cpf, *dpf, *epf;
104	BZFILE *cpfbz2, *dpfbz2, *epfbz2;
105	char *directory, *namebuf;
106	int cbz2err, dbz2err, ebz2err;
107	int newfd, oldfd;
108	off_t oldsize, newsize;
109	off_t bzctrllen, bzdatalen;
110	u_char header[HEADER_SIZE], buf[8];
111	u_char *old, *new;
112	off_t oldpos, newpos;
113	off_t ctrl[3];
114	off_t i, lenread, offset;
115#ifndef WITHOUT_CAPSICUM
116	cap_rights_t rights_dir, rights_ro, rights_wr;
117#endif
118
119	if (argc != 4)
120		usage();
121
122	/* Open patch file */
123	if ((f = fopen(argv[3], "rb")) == NULL)
124		err(1, "fopen(%s)", argv[3]);
125	/* Open patch file for control block */
126	if ((cpf = fopen(argv[3], "rb")) == NULL)
127		err(1, "fopen(%s)", argv[3]);
128	/* open patch file for diff block */
129	if ((dpf = fopen(argv[3], "rb")) == NULL)
130		err(1, "fopen(%s)", argv[3]);
131	/* open patch file for extra block */
132	if ((epf = fopen(argv[3], "rb")) == NULL)
133		err(1, "fopen(%s)", argv[3]);
134	/* open oldfile */
135	if ((oldfd = open(argv[1], O_RDONLY | O_BINARY, 0)) < 0)
136		err(1, "open(%s)", argv[1]);
137	/* open directory where we'll write newfile */
138	if ((namebuf = strdup(argv[2])) == NULL ||
139	    (directory = dirname(namebuf)) == NULL ||
140	    (dirfd = open(directory, O_DIRECTORY)) < 0)
141		err(1, "open %s", argv[2]);
142	free(namebuf);
143	if ((newfile = basename(argv[2])) == NULL)
144		err(1, "basename");
145	/* open newfile */
146	if ((newfd = openat(dirfd, newfile,
147	    O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, 0666)) < 0)
148		err(1, "open(%s)", argv[2]);
149	atexit(exit_cleanup);
150
151#ifndef WITHOUT_CAPSICUM
152	if (cap_enter() < 0)
153		err(1, "failed to enter security sandbox");
154
155	cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK, CAP_MMAP_R);
156	cap_rights_init(&rights_wr, CAP_WRITE);
157	cap_rights_init(&rights_dir, CAP_UNLINKAT);
158
159	if (cap_rights_limit(fileno(f), &rights_ro) < 0 ||
160	    cap_rights_limit(fileno(cpf), &rights_ro) < 0 ||
161	    cap_rights_limit(fileno(dpf), &rights_ro) < 0 ||
162	    cap_rights_limit(fileno(epf), &rights_ro) < 0 ||
163	    cap_rights_limit(oldfd, &rights_ro) < 0 ||
164	    cap_rights_limit(newfd, &rights_wr) < 0 ||
165	    cap_rights_limit(dirfd, &rights_dir) < 0)
166		err(1, "cap_rights_limit() failed, could not restrict"
167		    " capabilities");
168#endif
169
170	/*
171	File format:
172		0	8	"BSDIFF40"
173		8	8	X
174		16	8	Y
175		24	8	sizeof(newfile)
176		32	X	bzip2(control block)
177		32+X	Y	bzip2(diff block)
178		32+X+Y	???	bzip2(extra block)
179	with control block a set of triples (x,y,z) meaning "add x bytes
180	from oldfile to x bytes from the diff block; copy y bytes from the
181	extra block; seek forwards in oldfile by z bytes".
182	*/
183
184	/* Read header */
185	if (fread(header, 1, HEADER_SIZE, f) < HEADER_SIZE) {
186		if (feof(f))
187			errx(1, "Corrupt patch");
188		err(1, "fread(%s)", argv[3]);
189	}
190
191	/* Check for appropriate magic */
192	if (memcmp(header, "BSDIFF40", 8) != 0)
193		errx(1, "Corrupt patch");
194
195	/* Read lengths from header */
196	bzctrllen = offtin(header + 8);
197	bzdatalen = offtin(header + 16);
198	newsize = offtin(header + 24);
199	if (bzctrllen < 0 || bzctrllen > OFF_MAX - HEADER_SIZE ||
200	    bzdatalen < 0 || bzctrllen + HEADER_SIZE > OFF_MAX - bzdatalen ||
201	    newsize < 0 || newsize > SSIZE_MAX)
202		errx(1, "Corrupt patch");
203
204	/* Close patch file and re-open it via libbzip2 at the right places */
205	if (fclose(f))
206		err(1, "fclose(%s)", argv[3]);
207	offset = HEADER_SIZE;
208	if (fseeko(cpf, offset, SEEK_SET))
209		err(1, "fseeko(%s, %jd)", argv[3], (intmax_t)offset);
210	if ((cpfbz2 = BZ2_bzReadOpen(&cbz2err, cpf, 0, 0, NULL, 0)) == NULL)
211		errx(1, "BZ2_bzReadOpen, bz2err = %d", cbz2err);
212	offset = add_off_t(offset, bzctrllen);
213	if (fseeko(dpf, offset, SEEK_SET))
214		err(1, "fseeko(%s, %jd)", argv[3], (intmax_t)offset);
215	if ((dpfbz2 = BZ2_bzReadOpen(&dbz2err, dpf, 0, 0, NULL, 0)) == NULL)
216		errx(1, "BZ2_bzReadOpen, bz2err = %d", dbz2err);
217	offset = add_off_t(offset, bzdatalen);
218	if (fseeko(epf, offset, SEEK_SET))
219		err(1, "fseeko(%s, %jd)", argv[3], (intmax_t)offset);
220	if ((epfbz2 = BZ2_bzReadOpen(&ebz2err, epf, 0, 0, NULL, 0)) == NULL)
221		errx(1, "BZ2_bzReadOpen, bz2err = %d", ebz2err);
222
223	if ((oldsize = lseek(oldfd, 0, SEEK_END)) == -1 ||
224	    oldsize > SSIZE_MAX)
225		err(1, "%s", argv[1]);
226
227	old = mmap(NULL, oldsize+1, PROT_READ, MAP_SHARED, oldfd, 0);
228	if (old == MAP_FAILED || close(oldfd) != 0)
229		err(1, "%s", argv[1]);
230
231	if ((new = malloc(newsize)) == NULL)
232		err(1, NULL);
233
234	oldpos = 0;
235	newpos = 0;
236	while (newpos < newsize) {
237		/* Read control data */
238		for (i = 0; i <= 2; i++) {
239			lenread = BZ2_bzRead(&cbz2err, cpfbz2, buf, 8);
240			if ((lenread < 8) || ((cbz2err != BZ_OK) &&
241			    (cbz2err != BZ_STREAM_END)))
242				errx(1, "Corrupt patch");
243			ctrl[i] = offtin(buf);
244		}
245
246		/* Sanity-check */
247		if (ctrl[0] < 0 || ctrl[0] > INT_MAX ||
248		    ctrl[1] < 0 || ctrl[1] > INT_MAX)
249			errx(1, "Corrupt patch");
250
251		/* Sanity-check */
252		if (add_off_t(newpos, ctrl[0]) > newsize)
253			errx(1, "Corrupt patch");
254
255		/* Read diff string */
256		lenread = BZ2_bzRead(&dbz2err, dpfbz2, new + newpos, ctrl[0]);
257		if ((lenread < ctrl[0]) ||
258		    ((dbz2err != BZ_OK) && (dbz2err != BZ_STREAM_END)))
259			errx(1, "Corrupt patch");
260
261		/* Add old data to diff string */
262		for (i = 0; i < ctrl[0]; i++)
263			if (add_off_t(oldpos, i) < oldsize)
264				new[newpos + i] += old[oldpos + i];
265
266		/* Adjust pointers */
267		newpos = add_off_t(newpos, ctrl[0]);
268		oldpos = add_off_t(oldpos, ctrl[0]);
269
270		/* Sanity-check */
271		if (add_off_t(newpos, ctrl[1]) > newsize)
272			errx(1, "Corrupt patch");
273
274		/* Read extra string */
275		lenread = BZ2_bzRead(&ebz2err, epfbz2, new + newpos, ctrl[1]);
276		if ((lenread < ctrl[1]) ||
277		    ((ebz2err != BZ_OK) && (ebz2err != BZ_STREAM_END)))
278			errx(1, "Corrupt patch");
279
280		/* Adjust pointers */
281		newpos = add_off_t(newpos, ctrl[1]);
282		oldpos = add_off_t(oldpos, ctrl[2]);
283	}
284
285	/* Clean up the bzip2 reads */
286	BZ2_bzReadClose(&cbz2err, cpfbz2);
287	BZ2_bzReadClose(&dbz2err, dpfbz2);
288	BZ2_bzReadClose(&ebz2err, epfbz2);
289	if (fclose(cpf) || fclose(dpf) || fclose(epf))
290		err(1, "fclose(%s)", argv[3]);
291
292	/* Write the new file */
293	if (write(newfd, new, newsize) != newsize || close(newfd) == -1)
294		err(1, "%s", argv[2]);
295	/* Disable atexit cleanup */
296	newfile = NULL;
297
298	free(new);
299	munmap(old, oldsize+1);
300
301	return (0);
302}
303