HashCore.pm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. # Copyright © 2007-2009 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::Control::HashCore;
  16. use strict;
  17. use warnings;
  18. our $VERSION = '1.01';
  19. use Dpkg::Gettext;
  20. use Dpkg::ErrorHandling;
  21. use Dpkg::Control::FieldsCore;
  22. # This module cannot use Dpkg::Control::Fields, because that one makes use
  23. # of Dpkg::Vendor which at the same time uses this module, which would turn
  24. # into a compilation error. We can use Dpkg::Control::FieldsCore instead.
  25. use parent qw(Dpkg::Interface::Storable);
  26. use overload
  27. '%{}' => sub { ${$_[0]}->{fields} },
  28. 'eq' => sub { "$_[0]" eq "$_[1]" };
  29. =encoding utf8
  30. =head1 NAME
  31. Dpkg::Control::HashCore - parse and manipulate a block of RFC822-like fields
  32. =head1 DESCRIPTION
  33. The Dpkg::Control::Hash object is a hash-like representation of a set of
  34. RFC822-like fields. The fields names are case insensitive and are always
  35. capitalized the same when output (see field_capitalize function in
  36. Dpkg::Control::Fields).
  37. The order in which fields have been set is remembered and is used
  38. to be able to dump back the same content. The output order can also be
  39. overridden if needed.
  40. You can store arbitrary values in the hash, they will always be properly
  41. escaped in the output to conform to the syntax of control files. This is
  42. relevant mainly for multilines values: while the first line is always output
  43. unchanged directly after the field name, supplementary lines are
  44. modified. Empty lines and lines containing only dots are prefixed with
  45. " ." (space + dot) while other lines are prefixed with a single space.
  46. During parsing, trailing spaces are stripped on all lines while leading
  47. spaces are stripped only on the first line of each field.
  48. =head1 FUNCTIONS
  49. =over 4
  50. =item my $c = Dpkg::Control::Hash->new(%opts)
  51. Creates a new object with the indicated options. Supported options
  52. are:
  53. =over 8
  54. =item allow_pgp
  55. Configures the parser to accept PGP signatures around the control
  56. information. Value can be 0 (default) or 1.
  57. =item allow_duplicate
  58. Configures the parser to allow duplicate fields in the control
  59. information. Value can be 0 (default) or 1.
  60. =item drop_empty
  61. Defines if empty fields are dropped during the output. Value can be 0
  62. (default) or 1.
  63. =item name
  64. The user friendly name of the information stored in the object. It might
  65. be used in some error messages or warnings. A default name might be set
  66. depending on the type.
  67. =back
  68. =cut
  69. sub new {
  70. my ($this, %opts) = @_;
  71. my $class = ref($this) || $this;
  72. # Object is a scalar reference and not a hash ref to avoid
  73. # infinite recursion due to overloading hash-derefencing
  74. my $self = \{
  75. in_order => [],
  76. out_order => [],
  77. is_pgp_signed => 0,
  78. allow_pgp => 0,
  79. allow_duplicate => 0,
  80. drop_empty => 0,
  81. };
  82. bless $self, $class;
  83. $$self->{fields} = Dpkg::Control::HashCore::Tie->new($self);
  84. # Options set by the user override default values
  85. $$self->{$_} = $opts{$_} foreach keys %opts;
  86. return $self;
  87. }
  88. # There is naturally a circular reference between the tied hash and its
  89. # containing object. Happily, the extra layer of scalar reference can
  90. # be used to detect the destruction of the object and break the loop so
  91. # that everything gets garbage-collected.
  92. sub DESTROY {
  93. my ($self) = @_;
  94. delete $$self->{fields};
  95. }
  96. =item $c->set_options($option, %opts)
  97. Changes the value of one or more options.
  98. =cut
  99. sub set_options {
  100. my ($self, %opts) = @_;
  101. $$self->{$_} = $opts{$_} foreach keys %opts;
  102. }
  103. =item my $value = $c->get_option($option)
  104. Returns the value of the corresponding option.
  105. =cut
  106. sub get_option {
  107. my ($self, $k) = @_;
  108. return $$self->{$k};
  109. }
  110. =item $c->load($file)
  111. Parse the content of $file. Exits in case of errors. Returns true if some
  112. fields have been parsed.
  113. =item $c->parse_error($file, $fmt, ...)
  114. Prints an error message and dies on syntax parse errors.
  115. =cut
  116. sub parse_error {
  117. my ($self, $file, $msg) = (shift, shift, shift);
  118. $msg = sprintf($msg, @_) if (@_);
  119. error(_g('syntax error in %s at line %d: %s'), $file, $., $msg);
  120. }
  121. =item $c->parse($fh, $description)
  122. Parse a control file from the given filehandle. Exits in case of errors.
  123. $description is used to describe the filehandle, ideally it's a filename
  124. or a description of where the data comes from. It's used in error
  125. messages. Returns true if some fields have been parsed.
  126. =cut
  127. sub parse {
  128. my ($self, $fh, $desc) = @_;
  129. my $paraborder = 1;
  130. my $parabody = 0;
  131. my $cf; # Current field
  132. my $expect_pgp_sig = 0;
  133. while (<$fh>) {
  134. s/\s*\n$//;
  135. next if (m/^$/ and $paraborder);
  136. next if (m/^#/);
  137. $paraborder = 0;
  138. if (m/^(\S+?)\s*:\s*(.*)$/) {
  139. $parabody = 1;
  140. if (exists $self->{$1}) {
  141. unless ($$self->{allow_duplicate}) {
  142. $self->parse_error($desc, _g('duplicate field %s found'), $1);
  143. }
  144. }
  145. $self->{$1} = $2;
  146. $cf = $1;
  147. } elsif (m/^\s(\s*\S.*)$/) {
  148. my $line = $1;
  149. unless (defined($cf)) {
  150. $self->parse_error($desc, _g('continued value line not in field'));
  151. }
  152. if ($line =~ /^\.+$/) {
  153. $line = substr $line, 1;
  154. }
  155. $self->{$cf} .= "\n$line";
  156. } elsif (m/^-----BEGIN PGP SIGNED MESSAGE-----$/) {
  157. $expect_pgp_sig = 1;
  158. if ($$self->{allow_pgp} and not $parabody) {
  159. # Skip PGP headers
  160. while (<$fh>) {
  161. last if m/^\s*$/;
  162. }
  163. } else {
  164. $self->parse_error($desc, _g('PGP signature not allowed here'));
  165. }
  166. } elsif (m/^$/ || ($expect_pgp_sig && m/^-----BEGIN PGP SIGNATURE-----$/)) {
  167. if ($expect_pgp_sig) {
  168. # Skip empty lines
  169. $_ = <$fh> while defined($_) && $_ =~ /^\s*$/;
  170. unless (length $_) {
  171. $self->parse_error($desc, _g('expected PGP signature, ' .
  172. 'found EOF after blank line'));
  173. }
  174. s/\s*\n$//;
  175. unless (m/^-----BEGIN PGP SIGNATURE-----$/) {
  176. $self->parse_error($desc, _g('expected PGP signature, ' .
  177. "found something else \`%s'"), $_);
  178. }
  179. # Skip PGP signature
  180. while (<$fh>) {
  181. s/\s*\n$//;
  182. last if m/^-----END PGP SIGNATURE-----$/;
  183. }
  184. unless (defined($_)) {
  185. $self->parse_error($desc, _g('unfinished PGP signature'));
  186. }
  187. # This does not mean the signature is correct, that needs to
  188. # be verified by gnupg.
  189. $$self->{is_pgp_signed} = 1;
  190. }
  191. last; # Finished parsing one block
  192. } else {
  193. $self->parse_error($desc,
  194. _g('line with unknown format (not field-colon-value)'));
  195. }
  196. }
  197. if ($expect_pgp_sig and not $$self->{is_pgp_signed}) {
  198. $self->parse_error($desc, _g('unfinished PGP signature'));
  199. }
  200. return defined($cf);
  201. }
  202. =item $c->find_custom_field($name)
  203. Scan the fields and look for a user specific field whose name matches the
  204. following regex: /X[SBC]*-$name/i. Return the name of the field found or
  205. undef if nothing has been found.
  206. =cut
  207. sub find_custom_field {
  208. my ($self, $name) = @_;
  209. foreach my $key (keys %$self) {
  210. return $key if $key =~ /^X[SBC]*-\Q$name\E$/i;
  211. }
  212. return;
  213. }
  214. =item $c->get_custom_field($name)
  215. Identify a user field and retrieve its value.
  216. =cut
  217. sub get_custom_field {
  218. my ($self, $name) = @_;
  219. my $key = $self->find_custom_field($name);
  220. return $self->{$key} if defined $key;
  221. return;
  222. }
  223. =item $c->save($filename)
  224. Write the string representation of the control information to a
  225. file.
  226. =item my $str = $c->output()
  227. =item "$c"
  228. Get a string representation of the control information. The fields
  229. are sorted in the order in which they have been read or set except
  230. if the order has been overridden with set_output_order().
  231. =item $c->output($fh)
  232. Print the string representation of the control information to a
  233. filehandle.
  234. =cut
  235. sub output {
  236. my ($self, $fh) = @_;
  237. my $str = '';
  238. my @keys;
  239. if (@{$$self->{out_order}}) {
  240. my $i = 1;
  241. my $imp = {};
  242. $imp->{$_} = $i++ foreach @{$$self->{out_order}};
  243. @keys = sort {
  244. if (defined $imp->{$a} && defined $imp->{$b}) {
  245. $imp->{$a} <=> $imp->{$b};
  246. } elsif (defined($imp->{$a})) {
  247. -1;
  248. } elsif (defined($imp->{$b})) {
  249. 1;
  250. } else {
  251. $a cmp $b;
  252. }
  253. } keys %$self;
  254. } else {
  255. @keys = @{$$self->{in_order}};
  256. }
  257. foreach my $key (@keys) {
  258. if (exists $self->{$key}) {
  259. my $value = $self->{$key};
  260. # Skip whitespace-only fields
  261. next if $$self->{drop_empty} and $value !~ m/\S/;
  262. # Escape data to follow control file syntax
  263. my @lines = split(/\n/, $value);
  264. $value = (scalar @lines) ? shift @lines : '';
  265. foreach (@lines) {
  266. s/\s+$//;
  267. if (/^$/ or /^\.+$/) {
  268. $value .= "\n .$_";
  269. } else {
  270. $value .= "\n $_";
  271. }
  272. }
  273. # Print it out
  274. if ($fh) {
  275. print $fh "$key: $value\n"
  276. or syserr(_g('write error on control data'));
  277. }
  278. $str .= "$key: $value\n" if defined wantarray;
  279. }
  280. }
  281. return $str;
  282. }
  283. =item $c->set_output_order(@fields)
  284. Define the order in which fields will be displayed in the output() method.
  285. =cut
  286. sub set_output_order {
  287. my ($self, @fields) = @_;
  288. $$self->{out_order} = [@fields];
  289. }
  290. =item $c->apply_substvars($substvars)
  291. Update all fields by replacing the variables references with
  292. the corresponding value stored in the Dpkg::Substvars object.
  293. =cut
  294. sub apply_substvars {
  295. my ($self, $substvars, %opts) = @_;
  296. # Add substvars to refer to other fields
  297. foreach my $f (keys %$self) {
  298. $substvars->set_as_used("F:$f", $self->{$f});
  299. }
  300. foreach my $f (keys %$self) {
  301. my $v = $substvars->substvars($self->{$f}, %opts);
  302. if ($v ne $self->{$f}) {
  303. my $sep;
  304. $sep = field_get_sep_type($f);
  305. # If we replaced stuff, ensure we're not breaking
  306. # a dependency field by introducing empty lines, or multiple
  307. # commas
  308. if ($sep & (FIELD_SEP_COMMA | FIELD_SEP_LINE)) {
  309. # Drop empty/whitespace-only lines
  310. $v =~ s/\n[ \t]*(\n|$)/$1/;
  311. }
  312. if ($sep & FIELD_SEP_COMMA) {
  313. $v =~ s/,[\s,]*,/,/g;
  314. $v =~ s/^\s*,\s*//;
  315. $v =~ s/\s*,\s*$//;
  316. }
  317. }
  318. $v =~ s/\$\{\}/\$/g; # XXX: what for?
  319. $self->{$f} = $v;
  320. }
  321. }
  322. package Dpkg::Control::HashCore::Tie;
  323. # This object is used to tie a hash. It implements hash-like functions by
  324. # normalizing the name of fields received in keys (using
  325. # Dpkg::Control::Fields::field_capitalize). It also stores the order in
  326. # which fields have been added in order to be able to dump them in the
  327. # same order. But the order information is stored in a parent object of
  328. # type Dpkg::Control.
  329. use Dpkg::Checksums;
  330. use Dpkg::Control::FieldsCore;
  331. use Tie::Hash;
  332. use parent -norequire, qw(Tie::ExtraHash);
  333. # $self->[0] is the real hash
  334. # $self->[1] is a reference to the hash contained by the parent object.
  335. # This reference bypasses the top-level scalar reference of a
  336. # Dpkg::Control::Hash, hence ensuring that that reference gets DESTROYed
  337. # properly.
  338. # Dpkg::Control::Hash->new($parent)
  339. #
  340. # Return a reference to a tied hash implementing storage of simple
  341. # "field: value" mapping as used in many Debian-specific files.
  342. sub new {
  343. my $class = shift;
  344. my $hash = {};
  345. tie %{$hash}, $class, @_;
  346. return $hash;
  347. }
  348. sub TIEHASH {
  349. my ($class, $parent) = @_;
  350. die 'Parent object must be Dpkg::Control::Hash'
  351. if not $parent->isa('Dpkg::Control::HashCore') and
  352. not $parent->isa('Dpkg::Control::Hash');
  353. return bless [ {}, $$parent ], $class;
  354. }
  355. sub FETCH {
  356. my ($self, $key) = @_;
  357. $key = lc($key);
  358. return $self->[0]->{$key} if exists $self->[0]->{$key};
  359. return;
  360. }
  361. sub STORE {
  362. my ($self, $key, $value) = @_;
  363. my $parent = $self->[1];
  364. $key = lc($key);
  365. if (not exists $self->[0]->{$key}) {
  366. push @{$parent->{in_order}}, field_capitalize($key);
  367. }
  368. $self->[0]->{$key} = $value;
  369. }
  370. sub EXISTS {
  371. my ($self, $key) = @_;
  372. $key = lc($key);
  373. return exists $self->[0]->{$key};
  374. }
  375. sub DELETE {
  376. my ($self, $key) = @_;
  377. my $parent = $self->[1];
  378. my $in_order = $parent->{in_order};
  379. $key = lc($key);
  380. if (exists $self->[0]->{$key}) {
  381. delete $self->[0]->{$key};
  382. @$in_order = grep { lc($_) ne $key } @$in_order;
  383. return 1;
  384. } else {
  385. return 0;
  386. }
  387. }
  388. sub FIRSTKEY {
  389. my $self = shift;
  390. my $parent = $self->[1];
  391. foreach (@{$parent->{in_order}}) {
  392. return $_ if exists $self->[0]->{lc($_)};
  393. }
  394. }
  395. sub NEXTKEY {
  396. my ($self, $last) = @_;
  397. my $parent = $self->[1];
  398. my $found = 0;
  399. foreach (@{$parent->{in_order}}) {
  400. if ($found) {
  401. return $_ if exists $self->[0]->{lc($_)};
  402. } else {
  403. $found = 1 if $_ eq $last;
  404. }
  405. }
  406. return;
  407. }
  408. 1;
  409. =back
  410. =head1 CHANGES
  411. =head2 Version 1.01
  412. New method: parse_error().
  413. =head1 AUTHOR
  414. Raphaël Hertzog <hertzog@debian.org>.
  415. =cut
  416. 1;