Hash.pm 12 KB

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