Patch.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 qw(error errormsg syserr warning subprocerr);
  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 $success = $self->add_diff_file($old_file, "$new/$fn",
  166. label_old => "$basedir.orig/$fn",
  167. label_new => "$basedir/$fn",
  168. %opts);
  169. if ($success and ($old_file eq "/dev/null")) {
  170. if (not $size) {
  171. warning(_g("newly created empty file '%s' will not " .
  172. "be represented in diff"), $fn);
  173. } else {
  174. if ($mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
  175. warning(_g("executable mode %04o of '%s' will " .
  176. "not be represented in diff"), $mode, $fn)
  177. unless $fn eq 'debian/rules';
  178. }
  179. if ($mode & (S_ISUID | S_ISGID | S_ISVTX)) {
  180. warning(_g("special mode %04o of '%s' will not " .
  181. "be represented in diff"), $mode, $fn);
  182. }
  183. }
  184. }
  185. } elsif (-p _) {
  186. unless (-p "$old/$fn") {
  187. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  188. }
  189. } elsif (-b _ || -c _ || -S _) {
  190. $self->_fail_with_msg("$new/$fn",
  191. _g("device or socket is not allowed"));
  192. } elsif (-d _) {
  193. if (not lstat("$old/$fn")) {
  194. $! == ENOENT ||
  195. syserr(_g("cannot stat file %s"), "$old/$fn");
  196. } elsif (not -d _) {
  197. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  198. }
  199. } else {
  200. $self->_fail_with_msg("$new/$fn", _g("unknown file type"));
  201. }
  202. };
  203. my $scan_old = sub {
  204. my $fn = File::Spec->abs2rel($_, $old);
  205. return if &$diff_ignore($fn);
  206. return if $files_in_new{$fn};
  207. lstat("$old/$fn") || syserr(_g("cannot stat file %s"), "$old/$fn");
  208. if (-f _) {
  209. if ($inc_removal) {
  210. $self->add_diff_file("$old/$fn", "/dev/null",
  211. label_old => "$basedir.orig/$fn",
  212. label_new => "/dev/null",
  213. %opts);
  214. } else {
  215. warning(_g("ignoring deletion of file %s"), $fn);
  216. }
  217. } elsif (-d _) {
  218. warning(_g("ignoring deletion of directory %s"), $fn);
  219. } elsif (-l _) {
  220. warning(_g("ignoring deletion of symlink %s"), $fn);
  221. } else {
  222. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  223. }
  224. };
  225. find({ wanted => $scan_new, no_chdir => 1 }, $new);
  226. find({ wanted => $scan_old, no_chdir => 1 }, $old);
  227. }
  228. sub finish {
  229. my ($self) = @_;
  230. close($self->{'handle'}) ||
  231. syserr(_g("cannot close %s"), $self->get_filename());
  232. delete $self->{'handle'};
  233. $self->cleanup_after_open();
  234. return not $self->{'errors'};
  235. }
  236. sub register_error {
  237. my ($self) = @_;
  238. $self->{'errors'}++;
  239. }
  240. sub _fail_with_msg {
  241. my ($self, $file, $msg) = @_;
  242. errormsg(_g("cannot represent change to %s: %s"), $file, $msg);
  243. $self->register_error();
  244. }
  245. sub _fail_not_same_type {
  246. my ($self, $old, $new) = @_;
  247. my $old_type = get_type($old);
  248. my $new_type = get_type($new);
  249. errormsg(_g("cannot represent change to %s:"), $new);
  250. errormsg(_g(" new version is %s"), $old_type);
  251. errormsg(_g(" old version is %s"), $new_type);
  252. $self->register_error();
  253. }
  254. # check diff for sanity, find directories to create as a side effect
  255. sub analyze {
  256. my ($self, $destdir, %opts) = @_;
  257. my $diff = $self->get_filename();
  258. my $diff_handle = $self->open_for_read();
  259. my %filepatched;
  260. my %dirtocreate;
  261. my $diff_count = 0;
  262. $_ = <$diff_handle>;
  263. HUNK:
  264. while (defined($_) || not eof($diff_handle)) {
  265. # skip comments leading up to patch (if any)
  266. until (/^--- /) {
  267. last HUNK if not defined($_ = <$diff_handle>);
  268. }
  269. chomp;
  270. $diff_count++;
  271. # read file header (---/+++ pair)
  272. unless(s/^--- //) {
  273. error(_g("expected ^--- in line %d of diff `%s'"), $., $diff);
  274. }
  275. s/\t.*//; # Strip any timestamp at the end
  276. unless ($_ eq '/dev/null' or s{^(\./)?[^/]+/}{$destdir/}) {
  277. error(_g("diff `%s' patches file with no subdirectory"), $diff);
  278. }
  279. if (/\.dpkg-orig$/) {
  280. error(_g("diff `%s' patches file with name ending .dpkg-orig"), $diff);
  281. }
  282. my $fn = $_;
  283. unless (defined($_= <$diff_handle>) and chomp) {
  284. error(_g("diff `%s' finishes in middle of ---/+++ (line %d)"), $diff, $.);
  285. }
  286. s/\t.*//; # Strip any timestamp at the end
  287. unless (s/^\+\+\+ // and ($_ eq '/dev/null' or s!^(\./)?[^/]+/!!)) {
  288. error(_g("line after --- isn't as expected in diff `%s' (line %d)"),
  289. $diff, $.);
  290. }
  291. if ($fn eq '/dev/null') {
  292. error(_g("original and modified files are /dev/null in diff `%s' (line %d)"),
  293. $diff, $.) if $_ eq '/dev/null';
  294. $fn = "$destdir/$_";
  295. } else {
  296. unless ($_ eq '/dev/null' or $_ eq substr($fn, length($destdir) + 1)) {
  297. error(_g("line after --- isn't as expected in diff `%s' (line %d)"),
  298. $diff, $.);
  299. }
  300. }
  301. my $dirname = $fn;
  302. if ($dirname =~ s{/[^/]+$}{} && not -d $dirname) {
  303. $dirtocreate{$dirname} = 1;
  304. }
  305. if (-e $fn and not -f _) {
  306. error(_g("diff `%s' patches something which is not a plain file"), $diff);
  307. }
  308. if ($filepatched{$fn}) {
  309. error(_g("diff `%s' patches file %s twice"), $diff, $fn);
  310. }
  311. $filepatched{$fn} = 1;
  312. # read hunks
  313. my $hunk = 0;
  314. while (defined($_ = <$diff_handle>)) {
  315. # read hunk header (@@)
  316. chomp;
  317. next if /^\\ No newline/;
  318. last unless (/^@@ -\d+(,(\d+))? \+\d+(,(\d+))? @\@( .*)?$/);
  319. my ($olines, $nlines) = ($1 ? $2 : 1, $3 ? $4 : 1);
  320. # read hunk
  321. while ($olines || $nlines) {
  322. unless (defined($_ = <$diff_handle>)) {
  323. error(_g("unexpected end of diff `%s'"), $diff);
  324. }
  325. unless (chomp) {
  326. error(_g("diff `%s' is missing trailing newline"), $diff);
  327. }
  328. next if /^\\ No newline/;
  329. # Check stats
  330. if (/^ /) { --$olines; --$nlines; }
  331. elsif (/^-/) { --$olines; }
  332. elsif (/^\+/) { --$nlines; }
  333. else {
  334. error(_g("expected [ +-] at start of line %d of diff `%s'"),
  335. $., $diff);
  336. }
  337. }
  338. $hunk++;
  339. }
  340. unless($hunk) {
  341. error(_g("expected ^\@\@ at line %d of diff `%s'"), $., $diff);
  342. }
  343. }
  344. close($diff_handle);
  345. unless ($diff_count) {
  346. warning(_g("diff `%s' doesn't contain any patch"), $diff);
  347. }
  348. $self->cleanup_after_open();
  349. $self->{'analysis'}{$destdir}{"dirtocreate"} = \%dirtocreate;
  350. $self->{'analysis'}{$destdir}{"filepatched"} = \%filepatched;
  351. return $self->{'analysis'}{$destdir};
  352. }
  353. sub apply {
  354. my ($self, $destdir, %opts) = @_;
  355. # Set default values to options
  356. $opts{"force_timestamp"} = 1 unless exists $opts{"force_timestamp"};
  357. $opts{"remove_backup"} = 1 unless exists $opts{"remove_backup"};
  358. $opts{"create_dirs"} = 1 unless exists $opts{"create_dirs"};
  359. $opts{"options"} ||= [ '-s', '-t', '-F', '0', '-N', '-p1', '-u',
  360. '-V', 'never', '-g0', '-b', '-z', '.dpkg-orig'];
  361. $opts{"add_options"} ||= [];
  362. push @{$opts{"options"}}, @{$opts{"add_options"}};
  363. # Check the diff and create missing directories
  364. my $analysis = $self->analyze($destdir, %opts);
  365. if ($opts{"create_dirs"}) {
  366. foreach my $dir (keys %{$analysis->{'dirtocreate'}}) {
  367. eval { mkpath($dir, 0, 0777); };
  368. syserr(_g("cannot create directory %s"), $dir) if $@;
  369. }
  370. }
  371. # Apply the patch
  372. my $diff_handle = $self->open_for_read();
  373. fork_and_exec(
  374. 'exec' => [ 'patch', @{$opts{"options"}} ],
  375. 'chdir' => $destdir,
  376. 'env' => { LC_ALL => 'C', LANG => 'C' },
  377. 'delete_env' => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
  378. 'wait_child' => 1,
  379. 'from_handle' => $diff_handle
  380. );
  381. $self->cleanup_after_open();
  382. # Reset the timestamp of all the patched files
  383. # and remove .dpkg-orig files
  384. my $now = $opts{"timestamp"} || time;
  385. foreach my $fn (keys %{$analysis->{'filepatched'}}) {
  386. if ($opts{"force_timestamp"}) {
  387. utime($now, $now, $fn) || $! == ENOENT ||
  388. syserr(_g("cannot change timestamp for %s"), $fn);
  389. }
  390. if ($opts{"remove_backup"}) {
  391. $fn .= ".dpkg-orig";
  392. unlink($fn) || syserr(_g("remove patch backup file %s"), $fn);
  393. }
  394. }
  395. }
  396. # Helper functions
  397. sub get_type {
  398. my $file = shift;
  399. if (not lstat($file)) {
  400. return _g("nonexistent") if $! == ENOENT;
  401. syserr(_g("cannot stat %s"), $file);
  402. } else {
  403. -f _ && return _g("plain file");
  404. -d _ && return _g("directory");
  405. -l _ && return sprintf(_g("symlink to %s"), readlink($file));
  406. -b _ && return _g("block device");
  407. -c _ && return _g("character device");
  408. -p _ && return _g("named pipe");
  409. -S _ && return _g("named socket");
  410. }
  411. }
  412. 1;
  413. # vim: set et sw=4 ts=8