rredpatch.c 16.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*  This file is part of "reprepro"
 *  Copyright (C) 2009 Bernhard R. Link
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02111-1301  USA
 */
#include <config.h>

#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <malloc.h>
#include <string.h>
#include <assert.h>
#include "error.h"
30
#include "rredpatch.h"
31 32 33

struct modification {
	/* next item in the list (sorted by oldlinestart) */
34
	struct modification *next, *previous;
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	/* each modification removes an (possible empty) range from
	 * the file and replaces it with an (possible empty) range
	 * of new lines */
	int oldlinestart, oldlinecount, newlinecount;
	size_t len;
	const char *content;
	/* a entry might be followed by one other with the same
	 * oldlinestart (due to merging or inefficient patches),
	 * but always: next->oldlinestart >= oldlinestart + oldlinecount
	 */
};

struct rred_patch {
	int fd;
	/* content of the file mapped with mmap */
	char *data;
	off_t len;
	struct modification *modifications;
53
	bool alreadyinuse;
54 55
};

56
void modification_freelist(struct modification *p) {
57 58 59 60 61 62 63
	while( p != NULL ) {
		struct modification *m = p;
		p = m->next;
		free(m);
	}
}

64 65 66 67 68 69 70 71 72 73
struct modification *patch_getmodifications(struct rred_patch *p) {
	struct modification *m;

	assert( !p->alreadyinuse );
	m = p->modifications;
	p->modifications = NULL;
	p->alreadyinuse = true;
	return m;
}

74 75 76 77 78 79
static struct modification *modification_freehead(/*@only@*/struct modification *p) {
	struct modification *m = p->next;
	free(p);
	return m;
}

80
void patch_free(/*@only@*/struct rred_patch *p) {
81 82 83 84 85 86 87 88
	if( p->data != NULL )
		(void)munmap(p->data, p->len);
	if( p->fd >= 0 )
		(void)close(p->fd);
	modification_freelist(p->modifications);
	free(p);
}

