Patch.pm 18 KB

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