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

File Contents

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