89
retvalue patch_load(const char *filename, off_t length, struct rred_patch **patch_p) {
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
	int i;
	struct rred_patch *patch;
	const char *p, *e, *d, *l;
	int number, number2, line;
	char type;
	struct modification *n;
	struct stat statbuf;

	patch = calloc(1, sizeof(struct rred_patch));
	if( FAILEDTOALLOC(patch) )
		return RET_ERROR_OOM;
	patch->fd = open(filename, O_NOCTTY|O_RDONLY);
	if( patch->fd < 0 ) {
		int err = errno;
		fprintf(stderr,
"Error %d opening '%s' for reading: %s\n", err, filename, strerror(err));
		patch_free(patch);
		return RET_ERRNO(err);
	}
	i = fstat(patch->fd, &statbuf);
	if( i != 0 ) {
		int err = errno;
		fprintf(stderr,
"Error %d retrieving length of '%s': %s\n", err, filename, strerror(err));
		patch_free(patch);
		return RET_ERRNO(err);
	}
	if( length == -1 )
		length = statbuf.st_size;
	if( statbuf.st_size != length ) {
		int err = errno;
		fprintf(stderr,
"Unexpected size of '%s': expected %lld, got %lld\n", filename,
			(long long)length, (long long)statbuf.st_size);
		patch_free(patch);
		return RET_ERRNO(err);
	}
	patch->len = length;
	patch->data = mmap(NULL, patch->len, PROT_READ, MAP_PRIVATE,
			patch->fd, 0);
	if( patch->data == MAP_FAILED ) {
		int err = errno;
		fprintf(stderr,
"Error %d mapping '%s' into memory: %s\n", err, filename, strerror(err));
		patch_free(patch);
		return RET_ERRNO(err);
	}
	p = patch->data;
	e = p + patch->len;
	line = 1;
	while( p < e ) {
		/* <number>,<number>(c|d)\n or <number>(a|i|c|d) */
		d = p;
		number = 0; number2 = -1;
		while( d < e && *d >= '0' && *d <= '9' ) {
			number = (*d - '0') + 10 * number;
			d++;
		}
		if( d > p && d < e && *d == ',' ) {
			d++;
			number2 = 0;
			while( d < e && *d >= '0' && *d <= '9' ) {
				number2 = (*d - '0') + 10 * number2;
				d++;
			}
			if( number2 < number ) {
				fprintf(stderr,
"Error parsing '%s': malformed range (2nd number smaller than 1s) at line %d\n",
					filename, line);
				patch_free(patch);
				return RET_ERROR;
			}
		}
		if( d >= e || (*d != 'c' && *d != 'i' && *d != 'a' && *d != 'd') ) {
			fprintf(stderr,
"Error parsing '%s': expected rule (c,i,a or d) at line %d\n",
				filename, line);
			patch_free(patch);
			return RET_ERROR;
		}
		type = *d;
		d++;
		while( d < e && *d == '\r' )
			d++;
		if( d >= e || *d != '\n' ) {
			fprintf(stderr,
"Error parsing '%s': expected newline after command at line %d\n",
				filename, line);
			patch_free(patch);
			return RET_ERROR;
		}
		d++;
		line++;

		if( type != 'a' && number == 0 ) {
			fprintf(stderr,
"Error parsing '%s': missing number at line %d\n",
				filename, line);
			patch_free(patch);
			return RET_ERROR;
		}
		if( type != 'c' && type != 'd'  && number2 >= 0 ) {
			fprintf(stderr,
"Error parsing '%s': line range not allowed with %c at line %d\n",
				filename, (char)type, line);
			patch_free(patch);
			return RET_ERROR;
		}
		n = calloc(1, sizeof(struct modification));
		if( FAILEDTOALLOC(n) ) {
			patch_free(patch);
			return RET_ERROR_OOM;
		}
		n->next = patch->modifications;
204 205
		if( n->next != NULL )
			n->next->previous = n;
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
		patch->modifications = n;

		p = d;
		if( type == 'd') {
			n->content = NULL;
			n->len = 0;
			n->newlinecount = 0;
		} else {
			int startline = line;

			l = p;
			while( l < e ) {
				p = l;
				while( l < e && *l != '\n' )
					l++;
				if( l >= e ) {
					if( l == p + 1 && *p == '.' ) {
						/* that is also corrupted,
						 * but we can cure it */
						break;
					}
					fprintf(stderr,
"Error parsing '%s': ends in unterminated line. File most likely corrupted\n",
							filename);
					patch_free(patch);
					return RET_ERROR;
				}
				l++;
				if( p[0] == '.' && (p[1] == '\n' || p[1] == '\r') )
					break;
				line++;
			}
			if( p[0] != '.' || ( l > p + 1 && p[1] != '\n' && p[1] != '\r' )) {
					fprintf(stderr,
"Error parsing '%s': ends waiting for dot. File most likely corrupted\n",
							filename);
					patch_free(patch);
					return RET_ERROR;
			}
			n->content = d;
			n->len = p - d;
			n->newlinecount = line - startline;
			p = l;
			line++;
		}
		if( type == 'a' ) {
			/* appends appends after instead of before something: */
			n->oldlinestart = number + 1;
			n->oldlinecount = 0;
		} else if( type == 'i' ) {
			n->oldlinestart = number;
			n->oldlinecount = 0;
		} else {
			n->oldlinestart = number;
			if( number2 < 0 )
				n->oldlinecount = 1;
			else
				n->oldlinecount = (number2 - number) + 1;
		}
		/* make sure things are in the order diff usually
		 * generates them, which makes line-calculation much easier: */
		if( n->next != NULL ) {
			// TODO: theoretically, that could be healed by
			// changing the numbers when this item is moving to
			// the later code. But how test this as diff uses
			// the sane order?
			if( n->oldlinestart + n->oldlinecount
					> n->next->oldlinestart ) {
				fprintf(stderr,
275 276
"Error using '%s' line %d: wrong order of edit-commands\n",
						filename, line);
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
				patch_free(patch);
				return RET_ERROR;
			}
		}
	}
	*patch_p = patch;
	return RET_OK;
}

