Patch.pm 17 KB

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