Commit | Line | Data |
---|---|---|
25f64a11 | 1 | # |
f17010da RU |
2 | # Copyright (c) 1995-2001, Raphael Manfredi |
3 | # Copyright (c) 2002-2013 by the Perl 5 Porters | |
25f64a11 AMS |
4 | # |
5 | # You may redistribute only under the same terms as Perl 5, as specified | |
6 | # in the README file that comes with the distribution. | |
7 | # | |
7a6a85bf | 8 | |
71a48636 | 9 | require XSLoader; |
7a6a85bf | 10 | require Exporter; |
71a48636 | 11 | package Storable; @ISA = qw(Exporter); |
7a6a85bf RG |
12 | |
13 | @EXPORT = qw(store retrieve); | |
14 | @EXPORT_OK = qw( | |
9e21b3d0 | 15 | nstore store_fd nstore_fd fd_retrieve |
7a6a85bf RG |
16 | freeze nfreeze thaw |
17 | dclone | |
9e21b3d0 | 18 | retrieve_fd |
dd19458b | 19 | lock_store lock_nstore lock_retrieve |
d4b9b6e4 | 20 | file_magic read_magic |
7a6a85bf RG |
21 | ); |
22 | ||
01d7b99e | 23 | use vars qw($canonical $forgive_me $VERSION); |
7a6a85bf | 24 | |
997ca471 | 25 | $VERSION = '2.48'; |
7a6a85bf | 26 | |
1541ec63 DL |
27 | BEGIN { |
28 | if (eval { local $SIG{__DIE__}; require Log::Agent; 1 }) { | |
29 | Log::Agent->import; | |
30 | } | |
31 | # | |
32 | # Use of Log::Agent is optional. If it hasn't imported these subs then | |
33 | # provide a fallback implementation. | |
34 | # | |
81447963 | 35 | unless ($Storable::{logcroak} && *{$Storable::{logcroak}}{CODE}) { |
1541ec63 | 36 | require Carp; |
1541ec63 DL |
37 | *logcroak = sub { |
38 | Carp::croak(@_); | |
39 | }; | |
6fe613da | 40 | } |
81447963 | 41 | unless ($Storable::{logcarp} && *{$Storable::{logcarp}}{CODE}) { |
6fe613da | 42 | require Carp; |
1541ec63 DL |
43 | *logcarp = sub { |
44 | Carp::carp(@_); | |
45 | }; | |
46 | } | |
47 | } | |
7a6a85bf | 48 | |
dd19458b JH |
49 | # |
50 | # They might miss :flock in Fcntl | |
51 | # | |
52 | ||
53 | BEGIN { | |
596596d5 | 54 | if (eval { require Fcntl; 1 } && exists $Fcntl::EXPORT_TAGS{'flock'}) { |
dd19458b JH |
55 | Fcntl->import(':flock'); |
56 | } else { | |
57 | eval q{ | |
58 | sub LOCK_SH () {1} | |
59 | sub LOCK_EX () {2} | |
60 | }; | |
61 | } | |
62 | } | |
63 | ||
a8b7ef86 AMS |
64 | sub CLONE { |
65 | # clone context under threads | |
66 | Storable::init_perinterp(); | |
67 | } | |
68 | ||
530b72ba NC |
69 | # By default restricted hashes are downgraded on earlier perls. |
70 | ||
71 | $Storable::downgrade_restricted = 1; | |
e8189732 | 72 | $Storable::accept_future_minor = 1; |
71a48636 | 73 | |
70e1279a | 74 | XSLoader::load('Storable', $Storable::VERSION); |
b8778c7c | 75 | |
862382c7 JH |
76 | # |
77 | # Determine whether locking is possible, but only when needed. | |
78 | # | |
79 | ||
530b72ba | 80 | sub CAN_FLOCK; my $CAN_FLOCK; sub CAN_FLOCK { |
862382c7 JH |
81 | return $CAN_FLOCK if defined $CAN_FLOCK; |
82 | require Config; import Config; | |
83 | return $CAN_FLOCK = | |
84 | $Config{'d_flock'} || | |
85 | $Config{'d_fcntl_can_lock'} || | |
86 | $Config{'d_lockf'}; | |
87 | } | |
88 | ||
0a0da639 JH |
89 | sub show_file_magic { |
90 | print <<EOM; | |
91 | # | |
92 | # To recognize the data files of the Perl module Storable, | |
93 | # the following lines need to be added to the local magic(5) file, | |
94 | # usually either /usr/share/misc/magic or /etc/magic. | |
0a0da639 JH |
95 | # |
96 | 0 string perl-store perl Storable(v0.6) data | |
8b793558 JH |
97 | >4 byte >0 (net-order %d) |
98 | >>4 byte &01 (network-ordered) | |
99 | >>4 byte =3 (major 1) | |
100 | >>4 byte =2 (major 1) | |
101 | ||
0a0da639 | 102 | 0 string pst0 perl Storable(v0.7) data |
8b793558 JH |
103 | >4 byte >0 |
104 | >>4 byte &01 (network-ordered) | |
105 | >>4 byte =5 (major 2) | |
106 | >>4 byte =4 (major 2) | |
107 | >>5 byte >0 (minor %d) | |
0a0da639 JH |
108 | EOM |
109 | } | |
110 | ||
d4b9b6e4 | 111 | sub file_magic { |
ed0d1802 DL |
112 | require IO::File; |
113 | ||
d4b9b6e4 | 114 | my $file = shift; |
ed0d1802 | 115 | my $fh = IO::File->new; |
ab6f8ca1 | 116 | open($fh, "<". $file) || die "Can't open '$file': $!"; |
d4b9b6e4 GA |
117 | binmode($fh); |
118 | defined(sysread($fh, my $buf, 32)) || die "Can't read from '$file': $!"; | |
119 | close($fh); | |
120 | ||
121 | $file = "./$file" unless $file; # ensure TRUE value | |
122 | ||
123 | return read_magic($buf, $file); | |
124 | } | |
125 | ||
b8778c7c | 126 | sub read_magic { |
d4b9b6e4 GA |
127 | my($buf, $file) = @_; |
128 | my %info; | |
129 | ||
130 | my $buflen = length($buf); | |
131 | my $magic; | |
132 | if ($buf =~ s/^(pst0|perl-store)//) { | |
133 | $magic = $1; | |
134 | $info{file} = $file || 1; | |
135 | } | |
136 | else { | |
137 | return undef if $file; | |
138 | $magic = ""; | |
139 | } | |
140 | ||
141 | return undef unless length($buf); | |
142 | ||
143 | my $net_order; | |
144 | if ($magic eq "perl-store" && ord(substr($buf, 0, 1)) > 1) { | |
145 | $info{version} = -1; | |
146 | $net_order = 0; | |
147 | } | |
148 | else { | |
5e12106f NC |
149 | $buf =~ s/(.)//s; |
150 | my $major = (ord $1) >> 1; | |
d4b9b6e4 GA |
151 | return undef if $major > 4; # sanity (assuming we never go that high) |
152 | $info{major} = $major; | |
5e12106f | 153 | $net_order = (ord $1) & 0x01; |
d4b9b6e4 | 154 | if ($major > 1) { |
5e12106f NC |
155 | return undef unless $buf =~ s/(.)//s; |
156 | my $minor = ord $1; | |
d4b9b6e4 GA |
157 | $info{minor} = $minor; |
158 | $info{version} = "$major.$minor"; | |
159 | $info{version_nv} = sprintf "%d.%03d", $major, $minor; | |
160 | } | |
161 | else { | |
162 | $info{version} = $major; | |
163 | } | |
164 | } | |
165 | $info{version_nv} ||= $info{version}; | |
166 | $info{netorder} = $net_order; | |
167 | ||
168 | unless ($net_order) { | |
5e12106f NC |
169 | return undef unless $buf =~ s/(.)//s; |
170 | my $len = ord $1; | |
d4b9b6e4 GA |
171 | return undef unless length($buf) >= $len; |
172 | return undef unless $len == 4 || $len == 8; # sanity | |
5e12106f NC |
173 | @info{qw(byteorder intsize longsize ptrsize)} |
174 | = unpack "a${len}CCC", $buf; | |
175 | (substr $buf, 0, $len + 3) = ''; | |
d4b9b6e4 | 176 | if ($info{version_nv} >= 2.002) { |
5e12106f NC |
177 | return undef unless $buf =~ s/(.)//s; |
178 | $info{nvsize} = ord $1; | |
d4b9b6e4 GA |
179 | } |
180 | } | |
181 | $info{hdrsize} = $buflen - length($buf); | |
182 | ||
183 | return \%info; | |
184 | } | |
185 | ||
186 | sub BIN_VERSION_NV { | |
187 | sprintf "%d.%03d", BIN_MAJOR(), BIN_MINOR(); | |
188 | } | |
189 | ||
190 | sub BIN_WRITE_VERSION_NV { | |
191 | sprintf "%d.%03d", BIN_MAJOR(), BIN_WRITE_MINOR(); | |
b8778c7c | 192 | } |
7a6a85bf RG |
193 | |
194 | # | |
195 | # store | |
196 | # | |
197 | # Store target object hierarchy, identified by a reference to its root. | |
198 | # The stored object tree may later be retrieved to memory via retrieve. | |
199 | # Returns undef if an I/O error occurred, in which case the file is | |
200 | # removed. | |
201 | # | |
202 | sub store { | |
dd19458b | 203 | return _store(\&pstore, @_, 0); |
7a6a85bf RG |
204 | } |
205 | ||
206 | # | |
207 | # nstore | |
208 | # | |
209 | # Same as store, but in network order. | |
210 | # | |
211 | sub nstore { | |
dd19458b JH |
212 | return _store(\&net_pstore, @_, 0); |
213 | } | |
214 | ||
215 | # | |
216 | # lock_store | |
217 | # | |
218 | # Same as store, but flock the file first (advisory locking). | |
219 | # | |
220 | sub lock_store { | |
221 | return _store(\&pstore, @_, 1); | |
222 | } | |
223 | ||
224 | # | |
225 | # lock_nstore | |
226 | # | |
227 | # Same as nstore, but flock the file first (advisory locking). | |
228 | # | |
229 | sub lock_nstore { | |
230 | return _store(\&net_pstore, @_, 1); | |
7a6a85bf RG |
231 | } |
232 | ||
233 | # Internal store to file routine | |
234 | sub _store { | |
235 | my $xsptr = shift; | |
236 | my $self = shift; | |
dd19458b | 237 | my ($file, $use_locking) = @_; |
7a6a85bf | 238 | logcroak "not a reference" unless ref($self); |
b12202d0 | 239 | logcroak "wrong argument number" unless @_ == 2; # No @foo in arglist |
7a6a85bf | 240 | local *FILE; |
dd19458b | 241 | if ($use_locking) { |
6e0ac6f5 | 242 | open(FILE, ">>$file") || logcroak "can't write into $file: $!"; |
862382c7 | 243 | unless (&CAN_FLOCK) { |
b29b780f RM |
244 | logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O"; |
245 | return undef; | |
f567092b | 246 | } |
dd19458b JH |
247 | flock(FILE, LOCK_EX) || |
248 | logcroak "can't get exclusive lock on $file: $!"; | |
249 | truncate FILE, 0; | |
250 | # Unlocking will happen when FILE is closed | |
6e0ac6f5 JH |
251 | } else { |
252 | open(FILE, ">$file") || logcroak "can't create $file: $!"; | |
dd19458b | 253 | } |
6e0ac6f5 | 254 | binmode FILE; # Archaic systems... |
7a6a85bf RG |
255 | my $da = $@; # Don't mess if called from exception handler |
256 | my $ret; | |
257 | # Call C routine nstore or pstore, depending on network order | |
258 | eval { $ret = &$xsptr(*FILE, $self) }; | |
9c09e8a7 NC |
259 | # close will return true on success, so the or short-circuits, the () |
260 | # expression is true, and for that case the block will only be entered | |
261 | # if $@ is true (ie eval failed) | |
262 | # if close fails, it returns false, $ret is altered, *that* is (also) | |
263 | # false, so the () expression is false, !() is true, and the block is | |
264 | # entered. | |
cbc736f3 | 265 | if (!(close(FILE) or undef $ret) || $@) { |
9c09e8a7 NC |
266 | unlink($file) or warn "Can't unlink $file: $!\n"; |
267 | } | |
7a6a85bf RG |
268 | logcroak $@ if $@ =~ s/\.?\n$/,/; |
269 | $@ = $da; | |
cbc736f3 | 270 | return $ret; |
7a6a85bf RG |
271 | } |
272 | ||
273 | # | |
274 | # store_fd | |
275 | # | |
276 | # Same as store, but perform on an already opened file descriptor instead. | |
277 | # Returns undef if an I/O error occurred. | |
278 | # | |
279 | sub store_fd { | |
280 | return _store_fd(\&pstore, @_); | |
281 | } | |
282 | ||
283 | # | |
284 | # nstore_fd | |
285 | # | |
286 | # Same as store_fd, but in network order. | |
287 | # | |
288 | sub nstore_fd { | |
289 | my ($self, $file) = @_; | |
290 | return _store_fd(\&net_pstore, @_); | |
291 | } | |
292 | ||
293 | # Internal store routine on opened file descriptor | |
294 | sub _store_fd { | |
295 | my $xsptr = shift; | |
296 | my $self = shift; | |
297 | my ($file) = @_; | |
298 | logcroak "not a reference" unless ref($self); | |
299 | logcroak "too many arguments" unless @_ == 1; # No @foo in arglist | |
300 | my $fd = fileno($file); | |
301 | logcroak "not a valid file descriptor" unless defined $fd; | |
302 | my $da = $@; # Don't mess if called from exception handler | |
303 | my $ret; | |
304 | # Call C routine nstore or pstore, depending on network order | |
305 | eval { $ret = &$xsptr($file, $self) }; | |
306 | logcroak $@ if $@ =~ s/\.?\n$/,/; | |
596596d5 | 307 | local $\; print $file ''; # Autoflush the file if wanted |
7a6a85bf | 308 | $@ = $da; |
cbc736f3 | 309 | return $ret; |
7a6a85bf RG |
310 | } |
311 | ||
312 | # | |
313 | # freeze | |
314 | # | |
efaa61e2 | 315 | # Store object and its hierarchy in memory and return a scalar |
7a6a85bf RG |
316 | # containing the result. |
317 | # | |
318 | sub freeze { | |
319 | _freeze(\&mstore, @_); | |
320 | } | |
321 | ||
322 | # | |
323 | # nfreeze | |
324 | # | |
325 | # Same as freeze but in network order. | |
326 | # | |
327 | sub nfreeze { | |
328 | _freeze(\&net_mstore, @_); | |
329 | } | |
330 | ||
331 | # Internal freeze routine | |
332 | sub _freeze { | |
333 | my $xsptr = shift; | |
334 | my $self = shift; | |
335 | logcroak "not a reference" unless ref($self); | |
336 | logcroak "too many arguments" unless @_ == 0; # No @foo in arglist | |
337 | my $da = $@; # Don't mess if called from exception handler | |
338 | my $ret; | |
339 | # Call C routine mstore or net_mstore, depending on network order | |
340 | eval { $ret = &$xsptr($self) }; | |
341 | logcroak $@ if $@ =~ s/\.?\n$/,/; | |
342 | $@ = $da; | |
343 | return $ret ? $ret : undef; | |
344 | } | |
345 | ||
346 | # | |
347 | # retrieve | |
348 | # | |
349 | # Retrieve object hierarchy from disk, returning a reference to the root | |
350 | # object of that tree. | |
351 | # | |
352 | sub retrieve { | |
dd19458b JH |
353 | _retrieve($_[0], 0); |
354 | } | |
355 | ||
356 | # | |
357 | # lock_retrieve | |
358 | # | |
359 | # Same as retrieve, but with advisory locking. | |
360 | # | |
361 | sub lock_retrieve { | |
362 | _retrieve($_[0], 1); | |
363 | } | |
364 | ||
365 | # Internal retrieve routine | |
366 | sub _retrieve { | |
367 | my ($file, $use_locking) = @_; | |
7a6a85bf | 368 | local *FILE; |
dd19458b | 369 | open(FILE, $file) || logcroak "can't open $file: $!"; |
7a6a85bf RG |
370 | binmode FILE; # Archaic systems... |
371 | my $self; | |
372 | my $da = $@; # Could be from exception handler | |
dd19458b | 373 | if ($use_locking) { |
862382c7 | 374 | unless (&CAN_FLOCK) { |
8be2b38b | 375 | logcarp "Storable::lock_store: fcntl/flock emulation broken on $^O"; |
b29b780f RM |
376 | return undef; |
377 | } | |
8be2b38b | 378 | flock(FILE, LOCK_SH) || logcroak "can't get shared lock on $file: $!"; |
dd19458b JH |
379 | # Unlocking will happen when FILE is closed |
380 | } | |
7a6a85bf RG |
381 | eval { $self = pretrieve(*FILE) }; # Call C routine |
382 | close(FILE); | |
383 | logcroak $@ if $@ =~ s/\.?\n$/,/; | |
384 | $@ = $da; | |
385 | return $self; | |
386 | } | |
387 | ||
388 | # | |
9e21b3d0 | 389 | # fd_retrieve |
7a6a85bf RG |
390 | # |
391 | # Same as retrieve, but perform from an already opened file descriptor instead. | |
392 | # | |
9e21b3d0 | 393 | sub fd_retrieve { |
7a6a85bf RG |
394 | my ($file) = @_; |
395 | my $fd = fileno($file); | |
396 | logcroak "not a valid file descriptor" unless defined $fd; | |
397 | my $self; | |
398 | my $da = $@; # Could be from exception handler | |
399 | eval { $self = pretrieve($file) }; # Call C routine | |
400 | logcroak $@ if $@ =~ s/\.?\n$/,/; | |
401 | $@ = $da; | |
402 | return $self; | |
403 | } | |
404 | ||
1541ec63 DL |
405 | sub retrieve_fd { &fd_retrieve } # Backward compatibility |
406 | ||
7a6a85bf RG |
407 | # |
408 | # thaw | |
409 | # | |
410 | # Recreate objects in memory from an existing frozen image created | |
411 | # by freeze. If the frozen image passed is undef, return undef. | |
412 | # | |
413 | sub thaw { | |
414 | my ($frozen) = @_; | |
415 | return undef unless defined $frozen; | |
416 | my $self; | |
417 | my $da = $@; # Could be from exception handler | |
418 | eval { $self = mretrieve($frozen) }; # Call C routine | |
419 | logcroak $@ if $@ =~ s/\.?\n$/,/; | |
420 | $@ = $da; | |
421 | return $self; | |
422 | } | |
423 | ||
a2307be4 NC |
424 | 1; |
425 | __END__ | |
426 | ||
7a6a85bf RG |
427 | =head1 NAME |
428 | ||
f062ea6c | 429 | Storable - persistence for Perl data structures |
7a6a85bf RG |
430 | |
431 | =head1 SYNOPSIS | |
432 | ||
433 | use Storable; | |
434 | store \%table, 'file'; | |
435 | $hashref = retrieve('file'); | |
436 | ||
437 | use Storable qw(nstore store_fd nstore_fd freeze thaw dclone); | |
438 | ||
439 | # Network order | |
440 | nstore \%table, 'file'; | |
441 | $hashref = retrieve('file'); # There is NO nretrieve() | |
442 | ||
443 | # Storing to and retrieving from an already opened file | |
444 | store_fd \@array, \*STDOUT; | |
445 | nstore_fd \%table, \*STDOUT; | |
9e21b3d0 JH |
446 | $aryref = fd_retrieve(\*SOCKET); |
447 | $hashref = fd_retrieve(\*SOCKET); | |
7a6a85bf RG |
448 | |
449 | # Serializing to memory | |
450 | $serialized = freeze \%table; | |
451 | %table_clone = %{ thaw($serialized) }; | |
452 | ||
453 | # Deep (recursive) cloning | |
454 | $cloneref = dclone($ref); | |
455 | ||
dd19458b JH |
456 | # Advisory locking |
457 | use Storable qw(lock_store lock_nstore lock_retrieve) | |
458 | lock_store \%table, 'file'; | |
459 | lock_nstore \%table, 'file'; | |
460 | $hashref = lock_retrieve('file'); | |
461 | ||
7a6a85bf RG |
462 | =head1 DESCRIPTION |
463 | ||
f062ea6c | 464 | The Storable package brings persistence to your Perl data structures |
7a6a85bf | 465 | containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be |
c261f00e | 466 | conveniently stored to disk and retrieved at a later time. |
7a6a85bf RG |
467 | |
468 | It can be used in the regular procedural way by calling C<store> with | |
469 | a reference to the object to be stored, along with the file name where | |
470 | the image should be written. | |
775ecd75 | 471 | |
7a6a85bf RG |
472 | The routine returns C<undef> for I/O problems or other internal error, |
473 | a true value otherwise. Serious errors are propagated as a C<die> exception. | |
474 | ||
f062ea6c PN |
475 | To retrieve data stored to disk, use C<retrieve> with a file name. |
476 | The objects stored into that file are recreated into memory for you, | |
477 | and a I<reference> to the root object is returned. In case an I/O error | |
7a6a85bf RG |
478 | occurs while reading, C<undef> is returned instead. Other serious |
479 | errors are propagated via C<die>. | |
480 | ||
481 | Since storage is performed recursively, you might want to stuff references | |
482 | to objects that share a lot of common data into a single array or hash | |
483 | table, and then store that object. That way, when you retrieve back the | |
484 | whole thing, the objects will continue to share what they originally shared. | |
485 | ||
486 | At the cost of a slight header overhead, you may store to an already | |
487 | opened file descriptor using the C<store_fd> routine, and retrieve | |
9e21b3d0 | 488 | from a file via C<fd_retrieve>. Those names aren't imported by default, |
c261f00e | 489 | so you will have to do that explicitly if you need those routines. |
7a6a85bf RG |
490 | The file descriptor you supply must be already opened, for read |
491 | if you're going to retrieve and for write if you wish to store. | |
492 | ||
493 | store_fd(\%table, *STDOUT) || die "can't store to stdout\n"; | |
9e21b3d0 | 494 | $hashref = fd_retrieve(*STDIN); |
7a6a85bf RG |
495 | |
496 | You can also store data in network order to allow easy sharing across | |
497 | multiple platforms, or when storing on a socket known to be remotely | |
498 | connected. The routines to call have an initial C<n> prefix for I<network>, | |
499 | as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be | |
500 | correctly restored so you don't have to know whether you're restoring | |
dd19458b JH |
501 | from native or network ordered data. Double values are stored stringified |
502 | to ensure portability as well, at the slight risk of loosing some precision | |
503 | in the last decimals. | |
7a6a85bf | 504 | |
9e21b3d0 | 505 | When using C<fd_retrieve>, objects are retrieved in sequence, one |
7a6a85bf RG |
506 | object (i.e. one recursive tree) per associated C<store_fd>. |
507 | ||
508 | If you're more from the object-oriented camp, you can inherit from | |
509 | Storable and directly store your objects by invoking C<store> as | |
510 | a method. The fact that the root of the to-be-stored tree is a | |
511 | blessed reference (i.e. an object) is special-cased so that the | |
512 | retrieve does not provide a reference to that object but rather the | |
513 | blessed object reference itself. (Otherwise, you'd get a reference | |
514 | to that blessed object). | |
515 | ||
516 | =head1 MEMORY STORE | |
517 | ||
518 | The Storable engine can also store data into a Perl scalar instead, to | |
519 | later retrieve them. This is mainly used to freeze a complex structure in | |
520 | some safe compact memory place (where it can possibly be sent to another | |
521 | process via some IPC, since freezing the structure also serializes it in | |
522 | effect). Later on, and maybe somewhere else, you can thaw the Perl scalar | |
523 | out and recreate the original complex structure in memory. | |
524 | ||
525 | Surprisingly, the routines to be called are named C<freeze> and C<thaw>. | |
526 | If you wish to send out the frozen scalar to another machine, use | |
527 | C<nfreeze> instead to get a portable image. | |
528 | ||
529 | Note that freezing an object structure and immediately thawing it | |
530 | actually achieves a deep cloning of that structure: | |
531 | ||
532 | dclone(.) = thaw(freeze(.)) | |
533 | ||
534 | Storable provides you with a C<dclone> interface which does not create | |
535 | that intermediary scalar but instead freezes the structure in some | |
c261f00e | 536 | internal memory space and then immediately thaws it out. |
7a6a85bf | 537 | |
dd19458b JH |
538 | =head1 ADVISORY LOCKING |
539 | ||
f062ea6c PN |
540 | The C<lock_store> and C<lock_nstore> routine are equivalent to |
541 | C<store> and C<nstore>, except that they get an exclusive lock on | |
542 | the file before writing. Likewise, C<lock_retrieve> does the same | |
543 | as C<retrieve>, but also gets a shared lock on the file before reading. | |
dd19458b | 544 | |
f062ea6c PN |
545 | As with any advisory locking scheme, the protection only works if you |
546 | systematically use C<lock_store> and C<lock_retrieve>. If one side of | |
547 | your application uses C<store> whilst the other uses C<lock_retrieve>, | |
dd19458b JH |
548 | you will get no protection at all. |
549 | ||
f062ea6c PN |
550 | The internal advisory locking is implemented using Perl's flock() |
551 | routine. If your system does not support any form of flock(), or if | |
552 | you share your files across NFS, you might wish to use other forms | |
553 | of locking by using modules such as LockFile::Simple which lock a | |
554 | file using a filesystem entry, instead of locking the file descriptor. | |
dd19458b | 555 | |
7a6a85bf RG |
556 | =head1 SPEED |
557 | ||
558 | The heart of Storable is written in C for decent speed. Extra low-level | |
4d3295e3 PN |
559 | optimizations have been made when manipulating perl internals, to |
560 | sacrifice encapsulation for the benefit of greater speed. | |
7a6a85bf RG |
561 | |
562 | =head1 CANONICAL REPRESENTATION | |
563 | ||
f062ea6c | 564 | Normally, Storable stores elements of hashes in the order they are |
7a6a85bf RG |
565 | stored internally by Perl, i.e. pseudo-randomly. If you set |
566 | C<$Storable::canonical> to some C<TRUE> value, Storable will store | |
567 | hashes with the elements sorted by their key. This allows you to | |
568 | compare data structures by comparing their frozen representations (or | |
569 | even the compressed frozen representations), which can be useful for | |
570 | creating lookup tables for complicated queries. | |
571 | ||
f062ea6c | 572 | Canonical order does not imply network order; those are two orthogonal |
7a6a85bf RG |
573 | settings. |
574 | ||
d2b96869 SR |
575 | =head1 CODE REFERENCES |
576 | ||
577 | Since Storable version 2.05, CODE references may be serialized with | |
578 | the help of L<B::Deparse>. To enable this feature, set | |
3c4b39be | 579 | C<$Storable::Deparse> to a true value. To enable deserialization, |
d2b96869 SR |
580 | C<$Storable::Eval> should be set to a true value. Be aware that |
581 | deserialization is done through C<eval>, which is dangerous if the | |
582 | Storable file contains malicious data. You can set C<$Storable::Eval> | |
583 | to a subroutine reference which would be used instead of C<eval>. See | |
584 | below for an example using a L<Safe> compartment for deserialization | |
585 | of CODE references. | |
586 | ||
197b90bc SR |
587 | If C<$Storable::Deparse> and/or C<$Storable::Eval> are set to false |
588 | values, then the value of C<$Storable::forgive_me> (see below) is | |
589 | respected while serializing and deserializing. | |
590 | ||
c261f00e NC |
591 | =head1 FORWARD COMPATIBILITY |
592 | ||
593 | This release of Storable can be used on a newer version of Perl to | |
f062ea6c | 594 | serialize data which is not supported by earlier Perls. By default, |
c261f00e | 595 | Storable will attempt to do the right thing, by C<croak()>ing if it |
775ecd75 | 596 | encounters data that it cannot deserialize. However, the defaults |
f062ea6c | 597 | can be changed as follows: |
c261f00e NC |
598 | |
599 | =over 4 | |
600 | ||
601 | =item utf8 data | |
602 | ||
603 | Perl 5.6 added support for Unicode characters with code points > 255, | |
604 | and Perl 5.8 has full support for Unicode characters in hash keys. | |
605 | Perl internally encodes strings with these characters using utf8, and | |
606 | Storable serializes them as utf8. By default, if an older version of | |
607 | Perl encounters a utf8 value it cannot represent, it will C<croak()>. | |
608 | To change this behaviour so that Storable deserializes utf8 encoded | |
609 | values as the string of bytes (effectively dropping the I<is_utf8> flag) | |
610 | set C<$Storable::drop_utf8> to some C<TRUE> value. This is a form of | |
611 | data loss, because with C<$drop_utf8> true, it becomes impossible to tell | |
612 | whether the original data was the Unicode string, or a series of bytes | |
613 | that happen to be valid utf8. | |
614 | ||
615 | =item restricted hashes | |
616 | ||
f062ea6c PN |
617 | Perl 5.8 adds support for restricted hashes, which have keys |
618 | restricted to a given set, and can have values locked to be read only. | |
619 | By default, when Storable encounters a restricted hash on a perl | |
620 | that doesn't support them, it will deserialize it as a normal hash, | |
621 | silently discarding any placeholder keys and leaving the keys and | |
622 | all values unlocked. To make Storable C<croak()> instead, set | |
623 | C<$Storable::downgrade_restricted> to a C<FALSE> value. To restore | |
624 | the default set it back to some C<TRUE> value. | |
c261f00e | 625 | |
e8189732 NC |
626 | =item files from future versions of Storable |
627 | ||
628 | Earlier versions of Storable would immediately croak if they encountered | |
629 | a file with a higher internal version number than the reading Storable | |
630 | knew about. Internal version numbers are increased each time new data | |
631 | types (such as restricted hashes) are added to the vocabulary of the file | |
632 | format. This meant that a newer Storable module had no way of writing a | |
f062ea6c | 633 | file readable by an older Storable, even if the writer didn't store newer |
e8189732 NC |
634 | data types. |
635 | ||
636 | This version of Storable will defer croaking until it encounters a data | |
637 | type in the file that it does not recognize. This means that it will | |
638 | continue to read files generated by newer Storable modules which are careful | |
639 | in what they write out, making it easier to upgrade Storable modules in a | |
640 | mixed environment. | |
641 | ||
642 | The old behaviour of immediate croaking can be re-instated by setting | |
f062ea6c | 643 | C<$Storable::accept_future_minor> to some C<FALSE> value. |
e8189732 | 644 | |
c261f00e NC |
645 | =back |
646 | ||
f062ea6c | 647 | All these variables have no effect on a newer Perl which supports the |
c261f00e NC |
648 | relevant feature. |
649 | ||
7a6a85bf RG |
650 | =head1 ERROR REPORTING |
651 | ||
652 | Storable uses the "exception" paradigm, in that it does not try to workaround | |
653 | failures: if something bad happens, an exception is generated from the | |
654 | caller's perspective (see L<Carp> and C<croak()>). Use eval {} to trap | |
655 | those exceptions. | |
656 | ||
657 | When Storable croaks, it tries to report the error via the C<logcroak()> | |
658 | routine from the C<Log::Agent> package, if it is available. | |
659 | ||
212e9bde JH |
660 | Normal errors are reported by having store() or retrieve() return C<undef>. |
661 | Such errors are usually I/O errors (or truncated stream errors at retrieval). | |
662 | ||
7a6a85bf RG |
663 | =head1 WIZARDS ONLY |
664 | ||
665 | =head2 Hooks | |
666 | ||
667 | Any class may define hooks that will be called during the serialization | |
668 | and deserialization process on objects that are instances of that class. | |
669 | Those hooks can redefine the way serialization is performed (and therefore, | |
c261f00e | 670 | how the symmetrical deserialization should be conducted). |
7a6a85bf RG |
671 | |
672 | Since we said earlier: | |
673 | ||
674 | dclone(.) = thaw(freeze(.)) | |
675 | ||
676 | everything we say about hooks should also hold for deep cloning. However, | |
677 | hooks get to know whether the operation is a mere serialization, or a cloning. | |
678 | ||
679 | Therefore, when serializing hooks are involved, | |
680 | ||
681 | dclone(.) <> thaw(freeze(.)) | |
682 | ||
683 | Well, you could keep them in sync, but there's no guarantee it will always | |
684 | hold on classes somebody else wrote. Besides, there is little to gain in | |
f062ea6c | 685 | doing so: a serializing hook could keep only one attribute of an object, |
7a6a85bf RG |
686 | which is probably not what should happen during a deep cloning of that |
687 | same object. | |
688 | ||
689 | Here is the hooking interface: | |
690 | ||
bbc7dcd2 | 691 | =over 4 |
7a6a85bf RG |
692 | |
693 | =item C<STORABLE_freeze> I<obj>, I<cloning> | |
694 | ||
695 | The serializing hook, called on the object during serialization. It can be | |
696 | inherited, or defined in the class itself, like any other method. | |
697 | ||
698 | Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating | |
699 | whether we're in a dclone() or a regular serialization via store() or freeze(). | |
700 | ||
701 | Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized | |
702 | is the serialized form to be used, and the optional $ref1, $ref2, etc... are | |
703 | extra references that you wish to let the Storable engine serialize. | |
704 | ||
705 | At deserialization time, you will be given back the same LIST, but all the | |
706 | extra references will be pointing into the deserialized structure. | |
707 | ||
708 | The B<first time> the hook is hit in a serialization flow, you may have it | |
709 | return an empty list. That will signal the Storable engine to further | |
710 | discard that hook for this class and to therefore revert to the default | |
711 | serialization of the underlying Perl data. The hook will again be normally | |
712 | processed in the next serialization. | |
713 | ||
714 | Unless you know better, serializing hook should always say: | |
715 | ||
716 | sub STORABLE_freeze { | |
717 | my ($self, $cloning) = @_; | |
718 | return if $cloning; # Regular default serialization | |
719 | .... | |
720 | } | |
721 | ||
722 | in order to keep reasonable dclone() semantics. | |
723 | ||
724 | =item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ... | |
725 | ||
726 | The deserializing hook called on the object during deserialization. | |
f062ea6c | 727 | But wait: if we're deserializing, there's no object yet... right? |
7a6a85bf RG |
728 | |
729 | Wrong: the Storable engine creates an empty one for you. If you know Eiffel, | |
730 | you can view C<STORABLE_thaw> as an alternate creation routine. | |
731 | ||
732 | This means the hook can be inherited like any other method, and that | |
733 | I<obj> is your blessed reference for this particular instance. | |
734 | ||
735 | The other arguments should look familiar if you know C<STORABLE_freeze>: | |
736 | I<cloning> is true when we're part of a deep clone operation, I<serialized> | |
737 | is the serialized string you returned to the engine in C<STORABLE_freeze>, | |
738 | and there may be an optional list of references, in the same order you gave | |
739 | them at serialization time, pointing to the deserialized objects (which | |
740 | have been processed courtesy of the Storable engine). | |
741 | ||
212e9bde JH |
742 | When the Storable engine does not find any C<STORABLE_thaw> hook routine, |
743 | it tries to load the class by requiring the package dynamically (using | |
744 | the blessed package name), and then re-attempts the lookup. If at that | |
745 | time the hook cannot be located, the engine croaks. Note that this mechanism | |
c261f00e | 746 | will fail if you define several classes in the same file, but L<perlmod> |
212e9bde JH |
747 | warned you. |
748 | ||
f062ea6c | 749 | It is up to you to use this information to populate I<obj> the way you want. |
7a6a85bf RG |
750 | |
751 | Returned value: none. | |
752 | ||
2f796f32 AMS |
753 | =item C<STORABLE_attach> I<class>, I<cloning>, I<serialized> |
754 | ||
755 | While C<STORABLE_freeze> and C<STORABLE_thaw> are useful for classes where | |
3c4b39be | 756 | each instance is independent, this mechanism has difficulty (or is |
2f796f32 AMS |
757 | incompatible) with objects that exist as common process-level or |
758 | system-level resources, such as singleton objects, database pools, caches | |
759 | or memoized objects. | |
760 | ||
761 | The alternative C<STORABLE_attach> method provides a solution for these | |
1e2a0f0b RGS |
762 | shared objects. Instead of C<STORABLE_freeze> --E<gt> C<STORABLE_thaw>, |
763 | you implement C<STORABLE_freeze> --E<gt> C<STORABLE_attach> instead. | |
2f796f32 AMS |
764 | |
765 | Arguments: I<class> is the class we are attaching to, I<cloning> is a flag | |
766 | indicating whether we're in a dclone() or a regular de-serialization via | |
767 | thaw(), and I<serialized> is the stored string for the resource object. | |
768 | ||
769 | Because these resource objects are considered to be owned by the entire | |
770 | process/system, and not the "property" of whatever is being serialized, | |
771 | no references underneath the object should be included in the serialized | |
772 | string. Thus, in any class that implements C<STORABLE_attach>, the | |
773 | C<STORABLE_freeze> method cannot return any references, and C<Storable> | |
774 | will throw an error if C<STORABLE_freeze> tries to return references. | |
775 | ||
776 | All information required to "attach" back to the shared resource object | |
777 | B<must> be contained B<only> in the C<STORABLE_freeze> return string. | |
778 | Otherwise, C<STORABLE_freeze> behaves as normal for C<STORABLE_attach> | |
779 | classes. | |
780 | ||
781 | Because C<STORABLE_attach> is passed the class (rather than an object), | |
782 | it also returns the object directly, rather than modifying the passed | |
783 | object. | |
784 | ||
785 | Returned value: object of type C<class> | |
786 | ||
7a6a85bf RG |
787 | =back |
788 | ||
789 | =head2 Predicates | |
790 | ||
c261f00e | 791 | Predicates are not exportable. They must be called by explicitly prefixing |
7a6a85bf RG |
792 | them with the Storable package name. |
793 | ||
bbc7dcd2 | 794 | =over 4 |
7a6a85bf RG |
795 | |
796 | =item C<Storable::last_op_in_netorder> | |
797 | ||
798 | The C<Storable::last_op_in_netorder()> predicate will tell you whether | |
799 | network order was used in the last store or retrieve operation. If you | |
800 | don't know how to use this, just forget about it. | |
801 | ||
802 | =item C<Storable::is_storing> | |
803 | ||
804 | Returns true if within a store operation (via STORABLE_freeze hook). | |
805 | ||
806 | =item C<Storable::is_retrieving> | |
807 | ||
f062ea6c | 808 | Returns true if within a retrieve operation (via STORABLE_thaw hook). |
7a6a85bf RG |
809 | |
810 | =back | |
811 | ||
812 | =head2 Recursion | |
813 | ||
f062ea6c PN |
814 | With hooks comes the ability to recurse back to the Storable engine. |
815 | Indeed, hooks are regular Perl code, and Storable is convenient when | |
816 | it comes to serializing and deserializing things, so why not use it | |
817 | to handle the serialization string? | |
7a6a85bf | 818 | |
f062ea6c | 819 | There are a few things you need to know, however: |
7a6a85bf | 820 | |
bbc7dcd2 | 821 | =over 4 |
7a6a85bf RG |
822 | |
823 | =item * | |
824 | ||
825 | You can create endless loops if the things you serialize via freeze() | |
f062ea6c PN |
826 | (for instance) point back to the object we're trying to serialize in |
827 | the hook. | |
7a6a85bf RG |
828 | |
829 | =item * | |
830 | ||
831 | Shared references among objects will not stay shared: if we're serializing | |
832 | the list of object [A, C] where both object A and C refer to the SAME object | |
833 | B, and if there is a serializing hook in A that says freeze(B), then when | |
834 | deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D, | |
835 | a deep clone of B'. The topology was not preserved. | |
836 | ||
837 | =back | |
838 | ||
839 | That's why C<STORABLE_freeze> lets you provide a list of references | |
840 | to serialize. The engine guarantees that those will be serialized in the | |
841 | same context as the other objects, and therefore that shared objects will | |
842 | stay shared. | |
843 | ||
844 | In the above [A, C] example, the C<STORABLE_freeze> hook could return: | |
845 | ||
846 | ("something", $self->{B}) | |
847 | ||
848 | and the B part would be serialized by the engine. In C<STORABLE_thaw>, you | |
849 | would get back the reference to the B' object, deserialized for you. | |
850 | ||
851 | Therefore, recursion should normally be avoided, but is nonetheless supported. | |
852 | ||
853 | =head2 Deep Cloning | |
854 | ||
f062ea6c | 855 | There is a Clone module available on CPAN which implements deep cloning |
7a6a85bf RG |
856 | natively, i.e. without freezing to memory and thawing the result. It is |
857 | aimed to replace Storable's dclone() some day. However, it does not currently | |
858 | support Storable hooks to redefine the way deep cloning is performed. | |
859 | ||
0a0da639 JH |
860 | =head1 Storable magic |
861 | ||
862 | Yes, there's a lot of that :-) But more precisely, in UNIX systems | |
863 | there's a utility called C<file>, which recognizes data files based on | |
864 | their contents (usually their first few bytes). For this to work, | |
8b793558 | 865 | a certain file called F<magic> needs to taught about the I<signature> |
0a0da639 | 866 | of the data. Where that configuration file lives depends on the UNIX |
f062ea6c | 867 | flavour; often it's something like F</usr/share/misc/magic> or |
8b793558 JH |
868 | F</etc/magic>. Your system administrator needs to do the updating of |
869 | the F<magic> file. The necessary signature information is output to | |
f062ea6c PN |
870 | STDOUT by invoking Storable::show_file_magic(). Note that the GNU |
871 | implementation of the C<file> utility, version 3.38 or later, | |
872 | is expected to contain support for recognising Storable files | |
873 | out-of-the-box, in addition to other kinds of Perl files. | |
0a0da639 | 874 | |
d4b9b6e4 GA |
875 | You can also use the following functions to extract the file header |
876 | information from Storable images: | |
877 | ||
878 | =over | |
879 | ||
880 | =item $info = Storable::file_magic( $filename ) | |
881 | ||
882 | If the given file is a Storable image return a hash describing it. If | |
883 | the file is readable, but not a Storable image return C<undef>. If | |
884 | the file does not exist or is unreadable then croak. | |
885 | ||
886 | The hash returned has the following elements: | |
887 | ||
888 | =over | |
889 | ||
890 | =item C<version> | |
891 | ||
892 | This returns the file format version. It is a string like "2.7". | |
893 | ||
894 | Note that this version number is not the same as the version number of | |
895 | the Storable module itself. For instance Storable v0.7 create files | |
896 | in format v2.0 and Storable v2.15 create files in format v2.7. The | |
897 | file format version number only increment when additional features | |
898 | that would confuse older versions of the module are added. | |
899 | ||
900 | Files older than v2.0 will have the one of the version numbers "-1", | |
901 | "0" or "1". No minor number was used at that time. | |
902 | ||
903 | =item C<version_nv> | |
904 | ||
905 | This returns the file format version as number. It is a string like | |
906 | "2.007". This value is suitable for numeric comparisons. | |
907 | ||
908 | The constant function C<Storable::BIN_VERSION_NV> returns a comparable | |
b846e6a6 FC |
909 | number that represents the highest file version number that this |
910 | version of Storable fully supports (but see discussion of | |
d4b9b6e4 GA |
911 | C<$Storable::accept_future_minor> above). The constant |
912 | C<Storable::BIN_WRITE_VERSION_NV> function returns what file version | |
913 | is written and might be less than C<Storable::BIN_VERSION_NV> in some | |
c4a6f826 | 914 | configurations. |
d4b9b6e4 GA |
915 | |
916 | =item C<major>, C<minor> | |
917 | ||
918 | This also returns the file format version. If the version is "2.7" | |
919 | then major would be 2 and minor would be 7. The minor element is | |
920 | missing for when major is less than 2. | |
921 | ||
922 | =item C<hdrsize> | |
923 | ||
924 | The is the number of bytes that the Storable header occupies. | |
925 | ||
926 | =item C<netorder> | |
927 | ||
928 | This is TRUE if the image store data in network order. This means | |
929 | that it was created with nstore() or similar. | |
930 | ||
931 | =item C<byteorder> | |
932 | ||
933 | This is only present when C<netorder> is FALSE. It is the | |
934 | $Config{byteorder} string of the perl that created this image. It is | |
935 | a string like "1234" (32 bit little endian) or "87654321" (64 bit big | |
936 | endian). This must match the current perl for the image to be | |
937 | readable by Storable. | |
938 | ||
939 | =item C<intsize>, C<longsize>, C<ptrsize>, C<nvsize> | |
940 | ||
941 | These are only present when C<netorder> is FALSE. These are the sizes of | |
942 | various C datatypes of the perl that created this image. These must | |
943 | match the current perl for the image to be readable by Storable. | |
944 | ||
945 | The C<nvsize> element is only present for file format v2.2 and | |
946 | higher. | |
947 | ||
948 | =item C<file> | |
949 | ||
950 | The name of the file. | |
951 | ||
952 | =back | |
953 | ||
954 | =item $info = Storable::read_magic( $buffer ) | |
955 | ||
956 | =item $info = Storable::read_magic( $buffer, $must_be_file ) | |
957 | ||
958 | The $buffer should be a Storable image or the first few bytes of it. | |
959 | If $buffer starts with a Storable header, then a hash describing the | |
960 | image is returned, otherwise C<undef> is returned. | |
961 | ||
962 | The hash has the same structure as the one returned by | |
963 | Storable::file_magic(). The C<file> element is true if the image is a | |
964 | file image. | |
965 | ||
966 | If the $must_be_file argument is provided and is TRUE, then return | |
967 | C<undef> unless the image looks like it belongs to a file dump. | |
968 | ||
969 | The maximum size of a Storable header is currently 21 bytes. If the | |
970 | provided $buffer is only the first part of a Storable image it should | |
971 | at least be this long to ensure that read_magic() will recognize it as | |
972 | such. | |
973 | ||
974 | =back | |
975 | ||
7a6a85bf RG |
976 | =head1 EXAMPLES |
977 | ||
978 | Here are some code samples showing a possible usage of Storable: | |
979 | ||
980 | use Storable qw(store retrieve freeze thaw dclone); | |
981 | ||
982 | %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1); | |
983 | ||
2359510d | 984 | store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n"; |
7a6a85bf | 985 | |
2359510d SD |
986 | $colref = retrieve('mycolors'); |
987 | die "Unable to retrieve from mycolors!\n" unless defined $colref; | |
7a6a85bf RG |
988 | printf "Blue is still %lf\n", $colref->{'Blue'}; |
989 | ||
990 | $colref2 = dclone(\%color); | |
991 | ||
992 | $str = freeze(\%color); | |
993 | printf "Serialization of %%color is %d bytes long.\n", length($str); | |
994 | $colref3 = thaw($str); | |
995 | ||
996 | which prints (on my machine): | |
997 | ||
998 | Blue is still 0.100000 | |
999 | Serialization of %color is 102 bytes long. | |
1000 | ||
d2b96869 SR |
1001 | Serialization of CODE references and deserialization in a safe |
1002 | compartment: | |
1003 | ||
197b90bc SR |
1004 | =for example begin |
1005 | ||
d2b96869 SR |
1006 | use Storable qw(freeze thaw); |
1007 | use Safe; | |
1008 | use strict; | |
1009 | my $safe = new Safe; | |
197b90bc | 1010 | # because of opcodes used in "use strict": |
d1e2299c | 1011 | $safe->permit(qw(:default require)); |
d2b96869 SR |
1012 | local $Storable::Deparse = 1; |
1013 | local $Storable::Eval = sub { $safe->reval($_[0]) }; | |
197b90bc | 1014 | my $serialized = freeze(sub { 42 }); |
d2b96869 | 1015 | my $code = thaw($serialized); |
197b90bc SR |
1016 | $code->() == 42; |
1017 | ||
1018 | =for example end | |
1019 | ||
1020 | =for example_testing | |
1021 | is( $code->(), 42 ); | |
d2b96869 | 1022 | |
664f237a S |
1023 | =head1 SECURITY WARNING |
1024 | ||
1025 | B<Do not accept Storable documents from untrusted sources!> | |
1026 | ||
1027 | Some features of Storable can lead to security vulnerabilities if you | |
1028 | accept Storable documents from untrusted sources. Most obviously, the | |
1029 | optional (off by default) CODE reference serialization feature allows | |
1030 | transfer of code to the deserializing process. Furthermore, any | |
1031 | serialized object will cause Storable to helpfully load the module | |
1032 | corresponding to the class of the object in the deserializing module. | |
1033 | For manipulated module names, this can load almost arbitrary code. | |
1034 | Finally, the deserialized object's destructors will be invoked when | |
1035 | the objects get destroyed in the deserializing process. Maliciously | |
1036 | crafted Storable documents may put such objects in the value of | |
1037 | a hash key that is overridden by another key/value pair in the | |
1038 | same hash, thus causing immediate destructor execution. | |
1039 | ||
1040 | In a future version of Storable, we intend to provide options to disable | |
1041 | loading modules for classes and to disable deserializing objects | |
1042 | altogether. I<Nonetheless, Storable deserializing documents from | |
1043 | untrusted sources is expected to have other, yet undiscovered, | |
1044 | security concerns such as allowing an attacker to cause the deserializer | |
1045 | to crash hard.> | |
1046 | ||
1047 | B<Therefore, let me repeat: Do not accept Storable documents from | |
1048 | untrusted sources!> | |
1049 | ||
1050 | If your application requires accepting data from untrusted sources, you | |
1051 | are best off with a less powerful and more-likely safe serialization format | |
efaa61e2 | 1052 | and implementation. If your data is sufficiently simple, JSON is a good |
664f237a S |
1053 | choice and offers maximum interoperability. |
1054 | ||
7a6a85bf RG |
1055 | =head1 WARNING |
1056 | ||
1057 | If you're using references as keys within your hash tables, you're bound | |
f062ea6c | 1058 | to be disappointed when retrieving your data. Indeed, Perl stringifies |
7a6a85bf RG |
1059 | references used as hash table keys. If you later wish to access the |
1060 | items via another reference stringification (i.e. using the same | |
1061 | reference that was used for the key originally to record the value into | |
1062 | the hash table), it will work because both references stringify to the | |
1063 | same string. | |
1064 | ||
6fe6778b PN |
1065 | It won't work across a sequence of C<store> and C<retrieve> operations, |
1066 | however, because the addresses in the retrieved objects, which are | |
1067 | part of the stringified references, will probably differ from the | |
1068 | original addresses. The topology of your structure is preserved, | |
1069 | but not hidden semantics like those. | |
7a6a85bf RG |
1070 | |
1071 | On platforms where it matters, be sure to call C<binmode()> on the | |
1072 | descriptors that you pass to Storable functions. | |
1073 | ||
1074 | Storing data canonically that contains large hashes can be | |
1075 | significantly slower than storing the same data normally, as | |
c261f00e | 1076 | temporary arrays to hold the keys for each hash have to be allocated, |
7a6a85bf RG |
1077 | populated, sorted and freed. Some tests have shown a halving of the |
1078 | speed of storing -- the exact penalty will depend on the complexity of | |
1079 | your data. There is no slowdown on retrieval. | |
1080 | ||
1081 | =head1 BUGS | |
1082 | ||
eda690a0 | 1083 | You can't store GLOB, FORMLINE, REGEXP, etc.... If you can define semantics |
197b90bc SR |
1084 | for those operations, feel free to enhance Storable so that it can |
1085 | deal with them. | |
7a6a85bf RG |
1086 | |
1087 | The store functions will C<croak> if they run into such references | |
1088 | unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that | |
1089 | case, the fatal message is turned in a warning and some | |
1090 | meaningless string is stored instead. | |
1091 | ||
1092 | Setting C<$Storable::canonical> may not yield frozen strings that | |
1093 | compare equal due to possible stringification of numbers. When the | |
f062ea6c | 1094 | string version of a scalar exists, it is the form stored; therefore, |
7a6a85bf RG |
1095 | if you happen to use your numbers as strings between two freezing |
1096 | operations on the same data structures, you will get different | |
1097 | results. | |
1098 | ||
dd19458b JH |
1099 | When storing doubles in network order, their value is stored as text. |
1100 | However, you should also not expect non-numeric floating-point values | |
1101 | such as infinity and "not a number" to pass successfully through a | |
1102 | nstore()/retrieve() pair. | |
1103 | ||
1104 | As Storable neither knows nor cares about character sets (although it | |
1105 | does know that characters may be more than eight bits wide), any difference | |
1106 | in the interpretation of character codes between a host and a target | |
1107 | system is your problem. In particular, if host and target use different | |
1108 | code points to represent the characters used in the text representation | |
1109 | of floating-point numbers, you will not be able be able to exchange | |
1110 | floating-point data, even with nstore(). | |
1111 | ||
c261f00e NC |
1112 | C<Storable::drop_utf8> is a blunt tool. There is no facility either to |
1113 | return B<all> strings as utf8 sequences, or to attempt to convert utf8 | |
1114 | data back to 8 bit and C<croak()> if the conversion fails. | |
1115 | ||
ee0f7aac NC |
1116 | Prior to Storable 2.01, no distinction was made between signed and |
1117 | unsigned integers on storing. By default Storable prefers to store a | |
1118 | scalars string representation (if it has one) so this would only cause | |
3c4b39be | 1119 | problems when storing large unsigned integers that had never been converted |
ee0f7aac NC |
1120 | to string or floating point. In other words values that had been generated |
1121 | by integer operations such as logic ops and then not used in any string or | |
1122 | arithmetic context before storing. | |
1123 | ||
1124 | =head2 64 bit data in perl 5.6.0 and 5.6.1 | |
1125 | ||
1126 | This section only applies to you if you have existing data written out | |
1127 | by Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux which | |
1128 | has been configured with 64 bit integer support (not the default) | |
1129 | If you got a precompiled perl, rather than running Configure to build | |
1130 | your own perl from source, then it almost certainly does not affect you, | |
1131 | and you can stop reading now (unless you're curious). If you're using perl | |
1132 | on Windows it does not affect you. | |
1133 | ||
1134 | Storable writes a file header which contains the sizes of various C | |
1135 | language types for the C compiler that built Storable (when not writing in | |
1136 | network order), and will refuse to load files written by a Storable not | |
1137 | on the same (or compatible) architecture. This check and a check on | |
1138 | machine byteorder is needed because the size of various fields in the file | |
1139 | are given by the sizes of the C language types, and so files written on | |
1140 | different architectures are incompatible. This is done for increased speed. | |
1141 | (When writing in network order, all fields are written out as standard | |
1142 | lengths, which allows full interworking, but takes longer to read and write) | |
1143 | ||
1144 | Perl 5.6.x introduced the ability to optional configure the perl interpreter | |
1145 | to use C's C<long long> type to allow scalars to store 64 bit integers on 32 | |
1146 | bit systems. However, due to the way the Perl configuration system | |
1147 | generated the C configuration files on non-Windows platforms, and the way | |
1148 | Storable generates its header, nothing in the Storable file header reflected | |
1149 | whether the perl writing was using 32 or 64 bit integers, despite the fact | |
1150 | that Storable was storing some data differently in the file. Hence Storable | |
1151 | running on perl with 64 bit integers will read the header from a file | |
1152 | written by a 32 bit perl, not realise that the data is actually in a subtly | |
1153 | incompatible format, and then go horribly wrong (possibly crashing) if it | |
1154 | encountered a stored integer. This is a design failure. | |
1155 | ||
1156 | Storable has now been changed to write out and read in a file header with | |
1157 | information about the size of integers. It's impossible to detect whether | |
1158 | an old file being read in was written with 32 or 64 bit integers (they have | |
1159 | the same header) so it's impossible to automatically switch to a correct | |
1160 | backwards compatibility mode. Hence this Storable defaults to the new, | |
1161 | correct behaviour. | |
1162 | ||
1163 | What this means is that if you have data written by Storable 1.x running | |
1164 | on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix or Linux | |
1165 | then by default this Storable will refuse to read it, giving the error | |
efaa61e2 | 1166 | I<Byte order is not compatible>. If you have such data then you |
ee0f7aac NC |
1167 | should set C<$Storable::interwork_56_64bit> to a true value to make this |
1168 | Storable read and write files with the old header. You should also | |
1169 | migrate your data, or any older perl you are communicating with, to this | |
1170 | current version of Storable. | |
1171 | ||
1172 | If you don't have data written with specific configuration of perl described | |
1173 | above, then you do not and should not do anything. Don't set the flag - | |
1174 | not only will Storable on an identically configured perl refuse to load them, | |
1175 | but Storable a differently configured perl will load them believing them | |
1176 | to be correct for it, and then may well fail or crash part way through | |
1177 | reading them. | |
1178 | ||
7a6a85bf RG |
1179 | =head1 CREDITS |
1180 | ||
1181 | Thank you to (in chronological order): | |
1182 | ||
1183 | Jarkko Hietaniemi <jhi@iki.fi> | |
1184 | Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de> | |
51f77169 | 1185 | Benjamin A. Holzman <bholzman@earthlink.net> |
7a6a85bf RG |
1186 | Andrew Ford <A.Ford@ford-mason.co.uk> |
1187 | Gisle Aas <gisle@aas.no> | |
1188 | Jeff Gresham <gresham_jeffrey@jpmorgan.com> | |
1189 | Murray Nesbitt <murray@activestate.com> | |
1190 | Marc Lehmann <pcg@opengroup.org> | |
9e21b3d0 JH |
1191 | Justin Banks <justinb@wamnet.com> |
1192 | Jarkko Hietaniemi <jhi@iki.fi> (AGAIN, as perl 5.7.0 Pumpkin!) | |
dd19458b JH |
1193 | Salvador Ortiz Garcia <sog@msg.com.mx> |
1194 | Dominic Dunlop <domo@computer.org> | |
1195 | Erik Haugan <erik@solbors.no> | |
f17010da RU |
1196 | Benjamin A. Holzman <ben.holzman@grantstreet.com> |
1197 | Reini Urban <rurban@cpanel.net> | |
7a6a85bf RG |
1198 | |
1199 | for their bug reports, suggestions and contributions. | |
1200 | ||
1201 | Benjamin Holzman contributed the tied variable support, Andrew Ford | |
1202 | contributed the canonical order for hashes, and Gisle Aas fixed | |
f062ea6c | 1203 | a few misunderstandings of mine regarding the perl internals, |
7a6a85bf RG |
1204 | and optimized the emission of "tags" in the output streams by |
1205 | simply counting the objects instead of tagging them (leading to | |
1206 | a binary incompatibility for the Storable image starting at version | |
f062ea6c | 1207 | 0.6--older images are, of course, still properly understood). |
7a6a85bf | 1208 | Murray Nesbitt made Storable thread-safe. Marc Lehmann added overloading |
51f77169 AMS |
1209 | and references to tied items support. Benjamin Holzman added a performance |
1210 | improvement for overloaded classes; thanks to Grant Street Group for footing | |
1211 | the bill. | |
7a6a85bf | 1212 | |
7a6a85bf RG |
1213 | =head1 AUTHOR |
1214 | ||
0ba8809e | 1215 | Storable was written by Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>> |
775ecd75 | 1216 | Maintenance is now done by the perl5-porters F<E<lt>perl5-porters@perl.orgE<gt>> |
0ba8809e NC |
1217 | |
1218 | Please e-mail us with problems, bug fixes, comments and complaints, | |
d119459b | 1219 | although if you have compliments you should send them to Raphael. |
0ba8809e NC |
1220 | Please don't e-mail Raphael with problems, as he no longer works on |
1221 | Storable, and your message will be delayed while he forwards it to us. | |
7a6a85bf RG |
1222 | |
1223 | =head1 SEE ALSO | |
1224 | ||
c261f00e | 1225 | L<Clone>. |
7a6a85bf RG |
1226 | |
1227 | =cut |