static void modification_stripendlines(struct modification *m, int r) {
	int lines;
	const char *p;

	m->newlinecount -= r;
	lines = m->newlinecount;
	p = m->content;
	while( lines > 0 ) {
		while( *p != '\n')
			p++;
		p++;
		lines--;
	}
	assert( p - m->content <= m->len );
	m->len = p - m->content;
}

static void modification_stripstartlines(struct modification *m, int r) {
	const char *p;

	m->newlinecount -= r;
	p = m->content;
	while( r > 0 ) {
		while( *p != '\n')
			p++;
		p++;
		r--;
	}
	assert( p - m->content <= m->len );
	m->len -= p - m->content;
	m->content = p;
}

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
static inline void move_queue(struct modification **last_p, struct modification **result_p, struct modification **from_p) {
	struct modification *toadd, *last;

	/* remove from queue: */
	toadd = *from_p;
	*from_p = toadd->next;
	if( toadd->next != NULL ) {
		toadd->next->previous = NULL;
		toadd->next = NULL;
	}

	/* if nothing yet, make it the first */
	if( *last_p == NULL ) {
		*result_p = toadd;
		toadd->previous = NULL;
		*last_p = toadd;
		return;
	}

	last = *last_p;
	if( toadd->oldlinestart == last->oldlinestart + last->oldlinecount ) {
		/* check if something can be combined: */
		if( toadd->newlinecount == 0 ) {
			last->oldlinecount += toadd->oldlinecount;
			free(toadd);
			return;
		}
		if( last->newlinecount == 0 ) {
			toadd->oldlinestart = last->oldlinestart;
			toadd->oldlinecount += last->oldlinecount;
			toadd->previous = last->previous;
			if( toadd->previous == NULL )
				*result_p = toadd;
			else
				toadd->previous->next = toadd;
			*last_p = toadd;
			free(last);
			return;
		}
		if( last->content + last->len == toadd->content ) {
			last->oldlinecount += toadd->oldlinecount;
			last->newlinecount += toadd->newlinecount;
			last->len += toadd->len;
			free(toadd);
			return;
		}
	}
	toadd->previous = last;
	last->next = toadd;
368
	assert( last->oldlinestart + last->oldlinecount <= toadd->oldlinestart );
369 370 371 372
	*last_p = toadd;
	return;
}

373 374 375
/* this merges a set of modifications into an already existing stack,
 * modifying line numbers or even cutting away deleted/newly overwritten
 * stuff as necessary */
