ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Convert-BER-XS/XS.xs
Revision: 1.19
Committed: Sat Apr 20 16:34:34 2019 UTC (5 years, 1 month ago) by root
Branch: MAIN
Changes since 1.18: +16 -2 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 root 1.15 ASN_INTEGER = 0x02,
14 root 1.1 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.16 BER_CLASS = 0,
86     BER_TAG = 1,
87     BER_FLAGS = 2,
88     BER_DATA = 3,
89 root 1.1 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 root 1.14 profile_new (void)
187 root 1.5 {
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 root 1.15 { ASN_UNIVERSAL, ASN_INTEGER , BER_TYPE_INT },
197 root 1.5 { ASN_UNIVERSAL, ASN_NULL , BER_TYPE_NULL },
198     { ASN_UNIVERSAL, ASN_OBJECT_IDENTIFIER, BER_TYPE_OID },
199     { ASN_UNIVERSAL, ASN_RELATIVE_OID , BER_TYPE_RELOID },
200     { ASN_UNIVERSAL, ASN_REAL , BER_TYPE_REAL },
201 root 1.13 { ASN_UNIVERSAL, ASN_ENUMERATED , BER_TYPE_INT },
202 root 1.5 { 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.15 static UV
254 root 1.3 get_w (void)
255 root 1.1 {
256 root 1.15 UV res = 0;
257 root 1.1
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 root 1.19 // get_w, but disallow padding
269     static UV
270     get_w_nopad (void)
271     {
272     U8 first = get_u8 ();
273    
274     if (first == 0x80)
275     error ("illegal BER padding");
276    
277     --cur;
278    
279     return get_w ();
280     }
281    
282 root 1.15 static UV
283 root 1.2 get_length (void)
284 root 1.1 {
285 root 1.15 UV res = get_u8 ();
286 root 1.1
287     if (res & 0x80)
288     {
289     int cnt = res & 0x7f;
290     res = 0;
291    
292     switch (cnt)
293     {
294     case 0:
295     error ("indefinite ASN.1 lengths not supported");
296     return 0;
297    
298 root 1.18 //case 0x80: // indefinite length
299    
300     //case 0xff: reserved
301 root 1.1 default:
302     error ("ASN.1 length too long");
303     return 0;
304    
305 root 1.15 case 8: res = (res << 8) | get_u8 ();
306     case 7: res = (res << 8) | get_u8 ();
307     case 6: res = (res << 8) | get_u8 ();
308     case 5: res = (res << 8) | get_u8 ();
309 root 1.2 case 4: res = (res << 8) | get_u8 ();
310     case 3: res = (res << 8) | get_u8 ();
311     case 2: res = (res << 8) | get_u8 ();
312     case 1: res = (res << 8) | get_u8 ();
313 root 1.1 }
314     }
315    
316     return res;
317     }
318    
319     static SV *
320 root 1.14 decode_int (void)
321 root 1.1 {
322 root 1.15 UV len = get_length ();
323 root 1.1
324 root 1.15 if (!len)
325 root 1.1 {
326 root 1.15 error ("invalid integer length equal to zero");
327 root 1.1 return 0;
328     }
329    
330 root 1.5 U8 *data = get_n (len);
331 root 1.1
332 root 1.5 int negative = data [0] & 0x80;
333 root 1.1
334 root 1.5 UV val = negative ? -1 : 0; // copy signbit to all bits
335 root 1.1
336 root 1.5 do
337     val = (val << 8) | *data++;
338     while (--len);
339 root 1.1
340 root 1.6 // the cast to IV relies on implementation-defined behaviour (two's complement cast)
341 root 1.5 // but that's ok, as perl relies on it as well.
342     return negative ? newSViv ((IV)val) : newSVuv (val);
343 root 1.1 }
344    
345     static SV *
346 root 1.5 decode_data (void)
347 root 1.1 {
348 root 1.15 UV len = get_length ();
349     return newSVpvn ((char *)get_n (len), len);
350 root 1.1 }
351    
352 root 1.15 // helper for decode_object_identifier
353 root 1.1 static char *
354 root 1.15 write_uv (char *buf, UV u)
355 root 1.1 {
356     // the one-digit case is absolutely predominant, so this pays off (hopefully)
357 root 1.5 if (expect_true (u < 10))
358 root 1.1 *buf++ = u + '0';
359     else
360     {
361 root 1.15 // this *could* be done much faster using branchless fixed-point arithmetics
362 root 1.1 char *beg = buf;
363    
364     do
365     {
366     *buf++ = u % 10 + '0';
367     u /= 10;
368     }
369     while (u);
370    
371     // reverse digits
372 root 1.11 char *ptr = buf;
373 root 1.13 while (--ptr > beg)
374 root 1.1 {
375     char c = *ptr;
376     *ptr = *beg;
377     *beg = c;
378 root 1.11 ++beg;
379 root 1.1 }
380     }
381    
382     return buf;
383     }
384    
385     static SV *
386 root 1.5 decode_oid (int relative)
387 root 1.1 {
388 root 1.15 UV len = get_length ();
389 root 1.1
390 root 1.5 if (len <= 0)
391 root 1.1 {
392     error ("OBJECT IDENTIFIER length equal to zero");
393     return &PL_sv_undef;
394     }
395    
396 root 1.5 U8 *end = cur + len;
397 root 1.19 UV w = get_w_nopad ();
398 root 1.1
399 root 1.13 static char oid[MAX_OID_STRLEN]; // static, becaueds too large for stack
400 root 1.1 char *app = oid;
401    
402 root 1.5 if (relative)
403     app = write_uv (app, w);
404 root 1.18 else if (w < 2 * 40)
405 root 1.5 {
406     app = write_uv (app, (U8)w / 40);
407     *app++ = '.';
408     app = write_uv (app, (U8)w % 40);
409     }
410 root 1.18 else
411     {
412     app = write_uv (app, 2);
413     *app++ = '.';
414     app = write_uv (app, w - 2 * 40);
415     }
416 root 1.1
417 root 1.13 while (cur < end)
418 root 1.1 {
419 root 1.13 // we assume an oid component is never > 64 digits
420     if (oid + sizeof (oid) - app < 64)
421     croak ("BER_TYPE_OID to long to decode");
422    
423 root 1.19 w = get_w_nopad ();
424 root 1.1 *app++ = '.';
425     app = write_uv (app, w);
426     }
427    
428     return newSVpvn (oid, app - oid);
429     }
430    
431 root 1.7 // TODO: this is unacceptably slow
432     static SV *
433     decode_ucs (int chrsize)
434     {
435     SV *res = NEWSV (0, 0);
436    
437 root 1.15 UV len = get_length ();
438 root 1.7
439     if (len & (chrsize - 1))
440     croak ("BER_TYPE_UCS has an invalid number of octets (%d)", len);
441    
442     while (len)
443     {
444     U8 b1 = get_u8 ();
445     U8 b2 = get_u8 ();
446     U32 chr = (b1 << 8) | b2;
447    
448     if (chrsize == 4)
449     {
450     U8 b3 = get_u8 ();
451     U8 b4 = get_u8 ();
452     chr = (chr << 16) | (b3 << 8) | b4;
453     }
454    
455     U8 uchr [UTF8_MAXBYTES];
456     int uclen = uvuni_to_utf8 (uchr, chr) - uchr;
457    
458     sv_catpvn (res, (const char *)uchr, uclen);
459     len -= chrsize;
460     }
461    
462     SvUTF8_on (res);
463    
464     return res;
465     }
466    
467 root 1.1 static SV *
468 root 1.14 decode_ber (void)
469 root 1.1 {
470 root 1.2 int identifier = get_u8 ();
471 root 1.1
472     SV *res;
473    
474 root 1.5 int constructed = identifier & ASN_CONSTRUCTED;
475     int klass = (identifier & ASN_CLASS_MASK) >> ASN_CLASS_SHIFT;
476     int tag = identifier & ASN_TAG_MASK;
477 root 1.1
478     if (tag == ASN_TAG_BER)
479 root 1.3 tag = get_w ();
480 root 1.1
481     if (tag == ASN_TAG_BER)
482 root 1.3 tag = get_w ();
483 root 1.1
484     if (constructed)
485     {
486 root 1.15 UV len = get_length ();
487     UV seqend = (cur - buf) + len;
488 root 1.1 AV *av = (AV *)sv_2mortal ((SV *)newAV ());
489    
490     while (cur < buf + seqend)
491 root 1.2 av_push (av, decode_ber ());
492 root 1.1
493     if (cur > buf + seqend)
494     croak ("constructed type %02x overflow (%x %x)\n", identifier, cur - buf, seqend);
495    
496     res = newRV_inc ((SV *)av);
497     }
498     else
499 root 1.5 switch (profile_lookup (cur_profile, klass, tag))
500 root 1.1 {
501 root 1.5 case BER_TYPE_NULL:
502 root 1.13 {
503 root 1.15 UV len = get_length ();
504 root 1.13
505     if (len)
506     croak ("BER_TYPE_NULL value with non-zero length %d encountered", len);
507    
508     res = &PL_sv_undef;
509     }
510 root 1.1 break;
511    
512 root 1.5 case BER_TYPE_BOOL:
513     {
514 root 1.15 UV len = get_length ();
515 root 1.5
516     if (len != 1)
517 root 1.13 croak ("BER_TYPE_BOOLEAN value with invalid length %d encountered", len);
518 root 1.5
519 root 1.13 res = newSVcacheint (!!get_u8 ());
520 root 1.5 }
521     break;
522    
523     case BER_TYPE_OID:
524     res = decode_oid (0);
525 root 1.1 break;
526    
527 root 1.5 case BER_TYPE_RELOID:
528     res = decode_oid (1);
529 root 1.1 break;
530    
531 root 1.5 case BER_TYPE_INT:
532     res = decode_int ();
533 root 1.1 break;
534    
535 root 1.5 case BER_TYPE_UTF8:
536     res = decode_data ();
537     SvUTF8_on (res);
538 root 1.1 break;
539    
540 root 1.5 case BER_TYPE_BYTES:
541     res = decode_data ();
542 root 1.1 break;
543    
544 root 1.6 case BER_TYPE_IPADDRESS:
545     {
546 root 1.15 UV len = get_length ();
547 root 1.6
548     if (len != 4)
549     croak ("BER_TYPE_IPADDRESS type with invalid length %d encountered", len);
550    
551     U8 c1 = get_u8 ();
552     U8 c2 = get_u8 ();
553     U8 c3 = get_u8 ();
554     U8 c4 = get_u8 ();
555    
556     res = newSVpvf ("%d.%d.%d.%d", c1, c2, c3, c4);
557     }
558     break;
559    
560 root 1.5 case BER_TYPE_UCS2:
561 root 1.7 res = decode_ucs (2);
562     break;
563    
564 root 1.5 case BER_TYPE_UCS4:
565 root 1.7 res = decode_ucs (4);
566     break;
567    
568     case BER_TYPE_REAL:
569 root 1.5 case BER_TYPE_CROAK:
570 root 1.1 default:
571 root 1.5 croak ("unconfigured/unsupported class/tag %d/%d", klass, tag);
572 root 1.1 }
573    
574     AV *av = newAV ();
575     av_fill (av, BER_ARRAYSIZE - 1);
576 root 1.16 AvARRAY (av)[BER_CLASS] = newSVcacheint (klass);
577     AvARRAY (av)[BER_TAG ] = newSVcacheint (tag);
578     AvARRAY (av)[BER_FLAGS] = newSVcacheint (constructed ? 1 : 0);
579     AvARRAY (av)[BER_DATA ] = res;
580 root 1.1
581     return newRV_noinc ((SV *)av);
582     }
583    
584 root 1.3 /////////////////////////////////////////////////////////////////////////////
585     // encoder
586    
587     /* adds two STRLENs together, slow, and with paranoia */
588     static STRLEN
589     strlen_sum (STRLEN l1, STRLEN l2)
590     {
591     size_t sum = l1 + l2;
592    
593     if (sum < (size_t)l2 || sum != (size_t)(STRLEN)sum)
594     croak ("JSON::XS: string size overflow");
595    
596     return sum;
597     }
598    
599     static void
600     set_buf (SV *sv)
601     {
602     STRLEN len;
603     buf_sv = sv;
604 root 1.10 buf = (U8 *)SvPVbyte (buf_sv, len);
605 root 1.3 cur = buf;
606     end = buf + len;
607     }
608    
609     /* similar to SvGROW, but somewhat safer and guarantees exponential realloc strategy */
610     static char *
611     my_sv_grow (SV *sv, size_t len1, size_t len2)
612     {
613     len1 = strlen_sum (len1, len2);
614     len1 = strlen_sum (len1, len1 >> 1);
615    
616     if (len1 > 4096 - 24)
617     len1 = (len1 | 4095) - 24;
618    
619     return SvGROW (sv, len1);
620     }
621    
622     static void
623     need (STRLEN len)
624     {
625     if (expect_false ((uintptr_t)(end - cur) < len))
626     {
627     STRLEN pos = cur - buf;
628 root 1.10 buf = (U8 *)my_sv_grow (buf_sv, pos, len);
629 root 1.3 cur = buf + pos;
630     end = buf + SvLEN (buf_sv) - 1;
631     }
632     }
633    
634     static void
635     put_u8 (int val)
636     {
637     need (1);
638     *cur++ = val;
639     }
640    
641     static void
642 root 1.15 put_w_nocheck (UV val)
643 root 1.3 {
644 root 1.15 #if UVSIZE > 4
645     *cur = (val >> 7 * 9) | 0x80; cur += val >= ((UV)1 << (7 * 9));
646     *cur = (val >> 7 * 8) | 0x80; cur += val >= ((UV)1 << (7 * 8));
647     *cur = (val >> 7 * 7) | 0x80; cur += val >= ((UV)1 << (7 * 7));
648     *cur = (val >> 7 * 6) | 0x80; cur += val >= ((UV)1 << (7 * 6));
649     *cur = (val >> 7 * 5) | 0x80; cur += val >= ((UV)1 << (7 * 5));
650     #endif
651     *cur = (val >> 7 * 4) | 0x80; cur += val >= ((UV)1 << (7 * 4));
652     *cur = (val >> 7 * 3) | 0x80; cur += val >= ((UV)1 << (7 * 3));
653     *cur = (val >> 7 * 2) | 0x80; cur += val >= ((UV)1 << (7 * 2));
654     *cur = (val >> 7 * 1) | 0x80; cur += val >= ((UV)1 << (7 * 1));
655 root 1.3 *cur = val & 0x7f; cur += 1;
656     }
657    
658     static void
659 root 1.15 put_w (UV val)
660 root 1.3 {
661     need (5); // we only handle up to 5 bytes
662    
663     put_w_nocheck (val);
664     }
665    
666     static U8 *
667 root 1.15 put_length_at (UV val, U8 *cur)
668 root 1.3 {
669     if (val < 0x7fU)
670     *cur++ = val;
671     else
672     {
673     U8 *lenb = cur++;
674    
675 root 1.15 #if UVSIZE > 4
676     *cur = val >> 56; cur += *cur > 0;
677     *cur = val >> 48; cur += *cur > 0;
678     *cur = val >> 40; cur += *cur > 0;
679     *cur = val >> 32; cur += *cur > 0;
680     #endif
681 root 1.3 *cur = val >> 24; cur += *cur > 0;
682     *cur = val >> 16; cur += *cur > 0;
683     *cur = val >> 8; cur += *cur > 0;
684     *cur = val ; cur += 1;
685    
686     *lenb = 0x80 + cur - lenb - 1;
687     }
688    
689     return cur;
690     }
691    
692     static void
693 root 1.15 put_length (UV val)
694 root 1.3 {
695 root 1.7 need (5 + val);
696 root 1.3 cur = put_length_at (val, cur);
697     }
698    
699     // return how many bytes the encoded length requires
700 root 1.15 static int length_length (UV val)
701 root 1.3 {
702     return val < 0x7fU
703     ? 1
704 root 1.15 : 2
705     + (val > 0xffU)
706     + (val > 0xffffU)
707     + (val > 0xffffffU)
708     #if UVSIZE > 4
709     + (val > 0xffffffffU)
710     + (val > 0xffffffffffU)
711     + (val > 0xffffffffffffU)
712     + (val > 0xffffffffffffffU)
713     #endif
714     ;
715 root 1.3 }
716    
717     static void
718 root 1.5 encode_data (const char *ptr, STRLEN len)
719 root 1.3 {
720     put_length (len);
721     memcpy (cur, ptr, len);
722     cur += len;
723     }
724    
725     static void
726 root 1.5 encode_uv (UV uv)
727     {
728     }
729    
730     static void
731     encode_int (SV *sv)
732 root 1.3 {
733 root 1.5 need (8 + 1 + 1); // 64 bit + length + extra 0
734    
735     if (expect_false (!SvIOK (sv)))
736     sv_2iv_flags (sv, 0);
737 root 1.3
738     U8 *lenb = cur++;
739    
740 root 1.5 if (SvIOK_notUV (sv))
741 root 1.3 {
742 root 1.5 IV iv = SvIVX (sv);
743    
744     if (expect_false (iv < 0))
745     {
746     // get two's complement bit pattern - works even on hypothetical non-2c machines
747     UV uv = iv;
748    
749     #if UVSIZE > 4
750     *cur = uv >> 56; cur += !!(~uv & 0xff80000000000000U);
751     *cur = uv >> 48; cur += !!(~uv & 0xffff800000000000U);
752     *cur = uv >> 40; cur += !!(~uv & 0xffffff8000000000U);
753     *cur = uv >> 32; cur += !!(~uv & 0xffffffff80000000U);
754     #endif
755     *cur = uv >> 24; cur += !!(~uv & 0xffffffffff800000U);
756     *cur = uv >> 16; cur += !!(~uv & 0xffffffffffff8000U);
757     *cur = uv >> 8; cur += !!(~uv & 0xffffffffffffff80U);
758     *cur = uv ; cur += 1;
759    
760     *lenb = cur - lenb - 1;
761 root 1.3
762 root 1.5 return;
763     }
764 root 1.3 }
765    
766 root 1.5 UV uv = SvUV (sv);
767 root 1.3
768 root 1.5 // prepend an extra 0 if the high bit is 1
769     *cur = 0; cur += !!(uv & ((UV)1 << (UVSIZE * 8 - 1)));
770 root 1.3
771 root 1.5 #if UVSIZE > 4
772     *cur = uv >> 56; cur += !!(uv & 0xff80000000000000U);
773     *cur = uv >> 48; cur += !!(uv & 0xffff800000000000U);
774     *cur = uv >> 40; cur += !!(uv & 0xffffff8000000000U);
775     *cur = uv >> 32; cur += !!(uv & 0xffffffff80000000U);
776     #endif
777     *cur = uv >> 24; cur += !!(uv & 0xffffffffff800000U);
778     *cur = uv >> 16; cur += !!(uv & 0xffffffffffff8000U);
779     *cur = uv >> 8; cur += !!(uv & 0xffffffffffffff80U);
780 root 1.3 *cur = uv ; cur += 1;
781    
782     *lenb = cur - lenb - 1;
783     }
784    
785     // we don't know the length yet, so we optimistically
786 root 1.15 // assume the length will need one octet later. If that
787     // turns out to be wrong, we memmove as needed.
788 root 1.3 // mark the beginning
789     static STRLEN
790 root 1.14 len_fixup_mark (void)
791 root 1.3 {
792     return cur++ - buf;
793     }
794    
795     // patch up the length
796     static void
797     len_fixup (STRLEN mark)
798     {
799     STRLEN reallen = (cur - buf) - mark - 1;
800     int lenlen = length_length (reallen);
801    
802     if (expect_false (lenlen > 1))
803     {
804     // bad luck, we have to shift the bytes to make room for the length
805     need (5);
806     memmove (buf + mark + lenlen, buf + mark + 1, reallen);
807     cur += lenlen - 1;
808     }
809    
810     put_length_at (reallen, buf + mark);
811     }
812    
813     static char *
814     read_uv (char *str, UV *uv)
815     {
816     UV r = 0;
817    
818     while (*str >= '0')
819     r = r * 10 + *str++ - '0';
820    
821     *uv = r;
822    
823     str += !!*str; // advance over any non-zero byte
824    
825     return str;
826     }
827    
828     static void
829 root 1.5 encode_oid (SV *oid, int relative)
830 root 1.3 {
831 root 1.5 STRLEN len;
832     char *ptr = SvPV (oid, len); // utf8 vs. bytes does not matter
833 root 1.3
834     // we need at most as many octets as the string form
835 root 1.5 need (len + 1);
836 root 1.3 STRLEN mark = len_fixup_mark ();
837    
838     UV w1, w2;
839    
840 root 1.5 if (!relative)
841     {
842     ptr = read_uv (ptr, &w1);
843     ptr = read_uv (ptr, &w2);
844 root 1.3
845 root 1.5 put_w_nocheck (w1 * 40 + w2);
846     }
847 root 1.3
848     while (*ptr)
849     {
850     ptr = read_uv (ptr, &w1);
851     put_w_nocheck (w1);
852     }
853    
854     len_fixup (mark);
855     }
856    
857 root 1.5 // check whether an SV is a BER tuple and returns its AV *
858 root 1.4 static AV *
859     ber_tuple (SV *tuple)
860 root 1.3 {
861 root 1.4 SV *rv;
862    
863     if (expect_false (!SvROK (tuple) || SvTYPE ((rv = SvRV (tuple))) != SVt_PVAV))
864 root 1.3 croak ("BER tuple must be array-reference");
865    
866 root 1.4 if (expect_false (SvRMAGICAL (rv)))
867     croak ("BER tuple must not be tied");
868 root 1.3
869 root 1.4 if (expect_false (AvFILL ((AV *)rv) != BER_ARRAYSIZE - 1))
870     croak ("BER tuple must contain exactly %d elements, not %d", BER_ARRAYSIZE, AvFILL ((AV *)rv) + 1);
871 root 1.3
872 root 1.4 return (AV *)rv;
873     }
874    
875     static void
876 root 1.7 encode_ucs (SV *data, int chrsize)
877     {
878     STRLEN uchars = sv_len_utf8 (data);
879     STRLEN len;;
880     char *ptr = SvPVutf8 (data, len);
881    
882     put_length (uchars * chrsize);
883    
884     while (uchars--)
885     {
886     STRLEN uclen;
887 root 1.10 UV uchr = utf8_to_uvchr_buf ((U8 *)ptr, (U8 *)ptr + len, &uclen);
888 root 1.7
889     ptr += uclen;
890     len -= uclen;
891    
892     if (chrsize == 4)
893     {
894     *cur++ = uchr >> 24;
895     *cur++ = uchr >> 16;
896     }
897    
898     *cur++ = uchr >> 8;
899     *cur++ = uchr;
900     }
901     }
902     static void
903 root 1.4 encode_ber (SV *tuple)
904     {
905     AV *av = ber_tuple (tuple);
906 root 1.3
907     int klass = SvIV (AvARRAY (av)[BER_CLASS]);
908     int tag = SvIV (AvARRAY (av)[BER_TAG]);
909 root 1.16 int constructed = SvIV (AvARRAY (av)[BER_FLAGS]) & 1 ? ASN_CONSTRUCTED : 0;
910 root 1.3 SV *data = AvARRAY (av)[BER_DATA];
911    
912     int identifier = (klass << ASN_CLASS_SHIFT) | constructed;
913    
914     if (expect_false (tag >= ASN_TAG_BER))
915     {
916     put_u8 (identifier | ASN_TAG_BER);
917     put_w (tag);
918     }
919     else
920     put_u8 (identifier | tag);
921    
922     if (constructed)
923     {
924     // we optimistically assume that only one length byte is needed
925     // and adjust later
926     need (1);
927     STRLEN mark = len_fixup_mark ();
928    
929     if (expect_false (!SvROK (data) || SvTYPE (SvRV (data)) != SVt_PVAV))
930     croak ("BER constructed data must be array-reference");
931    
932     AV *av = (AV *)SvRV (data);
933     int fill = AvFILL (av);
934    
935     if (expect_false (SvRMAGICAL (av)))
936     croak ("BER constructed data must not be tied");
937    
938 root 1.11 int i;
939     for (i = 0; i <= fill; ++i)
940 root 1.3 encode_ber (AvARRAY (av)[i]);
941    
942     len_fixup (mark);
943     }
944     else
945 root 1.5 switch (profile_lookup (cur_profile, klass, tag))
946 root 1.3 {
947 root 1.5 case BER_TYPE_NULL:
948 root 1.3 put_length (0);
949     break;
950    
951 root 1.5 case BER_TYPE_BOOL:
952     put_length (1);
953 root 1.17 *cur++ = SvTRUE (data) ? 0xff : 0x00; // 0xff = DER/CER
954 root 1.3 break;
955    
956 root 1.5 case BER_TYPE_OID:
957     encode_oid (data, 0);
958 root 1.3 break;
959    
960 root 1.5 case BER_TYPE_RELOID:
961     encode_oid (data, 1);
962 root 1.3 break;
963    
964 root 1.5 case BER_TYPE_INT:
965     encode_int (data);
966     break;
967    
968     case BER_TYPE_BYTES:
969     {
970     STRLEN len;
971     const char *ptr = SvPVbyte (data, len);
972     encode_data (ptr, len);
973     }
974     break;
975    
976     case BER_TYPE_UTF8:
977     {
978     STRLEN len;
979     const char *ptr = SvPVutf8 (data, len);
980     encode_data (ptr, len);
981     }
982     break;
983    
984 root 1.6 case BER_TYPE_IPADDRESS:
985     {
986     U8 ip[4];
987     sscanf (SvPV_nolen (data), "%hhu.%hhu.%hhu.%hhu", ip + 0, ip + 1, ip + 2, ip + 3);
988     encode_data ((const char *)ip, sizeof (ip));
989     }
990     break;
991    
992 root 1.5 case BER_TYPE_UCS2:
993 root 1.7 encode_ucs (data, 2);
994     break;
995    
996 root 1.5 case BER_TYPE_UCS4:
997 root 1.7 encode_ucs (data, 4);
998     break;
999    
1000     case BER_TYPE_REAL:
1001 root 1.5 case BER_TYPE_CROAK:
1002 root 1.3 default:
1003 root 1.5 croak ("unconfigured/unsupported class/tag %d/%d", klass, tag);
1004 root 1.3 }
1005    
1006     }
1007    
1008     /////////////////////////////////////////////////////////////////////////////
1009    
1010 root 1.1 MODULE = Convert::BER::XS PACKAGE = Convert::BER::XS
1011    
1012     PROTOTYPES: ENABLE
1013    
1014     BOOT:
1015     {
1016     HV *stash = gv_stashpv ("Convert::BER::XS", 1);
1017    
1018 root 1.5 profile_stash = gv_stashpv ("Convert::BER::XS::Profile", 1);
1019    
1020 root 1.1 static const struct {
1021     const char *name;
1022     IV iv;
1023     } *civ, const_iv[] = {
1024 root 1.5 #define const_iv(name) { # name, name },
1025     const_iv (ASN_BOOLEAN)
1026 root 1.15 const_iv (ASN_INTEGER)
1027 root 1.5 const_iv (ASN_BIT_STRING)
1028     const_iv (ASN_OCTET_STRING)
1029     const_iv (ASN_NULL)
1030     const_iv (ASN_OBJECT_IDENTIFIER)
1031     const_iv (ASN_OBJECT_DESCRIPTOR)
1032     const_iv (ASN_OID)
1033     const_iv (ASN_EXTERNAL)
1034     const_iv (ASN_REAL)
1035     const_iv (ASN_SEQUENCE)
1036     const_iv (ASN_ENUMERATED)
1037     const_iv (ASN_EMBEDDED_PDV)
1038     const_iv (ASN_UTF8_STRING)
1039     const_iv (ASN_RELATIVE_OID)
1040     const_iv (ASN_SET)
1041     const_iv (ASN_NUMERIC_STRING)
1042     const_iv (ASN_PRINTABLE_STRING)
1043     const_iv (ASN_TELETEX_STRING)
1044     const_iv (ASN_T61_STRING)
1045     const_iv (ASN_VIDEOTEX_STRING)
1046     const_iv (ASN_IA5_STRING)
1047     const_iv (ASN_ASCII_STRING)
1048     const_iv (ASN_UTC_TIME)
1049     const_iv (ASN_GENERALIZED_TIME)
1050     const_iv (ASN_GRAPHIC_STRING)
1051     const_iv (ASN_VISIBLE_STRING)
1052     const_iv (ASN_ISO646_STRING)
1053     const_iv (ASN_GENERAL_STRING)
1054     const_iv (ASN_UNIVERSAL_STRING)
1055     const_iv (ASN_CHARACTER_STRING)
1056     const_iv (ASN_BMP_STRING)
1057    
1058     const_iv (ASN_UNIVERSAL)
1059     const_iv (ASN_APPLICATION)
1060     const_iv (ASN_CONTEXT)
1061     const_iv (ASN_PRIVATE)
1062    
1063     const_iv (BER_CLASS)
1064     const_iv (BER_TAG)
1065 root 1.16 const_iv (BER_FLAGS)
1066 root 1.5 const_iv (BER_DATA)
1067    
1068     const_iv (BER_TYPE_BYTES)
1069     const_iv (BER_TYPE_UTF8)
1070     const_iv (BER_TYPE_UCS2)
1071     const_iv (BER_TYPE_UCS4)
1072     const_iv (BER_TYPE_INT)
1073     const_iv (BER_TYPE_OID)
1074     const_iv (BER_TYPE_RELOID)
1075     const_iv (BER_TYPE_NULL)
1076     const_iv (BER_TYPE_BOOL)
1077     const_iv (BER_TYPE_REAL)
1078 root 1.6 const_iv (BER_TYPE_IPADDRESS)
1079 root 1.5 const_iv (BER_TYPE_CROAK)
1080    
1081     const_iv (SNMP_IPADDRESS)
1082     const_iv (SNMP_COUNTER32)
1083     const_iv (SNMP_UNSIGNED32)
1084     const_iv (SNMP_TIMETICKS)
1085     const_iv (SNMP_OPAQUE)
1086     const_iv (SNMP_COUNTER64)
1087 root 1.1 };
1088    
1089     for (civ = const_iv + sizeof (const_iv) / sizeof (const_iv [0]); civ > const_iv; civ--)
1090     newCONSTSUB (stash, (char *)civ[-1].name, newSViv (civ[-1].iv));
1091     }
1092    
1093     SV *
1094 root 1.5 ber_decode (SV *ber, SV *profile = &PL_sv_undef)
1095 root 1.1 CODE:
1096     {
1097 root 1.5 cur_profile = SvPROFILE (profile);
1098 root 1.3 STRLEN len;
1099 root 1.10 buf = (U8 *)SvPVbyte (ber, len);
1100 root 1.1 cur = buf;
1101 root 1.3 end = buf + len;
1102 root 1.1
1103 root 1.2 RETVAL = decode_ber ();
1104 root 1.1 }
1105     OUTPUT: RETVAL
1106    
1107     void
1108 root 1.16 ber_is (SV *tuple, SV *klass = &PL_sv_undef, SV *tag = &PL_sv_undef, SV *flags = &PL_sv_undef, SV *data = &PL_sv_undef)
1109 root 1.1 PPCODE:
1110     {
1111     if (!SvOK (tuple))
1112     XSRETURN_NO;
1113    
1114     if (!SvROK (tuple) || SvTYPE (SvRV (tuple)) != SVt_PVAV)
1115 root 1.4 croak ("ber_is: tuple must be BER tuple (array-ref)");
1116 root 1.1
1117     AV *av = (AV *)SvRV (tuple);
1118    
1119     XPUSHs (
1120 root 1.16 (!SvOK (klass) || SvIV (AvARRAY (av)[BER_CLASS]) == SvIV (klass))
1121     && (!SvOK (tag) || SvIV (AvARRAY (av)[BER_TAG ]) == SvIV (tag))
1122     && (!SvOK (flags) || !SvIV (AvARRAY (av)[BER_FLAGS]) == !SvIV (flags))
1123     && (!SvOK (data) || sv_eq (AvARRAY (av)[BER_DATA ], data))
1124 root 1.4 ? &PL_sv_yes : &PL_sv_undef);
1125 root 1.1 }
1126    
1127     void
1128     ber_is_seq (SV *tuple)
1129     PPCODE:
1130     {
1131     if (!SvOK (tuple))
1132     XSRETURN_UNDEF;
1133    
1134 root 1.4 AV *av = ber_tuple (tuple);
1135 root 1.1
1136     XPUSHs (
1137 root 1.16 SvIV (AvARRAY (av)[BER_CLASS]) == ASN_UNIVERSAL
1138     && SvIV (AvARRAY (av)[BER_TAG ]) == ASN_SEQUENCE
1139     && SvIV (AvARRAY (av)[BER_FLAGS])
1140 root 1.1 ? AvARRAY (av)[BER_DATA] : &PL_sv_undef);
1141     }
1142    
1143     void
1144 root 1.15 ber_is_int (SV *tuple, SV *value = &PL_sv_undef)
1145 root 1.1 PPCODE:
1146     {
1147     if (!SvOK (tuple))
1148     XSRETURN_NO;
1149    
1150 root 1.4 AV *av = ber_tuple (tuple);
1151 root 1.1
1152 root 1.15 UV data = SvUV (AvARRAY (av)[BER_DATA]);
1153 root 1.1
1154     XPUSHs (
1155 root 1.16 SvIV (AvARRAY (av)[BER_CLASS]) == ASN_UNIVERSAL
1156     && SvIV (AvARRAY (av)[BER_TAG ]) == ASN_INTEGER
1157     && !SvIV (AvARRAY (av)[BER_FLAGS])
1158 root 1.15 && (!SvOK (value) || data == SvUV (value))
1159     ? sv_2mortal (data ? newSVsv (AvARRAY (av)[BER_DATA]) : newSVpv ("0 but true", 0))
1160 root 1.4 : &PL_sv_undef);
1161 root 1.1 }
1162    
1163     void
1164 root 1.4 ber_is_oid (SV *tuple, SV *oid = &PL_sv_undef)
1165 root 1.1 PPCODE:
1166     {
1167     if (!SvOK (tuple))
1168     XSRETURN_NO;
1169    
1170 root 1.4 AV *av = ber_tuple (tuple);
1171 root 1.1
1172     XPUSHs (
1173 root 1.16 SvIV (AvARRAY (av)[BER_CLASS]) == ASN_UNIVERSAL
1174     && SvIV (AvARRAY (av)[BER_TAG ]) == ASN_OBJECT_IDENTIFIER
1175     && !SvIV (AvARRAY (av)[BER_FLAGS])
1176 root 1.4 && (!SvOK (oid) || sv_eq (AvARRAY (av)[BER_DATA], oid))
1177     ? newSVsv (AvARRAY (av)[BER_DATA]) : &PL_sv_undef);
1178 root 1.1 }
1179    
1180 root 1.3 #############################################################################
1181    
1182     void
1183 root 1.5 ber_encode (SV *tuple, SV *profile = &PL_sv_undef)
1184 root 1.3 PPCODE:
1185     {
1186 root 1.5 cur_profile = SvPROFILE (profile);
1187 root 1.3 buf_sv = sv_2mortal (NEWSV (0, 256));
1188     SvPOK_only (buf_sv);
1189     set_buf (buf_sv);
1190    
1191     encode_ber (tuple);
1192    
1193     SvCUR_set (buf_sv, cur - buf);
1194     XPUSHs (buf_sv);
1195     }
1196    
1197 root 1.4 SV *
1198 root 1.15 ber_int (SV *sv)
1199 root 1.4 CODE:
1200     {
1201     AV *av = newAV ();
1202     av_fill (av, BER_ARRAYSIZE - 1);
1203 root 1.16 AvARRAY (av)[BER_CLASS] = newSVcacheint (ASN_UNIVERSAL);
1204     AvARRAY (av)[BER_TAG ] = newSVcacheint (ASN_INTEGER);
1205     AvARRAY (av)[BER_FLAGS] = newSVcacheint (0);
1206     AvARRAY (av)[BER_DATA ] = newSVsv (sv);
1207 root 1.4 RETVAL = newRV_noinc ((SV *)av);
1208     }
1209     OUTPUT: RETVAL
1210    
1211     # TODO: not arrayref, but elements?
1212     SV *
1213     ber_seq (SV *arrayref)
1214     CODE:
1215     {
1216     AV *av = newAV ();
1217     av_fill (av, BER_ARRAYSIZE - 1);
1218 root 1.16 AvARRAY (av)[BER_CLASS] = newSVcacheint (ASN_UNIVERSAL);
1219     AvARRAY (av)[BER_TAG ] = newSVcacheint (ASN_SEQUENCE);
1220     AvARRAY (av)[BER_FLAGS] = newSVcacheint (1);
1221     AvARRAY (av)[BER_DATA ] = newSVsv (arrayref);
1222 root 1.4 RETVAL = newRV_noinc ((SV *)av);
1223     }
1224     OUTPUT: RETVAL
1225    
1226 root 1.5 MODULE = Convert::BER::XS PACKAGE = Convert::BER::XS::Profile
1227    
1228     SV *
1229     new (SV *klass)
1230     CODE:
1231     RETVAL = profile_new ();
1232     OUTPUT: RETVAL
1233    
1234 root 1.6 void
1235     set (SV *profile, int klass, int tag, int type)
1236     CODE:
1237     profile_set (SvPROFILE (profile), klass, tag, type);
1238    
1239     IV
1240     get (SV *profile, int klass, int tag)
1241     CODE:
1242     RETVAL = profile_lookup (SvPROFILE (profile), klass, tag);
1243     OUTPUT: RETVAL
1244    
1245     void
1246     _set_default (SV *profile)
1247     CODE:
1248     default_profile = SvPROFILE (profile);
1249    
1250