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