Patch.pm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. # Copyright © 2008 Raphaël Hertzog <hertzog@debian.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package Dpkg::Source::Patch;
  16. use strict;
  17. use warnings;
  18. our $VERSION = "0.01";
  19. use Dpkg;
  20. use Dpkg::Gettext;
  21. use Dpkg::IPC;
  22. use Dpkg::ErrorHandling;
  23. use POSIX;
  24. use File::Find;
  25. use File::Basename;
  26. use File::Spec;
  27. use File::Path;
  28. use File::Compare;
  29. use Fcntl ':mode';
  30. #XXX: Needed for sub-second timestamps, require recent perl
  31. #use Time::HiRes qw(stat);
  32. use base 'Dpkg::Compression::FileHandle';
  33. sub create {
  34. my ($self, %opts) = @_;
  35. $self->ensure_open("w"); # Creates the file
  36. *$self->{'errors'} = 0;
  37. *$self->{'empty'} = 1;
  38. if ($opts{'old'} and $opts{'new'}) {
  39. $opts{'old'} = "/dev/null" unless -e $opts{'old'};
  40. $opts{'new'} = "/dev/null" unless -e $opts{'new'};
  41. if (-d $opts{'old'} and -d $opts{'new'}) {
  42. $self->add_diff_directory($opts{'old'}, $opts{'new'}, %opts);
  43. } elsif (-f $opts{'old'} and -f $opts{'new'}) {
  44. $self->add_diff_file($opts{'old'}, $opts{'new'}, %opts);
  45. } else {
  46. $self->_fail_not_same_type($opts{'old'}, $opts{'new'});
  47. }
  48. $self->finish() unless $opts{"nofinish"};
  49. }
  50. }
  51. sub set_header {
  52. my ($self, $header) = @_;
  53. *$self->{'header'} = $header;
  54. }
  55. sub add_diff_file {
  56. my ($self, $old, $new, %opts) = @_;
  57. $opts{"include_timestamp"} = 0 unless exists $opts{"include_timestamp"};
  58. my $handle_binary = $opts{"handle_binary_func"} || sub {
  59. my ($self, $old, $new) = @_;
  60. $self->_fail_with_msg($new, _g("binary file contents changed"));
  61. };
  62. # Optimization to avoid forking diff if unnecessary
  63. return 1 if compare($old, $new, 4096) == 0;
  64. # Default diff options
  65. my @options;
  66. if ($opts{"options"}) {
  67. push @options, @{$opts{"options"}};
  68. } else {
  69. push @options, '-p';
  70. }
  71. # Add labels
  72. if ($opts{"label_old"} and $opts{"label_new"}) {
  73. if ($opts{"include_timestamp"}) {
  74. my $ts = (stat($old))[9];
  75. my $t = POSIX::strftime("%Y-%m-%d %H:%M:%S", gmtime($ts));
  76. $opts{"label_old"} .= sprintf("\t%s.%09d +0000", $t,
  77. ($ts-int($ts))*1000000000);
  78. $ts = (stat($new))[9];
  79. $t = POSIX::strftime("%Y-%m-%d %H:%M:%S", gmtime($ts));
  80. $opts{"label_new"} .= sprintf("\t%s.%09d +0000", $t,
  81. ($ts-int($ts))*1000000000);
  82. } else {
  83. # Space in filenames need special treatment
  84. $opts{"label_old"} .= "\t" if $opts{"label_old"} =~ / /;
  85. $opts{"label_new"} .= "\t" if $opts{"label_new"} =~ / /;
  86. }
  87. push @options, "-L", $opts{"label_old"},
  88. "-L", $opts{"label_new"};
  89. }
  90. # Generate diff
  91. my $diffgen;
  92. my $diff_pid = spawn(
  93. 'exec' => [ 'diff', '-u', @options, '--', $old, $new ],
  94. 'env' => { LC_ALL => 'C', LANG => 'C', TZ => 'UTC0' },
  95. 'to_pipe' => \$diffgen
  96. );
  97. # Check diff and write it in patch file
  98. my $difflinefound = 0;
  99. my $binary = 0;
  100. while (<$diffgen>) {
  101. if (m/^binary/i) {
  102. $binary = 1;
  103. &$handle_binary($self, $old, $new);
  104. last;
  105. } elsif (m/^[-+\@ ]/) {
  106. $difflinefound++;
  107. } elsif (m/^\\ No newline at end of file$/) {
  108. warning(_g("file %s has no final newline (either " .
  109. "original or modified version)"), $new);
  110. } else {
  111. chomp;
  112. error(_g("unknown line from diff -u on %s: `%s'"), $new, $_);
  113. }
  114. if (*$self->{'empty'} and defined(*$self->{'header'})) {
  115. $self->print(*$self->{'header'}) or syserr(_g("failed to write"));
  116. *$self->{'empty'} = 0;
  117. }
  118. print $self $_ || syserr(_g("failed to write"));
  119. }
  120. close($diffgen) or syserr("close on diff pipe");
  121. wait_child($diff_pid, nocheck => 1,
  122. cmdline => "diff -u @options -- $old $new");
  123. # Verify diff process ended successfully
  124. # Exit code of diff: 0 => no difference, 1 => diff ok, 2 => error
  125. # Ignore error if binary content detected
  126. my $exit = WEXITSTATUS($?);
  127. unless (WIFEXITED($?) && ($exit == 0 || $exit == 1 || $binary)) {
  128. subprocerr(_g("diff on %s"), $new);
  129. }
  130. return ($exit == 0 || $exit == 1);
  131. }
  132. sub add_diff_directory {
  133. my ($self, $old, $new, %opts) = @_;
  134. # TODO: make this function more configurable
  135. # - offer to disable some checks
  136. my $basedir = $opts{"basedirname"} || basename($new);
  137. my $inc_removal = $opts{"include_removal"} || 0;
  138. my $diff_ignore;
  139. if ($opts{"diff_ignore_func"}) {
  140. $diff_ignore = $opts{"diff_ignore_func"};
  141. } elsif ($opts{"diff_ignore_regexp"}) {
  142. $diff_ignore = sub { return $_[0] =~ /$opts{"diff_ignore_regexp"}/o };
  143. } else {
  144. $diff_ignore = sub { return 0 };
  145. }
  146. my %files_in_new;
  147. my $scan_new = sub {
  148. my $fn = (length > length($new)) ? substr($_, length($new) + 1) : '.';
  149. return if &$diff_ignore($fn);
  150. $files_in_new{$fn} = 1;
  151. lstat("$new/$fn") || syserr(_g("cannot stat file %s"), "$new/$fn");
  152. my $mode = S_IMODE((lstat(_))[2]);
  153. my $size = (lstat(_))[7];
  154. if (-l _) {
  155. unless (-l "$old/$fn") {
  156. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  157. return;
  158. }
  159. defined(my $n = readlink("$new/$fn")) ||
  160. syserr(_g("cannot read link %s"), "$new/$fn");
  161. defined(my $n2 = readlink("$old/$fn")) ||
  162. syserr(_g("cannot read link %s"), "$old/$fn");
  163. unless ($n eq $n2) {
  164. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  165. }
  166. } elsif (-f _) {
  167. my $old_file = "$old/$fn";
  168. if (not lstat("$old/$fn")) {
  169. $! == ENOENT ||
  170. syserr(_g("cannot stat file %s"), "$old/$fn");
  171. $old_file = '/dev/null';
  172. } elsif (not -f _) {
  173. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  174. return;
  175. }
  176. my $label_old = "$basedir.orig/$fn";
  177. if ($opts{'use_dev_null'}) {
  178. $label_old = $old_file if $old_file eq '/dev/null';
  179. }
  180. my $success = $self->add_diff_file($old_file, "$new/$fn",
  181. label_old => $label_old,
  182. label_new => "$basedir/$fn",
  183. %opts);
  184. if ($success and ($old_file eq "/dev/null")) {
  185. if (not $size) {
  186. warning(_g("newly created empty file '%s' will not " .
  187. "be represented in diff"), $fn);
  188. } else {
  189. if ($mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
  190. warning(_g("executable mode %04o of '%s' will " .
  191. "not be represented in diff"), $mode, $fn)
  192. unless $fn eq 'debian/rules';
  193. }
  194. if ($mode & (S_ISUID | S_ISGID | S_ISVTX)) {
  195. warning(_g("special mode %04o of '%s' will not " .
  196. "be represented in diff"), $mode, $fn);
  197. }
  198. }
  199. }
  200. } elsif (-p _) {
  201. unless (-p "$old/$fn") {
  202. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  203. }
  204. } elsif (-b _ || -c _ || -S _) {
  205. $self->_fail_with_msg("$new/$fn",
  206. _g("device or socket is not allowed"));
  207. } elsif (-d _) {
  208. if (not lstat("$old/$fn")) {
  209. $! == ENOENT ||
  210. syserr(_g("cannot stat file %s"), "$old/$fn");
  211. } elsif (not -d _) {
  212. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  213. }
  214. } else {
  215. $self->_fail_with_msg("$new/$fn", _g("unknown file type"));
  216. }
  217. };
  218. my $scan_old = sub {
  219. my $fn = (length > length($old)) ? substr($_, length($old) + 1) : '.';
  220. return if &$diff_ignore($fn);
  221. return if $files_in_new{$fn};
  222. lstat("$old/$fn") || syserr(_g("cannot stat file %s"), "$old/$fn");
  223. if (-f _) {
  224. if ($inc_removal) {
  225. $self->add_diff_file("$old/$fn", "/dev/null",
  226. label_old => "$basedir.orig/$fn",
  227. label_new => "/dev/null",
  228. %opts);
  229. } else {
  230. warning(_g("ignoring deletion of file %s"), $fn);
  231. }
  232. } elsif (-d _) {
  233. warning(_g("ignoring deletion of directory %s"), $fn);
  234. } elsif (-l _) {
  235. warning(_g("ignoring deletion of symlink %s"), $fn);
  236. } else {
  237. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  238. }
  239. };
  240. find({ wanted => $scan_new, no_chdir => 1 }, $new);
  241. find({ wanted => $scan_old, no_chdir => 1 }, $old);
  242. }
  243. sub finish {
  244. my ($self) = @_;
  245. close($self) || syserr(_g("cannot close %s"), $self->get_filename());
  246. return not *$self->{'errors'};
  247. }
  248. sub register_error {
  249. my ($self) = @_;
  250. *$self->{'errors'}++;
  251. }
  252. sub _fail_with_msg {
  253. my ($self, $file, $msg) = @_;
  254. errormsg(_g("cannot represent change to %s: %s"), $file, $msg);
  255. $self->register_error();
  256. }
  257. sub _fail_not_same_type {
  258. my ($self, $old, $new) = @_;
  259. my $old_type = get_type($old);
  260. my $new_type = get_type($new);
  261. errormsg(_g("cannot represent change to %s:"), $new);
  262. errormsg(_g(" new version is %s"), $new_type);
  263. errormsg(_g(" old version is %s"), $old_type);
  264. $self->register_error();
  265. }
  266. # check diff for sanity, find directories to create as a side effect
  267. sub analyze {
  268. my ($self, $destdir, %opts) = @_;
  269. my $diff = $self->get_filename();
  270. my %filepatched;
  271. my %dirtocreate;
  272. my $diff_count = 0;
  273. sub getline {
  274. my $handle = shift;
  275. my $line = <$handle>;
  276. if (defined $line) {
  277. # Strip end-of-line chars
  278. chomp($line);
  279. $line =~ s/\r$//;
  280. }
  281. return $line;
  282. }
  283. sub strip_ts { # Strip timestamp
  284. my $header = shift;
  285. # Tab is the official separator, it's always used when
  286. # filename contain spaces. Try it first, otherwise strip on space
  287. # if there's no tab
  288. $header =~ s/\s.*// unless ($header =~ s/\t.*//);
  289. return $header;
  290. }
  291. $_ = getline($self);
  292. HUNK:
  293. while (defined($_) || not eof($self)) {
  294. my ($fn, $fn2);
  295. # skip comments leading up to patch (if any)
  296. until (/^--- /) {
  297. last HUNK if not defined($_ = getline($self));
  298. }
  299. $diff_count++;
  300. # read file header (---/+++ pair)
  301. unless(s/^--- //) {
  302. error(_g("expected ^--- in line %d of diff `%s'"), $., $diff);
  303. }
  304. $_ = strip_ts($_);
  305. if ($_ eq '/dev/null' or s{^(\./)?[^/]+/}{$destdir/}) {
  306. $fn = $_;
  307. }
  308. if (/\.dpkg-orig$/) {
  309. error(_g("diff `%s' patches file with name ending .dpkg-orig"), $diff);
  310. }
  311. unless (defined($_ = getline($self))) {
  312. error(_g("diff `%s' finishes in middle of ---/+++ (line %d)"), $diff, $.);
  313. }
  314. unless (s/^\+\+\+ //) {
  315. error(_g("line after --- isn't as expected in diff `%s' (line %d)"), $diff, $.);
  316. }
  317. $_ = strip_ts($_);
  318. if ($_ eq '/dev/null' or s{^(\./)?[^/]+/}{$destdir/}) {
  319. $fn2 = $_;
  320. } else {
  321. unless (defined $fn) {
  322. error(_g("none of the filenames in ---/+++ are relative in diff `%s' (line %d)"),
  323. $diff, $.);
  324. }
  325. }
  326. if (defined($fn) and $fn eq '/dev/null') {
  327. error(_g("original and modified files are /dev/null in diff `%s' (line %d)"),
  328. $diff, $.) if (defined($fn2) and $fn2 eq '/dev/null');
  329. $fn = $fn2;
  330. } elsif (defined($fn2) and $fn2 ne '/dev/null') {
  331. $fn = $fn2 unless defined $fn;
  332. $fn = $fn2 if ((not -e $fn) and -e $fn2);
  333. } elsif (defined($fn2) and $fn2 eq '/dev/null') {
  334. error(_g("file removal without proper filename in diff `%s' (line %d)"),
  335. $diff, $. - 1) unless defined $fn;
  336. warning(_g("diff %s removes a non-existing file %s (line %d)"),
  337. $diff, $fn, $.) unless -e $fn;
  338. }
  339. my $dirname = $fn;
  340. if ($dirname =~ s{/[^/]+$}{} && not -d $dirname) {
  341. $dirtocreate{$dirname} = 1;
  342. }
  343. if (-e $fn and not -f _) {
  344. error(_g("diff `%s' patches something which is not a plain file"), $diff);
  345. }
  346. if ($filepatched{$fn}) {
  347. error(_g("diff `%s' patches file %s twice"), $diff, $fn);
  348. }
  349. $filepatched{$fn} = 1;
  350. # read hunks
  351. my $hunk = 0;
  352. while (defined($_ = getline($self))) {
  353. # read hunk header (@@)
  354. next if /^\\ No newline/;
  355. last unless (/^@@ -\d+(,(\d+))? \+\d+(,(\d+))? @\@( .*)?$/);
  356. my ($olines, $nlines) = ($1 ? $2 : 1, $3 ? $4 : 1);
  357. # read hunk
  358. while ($olines || $nlines) {
  359. unless (defined($_ = getline($self))) {
  360. if (($olines == $nlines) and ($olines < 3)) {
  361. warning(_g("unexpected end of diff `%s'"), $diff);
  362. last;
  363. } else {
  364. error(_g("unexpected end of diff `%s'"), $diff);
  365. }
  366. }
  367. next if /^\\ No newline/;
  368. # Check stats
  369. if (/^ / || /^$/) { --$olines; --$nlines; }
  370. elsif (/^-/) { --$olines; }
  371. elsif (/^\+/) { --$nlines; }
  372. else {
  373. error(_g("expected [ +-] at start of line %d of diff `%s'"),
  374. $., $diff);
  375. }
  376. }
  377. $hunk++;
  378. }
  379. unless($hunk) {
  380. error(_g("expected ^\@\@ at line %d of diff `%s'"), $., $diff);
  381. }
  382. }
  383. close($self);
  384. unless ($diff_count) {
  385. warning(_g("diff `%s' doesn't contain any patch"), $diff);
  386. }
  387. *$self->{'analysis'}{$destdir}{"dirtocreate"} = \%dirtocreate;
  388. *$self->{'analysis'}{$destdir}{"filepatched"} = \%filepatched;
  389. return *$self->{'analysis'}{$destdir};
  390. }
  391. sub prepare_apply {
  392. my ($self, $analysis, %opts) = @_;
  393. if ($opts{"create_dirs"}) {
  394. foreach my $dir (keys %{$analysis->{'dirtocreate'}}) {
  395. eval { mkpath($dir, 0, 0777); };
  396. syserr(_g("cannot create directory %s"), $dir) if $@;
  397. }
  398. }
  399. }
  400. sub apply {
  401. my ($self, $destdir, %opts) = @_;
  402. # Set default values to options
  403. $opts{"force_timestamp"} = 1 unless exists $opts{"force_timestamp"};
  404. $opts{"remove_backup"} = 1 unless exists $opts{"remove_backup"};
  405. $opts{"create_dirs"} = 1 unless exists $opts{"create_dirs"};
  406. $opts{"options"} ||= [ '-s', '-t', '-F', '0', '-N', '-p1', '-u',
  407. '-V', 'never', '-g0', '-b', '-z', '.dpkg-orig'];
  408. $opts{"add_options"} ||= [];
  409. push @{$opts{"options"}}, @{$opts{"add_options"}};
  410. # Check the diff and create missing directories
  411. my $analysis = $self->analyze($destdir, %opts);
  412. $self->prepare_apply($analysis, %opts);
  413. # Apply the patch
  414. $self->ensure_open("r");
  415. spawn(
  416. 'exec' => [ 'patch', @{$opts{"options"}} ],
  417. 'chdir' => $destdir,
  418. 'env' => { LC_ALL => 'C', LANG => 'C' },
  419. 'delete_env' => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
  420. 'wait_child' => 1,
  421. 'from_handle' => $self->get_filehandle(),
  422. );
  423. $self->close();
  424. # Reset the timestamp of all the patched files
  425. # and remove .dpkg-orig files
  426. my $now = $opts{"timestamp"} || time;
  427. foreach my $fn (keys %{$analysis->{'filepatched'}}) {
  428. if ($opts{"force_timestamp"}) {
  429. utime($now, $now, $fn) || $! == ENOENT ||
  430. syserr(_g("cannot change timestamp for %s"), $fn);
  431. }
  432. if ($opts{"remove_backup"}) {
  433. $fn .= ".dpkg-orig";
  434. unlink($fn) || syserr(_g("remove patch backup file %s"), $fn);
  435. }
  436. }
  437. return $analysis;
  438. }
  439. # Verify if check will work...
  440. sub check_apply {
  441. my ($self, $destdir, %opts) = @_;
  442. # Set default values to options
  443. $opts{"create_dirs"} = 1 unless exists $opts{"create_dirs"};
  444. $opts{"options"} ||= [ '--dry-run', '-s', '-t', '-F', '0', '-N', '-p1', '-u',
  445. '-V', 'never', '-g0', '-b', '-z', '.dpkg-orig'];
  446. $opts{"add_options"} ||= [];
  447. push @{$opts{"options"}}, @{$opts{"add_options"}};
  448. # Check the diff and create missing directories
  449. my $analysis = $self->analyze($destdir, %opts);
  450. $self->prepare_apply($analysis, %opts);
  451. # Apply the patch
  452. $self->ensure_open("r");
  453. my $error;
  454. my $patch_pid = spawn(
  455. 'exec' => [ 'patch', @{$opts{"options"}} ],
  456. 'chdir' => $destdir,
  457. 'env' => { LC_ALL => 'C', LANG => 'C' },
  458. 'delete_env' => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
  459. 'from_handle' => $self->get_filehandle(),
  460. 'to_file' => '/dev/null',
  461. 'error_to_file' => '/dev/null',
  462. );
  463. wait_child($patch_pid, nocheck => 1);
  464. my $exit = WEXITSTATUS($?);
  465. subprocerr("patch --dry-run") unless WIFEXITED($?);
  466. $self->close();
  467. return ($exit == 0);
  468. }
  469. # Helper functions
  470. sub get_type {
  471. my $file = shift;
  472. if (not lstat($file)) {
  473. return _g("nonexistent") if $! == ENOENT;
  474. syserr(_g("cannot stat %s"), $file);
  475. } else {
  476. -f _ && return _g("plain file");
  477. -d _ && return _g("directory");
  478. -l _ && return sprintf(_g("symlink to %s"), readlink($file));
  479. -b _ && return _g("block device");
  480. -c _ && return _g("character device");
  481. -p _ && return _g("named pipe");
  482. -S _ && return _g("named socket");
  483. }
  484. }
  485. 1;
  486. # vim: set et sw=4 ts=8