Hash.pm 12 KB

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