Hash.pm 12 KB

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