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