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