Patch.pm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 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. # Default diff options
  53. my @options;
  54. if ($opts{"options"}) {
  55. push @options, @{$opts{"options"}};
  56. } else {
  57. push @options, '-p';
  58. }
  59. # Add labels
  60. if ($opts{"label_old"} and $opts{"label_new"}) {
  61. if ($opts{"include_timestamp"}) {
  62. my $ts = (stat($old))[9];
  63. my $t = POSIX::strftime("%Y-%m-%d %H:%M:%S", gmtime($ts));
  64. $opts{"label_old"} .= sprintf("\t%s.%09d +0000", $t,
  65. ($ts-int($ts))*1000000000);
  66. $ts = (stat($new))[9];
  67. $t = POSIX::strftime("%Y-%m-%d %H:%M:%S", gmtime($ts));
  68. $opts{"label_new"} .= sprintf("\t%s.%09d +0000", $t,
  69. ($ts-int($ts))*1000000000);
  70. } else {
  71. # Space in filenames need special treatment
  72. $opts{"label_old"} .= "\t" if $opts{"label_old"} =~ / /;
  73. $opts{"label_new"} .= "\t" if $opts{"label_new"} =~ / /;
  74. }
  75. push @options, "-L", $opts{"label_old"},
  76. "-L", $opts{"label_new"};
  77. }
  78. # Generate diff
  79. my $diffgen;
  80. my $diff_pid = fork_and_exec(
  81. 'exec' => [ 'diff', '-u', @options, '--', $old, $new ],
  82. 'env' => { LC_ALL => 'C', LANG => 'C', TZ => 'UTC0' },
  83. 'to_pipe' => \$diffgen
  84. );
  85. # Check diff and write it in patch file
  86. my $difflinefound = 0;
  87. while (<$diffgen>) {
  88. if (m/^binary/i) {
  89. $self->_fail_with_msg($new,_g("binary file contents changed"));
  90. last;
  91. } elsif (m/^[-+\@ ]/) {
  92. $difflinefound++;
  93. } elsif (m/^\\ No newline at end of file$/) {
  94. warning(_g("file %s has no final newline (either " .
  95. "original or modified version)"), $new);
  96. } else {
  97. chomp;
  98. internerr(_g("unknown line from diff -u on %s: `%s'"),
  99. $new, $_);
  100. }
  101. print({ $self->{'handle'} } $_) || syserr(_g("failed to write"));
  102. }
  103. close($diffgen) or syserr("close on diff pipe");
  104. wait_child($diff_pid, nocheck => 1,
  105. cmdline => "diff -u @options -- $old $new");
  106. # Verify diff process ended successfully
  107. # Exit code of diff: 0 => no difference, 1 => diff ok, 2 => error
  108. my $exit = WEXITSTATUS($?);
  109. unless (WIFEXITED($?) && ($exit == 0 || $exit == 1)) {
  110. subprocerr(_g("diff on %s"), $new);
  111. }
  112. return $exit;
  113. }
  114. sub add_diff_directory {
  115. my ($self, $old, $new, %opts) = @_;
  116. # TODO: make this function more configurable
  117. # - offer diff generation for removed files
  118. # - offer to disable some checks
  119. my $basedir = $opts{"basedirname"} || basename($new);
  120. my $diff_ignore;
  121. if ($opts{"diff_ignore_func"}) {
  122. $diff_ignore = $opts{"diff_ignore_func"};
  123. } elsif ($opts{"diff_ignore_regexp"}) {
  124. $diff_ignore = sub { return $_[0] =~ /$opts{"diff_ignore_regexp"}/o };
  125. } else {
  126. $diff_ignore = sub { return 0 };
  127. }
  128. my %files_in_new;
  129. my $scan_new = sub {
  130. my $fn = File::Spec->abs2rel($_, $new);
  131. next if &$diff_ignore($fn);
  132. $files_in_new{$fn} = 1;
  133. lstat("$new/$fn") || syserr(_g("cannot stat file %s"), "$new/$fn");
  134. my $mode = S_IMODE((lstat(_))[2]);
  135. my $size = (lstat(_))[7];
  136. if (-l _) {
  137. unless (-l "$old/$fn") {
  138. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  139. return;
  140. }
  141. defined(my $n = readlink("$new/$fn")) ||
  142. syserr(_g("cannot read link %s"), "$new/$fn");
  143. defined(my $n2 = readlink("$old/$fn")) ||
  144. syserr(_g("cannot read link %s"), "$old/$fn");
  145. unless ($n eq $n2) {
  146. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  147. }
  148. } elsif (-f _) {
  149. my $old_file = "$old/$fn";
  150. if (not lstat("$old/$fn")) {
  151. $! == ENOENT ||
  152. syserr(_g("cannot stat file %s"), "$old/$fn");
  153. $old_file = '/dev/null';
  154. if (not $size) {
  155. warning(_g("newly created empty file '%s' will not " .
  156. "be represented in diff"), $fn);
  157. } else {
  158. if ($mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
  159. warning(_g("executable mode %04o of '%s' will " .
  160. "not be represented in diff"), $mode, $fn)
  161. unless $fn eq 'debian/rules';
  162. }
  163. if ($mode & (S_ISUID | S_ISGID | S_ISVTX)) {
  164. warning(_g("special mode %04o of '%s' will not " .
  165. "be represented in diff"), $mode, $fn);
  166. }
  167. }
  168. } elsif (not -f _) {
  169. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  170. return;
  171. }
  172. $self->add_diff_file($old_file, "$new/$fn",
  173. label_old => "$basedir.orig/$fn",
  174. label_new => "$basedir/$fn",
  175. %opts);
  176. } elsif (-p _) {
  177. unless (-p "$old/$fn") {
  178. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  179. }
  180. } elsif (-b _ || -c _ || -S _) {
  181. $self->_fail_with_msg("$new/$fn",
  182. _g("device or socket is not allowed"));
  183. } elsif (-d _) {
  184. if (not lstat("$old/$fn")) {
  185. $! == ENOENT ||
  186. syserr(_g("cannot stat file %s"), "$old/$fn");
  187. } elsif (not -d _) {
  188. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  189. }
  190. } else {
  191. $self->_fail_with_msg("$new/$fn", _g("unknown file type"));
  192. }
  193. };
  194. my $scan_old = sub {
  195. my $fn = File::Spec->abs2rel($_, $old);
  196. return if &$diff_ignore($fn);
  197. return if $files_in_new{$fn};
  198. lstat("$new/$fn") || syserr(_g("cannot stat file %s"), "$old/$fn");
  199. if (-f _) {
  200. warning(_g("ignoring deletion of file %s"), $fn);
  201. } elsif (-d _) {
  202. warning(_g("ignoring deletion of directory %s"), $fn);
  203. } elsif (-l _) {
  204. warning(_g("ignoring deletion of symlink %s"), $fn);
  205. } else {
  206. $self->_fail_not_same_type("$old/$fn", "$new/$fn");
  207. }
  208. };
  209. find({ wanted => $scan_new, no_chdir => 1 }, $new);
  210. find({ wanted => $scan_old, no_chdir => 1 }, $old);
  211. }
  212. sub finish {
  213. my ($self) = @_;
  214. close($self->{'handle'}) ||
  215. syserr(_g("cannot close %s"), $self->get_filename());
  216. delete $self->{'handle'};
  217. $self->cleanup_after_open();
  218. return not $self->{'errors'};
  219. }
  220. sub _fail_with_msg {
  221. my ($self, $file, $msg) = @_;
  222. printf(STDERR _g("%s: cannot represent change to %s: %s")."\n",
  223. $progname, $file, $msg);
  224. $self->{'errors'}++;
  225. }
  226. sub _fail_not_same_type {
  227. my ($self, $old, $new) = @_;
  228. my $old_type = get_type($old);
  229. my $new_type = get_type($new);
  230. printf(STDERR _g("%s: cannot represent change to %s:\n".
  231. "%s: new version is %s\n".
  232. "%s: old version is %s\n"),
  233. $progname, $new, $progname, $old_type, $progname, $new_type);
  234. $self->{'errors'}++;
  235. }
  236. # check diff for sanity, find directories to create as a side effect
  237. sub analyze {
  238. my ($self, $destdir, %opts) = @_;
  239. my $diff = $self->get_filename();
  240. my $diff_handle = $self->open_for_read();
  241. my %filepatched;
  242. my %dirtocreate;
  243. my $diff_count = 0;
  244. $_ = <$diff_handle>;
  245. HUNK:
  246. while (defined($_) || not eof($diff_handle)) {
  247. # skip comments leading up to patch (if any)
  248. until (/^--- /) {
  249. last HUNK if not defined($_ = <$diff_handle>);
  250. }
  251. chomp;
  252. $diff_count++;
  253. # read file header (---/+++ pair)
  254. unless(s/^--- //) {
  255. error(_g("expected ^--- in line %d of diff `%s'"), $., $diff);
  256. }
  257. s/\t.*//; # Strip any timestamp at the end
  258. unless ($_ eq '/dev/null' or s{^(\./)?[^/]+/}{$destdir/}) {
  259. error(_g("diff `%s' patches file with no subdirectory"), $diff);
  260. }
  261. if (/\.dpkg-orig$/) {
  262. error(_g("diff `%s' patches file with name ending .dpkg-orig"), $diff);
  263. }
  264. my $fn = $_;
  265. unless (defined($_= <$diff_handle>) and chomp) {
  266. error(_g("diff `%s' finishes in middle of ---/+++ (line %d)"), $diff, $.);
  267. }
  268. s/\t.*//; # Strip any timestamp at the end
  269. unless (s/^\+\+\+ // and ($_ eq '/dev/null' or s!^(\./)?[^/]+/!!)) {
  270. error(_g("line after --- isn't as expected in diff `%s' (line %d)"),
  271. $diff, $.);
  272. }
  273. if ($fn eq '/dev/null') {
  274. error(_g("original and modified files are /dev/null in diff `%s' (line %d)"),
  275. $diff, $.) if $_ eq '/dev/null';
  276. $fn = "$destdir/$_";
  277. } else {
  278. unless ($_ eq substr($fn, length($destdir) + 1)) {
  279. printf("$_ $fn $destdir %s", substr($fn, length($destdir) + 1));
  280. error(_g("line after --- isn't as expected in diff `%s' (line %d)"),
  281. $diff, $.);
  282. }
  283. }
  284. my $dirname = $fn;
  285. if ($dirname =~ s{/[^/]+$}{} && not -d $dirname) {
  286. $dirtocreate{$dirname} = 1;
  287. }
  288. if (-e $fn and not -f _) {
  289. error(_g("diff `%s' patches something which is not a plain file"), $diff);
  290. }
  291. if ($filepatched{$fn}) {
  292. error(_g("diff `%s' patches file %s twice"), $diff, $fn);
  293. }
  294. $filepatched{$fn} = 1;
  295. # read hunks
  296. my $hunk = 0;
  297. while (defined($_ = <$diff_handle>)) {
  298. # read hunk header (@@)
  299. chomp;
  300. next if /^\\ No newline/;
  301. last unless (/^@@ -\d+(,(\d+))? \+\d+(,(\d+))? @\@( .*)?$/);
  302. my ($olines, $nlines) = ($1 ? $2 : 1, $3 ? $4 : 1);
  303. # read hunk
  304. while ($olines || $nlines) {
  305. unless (defined($_ = <$diff_handle>)) {
  306. error(_g("unexpected end of diff `%s'"), $diff);
  307. }
  308. unless (chomp) {
  309. error(_g("diff `%s' is missing trailing newline"), $diff);
  310. }
  311. next if /^\\ No newline/;
  312. # Check stats
  313. if (/^ /) { --$olines; --$nlines; }
  314. elsif (/^-/) { --$olines; }
  315. elsif (/^\+/) { --$nlines; }
  316. else {
  317. error(_g("expected [ +-] at start of line %d of diff `%s'"),
  318. $., $diff);
  319. }
  320. }
  321. $hunk++;
  322. }
  323. unless($hunk) {
  324. error(_g("expected ^\@\@ at line %d of diff `%s'"), $., $diff);
  325. }
  326. }
  327. close($diff_handle);
  328. unless ($diff_count) {
  329. error(_g("diff `%s' doesn't contain any patch"), $diff);
  330. }
  331. $self->cleanup_after_open();
  332. $self->{'analysis'}{$destdir}{"dirtocreate"} = \%dirtocreate;
  333. $self->{'analysis'}{$destdir}{"filepatched"} = \%filepatched;
  334. return $self->{'analysis'}{$destdir};
  335. }
  336. sub apply {
  337. my ($self, $destdir, %opts) = @_;
  338. # Set default values to options
  339. $opts{"force_timestamp"} = 1 unless exists $opts{"force_timestamp"};
  340. $opts{"remove_backup"} = 1 unless exists $opts{"remove_backup"};
  341. $opts{"create_dirs"} = 1 unless exists $opts{"create_dirs"};
  342. $opts{"options"} ||= [ '-s', '-t', '-F', '0', '-N', '-p1', '-u',
  343. '-V', 'never', '-g0', '-b', '-z', '.dpkg-orig'];
  344. # Check the diff and create missing directories
  345. my $analysis = $self->analyze($destdir, %opts);
  346. if ($opts{"create_dirs"}) {
  347. foreach my $dir (keys %{$analysis->{'dirtocreate'}}) {
  348. eval { mkpath($dir, 0, 0777); };
  349. syserr(_g("cannot create directory %s"), $dir) if $@;
  350. }
  351. }
  352. # Apply the patch
  353. my $diff_handle = $self->open_for_read();
  354. fork_and_exec(
  355. 'exec' => [ 'patch', @{$opts{"options"}} ],
  356. 'chdir' => $destdir,
  357. 'env' => { LC_ALL => 'C', LANG => 'C' },
  358. 'delete_env' => [ 'POSIXLY_CORRECT' ], # ensure expected patch behaviour
  359. 'wait_child' => 1,
  360. 'from_handle' => $diff_handle
  361. );
  362. $self->cleanup_after_open();
  363. # Reset the timestamp of all the patched files
  364. # and remove .dpkg-orig files
  365. my $now = $opts{"timestamp"} || time;
  366. foreach my $fn (keys %{$analysis->{'filepatched'}}) {
  367. if ($opts{"force_timestamp"}) {
  368. utime($now, $now, $fn) ||
  369. syserr(_g("cannot change timestamp for %s"), $fn);
  370. }
  371. if ($opts{"remove_backup"}) {
  372. $fn .= ".dpkg-orig";
  373. unlink($fn) || syserr(_g("remove patch backup file %s"), $fn);
  374. }
  375. }
  376. }
  377. # Helper functions
  378. sub get_type {
  379. my $file = shift;
  380. if (not lstat($file)) {
  381. return _g("nonexistent") if $! == ENOENT;
  382. syserr(_g("cannot stat %s"), $file);
  383. } else {
  384. -f _ && return _g("plain file");
  385. -d _ && return _g("directory");
  386. -l _ && return sprintf(_g("symlink to %"), readlink($file));
  387. -b _ && return _g("block device");
  388. -c _ && return _g("character device");
  389. -p _ && return _g("named pipe");
  390. -S _ && return _g("named socket");
  391. }
  392. }
  393. 1;
  394. # vim: set et sw=4 ts=8