1 /*-
2  * Copyright 2003-2005 Colin Percival
3  * All rights reserved
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted providing 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 ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18  * 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,
22  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
23  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #if 0
28 __FBSDID("$FreeBSD: src/usr.bin/bsdiff/bsdiff/bsdiff.c,v 1.1 2005/08/06 01:59:05 cperciva Exp $");
29 #endif
30 
31 #include "bsdiff.h"
32 
33 #include <sys/types.h>
34 
35 #include <bzlib.h>
36 #include <err.h>
37 #include <fcntl.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 
43 #include <algorithm>
44 
45 namespace bsdiff {
46 
matchlen(const u_char * old,off_t oldsize,const u_char * new_buf,off_t newsize)47 static off_t matchlen(const u_char* old, off_t oldsize, const u_char* new_buf,
48                       off_t newsize) {
49 	off_t i;
50 
51 	for(i=0;(i<oldsize)&&(i<newsize);i++)
52 		if(old[i]!=new_buf[i]) break;
53 
54 	return i;
55 }
56 
57 // This is a binary search of the string |new_buf| of size |newsize| (or a
58 // prefix of it) in the |old| string with size |oldsize| using the suffix array
59 // |I|. |st| and |en| is the start and end of the search range (inclusive).
60 // Returns the length of the longest prefix found and stores the position of the
61 // string found in |*pos|.
search(saidx_t * I,const u_char * old,off_t oldsize,const u_char * new_buf,off_t newsize,off_t st,off_t en,off_t * pos)62 static off_t search(saidx_t* I, const u_char* old, off_t oldsize,
63                     const u_char* new_buf, off_t newsize, off_t st, off_t en,
64                     off_t* pos) {
65 	off_t x,y;
66 
67 	if(en-st<2) {
68 		x=matchlen(old+I[st],oldsize-I[st],new_buf,newsize);
69 		y=matchlen(old+I[en],oldsize-I[en],new_buf,newsize);
70 
71 		if(x>y) {
72 			*pos=I[st];
73 			return x;
74 		} else {
75 			*pos=I[en];
76 			return y;
77 		}
78 	};
79 
80 	x=st+(en-st)/2;
81 	if(memcmp(old+I[x],new_buf,std::min(oldsize-I[x],newsize))<=0) {
82 		return search(I,old,oldsize,new_buf,newsize,x,en,pos);
83 	} else {
84 		return search(I,old,oldsize,new_buf,newsize,st,x,pos);
85 	};
86 }
87 
offtout(off_t x,u_char * buf)88 static void offtout(off_t x,u_char *buf)
89 {
90 	off_t y;
91 
92 	if(x<0) y=-x; else y=x;
93 
94 		buf[0]=y%256;y-=buf[0];
95 	y=y/256;buf[1]=y%256;y-=buf[1];
96 	y=y/256;buf[2]=y%256;y-=buf[2];
97 	y=y/256;buf[3]=y%256;y-=buf[3];
98 	y=y/256;buf[4]=y%256;y-=buf[4];
99 	y=y/256;buf[5]=y%256;y-=buf[5];
100 	y=y/256;buf[6]=y%256;y-=buf[6];
101 	y=y/256;buf[7]=y%256;
102 
103 	if(x<0) buf[7]|=0x80;
104 }
105 
bsdiff(const char * old_filename,const char * new_filename,const char * patch_filename)106 int bsdiff(const char* old_filename, const char* new_filename,
107            const char* patch_filename) {
108 	int fd;
109 	u_char *old_buf,*new_buf;
110 	off_t oldsize,newsize;
111 
112 	/* Allocate oldsize+1 bytes instead of oldsize bytes to ensure
113 		that we never try to malloc(0) and get a NULL pointer */
114 	if(((fd=open(old_filename,O_RDONLY,0))<0) ||
115 		((oldsize=lseek(fd,0,SEEK_END))==-1) ||
116 		((old_buf=static_cast<u_char*>(malloc(oldsize+1)))==NULL) ||
117 		(lseek(fd,0,SEEK_SET)!=0) ||
118 		(read(fd,old_buf,oldsize)!=oldsize) ||
119 		(close(fd)==-1)) err(1,"%s",old_filename);
120 
121 	/* Allocate newsize+1 bytes instead of newsize bytes to ensure
122 		that we never try to malloc(0) and get a NULL pointer */
123 	if(((fd=open(new_filename,O_RDONLY,0))<0) ||
124 		((newsize=lseek(fd,0,SEEK_END))==-1) ||
125 		((new_buf = static_cast<u_char*>(malloc(newsize+1)))==NULL) ||
126 		(lseek(fd,0,SEEK_SET)!=0) ||
127 		(read(fd,new_buf,newsize)!=newsize) ||
128 		(close(fd)==-1)) err(1,"%s",new_filename);
129 
130 	int ret = bsdiff(old_buf, oldsize, new_buf, newsize, patch_filename, nullptr);
131 
132 	free(old_buf);
133 	free(new_buf);
134 
135 	return ret;
136 }
137 
138 // Generate bsdiff patch from |old_buf| to |new_buf|, save the patch file to
139 // |patch_filename|. Returns 0 on success.
140 // |I_cache| can be used to cache the suffix array if the same |old_buf| is used
141 // repeatedly, pass nullptr if not needed.
bsdiff(const u_char * old_buf,off_t oldsize,const u_char * new_buf,off_t newsize,const char * patch_filename,saidx_t ** I_cache)142 int bsdiff(const u_char* old_buf, off_t oldsize, const u_char* new_buf,
143            off_t newsize, const char* patch_filename, saidx_t** I_cache) {
144 	saidx_t *I;
145 	off_t scan,pos=0,len;
146 	off_t lastscan,lastpos,lastoffset;
147 	off_t oldscore,scsc;
148 	off_t s,Sf,lenf,Sb,lenb;
149 	off_t overlap,Ss,lens;
150 	off_t i;
151 	off_t dblen,eblen;
152 	u_char *db,*eb;
153 	u_char buf[8];
154 	u_char header[32];
155 	FILE * pf;
156 	BZFILE * pfbz2;
157 	int bz2err;
158 
159 	if (I_cache && *I_cache) {
160 		I = *I_cache;
161 	} else {
162 		if ((I=static_cast<saidx_t*>(malloc((oldsize+1)*sizeof(saidx_t))))==NULL)
163 			err(1,NULL);
164 
165 		if (divsufsort(old_buf, I, oldsize)) err(1, "divsufsort");
166 		if (I_cache)
167 			*I_cache = I;
168 	}
169 
170 	if(((db=static_cast<u_char*>(malloc(newsize+1)))==NULL) ||
171 		((eb=static_cast<u_char*>(malloc(newsize+1)))==NULL)) err(1,NULL);
172 	dblen=0;
173 	eblen=0;
174 
175 	/* Create the patch file */
176 	if ((pf = fopen(patch_filename, "w")) == NULL)
177 		err(1, "%s", patch_filename);
178 
179 	/* Header is
180 		0	8	 "BSDIFF40"
181 		8	8	length of bzip2ed ctrl block
182 		16	8	length of bzip2ed diff block
183 		24	8	length of new file */
184 	/* File is
185 		0	32	Header
186 		32	??	Bzip2ed ctrl block
187 		??	??	Bzip2ed diff block
188 		??	??	Bzip2ed extra block */
189 	memcpy(header,"BSDIFF40",8);
190 	offtout(0, header + 8);
191 	offtout(0, header + 16);
192 	offtout(newsize, header + 24);
193 	if (fwrite(header, 32, 1, pf) != 1)
194 		err(1, "fwrite(%s)", patch_filename);
195 
196 	/* Compute the differences, writing ctrl as we go */
197 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
198 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
199 	scan=0;len=0;
200 	lastscan=0;lastpos=0;lastoffset=0;
201 	while(scan<newsize) {
202 		oldscore=0;
203 
204 		/* If we come across a large block of data that only differs
205 		 * by less than 8 bytes, this loop will take a long time to
206 		 * go past that block of data. We need to track the number of
207 		 * times we're stuck in the block and break out of it. */
208 		int num_less_than_eight = 0;
209 		off_t prev_len, prev_oldscore, prev_pos;
210 		for(scsc=scan+=len;scan<newsize;scan++) {
211 			prev_len=len;
212 			prev_oldscore=oldscore;
213 			prev_pos=pos;
214 
215 			len=search(I,old_buf,oldsize,new_buf+scan,newsize-scan,
216 					0,oldsize-1,&pos);
217 
218 			for(;scsc<scan+len;scsc++)
219 			if((scsc+lastoffset<oldsize) &&
220 				(old_buf[scsc+lastoffset] == new_buf[scsc]))
221 				oldscore++;
222 
223 			if(((len==oldscore) && (len!=0)) ||
224 				(len>oldscore+8)) break;
225 
226 			if((scan+lastoffset<oldsize) &&
227 				(old_buf[scan+lastoffset] == new_buf[scan]))
228 				oldscore--;
229 
230 			const off_t fuzz = 8;
231 			if (prev_len-fuzz<=len && len<=prev_len &&
232 			    prev_oldscore-fuzz<=oldscore &&
233 			    oldscore<=prev_oldscore &&
234 			    prev_pos<=pos && pos <=prev_pos+fuzz &&
235 			    oldscore<=len && len<=oldscore+fuzz)
236 				++num_less_than_eight;
237 			else
238 				num_less_than_eight=0;
239 			if (num_less_than_eight > 100) break;
240 		};
241 
242 		if((len!=oldscore) || (scan==newsize)) {
243 			s=0;Sf=0;lenf=0;
244 			for(i=0;(lastscan+i<scan)&&(lastpos+i<oldsize);) {
245 				if(old_buf[lastpos+i]==new_buf[lastscan+i]) s++;
246 				i++;
247 				if(s*2-i>Sf*2-lenf) { Sf=s; lenf=i; };
248 			};
249 
250 			lenb=0;
251 			if(scan<newsize) {
252 				s=0;Sb=0;
253 				for(i=1;(scan>=lastscan+i)&&(pos>=i);i++) {
254 					if(old_buf[pos-i]==new_buf[scan-i]) s++;
255 					if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; };
256 				};
257 			};
258 
259 			if(lastscan+lenf>scan-lenb) {
260 				overlap=(lastscan+lenf)-(scan-lenb);
261 				s=0;Ss=0;lens=0;
262 				for(i=0;i<overlap;i++) {
263 					if(new_buf[lastscan+lenf-overlap+i]==
264 					   old_buf[lastpos+lenf-overlap+i]) s++;
265 					if(new_buf[scan-lenb+i]==
266 					   old_buf[pos-lenb+i]) s--;
267 					if(s>Ss) { Ss=s; lens=i+1; };
268 				};
269 
270 				lenf+=lens-overlap;
271 				lenb-=lens;
272 			};
273 
274 			for(i=0;i<lenf;i++)
275 				db[dblen+i]=new_buf[lastscan+i]-old_buf[lastpos+i];
276 			for(i=0;i<(scan-lenb)-(lastscan+lenf);i++)
277 				eb[eblen+i]=new_buf[lastscan+lenf+i];
278 
279 			dblen+=lenf;
280 			eblen+=(scan-lenb)-(lastscan+lenf);
281 
282 			offtout(lenf,buf);
283 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
284 			if (bz2err != BZ_OK)
285 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
286 
287 			offtout((scan-lenb)-(lastscan+lenf),buf);
288 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
289 			if (bz2err != BZ_OK)
290 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
291 
292 			offtout((pos-lenb)-(lastpos+lenf),buf);
293 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
294 			if (bz2err != BZ_OK)
295 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
296 
297 			lastscan=scan-lenb;
298 			lastpos=pos-lenb;
299 			lastoffset=pos-scan;
300 		};
301 	};
302 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
303 	if (bz2err != BZ_OK)
304 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
305 
306 	/* Compute size of compressed ctrl data */
307 	if ((len = ftello(pf)) == -1)
308 		err(1, "ftello");
309 	offtout(len-32, header + 8);
310 
311 	/* Write compressed diff data */
312 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
313 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
314 	BZ2_bzWrite(&bz2err, pfbz2, db, dblen);
315 	if (bz2err != BZ_OK)
316 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
317 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
318 	if (bz2err != BZ_OK)
319 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
320 
321 	/* Compute size of compressed diff data */
322 	if ((newsize = ftello(pf)) == -1)
323 		err(1, "ftello");
324 	offtout(newsize - len, header + 16);
325 
326 	/* Write compressed extra data */
327 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
328 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
329 	BZ2_bzWrite(&bz2err, pfbz2, eb, eblen);
330 	if (bz2err != BZ_OK)
331 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
332 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
333 	if (bz2err != BZ_OK)
334 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
335 
336 	/* Seek to the beginning, write the header, and close the file */
337 	if (fseeko(pf, 0, SEEK_SET))
338 		err(1, "fseeko");
339 	if (fwrite(header, 32, 1, pf) != 1)
340 		err(1, "fwrite(%s)", patch_filename);
341 	if (fclose(pf))
342 		err(1, "fclose");
343 
344 	/* Free the memory we used */
345 	free(db);
346 	free(eb);
347 	if (I_cache == nullptr)
348 		free(I);
349 
350 	return 0;
351 }
352 
353 }  // namespace bsdiff
354