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