ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/README
Revision: 1.7
Committed: Tue Oct 29 15:56:31 2013 UTC (10 years, 6 months ago) by root
Branch: MAIN
CVS Tags: rel-0_06
Changes since 1.6: +64 -3 lines
Log Message:
0.06

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