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 <sys/types.h>
32 
33 #include <bzlib.h>
34 #include <err.h>
35 #include <fcntl.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 
41 #include <algorithm>
42 
43 #if _FILE_OFFSET_BITS == 64
44 #include "divsufsort64.h"
45 #define saidx_t saidx64_t
46 #define divsufsort divsufsort64
47 #else
48 #include "divsufsort.h"
49 #endif
50 
51 namespace bsdiff {
52 
matchlen(u_char * old,off_t oldsize,u_char * new_buf,off_t newsize)53 static off_t matchlen(u_char *old, off_t oldsize, u_char *new_buf,
54                       off_t newsize) {
55 	off_t i;
56 
57 	for(i=0;(i<oldsize)&&(i<newsize);i++)
58 		if(old[i]!=new_buf[i]) break;
59 
60 	return i;
61 }
62 
search(saidx_t * I,u_char * old,off_t oldsize,u_char * new_buf,off_t newsize,off_t st,off_t en,off_t * pos)63 static off_t search(saidx_t *I,u_char *old,off_t oldsize,
64 		u_char *new_buf,off_t newsize,off_t st,off_t en,off_t *pos)
65 {
66 	off_t x,y;
67 
68 	if(en-st<2) {
69 		x=matchlen(old+I[st],oldsize-I[st],new_buf,newsize);
70 		y=matchlen(old+I[en],oldsize-I[en],new_buf,newsize);
71 
72 		if(x>y) {
73 			*pos=I[st];
74 			return x;
75 		} else {
76 			*pos=I[en];
77 			return y;
78 		}
79 	};
80 
81 	x=st+(en-st)/2;
82 	if(memcmp(old+I[x],new_buf,std::min(oldsize-I[x],newsize))<=0) {
83 		return search(I,old,oldsize,new_buf,newsize,x,en,pos);
84 	} else {
85 		return search(I,old,oldsize,new_buf,newsize,st,x,pos);
86 	};
87 }
88 
offtout(off_t x,u_char * buf)89 static void offtout(off_t x,u_char *buf)
90 {
91 	off_t y;
92 
93 	if(x<0) y=-x; else y=x;
94 
95 		buf[0]=y%256;y-=buf[0];
96 	y=y/256;buf[1]=y%256;y-=buf[1];
97 	y=y/256;buf[2]=y%256;y-=buf[2];
98 	y=y/256;buf[3]=y%256;y-=buf[3];
99 	y=y/256;buf[4]=y%256;y-=buf[4];
100 	y=y/256;buf[5]=y%256;y-=buf[5];
101 	y=y/256;buf[6]=y%256;y-=buf[6];
102 	y=y/256;buf[7]=y%256;
103 
104 	if(x<0) buf[7]|=0x80;
105 }
106 
bsdiff(const char * old_filename,const char * new_filename,const char * patch_filename)107 int bsdiff(const char* old_filename, const char* new_filename,
108            const char* patch_filename) {
109 	int fd;
110 	u_char *old_buf,*new_buf;
111 	off_t oldsize,newsize;
112 	saidx_t *I;
113 	off_t scan,pos=0,len;
114 	off_t lastscan,lastpos,lastoffset;
115 	off_t oldscore,scsc;
116 	off_t s,Sf,lenf,Sb,lenb;
117 	off_t overlap,Ss,lens;
118 	off_t i;
119 	off_t dblen,eblen;
120 	u_char *db,*eb;
121 	u_char buf[8];
122 	u_char header[32];
123 	FILE * pf;
124 	BZFILE * pfbz2;
125 	int bz2err;
126 
127 	/* Allocate oldsize+1 bytes instead of oldsize bytes to ensure
128 		that we never try to malloc(0) and get a NULL pointer */
129 	if(((fd=open(old_filename,O_RDONLY,0))<0) ||
130 		((oldsize=lseek(fd,0,SEEK_END))==-1) ||
131 		((old_buf=static_cast<u_char*>(malloc(oldsize+1)))==NULL) ||
132 		(lseek(fd,0,SEEK_SET)!=0) ||
133 		(read(fd,old_buf,oldsize)!=oldsize) ||
134 		(close(fd)==-1)) err(1,"%s",old_filename);
135 
136 	if((I=static_cast<saidx_t*>(malloc((oldsize+1)*sizeof(saidx_t))))==NULL)
137 		err(1,NULL);
138 
139 	if(divsufsort(old_buf, I, oldsize)) err(1, "divsufsort");
140 
141 	/* Allocate newsize+1 bytes instead of newsize bytes to ensure
142 		that we never try to malloc(0) and get a NULL pointer */
143 	if(((fd=open(new_filename,O_RDONLY,0))<0) ||
144 		((newsize=lseek(fd,0,SEEK_END))==-1) ||
145 		((new_buf = static_cast<u_char*>(malloc(newsize+1)))==NULL) ||
146 		(lseek(fd,0,SEEK_SET)!=0) ||
147 		(read(fd,new_buf,newsize)!=newsize) ||
148 		(close(fd)==-1)) err(1,"%s",new_filename);
149 
150 	if(((db=static_cast<u_char*>(malloc(newsize+1)))==NULL) ||
151 		((eb=static_cast<u_char*>(malloc(newsize+1)))==NULL)) err(1,NULL);
152 	dblen=0;
153 	eblen=0;
154 
155 	/* Create the patch file */
156 	if ((pf = fopen(patch_filename, "w")) == NULL)
157 		err(1, "%s", patch_filename);
158 
159 	/* Header is
160 		0	8	 "BSDIFF40"
161 		8	8	length of bzip2ed ctrl block
162 		16	8	length of bzip2ed diff block
163 		24	8	length of new file */
164 	/* File is
165 		0	32	Header
166 		32	??	Bzip2ed ctrl block
167 		??	??	Bzip2ed diff block
168 		??	??	Bzip2ed extra block */
169 	memcpy(header,"BSDIFF40",8);
170 	offtout(0, header + 8);
171 	offtout(0, header + 16);
172 	offtout(newsize, header + 24);
173 	if (fwrite(header, 32, 1, pf) != 1)
174 		err(1, "fwrite(%s)", patch_filename);
175 
176 	/* Compute the differences, writing ctrl as we go */
177 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
178 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
179 	scan=0;len=0;
180 	lastscan=0;lastpos=0;lastoffset=0;
181 	while(scan<newsize) {
182 		oldscore=0;
183 
184 		/* If we come across a large block of data that only differs
185 		 * by less than 8 bytes, this loop will take a long time to
186 		 * go past that block of data. We need to track the number of
187 		 * times we're stuck in the block and break out of it. */
188 		int num_less_than_eight = 0;
189 		off_t prev_len, prev_oldscore, prev_pos;
190 		for(scsc=scan+=len;scan<newsize;scan++) {
191 			prev_len=len;
192 			prev_oldscore=oldscore;
193 			prev_pos=pos;
194 
195 			len=search(I,old_buf,oldsize,new_buf+scan,newsize-scan,
196 					0,oldsize,&pos);
197 
198 			for(;scsc<scan+len;scsc++)
199 			if((scsc+lastoffset<oldsize) &&
200 				(old_buf[scsc+lastoffset] == new_buf[scsc]))
201 				oldscore++;
202 
203 			if(((len==oldscore) && (len!=0)) ||
204 				(len>oldscore+8)) break;
205 
206 			if((scan+lastoffset<oldsize) &&
207 				(old_buf[scan+lastoffset] == new_buf[scan]))
208 				oldscore--;
209 
210 			const off_t fuzz = 8;
211 			if (prev_len-fuzz<=len && len<=prev_len &&
212 			    prev_oldscore-fuzz<=oldscore &&
213 			    oldscore<=prev_oldscore &&
214 			    prev_pos<=pos && pos <=prev_pos+fuzz &&
215 			    oldscore<=len && len<=oldscore+fuzz)
216 				++num_less_than_eight;
217 			else
218 				num_less_than_eight=0;
219 			if (num_less_than_eight > 100) break;
220 		};
221 
222 		if((len!=oldscore) || (scan==newsize)) {
223 			s=0;Sf=0;lenf=0;
224 			for(i=0;(lastscan+i<scan)&&(lastpos+i<oldsize);) {
225 				if(old_buf[lastpos+i]==new_buf[lastscan+i]) s++;
226 				i++;
227 				if(s*2-i>Sf*2-lenf) { Sf=s; lenf=i; };
228 			};
229 
230 			lenb=0;
231 			if(scan<newsize) {
232 				s=0;Sb=0;
233 				for(i=1;(scan>=lastscan+i)&&(pos>=i);i++) {
234 					if(old_buf[pos-i]==new_buf[scan-i]) s++;
235 					if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; };
236 				};
237 			};
238 
239 			if(lastscan+lenf>scan-lenb) {
240 				overlap=(lastscan+lenf)-(scan-lenb);
241 				s=0;Ss=0;lens=0;
242 				for(i=0;i<overlap;i++) {
243 					if(new_buf[lastscan+lenf-overlap+i]==
244 					   old_buf[lastpos+lenf-overlap+i]) s++;
245 					if(new_buf[scan-lenb+i]==
246 					   old_buf[pos-lenb+i]) s--;
247 					if(s>Ss) { Ss=s; lens=i+1; };
248 				};
249 
250 				lenf+=lens-overlap;
251 				lenb-=lens;
252 			};
253 
254 			for(i=0;i<lenf;i++)
255 				db[dblen+i]=new_buf[lastscan+i]-old_buf[lastpos+i];
256 			for(i=0;i<(scan-lenb)-(lastscan+lenf);i++)
257 				eb[eblen+i]=new_buf[lastscan+lenf+i];
258 
259 			dblen+=lenf;
260 			eblen+=(scan-lenb)-(lastscan+lenf);
261 
262 			offtout(lenf,buf);
263 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
264 			if (bz2err != BZ_OK)
265 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
266 
267 			offtout((scan-lenb)-(lastscan+lenf),buf);
268 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
269 			if (bz2err != BZ_OK)
270 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
271 
272 			offtout((pos-lenb)-(lastpos+lenf),buf);
273 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
274 			if (bz2err != BZ_OK)
275 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
276 
277 			lastscan=scan-lenb;
278 			lastpos=pos-lenb;
279 			lastoffset=pos-scan;
280 		};
281 	};
282 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
283 	if (bz2err != BZ_OK)
284 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
285 
286 	/* Compute size of compressed ctrl data */
287 	if ((len = ftello(pf)) == -1)
288 		err(1, "ftello");
289 	offtout(len-32, header + 8);
290 
291 	/* Write compressed diff data */
292 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
293 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
294 	BZ2_bzWrite(&bz2err, pfbz2, db, dblen);
295 	if (bz2err != BZ_OK)
296 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
297 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
298 	if (bz2err != BZ_OK)
299 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
300 
301 	/* Compute size of compressed diff data */
302 	if ((newsize = ftello(pf)) == -1)
303 		err(1, "ftello");
304 	offtout(newsize - len, header + 16);
305 
306 	/* Write compressed extra data */
307 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
308 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
309 	BZ2_bzWrite(&bz2err, pfbz2, eb, eblen);
310 	if (bz2err != BZ_OK)
311 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
312 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
313 	if (bz2err != BZ_OK)
314 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
315 
316 	/* Seek to the beginning, write the header, and close the file */
317 	if (fseeko(pf, 0, SEEK_SET))
318 		err(1, "fseeko");
319 	if (fwrite(header, 32, 1, pf) != 1)
320 		err(1, "fwrite(%s)", patch_filename);
321 	if (fclose(pf))
322 		err(1, "fclose");
323 
324 	/* Free the memory we used */
325 	free(db);
326 	free(eb);
327 	free(I);
328 	free(old_buf);
329 	free(new_buf);
330 
331 	return 0;
332 }
333 
334 }  // namespace bsdiff
335