Patch.pm 18 KB

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