1baaa8fd71acccd7d7f9a54b1ccb4a043663b845
[ric-plt/resource-status-manager.git] / RSM / asn1codec / e2ap_engine / INTEGER.c
1
2 /*-
3  * Copyright (c) 2003-2014 Lev Walkin <vlm@lionet.info>.
4  * All rights reserved.
5  * Redistribution and modifications are permitted subject to BSD license.
6  */
7 #include <asn_internal.h>
8 #include <INTEGER.h>
9 #include <asn_codecs_prim.h>    /* Encoder and decoder of a primitive type */
10 #include <errno.h>
11
12 /*
13  * INTEGER basic type description.
14  */
15 static const ber_tlv_tag_t asn_DEF_INTEGER_tags[] = {
16         (ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
17 };
18 asn_TYPE_operation_t asn_OP_INTEGER = {
19         INTEGER_free,
20         INTEGER_print,
21         INTEGER_compare,
22         ber_decode_primitive,
23         INTEGER_encode_der,
24         INTEGER_decode_xer,
25         INTEGER_encode_xer,
26 #ifdef  ASN_DISABLE_OER_SUPPORT
27         0,
28         0,
29 #else
30         INTEGER_decode_oer,     /* OER decoder */
31         INTEGER_encode_oer,     /* Canonical OER encoder */
32 #endif  /* ASN_DISABLE_OER_SUPPORT */
33 #ifdef  ASN_DISABLE_PER_SUPPORT
34         0,
35         0,
36         0,
37         0,
38 #else
39         INTEGER_decode_uper,    /* Unaligned PER decoder */
40         INTEGER_encode_uper,    /* Unaligned PER encoder */
41         INTEGER_decode_aper,    /* Aligned PER decoder */
42         INTEGER_encode_aper,    /* Aligned PER encoder */
43 #endif  /* ASN_DISABLE_PER_SUPPORT */
44         INTEGER_random_fill,
45         0       /* Use generic outmost tag fetcher */
46 };
47 asn_TYPE_descriptor_t asn_DEF_INTEGER = {
48         "INTEGER",
49         "INTEGER",
50         &asn_OP_INTEGER,
51         asn_DEF_INTEGER_tags,
52         sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
53         asn_DEF_INTEGER_tags,   /* Same as above */
54         sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
55         { 0, 0, asn_generic_no_constraint },
56         0, 0,   /* No members */
57         0       /* No specifics */
58 };
59
60 /*
61  * Encode INTEGER type using DER.
62  */
63 asn_enc_rval_t
64 INTEGER_encode_der(const asn_TYPE_descriptor_t *td, const void *sptr,
65                    int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb,
66                    void *app_key) {
67     const INTEGER_t *st = (const INTEGER_t *)sptr;
68     asn_enc_rval_t rval;
69     INTEGER_t effective_integer;
70
71         ASN_DEBUG("%s %s as INTEGER (tm=%d)",
72                 cb?"Encoding":"Estimating", td->name, tag_mode);
73
74         /*
75          * Canonicalize integer in the buffer.
76          * (Remove too long sign extension, remove some first 0x00 bytes)
77          */
78         if(st->buf) {
79                 uint8_t *buf = st->buf;
80                 uint8_t *end1 = buf + st->size - 1;
81                 int shift;
82
83                 /* Compute the number of superfluous leading bytes */
84                 for(; buf < end1; buf++) {
85                         /*
86                          * If the contents octets of an integer value encoding
87                          * consist of more than one octet, then the bits of the
88                          * first octet and bit 8 of the second octet:
89                          * a) shall not all be ones; and
90                          * b) shall not all be zero.
91                          */
92                         switch(*buf) {
93                         case 0x00: if((buf[1] & 0x80) == 0)
94                                         continue;
95                                 break;
96                         case 0xff: if((buf[1] & 0x80))
97                                         continue;
98                                 break;
99                         }
100                         break;
101                 }
102
103                 /* Remove leading superfluous bytes from the integer */
104                 shift = buf - st->buf;
105                 if(shift) {
106             union {
107                 const uint8_t *c_buf;
108                 uint8_t *nc_buf;
109             } unconst;
110             unconst.c_buf = st->buf;
111             effective_integer.buf = unconst.nc_buf + shift;
112             effective_integer.size = st->size - shift;
113
114             st = &effective_integer;
115         }
116     }
117
118     rval = der_encode_primitive(td, st, tag_mode, tag, cb, app_key);
119     if(rval.structure_ptr == &effective_integer) {
120         rval.structure_ptr = sptr;
121     }
122     return rval;
123 }
124
125 static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(
126     const asn_INTEGER_specifics_t *specs, const char *lstart,
127     const char *lstop);
128
129 /*
130  * INTEGER specific human-readable output.
131  */
132 static ssize_t
133 INTEGER__dump(const asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) {
134     const asn_INTEGER_specifics_t *specs =
135         (const asn_INTEGER_specifics_t *)td->specifics;
136         char scratch[32];
137         uint8_t *buf = st->buf;
138         uint8_t *buf_end = st->buf + st->size;
139         intmax_t value;
140         ssize_t wrote = 0;
141         char *p;
142         int ret;
143
144         if(specs && specs->field_unsigned)
145                 ret = asn_INTEGER2umax(st, (uintmax_t *)&value);
146         else
147                 ret = asn_INTEGER2imax(st, &value);
148
149         /* Simple case: the integer size is small */
150         if(ret == 0) {
151                 const asn_INTEGER_enum_map_t *el;
152                 el = (value >= 0 || !specs || !specs->field_unsigned)
153                         ? INTEGER_map_value2enum(specs, value) : 0;
154                 if(el) {
155                         if(plainOrXER == 0)
156                                 return asn__format_to_callback(cb, app_key,
157                                         "%" ASN_PRIdMAX " (%s)", value, el->enum_name);
158                         else
159                                 return asn__format_to_callback(cb, app_key,
160                                         "<%s/>", el->enum_name);
161                 } else if(plainOrXER && specs && specs->strict_enumeration) {
162                         ASN_DEBUG("ASN.1 forbids dealing with "
163                                 "unknown value of ENUMERATED type");
164                         errno = EPERM;
165                         return -1;
166                 } else {
167             return asn__format_to_callback(cb, app_key,
168                                            (specs && specs->field_unsigned)
169                                                ? "%" ASN_PRIuMAX
170                                                : "%" ASN_PRIdMAX,
171                                            value);
172         }
173         } else if(plainOrXER && specs && specs->strict_enumeration) {
174                 /*
175                  * Here and earlier, we cannot encode the ENUMERATED values
176                  * if there is no corresponding identifier.
177                  */
178                 ASN_DEBUG("ASN.1 forbids dealing with "
179                         "unknown value of ENUMERATED type");
180                 errno = EPERM;
181                 return -1;
182         }
183
184         /* Output in the long xx:yy:zz... format */
185         /* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */
186         for(p = scratch; buf < buf_end; buf++) {
187                 const char * const h2c = "0123456789ABCDEF";
188                 if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) {
189                         /* Flush buffer */
190                         if(cb(scratch, p - scratch, app_key) < 0)
191                                 return -1;
192                         wrote += p - scratch;
193                         p = scratch;
194                 }
195                 *p++ = h2c[*buf >> 4];
196                 *p++ = h2c[*buf & 0x0F];
197                 *p++ = 0x3a;    /* ":" */
198         }
199         if(p != scratch)
200                 p--;    /* Remove the last ":" */
201
202         wrote += p - scratch;
203         return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
204 }
205
206 /*
207  * INTEGER specific human-readable output.
208  */
209 int
210 INTEGER_print(const asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
211               asn_app_consume_bytes_f *cb, void *app_key) {
212     const INTEGER_t *st = (const INTEGER_t *)sptr;
213         ssize_t ret;
214
215         (void)ilevel;
216
217         if(!st || !st->buf)
218                 ret = cb("<absent>", 8, app_key);
219         else
220                 ret = INTEGER__dump(td, st, cb, app_key, 0);
221
222         return (ret < 0) ? -1 : 0;
223 }
224
225 struct e2v_key {
226         const char *start;
227         const char *stop;
228         const asn_INTEGER_enum_map_t *vemap;
229         const unsigned int *evmap;
230 };
231 static int
232 INTEGER__compar_enum2value(const void *kp, const void *am) {
233         const struct e2v_key *key = (const struct e2v_key *)kp;
234         const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
235         const char *ptr, *end, *name;
236
237         /* Remap the element (sort by different criterion) */
238         el = key->vemap + key->evmap[el - key->vemap];
239
240         /* Compare strings */
241         for(ptr = key->start, end = key->stop, name = el->enum_name;
242                         ptr < end; ptr++, name++) {
243                 if(*ptr != *name || !*name)
244                         return *(const unsigned char *)ptr
245                                 - *(const unsigned char *)name;
246         }
247         return name[0] ? -1 : 0;
248 }
249
250 static const asn_INTEGER_enum_map_t *
251 INTEGER_map_enum2value(const asn_INTEGER_specifics_t *specs, const char *lstart,
252                        const char *lstop) {
253     const asn_INTEGER_enum_map_t *el_found;
254         int count = specs ? specs->map_count : 0;
255         struct e2v_key key;
256         const char *lp;
257
258         if(!count) return NULL;
259
260         /* Guaranteed: assert(lstart < lstop); */
261         /* Figure out the tag name */
262         for(lstart++, lp = lstart; lp < lstop; lp++) {
263                 switch(*lp) {
264                 case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */
265                 case 0x2f: /* '/' */ case 0x3e: /* '>' */
266                         break;
267                 default:
268                         continue;
269                 }
270                 break;
271         }
272         if(lp == lstop) return NULL;    /* No tag found */
273         lstop = lp;
274
275         key.start = lstart;
276         key.stop = lstop;
277         key.vemap = specs->value2enum;
278         key.evmap = specs->enum2value;
279         el_found = (asn_INTEGER_enum_map_t *)bsearch(&key,
280                 specs->value2enum, count, sizeof(specs->value2enum[0]),
281                 INTEGER__compar_enum2value);
282         if(el_found) {
283                 /* Remap enum2value into value2enum */
284                 el_found = key.vemap + key.evmap[el_found - key.vemap];
285         }
286         return el_found;
287 }
288
289 static int
290 INTEGER__compar_value2enum(const void *kp, const void *am) {
291         long a = *(const long *)kp;
292         const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
293         long b = el->nat_value;
294         if(a < b) return -1;
295         else if(a == b) return 0;
296         else return 1;
297 }
298
299 const asn_INTEGER_enum_map_t *
300 INTEGER_map_value2enum(const asn_INTEGER_specifics_t *specs, long value) {
301         int count = specs ? specs->map_count : 0;
302         if(!count) return 0;
303         return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum,
304                 count, sizeof(specs->value2enum[0]),
305                 INTEGER__compar_value2enum);
306 }
307
308 static int
309 INTEGER_st_prealloc(INTEGER_t *st, int min_size) {
310         void *p = MALLOC(min_size + 1);
311         if(p) {
312                 void *b = st->buf;
313                 st->size = 0;
314                 st->buf = p;
315                 FREEMEM(b);
316                 return 0;
317         } else {
318                 return -1;
319         }
320 }
321
322 /*
323  * Decode the chunk of XML text encoding INTEGER.
324  */
325 static enum xer_pbd_rval
326 INTEGER__xer_body_decode(const asn_TYPE_descriptor_t *td, void *sptr,
327                          const void *chunk_buf, size_t chunk_size) {
328     const asn_INTEGER_specifics_t *specs =
329         (const asn_INTEGER_specifics_t *)td->specifics;
330     INTEGER_t *st = (INTEGER_t *)sptr;
331         intmax_t dec_value;
332         intmax_t hex_value = 0;
333         const char *lp;
334         const char *lstart = (const char *)chunk_buf;
335         const char *lstop = lstart + chunk_size;
336         enum {
337                 ST_LEADSPACE,
338                 ST_SKIPSPHEX,
339                 ST_WAITDIGITS,
340                 ST_DIGITS,
341                 ST_DIGITS_TRAILSPACE,
342                 ST_HEXDIGIT1,
343                 ST_HEXDIGIT2,
344                 ST_HEXDIGITS_TRAILSPACE,
345                 ST_HEXCOLON,
346                 ST_END_ENUM,
347                 ST_UNEXPECTED
348         } state = ST_LEADSPACE;
349         const char *dec_value_start = 0; /* INVARIANT: always !0 in ST_DIGITS */
350         const char *dec_value_end = 0;
351
352         if(chunk_size)
353                 ASN_DEBUG("INTEGER body %ld 0x%2x..0x%2x",
354                         (long)chunk_size, *lstart, lstop[-1]);
355
356         if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
357                 return XPBD_SYSTEM_FAILURE;
358
359         /*
360          * We may have received a tag here. It will be processed inline.
361          * Use strtoul()-like code and serialize the result.
362          */
363         for(lp = lstart; lp < lstop; lp++) {
364                 int lv = *lp;
365                 switch(lv) {
366                 case 0x09: case 0x0a: case 0x0d: case 0x20:
367                         switch(state) {
368                         case ST_LEADSPACE:
369                         case ST_DIGITS_TRAILSPACE:
370                         case ST_HEXDIGITS_TRAILSPACE:
371                         case ST_SKIPSPHEX:
372                                 continue;
373                         case ST_DIGITS:
374                                 dec_value_end = lp;
375                                 state = ST_DIGITS_TRAILSPACE;
376                                 continue;
377                         case ST_HEXCOLON:
378                                 state = ST_HEXDIGITS_TRAILSPACE;
379                                 continue;
380                         default:
381                                 break;
382                         }
383                         break;
384                 case 0x2d:      /* '-' */
385                         if(state == ST_LEADSPACE) {
386                                 dec_value = 0;
387                                 dec_value_start = lp;
388                                 state = ST_WAITDIGITS;
389                                 continue;
390                         }
391                         break;
392                 case 0x2b:      /* '+' */
393                         if(state == ST_LEADSPACE) {
394                                 dec_value = 0;
395                                 dec_value_start = lp;
396                                 state = ST_WAITDIGITS;
397                                 continue;
398                         }
399                         break;
400                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
401                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
402                         switch(state) {
403                         case ST_DIGITS: continue;
404                         case ST_SKIPSPHEX:      /* Fall through */
405                         case ST_HEXDIGIT1:
406                                 hex_value = (lv - 0x30) << 4;
407                                 state = ST_HEXDIGIT2;
408                                 continue;
409                         case ST_HEXDIGIT2:
410                                 hex_value += (lv - 0x30);
411                                 state = ST_HEXCOLON;
412                                 st->buf[st->size++] = (uint8_t)hex_value;
413                                 continue;
414                         case ST_HEXCOLON:
415                                 return XPBD_BROKEN_ENCODING;
416                         case ST_LEADSPACE:
417                                 dec_value = 0;
418                                 dec_value_start = lp;
419                                 /* FALL THROUGH */
420                         case ST_WAITDIGITS:
421                                 state = ST_DIGITS;
422                                 continue;
423                         default:
424                                 break;
425                         }
426                         break;
427                 case 0x3c:      /* '<', start of XML encoded enumeration */
428                         if(state == ST_LEADSPACE) {
429                                 const asn_INTEGER_enum_map_t *el;
430                                 el = INTEGER_map_enum2value(
431                                         (const asn_INTEGER_specifics_t *)
432                                         td->specifics, lstart, lstop);
433                                 if(el) {
434                                         ASN_DEBUG("Found \"%s\" => %ld",
435                                                 el->enum_name, el->nat_value);
436                                         dec_value = el->nat_value;
437                                         state = ST_END_ENUM;
438                                         lp = lstop - 1;
439                                         continue;
440                                 }
441                                 ASN_DEBUG("Unknown identifier for INTEGER");
442                         }
443                         return XPBD_BROKEN_ENCODING;
444                 case 0x3a:      /* ':' */
445                         if(state == ST_HEXCOLON) {
446                                 /* This colon is expected */
447                                 state = ST_HEXDIGIT1;
448                                 continue;
449                         } else if(state == ST_DIGITS) {
450                                 /* The colon here means that we have
451                                  * decoded the first two hexadecimal
452                                  * places as a decimal value.
453                                  * Switch decoding mode. */
454                                 ASN_DEBUG("INTEGER re-evaluate as hex form");
455                                 state = ST_SKIPSPHEX;
456                                 dec_value_start = 0;
457                                 lp = lstart - 1;
458                                 continue;
459                         } else {
460                                 ASN_DEBUG("state %d at %ld", state, (long)(lp - lstart));
461                                 break;
462                         }
463                 /* [A-Fa-f] */
464                 case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46:
465                 case 0x61:case 0x62:case 0x63:case 0x64:case 0x65:case 0x66:
466                         switch(state) {
467                         case ST_SKIPSPHEX:
468                         case ST_LEADSPACE: /* Fall through */
469                         case ST_HEXDIGIT1:
470                                 hex_value = lv - ((lv < 0x61) ? 0x41 : 0x61);
471                                 hex_value += 10;
472                                 hex_value <<= 4;
473                                 state = ST_HEXDIGIT2;
474                                 continue;
475                         case ST_HEXDIGIT2:
476                                 hex_value += lv - ((lv < 0x61) ? 0x41 : 0x61);
477                                 hex_value += 10;
478                                 st->buf[st->size++] = (uint8_t)hex_value;
479                                 state = ST_HEXCOLON;
480                                 continue;
481                         case ST_DIGITS:
482                                 ASN_DEBUG("INTEGER re-evaluate as hex form");
483                                 state = ST_SKIPSPHEX;
484                                 dec_value_start = 0;
485                                 lp = lstart - 1;
486                                 continue;
487                         default:
488                                 break;
489                         }
490                         break;
491                 }
492
493                 /* Found extra non-numeric stuff */
494                 ASN_DEBUG("INTEGER :: Found non-numeric 0x%2x at %ld",
495                         lv, (long)(lp - lstart));
496                 state = ST_UNEXPECTED;
497                 break;
498         }
499
500         switch(state) {
501         case ST_END_ENUM:
502                 /* Got a complete and valid enumeration encoded as a tag. */
503                 break;
504         case ST_DIGITS:
505                 dec_value_end = lstop;
506                 /* FALL THROUGH */
507         case ST_DIGITS_TRAILSPACE:
508                 /* The last symbol encountered was a digit. */
509         switch(asn_strtoimax_lim(dec_value_start, &dec_value_end, &dec_value)) {
510         case ASN_STRTOX_OK:
511             if(specs && specs->field_unsigned && (uintmax_t) dec_value <= ULONG_MAX) {
512                 break;
513             } else if(dec_value >= LONG_MIN && dec_value <= LONG_MAX) {
514                 break;
515             } else {
516                 /*
517                  * We model INTEGER on long for XER,
518                  * to avoid rewriting all the tests at once.
519                  */
520                 ASN_DEBUG("INTEGER exceeds long range");
521             }
522             /* Fall through */
523         case ASN_STRTOX_ERROR_RANGE:
524             ASN_DEBUG("INTEGER decode %s hit range limit", td->name);
525             return XPBD_DECODER_LIMIT;
526                 case ASN_STRTOX_ERROR_INVAL:
527                 case ASN_STRTOX_EXPECT_MORE:
528                 case ASN_STRTOX_EXTRA_DATA:
529                         return XPBD_BROKEN_ENCODING;
530                 }
531                 break;
532         case ST_HEXCOLON:
533         case ST_HEXDIGITS_TRAILSPACE:
534                 st->buf[st->size] = 0;  /* Just in case termination */
535                 return XPBD_BODY_CONSUMED;
536         case ST_HEXDIGIT1:
537         case ST_HEXDIGIT2:
538         case ST_SKIPSPHEX:
539                 return XPBD_BROKEN_ENCODING;
540         case ST_LEADSPACE:
541                 /* Content not found */
542                 return XPBD_NOT_BODY_IGNORE;
543         case ST_WAITDIGITS:
544         case ST_UNEXPECTED:
545                 ASN_DEBUG("INTEGER: No useful digits (state %d)", state);
546                 return XPBD_BROKEN_ENCODING;    /* No digits */
547         }
548
549         /*
550          * Convert the result of parsing of enumeration or a straight
551          * decimal value into a BER representation.
552          */
553         if(asn_imax2INTEGER(st, dec_value)) {
554                 ASN_DEBUG("INTEGER decode %s conversion failed", td->name);
555                 return XPBD_SYSTEM_FAILURE;
556         }
557
558         return XPBD_BODY_CONSUMED;
559 }
560
561 asn_dec_rval_t
562 INTEGER_decode_xer(const asn_codec_ctx_t *opt_codec_ctx,
563                    const asn_TYPE_descriptor_t *td, void **sptr,
564                    const char *opt_mname, const void *buf_ptr, size_t size) {
565     return xer_decode_primitive(opt_codec_ctx, td,
566                 sptr, sizeof(INTEGER_t), opt_mname,
567                 buf_ptr, size, INTEGER__xer_body_decode);
568 }
569
570 asn_enc_rval_t
571 INTEGER_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr,
572                    int ilevel, enum xer_encoder_flags_e flags,
573                    asn_app_consume_bytes_f *cb, void *app_key) {
574     const INTEGER_t *st = (const INTEGER_t *)sptr;
575         asn_enc_rval_t er = {0,0,0};
576
577         (void)ilevel;
578         (void)flags;
579         
580         if(!st || !st->buf)
581                 ASN__ENCODE_FAILED;
582
583         er.encoded = INTEGER__dump(td, st, cb, app_key, 1);
584         if(er.encoded < 0) ASN__ENCODE_FAILED;
585
586         ASN__ENCODED_OK(er);
587 }
588
589 #ifndef ASN_DISABLE_PER_SUPPORT
590
591 asn_dec_rval_t
592 INTEGER_decode_uper(const asn_codec_ctx_t *opt_codec_ctx,
593                     const asn_TYPE_descriptor_t *td,
594                     const asn_per_constraints_t *constraints, void **sptr,
595                     asn_per_data_t *pd) {
596     const asn_INTEGER_specifics_t *specs =
597         (const asn_INTEGER_specifics_t *)td->specifics;
598     asn_dec_rval_t rval = { RC_OK, 0 };
599         INTEGER_t *st = (INTEGER_t *)*sptr;
600         const asn_per_constraint_t *ct;
601         int repeat;
602
603         (void)opt_codec_ctx;
604
605         if(!st) {
606                 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
607                 if(!st) ASN__DECODE_FAILED;
608         }
609
610         if(!constraints) constraints = td->encoding_constraints.per_constraints;
611         ct = constraints ? &constraints->value : 0;
612
613         if(ct && ct->flags & APC_EXTENSIBLE) {
614                 int inext = per_get_few_bits(pd, 1);
615                 if(inext < 0) ASN__DECODE_STARVED;
616                 if(inext) ct = 0;
617         }
618
619         FREEMEM(st->buf);
620         st->buf = 0;
621         st->size = 0;
622         if(ct) {
623                 if(ct->flags & APC_SEMI_CONSTRAINED) {
624                         st->buf = (uint8_t *)CALLOC(1, 2);
625                         if(!st->buf) ASN__DECODE_FAILED;
626                         st->size = 1;
627                 } else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
628                         size_t size = (ct->range_bits + 7) >> 3;
629                         st->buf = (uint8_t *)MALLOC(1 + size + 1);
630                         if(!st->buf) ASN__DECODE_FAILED;
631                         st->size = size;
632                 }
633         }
634
635         /* X.691-2008/11, #13.2.2, constrained whole number */
636         if(ct && ct->flags != APC_UNCONSTRAINED) {
637                 /* #11.5.6 */
638                 ASN_DEBUG("Integer with range %d bits", ct->range_bits);
639                 if(ct->range_bits >= 0) {
640                         if((size_t)ct->range_bits > 8 * sizeof(unsigned long))
641                                 ASN__DECODE_FAILED;
642
643                         if(specs && specs->field_unsigned) {
644                                 unsigned long uvalue = 0;
645                                 if(uper_get_constrained_whole_number(pd,
646                                         &uvalue, ct->range_bits))
647                                         ASN__DECODE_STARVED;
648                                 ASN_DEBUG("Got value %lu + low %ld",
649                                         uvalue, ct->lower_bound);
650                                 uvalue += ct->lower_bound;
651                                 if(asn_ulong2INTEGER(st, uvalue))
652                                         ASN__DECODE_FAILED;
653                         } else {
654                                 unsigned long uvalue = 0;
655                                 long svalue;
656                                 if(uper_get_constrained_whole_number(pd,
657                                         &uvalue, ct->range_bits))
658                                         ASN__DECODE_STARVED;
659                                 ASN_DEBUG("Got value %lu + low %ld",
660                                         uvalue, ct->lower_bound);
661                 if(per_long_range_unrebase(uvalue, ct->lower_bound,
662                                            ct->upper_bound, &svalue)
663                    || asn_long2INTEGER(st, svalue)) {
664                     ASN__DECODE_FAILED;
665                 }
666                         }
667                         return rval;
668                 }
669         } else {
670                 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
671         }
672
673         /* X.691, #12.2.3, #12.2.4 */
674         do {
675                 ssize_t len = 0;
676                 void *p = NULL;
677                 int ret = 0;
678
679                 /* Get the PER length */
680                 len = uper_get_length(pd, -1, 0, &repeat);
681                 if(len < 0) ASN__DECODE_STARVED;
682
683                 p = REALLOC(st->buf, st->size + len + 1);
684                 if(!p) ASN__DECODE_FAILED;
685                 st->buf = (uint8_t *)p;
686
687                 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
688                 if(ret < 0) ASN__DECODE_STARVED;
689                 st->size += len;
690         } while(repeat);
691         st->buf[st->size] = 0;  /* JIC */
692
693         /* #12.2.3 */
694         if(ct && ct->lower_bound) {
695                 /*
696                  * TODO: replace by in-place arithmetics.
697                  */
698                 long value = 0;
699                 if(asn_INTEGER2long(st, &value))
700                         ASN__DECODE_FAILED;
701                 if(asn_imax2INTEGER(st, value + ct->lower_bound))
702                         ASN__DECODE_FAILED;
703         }
704
705         return rval;
706 }
707
708 asn_enc_rval_t
709 INTEGER_encode_uper(const asn_TYPE_descriptor_t *td,
710                     const asn_per_constraints_t *constraints, const void *sptr,
711                     asn_per_outp_t *po) {
712         const asn_INTEGER_specifics_t *specs =
713                 (const asn_INTEGER_specifics_t *)td->specifics;
714         asn_enc_rval_t er = {0,0,0};
715         const INTEGER_t *st = (const INTEGER_t *)sptr;
716         const uint8_t *buf;
717         const uint8_t *end;
718         const asn_per_constraint_t *ct;
719         long value = 0;
720
721         if(!st || st->size == 0) ASN__ENCODE_FAILED;
722
723         if(!constraints) constraints = td->encoding_constraints.per_constraints;
724         ct = constraints ? &constraints->value : 0;
725
726         er.encoded = 0;
727
728         if(ct) {
729                 int inext = 0;
730                 if(specs && specs->field_unsigned) {
731                         unsigned long uval;
732                         if(asn_INTEGER2ulong(st, &uval))
733                                 ASN__ENCODE_FAILED;
734                         /* Check proper range */
735                         if(ct->flags & APC_SEMI_CONSTRAINED) {
736                                 if(uval < (unsigned long)ct->lower_bound)
737                                         inext = 1;
738                         } else if(ct->range_bits >= 0) {
739                                 if(uval < (unsigned long)ct->lower_bound
740                                 || uval > (unsigned long)ct->upper_bound)
741                                         inext = 1;
742                         }
743                         ASN_DEBUG("Value %lu (%02x/%" ASN_PRI_SIZE ") lb %lu ub %lu %s",
744                                 uval, st->buf[0], st->size,
745                                 ct->lower_bound, ct->upper_bound,
746                                 inext ? "ext" : "fix");
747                         value = uval;
748                 } else {
749                         if(asn_INTEGER2long(st, &value))
750                                 ASN__ENCODE_FAILED;
751                         /* Check proper range */
752                         if(ct->flags & APC_SEMI_CONSTRAINED) {
753                                 if(value < ct->lower_bound)
754                                         inext = 1;
755                         } else if(ct->range_bits >= 0) {
756                                 if(value < ct->lower_bound
757                                 || value > ct->upper_bound)
758                                         inext = 1;
759                         }
760                         ASN_DEBUG("Value %ld (%02x/%" ASN_PRI_SIZE ") lb %ld ub %ld %s",
761                                 value, st->buf[0], st->size,
762                                 ct->lower_bound, ct->upper_bound,
763                                 inext ? "ext" : "fix");
764                 }
765                 if(ct->flags & APC_EXTENSIBLE) {
766                         if(per_put_few_bits(po, inext, 1))
767                                 ASN__ENCODE_FAILED;
768                         if(inext) ct = 0;
769                 } else if(inext) {
770                         ASN__ENCODE_FAILED;
771                 }
772         }
773
774
775         /* X.691-11/2008, #13.2.2, test if constrained whole number */
776         if(ct && ct->range_bits >= 0) {
777         unsigned long v;
778                 /* #11.5.6 -> #11.3 */
779                 ASN_DEBUG("Encoding integer %ld (%lu) with range %d bits",
780                         value, value - ct->lower_bound, ct->range_bits);
781         if(specs && specs->field_unsigned) {
782                 if (  ((unsigned long)ct->lower_bound > (unsigned long)(ct->upper_bound)
783                    || ((unsigned long)value < (unsigned long)ct->lower_bound))
784                    || ((unsigned long)value > (unsigned long)ct->upper_bound)
785                 ) {
786                         ASN_DEBUG("Value %lu to-be-encoded is outside the bounds [%lu, %lu]!",
787                                 value, ct->lower_bound, ct->upper_bound);
788                         ASN__ENCODE_FAILED;
789                 }
790                 v = (unsigned long)value - (unsigned long)ct->lower_bound;
791         } else {
792                 if(per_long_range_rebase(value, ct->lower_bound, ct->upper_bound, &v)) {
793                         ASN__ENCODE_FAILED;
794                 }
795         }
796         if(uper_put_constrained_whole_number_u(po, v, ct->range_bits))
797                 ASN__ENCODE_FAILED;
798         ASN__ENCODED_OK(er);
799         }
800
801         if(ct && ct->lower_bound) {
802                 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
803                 /* TODO: adjust lower bound */
804                 ASN__ENCODE_FAILED;
805         }
806
807         for(buf = st->buf, end = st->buf + st->size; buf < end;) {
808         int need_eom = 0;
809         ssize_t mayEncode = uper_put_length(po, end - buf, &need_eom);
810         if(mayEncode < 0)
811                         ASN__ENCODE_FAILED;
812                 if(per_put_many_bits(po, buf, 8 * mayEncode))
813                         ASN__ENCODE_FAILED;
814                 buf += mayEncode;
815         if(need_eom && uper_put_length(po, 0, 0)) ASN__ENCODE_FAILED;
816     }
817
818         ASN__ENCODED_OK(er);
819 }
820
821 asn_dec_rval_t
822 INTEGER_decode_aper(const asn_codec_ctx_t *opt_codec_ctx,
823                     const asn_TYPE_descriptor_t *td,
824                     const asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
825         const asn_INTEGER_specifics_t *specs = (const asn_INTEGER_specifics_t *)td->specifics;
826         asn_dec_rval_t rval = { RC_OK, 0 };
827         INTEGER_t *st = (INTEGER_t *)*sptr;
828         const asn_per_constraint_t *ct;
829         int repeat;
830
831         (void)opt_codec_ctx;
832
833         if(!st) {
834                 st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
835                 if(!st) ASN__DECODE_FAILED;
836         }
837
838         if(!constraints) constraints = td->encoding_constraints.per_constraints;
839         ct = constraints ? &constraints->value : 0;
840
841         if(ct && ct->flags & APC_EXTENSIBLE) {
842                 int inext = per_get_few_bits(pd, 1);
843                 if(inext < 0) ASN__DECODE_STARVED;
844                 if(inext) ct = 0;
845         }
846
847         FREEMEM(st->buf);
848         st->buf = 0;
849         st->size = 0;
850         if(ct) {
851                 if(ct->flags & APC_SEMI_CONSTRAINED) {
852                         st->buf = (uint8_t *)CALLOC(1, 2);
853                         if(!st->buf) ASN__DECODE_FAILED;
854                         st->size = 1;
855                 } else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
856                         size_t size = (ct->range_bits + 7) >> 3;
857                         st->buf = (uint8_t *)MALLOC(1 + size + 1);
858                         if(!st->buf) ASN__DECODE_FAILED;
859                         st->size = size;
860                 }
861         }
862
863         /* X.691, #12.2.2 */
864         if(ct && ct->flags != APC_UNCONSTRAINED) {
865                 /* #10.5.6 */
866                 ASN_DEBUG("Integer with range %d bits", ct->range_bits);
867                 if(ct->range_bits >= 0) {
868                         if (ct->range_bits > 16) {
869                                 int max_range_bytes = (ct->range_bits >> 3) +
870                                                       (((ct->range_bits % 8) > 0) ? 1 : 0);
871                                 int length = 0, i;
872                                 long value = 0;
873
874                                 for (i = 1; ; i++) {
875                                         int upper = 1 << i;
876                                         if (upper >= max_range_bytes)
877                                                 break;
878                                 }
879                                 ASN_DEBUG("Can encode %d (%d bytes) in %d bits", ct->range_bits,
880                                           max_range_bytes, i);
881
882                                 if ((length = per_get_few_bits(pd, i)) < 0)
883                                         ASN__DECODE_FAILED;
884
885                                 /* X.691 #12.2.6 length determinant + lb (1) */
886                                 length += 1;
887                                 ASN_DEBUG("Got length %d", length);
888                                 if (aper_get_align(pd) != 0)
889                                         ASN__DECODE_FAILED;
890                                 while (length--) {
891                                         int buf = per_get_few_bits(pd, 8);
892                                         if (buf < 0)
893                                                 ASN__DECODE_FAILED;
894                                         value += (((long)buf) << (8 * length));
895                                 }
896
897                                 value += ct->lower_bound;
898                                 if((specs && specs->field_unsigned)
899                                         ? asn_uint642INTEGER(st, (unsigned long)value)
900                                         : asn_int642INTEGER(st, value))
901                                         ASN__DECODE_FAILED;
902                                 ASN_DEBUG("Got value %ld + low %ld",
903                                           value, ct->lower_bound);
904                         } else {
905                                 long value = 0;
906                                 if (ct->range_bits < 8) {
907                                         value = per_get_few_bits(pd, ct->range_bits);
908                                         if(value < 0) ASN__DECODE_STARVED;
909                                 } else if (ct->range_bits == 8) {
910                                         if (aper_get_align(pd) < 0)
911                                                 ASN__DECODE_FAILED;
912                                         value = per_get_few_bits(pd, ct->range_bits);
913                                         if(value < 0) ASN__DECODE_STARVED;
914                                 } else {
915                                         /* Align */
916                                         if (aper_get_align(pd) < 0)
917                                                 ASN__DECODE_FAILED;
918                                         value = per_get_few_bits(pd, 16);
919                                         if(value < 0) ASN__DECODE_STARVED;
920                                 }
921                                 value += ct->lower_bound;
922                                 if((specs && specs->field_unsigned)
923                                         ? asn_ulong2INTEGER(st, value)
924                                         : asn_long2INTEGER(st, value))
925                                         ASN__DECODE_FAILED;
926                                 ASN_DEBUG("Got value %ld + low %ld",
927                                           value, ct->lower_bound);
928                         }
929                         return rval;
930                 } else {
931                         ASN__DECODE_FAILED;
932                 }
933         } else {
934                 ASN_DEBUG("Decoding unconstrained integer %s", td->name);
935         }
936
937         /* X.691, #12.2.3, #12.2.4 */
938         do {
939                 ssize_t len;
940                 void *p;
941                 int ret;
942
943                 /* Get the PER length */
944                 len = aper_get_length(pd, -1, -1, &repeat);
945                 if(len < 0) ASN__DECODE_STARVED;
946
947                 p = REALLOC(st->buf, st->size + len + 1);
948                 if(!p) ASN__DECODE_FAILED;
949                 st->buf = (uint8_t *)p;
950
951                 ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
952                 if(ret < 0) ASN__DECODE_STARVED;
953                 st->size += len;
954         } while(repeat);
955         st->buf[st->size] = 0;  /* JIC */
956
957         /* #12.2.3 */
958         if(ct && ct->lower_bound) {
959                 /*
960                  * TODO: replace by in-place arithmetics.
961                  */
962                 long value;
963                 if(asn_INTEGER2long(st, &value))
964                         ASN__DECODE_FAILED;
965                 if(asn_long2INTEGER(st, value + ct->lower_bound))
966                         ASN__DECODE_FAILED;
967         }
968
969         return rval;
970 }
971
972 asn_enc_rval_t
973 INTEGER_encode_aper(const asn_TYPE_descriptor_t *td,
974                     const asn_per_constraints_t *constraints,
975                     const void *sptr, asn_per_outp_t *po) {
976         const asn_INTEGER_specifics_t *specs = (const asn_INTEGER_specifics_t *)td->specifics;
977         asn_enc_rval_t er = {0,0,0};
978         const INTEGER_t *st = (const INTEGER_t *)sptr;
979         const uint8_t *buf;
980         const uint8_t *end;
981         const asn_per_constraint_t *ct;
982         long value = 0;
983
984         if(!st || st->size == 0) ASN__ENCODE_FAILED;
985
986         if(!constraints) constraints = td->encoding_constraints.per_constraints;
987         ct = constraints ? &constraints->value : 0;
988
989         er.encoded = 0;
990
991         if(ct) {
992                 int inext = 0;
993                 if(specs && specs->field_unsigned) {
994                         unsigned long uval;
995                         if(asn_INTEGER2ulong(st, &uval))
996                                 ASN__ENCODE_FAILED;
997                         /* Check proper range */
998                         if(ct->flags & APC_SEMI_CONSTRAINED) {
999                                 if(uval < (unsigned long)ct->lower_bound)
1000                                         inext = 1;
1001                         } else if(ct->range_bits >= 0) {
1002                                 if(uval < (unsigned long)ct->lower_bound
1003                                         || uval > (unsigned long)ct->upper_bound)
1004                                         inext = 1;
1005                         }
1006                         ASN_DEBUG("Value %lu (%02x/%lu) lb %ld ub %ld %s",
1007                                   uval, st->buf[0], st->size,
1008                                   ct->lower_bound, ct->upper_bound,
1009                                   inext ? "ext" : "fix");
1010                         value = uval;
1011                 } else {
1012                         if(asn_INTEGER2long(st, &value)) ASN__ENCODE_FAILED;
1013                         /* Check proper range */
1014                         if(ct->flags & APC_SEMI_CONSTRAINED) {
1015                                 if(value < ct->lower_bound)
1016                                         inext = 1;
1017                         } else if(ct->range_bits >= 0) {
1018                                 if(value < ct->lower_bound
1019                                         || value > ct->upper_bound)
1020                                         inext = 1;
1021                         }
1022                         ASN_DEBUG("Value %lu (%02x/%lu) lb %ld ub %ld %s",
1023                                   value, st->buf[0], st->size,
1024                                   ct->lower_bound, ct->upper_bound,
1025                                   inext ? "ext" : "fix");
1026                 }
1027                 if(ct->flags & APC_EXTENSIBLE) {
1028                         if(per_put_few_bits(po, inext, 1))
1029                                 ASN__ENCODE_FAILED;
1030                         if(inext) ct = 0;
1031                 } else if(inext) {
1032                         ASN__ENCODE_FAILED;
1033                 }
1034         }
1035
1036         /* X.691, #12.2.2 */
1037         if(ct && ct->range_bits >= 0) {
1038                 unsigned long v;
1039
1040                 /* #10.5.6 */
1041                 ASN_DEBUG("Encoding integer %ld (%lu) with range %d bits",
1042                           value, value - ct->lower_bound, ct->range_bits);
1043
1044                 v = value - ct->lower_bound;
1045
1046                 /* #12 <= 8 -> alignment ? */
1047                 if (ct->range_bits < 8) {
1048                         if(per_put_few_bits(po, 0x00 | v, ct->range_bits))
1049                                 ASN__ENCODE_FAILED;
1050                 } else if (ct->range_bits == 8) {
1051                         if(aper_put_align(po) < 0)
1052                                 ASN__ENCODE_FAILED;
1053                         if(per_put_few_bits(po, 0x00 | v, ct->range_bits))
1054                                 ASN__ENCODE_FAILED;
1055                 } else if (ct->range_bits <= 16) {
1056                         /* Consume the bytes to align on octet */
1057                         if(aper_put_align(po) < 0)
1058                                 ASN__ENCODE_FAILED;
1059                         if(per_put_few_bits(po, 0x0000 | v,
1060                                             16))
1061                                 ASN__ENCODE_FAILED;
1062                 } else {
1063                         /* TODO: extend to >64 bits */
1064                         int64_t v64 = v;
1065                         int i, j;
1066                         int max_range_bytes = (ct->range_bits >> 3) +
1067                                               (((ct->range_bits % 8) > 0) ? 1 : 0);
1068
1069                         for (i = 1; ; i++) {
1070                                 int upper = 1 << i;
1071                                 if (upper >= max_range_bytes)
1072                                         break;
1073                         }
1074
1075                         for (j = sizeof(int64_t) -1; j != 0; j--) {
1076                                 int64_t val;
1077                                 val = v64 >> (j * 8);
1078                                 if (val != 0)
1079                                         break;
1080                         }
1081
1082                         /* Putting length in the minimum number of bits ex: 5 = 3bits */
1083                         if (per_put_few_bits(po, j, i))
1084                                 ASN__ENCODE_FAILED;
1085
1086                         /* Consume the bits to align on octet */
1087                         if (aper_put_align(po) < 0)
1088                                 ASN__ENCODE_FAILED;
1089                         /* Put the value */
1090                         for (i = 0; i <= j; i++) {
1091                                 if(per_put_few_bits(po, (v64 >> (8 * (j - i))) & 0xff, 8))
1092                                         ASN__ENCODE_FAILED;
1093                         }
1094                 }
1095                 ASN__ENCODED_OK(er);
1096         }
1097
1098         if(ct && ct->lower_bound) {
1099                 ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
1100                 /* TODO: adjust lower bound */
1101                 ASN__ENCODE_FAILED;
1102         }
1103
1104         for(buf = st->buf, end = st->buf + st->size; buf < end;) {
1105                 ssize_t mayEncode = aper_put_length(po, -1, end - buf);
1106                 if(mayEncode < 0)
1107                         ASN__ENCODE_FAILED;
1108                 if(per_put_many_bits(po, buf, 8 * mayEncode))
1109                         ASN__ENCODE_FAILED;
1110                 buf += mayEncode;
1111         }
1112
1113         ASN__ENCODED_OK(er);
1114 }
1115
1116 #endif  /* ASN_DISABLE_PER_SUPPORT */
1117
1118 static intmax_t
1119 asn__integer_convert(const uint8_t *b, const uint8_t *end) {
1120     uintmax_t value;
1121
1122     /* Perform the sign initialization */
1123     /* Actually value = -(*b >> 7); gains nothing, yet unreadable! */
1124     if((*b >> 7)) {
1125         value = (uintmax_t)(-1);
1126     } else {
1127         value = 0;
1128     }
1129
1130     /* Conversion engine */
1131     for(; b < end; b++) {
1132         value = (value << 8) | *b;
1133     }
1134
1135     return value;
1136 }
1137
1138 int
1139 asn_INTEGER2imax(const INTEGER_t *iptr, intmax_t *lptr) {
1140         uint8_t *b, *end;
1141         size_t size;
1142
1143         /* Sanity checking */
1144         if(!iptr || !iptr->buf || !lptr) {
1145                 errno = EINVAL;
1146                 return -1;
1147         }
1148
1149         /* Cache the begin/end of the buffer */
1150         b = iptr->buf;  /* Start of the INTEGER buffer */
1151         size = iptr->size;
1152         end = b + size; /* Where to stop */
1153
1154         if(size > sizeof(intmax_t)) {
1155                 uint8_t *end1 = end - 1;
1156                 /*
1157                  * Slightly more advanced processing,
1158                  * able to process INTEGERs with >sizeof(intmax_t) bytes
1159                  * when the actual value is small, e.g. for intmax_t == int32_t
1160                  * (0x0000000000abcdef INTEGER would yield a fine 0x00abcdef int32_t)
1161                  */
1162                 /* Skip out the insignificant leading bytes */
1163                 for(; b < end1; b++) {
1164                         switch(*b) {
1165                                 case 0x00: if((b[1] & 0x80) == 0) continue; break;
1166                                 case 0xff: if((b[1] & 0x80) != 0) continue; break;
1167                         }
1168                         break;
1169                 }
1170
1171                 size = end - b;
1172                 if(size > sizeof(intmax_t)) {
1173                         /* Still cannot fit the sizeof(intmax_t) */
1174                         errno = ERANGE;
1175                         return -1;
1176                 }
1177         }
1178
1179         /* Shortcut processing of a corner case */
1180         if(end == b) {
1181                 *lptr = 0;
1182                 return 0;
1183         }
1184
1185         *lptr = asn__integer_convert(b, end);
1186         return 0;
1187 }
1188
1189 /* FIXME: negative INTEGER values are silently interpreted as large unsigned ones. */
1190 int
1191 asn_INTEGER2umax(const INTEGER_t *iptr, uintmax_t *lptr) {
1192         uint8_t *b, *end;
1193         uintmax_t value;
1194         size_t size;
1195
1196         if(!iptr || !iptr->buf || !lptr) {
1197                 errno = EINVAL;
1198                 return -1;
1199         }
1200
1201         b = iptr->buf;
1202         size = iptr->size;
1203         end = b + size;
1204
1205         /* If all extra leading bytes are zeroes, ignore them */
1206         for(; size > sizeof(value); b++, size--) {
1207                 if(*b) {
1208                         /* Value won't fit into uintmax_t */
1209                         errno = ERANGE;
1210                         return -1;
1211                 }
1212         }
1213
1214         /* Conversion engine */
1215         for(value = 0; b < end; b++)
1216                 value = (value << 8) | *b;
1217
1218         *lptr = value;
1219         return 0;
1220 }
1221
1222 int
1223 asn_umax2INTEGER(INTEGER_t *st, uintmax_t value) {
1224     uint8_t *buf;
1225     uint8_t *end;
1226     uint8_t *b;
1227     int shr;
1228
1229     if(value <= ((~(uintmax_t)0) >> 1)) {
1230         return asn_imax2INTEGER(st, value);
1231     }
1232
1233     buf = (uint8_t *)MALLOC(1 + sizeof(value));
1234     if(!buf) return -1;
1235
1236     end = buf + (sizeof(value) + 1);
1237     buf[0] = 0; /* INTEGERs are signed. 0-byte indicates positive. */
1238     for(b = buf + 1, shr = (sizeof(value) - 1) * 8; b < end; shr -= 8, b++)
1239         *b = (uint8_t)(value >> shr);
1240
1241     if(st->buf) FREEMEM(st->buf);
1242     st->buf = buf;
1243     st->size = 1 + sizeof(value);
1244
1245         return 0;
1246 }
1247
1248 int
1249 asn_imax2INTEGER(INTEGER_t *st, intmax_t value) {
1250         uint8_t *buf, *bp;
1251         uint8_t *p;
1252         uint8_t *pstart;
1253         uint8_t *pend1;
1254         int littleEndian = 1;   /* Run-time detection */
1255         int add;
1256
1257         if(!st) {
1258                 errno = EINVAL;
1259                 return -1;
1260         }
1261
1262         buf = (uint8_t *)(long *)MALLOC(sizeof(value));
1263         if(!buf) return -1;
1264
1265         if(*(char *)&littleEndian) {
1266                 pstart = (uint8_t *)&value + sizeof(value) - 1;
1267                 pend1 = (uint8_t *)&value;
1268                 add = -1;
1269         } else {
1270                 pstart = (uint8_t *)&value;
1271                 pend1 = pstart + sizeof(value) - 1;
1272                 add = 1;
1273         }
1274
1275         /*
1276          * If the contents octet consists of more than one octet,
1277          * then bits of the first octet and bit 8 of the second octet:
1278          * a) shall not all be ones; and
1279          * b) shall not all be zero.
1280          */
1281         for(p = pstart; p != pend1; p += add) {
1282                 switch(*p) {
1283                 case 0x00: if((*(p+add) & 0x80) == 0)
1284                                 continue;
1285                         break;
1286                 case 0xff: if((*(p+add) & 0x80))
1287                                 continue;
1288                         break;
1289                 }
1290                 break;
1291         }
1292         /* Copy the integer body */
1293         for(bp = buf, pend1 += add; p != pend1; p += add)
1294                 *bp++ = *p;
1295
1296         if(st->buf) FREEMEM(st->buf);
1297         st->buf = buf;
1298         st->size = bp - buf;
1299
1300         return 0;
1301 }
1302
1303 int
1304 asn_INTEGER2long(const INTEGER_t *iptr, long *l) {
1305     intmax_t v;
1306     if(asn_INTEGER2imax(iptr, &v) == 0) {
1307         if(v < LONG_MIN || v > LONG_MAX) {
1308             errno = ERANGE;
1309             return -1;
1310         }
1311         *l = v;
1312         return 0;
1313     } else {
1314         return -1;
1315     }
1316 }
1317
1318 int
1319 asn_INTEGER2ulong(const INTEGER_t *iptr, unsigned long *l) {
1320     uintmax_t v;
1321     if(asn_INTEGER2umax(iptr, &v) == 0) {
1322         if(v > ULONG_MAX) {
1323             errno = ERANGE;
1324             return -1;
1325         }
1326         *l = v;
1327         return 0;
1328     } else {
1329         return -1;
1330     }
1331 }
1332
1333 int
1334 asn_long2INTEGER(INTEGER_t *st, long value) {
1335     return asn_imax2INTEGER(st, value);
1336 }
1337
1338 int
1339 asn_ulong2INTEGER(INTEGER_t *st, unsigned long value) {
1340     return asn_imax2INTEGER(st, value);
1341 }
1342
1343
1344 int
1345 asn_uint642INTEGER(INTEGER_t *st, uint64_t value) {
1346         uint8_t *buf;
1347         uint8_t *end;
1348         uint8_t *b;
1349         int shr;
1350
1351         if(value <= INT64_MAX)
1352                 return asn_int642INTEGER(st, value);
1353
1354         buf = (uint8_t *)MALLOC(1 + sizeof(value));
1355         if(!buf) return -1;
1356
1357         end = buf + (sizeof(value) + 1);
1358         buf[0] = 0;
1359         for(b = buf + 1, shr = (sizeof(value)-1)*8; b < end; shr -= 8, b++)
1360                 *b = (uint8_t)(value >> shr);
1361
1362         if(st->buf) FREEMEM(st->buf);
1363         st->buf = buf;
1364         st->size = 1 + sizeof(value);
1365
1366         return 0;
1367 }
1368
1369 int
1370 asn_int642INTEGER(INTEGER_t *st, int64_t value) {
1371         uint8_t *buf, *bp;
1372         uint8_t *p;
1373         uint8_t *pstart;
1374         uint8_t *pend1;
1375         int littleEndian = 1;   /* Run-time detection */
1376         int add;
1377
1378         if(!st) {
1379                 errno = EINVAL;
1380                 return -1;
1381         }
1382
1383         buf = (uint8_t *)MALLOC(sizeof(value));
1384         if(!buf) return -1;
1385
1386         if(*(char *)&littleEndian) {
1387                 pstart = (uint8_t *)&value + sizeof(value) - 1;
1388                 pend1 = (uint8_t *)&value;
1389                 add = -1;
1390         } else {
1391                 pstart = (uint8_t *)&value;
1392                 pend1 = pstart + sizeof(value) - 1;
1393                 add = 1;
1394         }
1395
1396         /*
1397          * If the contents octet consists of more than one octet,
1398          * then bits of the first octet and bit 8 of the second octet:
1399          * a) shall not all be ones; and
1400          * b) shall not all be zero.
1401          */
1402         for(p = pstart; p != pend1; p += add) {
1403                 switch(*p) {
1404                 case 0x00: if((*(p+add) & 0x80) == 0)
1405                                 continue;
1406                         break;
1407                 case 0xff: if((*(p+add) & 0x80))
1408                                 continue;
1409                         break;
1410                 }
1411                 break;
1412         }
1413         /* Copy the integer body */
1414         for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add)
1415                 *bp++ = *p;
1416
1417         if(st->buf) FREEMEM(st->buf);
1418         st->buf = buf;
1419         st->size = bp - buf;
1420
1421         return 0;
1422 }
1423
1424 /*
1425  * Parse the number in the given string until the given *end position,
1426  * returning the position after the last parsed character back using the
1427  * same (*end) pointer.
1428  * WARNING: This behavior is different from the standard strtol/strtoimax(3).
1429  */
1430 enum asn_strtox_result_e
1431 asn_strtoimax_lim(const char *str, const char **end, intmax_t *intp) {
1432         int sign = 1;
1433         intmax_t value;
1434
1435 #define ASN1_INTMAX_MAX ((~(uintmax_t)0) >> 1)
1436     const intmax_t upper_boundary = ASN1_INTMAX_MAX / 10;
1437         intmax_t last_digit_max = ASN1_INTMAX_MAX % 10;
1438 #undef  ASN1_INTMAX_MAX
1439
1440         if(str >= *end) return ASN_STRTOX_ERROR_INVAL;
1441
1442         switch(*str) {
1443         case '-':
1444                 last_digit_max++;
1445                 sign = -1;
1446                 /* FALL THROUGH */
1447         case '+':
1448                 str++;
1449                 if(str >= *end) {
1450                         *end = str;
1451                         return ASN_STRTOX_EXPECT_MORE;
1452                 }
1453         }
1454
1455         for(value = 0; str < (*end); str++) {
1456                 switch(*str) {
1457                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
1458                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: {
1459                         int d = *str - '0';
1460                         if(value < upper_boundary) {
1461                                 value = value * 10 + d;
1462                         } else if(value == upper_boundary) {
1463                                 if(d <= last_digit_max) {
1464                                         if(sign > 0) {
1465                                                 value = value * 10 + d;
1466                                         } else {
1467                                                 sign = 1;
1468                                                 value = -value * 10 - d;
1469                                         }
1470                                 } else {
1471                                         *end = str;
1472                                         return ASN_STRTOX_ERROR_RANGE;
1473                                 }
1474                         } else {
1475                                 *end = str;
1476                                 return ASN_STRTOX_ERROR_RANGE;
1477                         }
1478                     }
1479                     continue;
1480                 default:
1481                     *end = str;
1482                     *intp = sign * value;
1483                     return ASN_STRTOX_EXTRA_DATA;
1484                 }
1485         }
1486
1487         *end = str;
1488         *intp = sign * value;
1489         return ASN_STRTOX_OK;
1490 }
1491
1492 /*
1493  * Parse the number in the given string until the given *end position,
1494  * returning the position after the last parsed character back using the
1495  * same (*end) pointer.
1496  * WARNING: This behavior is different from the standard strtoul/strtoumax(3).
1497  */
1498 enum asn_strtox_result_e
1499 asn_strtoumax_lim(const char *str, const char **end, uintmax_t *uintp) {
1500         uintmax_t value;
1501
1502 #define ASN1_UINTMAX_MAX ((~(uintmax_t)0))
1503     const uintmax_t upper_boundary = ASN1_UINTMAX_MAX / 10;
1504     uintmax_t last_digit_max = ASN1_UINTMAX_MAX % 10;
1505 #undef ASN1_UINTMAX_MAX
1506
1507     if(str >= *end) return ASN_STRTOX_ERROR_INVAL;
1508
1509         switch(*str) {
1510         case '-':
1511         return ASN_STRTOX_ERROR_INVAL;
1512         case '+':
1513                 str++;
1514                 if(str >= *end) {
1515                         *end = str;
1516                         return ASN_STRTOX_EXPECT_MORE;
1517                 }
1518         }
1519
1520         for(value = 0; str < (*end); str++) {
1521                 switch(*str) {
1522                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
1523                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: {
1524                         unsigned int d = *str - '0';
1525                         if(value < upper_boundary) {
1526                                 value = value * 10 + d;
1527                         } else if(value == upper_boundary) {
1528                                 if(d <= last_digit_max) {
1529                     value = value * 10 + d;
1530                 } else {
1531                                         *end = str;
1532                                         return ASN_STRTOX_ERROR_RANGE;
1533                                 }
1534                         } else {
1535                                 *end = str;
1536                                 return ASN_STRTOX_ERROR_RANGE;
1537                         }
1538                     }
1539                     continue;
1540                 default:
1541                     *end = str;
1542                     *uintp = value;
1543                     return ASN_STRTOX_EXTRA_DATA;
1544                 }
1545         }
1546
1547         *end = str;
1548         *uintp = value;
1549         return ASN_STRTOX_OK;
1550 }
1551
1552 enum asn_strtox_result_e
1553 asn_strtol_lim(const char *str, const char **end, long *lp) {
1554     intmax_t value;
1555     switch(asn_strtoimax_lim(str, end, &value)) {
1556     case ASN_STRTOX_ERROR_RANGE:
1557         return ASN_STRTOX_ERROR_RANGE;
1558     case ASN_STRTOX_ERROR_INVAL:
1559         return ASN_STRTOX_ERROR_INVAL;
1560     case ASN_STRTOX_EXPECT_MORE:
1561         return ASN_STRTOX_EXPECT_MORE;
1562     case ASN_STRTOX_OK:
1563         if(value >= LONG_MIN && value <= LONG_MAX) {
1564             *lp = value;
1565             return ASN_STRTOX_OK;
1566         } else {
1567             return ASN_STRTOX_ERROR_RANGE;
1568         }
1569     case ASN_STRTOX_EXTRA_DATA:
1570         if(value >= LONG_MIN && value <= LONG_MAX) {
1571             *lp = value;
1572             return ASN_STRTOX_EXTRA_DATA;
1573         } else {
1574             return ASN_STRTOX_ERROR_RANGE;
1575         }
1576     }
1577
1578     assert(!"Unreachable");
1579     return ASN_STRTOX_ERROR_INVAL;
1580 }
1581
1582 enum asn_strtox_result_e
1583 asn_strtoul_lim(const char *str, const char **end, unsigned long *ulp) {
1584     uintmax_t value;
1585     switch(asn_strtoumax_lim(str, end, &value)) {
1586     case ASN_STRTOX_ERROR_RANGE:
1587         return ASN_STRTOX_ERROR_RANGE;
1588     case ASN_STRTOX_ERROR_INVAL:
1589         return ASN_STRTOX_ERROR_INVAL;
1590     case ASN_STRTOX_EXPECT_MORE:
1591         return ASN_STRTOX_EXPECT_MORE;
1592     case ASN_STRTOX_OK:
1593         if(value <= ULONG_MAX) {
1594             *ulp = value;
1595             return ASN_STRTOX_OK;
1596         } else {
1597             return ASN_STRTOX_ERROR_RANGE;
1598         }
1599     case ASN_STRTOX_EXTRA_DATA:
1600         if(value <= ULONG_MAX) {
1601             *ulp = value;
1602             return ASN_STRTOX_EXTRA_DATA;
1603         } else {
1604             return ASN_STRTOX_ERROR_RANGE;
1605         }
1606     }
1607
1608     assert(!"Unreachable");
1609     return ASN_STRTOX_ERROR_INVAL;
1610 }
1611
1612 int
1613 INTEGER_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
1614                      const void *bptr) {
1615     const INTEGER_t *a = aptr;
1616     const INTEGER_t *b = bptr;
1617
1618     (void)td;
1619
1620     if(a && b) {
1621         if(a->size && b->size) {
1622             int sign_a = (a->buf[0] & 0x80) ? -1 : 1;
1623             int sign_b = (b->buf[0] & 0x80) ? -1 : 1;
1624
1625             if(sign_a < sign_b) return -1;
1626             if(sign_a > sign_b) return 1;
1627
1628             /* The shortest integer wins, unless comparing negatives */
1629             if(a->size < b->size) {
1630                 return -1 * sign_a;
1631             } else if(a->size > b->size) {
1632                 return 1 * sign_b;
1633             }
1634
1635             return sign_a * memcmp(a->buf, b->buf, a->size);
1636         } else if(a->size) {
1637             int sign = (a->buf[0] & 0x80) ? -1 : 1;
1638             return (1) * sign;
1639         } else if(b->size) {
1640             int sign = (a->buf[0] & 0x80) ? -1 : 1;
1641             return (-1) * sign;
1642         } else {
1643             return 0;
1644         }
1645     } else if(!a && !b) {
1646         return 0;
1647     } else if(!a) {
1648         return -1;
1649     } else {
1650         return 1;
1651     }
1652
1653 }
1654
1655 asn_random_fill_result_t
1656 INTEGER_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
1657                     const asn_encoding_constraints_t *constraints,
1658                     size_t max_length) {
1659     const asn_INTEGER_specifics_t *specs =
1660         (const asn_INTEGER_specifics_t *)td->specifics;
1661     asn_random_fill_result_t result_ok = {ARFILL_OK, 1};
1662     asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
1663     asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
1664     INTEGER_t *st = *sptr;
1665     const asn_INTEGER_enum_map_t *emap;
1666     size_t emap_len;
1667     intmax_t value;
1668     int find_inside_map;
1669
1670     if(max_length == 0) return result_skipped;
1671
1672     if(st == NULL) {
1673         st = (INTEGER_t *)CALLOC(1, sizeof(*st));
1674         if(st == NULL) {
1675             return result_failed;
1676         }
1677     }
1678
1679     if(specs) {
1680         emap = specs->value2enum;
1681         emap_len = specs->map_count;
1682         if(specs->strict_enumeration) {
1683             find_inside_map = emap_len > 0;
1684         } else {
1685             find_inside_map = emap_len ? asn_random_between(0, 1) : 0;
1686         }
1687     } else {
1688         emap = 0;
1689         emap_len = 0;
1690         find_inside_map = 0;
1691     }
1692
1693     if(find_inside_map) {
1694         assert(emap_len > 0);
1695         value = emap[asn_random_between(0, emap_len - 1)].nat_value;
1696     } else {
1697         const asn_per_constraints_t *ct;
1698
1699         static const long variants[] = {
1700             -65536, -65535, -65534, -32769, -32768, -32767, -16385, -16384,
1701             -16383, -257,   -256,   -255,   -254,   -129,   -128,   -127,
1702             -126,   -1,     0,      1,      126,    127,    128,    129,
1703             254,    255,    256,    257,    16383,  16384,  16385,  32767,
1704             32768,  32769,  65534,  65535,  65536,  65537};
1705         if(specs && specs->field_unsigned) {
1706             assert(variants[18] == 0);
1707             value = variants[asn_random_between(
1708                 18, sizeof(variants) / sizeof(variants[0]) - 1)];
1709         } else {
1710             value = variants[asn_random_between(
1711                 0, sizeof(variants) / sizeof(variants[0]) - 1)];
1712         }
1713
1714         if(!constraints) constraints = &td->encoding_constraints;
1715         ct = constraints ? constraints->per_constraints : 0;
1716         if(ct && (ct->value.flags & APC_CONSTRAINED)) {
1717             if(value < ct->value.lower_bound || value > ct->value.upper_bound) {
1718                 value = asn_random_between(ct->value.lower_bound,
1719                                            ct->value.upper_bound);
1720             }
1721         }
1722     }
1723
1724     if(asn_imax2INTEGER(st, value)) {
1725         if(st == *sptr) {
1726             ASN_STRUCT_RESET(*td, st);
1727         } else {
1728             ASN_STRUCT_FREE(*td, st);
1729         }
1730         return result_failed;
1731     } else {
1732         *sptr = st;
1733         result_ok.length = st->size;
1734         return result_ok;
1735     }
1736 }