376 377
retvalue combine_patches(struct modification **result_p, /*@only@*/struct modification *first, /*@only@*/struct modification *second) {
	struct modification *p, *a, *result, *last;
378 379 380 381
	long lineofs;

	p = first;
	result = NULL;
382
	last = NULL;
383 384 385 386 387 388 389
	a = second;

	lineofs = 0;

	while( a != NULL ) {
		/* modification totally before current one,
		 * so just add it before it */
390
		if( p == NULL || lineofs + a->oldlinestart + a->oldlinecount
391 392
				<= p->oldlinestart ) {
			a->oldlinestart += lineofs;
393
			move_queue(&last, &result, &a);
394 395
			assert( p == NULL || p->oldlinestart >=
					last->oldlinestart + last->oldlinecount );
396 397 398 399 400 401 402
			continue;
		}
		/* modification to add after current head modification,
		 * so finalize head modification and update lineofs */
		if( lineofs + a->oldlinestart
			  	>= p->oldlinestart + p->newlinecount ) {
			lineofs += p->oldlinecount - p->newlinecount;
403
			move_queue(&last, &result, &p);
404 405
			assert( lineofs + a->oldlinestart >=
					last->oldlinestart + last->oldlinecount );
406 407 408 409 410 411
			continue;
		}
		/* new modification removes everything the old one added: */
		if( lineofs + a->oldlinestart <= p->oldlinestart
			  && lineofs + a->oldlinestart + a->oldlinecount
			  	>= p->oldlinestart + p->newlinecount ) {
412
			a->oldlinestart -= p->oldlinecount - p->newlinecount;
413
			a->oldlinecount += p->oldlinecount - p->newlinecount;
414
			lineofs += p->oldlinecount - p->newlinecount;
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
			p = modification_freehead(p);
			/* we cannot finalize a here, as it might still
			 * eat more p (in full or partial)... */
			continue;
		}
		/* otherwise something overlaps, things get complicated here: */

		/* start of *a removes end of *p, so reduce *p: */
		if( lineofs + a->oldlinestart > p->oldlinestart &&
				lineofs + a->oldlinestart
				< p->oldlinestart + p->newlinecount &&
				lineofs + a->oldlinestart + a->oldlinecount
				>= p->oldlinestart + p->newlinecount ) {
			int removedlines = p->oldlinestart + p->newlinecount
				- (lineofs + a->oldlinestart);

			/* finalize p as before */
			lineofs += p->oldlinecount - p->newlinecount;
			/* just telling a to delete less */
			a->oldlinestart += removedlines;
			a->oldlinecount -= removedlines;
			/* and p to add less */
			modification_stripendlines(p, removedlines);
438
			move_queue(&last, &result, &p);
439 440
			assert( lineofs + a->oldlinestart >=
					last->oldlinestart + last->oldlinecount );
441 442 443 444 445 446 447 448 449 450 451 452 453 454
			continue;
		}
		/* end of *a remove start of *p, so finalize *a and reduce *p */
		if( lineofs + a->oldlinestart <= p->oldlinestart &&
				lineofs + a->oldlinestart + a->oldlinecount
				> p->oldlinestart  &&
				lineofs + a->oldlinestart + a->oldlinecount
				< p->oldlinestart + p->newlinecount ) {
			int removedlines =
				lineofs + a->oldlinestart + a->oldlinecount
				- p->oldlinestart;
			/* finalize *a with less lines deleted:*/
			a->oldlinestart += lineofs;
			a->oldlinecount -= removedlines;
455
			move_queue(&last, &result, &a);
456 457
			/* and reduce the number of lines of *p */
			modification_stripstartlines(p, removedlines);
458 459 460
			assert( p->oldlinestart >= last->oldlinestart + last->oldlinecount);
			if( a != NULL )
				assert( lineofs + a->oldlinestart >= last->oldlinestart + last->oldlinecount);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
			/* note that a->oldlinestart+a->oldlinecount+1
			 *        == p->oldlinestart */
			continue;
		}
		/* the most complex case left, a inside p, this
		 * needs p split in two */
		if( lineofs + a->oldlinestart > p->oldlinestart &&
				lineofs + a->oldlinestart + a->oldlinecount
				< p->oldlinestart + p->newlinecount ) {
			struct modification *n;
			int removedlines = p->oldlinestart + p->newlinecount
				- (lineofs + a->oldlinestart);

			n = calloc(1, sizeof(struct modification));
			if( FAILEDTOALLOC(n) ) {
				modification_freelist(result);
				modification_freelist(p);
				modification_freelist(a);
				return RET_ERROR_OOM;
			}
			*n = *p;
			/* all removing into the later pater, so
			 * that later numbers fit */
484
			n->next = NULL;
485 486 487 488 489 490
			n->oldlinecount = 0;
			modification_stripendlines(n,
					n->newlinecount - removedlines);
			assert(n->newlinecount == removedlines);
			lineofs += n->oldlinecount - n->newlinecount;
			assert( lineofs+a->oldlinestart <= p->oldlinestart);
491 492
			move_queue(&last, &result, &n);
			assert( n == NULL);
493 494 495
			/* only remove this and let the rest of the
			 * code handle the other changes */
			modification_stripstartlines(p, removedlines);
496 497
			assert( lineofs + a->oldlinestart >=
					last->oldlinestart + last->oldlinecount );
498 499 500 501 502 503 504
		}
		modification_freelist(result);
		modification_freelist(p);
		modification_freelist(a);
		fputs("Internal error in rred merging!\n", stderr);
		return RET_ERROR;
	}
505 506 507 508
	while( p != NULL ) {
		move_queue(&last, &result, &p);
	}
	*result_p = result;
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
	return RET_OK;
}

