Hash.pm 12 KB

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