Patch.pm 17 KB

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