static retvalue patch_file(const char *destination, const char *source, const struct modification *patch) {
	FILE *i, *o;
	int currentline, ignore, c;

	i = fopen(source, "r");
	if( i == NULL ) {
		perror("error opening\n");
		return RET_ERROR;
	}
	o = fopen(destination, "w");
	if( o == NULL ) {
		perror("error creating\n");
		return RET_ERROR;
	}
526
	assert( patch == NULL || patch->oldlinestart > 0 );
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
	currentline = 1;
	do {
		while( patch != NULL && patch->oldlinestart == currentline ) {
			fwrite(patch->content, patch->len, 1, o);
			ignore = patch->oldlinecount;
			patch = patch->next;
			while( ignore > 0 ) {
				do {
					c = getc(i);
				} while( c != '\n' && c != EOF);
				ignore--;
				currentline++;
			}
		}
		assert( patch == NULL || patch->oldlinestart >= currentline );
		while( (c = getc(i)) != '\n' ) {
			if( c == EOF ) {
				if( patch != NULL ) {
					fprintf(stderr,
"Error patching '%s', file shorter than expected by patches!\n",
						source);
					return RET_ERROR;
				}
				return RET_OK;
			}
			putc(c, o);
		}
		putc(c, o);
		currentline++;
	} while (1);
	// TODO: check errors
	fclose(i);
	fclose(o);
	return RET_OK;
}

static void modification_print(const struct modification *m) {
	while( m != NULL ) {
		printf("mod %d+%d to %d:\n", m->oldlinestart, m->oldlinecount, m->newlinecount);
		fwrite(m->content, m->len, 1, stdout);
		m = m->next;
	}
}
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

void modification_printaspatch(const struct modification *m) {
	const struct modification *p, *q, *r;

	if( m == NULL )
		return;
	assert( m->previous == NULL );
	/* go to the end, as we have to print it backwards */
	p = m;
	while( p->next != NULL ) {
		assert( p->next->previous == p );
		p = p->next;
	}
	/* then print, possibly merging things */
	while( p != NULL ) {
		int start, oldcount, newcount;
		start = p->oldlinestart;
		oldcount = p->oldlinecount;
		newcount = p->newlinecount;

590 591 592
		if( p->next != NULL )
			assert( start + oldcount <= p->next->oldlinestart );

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
		r = p;
		for( q = p->previous ;
		     q != NULL && q->oldlinestart + q->oldlinecount == start ;
		     q = q->previous ) {
			oldcount += q->oldlinecount;
			start = q->oldlinestart;
			newcount += q->newlinecount;
			r = q;
		}
		if( newcount == 0 ) {
			assert( oldcount > 0 );
			if( oldcount == 1 )
				printf("%dd\n", start);
			else
				printf("%d,%dd\n", start, start + oldcount - 1);
		} else {
			if( oldcount == 0 )
				printf("%da\n", start-1);
			else if( oldcount == 1 )
				printf("%dc\n", start);
			else
				printf("%d,%dc\n", start, start + oldcount - 1);
			while( r != p->next ) {
				if( r->len > 0 )
					fwrite(r->content, r->len, 1, stdout);
				newcount -= r->newlinecount;
				r = r->next;
			}
			assert( newcount == 0 );
			puts(".");
		}
		p = q;
	}
626
}