Hash.pm 13 KB

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