ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/XS.xs
Revision: 1.35
Committed: Sat Nov 30 17:19:34 2013 UTC (10 years, 5 months ago) by root
Branch: MAIN
Changes since 1.34: +140 -108 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4
5 #include <assert.h>
6 #include <string.h>
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <limits.h>
10 #include <float.h>
11
12 #include "ecb.h"
13
14 // compatibility with perl <5.18
15 #ifndef HvNAMELEN_get
16 # define HvNAMELEN_get(hv) strlen (HvNAME (hv))
17 #endif
18 #ifndef HvNAMELEN
19 # define HvNAMELEN(hv) HvNAMELEN_get (hv)
20 #endif
21 #ifndef HvNAMEUTF8
22 # define HvNAMEUTF8(hv) 0
23 #endif
24 #ifndef SvREFCNT_dec_NN
25 # define SvREFCNT_dec_NN(sv) SvREFCNT_dec (sv)
26 #endif
27
28 // known major and minor types
29 enum cbor_type
30 {
31 MAJOR_SHIFT = 5,
32 MINOR_MASK = 0x1f,
33
34 MAJOR_POS_INT = 0 << MAJOR_SHIFT,
35 MAJOR_NEG_INT = 1 << MAJOR_SHIFT,
36 MAJOR_BYTES = 2 << MAJOR_SHIFT,
37 MAJOR_TEXT = 3 << MAJOR_SHIFT,
38 MAJOR_ARRAY = 4 << MAJOR_SHIFT,
39 MAJOR_MAP = 5 << MAJOR_SHIFT,
40 MAJOR_TAG = 6 << MAJOR_SHIFT,
41 MAJOR_MISC = 7 << MAJOR_SHIFT,
42
43 // INT/STRING/ARRAY/MAP subtypes
44 LENGTH_EXT1 = 24,
45 LENGTH_EXT2 = 25,
46 LENGTH_EXT4 = 26,
47 LENGTH_EXT8 = 27,
48
49 // SIMPLE types (effectively MISC subtypes)
50 SIMPLE_FALSE = 20,
51 SIMPLE_TRUE = 21,
52 SIMPLE_NULL = 22,
53 SIMPLE_UNDEF = 23,
54
55 // MISC subtype (unused)
56 MISC_EXT1 = 24,
57 MISC_FLOAT16 = 25,
58 MISC_FLOAT32 = 26,
59 MISC_FLOAT64 = 27,
60
61 // BYTES/TEXT/ARRAY/MAP
62 MINOR_INDEF = 31,
63 };
64
65 // known tags
66 enum cbor_tag
67 {
68 // extensions
69 CBOR_TAG_STRINGREF = 25, // http://cbor.schmorp.de/stringref
70 CBOR_TAG_PERL_OBJECT = 26, // http://cbor.schmorp.de/perl-object
71 CBOR_TAG_GENERIC_OBJECT = 27, // http://cbor.schmorp.de/generic-object
72 CBOR_TAG_VALUE_SHAREABLE = 28, // http://cbor.schmorp.de/value-sharing
73 CBOR_TAG_VALUE_SHAREDREF = 29, // http://cbor.schmorp.de/value-sharing
74 CBOR_TAG_STRINGREF_NAMESPACE = 256, // http://cbor.schmorp.de/stringref
75 CBOR_TAG_INDIRECTION = 22098, // http://cbor.schmorp.de/indirection
76
77 // rfc7049
78 CBOR_TAG_DATETIME = 0, // rfc4287, utf-8
79 CBOR_TAG_TIMESTAMP = 1, // unix timestamp, any
80 CBOR_TAG_POS_BIGNUM = 2, // byte string
81 CBOR_TAG_NEG_BIGNUM = 3, // byte string
82 CBOR_TAG_DECIMAL = 4, // decimal fraction, array
83 CBOR_TAG_BIGFLOAT = 5, // array
84
85 CBOR_TAG_CONV_B64U = 21, // base64url, any
86 CBOR_TAG_CONV_B64 = 22, // base64, any
87 CBOR_TAG_CONV_HEX = 23, // base16, any
88 CBOR_TAG_CBOR = 24, // embedded cbor, byte string
89
90 CBOR_TAG_URI = 32, // URI rfc3986, utf-8
91 CBOR_TAG_B64U = 33, // base64url rfc4648, utf-8
92 CBOR_TAG_B64 = 34, // base6 rfc46484, utf-8
93 CBOR_TAG_REGEX = 35, // regex pcre/ecma262, utf-8
94 CBOR_TAG_MIME = 36, // mime message rfc2045, utf-8
95
96 CBOR_TAG_MAGIC = 55799, // self-describe cbor
97 };
98
99 #define F_SHRINK 0x00000001UL
100 #define F_ALLOW_UNKNOWN 0x00000002UL
101 #define F_ALLOW_SHARING 0x00000004UL
102 #define F_PACK_STRINGS 0x00000008UL
103
104 #define INIT_SIZE 32 // initial scalar size to be allocated
105
106 #define SB do {
107 #define SE } while (0)
108
109 #define IN_RANGE_INC(type,val,beg,end) \
110 ((unsigned type)((unsigned type)(val) - (unsigned type)(beg)) \
111 <= (unsigned type)((unsigned type)(end) - (unsigned type)(beg)))
112
113 #define ERR_NESTING_EXCEEDED "cbor text or perl structure exceeds maximum nesting level (max_depth set too low?)"
114
115 #ifdef USE_ITHREADS
116 # define CBOR_SLOW 1
117 # define CBOR_STASH (cbor_stash ? cbor_stash : gv_stashpv ("CBOR::XS", 1))
118 #else
119 # define CBOR_SLOW 0
120 # define CBOR_STASH cbor_stash
121 #endif
122
123 static HV *cbor_stash, *types_boolean_stash, *types_error_stash, *cbor_tagged_stash; // CBOR::XS::
124 static SV *types_true, *types_false, *types_error, *sv_cbor, *default_filter;
125
126 typedef struct {
127 U32 flags;
128 U32 max_depth;
129 STRLEN max_size;
130 SV *filter;
131 } CBOR;
132
133 ecb_inline void
134 cbor_init (CBOR *cbor)
135 {
136 Zero (cbor, 1, CBOR);
137 cbor->max_depth = 512;
138 }
139
140 ecb_inline void
141 cbor_free (CBOR *cbor)
142 {
143 SvREFCNT_dec (cbor->filter);
144 }
145
146 /////////////////////////////////////////////////////////////////////////////
147 // utility functions
148
149 ecb_inline SV *
150 get_bool (const char *name)
151 {
152 SV *sv = get_sv (name, 1);
153
154 SvREADONLY_on (sv);
155 SvREADONLY_on (SvRV (sv));
156
157 return sv;
158 }
159
160 ecb_inline void
161 shrink (SV *sv)
162 {
163 sv_utf8_downgrade (sv, 1);
164
165 if (SvLEN (sv) > SvCUR (sv) + 1)
166 {
167 #ifdef SvPV_shrink_to_cur
168 SvPV_shrink_to_cur (sv);
169 #elif defined (SvPV_renew)
170 SvPV_renew (sv, SvCUR (sv) + 1);
171 #endif
172 }
173 }
174
175 // minimum length of a string to be registered for stringref
176 ecb_inline int
177 minimum_string_length (UV idx)
178 {
179 return idx > 23
180 ? idx > 0xffU
181 ? idx > 0xffffU
182 ? idx > 0xffffffffU
183 ? 11
184 : 7
185 : 5
186 : 4
187 : 3;
188 }
189
190 /////////////////////////////////////////////////////////////////////////////
191 // encoder
192
193 // structure used for encoding CBOR
194 typedef struct
195 {
196 char *cur; // SvPVX (sv) + current output position
197 char *end; // SvEND (sv)
198 SV *sv; // result scalar
199 CBOR cbor;
200 U32 depth; // recursion level
201 HV *stringref[2]; // string => index, or 0 ([0] = bytes, [1] = utf-8)
202 UV stringref_idx;
203 HV *shareable; // ptr => index, or 0
204 UV shareable_idx;
205 } enc_t;
206
207 ecb_inline void
208 need (enc_t *enc, STRLEN len)
209 {
210 if (ecb_expect_false (enc->cur + len >= enc->end))
211 {
212 STRLEN cur = enc->cur - (char *)SvPVX (enc->sv);
213 SvGROW (enc->sv, cur + (len < (cur >> 2) ? cur >> 2 : len) + 1);
214 enc->cur = SvPVX (enc->sv) + cur;
215 enc->end = SvPVX (enc->sv) + SvLEN (enc->sv) - 1;
216 }
217 }
218
219 ecb_inline void
220 encode_ch (enc_t *enc, char ch)
221 {
222 need (enc, 1);
223 *enc->cur++ = ch;
224 }
225
226 static void
227 encode_uint (enc_t *enc, int major, UV len)
228 {
229 need (enc, 9);
230
231 if (ecb_expect_true (len < LENGTH_EXT1))
232 *enc->cur++ = major | len;
233 else if (ecb_expect_true (len <= 0xff))
234 {
235 *enc->cur++ = major | LENGTH_EXT1;
236 *enc->cur++ = len;
237 }
238 else if (len <= 0xffff)
239 {
240 *enc->cur++ = major | LENGTH_EXT2;
241 *enc->cur++ = len >> 8;
242 *enc->cur++ = len;
243 }
244 else if (len <= 0xffffffff)
245 {
246 *enc->cur++ = major | LENGTH_EXT4;
247 *enc->cur++ = len >> 24;
248 *enc->cur++ = len >> 16;
249 *enc->cur++ = len >> 8;
250 *enc->cur++ = len;
251 }
252 else
253 {
254 *enc->cur++ = major | LENGTH_EXT8;
255 *enc->cur++ = len >> 56;
256 *enc->cur++ = len >> 48;
257 *enc->cur++ = len >> 40;
258 *enc->cur++ = len >> 32;
259 *enc->cur++ = len >> 24;
260 *enc->cur++ = len >> 16;
261 *enc->cur++ = len >> 8;
262 *enc->cur++ = len;
263 }
264 }
265
266 ecb_inline void
267 encode_tag (enc_t *enc, UV tag)
268 {
269 encode_uint (enc, MAJOR_TAG, tag);
270 }
271
272 ecb_inline void
273 encode_str (enc_t *enc, int utf8, char *str, STRLEN len)
274 {
275 encode_uint (enc, utf8 ? MAJOR_TEXT : MAJOR_BYTES, len);
276 need (enc, len);
277 memcpy (enc->cur, str, len);
278 enc->cur += len;
279 }
280
281 static void
282 encode_strref (enc_t *enc, int utf8, char *str, STRLEN len)
283 {
284 if (ecb_expect_false (enc->cbor.flags & F_PACK_STRINGS))
285 {
286 SV **svp = hv_fetch (enc->stringref[!!utf8], str, len, 1);
287
288 if (SvOK (*svp))
289 {
290 // already registered, use stringref
291 encode_tag (enc, CBOR_TAG_STRINGREF);
292 encode_uint (enc, MAJOR_POS_INT, SvUV (*svp));
293 return;
294 }
295 else if (len >= minimum_string_length (enc->stringref_idx))
296 {
297 // register only
298 sv_setuv (*svp, enc->stringref_idx);
299 ++enc->stringref_idx;
300 }
301 }
302
303 encode_str (enc, utf8, str, len);
304 }
305
306 static void encode_sv (enc_t *enc, SV *sv);
307
308 static void
309 encode_av (enc_t *enc, AV *av)
310 {
311 int i, len = av_len (av);
312
313 if (enc->depth >= enc->cbor.max_depth)
314 croak (ERR_NESTING_EXCEEDED);
315
316 ++enc->depth;
317
318 encode_uint (enc, MAJOR_ARRAY, len + 1);
319
320 for (i = 0; i <= len; ++i)
321 {
322 SV **svp = av_fetch (av, i, 0);
323 encode_sv (enc, svp ? *svp : &PL_sv_undef);
324 }
325
326 --enc->depth;
327 }
328
329 static void
330 encode_hv (enc_t *enc, HV *hv)
331 {
332 HE *he;
333
334 if (enc->depth >= enc->cbor.max_depth)
335 croak (ERR_NESTING_EXCEEDED);
336
337 ++enc->depth;
338
339 int pairs = hv_iterinit (hv);
340 int mg = SvMAGICAL (hv);
341
342 if (mg)
343 encode_ch (enc, MAJOR_MAP | MINOR_INDEF);
344 else
345 encode_uint (enc, MAJOR_MAP, pairs);
346
347 while ((he = hv_iternext (hv)))
348 {
349 if (HeKLEN (he) == HEf_SVKEY)
350 encode_sv (enc, HeSVKEY (he));
351 else
352 encode_strref (enc, HeKUTF8 (he), HeKEY (he), HeKLEN (he));
353
354 encode_sv (enc, ecb_expect_false (mg) ? hv_iterval (hv, he) : HeVAL (he));
355 }
356
357 if (mg)
358 encode_ch (enc, MAJOR_MISC | MINOR_INDEF);
359
360 --enc->depth;
361 }
362
363 // encode objects, arrays and special \0=false and \1=true values.
364 static void
365 encode_rv (enc_t *enc, SV *sv)
366 {
367 SvGETMAGIC (sv);
368
369 svtype svt = SvTYPE (sv);
370
371 if (ecb_expect_false (SvOBJECT (sv)))
372 {
373 HV *boolean_stash = !CBOR_SLOW || types_boolean_stash
374 ? types_boolean_stash
375 : gv_stashpv ("Types::Serialiser::Boolean", 1);
376 HV *error_stash = !CBOR_SLOW || types_error_stash
377 ? types_error_stash
378 : gv_stashpv ("Types::Serialiser::Error", 1);
379 HV *tagged_stash = !CBOR_SLOW || cbor_tagged_stash
380 ? cbor_tagged_stash
381 : gv_stashpv ("CBOR::XS::Tagged" , 1);
382
383 HV *stash = SvSTASH (sv);
384
385 if (stash == boolean_stash)
386 {
387 encode_ch (enc, SvIV (sv) ? MAJOR_MISC | SIMPLE_TRUE : MAJOR_MISC | SIMPLE_FALSE);
388 return;
389 }
390 else if (stash == error_stash)
391 {
392 encode_ch (enc, MAJOR_MISC | SIMPLE_UNDEF);
393 return;
394 }
395 else if (stash == tagged_stash)
396 {
397 if (svt != SVt_PVAV)
398 croak ("encountered CBOR::XS::Tagged object that isn't an array");
399
400 encode_uint (enc, MAJOR_TAG, SvUV (*av_fetch ((AV *)sv, 0, 1)));
401 encode_sv (enc, *av_fetch ((AV *)sv, 1, 1));
402
403 return;
404 }
405 }
406
407 if (ecb_expect_false (SvREFCNT (sv) > 1)
408 && ecb_expect_false (enc->cbor.flags & F_ALLOW_SHARING))
409 {
410 if (!enc->shareable)
411 enc->shareable = (HV *)sv_2mortal ((SV *)newHV ());
412
413 SV **svp = hv_fetch (enc->shareable, (char *)&sv, sizeof (sv), 1);
414
415 if (SvOK (*svp))
416 {
417 encode_tag (enc, CBOR_TAG_VALUE_SHAREDREF);
418 encode_uint (enc, MAJOR_POS_INT, SvUV (*svp));
419 return;
420 }
421 else
422 {
423 sv_setuv (*svp, enc->shareable_idx);
424 ++enc->shareable_idx;
425 encode_tag (enc, CBOR_TAG_VALUE_SHAREABLE);
426 }
427 }
428
429 if (ecb_expect_false (SvOBJECT (sv)))
430 {
431 HV *stash = SvSTASH (sv);
432 GV *method;
433
434 if ((method = gv_fetchmethod_autoload (stash, "TO_CBOR", 0)))
435 {
436 dSP;
437
438 ENTER; SAVETMPS; PUSHMARK (SP);
439 // we re-bless the reference to get overload and other niceties right
440 XPUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash));
441
442 PUTBACK;
443 // G_SCALAR ensures that return value is 1
444 call_sv ((SV *)GvCV (method), G_SCALAR);
445 SPAGAIN;
446
447 // catch this surprisingly common error
448 if (SvROK (TOPs) && SvRV (TOPs) == sv)
449 croak ("%s::TO_CBOR method returned same object as was passed instead of a new one", HvNAME (stash));
450
451 encode_sv (enc, POPs);
452
453 PUTBACK;
454
455 FREETMPS; LEAVE;
456 }
457 else if ((method = gv_fetchmethod_autoload (stash, "FREEZE", 0)) != 0)
458 {
459 dSP;
460
461 ENTER; SAVETMPS; PUSHMARK (SP);
462 EXTEND (SP, 2);
463 // we re-bless the reference to get overload and other niceties right
464 PUSHs (sv_bless (sv_2mortal (newRV_inc (sv)), stash));
465 PUSHs (sv_cbor);
466
467 PUTBACK;
468 int count = call_sv ((SV *)GvCV (method), G_ARRAY);
469 SPAGAIN;
470
471 // catch this surprisingly common error
472 if (count == 1 && SvROK (TOPs) && SvRV (TOPs) == sv)
473 croak ("%s::FREEZE(CBOR) method returned same object as was passed instead of a new one", HvNAME (stash));
474
475 encode_tag (enc, CBOR_TAG_PERL_OBJECT);
476 encode_uint (enc, MAJOR_ARRAY, count + 1);
477 encode_strref (enc, HvNAMEUTF8 (stash), HvNAME (stash), HvNAMELEN (stash));
478
479 while (count)
480 encode_sv (enc, SP[1 - count--]);
481
482 PUTBACK;
483
484 FREETMPS; LEAVE;
485 }
486 else
487 croak ("encountered object '%s', but no TO_CBOR or FREEZE methods available on it",
488 SvPV_nolen (sv_2mortal (newRV_inc (sv))));
489 }
490 else if (svt == SVt_PVHV)
491 encode_hv (enc, (HV *)sv);
492 else if (svt == SVt_PVAV)
493 encode_av (enc, (AV *)sv);
494 else
495 {
496 encode_tag (enc, CBOR_TAG_INDIRECTION);
497 encode_sv (enc, sv);
498 }
499 }
500
501 static void
502 encode_nv (enc_t *enc, SV *sv)
503 {
504 double nv = SvNVX (sv);
505
506 need (enc, 9);
507
508 if (ecb_expect_false (nv == (NV)(U32)nv))
509 encode_uint (enc, MAJOR_POS_INT, (U32)nv);
510 //TODO: maybe I32?
511 else if (ecb_expect_false (nv == (float)nv))
512 {
513 uint32_t fp = ecb_float_to_binary32 (nv);
514
515 *enc->cur++ = MAJOR_MISC | MISC_FLOAT32;
516
517 if (!ecb_big_endian ())
518 fp = ecb_bswap32 (fp);
519
520 memcpy (enc->cur, &fp, 4);
521 enc->cur += 4;
522 }
523 else
524 {
525 uint64_t fp = ecb_double_to_binary64 (nv);
526
527 *enc->cur++ = MAJOR_MISC | MISC_FLOAT64;
528
529 if (!ecb_big_endian ())
530 fp = ecb_bswap64 (fp);
531
532 memcpy (enc->cur, &fp, 8);
533 enc->cur += 8;
534 }
535 }
536
537 static void
538 encode_sv (enc_t *enc, SV *sv)
539 {
540 SvGETMAGIC (sv);
541
542 if (SvPOKp (sv))
543 {
544 STRLEN len;
545 char *str = SvPV (sv, len);
546 encode_strref (enc, SvUTF8 (sv), str, len);
547 }
548 else if (SvNOKp (sv))
549 encode_nv (enc, sv);
550 else if (SvIOKp (sv))
551 {
552 if (SvIsUV (sv))
553 encode_uint (enc, MAJOR_POS_INT, SvUVX (sv));
554 else if (SvIVX (sv) >= 0)
555 encode_uint (enc, MAJOR_POS_INT, SvIVX (sv));
556 else
557 encode_uint (enc, MAJOR_NEG_INT, -(SvIVX (sv) + 1));
558 }
559 else if (SvROK (sv))
560 encode_rv (enc, SvRV (sv));
561 else if (!SvOK (sv))
562 encode_ch (enc, MAJOR_MISC | SIMPLE_NULL);
563 else if (enc->cbor.flags & F_ALLOW_UNKNOWN)
564 encode_ch (enc, MAJOR_MISC | SIMPLE_UNDEF);
565 else
566 croak ("encountered perl type (%s,0x%x) that CBOR cannot handle, check your input data",
567 SvPV_nolen (sv), (unsigned int)SvFLAGS (sv));
568 }
569
570 static SV *
571 encode_cbor (SV *scalar, CBOR *cbor)
572 {
573 enc_t enc = { };
574
575 enc.cbor = *cbor;
576 enc.sv = sv_2mortal (NEWSV (0, INIT_SIZE));
577 enc.cur = SvPVX (enc.sv);
578 enc.end = SvEND (enc.sv);
579
580 SvPOK_only (enc.sv);
581
582 if (cbor->flags & F_PACK_STRINGS)
583 {
584 encode_tag (&enc, CBOR_TAG_STRINGREF_NAMESPACE);
585 enc.stringref[0]= (HV *)sv_2mortal ((SV *)newHV ());
586 enc.stringref[1]= (HV *)sv_2mortal ((SV *)newHV ());
587 }
588
589 encode_sv (&enc, scalar);
590
591 SvCUR_set (enc.sv, enc.cur - SvPVX (enc.sv));
592 *SvEND (enc.sv) = 0; // many xs functions expect a trailing 0 for text strings
593
594 if (enc.cbor.flags & F_SHRINK)
595 shrink (enc.sv);
596
597 return enc.sv;
598 }
599
600 /////////////////////////////////////////////////////////////////////////////
601 // decoder
602
603 // structure used for decoding CBOR
604 typedef struct
605 {
606 U8 *cur; // current parser pointer
607 U8 *end; // end of input string
608 const char *err; // parse error, if != 0
609 CBOR cbor;
610 U32 depth; // recursion depth
611 U32 maxdepth; // recursion depth limit
612 AV *shareable;
613 AV *stringref;
614 SV *decode_tagged;
615 } dec_t;
616
617 #define ERR(reason) SB if (!dec->err) dec->err = reason; goto fail; SE
618
619 #define WANT(len) if (ecb_expect_false (dec->cur + len > dec->end)) ERR ("unexpected end of CBOR data")
620
621 #define DEC_INC_DEPTH if (++dec->depth > dec->cbor.max_depth) ERR (ERR_NESTING_EXCEEDED)
622 #define DEC_DEC_DEPTH --dec->depth
623
624 static UV
625 decode_uint (dec_t *dec)
626 {
627 U8 m = *dec->cur & MINOR_MASK;
628 ++dec->cur;
629
630 if (ecb_expect_true (m < LENGTH_EXT1))
631 return m;
632
633 switch (m)
634 {
635 case LENGTH_EXT1:
636 WANT (1);
637 dec->cur += 1;
638 return dec->cur[-1];
639
640 case LENGTH_EXT2:
641 WANT (2);
642 dec->cur += 2;
643 return (((UV)dec->cur[-2]) << 8)
644 | ((UV)dec->cur[-1]);
645
646 case LENGTH_EXT4:
647 WANT (4);
648 dec->cur += 4;
649 return (((UV)dec->cur[-4]) << 24)
650 | (((UV)dec->cur[-3]) << 16)
651 | (((UV)dec->cur[-2]) << 8)
652 | ((UV)dec->cur[-1]);
653
654 case LENGTH_EXT8:
655 WANT (8);
656 dec->cur += 8;
657
658 return
659 #if UVSIZE < 8
660 0
661 #else
662 (((UV)dec->cur[-8]) << 56)
663 | (((UV)dec->cur[-7]) << 48)
664 | (((UV)dec->cur[-6]) << 40)
665 | (((UV)dec->cur[-5]) << 32)
666 #endif
667 | (((UV)dec->cur[-4]) << 24)
668 | (((UV)dec->cur[-3]) << 16)
669 | (((UV)dec->cur[-2]) << 8)
670 | ((UV)dec->cur[-1]);
671
672 default:
673 ERR ("corrupted CBOR data (unsupported integer minor encoding)");
674 }
675
676 fail:
677 return 0;
678 }
679
680 static SV *decode_sv (dec_t *dec);
681
682 static SV *
683 decode_av (dec_t *dec)
684 {
685 AV *av = newAV ();
686
687 DEC_INC_DEPTH;
688
689 if (*dec->cur == (MAJOR_ARRAY | MINOR_INDEF))
690 {
691 ++dec->cur;
692
693 for (;;)
694 {
695 WANT (1);
696
697 if (*dec->cur == (MAJOR_MISC | MINOR_INDEF))
698 {
699 ++dec->cur;
700 break;
701 }
702
703 av_push (av, decode_sv (dec));
704 }
705 }
706 else
707 {
708 int i, len = decode_uint (dec);
709
710 av_fill (av, len - 1);
711
712 for (i = 0; i < len; ++i)
713 AvARRAY (av)[i] = decode_sv (dec);
714 }
715
716 DEC_DEC_DEPTH;
717 return newRV_noinc ((SV *)av);
718
719 fail:
720 SvREFCNT_dec (av);
721 DEC_DEC_DEPTH;
722 return &PL_sv_undef;
723 }
724
725 static void
726 decode_he (dec_t *dec, HV *hv)
727 {
728 // for speed reasons, we specialcase single-string
729 // byte or utf-8 strings as keys, but only when !stringref
730
731 if (ecb_expect_true (!dec->stringref))
732 if ((*dec->cur - MAJOR_BYTES) <= 27)
733 {
734 I32 len = decode_uint (dec);
735 char *key = (char *)dec->cur;
736
737 dec->cur += len;
738
739 if (ecb_expect_false (dec->stringref))
740 av_push (dec->stringref, newSVpvn (key, len));
741
742 hv_store (hv, key, len, decode_sv (dec), 0);
743
744 return;
745 }
746 else if ((*dec->cur - MAJOR_TEXT) <= 27)
747 {
748 I32 len = decode_uint (dec);
749 char *key = (char *)dec->cur;
750
751 dec->cur += len;
752
753 if (ecb_expect_false (dec->stringref))
754 av_push (dec->stringref, newSVpvn_utf8 (key, len, 1));
755
756 hv_store (hv, key, -len, decode_sv (dec), 0);
757
758 return;
759 }
760
761 SV *k = decode_sv (dec);
762 SV *v = decode_sv (dec);
763
764 hv_store_ent (hv, k, v, 0);
765 SvREFCNT_dec (k);
766 }
767
768 static SV *
769 decode_hv (dec_t *dec)
770 {
771 HV *hv = newHV ();
772
773 DEC_INC_DEPTH;
774
775 if (*dec->cur == (MAJOR_MAP | MINOR_INDEF))
776 {
777 ++dec->cur;
778
779 for (;;)
780 {
781 WANT (1);
782
783 if (*dec->cur == (MAJOR_MISC | MINOR_INDEF))
784 {
785 ++dec->cur;
786 break;
787 }
788
789 decode_he (dec, hv);
790 }
791 }
792 else
793 {
794 int pairs = decode_uint (dec);
795
796 while (pairs--)
797 decode_he (dec, hv);
798 }
799
800 DEC_DEC_DEPTH;
801 return newRV_noinc ((SV *)hv);
802
803 fail:
804 SvREFCNT_dec (hv);
805 DEC_DEC_DEPTH;
806 return &PL_sv_undef;
807 }
808
809 static SV *
810 decode_str (dec_t *dec, int utf8)
811 {
812 SV *sv = 0;
813
814 if ((*dec->cur & MINOR_MASK) == MINOR_INDEF)
815 {
816 // indefinite length strings
817 ++dec->cur;
818
819 U8 major = *dec->cur & MAJOR_MISC;
820
821 sv = newSVpvn ("", 0);
822
823 for (;;)
824 {
825 WANT (1);
826
827 if ((*dec->cur - major) > LENGTH_EXT8)
828 if (*dec->cur == (MAJOR_MISC | MINOR_INDEF))
829 {
830 ++dec->cur;
831 break;
832 }
833 else
834 ERR ("corrupted CBOR data (invalid chunks in indefinite length string)");
835
836 STRLEN len = decode_uint (dec);
837
838 WANT (len);
839 sv_catpvn (sv, dec->cur, len);
840 dec->cur += len;
841 }
842 }
843 else
844 {
845 STRLEN len = decode_uint (dec);
846
847 WANT (len);
848 sv = newSVpvn (dec->cur, len);
849 dec->cur += len;
850
851 if (ecb_expect_false (dec->stringref)
852 && SvCUR (sv) >= minimum_string_length (AvFILLp (dec->stringref) + 1))
853 av_push (dec->stringref, SvREFCNT_inc_NN (sv));
854 }
855
856 if (utf8)
857 SvUTF8_on (sv);
858
859 return sv;
860
861 fail:
862 SvREFCNT_dec (sv);
863 return &PL_sv_undef;
864 }
865
866 static SV *
867 decode_tagged (dec_t *dec)
868 {
869 SV *sv = 0;
870 UV tag = decode_uint (dec);
871
872 WANT (1);
873
874 switch (tag)
875 {
876 case CBOR_TAG_MAGIC:
877 sv = decode_sv (dec);
878 break;
879
880 case CBOR_TAG_INDIRECTION:
881 sv = newRV_noinc (decode_sv (dec));
882 break;
883
884 case CBOR_TAG_STRINGREF_NAMESPACE:
885 {
886 ENTER; SAVETMPS;
887
888 SAVESPTR (dec->stringref);
889 dec->stringref = (AV *)sv_2mortal ((SV *)newAV ());
890
891 sv = decode_sv (dec);
892
893 FREETMPS; LEAVE;
894 }
895 break;
896
897 case CBOR_TAG_STRINGREF:
898 {
899 if ((*dec->cur >> MAJOR_SHIFT) != (MAJOR_POS_INT >> MAJOR_SHIFT))
900 ERR ("corrupted CBOR data (stringref index not an unsigned integer)");
901
902 UV idx = decode_uint (dec);
903
904 if (!dec->stringref || (int)idx > AvFILLp (dec->stringref))
905 ERR ("corrupted CBOR data (stringref index out of bounds or outside namespace)");
906
907 sv = newSVsv (AvARRAY (dec->stringref)[idx]);
908 }
909 break;
910
911 case CBOR_TAG_VALUE_SHAREABLE:
912 {
913 if (ecb_expect_false (!dec->shareable))
914 dec->shareable = (AV *)sv_2mortal ((SV *)newAV ());
915
916 sv = newSV (0);
917 av_push (dec->shareable, SvREFCNT_inc_NN (sv));
918
919 SV *osv = decode_sv (dec);
920 sv_setsv (sv, osv);
921 SvREFCNT_dec_NN (osv);
922 }
923 break;
924
925 case CBOR_TAG_VALUE_SHAREDREF:
926 {
927 if ((*dec->cur >> MAJOR_SHIFT) != (MAJOR_POS_INT >> MAJOR_SHIFT))
928 ERR ("corrupted CBOR data (sharedref index not an unsigned integer)");
929
930 UV idx = decode_uint (dec);
931
932 if (!dec->shareable || (int)idx > AvFILLp (dec->shareable))
933 ERR ("corrupted CBOR data (sharedref index out of bounds)");
934
935 sv = SvREFCNT_inc_NN (AvARRAY (dec->shareable)[idx]);
936 }
937 break;
938
939 case CBOR_TAG_PERL_OBJECT:
940 {
941 sv = decode_sv (dec);
942
943 if (!SvROK (sv) || SvTYPE (SvRV (sv)) != SVt_PVAV)
944 ERR ("corrupted CBOR data (non-array perl object)");
945
946 AV *av = (AV *)SvRV (sv);
947 int len = av_len (av) + 1;
948 HV *stash = gv_stashsv (*av_fetch (av, 0, 1), 0);
949
950 if (!stash)
951 ERR ("cannot decode perl-object (package does not exist)");
952
953 GV *method = gv_fetchmethod_autoload (stash, "THAW", 0);
954
955 if (!method)
956 ERR ("cannot decode perl-object (package does not have a THAW method)");
957
958 dSP;
959
960 ENTER; SAVETMPS; PUSHMARK (SP);
961 EXTEND (SP, len + 1);
962 // we re-bless the reference to get overload and other niceties right
963 PUSHs (*av_fetch (av, 0, 1));
964 PUSHs (sv_cbor);
965
966 int i;
967
968 for (i = 1; i < len; ++i)
969 PUSHs (*av_fetch (av, i, 1));
970
971 PUTBACK;
972 call_sv ((SV *)GvCV (method), G_SCALAR | G_EVAL);
973 SPAGAIN;
974
975 if (SvTRUE (ERRSV))
976 {
977 FREETMPS; LEAVE;
978 ERR (SvPVutf8_nolen (sv_2mortal (SvREFCNT_inc (ERRSV))));
979 }
980
981 SvREFCNT_dec (sv);
982 sv = SvREFCNT_inc (POPs);
983
984 PUTBACK;
985
986 FREETMPS; LEAVE;
987 }
988 break;
989
990 default:
991 {
992 sv = decode_sv (dec);
993
994 dSP;
995 ENTER; SAVETMPS; PUSHMARK (SP);
996 EXTEND (SP, 2);
997 PUSHs (newSVuv (tag));
998 PUSHs (sv);
999
1000 PUTBACK;
1001 int count = call_sv (dec->cbor.filter ? dec->cbor.filter : default_filter, G_ARRAY | G_EVAL);
1002 SPAGAIN;
1003
1004 if (SvTRUE (ERRSV))
1005 {
1006 FREETMPS; LEAVE;
1007 ERR (SvPVutf8_nolen (sv_2mortal (SvREFCNT_inc (ERRSV))));
1008 }
1009
1010 if (count)
1011 {
1012 SvREFCNT_dec (sv);
1013 sv = SvREFCNT_inc (POPs);
1014 }
1015 else
1016 {
1017 AV *av = newAV ();
1018 av_push (av, newSVuv (tag));
1019 av_push (av, sv);
1020
1021 HV *tagged_stash = !CBOR_SLOW || cbor_tagged_stash
1022 ? cbor_tagged_stash
1023 : gv_stashpv ("CBOR::XS::Tagged" , 1);
1024 sv = sv_bless (newRV_noinc ((SV *)av), tagged_stash);
1025 }
1026
1027 PUTBACK;
1028
1029 FREETMPS; LEAVE;
1030 }
1031 break;
1032 }
1033
1034 return sv;
1035
1036 fail:
1037 SvREFCNT_dec (sv);
1038 return &PL_sv_undef;
1039 }
1040
1041 static SV *
1042 decode_sv (dec_t *dec)
1043 {
1044 WANT (1);
1045
1046 switch (*dec->cur >> MAJOR_SHIFT)
1047 {
1048 case MAJOR_POS_INT >> MAJOR_SHIFT: return newSVuv (decode_uint (dec));
1049 case MAJOR_NEG_INT >> MAJOR_SHIFT: return newSViv (-1 - (IV)decode_uint (dec));
1050 case MAJOR_BYTES >> MAJOR_SHIFT: return decode_str (dec, 0);
1051 case MAJOR_TEXT >> MAJOR_SHIFT: return decode_str (dec, 1);
1052 case MAJOR_ARRAY >> MAJOR_SHIFT: return decode_av (dec);
1053 case MAJOR_MAP >> MAJOR_SHIFT: return decode_hv (dec);
1054 case MAJOR_TAG >> MAJOR_SHIFT: return decode_tagged (dec);
1055
1056 case MAJOR_MISC >> MAJOR_SHIFT:
1057 switch (*dec->cur++ & MINOR_MASK)
1058 {
1059 case SIMPLE_FALSE:
1060 #if CBOR_SLOW
1061 types_false = get_bool ("Types::Serialiser::false");
1062 #endif
1063 return newSVsv (types_false);
1064 case SIMPLE_TRUE:
1065 #if CBOR_SLOW
1066 types_true = get_bool ("Types::Serialiser::true");
1067 #endif
1068 return newSVsv (types_true);
1069 case SIMPLE_NULL:
1070 return newSVsv (&PL_sv_undef);
1071 case SIMPLE_UNDEF:
1072 #if CBOR_SLOW
1073 types_error = get_bool ("Types::Serialiser::error");
1074 #endif
1075 return newSVsv (types_error);
1076
1077 case MISC_FLOAT16:
1078 {
1079 WANT (2);
1080
1081 uint16_t fp = (dec->cur[0] << 8) | dec->cur[1];
1082 dec->cur += 2;
1083
1084 return newSVnv (ecb_binary16_to_float (fp));
1085 }
1086
1087 case MISC_FLOAT32:
1088 {
1089 uint32_t fp;
1090 WANT (4);
1091 memcpy (&fp, dec->cur, 4);
1092 dec->cur += 4;
1093
1094 if (!ecb_big_endian ())
1095 fp = ecb_bswap32 (fp);
1096
1097 return newSVnv (ecb_binary32_to_float (fp));
1098 }
1099
1100 case MISC_FLOAT64:
1101 {
1102 uint64_t fp;
1103 WANT (8);
1104 memcpy (&fp, dec->cur, 8);
1105 dec->cur += 8;
1106
1107 if (!ecb_big_endian ())
1108 fp = ecb_bswap64 (fp);
1109
1110 return newSVnv (ecb_binary64_to_double (fp));
1111 }
1112
1113 // 0..19 unassigned simple
1114 // 24 reserved + unassigned (reserved values are not encodable)
1115 default:
1116 ERR ("corrupted CBOR data (reserved/unassigned major 7 value)");
1117 }
1118
1119 break;
1120 }
1121
1122 fail:
1123 return &PL_sv_undef;
1124 }
1125
1126 static SV *
1127 decode_cbor (SV *string, CBOR *cbor, char **offset_return)
1128 {
1129 dec_t dec = { };
1130 SV *sv;
1131 STRLEN len;
1132 char *data = SvPVbyte (string, len);
1133
1134 if (len > cbor->max_size && cbor->max_size)
1135 croak ("attempted decode of CBOR text of %lu bytes size, but max_size is set to %lu",
1136 (unsigned long)len, (unsigned long)cbor->max_size);
1137
1138 dec.cbor = *cbor;
1139 dec.cur = (U8 *)data;
1140 dec.end = (U8 *)data + len;
1141
1142 sv = decode_sv (&dec);
1143
1144 if (offset_return)
1145 *offset_return = dec.cur;
1146
1147 if (!(offset_return || !sv))
1148 if (dec.cur != dec.end && !dec.err)
1149 dec.err = "garbage after CBOR object";
1150
1151 if (dec.err)
1152 {
1153 SvREFCNT_dec (sv);
1154 croak ("%s, at offset %d (octet 0x%02x)", dec.err, dec.cur - (U8 *)data, (int)(uint8_t)*dec.cur);
1155 }
1156
1157 sv = sv_2mortal (sv);
1158
1159 return sv;
1160 }
1161
1162 /////////////////////////////////////////////////////////////////////////////
1163 // XS interface functions
1164
1165 MODULE = CBOR::XS PACKAGE = CBOR::XS
1166
1167 BOOT:
1168 {
1169 cbor_stash = gv_stashpv ("CBOR::XS" , 1);
1170 cbor_tagged_stash = gv_stashpv ("CBOR::XS::Tagged" , 1);
1171
1172 types_boolean_stash = gv_stashpv ("Types::Serialiser::Boolean", 1);
1173 types_error_stash = gv_stashpv ("Types::Serialiser::Error" , 1);
1174
1175 types_true = get_bool ("Types::Serialiser::true" );
1176 types_false = get_bool ("Types::Serialiser::false");
1177 types_error = get_bool ("Types::Serialiser::error");
1178
1179 default_filter = newSVpv ("CBOR::XS::default_filter", 0);
1180
1181 sv_cbor = newSVpv ("CBOR", 0);
1182 SvREADONLY_on (sv_cbor);
1183 }
1184
1185 PROTOTYPES: DISABLE
1186
1187 void CLONE (...)
1188 CODE:
1189 cbor_stash = 0;
1190 cbor_tagged_stash = 0;
1191 types_error_stash = 0;
1192 types_boolean_stash = 0;
1193
1194 void new (char *klass)
1195 PPCODE:
1196 {
1197 SV *pv = NEWSV (0, sizeof (CBOR));
1198 SvPOK_only (pv);
1199 cbor_init ((CBOR *)SvPVX (pv));
1200 XPUSHs (sv_2mortal (sv_bless (
1201 newRV_noinc (pv),
1202 strEQ (klass, "CBOR::XS") ? CBOR_STASH : gv_stashpv (klass, 1)
1203 )));
1204 }
1205
1206 void shrink (CBOR *self, int enable = 1)
1207 ALIAS:
1208 shrink = F_SHRINK
1209 allow_unknown = F_ALLOW_UNKNOWN
1210 allow_sharing = F_ALLOW_SHARING
1211 pack_strings = F_PACK_STRINGS
1212 PPCODE:
1213 {
1214 if (enable)
1215 self->flags |= ix;
1216 else
1217 self->flags &= ~ix;
1218
1219 XPUSHs (ST (0));
1220 }
1221
1222 void get_shrink (CBOR *self)
1223 ALIAS:
1224 get_shrink = F_SHRINK
1225 get_allow_unknown = F_ALLOW_UNKNOWN
1226 get_allow_sharing = F_ALLOW_SHARING
1227 get_pack_strings = F_PACK_STRINGS
1228 PPCODE:
1229 XPUSHs (boolSV (self->flags & ix));
1230
1231 void max_depth (CBOR *self, U32 max_depth = 0x80000000UL)
1232 PPCODE:
1233 self->max_depth = max_depth;
1234 XPUSHs (ST (0));
1235
1236 U32 get_max_depth (CBOR *self)
1237 CODE:
1238 RETVAL = self->max_depth;
1239 OUTPUT:
1240 RETVAL
1241
1242 void max_size (CBOR *self, U32 max_size = 0)
1243 PPCODE:
1244 self->max_size = max_size;
1245 XPUSHs (ST (0));
1246
1247 int get_max_size (CBOR *self)
1248 CODE:
1249 RETVAL = self->max_size;
1250 OUTPUT:
1251 RETVAL
1252
1253 void filter (CBOR *self, SV *filter = 0)
1254 PPCODE:
1255 SvREFCNT_dec (self->filter);
1256 self->filter = filter ? newSVsv (filter) : filter;
1257 XPUSHs (ST (0));
1258
1259 SV *get_filter (CBOR *self)
1260 CODE:
1261 RETVAL = self->filter ? self->filter : NEWSV (0, 0);
1262 OUTPUT:
1263 RETVAL
1264
1265 void encode (CBOR *self, SV *scalar)
1266 PPCODE:
1267 PUTBACK; scalar = encode_cbor (scalar, self); SPAGAIN;
1268 XPUSHs (scalar);
1269
1270 void decode (CBOR *self, SV *cborstr)
1271 PPCODE:
1272 PUTBACK; cborstr = decode_cbor (cborstr, self, 0); SPAGAIN;
1273 XPUSHs (cborstr);
1274
1275 void decode_prefix (CBOR *self, SV *cborstr)
1276 PPCODE:
1277 {
1278 SV *sv;
1279 char *offset;
1280 PUTBACK; sv = decode_cbor (cborstr, self, &offset); SPAGAIN;
1281 EXTEND (SP, 2);
1282 PUSHs (sv);
1283 PUSHs (sv_2mortal (newSVuv (offset - SvPVX (cborstr))));
1284 }
1285
1286 void DESTROY (CBOR *self)
1287 PPCODE:
1288 cbor_free (self);
1289
1290 PROTOTYPES: ENABLE
1291
1292 void encode_cbor (SV *scalar)
1293 PPCODE:
1294 {
1295 CBOR cbor;
1296 cbor_init (&cbor);
1297 PUTBACK; scalar = encode_cbor (scalar, &cbor); SPAGAIN;
1298 XPUSHs (scalar);
1299 }
1300
1301 void decode_cbor (SV *cborstr)
1302 PPCODE:
1303 {
1304 CBOR cbor;
1305 cbor_init (&cbor);
1306 PUTBACK; cborstr = decode_cbor (cborstr, &cbor, 0); SPAGAIN;
1307 XPUSHs (cborstr);
1308 }
1309