ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/XS.pm
Revision: 1.1
Committed: Fri Oct 25 23:09:45 2013 UTC (10 years, 6 months ago) by root
Branch: MAIN
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     CBOR::XS - Concise Binary Object Representation (CBOR, RFC7049)
4    
5     =encoding utf-8
6    
7     =head1 SYNOPSIS
8    
9     use CBOR::XS;
10    
11     $binary_cbor_data = encode_cbor $perl_value;
12     $perl_value = decode_cbor $binary_cbor_data;
13    
14     # OO-interface
15    
16     $coder = CBOR::XS->new;
17     #TODO
18    
19     =head1 DESCRIPTION
20    
21     WARNING! THIS IS A PRE-ALPHA RELEASE! IT WILL CRASH, CORRUPT YOUR DATA AND
22     EAT YOUR CHILDREN!
23    
24     This module converts Perl data structures to CBOR and vice versa. Its
25     primary goal is to be I<correct> and its secondary goal is to be
26     I<fast>. To reach the latter goal it was written in C.
27    
28     See MAPPING, below, on how CBOR::XS maps perl values to CBOR values and
29     vice versa.
30    
31     =cut
32    
33     package CBOR::XS;
34    
35     use common::sense;
36    
37     our $VERSION = 0.01;
38     our @ISA = qw(Exporter);
39    
40     our @EXPORT = qw(encode_cbor decode_cbor);
41    
42     use Exporter;
43     use XSLoader;
44    
45     =head1 FUNCTIONAL INTERFACE
46    
47     The following convenience methods are provided by this module. They are
48     exported by default:
49    
50     =over 4
51    
52     =item $cbor_data = encode_cbor $perl_scalar
53    
54     Converts the given Perl data structure to CBOR representation. Croaks on
55     error.
56    
57     =item $perl_scalar = decode_cbor $cbor_data
58    
59     The opposite of C<encode_cbor>: expects a valid CBOR string to parse,
60     returning the resulting perl scalar. Croaks on error.
61    
62     =back
63    
64    
65     =head1 OBJECT-ORIENTED INTERFACE
66    
67     The object oriented interface lets you configure your own encoding or
68     decoding style, within the limits of supported formats.
69    
70     =over 4
71    
72     =item $cbor = new CBOR::XS
73    
74     Creates a new CBOR::XS object that can be used to de/encode CBOR
75     strings. All boolean flags described below are by default I<disabled>.
76    
77     The mutators for flags all return the CBOR object again and thus calls can
78     be chained:
79    
80     #TODO
81     my $cbor = CBOR::XS->new->encode ({a => [1,2]});
82    
83     =item $cbor = $cbor->max_depth ([$maximum_nesting_depth])
84    
85     =item $max_depth = $cbor->get_max_depth
86    
87     Sets the maximum nesting level (default C<512>) accepted while encoding
88     or decoding. If a higher nesting level is detected in CBOR data or a Perl
89     data structure, then the encoder and decoder will stop and croak at that
90     point.
91    
92     Nesting level is defined by number of hash- or arrayrefs that the encoder
93     needs to traverse to reach a given point or the number of C<{> or C<[>
94     characters without their matching closing parenthesis crossed to reach a
95     given character in a string.
96    
97     Setting the maximum depth to one disallows any nesting, so that ensures
98     that the object is only a single hash/object or array.
99    
100     If no argument is given, the highest possible setting will be used, which
101     is rarely useful.
102    
103     Note that nesting is implemented by recursion in C. The default value has
104     been chosen to be as large as typical operating systems allow without
105     crashing.
106    
107     See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
108    
109     =item $cbor = $cbor->max_size ([$maximum_string_size])
110    
111     =item $max_size = $cbor->get_max_size
112    
113     Set the maximum length a CBOR string may have (in bytes) where decoding
114     is being attempted. The default is C<0>, meaning no limit. When C<decode>
115     is called on a string that is longer then this many bytes, it will not
116     attempt to decode the string but throw an exception. This setting has no
117     effect on C<encode> (yet).
118    
119     If no argument is given, the limit check will be deactivated (same as when
120     C<0> is specified).
121    
122     See SECURITY CONSIDERATIONS, below, for more info on why this is useful.
123    
124     =item $cbor_data = $cbor->encode ($perl_scalar)
125    
126     Converts the given Perl data structure (a scalar value) to its CBOR
127     representation.
128    
129     =item $perl_scalar = $cbor->decode ($cbor_data)
130    
131     The opposite of C<encode>: expects CBOR data and tries to parse it,
132     returning the resulting simple scalar or reference. Croaks on error.
133    
134     =item ($perl_scalar, $octets) = $cbor->decode_prefix ($cbor_data)
135    
136     This works like the C<decode> method, but instead of raising an exception
137     when there is trailing garbage after the CBOR string, it will silently
138     stop parsing there and return the number of characters consumed so far.
139    
140     This is useful if your CBOR texts are not delimited by an outer protocol
141     and you need to know where the first CBOR string ends amd the next one
142     starts.
143    
144     CBOR::XS->new->decode_prefix ("......")
145     => ("...", 3)
146    
147     =back
148    
149    
150     =head1 MAPPING
151    
152     This section describes how CBOR::XS maps Perl values to CBOR values and
153     vice versa. These mappings are designed to "do the right thing" in most
154     circumstances automatically, preserving round-tripping characteristics
155     (what you put in comes out as something equivalent).
156    
157     For the more enlightened: note that in the following descriptions,
158     lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl>
159     refers to the abstract Perl language itself.
160    
161    
162     =head2 CBOR -> PERL
163    
164     =over 4
165    
166     =item True, False
167    
168     These CBOR values become C<CBOR::XS::true> and C<CBOR::XS::false>,
169     respectively. They are overloaded to act almost exactly like the numbers
170     C<1> and C<0>. You can check whether a scalar is a CBOR boolean by using
171     the C<CBOR::XS::is_bool> function.
172    
173     =item null
174    
175     A CBOR Null value becomes C<undef> in Perl.
176    
177     =back
178    
179    
180     =head2 PERL -> CBOR
181    
182     The mapping from Perl to CBOR is slightly more difficult, as Perl is a
183     truly typeless language, so we can only guess which CBOR type is meant by
184     a Perl value.
185    
186     =over 4
187    
188     =item hash references
189    
190     Perl hash references become CBOR maps. As there is no inherent ordering
191     in hash keys (or CBOR maps), they will usually be encoded in a
192     pseudo-random order.
193    
194     =item array references
195    
196     Perl array references become CBOR arrays.
197    
198     =item other references
199    
200     Other unblessed references are generally not allowed and will cause an
201     exception to be thrown, except for references to the integers C<0> and
202     C<1>, which get turned into C<False> and C<True> in CBOR.
203    
204     =item CBOR::XS::true, CBOR::XS::false
205    
206     These special values become CBOR True and CBOR False values,
207     respectively. You can also use C<\1> and C<\0> directly if you want.
208    
209     =item blessed objects
210    
211     Blessed objects are not directly representable in CBOR. TODO
212     See the
213     C<allow_blessed> and C<convert_blessed> methods on various options on
214     how to deal with this: basically, you can choose between throwing an
215     exception, encoding the reference as if it weren't blessed, or provide
216     your own serialiser method.
217    
218     =item simple scalars
219    
220     TODO
221     Simple Perl scalars (any scalar that is not a reference) are the most
222     difficult objects to encode: CBOR::XS will encode undefined scalars as
223     CBOR C<Null> values, scalars that have last been used in a string context
224     before encoding as CBOR strings, and anything else as number value:
225    
226     # dump as number
227     encode_cbor [2] # yields [2]
228     encode_cbor [-3.0e17] # yields [-3e+17]
229     my $value = 5; encode_cbor [$value] # yields [5]
230    
231     # used as string, so dump as string
232     print $value;
233     encode_cbor [$value] # yields ["5"]
234    
235     # undef becomes null
236     encode_cbor [undef] # yields [null]
237    
238     You can force the type to be a CBOR string by stringifying it:
239    
240     my $x = 3.1; # some variable containing a number
241     "$x"; # stringified
242     $x .= ""; # another, more awkward way to stringify
243     print $x; # perl does it for you, too, quite often
244    
245     You can force the type to be a CBOR number by numifying it:
246    
247     my $x = "3"; # some variable containing a string
248     $x += 0; # numify it, ensuring it will be dumped as a number
249     $x *= 1; # same thing, the choice is yours.
250    
251     You can not currently force the type in other, less obscure, ways. Tell me
252     if you need this capability (but don't forget to explain why it's needed
253     :).
254    
255     Note that numerical precision has the same meaning as under Perl (so
256     binary to decimal conversion follows the same rules as in Perl, which
257     can differ to other languages). Also, your perl interpreter might expose
258     extensions to the floating point numbers of your platform, such as
259     infinities or NaN's - these cannot be represented in CBOR, and it is an
260     error to pass those in.
261    
262     =back
263    
264    
265     =head2 CBOR and JSON
266    
267     TODO
268    
269    
270     =head1 SECURITY CONSIDERATIONS
271    
272     When you are using CBOR in a protocol, talking to untrusted potentially
273     hostile creatures requires relatively few measures.
274    
275     First of all, your CBOR decoder should be secure, that is, should not have
276     any buffer overflows. Obviously, this module should ensure that and I am
277     trying hard on making that true, but you never know.
278    
279     Second, you need to avoid resource-starving attacks. That means you should
280     limit the size of CBOR data you accept, or make sure then when your
281     resources run out, that's just fine (e.g. by using a separate process that
282     can crash safely). The size of a CBOR string in octets is usually a good
283     indication of the size of the resources required to decode it into a Perl
284     structure. While CBOR::XS can check the size of the CBOR text, it might be
285     too late when you already have it in memory, so you might want to check
286     the size before you accept the string.
287    
288     Third, CBOR::XS recurses using the C stack when decoding objects and
289     arrays. The C stack is a limited resource: for instance, on my amd64
290     machine with 8MB of stack size I can decode around 180k nested arrays but
291     only 14k nested CBOR objects (due to perl itself recursing deeply on croak
292     to free the temporary). If that is exceeded, the program crashes. To be
293     conservative, the default nesting limit is set to 512. If your process
294     has a smaller stack, you should adjust this setting accordingly with the
295     C<max_depth> method.
296    
297     Something else could bomb you, too, that I forgot to think of. In that
298     case, you get to keep the pieces. I am always open for hints, though...
299    
300     Also keep in mind that CBOR::XS might leak contents of your Perl data
301     structures in its error messages, so when you serialise sensitive
302     information you might want to make sure that exceptions thrown by CBOR::XS
303     will not end up in front of untrusted eyes.
304    
305     =head1 CBOR IMPLEMENTATION NOTES
306    
307     This section contains some random implementation notes. They do not
308     describe guaranteed behaviour, but merely behaviour as-is implemented
309     right now.
310    
311     64 bit integers are only properly decoded when Perl was built with 64 bit
312     support.
313    
314     Strings and arrays are encoded with a definite length. Hashes as well,
315     unless they are tied (or otherwise magical).
316    
317     Only the double data type is supported for NV data types - when Perl uses
318     long double to represent floating point values, they might not be encoded
319     properly. Half precision types are accepted, but not encoded.
320    
321     Strict mode and canonical mode are not implemented.
322    
323    
324     =head1 THREADS
325    
326     This module is I<not> guaranteed to be thread safe and there are no
327     plans to change this until Perl gets thread support (as opposed to the
328     horribly slow so-called "threads" which are simply slow and bloated
329     process simulations - use fork, it's I<much> faster, cheaper, better).
330    
331     (It might actually work, but you have been warned).
332    
333    
334     =head1 BUGS
335    
336     While the goal of this module is to be correct, that unfortunately does
337     not mean it's bug-free, only that I think its design is bug-free. If you
338     keep reporting bugs they will be fixed swiftly, though.
339    
340     Please refrain from using rt.cpan.org or any other bug reporting
341     service. I put the contact address into my modules for a reason.
342    
343     =cut
344    
345     our $true = do { bless \(my $dummy = 1), "CBOR::XS::Boolean" };
346     our $false = do { bless \(my $dummy = 0), "CBOR::XS::Boolean" };
347    
348     sub true() { $true }
349     sub false() { $false }
350    
351     sub is_bool($) {
352     UNIVERSAL::isa $_[0], "CBOR::XS::Boolean"
353     # or UNIVERSAL::isa $_[0], "CBOR::Literal"
354     }
355    
356     XSLoader::load "CBOR::XS", $VERSION;
357    
358     package CBOR::XS::Boolean;
359    
360     use overload
361     "0+" => sub { ${$_[0]} },
362     "++" => sub { $_[0] = ${$_[0]} + 1 },
363     "--" => sub { $_[0] = ${$_[0]} - 1 },
364     fallback => 1;
365    
366     1;
367    
368     =head1 SEE ALSO
369    
370     The L<JSON> and L<JSON::XS> modules that do similar, but human-readable,
371     serialisation.
372    
373     =head1 AUTHOR
374    
375     Marc Lehmann <schmorp@schmorp.de>
376     http://home.schmorp.de/
377    
378     =cut
379