ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/README
Revision: 1.8
Committed: Tue Oct 29 22:04:52 2013 UTC (10 years, 6 months ago) by root
Branch: MAIN
CVS Tags: rel-0_07, rel-0_08
Changes since 1.7: +8 -0 lines
Log Message:
0.07

File Contents

# User Rev Content
1 root 1.2 NAME
2     CBOR::XS - Concise Binary Object Representation (CBOR, RFC7049)
3    
4     SYNOPSIS
5     use CBOR::XS;
6    
7     $binary_cbor_data = encode_cbor $perl_value;
8     $perl_value = decode_cbor $binary_cbor_data;
9    
10     # OO-interface
11    
12     $coder = CBOR::XS->new;
13 root 1.5 $binary_cbor_data = $coder->encode ($perl_value);
14     $perl_value = $coder->decode ($binary_cbor_data);
15    
16     # prefix decoding
17    
18     my $many_cbor_strings = ...;
19     while (length $many_cbor_strings) {
20     my ($data, $length) = $cbor->decode_prefix ($many_cbor_strings);
21     # data was decoded
22     substr $many_cbor_strings, 0, $length, ""; # remove decoded cbor string
23     }
24 root 1.2
25     DESCRIPTION
26 root 1.6 WARNING! This module is very new, and not very well tested (that's up to
27     you to do). Furthermore, details of the implementation might change
28     freely before version 1.0. And lastly, the object serialisation protocol
29     depends on a pending IANA assignment, and until that assignment is
30     official, this implementation is not interoperable with other
31     implementations (even future versions of this module) until the
32     assignment is done.
33    
34     You are still invited to try out CBOR, and this module.
35 root 1.2
36 root 1.4 This module converts Perl data structures to the Concise Binary Object
37     Representation (CBOR) and vice versa. CBOR is a fast binary
38     serialisation format that aims to use a superset of the JSON data model,
39     i.e. when you can represent something in JSON, you should be able to
40     represent it in CBOR.
41    
42 root 1.6 In short, CBOR is a faster and very compact binary alternative to JSON,
43     with the added ability of supporting serialisation of Perl objects.
44 root 1.7 (JSON often compresses better than CBOR though, so if you plan to
45     compress the data later you might want to compare both formats first).
46 root 1.4
47 root 1.8 To give you a general idea about speed, with texts in the megabyte
48     range, "CBOR::XS" usually encodes roughly twice as fast as Storable or
49     JSON::XS and decodes about 15%-30% faster than those. The shorter the
50     data, the worse Storable performs in comparison.
51    
52     As for compactness, "CBOR::XS" encoded data structures are usually about
53     20% smaller than the same data encoded as (compact) JSON or Storable.
54    
55 root 1.4 The primary goal of this module is to be *correct* and the secondary
56     goal is to be *fast*. To reach the latter goal it was written in C.
57 root 1.2
58     See MAPPING, below, on how CBOR::XS maps perl values to CBOR values and
59     vice versa.
60    
61     FUNCTIONAL INTERFACE
62     The following convenience methods are provided by this module. They are
63     exported by default:
64    
65     $cbor_data = encode_cbor $perl_scalar
66     Converts the given Perl data structure to CBOR representation.
67     Croaks on error.
68    
69     $perl_scalar = decode_cbor $cbor_data
70     The opposite of "encode_cbor": expects a valid CBOR string to parse,
71     returning the resulting perl scalar. Croaks on error.
72    
73     OBJECT-ORIENTED INTERFACE
74     The object oriented interface lets you configure your own encoding or
75     decoding style, within the limits of supported formats.
76    
77     $cbor = new CBOR::XS
78     Creates a new CBOR::XS object that can be used to de/encode CBOR
79     strings. All boolean flags described below are by default
80     *disabled*.
81    
82     The mutators for flags all return the CBOR object again and thus
83     calls can be chained:
84    
85     #TODO my $cbor = CBOR::XS->new->encode ({a => [1,2]});
86    
87     $cbor = $cbor->max_depth ([$maximum_nesting_depth])
88     $max_depth = $cbor->get_max_depth
89     Sets the maximum nesting level (default 512) accepted while encoding
90     or decoding. If a higher nesting level is detected in CBOR data or a
91     Perl data structure, then the encoder and decoder will stop and
92     croak at that point.
93    
94     Nesting level is defined by number of hash- or arrayrefs that the
95     encoder needs to traverse to reach a given point or the number of
96     "{" or "[" characters without their matching closing parenthesis
97     crossed to reach a given character in a string.
98    
99     Setting the maximum depth to one disallows any nesting, so that
100     ensures that the object is only a single hash/object or array.
101    
102     If no argument is given, the highest possible setting will be used,
103     which is rarely useful.
104    
105     Note that nesting is implemented by recursion in C. The default
106     value has been chosen to be as large as typical operating systems
107     allow without crashing.
108    
109     See SECURITY CONSIDERATIONS, below, for more info on why this is
110     useful.
111    
112     $cbor = $cbor->max_size ([$maximum_string_size])
113     $max_size = $cbor->get_max_size
114     Set the maximum length a CBOR string may have (in bytes) where
115     decoding is being attempted. The default is 0, meaning no limit.
116     When "decode" is called on a string that is longer then this many
117     bytes, it will not attempt to decode the string but throw an
118     exception. This setting has no effect on "encode" (yet).
119    
120     If no argument is given, the limit check will be deactivated (same
121     as when 0 is specified).
122    
123     See SECURITY CONSIDERATIONS, below, for more info on why this is
124     useful.
125    
126     $cbor_data = $cbor->encode ($perl_scalar)
127     Converts the given Perl data structure (a scalar value) to its CBOR
128     representation.
129    
130     $perl_scalar = $cbor->decode ($cbor_data)
131     The opposite of "encode": expects CBOR data and tries to parse it,
132     returning the resulting simple scalar or reference. Croaks on error.
133    
134     ($perl_scalar, $octets) = $cbor->decode_prefix ($cbor_data)
135     This works like the "decode" method, but instead of raising an
136     exception when there is trailing garbage after the CBOR string, it
137     will silently stop parsing there and return the number of characters
138     consumed so far.
139    
140     This is useful if your CBOR texts are not delimited by an outer
141     protocol and you need to know where the first CBOR string ends amd
142     the next one starts.
143    
144     CBOR::XS->new->decode_prefix ("......")
145     => ("...", 3)
146    
147     MAPPING
148     This section describes how CBOR::XS maps Perl values to CBOR values and
149     vice versa. These mappings are designed to "do the right thing" in most
150     circumstances automatically, preserving round-tripping characteristics
151     (what you put in comes out as something equivalent).
152    
153     For the more enlightened: note that in the following descriptions,
154     lowercase *perl* refers to the Perl interpreter, while uppercase *Perl*
155     refers to the abstract Perl language itself.
156    
157     CBOR -> PERL
158 root 1.4 integers
159     CBOR integers become (numeric) perl scalars. On perls without 64 bit
160     support, 64 bit integers will be truncated or otherwise corrupted.
161    
162     byte strings
163     Byte strings will become octet strings in Perl (the byte values
164     0..255 will simply become characters of the same value in Perl).
165    
166     UTF-8 strings
167     UTF-8 strings in CBOR will be decoded, i.e. the UTF-8 octets will be
168     decoded into proper Unicode code points. At the moment, the validity
169     of the UTF-8 octets will not be validated - corrupt input will
170     result in corrupted Perl strings.
171    
172     arrays, maps
173     CBOR arrays and CBOR maps will be converted into references to a
174     Perl array or hash, respectively. The keys of the map will be
175     stringified during this process.
176    
177 root 1.5 null
178     CBOR null becomes "undef" in Perl.
179    
180     true, false, undefined
181     These CBOR values become "Types:Serialiser::true",
182     "Types:Serialiser::false" and "Types::Serialiser::error",
183 root 1.2 respectively. They are overloaded to act almost exactly like the
184 root 1.5 numbers 1 and 0 (for true and false) or to throw an exception on
185     access (for error). See the Types::Serialiser manpage for details.
186    
187     CBOR tag 256 (perl object)
188     The tag value 256 (TODO: pending iana registration) will be used to
189 root 1.7 deserialise a Perl object serialised with "FREEZE". See OBJECT
190     SERIALISATION, below, for details.
191 root 1.5
192     CBOR tag 55799 (magic header)
193     The tag 55799 is ignored (this tag implements the magic header).
194    
195     other CBOR tags
196     Tagged items consists of a numeric tag and another CBOR value. Tags
197     not handled internally are currently converted into a
198     CBOR::XS::Tagged object, which is simply a blessed array reference
199     consisting of the numeric tag value followed by the (decoded) CBOR
200     value.
201 root 1.2
202 root 1.5 In the future, support for user-supplied conversions might get
203     added.
204 root 1.4
205     anything else
206     Anything else (e.g. unsupported simple values) will raise a decoding
207     error.
208 root 1.2
209     PERL -> CBOR
210     The mapping from Perl to CBOR is slightly more difficult, as Perl is a
211     truly typeless language, so we can only guess which CBOR type is meant
212     by a Perl value.
213    
214     hash references
215     Perl hash references become CBOR maps. As there is no inherent
216     ordering in hash keys (or CBOR maps), they will usually be encoded
217     in a pseudo-random order.
218    
219 root 1.4 Currently, tied hashes will use the indefinite-length format, while
220     normal hashes will use the fixed-length format.
221    
222 root 1.2 array references
223 root 1.4 Perl array references become fixed-length CBOR arrays.
224 root 1.2
225     other references
226     Other unblessed references are generally not allowed and will cause
227     an exception to be thrown, except for references to the integers 0
228 root 1.4 and 1, which get turned into false and true in CBOR.
229    
230     CBOR::XS::Tagged objects
231     Objects of this type must be arrays consisting of a single "[tag,
232     value]" pair. The (numerical) tag will be encoded as a CBOR tag, the
233 root 1.7 value will be encoded as appropriate for the value. You cna use
234     "CBOR::XS::tag" to create such objects.
235 root 1.2
236 root 1.5 Types::Serialiser::true, Types::Serialiser::false,
237     Types::Serialiser::error
238     These special values become CBOR true, CBOR false and CBOR undefined
239     values, respectively. You can also use "\1", "\0" and "\undef"
240     directly if you want.
241    
242     other blessed objects
243     Other blessed objects are serialised via "TO_CBOR" or "FREEZE". See
244     "OBJECT SERIALISATION", below, for details.
245 root 1.2
246     simple scalars
247     TODO Simple Perl scalars (any scalar that is not a reference) are
248     the most difficult objects to encode: CBOR::XS will encode undefined
249 root 1.4 scalars as CBOR null values, scalars that have last been used in a
250 root 1.2 string context before encoding as CBOR strings, and anything else as
251     number value:
252    
253     # dump as number
254     encode_cbor [2] # yields [2]
255     encode_cbor [-3.0e17] # yields [-3e+17]
256     my $value = 5; encode_cbor [$value] # yields [5]
257    
258     # used as string, so dump as string
259     print $value;
260     encode_cbor [$value] # yields ["5"]
261    
262     # undef becomes null
263     encode_cbor [undef] # yields [null]
264    
265     You can force the type to be a CBOR string by stringifying it:
266    
267     my $x = 3.1; # some variable containing a number
268     "$x"; # stringified
269     $x .= ""; # another, more awkward way to stringify
270     print $x; # perl does it for you, too, quite often
271    
272     You can force the type to be a CBOR number by numifying it:
273    
274     my $x = "3"; # some variable containing a string
275     $x += 0; # numify it, ensuring it will be dumped as a number
276     $x *= 1; # same thing, the choice is yours.
277    
278     You can not currently force the type in other, less obscure, ways.
279     Tell me if you need this capability (but don't forget to explain why
280     it's needed :).
281    
282 root 1.4 Perl values that seem to be integers generally use the shortest
283     possible representation. Floating-point values will use either the
284     IEEE single format if possible without loss of precision, otherwise
285     the IEEE double format will be used. Perls that use formats other
286     than IEEE double to represent numerical values are supported, but
287     might suffer loss of precision.
288 root 1.2
289 root 1.5 OBJECT SERIALISATION
290     This module knows two way to serialise a Perl object: The CBOR-specific
291     way, and the generic way.
292    
293     Whenever the encoder encounters a Perl object that it cnanot serialise
294     directly (most of them), it will first look up the "TO_CBOR" method on
295     it.
296    
297     If it has a "TO_CBOR" method, it will call it with the object as only
298     argument, and expects exactly one return value, which it will then
299     substitute and encode it in the place of the object.
300    
301     Otherwise, it will look up the "FREEZE" method. If it exists, it will
302     call it with the object as first argument, and the constant string
303     "CBOR" as the second argument, to distinguish it from other serialisers.
304    
305     The "FREEZE" method can return any number of values (i.e. zero or more).
306     These will be encoded as CBOR perl object, together with the classname.
307    
308     If an object supports neither "TO_CBOR" nor "FREEZE", encoding will fail
309     with an error.
310    
311     Objects encoded via "TO_CBOR" cannot be automatically decoded, but
312     objects encoded via "FREEZE" can be decoded using the following
313     protocol:
314    
315     When an encoded CBOR perl object is encountered by the decoder, it will
316     look up the "THAW" method, by using the stored classname, and will fail
317     if the method cannot be found.
318    
319     After the lookup it will call the "THAW" method with the stored
320     classname as first argument, the constant string "CBOR" as second
321     argument, and all values returned by "FREEZE" as remaining arguments.
322    
323     EXAMPLES
324     Here is an example "TO_CBOR" method:
325    
326     sub My::Object::TO_CBOR {
327     my ($obj) = @_;
328    
329     ["this is a serialised My::Object object", $obj->{id}]
330     }
331    
332     When a "My::Object" is encoded to CBOR, it will instead encode a simple
333     array with two members: a string, and the "object id". Decoding this
334     CBOR string will yield a normal perl array reference in place of the
335     object.
336    
337     A more useful and practical example would be a serialisation method for
338     the URI module. CBOR has a custom tag value for URIs, namely 32:
339    
340     sub URI::TO_CBOR {
341     my ($self) = @_;
342     my $uri = "$self"; # stringify uri
343     utf8::upgrade $uri; # make sure it will be encoded as UTF-8 string
344     CBOR::XS::tagged 32, "$_[0]"
345     }
346    
347     This will encode URIs as a UTF-8 string with tag 32, which indicates an
348     URI.
349    
350     Decoding such an URI will not (currently) give you an URI object, but
351     instead a CBOR::XS::Tagged object with tag number 32 and the string -
352     exactly what was returned by "TO_CBOR".
353    
354     To serialise an object so it can automatically be deserialised, you need
355     to use "FREEZE" and "THAW". To take the URI module as example, this
356     would be a possible implementation:
357    
358     sub URI::FREEZE {
359     my ($self, $serialiser) = @_;
360     "$self" # encode url string
361     }
362    
363     sub URI::THAW {
364     my ($class, $serialiser, $uri) = @_;
365    
366     $class->new ($uri)
367     }
368    
369     Unlike "TO_CBOR", multiple values can be returned by "FREEZE". For
370     example, a "FREEZE" method that returns "type", "id" and "variant"
371     values would cause an invocation of "THAW" with 5 arguments:
372    
373     sub My::Object::FREEZE {
374     my ($self, $serialiser) = @_;
375    
376     ($self->{type}, $self->{id}, $self->{variant})
377     }
378    
379     sub My::Object::THAW {
380     my ($class, $serialiser, $type, $id, $variant) = @_;
381    
382     $class-<new (type => $type, id => $id, variant => $variant)
383     }
384    
385     MAGIC HEADER
386 root 1.3 There is no way to distinguish CBOR from other formats programmatically.
387     To make it easier to distinguish CBOR from other formats, the CBOR
388     specification has a special "magic string" that can be prepended to any
389     CBOR string without changing it's meaning.
390    
391     This string is available as $CBOR::XS::MAGIC. This module does not
392     prepend this string tot he CBOR data it generates, but it will ignroe it
393     if present, so users can prepend this string as a "file type" indicator
394     as required.
395    
396 root 1.7 THE CBOR::XS::Tagged CLASS
397     CBOR has the concept of tagged values - any CBOR value can be tagged
398     with a numeric 64 bit number, which are centrally administered.
399    
400     "CBOR::XS" handles a few tags internally when en- or decoding. You can
401     also create tags yourself by encoding "CBOR::XS::Tagged" objects, and
402     the decoder will create "CBOR::XS::Tagged" objects itself when it hits
403     an unknown tag.
404    
405     These objects are simply blessed array references - the first member of
406     the array being the numerical tag, the second being the value.
407    
408     You can interact with "CBOR::XS::Tagged" objects in the following ways:
409    
410     $tagged = CBOR::XS::tag $tag, $value
411     This function(!) creates a new "CBOR::XS::Tagged" object using the
412     given $tag (0..2**64-1) to tag the given $value (which can be any
413     Perl value that can be encoded in CBOR, including serialisable Perl
414     objects and "CBOR::XS::Tagged" objects).
415    
416     $tagged->[0]
417     $tagged->[0] = $new_tag
418     $tag = $tagged->tag
419     $new_tag = $tagged->tag ($new_tag)
420     Access/mutate the tag.
421    
422     $tagged->[1]
423     $tagged->[1] = $new_value
424     $value = $tagged->value
425     $new_value = $tagged->value ($new_value)
426     Access/mutate the tagged value.
427    
428     EXAMPLES
429     Here are some examples of "CBOR::XS::Tagged" uses to tag objects.
430    
431     You can look up CBOR tag value and emanings in the IANA registry at
432     <http://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml>.
433    
434     Prepend a magic header ($CBOR::XS::MAGIC):
435    
436     my $cbor = encode_cbor CBOR::XS::tag 55799, $value;
437     # same as:
438     my $cbor = $CBOR::XS::MAGIC . encode_cbor $value;
439    
440     Serialise some URIs and a regex in an array:
441    
442     my $cbor = encode_cbor [
443     (CBOR::XS::tag 32, "http://www.nethype.de/"),
444     (CBOR::XS::tag 32, "http://software.schmorp.de/"),
445     (CBOR::XS::tag 35, "^[Pp][Ee][Rr][lL]\$"),
446     ];
447    
448     Wrap CBOR data in CBOR:
449    
450     my $cbor_cbor = encode_cbor
451     CBOR::XS::tag 24,
452     encode_cbor [1, 2, 3];
453    
454 root 1.5 CBOR and JSON
455 root 1.4 CBOR is supposed to implement a superset of the JSON data model, and is,
456     with some coercion, able to represent all JSON texts (something that
457     other "binary JSON" formats such as BSON generally do not support).
458    
459     CBOR implements some extra hints and support for JSON interoperability,
460     and the spec offers further guidance for conversion between CBOR and
461     JSON. None of this is currently implemented in CBOR, and the guidelines
462     in the spec do not result in correct round-tripping of data. If JSON
463     interoperability is improved in the future, then the goal will be to
464     ensure that decoded JSON data will round-trip encoding and decoding to
465     CBOR intact.
466 root 1.2
467     SECURITY CONSIDERATIONS
468     When you are using CBOR in a protocol, talking to untrusted potentially
469     hostile creatures requires relatively few measures.
470    
471     First of all, your CBOR decoder should be secure, that is, should not
472     have any buffer overflows. Obviously, this module should ensure that and
473     I am trying hard on making that true, but you never know.
474    
475     Second, you need to avoid resource-starving attacks. That means you
476     should limit the size of CBOR data you accept, or make sure then when
477     your resources run out, that's just fine (e.g. by using a separate
478     process that can crash safely). The size of a CBOR string in octets is
479     usually a good indication of the size of the resources required to
480     decode it into a Perl structure. While CBOR::XS can check the size of
481     the CBOR text, it might be too late when you already have it in memory,
482     so you might want to check the size before you accept the string.
483    
484     Third, CBOR::XS recurses using the C stack when decoding objects and
485     arrays. The C stack is a limited resource: for instance, on my amd64
486     machine with 8MB of stack size I can decode around 180k nested arrays
487     but only 14k nested CBOR objects (due to perl itself recursing deeply on
488     croak to free the temporary). If that is exceeded, the program crashes.
489     To be conservative, the default nesting limit is set to 512. If your
490     process has a smaller stack, you should adjust this setting accordingly
491     with the "max_depth" method.
492    
493     Something else could bomb you, too, that I forgot to think of. In that
494     case, you get to keep the pieces. I am always open for hints, though...
495    
496     Also keep in mind that CBOR::XS might leak contents of your Perl data
497     structures in its error messages, so when you serialise sensitive
498     information you might want to make sure that exceptions thrown by
499     CBOR::XS will not end up in front of untrusted eyes.
500    
501     CBOR IMPLEMENTATION NOTES
502     This section contains some random implementation notes. They do not
503     describe guaranteed behaviour, but merely behaviour as-is implemented
504     right now.
505    
506     64 bit integers are only properly decoded when Perl was built with 64
507     bit support.
508    
509     Strings and arrays are encoded with a definite length. Hashes as well,
510     unless they are tied (or otherwise magical).
511    
512     Only the double data type is supported for NV data types - when Perl
513     uses long double to represent floating point values, they might not be
514     encoded properly. Half precision types are accepted, but not encoded.
515    
516     Strict mode and canonical mode are not implemented.
517    
518     THREADS
519     This module is *not* guaranteed to be thread safe and there are no plans
520     to change this until Perl gets thread support (as opposed to the
521     horribly slow so-called "threads" which are simply slow and bloated
522     process simulations - use fork, it's *much* faster, cheaper, better).
523    
524     (It might actually work, but you have been warned).
525    
526     BUGS
527     While the goal of this module is to be correct, that unfortunately does
528     not mean it's bug-free, only that I think its design is bug-free. If you
529     keep reporting bugs they will be fixed swiftly, though.
530    
531     Please refrain from using rt.cpan.org or any other bug reporting
532     service. I put the contact address into my modules for a reason.
533    
534     SEE ALSO
535     The JSON and JSON::XS modules that do similar, but human-readable,
536     serialisation.
537    
538 root 1.5 The Types::Serialiser module provides the data model for true, false and
539     error values.
540    
541 root 1.2 AUTHOR
542     Marc Lehmann <schmorp@schmorp.de>
543     http://home.schmorp.de/
544