Patch.pm 17 KB

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