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