Patch.pm 17 KB

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