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