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