HashCore.pm 14 KB

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