ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/XS.xs
Revision: 1.27
Committed: Fri Nov 22 15:28:38 2013 UTC (10 years, 5 months ago) by root
Branch: MAIN
CVS Tags: rel-0_09
Changes since 1.26: +62 -9 lines
Log Message:
*** empty log message ***

File Contents

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