Patch.pm 18 KB

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