ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/README
Revision: 1.21
Committed: Tue Dec 8 08:29:44 2020 UTC (3 years, 5 months ago) by root
Branch: MAIN
CVS Tags: rel-1_83
Changes since 1.20: +18 -6 lines
Log Message:
1.83

File Contents

# Content
1 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 $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
25 DESCRIPTION
26 This module converts Perl data structures to the Concise Binary Object
27 Representation (CBOR) and vice versa. CBOR is a fast binary
28 serialisation format that aims to use an (almost) superset of the JSON
29 data model, i.e. when you can represent something useful in JSON, you
30 should be able to represent it in CBOR.
31
32 In short, CBOR is a faster and quite compact binary alternative to JSON,
33 with the added ability of supporting serialisation of Perl objects.
34 (JSON often compresses better than CBOR though, so if you plan to
35 compress the data later and speed is less important you might want to
36 compare both formats first).
37
38 The primary goal of this module is to be *correct* and the secondary
39 goal is to be *fast*. To reach the latter goal it was written in C.
40
41 To give you a general idea about speed, with texts in the megabyte
42 range, "CBOR::XS" usually encodes roughly twice as fast as Storable or
43 JSON::XS and decodes about 15%-30% faster than those. The shorter the
44 data, the worse Storable performs in comparison.
45
46 Regarding compactness, "CBOR::XS"-encoded data structures are usually
47 about 20% smaller than the same data encoded as (compact) JSON or
48 Storable.
49
50 In addition to the core CBOR data format, this module implements a
51 number of extensions, to support cyclic and shared data structures (see
52 "allow_sharing" and "allow_cycles"), string deduplication (see
53 "pack_strings") and scalar references (always enabled).
54
55 See MAPPING, below, on how CBOR::XS maps perl values to CBOR values and
56 vice versa.
57
58 FUNCTIONAL INTERFACE
59 The following convenience methods are provided by this module. They are
60 exported by default:
61
62 $cbor_data = encode_cbor $perl_scalar
63 Converts the given Perl data structure to CBOR representation.
64 Croaks on error.
65
66 $perl_scalar = decode_cbor $cbor_data
67 The opposite of "encode_cbor": expects a valid CBOR string to parse,
68 returning the resulting perl scalar. Croaks on error.
69
70 OBJECT-ORIENTED INTERFACE
71 The object oriented interface lets you configure your own encoding or
72 decoding style, within the limits of supported formats.
73
74 $cbor = new CBOR::XS
75 Creates a new CBOR::XS object that can be used to de/encode CBOR
76 strings. All boolean flags described below are by default
77 *disabled*.
78
79 The mutators for flags all return the CBOR object again and thus
80 calls can be chained:
81
82 my $cbor = CBOR::XS->new->encode ({a => [1,2]});
83
84 $cbor = new_safe CBOR::XS
85 Create a new, safe/secure CBOR::XS object. This is similar to "new",
86 but configures the coder object to be safe to use with untrusted
87 data. Currently, this is equivalent to:
88
89 my $cbor = CBOR::XS
90 ->new
91 ->forbid_objects
92 ->filter (\&CBOR::XS::safe_filter)
93 ->max_size (1e8);
94
95 But is more future proof (it is better to crash because of a change
96 than to be exploited in other ways).
97
98 $cbor = $cbor->max_depth ([$maximum_nesting_depth])
99 $max_depth = $cbor->get_max_depth
100 Sets the maximum nesting level (default 512) accepted while encoding
101 or decoding. If a higher nesting level is detected in CBOR data or a
102 Perl data structure, then the encoder and decoder will stop and
103 croak at that point.
104
105 Nesting level is defined by number of hash- or arrayrefs that the
106 encoder needs to traverse to reach a given point or the number of
107 "{" or "[" characters without their matching closing parenthesis
108 crossed to reach a given character in a string.
109
110 Setting the maximum depth to one disallows any nesting, so that
111 ensures that the object is only a single hash/object or array.
112
113 If no argument is given, the highest possible setting will be used,
114 which is rarely useful.
115
116 Note that nesting is implemented by recursion in C. The default
117 value has been chosen to be as large as typical operating systems
118 allow without crashing.
119
120 See "SECURITY CONSIDERATIONS", below, for more info on why this is
121 useful.
122
123 $cbor = $cbor->max_size ([$maximum_string_size])
124 $max_size = $cbor->get_max_size
125 Set the maximum length a CBOR string may have (in bytes) where
126 decoding is being attempted. The default is 0, meaning no limit.
127 When "decode" is called on a string that is longer then this many
128 bytes, it will not attempt to decode the string but throw an
129 exception. This setting has no effect on "encode" (yet).
130
131 If no argument is given, the limit check will be deactivated (same
132 as when 0 is specified).
133
134 See "SECURITY CONSIDERATIONS", below, for more info on why this is
135 useful.
136
137 $cbor = $cbor->allow_unknown ([$enable])
138 $enabled = $cbor->get_allow_unknown
139 If $enable is true (or missing), then "encode" will *not* throw an
140 exception when it encounters values it cannot represent in CBOR (for
141 example, filehandles) but instead will encode a CBOR "error" value.
142
143 If $enable is false (the default), then "encode" will throw an
144 exception when it encounters anything it cannot encode as CBOR.
145
146 This option does not affect "decode" in any way, and it is
147 recommended to leave it off unless you know your communications
148 partner.
149
150 $cbor = $cbor->allow_sharing ([$enable])
151 $enabled = $cbor->get_allow_sharing
152 If $enable is true (or missing), then "encode" will not
153 double-encode values that have been referenced before (e.g. when the
154 same object, such as an array, is referenced multiple times), but
155 instead will emit a reference to the earlier value.
156
157 This means that such values will only be encoded once, and will not
158 result in a deep cloning of the value on decode, in decoders
159 supporting the value sharing extension. This also makes it possible
160 to encode cyclic data structures (which need "allow_cycles" to be
161 enabled to be decoded by this module).
162
163 It is recommended to leave it off unless you know your communication
164 partner supports the value sharing extensions to CBOR
165 (<http://cbor.schmorp.de/value-sharing>), as without decoder
166 support, the resulting data structure might be unusable.
167
168 Detecting shared values incurs a runtime overhead when values are
169 encoded that have a reference counter large than one, and might
170 unnecessarily increase the encoded size, as potentially shared
171 values are encoded as shareable whether or not they are actually
172 shared.
173
174 At the moment, only targets of references can be shared (e.g.
175 scalars, arrays or hashes pointed to by a reference). Weirder
176 constructs, such as an array with multiple "copies" of the *same*
177 string, which are hard but not impossible to create in Perl, are not
178 supported (this is the same as with Storable).
179
180 If $enable is false (the default), then "encode" will encode shared
181 data structures repeatedly, unsharing them in the process. Cyclic
182 data structures cannot be encoded in this mode.
183
184 This option does not affect "decode" in any way - shared values and
185 references will always be decoded properly if present.
186
187 $cbor = $cbor->allow_cycles ([$enable])
188 $enabled = $cbor->get_allow_cycles
189 If $enable is true (or missing), then "decode" will happily decode
190 self-referential (cyclic) data structures. By default these will not
191 be decoded, as they need manual cleanup to avoid memory leaks, so
192 code that isn't prepared for this will not leak memory.
193
194 If $enable is false (the default), then "decode" will throw an error
195 when it encounters a self-referential/cyclic data structure.
196
197 FUTURE DIRECTION: the motivation behind this option is to avoid
198 *real* cycles - future versions of this module might chose to decode
199 cyclic data structures using weak references when this option is
200 off, instead of throwing an error.
201
202 This option does not affect "encode" in any way - shared values and
203 references will always be encoded properly if present.
204
205 $cbor = $cbor->forbid_objects ([$enable])
206 $enabled = $cbor->get_forbid_objects
207 Disables the use of the object serialiser protocol.
208
209 If $enable is true (or missing), then "encode" will will throw an
210 exception when it encounters perl objects that would be encoded
211 using the perl-object tag (26). When "decode" encounters such tags,
212 it will fall back to the general filter/tagged logic as if this were
213 an unknown tag (by default resulting in a "CBOR::XC::Tagged"
214 object).
215
216 If $enable is false (the default), then "encode" will use the
217 Types::Serialiser object serialisation protocol to serialise objects
218 into perl-object tags, and "decode" will do the same to decode such
219 tags.
220
221 See "SECURITY CONSIDERATIONS", below, for more info on why
222 forbidding this protocol can be useful.
223
224 $cbor = $cbor->pack_strings ([$enable])
225 $enabled = $cbor->get_pack_strings
226 If $enable is true (or missing), then "encode" will try not to
227 encode the same string twice, but will instead encode a reference to
228 the string instead. Depending on your data format, this can save a
229 lot of space, but also results in a very large runtime overhead
230 (expect encoding times to be 2-4 times as high as without).
231
232 It is recommended to leave it off unless you know your
233 communications partner supports the stringref extension to CBOR
234 (<http://cbor.schmorp.de/stringref>), as without decoder support,
235 the resulting data structure might not be usable.
236
237 If $enable is false (the default), then "encode" will encode strings
238 the standard CBOR way.
239
240 This option does not affect "decode" in any way - string references
241 will always be decoded properly if present.
242
243 $cbor = $cbor->text_keys ([$enable])
244 $enabled = $cbor->get_text_keys
245 If $enabled is true (or missing), then "encode" will encode all perl
246 hash keys as CBOR text strings/UTF-8 string, upgrading them as
247 needed.
248
249 If $enable is false (the default), then "encode" will encode hash
250 keys normally - upgraded perl strings (strings internally encoded as
251 UTF-8) as CBOR text strings, and downgraded perl strings as CBOR
252 byte strings.
253
254 This option does not affect "decode" in any way.
255
256 This option is useful for interoperability with CBOR decoders that
257 don't treat byte strings as a form of text. It is especially useful
258 as Perl gives very little control over hash keys.
259
260 Enabling this option can be slow, as all downgraded hash keys that
261 are encoded need to be scanned and converted to UTF-8.
262
263 $cbor = $cbor->text_strings ([$enable])
264 $enabled = $cbor->get_text_strings
265 This option works similar to "text_keys", above, but works on all
266 strings (including hash keys), so "text_keys" has no further effect
267 after enabling "text_strings".
268
269 If $enabled is true (or missing), then "encode" will encode all perl
270 strings as CBOR text strings/UTF-8 strings, upgrading them as
271 needed.
272
273 If $enable is false (the default), then "encode" will encode strings
274 normally (but see "text_keys") - upgraded perl strings (strings
275 internally encoded as UTF-8) as CBOR text strings, and downgraded
276 perl strings as CBOR byte strings.
277
278 This option does not affect "decode" in any way.
279
280 This option has similar advantages and disadvantages as "text_keys".
281 In addition, this option effectively removes the ability to
282 automatically encode byte strings, which might break some "FREEZE"
283 and "TO_CBOR" methods that rely on this.
284
285 A workaround is to use explicit type casts, which are unaffected by
286 this option.
287
288 $cbor = $cbor->validate_utf8 ([$enable])
289 $enabled = $cbor->get_validate_utf8
290 If $enable is true (or missing), then "decode" will validate that
291 elements (text strings) containing UTF-8 data in fact contain valid
292 UTF-8 data (instead of blindly accepting it). This validation
293 obviously takes extra time during decoding.
294
295 The concept of "valid UTF-8" used is perl's concept, which is a
296 superset of the official UTF-8.
297
298 If $enable is false (the default), then "decode" will blindly accept
299 UTF-8 data, marking them as valid UTF-8 in the resulting data
300 structure regardless of whether that's true or not.
301
302 Perl isn't too happy about corrupted UTF-8 in strings, but should
303 generally not crash or do similarly evil things. Extensions might be
304 not so forgiving, so it's recommended to turn on this setting if you
305 receive untrusted CBOR.
306
307 This option does not affect "encode" in any way - strings that are
308 supposedly valid UTF-8 will simply be dumped into the resulting CBOR
309 string without checking whether that is, in fact, true or not.
310
311 $cbor = $cbor->filter ([$cb->($tag, $value)])
312 $cb_or_undef = $cbor->get_filter
313 Sets or replaces the tagged value decoding filter (when $cb is
314 specified) or clears the filter (if no argument or "undef" is
315 provided).
316
317 The filter callback is called only during decoding, when a
318 non-enforced tagged value has been decoded (see "TAG HANDLING AND
319 EXTENSIONS" for a list of enforced tags). For specific tags, it's
320 often better to provide a default converter using the
321 %CBOR::XS::FILTER hash (see below).
322
323 The first argument is the numerical tag, the second is the (decoded)
324 value that has been tagged.
325
326 The filter function should return either exactly one value, which
327 will replace the tagged value in the decoded data structure, or no
328 values, which will result in default handling, which currently means
329 the decoder creates a "CBOR::XS::Tagged" object to hold the tag and
330 the value.
331
332 When the filter is cleared (the default state), the default filter
333 function, "CBOR::XS::default_filter", is used. This function simply
334 looks up the tag in the %CBOR::XS::FILTER hash. If an entry exists
335 it must be a code reference that is called with tag and value, and
336 is responsible for decoding the value. If no entry exists, it
337 returns no values. "CBOR::XS" provides a number of default filter
338 functions already, the the %CBOR::XS::FILTER hash can be freely
339 extended with more.
340
341 "CBOR::XS" additionally provides an alternative filter function that
342 is supposed to be safe to use with untrusted data (which the default
343 filter might not), called "CBOR::XS::safe_filter", which works the
344 same as the "default_filter" but uses the %CBOR::XS::SAFE_FILTER
345 variable instead. It is prepopulated with the tag decoding functions
346 that are deemed safe (basically the same as %CBOR::XS::FILTER
347 without all the bignum tags), and can be extended by user code as
348 wlel, although, obviously, one should be very careful about adding
349 decoding functions here, since the expectation is that they are safe
350 to use on untrusted data, after all.
351
352 Example: decode all tags not handled internally into
353 "CBOR::XS::Tagged" objects, with no other special handling (useful
354 when working with potentially "unsafe" CBOR data).
355
356 CBOR::XS->new->filter (sub { })->decode ($cbor_data);
357
358 Example: provide a global filter for tag 1347375694, converting the
359 value into some string form.
360
361 $CBOR::XS::FILTER{1347375694} = sub {
362 my ($tag, $value);
363
364 "tag 1347375694 value $value"
365 };
366
367 Example: provide your own filter function that looks up tags in your
368 own hash:
369
370 my %my_filter = (
371 998347484 => sub {
372 my ($tag, $value);
373
374 "tag 998347484 value $value"
375 };
376 );
377
378 my $coder = CBOR::XS->new->filter (sub {
379 &{ $my_filter{$_[0]} or return }
380 });
381
382 Example: use the safe filter function (see "SECURITY CONSIDERATIONS"
383 for more considerations on security).
384
385 CBOR::XS->new->filter (\&CBOR::XS::safe_filter)->decode ($cbor_data);
386
387 $cbor_data = $cbor->encode ($perl_scalar)
388 Converts the given Perl data structure (a scalar value) to its CBOR
389 representation.
390
391 $perl_scalar = $cbor->decode ($cbor_data)
392 The opposite of "encode": expects CBOR data and tries to parse it,
393 returning the resulting simple scalar or reference. Croaks on error.
394
395 ($perl_scalar, $octets) = $cbor->decode_prefix ($cbor_data)
396 This works like the "decode" method, but instead of raising an
397 exception when there is trailing garbage after the CBOR string, it
398 will silently stop parsing there and return the number of characters
399 consumed so far.
400
401 This is useful if your CBOR texts are not delimited by an outer
402 protocol and you need to know where the first CBOR string ends amd
403 the next one starts - CBOR strings are self-delimited, so it is
404 possible to concatenate CBOR strings without any delimiters or size
405 fields and recover their data.
406
407 CBOR::XS->new->decode_prefix ("......")
408 => ("...", 3)
409
410 INCREMENTAL PARSING
411 In some cases, there is the need for incremental parsing of JSON texts.
412 While this module always has to keep both CBOR text and resulting Perl
413 data structure in memory at one time, it does allow you to parse a CBOR
414 stream incrementally, using a similar to using "decode_prefix" to see if
415 a full CBOR object is available, but is much more efficient.
416
417 It basically works by parsing as much of a CBOR string as possible - if
418 the CBOR data is not complete yet, the pasrer will remember where it
419 was, to be able to restart when more data has been accumulated. Once
420 enough data is available to either decode a complete CBOR value or raise
421 an error, a real decode will be attempted.
422
423 A typical use case would be a network protocol that consists of sending
424 and receiving CBOR-encoded messages. The solution that works with CBOR
425 and about anything else is by prepending a length to every CBOR value,
426 so the receiver knows how many octets to read. More compact (and
427 slightly slower) would be to just send CBOR values back-to-back, as
428 "CBOR::XS" knows where a CBOR value ends, and doesn't need an explicit
429 length.
430
431 The following methods help with this:
432
433 @decoded = $cbor->incr_parse ($buffer)
434 This method attempts to decode exactly one CBOR value from the
435 beginning of the given $buffer. The value is removed from the
436 $buffer on success. When $buffer doesn't contain a complete value
437 yet, it returns nothing. Finally, when the $buffer doesn't start
438 with something that could ever be a valid CBOR value, it raises an
439 exception, just as "decode" would. In the latter case the decoder
440 state is undefined and must be reset before being able to parse
441 further.
442
443 This method modifies the $buffer in place. When no CBOR value can be
444 decoded, the decoder stores the current string offset. On the next
445 call, continues decoding at the place where it stopped before. For
446 this to make sense, the $buffer must begin with the same octets as
447 on previous unsuccessful calls.
448
449 You can call this method in scalar context, in which case it either
450 returns a decoded value or "undef". This makes it impossible to
451 distinguish between CBOR null values (which decode to "undef") and
452 an unsuccessful decode, which is often acceptable.
453
454 @decoded = $cbor->incr_parse_multiple ($buffer)
455 Same as "incr_parse", but attempts to decode as many CBOR values as
456 possible in one go, instead of at most one. Calls to "incr_parse"
457 and "incr_parse_multiple" can be interleaved.
458
459 $cbor->incr_reset
460 Resets the incremental decoder. This throws away any saved state, so
461 that subsequent calls to "incr_parse" or "incr_parse_multiple" start
462 to parse a new CBOR value from the beginning of the $buffer again.
463
464 This method can be called at any time, but it *must* be called if
465 you want to change your $buffer or there was a decoding error and
466 you want to reuse the $cbor object for future incremental parsings.
467
468 MAPPING
469 This section describes how CBOR::XS maps Perl values to CBOR values and
470 vice versa. These mappings are designed to "do the right thing" in most
471 circumstances automatically, preserving round-tripping characteristics
472 (what you put in comes out as something equivalent).
473
474 For the more enlightened: note that in the following descriptions,
475 lowercase *perl* refers to the Perl interpreter, while uppercase *Perl*
476 refers to the abstract Perl language itself.
477
478 CBOR -> PERL
479 integers
480 CBOR integers become (numeric) perl scalars. On perls without 64 bit
481 support, 64 bit integers will be truncated or otherwise corrupted.
482
483 byte strings
484 Byte strings will become octet strings in Perl (the Byte values
485 0..255 will simply become characters of the same value in Perl).
486
487 UTF-8 strings
488 UTF-8 strings in CBOR will be decoded, i.e. the UTF-8 octets will be
489 decoded into proper Unicode code points. At the moment, the validity
490 of the UTF-8 octets will not be validated - corrupt input will
491 result in corrupted Perl strings.
492
493 arrays, maps
494 CBOR arrays and CBOR maps will be converted into references to a
495 Perl array or hash, respectively. The keys of the map will be
496 stringified during this process.
497
498 null
499 CBOR null becomes "undef" in Perl.
500
501 true, false, undefined
502 These CBOR values become "Types:Serialiser::true",
503 "Types:Serialiser::false" and "Types::Serialiser::error",
504 respectively. They are overloaded to act almost exactly like the
505 numbers 1 and 0 (for true and false) or to throw an exception on
506 access (for error). See the Types::Serialiser manpage for details.
507
508 tagged values
509 Tagged items consists of a numeric tag and another CBOR value.
510
511 See "TAG HANDLING AND EXTENSIONS" and the description of "->filter"
512 for details on which tags are handled how.
513
514 anything else
515 Anything else (e.g. unsupported simple values) will raise a decoding
516 error.
517
518 PERL -> CBOR
519 The mapping from Perl to CBOR is slightly more difficult, as Perl is a
520 typeless language. That means this module can only guess which CBOR type
521 is meant by a perl value.
522
523 hash references
524 Perl hash references become CBOR maps. As there is no inherent
525 ordering in hash keys (or CBOR maps), they will usually be encoded
526 in a pseudo-random order. This order can be different each time a
527 hash is encoded.
528
529 Currently, tied hashes will use the indefinite-length format, while
530 normal hashes will use the fixed-length format.
531
532 array references
533 Perl array references become fixed-length CBOR arrays.
534
535 other references
536 Other unblessed references will be represented using the indirection
537 tag extension (tag value 22098,
538 <http://cbor.schmorp.de/indirection>). CBOR decoders are guaranteed
539 to be able to decode these values somehow, by either "doing the
540 right thing", decoding into a generic tagged object, simply ignoring
541 the tag, or something else.
542
543 CBOR::XS::Tagged objects
544 Objects of this type must be arrays consisting of a single "[tag,
545 value]" pair. The (numerical) tag will be encoded as a CBOR tag, the
546 value will be encoded as appropriate for the value. You must use
547 "CBOR::XS::tag" to create such objects.
548
549 Types::Serialiser::true, Types::Serialiser::false,
550 Types::Serialiser::error
551 These special values become CBOR true, CBOR false and CBOR undefined
552 values, respectively. You can also use "\1", "\0" and "\undef"
553 directly if you want.
554
555 other blessed objects
556 Other blessed objects are serialised via "TO_CBOR" or "FREEZE". See
557 "TAG HANDLING AND EXTENSIONS" for specific classes handled by this
558 module, and "OBJECT SERIALISATION" for generic object serialisation.
559
560 simple scalars
561 Simple Perl scalars (any scalar that is not a reference) are the
562 most difficult objects to encode: CBOR::XS will encode undefined
563 scalars as CBOR null values, scalars that have last been used in a
564 string context before encoding as CBOR strings, and anything else as
565 number value:
566
567 # dump as number
568 encode_cbor [2] # yields [2]
569 encode_cbor [-3.0e17] # yields [-3e+17]
570 my $value = 5; encode_cbor [$value] # yields [5]
571
572 # used as string, so dump as string (either byte or text)
573 print $value;
574 encode_cbor [$value] # yields ["5"]
575
576 # undef becomes null
577 encode_cbor [undef] # yields [null]
578
579 You can force the type to be a CBOR string by stringifying it:
580
581 my $x = 3.1; # some variable containing a number
582 "$x"; # stringified
583 $x .= ""; # another, more awkward way to stringify
584 print $x; # perl does it for you, too, quite often
585
586 You can force whether a string is encoded as byte or text string by
587 using "utf8::upgrade" and "utf8::downgrade" (if "text_strings" is
588 disabled).
589
590 utf8::upgrade $x; # encode $x as text string
591 utf8::downgrade $x; # encode $x as byte string
592
593 More options are available, see "TYPE CASTS", below, and the
594 "text_keys" and "text_strings" options.
595
596 Perl doesn't define what operations up- and downgrade strings, so if
597 the difference between byte and text is important, you should up- or
598 downgrade your string as late as possible before encoding. You can
599 also force the use of CBOR text strings by using "text_keys" or
600 "text_strings".
601
602 You can force the type to be a CBOR number by numifying it:
603
604 my $x = "3"; # some variable containing a string
605 $x += 0; # numify it, ensuring it will be dumped as a number
606 $x *= 1; # same thing, the choice is yours.
607
608 You can not currently force the type in other, less obscure, ways.
609 Tell me if you need this capability (but don't forget to explain why
610 it's needed :).
611
612 Perl values that seem to be integers generally use the shortest
613 possible representation. Floating-point values will use either the
614 IEEE single format if possible without loss of precision, otherwise
615 the IEEE double format will be used. Perls that use formats other
616 than IEEE double to represent numerical values are supported, but
617 might suffer loss of precision.
618
619 TYPE CASTS
620 EXPERIMENTAL: As an experimental extension, "CBOR::XS" allows you to
621 force specific cbor types to be used when encoding. That allows you to
622 encode types not normally accessible (e.g. half floats) as well as force
623 string types even when "text_strings" is in effect.
624
625 Type forcing is done by calling a special "cast" function which keeps a
626 copy of the value and returns a new value that can be handed over to any
627 CBOR encoder function.
628
629 The following casts are currently available (all of which are unary
630 operators):
631
632 CBOR::XS::as_int $value
633 Forces the value to be encoded as some form of (basic, not bignum)
634 integer type.
635
636 CBOR::XS::as_text $value
637 Forces the value to be encoded as (UTF-8) text values.
638
639 CBOR::XS::as_bytes $value
640 Forces the value to be encoded as a (binary) string value.
641
642 Example: encode a perl string as binary even though "text_strings"
643 is in effect.
644
645 CBOR::XS->new->text_strings->encode ([4, "text", CBOR::XS::bytes "bytevalue"]);
646
647 CBOR::XS::as_bool $value
648 Converts a Perl boolean (which can be any kind of scalar) into a
649 CBOR boolean. Strictly the same, but shorter to write, than:
650
651 $value ? Types::Serialiser::true : Types::Serialiser::false
652
653 CBOR::XS::as_float16 $value
654 Forces half-float (IEEE 754 binary16) encoding of the given value.
655
656 CBOR::XS::as_float32 $value
657 Forces single-float (IEEE 754 binary32) encoding of the given value.
658
659 CBOR::XS::as_float64 $value
660 Forces double-float (IEEE 754 binary64) encoding of the given value.
661
662 CBOR::XS::as_cbor $cbor_text
663 Not a type cast per-se, this type cast forces the argument to eb
664 encoded as-is. This can be used to embed pre-encoded CBOR data.
665
666 Note that no checking on the validity of the $cbor_text is done -
667 it's the callers responsibility to correctly encode values.
668
669 CBOR::XS::as_map [key => value...]
670 Treat the array reference as key value pairs and output a CBOR map.
671 This allows you to generate CBOR maps with arbitrary key types (or,
672 if you don't care about semantics, duplicate keys or prairs in a
673 custom order), which is otherwise hard to do with Perl.
674
675 The single argument must be an array reference with an even number
676 of elements.
677
678 Example: encode a CBOR map with a string and an integer as keys.
679
680 encode_cbor CBOR::XS::as_map [string => "value", 5 => "value"]
681
682 OBJECT SERIALISATION
683 This module implements both a CBOR-specific and the generic
684 Types::Serialier object serialisation protocol. The following
685 subsections explain both methods.
686
687 ENCODING
688 This module knows two way to serialise a Perl object: The CBOR-specific
689 way, and the generic way.
690
691 Whenever the encoder encounters a Perl object that it cannot serialise
692 directly (most of them), it will first look up the "TO_CBOR" method on
693 it.
694
695 If it has a "TO_CBOR" method, it will call it with the object as only
696 argument, and expects exactly one return value, which it will then
697 substitute and encode it in the place of the object.
698
699 Otherwise, it will look up the "FREEZE" method. If it exists, it will
700 call it with the object as first argument, and the constant string
701 "CBOR" as the second argument, to distinguish it from other serialisers.
702
703 The "FREEZE" method can return any number of values (i.e. zero or more).
704 These will be encoded as CBOR perl object, together with the classname.
705
706 These methods *MUST NOT* change the data structure that is being
707 serialised. Failure to comply to this can result in memory corruption -
708 and worse.
709
710 If an object supports neither "TO_CBOR" nor "FREEZE", encoding will fail
711 with an error.
712
713 DECODING
714 Objects encoded via "TO_CBOR" cannot (normally) be automatically
715 decoded, but objects encoded via "FREEZE" can be decoded using the
716 following protocol:
717
718 When an encoded CBOR perl object is encountered by the decoder, it will
719 look up the "THAW" method, by using the stored classname, and will fail
720 if the method cannot be found.
721
722 After the lookup it will call the "THAW" method with the stored
723 classname as first argument, the constant string "CBOR" as second
724 argument, and all values returned by "FREEZE" as remaining arguments.
725
726 EXAMPLES
727 Here is an example "TO_CBOR" method:
728
729 sub My::Object::TO_CBOR {
730 my ($obj) = @_;
731
732 ["this is a serialised My::Object object", $obj->{id}]
733 }
734
735 When a "My::Object" is encoded to CBOR, it will instead encode a simple
736 array with two members: a string, and the "object id". Decoding this
737 CBOR string will yield a normal perl array reference in place of the
738 object.
739
740 A more useful and practical example would be a serialisation method for
741 the URI module. CBOR has a custom tag value for URIs, namely 32:
742
743 sub URI::TO_CBOR {
744 my ($self) = @_;
745 my $uri = "$self"; # stringify uri
746 utf8::upgrade $uri; # make sure it will be encoded as UTF-8 string
747 CBOR::XS::tag 32, "$_[0]"
748 }
749
750 This will encode URIs as a UTF-8 string with tag 32, which indicates an
751 URI.
752
753 Decoding such an URI will not (currently) give you an URI object, but
754 instead a CBOR::XS::Tagged object with tag number 32 and the string -
755 exactly what was returned by "TO_CBOR".
756
757 To serialise an object so it can automatically be deserialised, you need
758 to use "FREEZE" and "THAW". To take the URI module as example, this
759 would be a possible implementation:
760
761 sub URI::FREEZE {
762 my ($self, $serialiser) = @_;
763 "$self" # encode url string
764 }
765
766 sub URI::THAW {
767 my ($class, $serialiser, $uri) = @_;
768 $class->new ($uri)
769 }
770
771 Unlike "TO_CBOR", multiple values can be returned by "FREEZE". For
772 example, a "FREEZE" method that returns "type", "id" and "variant"
773 values would cause an invocation of "THAW" with 5 arguments:
774
775 sub My::Object::FREEZE {
776 my ($self, $serialiser) = @_;
777
778 ($self->{type}, $self->{id}, $self->{variant})
779 }
780
781 sub My::Object::THAW {
782 my ($class, $serialiser, $type, $id, $variant) = @_;
783
784 $class-<new (type => $type, id => $id, variant => $variant)
785 }
786
787 MAGIC HEADER
788 There is no way to distinguish CBOR from other formats programmatically.
789 To make it easier to distinguish CBOR from other formats, the CBOR
790 specification has a special "magic string" that can be prepended to any
791 CBOR string without changing its meaning.
792
793 This string is available as $CBOR::XS::MAGIC. This module does not
794 prepend this string to the CBOR data it generates, but it will ignore it
795 if present, so users can prepend this string as a "file type" indicator
796 as required.
797
798 THE CBOR::XS::Tagged CLASS
799 CBOR has the concept of tagged values - any CBOR value can be tagged
800 with a numeric 64 bit number, which are centrally administered.
801
802 "CBOR::XS" handles a few tags internally when en- or decoding. You can
803 also create tags yourself by encoding "CBOR::XS::Tagged" objects, and
804 the decoder will create "CBOR::XS::Tagged" objects itself when it hits
805 an unknown tag.
806
807 These objects are simply blessed array references - the first member of
808 the array being the numerical tag, the second being the value.
809
810 You can interact with "CBOR::XS::Tagged" objects in the following ways:
811
812 $tagged = CBOR::XS::tag $tag, $value
813 This function(!) creates a new "CBOR::XS::Tagged" object using the
814 given $tag (0..2**64-1) to tag the given $value (which can be any
815 Perl value that can be encoded in CBOR, including serialisable Perl
816 objects and "CBOR::XS::Tagged" objects).
817
818 $tagged->[0]
819 $tagged->[0] = $new_tag
820 $tag = $tagged->tag
821 $new_tag = $tagged->tag ($new_tag)
822 Access/mutate the tag.
823
824 $tagged->[1]
825 $tagged->[1] = $new_value
826 $value = $tagged->value
827 $new_value = $tagged->value ($new_value)
828 Access/mutate the tagged value.
829
830 EXAMPLES
831 Here are some examples of "CBOR::XS::Tagged" uses to tag objects.
832
833 You can look up CBOR tag value and emanings in the IANA registry at
834 <http://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml>.
835
836 Prepend a magic header ($CBOR::XS::MAGIC):
837
838 my $cbor = encode_cbor CBOR::XS::tag 55799, $value;
839 # same as:
840 my $cbor = $CBOR::XS::MAGIC . encode_cbor $value;
841
842 Serialise some URIs and a regex in an array:
843
844 my $cbor = encode_cbor [
845 (CBOR::XS::tag 32, "http://www.nethype.de/"),
846 (CBOR::XS::tag 32, "http://software.schmorp.de/"),
847 (CBOR::XS::tag 35, "^[Pp][Ee][Rr][lL]\$"),
848 ];
849
850 Wrap CBOR data in CBOR:
851
852 my $cbor_cbor = encode_cbor
853 CBOR::XS::tag 24,
854 encode_cbor [1, 2, 3];
855
856 TAG HANDLING AND EXTENSIONS
857 This section describes how this module handles specific tagged values
858 and extensions. If a tag is not mentioned here and no additional filters
859 are provided for it, then the default handling applies (creating a
860 CBOR::XS::Tagged object on decoding, and only encoding the tag when
861 explicitly requested).
862
863 Tags not handled specifically are currently converted into a
864 CBOR::XS::Tagged object, which is simply a blessed array reference
865 consisting of the numeric tag value followed by the (decoded) CBOR
866 value.
867
868 Future versions of this module reserve the right to special case
869 additional tags (such as base64url).
870
871 ENFORCED TAGS
872 These tags are always handled when decoding, and their handling cannot
873 be overridden by the user.
874
875 26 (perl-object, <http://cbor.schmorp.de/perl-object>)
876 These tags are automatically created (and decoded) for serialisable
877 objects using the "FREEZE/THAW" methods (the Types::Serialier object
878 serialisation protocol). See "OBJECT SERIALISATION" for details.
879
880 28, 29 (shareable, sharedref, <http://cbor.schmorp.de/value-sharing>)
881 These tags are automatically decoded when encountered (and they do
882 not result in a cyclic data structure, see "allow_cycles"),
883 resulting in shared values in the decoded object. They are only
884 encoded, however, when "allow_sharing" is enabled.
885
886 Not all shared values can be successfully decoded: values that
887 reference themselves will *currently* decode as "undef" (this is not
888 the same as a reference pointing to itself, which will be
889 represented as a value that contains an indirect reference to itself
890 - these will be decoded properly).
891
892 Note that considerably more shared value data structures can be
893 decoded than will be encoded - currently, only values pointed to by
894 references will be shared, others will not. While non-reference
895 shared values can be generated in Perl with some effort, they were
896 considered too unimportant to be supported in the encoder. The
897 decoder, however, will decode these values as shared values.
898
899 256, 25 (stringref-namespace, stringref,
900 <http://cbor.schmorp.de/stringref>)
901 These tags are automatically decoded when encountered. They are only
902 encoded, however, when "pack_strings" is enabled.
903
904 22098 (indirection, <http://cbor.schmorp.de/indirection>)
905 This tag is automatically generated when a reference are encountered
906 (with the exception of hash and array references). It is converted
907 to a reference when decoding.
908
909 55799 (self-describe CBOR, RFC 7049)
910 This value is not generated on encoding (unless explicitly requested
911 by the user), and is simply ignored when decoding.
912
913 NON-ENFORCED TAGS
914 These tags have default filters provided when decoding. Their handling
915 can be overridden by changing the %CBOR::XS::FILTER entry for the tag,
916 or by providing a custom "filter" callback when decoding.
917
918 When they result in decoding into a specific Perl class, the module
919 usually provides a corresponding "TO_CBOR" method as well.
920
921 When any of these need to load additional modules that are not part of
922 the perl core distribution (e.g. URI), it is (currently) up to the user
923 to provide these modules. The decoding usually fails with an exception
924 if the required module cannot be loaded.
925
926 0, 1 (date/time string, seconds since the epoch)
927 These tags are decoded into Time::Piece objects. The corresponding
928 "Time::Piece::TO_CBOR" method always encodes into tag 1 values
929 currently.
930
931 The Time::Piece API is generally surprisingly bad, and fractional
932 seconds are only accidentally kept intact, so watch out. On the plus
933 side, the module comes with perl since 5.10, which has to count for
934 something.
935
936 2, 3 (positive/negative bignum)
937 These tags are decoded into Math::BigInt objects. The corresponding
938 "Math::BigInt::TO_CBOR" method encodes "small" bigints into normal
939 CBOR integers, and others into positive/negative CBOR bignums.
940
941 4, 5, 264, 265 (decimal fraction/bigfloat)
942 Both decimal fractions and bigfloats are decoded into Math::BigFloat
943 objects. The corresponding "Math::BigFloat::TO_CBOR" method *always*
944 encodes into a decimal fraction (either tag 4 or 264).
945
946 NaN and infinities are not encoded properly, as they cannot be
947 represented in CBOR.
948
949 See "BIGNUM SECURITY CONSIDERATIONS" for more info.
950
951 30 (rational numbers)
952 These tags are decoded into Math::BigRat objects. The corresponding
953 "Math::BigRat::TO_CBOR" method encodes rational numbers with
954 denominator 1 via their numerator only, i.e., they become normal
955 integers or "bignums".
956
957 See "BIGNUM SECURITY CONSIDERATIONS" for more info.
958
959 21, 22, 23 (expected later JSON conversion)
960 CBOR::XS is not a CBOR-to-JSON converter, and will simply ignore
961 these tags.
962
963 32 (URI)
964 These objects decode into URI objects. The corresponding
965 "URI::TO_CBOR" method again results in a CBOR URI value.
966
967 CBOR and JSON
968 CBOR is supposed to implement a superset of the JSON data model, and is,
969 with some coercion, able to represent all JSON texts (something that
970 other "binary JSON" formats such as BSON generally do not support).
971
972 CBOR implements some extra hints and support for JSON interoperability,
973 and the spec offers further guidance for conversion between CBOR and
974 JSON. None of this is currently implemented in CBOR, and the guidelines
975 in the spec do not result in correct round-tripping of data. If JSON
976 interoperability is improved in the future, then the goal will be to
977 ensure that decoded JSON data will round-trip encoding and decoding to
978 CBOR intact.
979
980 SECURITY CONSIDERATIONS
981 Tl;dr... if you want to decode or encode CBOR from untrusted sources,
982 you should start with a coder object created via "new_safe" (which
983 implements the mitigations explained below):
984
985 my $coder = CBOR::XS->new_safe;
986
987 my $data = $coder->decode ($cbor_text);
988 my $cbor = $coder->encode ($data);
989
990 Longer version: When you are using CBOR in a protocol, talking to
991 untrusted potentially hostile creatures requires some thought:
992
993 Security of the CBOR decoder itself
994 First and foremost, your CBOR decoder should be secure, that is,
995 should not have any buffer overflows or similar bugs that could
996 potentially be exploited. Obviously, this module should ensure that
997 and I am trying hard on making that true, but you never know.
998
999 CBOR::XS can invoke almost arbitrary callbacks during decoding
1000 CBOR::XS supports object serialisation - decoding CBOR can cause
1001 calls to *any* "THAW" method in *any* package that exists in your
1002 process (that is, CBOR::XS will not try to load modules, but any
1003 existing "THAW" method or function can be called, so they all have
1004 to be secure).
1005
1006 Less obviously, it will also invoke "TO_CBOR" and "FREEZE" methods -
1007 even if all your "THAW" methods are secure, encoding data structures
1008 from untrusted sources can invoke those and trigger bugs in those.
1009
1010 So, if you are not sure about the security of all the modules you
1011 have loaded (you shouldn't), you should disable this part using
1012 "forbid_objects" or using "new_safe".
1013
1014 CBOR can be extended with tags that call library code
1015 CBOR can be extended with tags, and "CBOR::XS" has a registry of
1016 conversion functions for many existing tags that can be extended via
1017 third-party modules (see the "filter" method).
1018
1019 If you don't trust these, you should configure the "safe" filter
1020 function, "CBOR::XS::safe_filter" ("new_safe" does this), which by
1021 default only includes conversion functions that are considered
1022 "safe" by the author (but again, they can be extended by third party
1023 modules).
1024
1025 Depending on your level of paranoia, you can use the "safe" filter:
1026
1027 $cbor->filter (\&CBOR::XS::safe_filter);
1028
1029 ... your own filter...
1030
1031 $cbor->filter (sub { ... do your stuffs here ... });
1032
1033 ... or even no filter at all, disabling all tag decoding:
1034
1035 $cbor->filter (sub { });
1036
1037 This is never a problem for encoding, as the tag mechanism only
1038 exists in CBOR texts.
1039
1040 Resource-starving attacks: object memory usage
1041 You need to avoid resource-starving attacks. That means you should
1042 limit the size of CBOR data you accept, or make sure then when your
1043 resources run out, that's just fine (e.g. by using a separate
1044 process that can crash safely). The size of a CBOR string in octets
1045 is usually a good indication of the size of the resources required
1046 to decode it into a Perl structure. While CBOR::XS can check the
1047 size of the CBOR text (using "max_size" - done by "new_safe"), it
1048 might be too late when you already have it in memory, so you might
1049 want to check the size before you accept the string.
1050
1051 As for encoding, it is possible to construct data structures that
1052 are relatively small but result in large CBOR texts (for example by
1053 having an array full of references to the same big data structure,
1054 which will all be deep-cloned during encoding by default). This is
1055 rarely an actual issue (and the worst case is still just running out
1056 of memory), but you can reduce this risk by using "allow_sharing".
1057
1058 Resource-starving attacks: stack overflows
1059 CBOR::XS recurses using the C stack when decoding objects and
1060 arrays. The C stack is a limited resource: for instance, on my amd64
1061 machine with 8MB of stack size I can decode around 180k nested
1062 arrays but only 14k nested CBOR objects (due to perl itself
1063 recursing deeply on croak to free the temporary). If that is
1064 exceeded, the program crashes. To be conservative, the default
1065 nesting limit is set to 512. If your process has a smaller stack,
1066 you should adjust this setting accordingly with the "max_depth"
1067 method.
1068
1069 Resource-starving attacks: CPU en-/decoding complexity
1070 CBOR::XS will use the Math::BigInt, Math::BigFloat and Math::BigRat
1071 libraries to represent encode/decode bignums. These can be very slow
1072 (as in, centuries of CPU time) and can even crash your program (and
1073 are generally not very trustworthy). See the next section on bignum
1074 security for details.
1075
1076 Data breaches: leaking information in error messages
1077 CBOR::XS might leak contents of your Perl data structures in its
1078 error messages, so when you serialise sensitive information you
1079 might want to make sure that exceptions thrown by CBOR::XS will not
1080 end up in front of untrusted eyes.
1081
1082 Something else...
1083 Something else could bomb you, too, that I forgot to think of. In
1084 that case, you get to keep the pieces. I am always open for hints,
1085 though...
1086
1087 BIGNUM SECURITY CONSIDERATIONS
1088 CBOR::XS provides a "TO_CBOR" method for both Math::BigInt and
1089 Math::BigFloat that tries to encode the number in the simplest possible
1090 way, that is, either a CBOR integer, a CBOR bigint/decimal fraction (tag
1091 4) or an arbitrary-exponent decimal fraction (tag 264). Rational numbers
1092 (Math::BigRat, tag 30) can also contain bignums as members.
1093
1094 CBOR::XS will also understand base-2 bigfloat or arbitrary-exponent
1095 bigfloats (tags 5 and 265), but it will never generate these on its own.
1096
1097 Using the built-in Math::BigInt::Calc support, encoding and decoding
1098 decimal fractions is generally fast. Decoding bigints can be slow for
1099 very big numbers (tens of thousands of digits, something that could
1100 potentially be caught by limiting the size of CBOR texts), and decoding
1101 bigfloats or arbitrary-exponent bigfloats can be *extremely* slow
1102 (minutes, decades) for large exponents (roughly 40 bit and longer).
1103
1104 Additionally, Math::BigInt can take advantage of other bignum libraries,
1105 such as Math::GMP, which cannot handle big floats with large exponents,
1106 and might simply abort or crash your program, due to their code quality.
1107
1108 This can be a concern if you want to parse untrusted CBOR. If it is, you
1109 might want to disable decoding of tag 2 (bigint) and 3 (negative bigint)
1110 types. You should also disable types 5 and 265, as these can be slow
1111 even without bigints.
1112
1113 Disabling bigints will also partially or fully disable types that rely
1114 on them, e.g. rational numbers that use bignums.
1115
1116 CBOR IMPLEMENTATION NOTES
1117 This section contains some random implementation notes. They do not
1118 describe guaranteed behaviour, but merely behaviour as-is implemented
1119 right now.
1120
1121 64 bit integers are only properly decoded when Perl was built with 64
1122 bit support.
1123
1124 Strings and arrays are encoded with a definite length. Hashes as well,
1125 unless they are tied (or otherwise magical).
1126
1127 Only the double data type is supported for NV data types - when Perl
1128 uses long double to represent floating point values, they might not be
1129 encoded properly. Half precision types are accepted, but not encoded.
1130
1131 Strict mode and canonical mode are not implemented.
1132
1133 LIMITATIONS ON PERLS WITHOUT 64-BIT INTEGER SUPPORT
1134 On perls that were built without 64 bit integer support (these are rare
1135 nowadays, even on 32 bit architectures, as all major Perl distributions
1136 are built with 64 bit integer support), support for any kind of 64 bit
1137 value in CBOR is very limited - most likely, these 64 bit values will be
1138 truncated, corrupted, or otherwise not decoded correctly. This also
1139 includes string, float, array and map sizes that are stored as 64 bit
1140 integers.
1141
1142 THREADS
1143 This module is *not* guaranteed to be thread safe and there are no plans
1144 to change this until Perl gets thread support (as opposed to the
1145 horribly slow so-called "threads" which are simply slow and bloated
1146 process simulations - use fork, it's *much* faster, cheaper, better).
1147
1148 (It might actually work, but you have been warned).
1149
1150 BUGS
1151 While the goal of this module is to be correct, that unfortunately does
1152 not mean it's bug-free, only that I think its design is bug-free. If you
1153 keep reporting bugs they will be fixed swiftly, though.
1154
1155 Please refrain from using rt.cpan.org or any other bug reporting
1156 service. I put the contact address into my modules for a reason.
1157
1158 SEE ALSO
1159 The JSON and JSON::XS modules that do similar, but human-readable,
1160 serialisation.
1161
1162 The Types::Serialiser module provides the data model for true, false and
1163 error values.
1164
1165 AUTHOR
1166 Marc Lehmann <schmorp@schmorp.de>
1167 http://home.schmorp.de/
1168