ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Convert-BER-XS/XS.xs
Revision: 1.12
Committed: Sat Apr 20 12:35:03 2019 UTC (5 years, 1 month ago) by root
Branch: MAIN
Changes since 1.11: +4 -1 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 root 1.12 // C99 required!
6     // this is not just for comments, but also for
7     // integer constant semantics,
8     // sscanf format modifiers and more.
9 root 1.1
10     enum {
11     // ASN_TAG
12     ASN_BOOLEAN = 0x01,
13     ASN_INTEGER32 = 0x02,
14     ASN_BIT_STRING = 0x03,
15     ASN_OCTET_STRING = 0x04,
16     ASN_NULL = 0x05,
17     ASN_OBJECT_IDENTIFIER = 0x06,
18 root 1.8 ASN_OID = 0x06,
19     ASN_OBJECT_DESCRIPTOR = 0x07,
20     ASN_EXTERNAL = 0x08,
21     ASN_REAL = 0x09,
22     ASN_ENUMERATED = 0x0a,
23     ASN_EMBEDDED_PDV = 0x0b,
24     ASN_UTF8_STRING = 0x0c,
25     ASN_RELATIVE_OID = 0x0d,
26 root 1.1 ASN_SEQUENCE = 0x10,
27 root 1.8 ASN_SET = 0x11,
28     ASN_NUMERIC_STRING = 0x12,
29     ASN_PRINTABLE_STRING = 0x13,
30     ASN_TELETEX_STRING = 0x14,
31     ASN_T61_STRING = 0x14,
32     ASN_VIDEOTEX_STRING = 0x15,
33     ASN_IA5_STRING = 0x16,
34     ASN_ASCII_STRING = 0x16,
35     ASN_UTC_TIME = 0x17,
36     ASN_GENERALIZED_TIME = 0x18,
37     ASN_GRAPHIC_STRING = 0x19,
38     ASN_VISIBLE_STRING = 0x1a,
39     ASN_ISO646_STRING = 0x1a,
40     ASN_GENERAL_STRING = 0x1b,
41     ASN_UNIVERSAL_STRING = 0x1c,
42     ASN_CHARACTER_STRING = 0x1d,
43     ASN_BMP_STRING = 0x1e,
44 root 1.1
45     ASN_TAG_BER = 0x1f,
46     ASN_TAG_MASK = 0x1f,
47    
48     // primitive/constructed
49     ASN_CONSTRUCTED = 0x20,
50    
51     // ASN_CLASS
52     ASN_UNIVERSAL = 0x00,
53 root 1.5 ASN_APPLICATION = 0x01,
54     ASN_CONTEXT = 0x02,
55     ASN_PRIVATE = 0x03,
56 root 1.1
57     ASN_CLASS_MASK = 0xc0,
58     ASN_CLASS_SHIFT = 6,
59    
60 root 1.2 // ASN_APPLICATION SNMP
61 root 1.3 SNMP_IPADDRESS = 0x00,
62     SNMP_COUNTER32 = 0x01,
63     SNMP_UNSIGNED32 = 0x02,
64     SNMP_TIMETICKS = 0x03,
65     SNMP_OPAQUE = 0x04,
66     SNMP_COUNTER64 = 0x06,
67 root 1.1 };
68    
69     enum {
70 root 1.5 BER_TYPE_BYTES,
71     BER_TYPE_UTF8,
72     BER_TYPE_UCS2,
73     BER_TYPE_UCS4,
74     BER_TYPE_INT,
75     BER_TYPE_OID,
76     BER_TYPE_RELOID,
77     BER_TYPE_NULL,
78     BER_TYPE_BOOL,
79     BER_TYPE_REAL,
80 root 1.6 BER_TYPE_IPADDRESS,
81 root 1.5 BER_TYPE_CROAK,
82     };
83    
84     enum {
85 root 1.1 BER_CLASS = 0,
86     BER_TAG = 1,
87     BER_CONSTRUCTED = 2,
88     BER_DATA = 3,
89     BER_ARRAYSIZE
90     };
91    
92     #define MAX_OID_STRLEN 4096
93    
94 root 1.5 typedef void profile_type;
95    
96     static profile_type *cur_profile, *default_profile;
97 root 1.3 static SV *buf_sv; // encoding buffer
98     static U8 *buf, *cur, *end; // buffer start, current, end
99    
100 root 1.9 #if PERL_VERSION < 18
101     # define utf8_to_uvchr_buf(s,e,l) utf8_to_uvchr (s, l)
102     #endif
103    
104 root 1.3 #if __GNUC__ >= 3
105     # define expect(expr,value) __builtin_expect ((expr), (value))
106     # define INLINE static inline
107     #else
108     # define expect(expr,value) (expr)
109     # define INLINE static
110     #endif
111    
112     #define expect_false(expr) expect ((expr) != 0, 0)
113     #define expect_true(expr) expect ((expr) != 0, 1)
114 root 1.1
115 root 1.5 /////////////////////////////////////////////////////////////////////////////
116    
117     static SV *sviv_cache[32];
118    
119 root 1.1 // for "small" integers, return a readonly sv, otherwise create a new one
120     static SV *newSVcacheint (int val)
121     {
122 root 1.5 if (expect_false (val < 0 || val >= sizeof (sviv_cache)))
123 root 1.1 return newSViv (val);
124    
125 root 1.5 if (expect_false (!sviv_cache [val]))
126 root 1.1 {
127 root 1.5 sviv_cache [val] = newSVuv (val);
128     SvREADONLY_on (sviv_cache [val]);
129 root 1.1 }
130    
131 root 1.5 return SvREFCNT_inc_NN (sviv_cache [val]);
132     }
133    
134     /////////////////////////////////////////////////////////////////////////////
135    
136     static HV *profile_stash;
137    
138     static profile_type *
139     SvPROFILE (SV *profile)
140     {
141     if (!SvOK (profile))
142 root 1.6 return default_profile;
143 root 1.5
144     if (!SvROK (profile))
145     croak ("invalid profile");
146    
147     profile = SvRV (profile);
148    
149     if (SvSTASH (profile) != profile_stash)
150     croak ("invalid profile object");
151    
152     return (void *)profile;
153     }
154    
155     static int
156     profile_lookup (profile_type *profile, int klass, int tag)
157     {
158     SV *sv = (SV *)profile;
159     U32 idx = (tag << 2) + klass;
160    
161     if (expect_false (idx >= SvCUR (sv)))
162     return BER_TYPE_BYTES;
163    
164     return SvPVX (sv)[idx];
165     }
166    
167 root 1.10 static void
168 root 1.5 profile_set (profile_type *profile, int klass, int tag, int type)
169     {
170     SV *sv = (SV *)profile;
171     U32 idx = (tag << 2) + klass;
172     STRLEN oldlen = SvCUR (sv);
173     STRLEN newlen = idx + 2;
174    
175     if (idx >= oldlen)
176     {
177     sv_grow (sv, newlen);
178     memset (SvPVX (sv) + oldlen, BER_TYPE_BYTES, newlen - oldlen);
179     SvCUR_set (sv, newlen);
180     }
181    
182     SvPVX (sv)[idx] = type;
183     }
184    
185     static SV *
186     profile_new ()
187     {
188     SV *sv = newSVpvn ("", 0);
189    
190     static const struct {
191     int klass;
192     int tag;
193     int type;
194     } *celem, default_map[] = {
195     { ASN_UNIVERSAL, ASN_BOOLEAN , BER_TYPE_BOOL },
196     { ASN_UNIVERSAL, ASN_INTEGER32 , BER_TYPE_INT },
197     { ASN_UNIVERSAL, ASN_NULL , BER_TYPE_NULL },
198     { ASN_UNIVERSAL, ASN_OBJECT_IDENTIFIER, BER_TYPE_OID },
199     { ASN_UNIVERSAL, ASN_OBJECT_DESCRIPTOR, BER_TYPE_OID },
200     { ASN_UNIVERSAL, ASN_RELATIVE_OID , BER_TYPE_RELOID },
201     { ASN_UNIVERSAL, ASN_REAL , BER_TYPE_REAL },
202     { ASN_UNIVERSAL, ASN_UTF8_STRING , BER_TYPE_UTF8 },
203     { ASN_UNIVERSAL, ASN_BMP_STRING , BER_TYPE_UCS2 },
204     { ASN_UNIVERSAL, ASN_UNIVERSAL_STRING , BER_TYPE_UCS4 },
205     };
206    
207 root 1.11 for (celem = default_map + sizeof (default_map) / sizeof (default_map [0]); celem-- > default_map; )
208     profile_set ((profile_type *)sv, celem->klass, celem->tag, celem->type);
209 root 1.5
210     return sv_bless (newRV_noinc (sv), profile_stash);
211 root 1.1 }
212    
213     /////////////////////////////////////////////////////////////////////////////
214 root 1.3 // decoder
215 root 1.1
216     static void
217     error (const char *errmsg)
218     {
219     croak ("%s at offset 0x%04x", errmsg, cur - buf);
220     }
221    
222 root 1.3 static void
223     want (UV count)
224 root 1.1 {
225 root 1.3 if (expect_false ((uintptr_t)(end - cur) < count))
226     error ("unexpected end of message buffer");
227 root 1.1 }
228    
229 root 1.2 // get_* functions fetch something from the buffer
230     // decode_* functions use get_* fun ctions to decode ber values
231    
232 root 1.3 // get n octets
233 root 1.1 static U8 *
234 root 1.3 get_n (UV count)
235 root 1.1 {
236 root 1.3 want (count);
237 root 1.1 U8 *res = cur;
238     cur += count;
239     return res;
240     }
241    
242 root 1.3 // get single octet
243 root 1.1 static U8
244 root 1.2 get_u8 (void)
245 root 1.1 {
246 root 1.3 if (cur == end)
247     error ("unexpected end of message buffer");
248 root 1.1
249     return *cur++;
250     }
251    
252 root 1.3 // get ber-encoded integer (i.e. pack "w")
253 root 1.1 static U32
254 root 1.3 get_w (void)
255 root 1.1 {
256     U32 res = 0;
257    
258     for (;;)
259     {
260 root 1.2 U8 c = get_u8 ();
261 root 1.1 res = (res << 7) | (c & 0x7f);
262    
263     if (!(c & 0x80))
264     return res;
265     }
266     }
267    
268     static U32
269 root 1.2 get_length (void)
270 root 1.1 {
271 root 1.2 U32 res = get_u8 ();
272 root 1.1
273     if (res & 0x80)
274     {
275     int cnt = res & 0x7f;
276     res = 0;
277    
278     switch (cnt)
279     {
280     case 0:
281     error ("indefinite ASN.1 lengths not supported");
282     return 0;
283    
284     default:
285     error ("ASN.1 length too long");
286     return 0;
287    
288 root 1.2 case 4: res = (res << 8) | get_u8 ();
289     case 3: res = (res << 8) | get_u8 ();
290     case 2: res = (res << 8) | get_u8 ();
291     case 1: res = (res << 8) | get_u8 ();
292 root 1.1 }
293     }
294    
295     return res;
296     }
297    
298     static SV *
299 root 1.5 decode_int ()
300 root 1.1 {
301 root 1.5 int len = get_length ();
302 root 1.1
303 root 1.5 if (len <= 0)
304 root 1.1 {
305 root 1.5 error ("integer length equal to zero");
306 root 1.1 return 0;
307     }
308    
309 root 1.5 U8 *data = get_n (len);
310 root 1.1
311 root 1.5 int negative = data [0] & 0x80;
312 root 1.1
313 root 1.5 UV val = negative ? -1 : 0; // copy signbit to all bits
314 root 1.1
315 root 1.5 do
316     val = (val << 8) | *data++;
317     while (--len);
318 root 1.1
319 root 1.6 // the cast to IV relies on implementation-defined behaviour (two's complement cast)
320 root 1.5 // but that's ok, as perl relies on it as well.
321     return negative ? newSViv ((IV)val) : newSVuv (val);
322 root 1.1 }
323    
324     static SV *
325 root 1.5 decode_data (void)
326 root 1.1 {
327 root 1.5 U32 len = get_length ();
328     U8 *data = get_n (len);
329     return newSVpvn ((char *)data, len);
330 root 1.1 }
331    
332 root 1.2 // gelper for decode_object_identifier
333 root 1.1 static char *
334     write_uv (char *buf, U32 u)
335     {
336     // the one-digit case is absolutely predominant, so this pays off (hopefully)
337 root 1.5 if (expect_true (u < 10))
338 root 1.1 *buf++ = u + '0';
339     else
340     {
341     char *beg = buf;
342    
343     do
344     {
345     *buf++ = u % 10 + '0';
346     u /= 10;
347     }
348     while (u);
349    
350     // reverse digits
351 root 1.11 char *ptr = buf;
352     while (--ptr != beg)
353 root 1.1 {
354     char c = *ptr;
355     *ptr = *beg;
356     *beg = c;
357 root 1.11 ++beg;
358 root 1.1 }
359     }
360    
361     return buf;
362     }
363    
364     static SV *
365 root 1.5 decode_oid (int relative)
366 root 1.1 {
367 root 1.5 U32 len = get_length ();
368 root 1.1
369 root 1.5 if (len <= 0)
370 root 1.1 {
371     error ("OBJECT IDENTIFIER length equal to zero");
372     return &PL_sv_undef;
373     }
374    
375 root 1.5 U8 *end = cur + len;
376 root 1.3 U32 w = get_w ();
377 root 1.1
378     static char oid[MAX_OID_STRLEN]; // must be static
379     char *app = oid;
380    
381 root 1.5 if (relative)
382     app = write_uv (app, w);
383     else
384     {
385     app = write_uv (app, (U8)w / 40);
386     *app++ = '.';
387     app = write_uv (app, (U8)w % 40);
388     }
389 root 1.1
390     // we assume an oid component is never > 64 bytes
391     while (cur < end && oid + sizeof (oid) - app > 64)
392     {
393 root 1.3 w = get_w ();
394 root 1.1 *app++ = '.';
395     app = write_uv (app, w);
396     }
397    
398     return newSVpvn (oid, app - oid);
399     }
400    
401 root 1.7 // TODO: this is unacceptably slow
402     static SV *
403     decode_ucs (int chrsize)
404     {
405     SV *res = NEWSV (0, 0);
406    
407     U32 len = get_length ();
408    
409     if (len & (chrsize - 1))
410     croak ("BER_TYPE_UCS has an invalid number of octets (%d)", len);
411    
412     while (len)
413     {
414     U8 b1 = get_u8 ();
415     U8 b2 = get_u8 ();
416     U32 chr = (b1 << 8) | b2;
417    
418     if (chrsize == 4)
419     {
420     U8 b3 = get_u8 ();
421     U8 b4 = get_u8 ();
422     chr = (chr << 16) | (b3 << 8) | b4;
423     }
424    
425     U8 uchr [UTF8_MAXBYTES];
426     int uclen = uvuni_to_utf8 (uchr, chr) - uchr;
427    
428     sv_catpvn (res, (const char *)uchr, uclen);
429     len -= chrsize;
430     }
431    
432     SvUTF8_on (res);
433    
434     return res;
435     }
436    
437 root 1.1 static SV *
438 root 1.2 decode_ber ()
439 root 1.1 {
440 root 1.2 int identifier = get_u8 ();
441 root 1.1
442     SV *res;
443    
444 root 1.5 int constructed = identifier & ASN_CONSTRUCTED;
445     int klass = (identifier & ASN_CLASS_MASK) >> ASN_CLASS_SHIFT;
446     int tag = identifier & ASN_TAG_MASK;
447 root 1.1
448     if (tag == ASN_TAG_BER)
449 root 1.3 tag = get_w ();
450 root 1.1
451     if (tag == ASN_TAG_BER)
452 root 1.3 tag = get_w ();
453 root 1.1
454     if (constructed)
455     {
456 root 1.2 U32 len = get_length ();
457 root 1.1 U32 seqend = (cur - buf) + len;
458     AV *av = (AV *)sv_2mortal ((SV *)newAV ());
459    
460     while (cur < buf + seqend)
461 root 1.2 av_push (av, decode_ber ());
462 root 1.1
463     if (cur > buf + seqend)
464     croak ("constructed type %02x overflow (%x %x)\n", identifier, cur - buf, seqend);
465    
466     res = newRV_inc ((SV *)av);
467     }
468     else
469 root 1.5 switch (profile_lookup (cur_profile, klass, tag))
470 root 1.1 {
471 root 1.5 case BER_TYPE_NULL:
472 root 1.1 res = &PL_sv_undef;
473     break;
474    
475 root 1.5 case BER_TYPE_BOOL:
476     {
477     U32 len = get_length ();
478    
479     if (len != 1)
480 root 1.6 croak ("BER_TYPE_BOOLEAN type with invalid length %d encountered", len);
481 root 1.5
482     res = newSVcacheint (get_u8 () ? 0 : 1);
483     }
484     break;
485    
486     case BER_TYPE_OID:
487     res = decode_oid (0);
488 root 1.1 break;
489    
490 root 1.5 case BER_TYPE_RELOID:
491     res = decode_oid (1);
492 root 1.1 break;
493    
494 root 1.5 case BER_TYPE_INT:
495     res = decode_int ();
496 root 1.1 break;
497    
498 root 1.5 case BER_TYPE_UTF8:
499     res = decode_data ();
500     SvUTF8_on (res);
501 root 1.1 break;
502    
503 root 1.5 case BER_TYPE_BYTES:
504     res = decode_data ();
505 root 1.1 break;
506    
507 root 1.6 case BER_TYPE_IPADDRESS:
508     {
509     U32 len = get_length ();
510    
511     if (len != 4)
512     croak ("BER_TYPE_IPADDRESS type with invalid length %d encountered", len);
513    
514     U8 c1 = get_u8 ();
515     U8 c2 = get_u8 ();
516     U8 c3 = get_u8 ();
517     U8 c4 = get_u8 ();
518    
519     res = newSVpvf ("%d.%d.%d.%d", c1, c2, c3, c4);
520     }
521     break;
522    
523 root 1.5 case BER_TYPE_UCS2:
524 root 1.7 res = decode_ucs (2);
525     break;
526    
527 root 1.5 case BER_TYPE_UCS4:
528 root 1.7 res = decode_ucs (4);
529     break;
530    
531     case BER_TYPE_REAL:
532 root 1.5 case BER_TYPE_CROAK:
533 root 1.1 default:
534 root 1.5 croak ("unconfigured/unsupported class/tag %d/%d", klass, tag);
535 root 1.1 }
536    
537     AV *av = newAV ();
538     av_fill (av, BER_ARRAYSIZE - 1);
539 root 1.5 AvARRAY (av)[BER_CLASS ] = newSVcacheint (klass);
540 root 1.1 AvARRAY (av)[BER_TAG ] = newSVcacheint (tag);
541     AvARRAY (av)[BER_CONSTRUCTED] = newSVcacheint (constructed ? 1 : 0);
542     AvARRAY (av)[BER_DATA ] = res;
543    
544     return newRV_noinc ((SV *)av);
545     }
546    
547 root 1.3 /////////////////////////////////////////////////////////////////////////////
548     // encoder
549    
550     /* adds two STRLENs together, slow, and with paranoia */
551     static STRLEN
552     strlen_sum (STRLEN l1, STRLEN l2)
553     {
554     size_t sum = l1 + l2;
555    
556     if (sum < (size_t)l2 || sum != (size_t)(STRLEN)sum)
557     croak ("JSON::XS: string size overflow");
558    
559     return sum;
560     }
561    
562     static void
563     set_buf (SV *sv)
564     {
565     STRLEN len;
566     buf_sv = sv;
567 root 1.10 buf = (U8 *)SvPVbyte (buf_sv, len);
568 root 1.3 cur = buf;
569     end = buf + len;
570     }
571    
572     /* similar to SvGROW, but somewhat safer and guarantees exponential realloc strategy */
573     static char *
574     my_sv_grow (SV *sv, size_t len1, size_t len2)
575     {
576     len1 = strlen_sum (len1, len2);
577     len1 = strlen_sum (len1, len1 >> 1);
578    
579     if (len1 > 4096 - 24)
580     len1 = (len1 | 4095) - 24;
581    
582     return SvGROW (sv, len1);
583     }
584    
585     static void
586     need (STRLEN len)
587     {
588     if (expect_false ((uintptr_t)(end - cur) < len))
589     {
590     STRLEN pos = cur - buf;
591 root 1.10 buf = (U8 *)my_sv_grow (buf_sv, pos, len);
592 root 1.3 cur = buf + pos;
593     end = buf + SvLEN (buf_sv) - 1;
594     }
595     }
596    
597     static void
598     put_u8 (int val)
599     {
600     need (1);
601     *cur++ = val;
602     }
603    
604     static void
605     put_w_nocheck (U32 val)
606     {
607     *cur = (val >> 7 * 4) | 0x80; cur += val >= (1 << (7 * 4));
608     *cur = (val >> 7 * 3) | 0x80; cur += val >= (1 << (7 * 3));
609     *cur = (val >> 7 * 2) | 0x80; cur += val >= (1 << (7 * 2));
610     *cur = (val >> 7 * 1) | 0x80; cur += val >= (1 << (7 * 1));
611     *cur = val & 0x7f; cur += 1;
612     }
613    
614     static void
615     put_w (U32 val)
616     {
617     need (5); // we only handle up to 5 bytes
618    
619     put_w_nocheck (val);
620     }
621    
622     static U8 *
623     put_length_at (U32 val, U8 *cur)
624     {
625     if (val < 0x7fU)
626     *cur++ = val;
627     else
628     {
629     U8 *lenb = cur++;
630    
631     *cur = val >> 24; cur += *cur > 0;
632     *cur = val >> 16; cur += *cur > 0;
633     *cur = val >> 8; cur += *cur > 0;
634     *cur = val ; cur += 1;
635    
636     *lenb = 0x80 + cur - lenb - 1;
637     }
638    
639     return cur;
640     }
641    
642     static void
643     put_length (U32 val)
644     {
645 root 1.7 need (5 + val);
646 root 1.3 cur = put_length_at (val, cur);
647     }
648    
649     // return how many bytes the encoded length requires
650     static int length_length (U32 val)
651     {
652     return val < 0x7fU
653     ? 1
654     : 2 + (val > 0xffU) + (val > 0xffffU) + (val > 0xffffffU);
655     }
656    
657     static void
658 root 1.5 encode_data (const char *ptr, STRLEN len)
659 root 1.3 {
660     put_length (len);
661     memcpy (cur, ptr, len);
662     cur += len;
663     }
664    
665     static void
666 root 1.5 encode_uv (UV uv)
667     {
668     }
669    
670     static void
671     encode_int (SV *sv)
672 root 1.3 {
673 root 1.5 need (8 + 1 + 1); // 64 bit + length + extra 0
674    
675     if (expect_false (!SvIOK (sv)))
676     sv_2iv_flags (sv, 0);
677 root 1.3
678     U8 *lenb = cur++;
679    
680 root 1.5 if (SvIOK_notUV (sv))
681 root 1.3 {
682 root 1.5 IV iv = SvIVX (sv);
683    
684     if (expect_false (iv < 0))
685     {
686     // get two's complement bit pattern - works even on hypothetical non-2c machines
687     UV uv = iv;
688    
689     #if UVSIZE > 4
690     *cur = uv >> 56; cur += !!(~uv & 0xff80000000000000U);
691     *cur = uv >> 48; cur += !!(~uv & 0xffff800000000000U);
692     *cur = uv >> 40; cur += !!(~uv & 0xffffff8000000000U);
693     *cur = uv >> 32; cur += !!(~uv & 0xffffffff80000000U);
694     #endif
695     *cur = uv >> 24; cur += !!(~uv & 0xffffffffff800000U);
696     *cur = uv >> 16; cur += !!(~uv & 0xffffffffffff8000U);
697     *cur = uv >> 8; cur += !!(~uv & 0xffffffffffffff80U);
698     *cur = uv ; cur += 1;
699    
700     *lenb = cur - lenb - 1;
701 root 1.3
702 root 1.5 return;
703     }
704 root 1.3 }
705    
706 root 1.5 UV uv = SvUV (sv);
707 root 1.3
708 root 1.5 // prepend an extra 0 if the high bit is 1
709     *cur = 0; cur += !!(uv & ((UV)1 << (UVSIZE * 8 - 1)));
710 root 1.3
711 root 1.5 #if UVSIZE > 4
712     *cur = uv >> 56; cur += !!(uv & 0xff80000000000000U);
713     *cur = uv >> 48; cur += !!(uv & 0xffff800000000000U);
714     *cur = uv >> 40; cur += !!(uv & 0xffffff8000000000U);
715     *cur = uv >> 32; cur += !!(uv & 0xffffffff80000000U);
716     #endif
717     *cur = uv >> 24; cur += !!(uv & 0xffffffffff800000U);
718     *cur = uv >> 16; cur += !!(uv & 0xffffffffffff8000U);
719     *cur = uv >> 8; cur += !!(uv & 0xffffffffffffff80U);
720 root 1.3 *cur = uv ; cur += 1;
721    
722     *lenb = cur - lenb - 1;
723     }
724    
725     // we don't know the length yet, so we optimistically
726     // assume the length will need one octet later. if that
727     // turns out to be wrong, we memove as needed.
728     // mark the beginning
729     static STRLEN
730     len_fixup_mark ()
731     {
732     return cur++ - buf;
733     }
734    
735     // patch up the length
736     static void
737     len_fixup (STRLEN mark)
738     {
739     STRLEN reallen = (cur - buf) - mark - 1;
740     int lenlen = length_length (reallen);
741    
742     if (expect_false (lenlen > 1))
743     {
744     // bad luck, we have to shift the bytes to make room for the length
745     need (5);
746     memmove (buf + mark + lenlen, buf + mark + 1, reallen);
747     cur += lenlen - 1;
748     }
749    
750     put_length_at (reallen, buf + mark);
751     }
752    
753     static char *
754     read_uv (char *str, UV *uv)
755     {
756     UV r = 0;
757    
758     while (*str >= '0')
759     r = r * 10 + *str++ - '0';
760    
761     *uv = r;
762    
763     str += !!*str; // advance over any non-zero byte
764    
765     return str;
766     }
767    
768     static void
769 root 1.5 encode_oid (SV *oid, int relative)
770 root 1.3 {
771 root 1.5 STRLEN len;
772     char *ptr = SvPV (oid, len); // utf8 vs. bytes does not matter
773 root 1.3
774     // we need at most as many octets as the string form
775 root 1.5 need (len + 1);
776 root 1.3 STRLEN mark = len_fixup_mark ();
777    
778     UV w1, w2;
779    
780 root 1.5 if (!relative)
781     {
782     ptr = read_uv (ptr, &w1);
783     ptr = read_uv (ptr, &w2);
784 root 1.3
785 root 1.5 put_w_nocheck (w1 * 40 + w2);
786     }
787 root 1.3
788     while (*ptr)
789     {
790     ptr = read_uv (ptr, &w1);
791     put_w_nocheck (w1);
792     }
793    
794     len_fixup (mark);
795     }
796    
797 root 1.5 // check whether an SV is a BER tuple and returns its AV *
798 root 1.4 static AV *
799     ber_tuple (SV *tuple)
800 root 1.3 {
801 root 1.4 SV *rv;
802    
803     if (expect_false (!SvROK (tuple) || SvTYPE ((rv = SvRV (tuple))) != SVt_PVAV))
804 root 1.3 croak ("BER tuple must be array-reference");
805    
806 root 1.4 if (expect_false (SvRMAGICAL (rv)))
807     croak ("BER tuple must not be tied");
808 root 1.3
809 root 1.4 if (expect_false (AvFILL ((AV *)rv) != BER_ARRAYSIZE - 1))
810     croak ("BER tuple must contain exactly %d elements, not %d", BER_ARRAYSIZE, AvFILL ((AV *)rv) + 1);
811 root 1.3
812 root 1.4 return (AV *)rv;
813     }
814    
815     static void
816 root 1.7 encode_ucs (SV *data, int chrsize)
817     {
818     STRLEN uchars = sv_len_utf8 (data);
819     STRLEN len;;
820     char *ptr = SvPVutf8 (data, len);
821    
822     put_length (uchars * chrsize);
823    
824     while (uchars--)
825     {
826     STRLEN uclen;
827 root 1.10 UV uchr = utf8_to_uvchr_buf ((U8 *)ptr, (U8 *)ptr + len, &uclen);
828 root 1.7
829     ptr += uclen;
830     len -= uclen;
831    
832     if (chrsize == 4)
833     {
834     *cur++ = uchr >> 24;
835     *cur++ = uchr >> 16;
836     }
837    
838     *cur++ = uchr >> 8;
839     *cur++ = uchr;
840     }
841     }
842     static void
843 root 1.4 encode_ber (SV *tuple)
844     {
845     AV *av = ber_tuple (tuple);
846 root 1.3
847     int klass = SvIV (AvARRAY (av)[BER_CLASS]);
848     int tag = SvIV (AvARRAY (av)[BER_TAG]);
849     int constructed = SvIV (AvARRAY (av)[BER_CONSTRUCTED]) ? ASN_CONSTRUCTED : 0;
850     SV *data = AvARRAY (av)[BER_DATA];
851    
852     int identifier = (klass << ASN_CLASS_SHIFT) | constructed;
853    
854     if (expect_false (tag >= ASN_TAG_BER))
855     {
856     put_u8 (identifier | ASN_TAG_BER);
857     put_w (tag);
858     }
859     else
860     put_u8 (identifier | tag);
861    
862     if (constructed)
863     {
864     // we optimistically assume that only one length byte is needed
865     // and adjust later
866     need (1);
867     STRLEN mark = len_fixup_mark ();
868    
869     if (expect_false (!SvROK (data) || SvTYPE (SvRV (data)) != SVt_PVAV))
870     croak ("BER constructed data must be array-reference");
871    
872     AV *av = (AV *)SvRV (data);
873     int fill = AvFILL (av);
874    
875     if (expect_false (SvRMAGICAL (av)))
876     croak ("BER constructed data must not be tied");
877    
878 root 1.11 int i;
879     for (i = 0; i <= fill; ++i)
880 root 1.3 encode_ber (AvARRAY (av)[i]);
881    
882     len_fixup (mark);
883     }
884     else
885 root 1.5 switch (profile_lookup (cur_profile, klass, tag))
886 root 1.3 {
887 root 1.5 case BER_TYPE_NULL:
888 root 1.3 put_length (0);
889     break;
890    
891 root 1.5 case BER_TYPE_BOOL:
892     put_length (1);
893 root 1.7 *cur++ = SvTRUE (data) ? 0xff : 0x00;
894 root 1.3 break;
895    
896 root 1.5 case BER_TYPE_OID:
897     encode_oid (data, 0);
898 root 1.3 break;
899    
900 root 1.5 case BER_TYPE_RELOID:
901     encode_oid (data, 1);
902 root 1.3 break;
903    
904 root 1.5 case BER_TYPE_INT:
905     encode_int (data);
906     break;
907    
908     case BER_TYPE_BYTES:
909     {
910     STRLEN len;
911     const char *ptr = SvPVbyte (data, len);
912     encode_data (ptr, len);
913     }
914     break;
915    
916     case BER_TYPE_UTF8:
917     {
918     STRLEN len;
919     const char *ptr = SvPVutf8 (data, len);
920     encode_data (ptr, len);
921     }
922     break;
923    
924 root 1.6 case BER_TYPE_IPADDRESS:
925     {
926     U8 ip[4];
927     sscanf (SvPV_nolen (data), "%hhu.%hhu.%hhu.%hhu", ip + 0, ip + 1, ip + 2, ip + 3);
928     encode_data ((const char *)ip, sizeof (ip));
929     }
930     break;
931    
932 root 1.5 case BER_TYPE_UCS2:
933 root 1.7 encode_ucs (data, 2);
934     break;
935    
936 root 1.5 case BER_TYPE_UCS4:
937 root 1.7 encode_ucs (data, 4);
938     break;
939    
940     case BER_TYPE_REAL:
941 root 1.5 case BER_TYPE_CROAK:
942 root 1.3 default:
943 root 1.5 croak ("unconfigured/unsupported class/tag %d/%d", klass, tag);
944 root 1.3 }
945    
946     }
947    
948     /////////////////////////////////////////////////////////////////////////////
949    
950 root 1.1 MODULE = Convert::BER::XS PACKAGE = Convert::BER::XS
951    
952     PROTOTYPES: ENABLE
953    
954     BOOT:
955     {
956     HV *stash = gv_stashpv ("Convert::BER::XS", 1);
957    
958 root 1.5 profile_stash = gv_stashpv ("Convert::BER::XS::Profile", 1);
959    
960 root 1.1 static const struct {
961     const char *name;
962     IV iv;
963     } *civ, const_iv[] = {
964 root 1.5 #define const_iv(name) { # name, name },
965     const_iv (ASN_BOOLEAN)
966     const_iv (ASN_INTEGER32)
967     const_iv (ASN_BIT_STRING)
968     const_iv (ASN_OCTET_STRING)
969     const_iv (ASN_NULL)
970     const_iv (ASN_OBJECT_IDENTIFIER)
971     const_iv (ASN_OBJECT_DESCRIPTOR)
972     const_iv (ASN_OID)
973     const_iv (ASN_EXTERNAL)
974     const_iv (ASN_REAL)
975     const_iv (ASN_SEQUENCE)
976     const_iv (ASN_ENUMERATED)
977     const_iv (ASN_EMBEDDED_PDV)
978     const_iv (ASN_UTF8_STRING)
979     const_iv (ASN_RELATIVE_OID)
980     const_iv (ASN_SET)
981     const_iv (ASN_NUMERIC_STRING)
982     const_iv (ASN_PRINTABLE_STRING)
983     const_iv (ASN_TELETEX_STRING)
984     const_iv (ASN_T61_STRING)
985     const_iv (ASN_VIDEOTEX_STRING)
986     const_iv (ASN_IA5_STRING)
987     const_iv (ASN_ASCII_STRING)
988     const_iv (ASN_UTC_TIME)
989     const_iv (ASN_GENERALIZED_TIME)
990     const_iv (ASN_GRAPHIC_STRING)
991     const_iv (ASN_VISIBLE_STRING)
992     const_iv (ASN_ISO646_STRING)
993     const_iv (ASN_GENERAL_STRING)
994     const_iv (ASN_UNIVERSAL_STRING)
995     const_iv (ASN_CHARACTER_STRING)
996     const_iv (ASN_BMP_STRING)
997    
998     const_iv (ASN_UNIVERSAL)
999     const_iv (ASN_APPLICATION)
1000     const_iv (ASN_CONTEXT)
1001     const_iv (ASN_PRIVATE)
1002    
1003     const_iv (BER_CLASS)
1004     const_iv (BER_TAG)
1005     const_iv (BER_CONSTRUCTED)
1006     const_iv (BER_DATA)
1007    
1008     const_iv (BER_TYPE_BYTES)
1009     const_iv (BER_TYPE_UTF8)
1010     const_iv (BER_TYPE_UCS2)
1011     const_iv (BER_TYPE_UCS4)
1012     const_iv (BER_TYPE_INT)
1013     const_iv (BER_TYPE_OID)
1014     const_iv (BER_TYPE_RELOID)
1015     const_iv (BER_TYPE_NULL)
1016     const_iv (BER_TYPE_BOOL)
1017     const_iv (BER_TYPE_REAL)
1018 root 1.6 const_iv (BER_TYPE_IPADDRESS)
1019 root 1.5 const_iv (BER_TYPE_CROAK)
1020    
1021     const_iv (SNMP_IPADDRESS)
1022     const_iv (SNMP_COUNTER32)
1023     const_iv (SNMP_UNSIGNED32)
1024     const_iv (SNMP_TIMETICKS)
1025     const_iv (SNMP_OPAQUE)
1026     const_iv (SNMP_COUNTER64)
1027 root 1.1 };
1028    
1029     for (civ = const_iv + sizeof (const_iv) / sizeof (const_iv [0]); civ > const_iv; civ--)
1030     newCONSTSUB (stash, (char *)civ[-1].name, newSViv (civ[-1].iv));
1031     }
1032    
1033     SV *
1034 root 1.5 ber_decode (SV *ber, SV *profile = &PL_sv_undef)
1035 root 1.1 CODE:
1036     {
1037 root 1.5 cur_profile = SvPROFILE (profile);
1038 root 1.3 STRLEN len;
1039 root 1.10 buf = (U8 *)SvPVbyte (ber, len);
1040 root 1.1 cur = buf;
1041 root 1.3 end = buf + len;
1042 root 1.1
1043 root 1.2 RETVAL = decode_ber ();
1044 root 1.1 }
1045     OUTPUT: RETVAL
1046    
1047     void
1048     ber_is (SV *tuple, SV *klass = &PL_sv_undef, SV *tag = &PL_sv_undef, SV *constructed = &PL_sv_undef, SV *data = &PL_sv_undef)
1049     PPCODE:
1050     {
1051     if (!SvOK (tuple))
1052     XSRETURN_NO;
1053    
1054     if (!SvROK (tuple) || SvTYPE (SvRV (tuple)) != SVt_PVAV)
1055 root 1.4 croak ("ber_is: tuple must be BER tuple (array-ref)");
1056 root 1.1
1057     AV *av = (AV *)SvRV (tuple);
1058    
1059     XPUSHs (
1060     (!SvOK (klass) || SvIV (AvARRAY (av)[BER_CLASS ]) == SvIV (klass))
1061     && (!SvOK (tag) || SvIV (AvARRAY (av)[BER_TAG ]) == SvIV (tag))
1062     && (!SvOK (constructed) || !SvIV (AvARRAY (av)[BER_CONSTRUCTED]) == !SvIV (constructed))
1063     && (!SvOK (data) || sv_eq (AvARRAY (av)[BER_DATA ], data))
1064 root 1.4 ? &PL_sv_yes : &PL_sv_undef);
1065 root 1.1 }
1066    
1067     void
1068     ber_is_seq (SV *tuple)
1069     PPCODE:
1070     {
1071     if (!SvOK (tuple))
1072     XSRETURN_UNDEF;
1073    
1074 root 1.4 AV *av = ber_tuple (tuple);
1075 root 1.1
1076     XPUSHs (
1077     SvIV (AvARRAY (av)[BER_CLASS ]) == ASN_UNIVERSAL
1078     && SvIV (AvARRAY (av)[BER_TAG ]) == ASN_SEQUENCE
1079     && SvIV (AvARRAY (av)[BER_CONSTRUCTED])
1080     ? AvARRAY (av)[BER_DATA] : &PL_sv_undef);
1081     }
1082    
1083     void
1084 root 1.4 ber_is_i32 (SV *tuple, SV *value = &PL_sv_undef)
1085 root 1.1 PPCODE:
1086     {
1087     if (!SvOK (tuple))
1088     XSRETURN_NO;
1089    
1090 root 1.4 AV *av = ber_tuple (tuple);
1091 root 1.1
1092 root 1.4 IV data = SvIV (AvARRAY (av)[BER_DATA]);
1093 root 1.1
1094     XPUSHs (
1095 root 1.4 SvIV (AvARRAY (av)[BER_CLASS ]) == ASN_UNIVERSAL
1096     && SvIV (AvARRAY (av)[BER_TAG ]) == ASN_INTEGER32
1097     && !SvIV (AvARRAY (av)[BER_CONSTRUCTED])
1098     && (!SvOK (value) || data == SvIV (value))
1099     ? sv_2mortal (data ? newSViv (data) : newSVpv ("0 but true", 0))
1100     : &PL_sv_undef);
1101 root 1.1 }
1102    
1103     void
1104 root 1.4 ber_is_oid (SV *tuple, SV *oid = &PL_sv_undef)
1105 root 1.1 PPCODE:
1106     {
1107     if (!SvOK (tuple))
1108     XSRETURN_NO;
1109    
1110 root 1.4 AV *av = ber_tuple (tuple);
1111 root 1.1
1112     XPUSHs (
1113     SvIV (AvARRAY (av)[BER_CLASS ]) == ASN_UNIVERSAL
1114     && SvIV (AvARRAY (av)[BER_TAG ]) == ASN_OBJECT_IDENTIFIER
1115     && !SvIV (AvARRAY (av)[BER_CONSTRUCTED])
1116 root 1.4 && (!SvOK (oid) || sv_eq (AvARRAY (av)[BER_DATA], oid))
1117     ? newSVsv (AvARRAY (av)[BER_DATA]) : &PL_sv_undef);
1118 root 1.1 }
1119    
1120 root 1.3 #############################################################################
1121    
1122     void
1123 root 1.5 ber_encode (SV *tuple, SV *profile = &PL_sv_undef)
1124 root 1.3 PPCODE:
1125     {
1126 root 1.5 cur_profile = SvPROFILE (profile);
1127 root 1.3 buf_sv = sv_2mortal (NEWSV (0, 256));
1128     SvPOK_only (buf_sv);
1129     set_buf (buf_sv);
1130    
1131     encode_ber (tuple);
1132    
1133     SvCUR_set (buf_sv, cur - buf);
1134     XPUSHs (buf_sv);
1135     }
1136    
1137 root 1.4 SV *
1138     ber_i32 (IV iv)
1139     CODE:
1140     {
1141     AV *av = newAV ();
1142     av_fill (av, BER_ARRAYSIZE - 1);
1143     AvARRAY (av)[BER_CLASS ] = newSVcacheint (ASN_UNIVERSAL);
1144     AvARRAY (av)[BER_TAG ] = newSVcacheint (ASN_INTEGER32);
1145     AvARRAY (av)[BER_CONSTRUCTED] = newSVcacheint (0);
1146     AvARRAY (av)[BER_DATA ] = newSViv (iv);
1147     RETVAL = newRV_noinc ((SV *)av);
1148     }
1149     OUTPUT: RETVAL
1150    
1151     # TODO: not arrayref, but elements?
1152     SV *
1153     ber_seq (SV *arrayref)
1154     CODE:
1155     {
1156     AV *av = newAV ();
1157     av_fill (av, BER_ARRAYSIZE - 1);
1158     AvARRAY (av)[BER_CLASS ] = newSVcacheint (ASN_UNIVERSAL);
1159     AvARRAY (av)[BER_TAG ] = newSVcacheint (ASN_SEQUENCE);
1160     AvARRAY (av)[BER_CONSTRUCTED] = newSVcacheint (1);
1161     AvARRAY (av)[BER_DATA ] = newSVsv (arrayref);
1162     RETVAL = newRV_noinc ((SV *)av);
1163     }
1164     OUTPUT: RETVAL
1165    
1166 root 1.5 MODULE = Convert::BER::XS PACKAGE = Convert::BER::XS::Profile
1167    
1168     SV *
1169     new (SV *klass)
1170     CODE:
1171     RETVAL = profile_new ();
1172     OUTPUT: RETVAL
1173    
1174 root 1.6 void
1175     set (SV *profile, int klass, int tag, int type)
1176     CODE:
1177     profile_set (SvPROFILE (profile), klass, tag, type);
1178    
1179     IV
1180     get (SV *profile, int klass, int tag)
1181     CODE:
1182     RETVAL = profile_lookup (SvPROFILE (profile), klass, tag);
1183     OUTPUT: RETVAL
1184    
1185     void
1186     _set_default (SV *profile)
1187     CODE:
1188     default_profile = SvPROFILE (profile);
1189    
1190