Patch.pm 18 KB

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