1 /*-
2  * Copyright (c) 2003, 2004, 2005, 2006, 2007 Lev Walkin <vlm@lionet.info>.
3  * All rights reserved.
4  * Redistribution and modifications are permitted subject to BSD license.
5  */
6 #include <asn_internal.h>
7 #include <INTEGER.h>
8 #include <asn_codecs_prim.h>	/* Encoder and decoder of a primitive type */
9 #include <errno.h>
10 
11 /*
12  * INTEGER basic type description.
13  */
14 static ber_tlv_tag_t asn_DEF_INTEGER_tags[] = {
15 	(ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
16 };
17 asn_TYPE_descriptor_t asn_DEF_INTEGER = {
18 	"INTEGER",
19 	"INTEGER",
20 	ASN__PRIMITIVE_TYPE_free,
21 	INTEGER_print,
22 	asn_generic_no_constraint,
23 	ber_decode_primitive,
24 	INTEGER_encode_der,
25 	INTEGER_decode_xer,
26 	INTEGER_encode_xer,
27 	INTEGER_decode_uper,	/* Unaligned PER decoder */
28 	INTEGER_encode_uper,	/* Unaligned PER encoder */
29 	0, /* Use generic outmost tag fetcher */
30 	asn_DEF_INTEGER_tags,
31 	sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
32 	asn_DEF_INTEGER_tags,	/* Same as above */
33 	sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
34 	0,	/* No PER visible constraints */
35 	0, 0,	/* No members */
36 	0	/* No specifics */
37 };
38 
39 /*
40  * Encode INTEGER type using DER.
41  */
42 asn_enc_rval_t
INTEGER_encode_der(asn_TYPE_descriptor_t * td,void * sptr,int tag_mode,ber_tlv_tag_t tag,asn_app_consume_bytes_f * cb,void * app_key)43 INTEGER_encode_der(asn_TYPE_descriptor_t *td, void *sptr,
44 	int tag_mode, ber_tlv_tag_t tag,
45 	asn_app_consume_bytes_f *cb, void *app_key) {
46 	INTEGER_t *st = (INTEGER_t *)sptr;
47 
48 	ASN_DEBUG("%s %s as INTEGER (tm=%d)",
49 		cb?"Encoding":"Estimating", td->name, tag_mode);
50 
51 	/*
52 	 * Canonicalize integer in the buffer.
53 	 * (Remove too long sign extension, remove some first 0x00 bytes)
54 	 */
55 	if(st->buf) {
56 		uint8_t *buf = st->buf;
57 		uint8_t *end1 = buf + st->size - 1;
58 		int shift;
59 
60 		/* Compute the number of superfluous leading bytes */
61 		for(; buf < end1; buf++) {
62 			/*
63 			 * If the contents octets of an integer value encoding
64 			 * consist of more than one octet, then the bits of the
65 			 * first octet and bit 8 of the second octet:
66 			 * a) shall not all be ones; and
67 			 * b) shall not all be zero.
68 			 */
69 			switch(*buf) {
70 			case 0x00: if((buf[1] & 0x80) == 0)
71 					continue;
72 				break;
73 			case 0xff: if((buf[1] & 0x80))
74 					continue;
75 				break;
76 			}
77 			break;
78 		}
79 
80 		/* Remove leading superfluous bytes from the integer */
81 		shift = buf - st->buf;
82 		if(shift) {
83 			uint8_t *nb = st->buf;
84 			uint8_t *end;
85 
86 			st->size -= shift;	/* New size, minus bad bytes */
87 			end = nb + st->size;
88 
89 			for(; nb < end; nb++, buf++)
90 				*nb = *buf;
91 		}
92 
93 	} /* if(1) */
94 
95 	return der_encode_primitive(td, sptr, tag_mode, tag, cb, app_key);
96 }
97 
98 static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop);
99 
100 /*
101  * INTEGER specific human-readable output.
102  */
103 static ssize_t
INTEGER__dump(asn_TYPE_descriptor_t * td,const INTEGER_t * st,asn_app_consume_bytes_f * cb,void * app_key,int plainOrXER)104 INTEGER__dump(asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) {
105 	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
106 	char scratch[32];	/* Enough for 64-bit integer */
107 	uint8_t *buf = st->buf;
108 	uint8_t *buf_end = st->buf + st->size;
109 	signed long accum;
110 	ssize_t wrote = 0;
111 	char *p;
112 	int ret;
113 
114 	/*
115 	 * Advance buf pointer until the start of the value's body.
116 	 * This will make us able to process large integers using simple case,
117 	 * when the actual value is small
118 	 * (0x0000000000abcdef would yield a fine 0x00abcdef)
119 	 */
120 	/* Skip the insignificant leading bytes */
121 	for(; buf < buf_end-1; buf++) {
122 		switch(*buf) {
123 		case 0x00: if((buf[1] & 0x80) == 0) continue; break;
124 		case 0xff: if((buf[1] & 0x80) != 0) continue; break;
125 		}
126 		break;
127 	}
128 
129 	/* Simple case: the integer size is small */
130 	if((size_t)(buf_end - buf) <= sizeof(accum)) {
131 		const asn_INTEGER_enum_map_t *el;
132 		size_t scrsize;
133 		char *scr;
134 
135 		if(buf == buf_end) {
136 			accum = 0;
137 		} else {
138 			accum = (*buf & 0x80) ? -1 : 0;
139 			for(; buf < buf_end; buf++)
140 				accum = (accum << 8) | *buf;
141 		}
142 
143 		el = INTEGER_map_value2enum(specs, accum);
144 		if(el) {
145 			scrsize = el->enum_len + 32;
146 			scr = (char *)alloca(scrsize);
147 			if(plainOrXER == 0)
148 				ret = snprintf(scr, scrsize,
149 					"%ld (%s)", accum, el->enum_name);
150 			else
151 				ret = snprintf(scr, scrsize,
152 					"<%s/>", el->enum_name);
153 		} else if(plainOrXER && specs && specs->strict_enumeration) {
154 			ASN_DEBUG("ASN.1 forbids dealing with "
155 				"unknown value of ENUMERATED type");
156 			errno = EPERM;
157 			return -1;
158 		} else {
159 			scrsize = sizeof(scratch);
160 			scr = scratch;
161 			ret = snprintf(scr, scrsize,
162 				(specs && specs->field_unsigned)
163 				?"%lu":"%ld", accum);
164 		}
165 		assert(ret > 0 && (size_t)ret < scrsize);
166 		return (cb(scr, ret, app_key) < 0) ? -1 : ret;
167 	} else if(plainOrXER && specs && specs->strict_enumeration) {
168 		/*
169 		 * Here and earlier, we cannot encode the ENUMERATED values
170 		 * if there is no corresponding identifier.
171 		 */
172 		ASN_DEBUG("ASN.1 forbids dealing with "
173 			"unknown value of ENUMERATED type");
174 		errno = EPERM;
175 		return -1;
176 	}
177 
178 	/* Output in the long xx:yy:zz... format */
179 	/* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */
180 	for(p = scratch; buf < buf_end; buf++) {
181 		static const char *h2c = "0123456789ABCDEF";
182 		if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) {
183 			/* Flush buffer */
184 			if(cb(scratch, p - scratch, app_key) < 0)
185 				return -1;
186 			wrote += p - scratch;
187 			p = scratch;
188 		}
189 		*p++ = h2c[*buf >> 4];
190 		*p++ = h2c[*buf & 0x0F];
191 		*p++ = 0x3a;	/* ":" */
192 	}
193 	if(p != scratch)
194 		p--;	/* Remove the last ":" */
195 
196 	wrote += p - scratch;
197 	return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
198 }
199 
200 /*
201  * INTEGER specific human-readable output.
202  */
203 int
INTEGER_print(asn_TYPE_descriptor_t * td,const void * sptr,int ilevel,asn_app_consume_bytes_f * cb,void * app_key)204 INTEGER_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
205 	asn_app_consume_bytes_f *cb, void *app_key) {
206 	const INTEGER_t *st = (const INTEGER_t *)sptr;
207 	ssize_t ret;
208 
209 	(void)td;
210 	(void)ilevel;
211 
212 	if(!st || !st->buf)
213 		ret = cb("<absent>", 8, app_key);
214 	else
215 		ret = INTEGER__dump(td, st, cb, app_key, 0);
216 
217 	return (ret < 0) ? -1 : 0;
218 }
219 
220 struct e2v_key {
221 	const char *start;
222 	const char *stop;
223 	asn_INTEGER_enum_map_t *vemap;
224 	unsigned int *evmap;
225 };
226 static int
INTEGER__compar_enum2value(const void * kp,const void * am)227 INTEGER__compar_enum2value(const void *kp, const void *am) {
228 	const struct e2v_key *key = (const struct e2v_key *)kp;
229 	const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
230 	const char *ptr, *end, *name;
231 
232 	/* Remap the element (sort by different criterion) */
233 	el = key->vemap + key->evmap[el - key->vemap];
234 
235 	/* Compare strings */
236 	for(ptr = key->start, end = key->stop, name = el->enum_name;
237 			ptr < end; ptr++, name++) {
238 		if(*ptr != *name)
239 			return *(const unsigned char *)ptr
240 				- *(const unsigned char *)name;
241 	}
242 	return name[0] ? -1 : 0;
243 }
244 
245 static const asn_INTEGER_enum_map_t *
INTEGER_map_enum2value(asn_INTEGER_specifics_t * specs,const char * lstart,const char * lstop)246 INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop) {
247 	asn_INTEGER_enum_map_t *el_found;
248 	int count = specs ? specs->map_count : 0;
249 	struct e2v_key key;
250 	const char *lp;
251 
252 	if(!count) return NULL;
253 
254 	/* Guaranteed: assert(lstart < lstop); */
255 	/* Figure out the tag name */
256 	for(lstart++, lp = lstart; lp < lstop; lp++) {
257 		switch(*lp) {
258 		case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */
259 		case 0x2f: /* '/' */ case 0x3e: /* '>' */
260 			break;
261 		default:
262 			continue;
263 		}
264 		break;
265 	}
266 	if(lp == lstop) return NULL;	/* No tag found */
267 	lstop = lp;
268 
269 	key.start = lstart;
270 	key.stop = lstop;
271 	key.vemap = specs->value2enum;
272 	key.evmap = specs->enum2value;
273 	el_found = (asn_INTEGER_enum_map_t *)bsearch(&key,
274 		specs->value2enum, count, sizeof(specs->value2enum[0]),
275 		INTEGER__compar_enum2value);
276 	if(el_found) {
277 		/* Remap enum2value into value2enum */
278 		el_found = key.vemap + key.evmap[el_found - key.vemap];
279 	}
280 	return el_found;
281 }
282 
283 static int
INTEGER__compar_value2enum(const void * kp,const void * am)284 INTEGER__compar_value2enum(const void *kp, const void *am) {
285 	long a = *(const long *)kp;
286 	const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
287 	long b = el->nat_value;
288 	if(a < b) return -1;
289 	else if(a == b) return 0;
290 	else return 1;
291 }
292 
293 const asn_INTEGER_enum_map_t *
INTEGER_map_value2enum(asn_INTEGER_specifics_t * specs,long value)294 INTEGER_map_value2enum(asn_INTEGER_specifics_t *specs, long value) {
295 	int count = specs ? specs->map_count : 0;
296 	if(!count) return 0;
297 	return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum,
298 		count, sizeof(specs->value2enum[0]),
299 		INTEGER__compar_value2enum);
300 }
301 
302 static int
INTEGER_st_prealloc(INTEGER_t * st,int min_size)303 INTEGER_st_prealloc(INTEGER_t *st, int min_size) {
304 	void *p = MALLOC(min_size + 1);
305 	if(p) {
306 		void *b = st->buf;
307 		st->size = 0;
308 		st->buf = p;
309 		FREEMEM(b);
310 		return 0;
311 	} else {
312 		return -1;
313 	}
314 }
315 
316 /*
317  * Decode the chunk of XML text encoding INTEGER.
318  */
319 static enum xer_pbd_rval
INTEGER__xer_body_decode(asn_TYPE_descriptor_t * td,void * sptr,const void * chunk_buf,size_t chunk_size)320 INTEGER__xer_body_decode(asn_TYPE_descriptor_t *td, void *sptr, const void *chunk_buf, size_t chunk_size) {
321 	INTEGER_t *st = (INTEGER_t *)sptr;
322 	long sign = 1;
323 	long value;
324 	const char *lp;
325 	const char *lstart = (const char *)chunk_buf;
326 	const char *lstop = lstart + chunk_size;
327 	enum {
328 		ST_SKIPSPACE,
329 		ST_SKIPSPHEX,
330 		ST_WAITDIGITS,
331 		ST_DIGITS,
332 		ST_HEXDIGIT1,
333 		ST_HEXDIGIT2,
334 		ST_HEXCOLON,
335 		ST_EXTRASTUFF
336 	} state = ST_SKIPSPACE;
337 
338 	if(chunk_size)
339 		ASN_DEBUG("INTEGER body %ld 0x%2x..0x%2x",
340 			(long)chunk_size, *lstart, lstop[-1]);
341 
342 	/*
343 	 * We may have received a tag here. It will be processed inline.
344 	 * Use strtoul()-like code and serialize the result.
345 	 */
346 	for(value = 0, lp = lstart; lp < lstop; lp++) {
347 		int lv = *lp;
348 		switch(lv) {
349 		case 0x09: case 0x0a: case 0x0d: case 0x20:
350 			switch(state) {
351 			case ST_SKIPSPACE:
352 			case ST_SKIPSPHEX:
353 				continue;
354 			case ST_HEXCOLON:
355 				if(xer_is_whitespace(lp, lstop - lp)) {
356 					lp = lstop - 1;
357 					continue;
358 				}
359 				break;
360 			default:
361 				break;
362 			}
363 			break;
364 		case 0x2d:	/* '-' */
365 			if(state == ST_SKIPSPACE) {
366 				sign = -1;
367 				state = ST_WAITDIGITS;
368 				continue;
369 			}
370 			break;
371 		case 0x2b:	/* '+' */
372 			if(state == ST_SKIPSPACE) {
373 				state = ST_WAITDIGITS;
374 				continue;
375 			}
376 			break;
377 		case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
378 		case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
379 			switch(state) {
380 			case ST_DIGITS: break;
381 			case ST_SKIPSPHEX:	/* Fall through */
382 			case ST_HEXDIGIT1:
383 				value = (lv - 0x30) << 4;
384 				state = ST_HEXDIGIT2;
385 				continue;
386 			case ST_HEXDIGIT2:
387 				value += (lv - 0x30);
388 				state = ST_HEXCOLON;
389 				st->buf[st->size++] = (uint8_t)value;
390 				continue;
391 			case ST_HEXCOLON:
392 				return XPBD_BROKEN_ENCODING;
393 			default:
394 				state = ST_DIGITS;
395 				break;
396 			}
397 
398 		    {
399 			long new_value = value * 10;
400 
401 			if(new_value / 10 != value)
402 				/* Overflow */
403 				return XPBD_DECODER_LIMIT;
404 
405 			value = new_value + (lv - 0x30);
406 			/* Check for two's complement overflow */
407 			if(value < 0) {
408 				/* Check whether it is a LONG_MIN */
409 				if(sign == -1
410 				&& (unsigned long)value
411 						== ~((unsigned long)-1 >> 1)) {
412 					sign = 1;
413 				} else {
414 					/* Overflow */
415 					return XPBD_DECODER_LIMIT;
416 				}
417 			}
418 		    }
419 			continue;
420 		case 0x3c:	/* '<' */
421 			if(state == ST_SKIPSPACE) {
422 				const asn_INTEGER_enum_map_t *el;
423 				el = INTEGER_map_enum2value(
424 					(asn_INTEGER_specifics_t *)
425 					td->specifics, lstart, lstop);
426 				if(el) {
427 					ASN_DEBUG("Found \"%s\" => %ld",
428 						el->enum_name, el->nat_value);
429 					state = ST_DIGITS;
430 					value = el->nat_value;
431 					lp = lstop - 1;
432 					continue;
433 				}
434 				ASN_DEBUG("Unknown identifier for INTEGER");
435 			}
436 			return XPBD_BROKEN_ENCODING;
437 		case 0x3a:	/* ':' */
438 			if(state == ST_HEXCOLON) {
439 				/* This colon is expected */
440 				state = ST_HEXDIGIT1;
441 				continue;
442 			} else if(state == ST_DIGITS) {
443 				/* The colon here means that we have
444 				 * decoded the first two hexadecimal
445 				 * places as a decimal value.
446 				 * Switch decoding mode. */
447 				ASN_DEBUG("INTEGER re-evaluate as hex form");
448 				if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
449 					return XPBD_SYSTEM_FAILURE;
450 				state = ST_SKIPSPHEX;
451 				lp = lstart - 1;
452 				continue;
453 			} else {
454 				ASN_DEBUG("state %d at %d", state, lp - lstart);
455 				break;
456 			}
457 		/* [A-Fa-f] */
458 		case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46:
459 		case 0x61:case 0x62:case 0x63:case 0x64:case 0x65:case 0x66:
460 			switch(state) {
461 			case ST_SKIPSPHEX:
462 			case ST_SKIPSPACE: /* Fall through */
463 			case ST_HEXDIGIT1:
464 				value = lv - ((lv < 0x61) ? 0x41 : 0x61);
465 				value += 10;
466 				value <<= 4;
467 				state = ST_HEXDIGIT2;
468 				continue;
469 			case ST_HEXDIGIT2:
470 				value += lv - ((lv < 0x61) ? 0x41 : 0x61);
471 				value += 10;
472 				st->buf[st->size++] = (uint8_t)value;
473 				state = ST_HEXCOLON;
474 				continue;
475 			case ST_DIGITS:
476 				ASN_DEBUG("INTEGER re-evaluate as hex form");
477 				if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
478 					return XPBD_SYSTEM_FAILURE;
479 				state = ST_SKIPSPHEX;
480 				lp = lstart - 1;
481 				continue;
482 			default:
483 				break;
484 			}
485 			break;
486 		}
487 
488 		/* Found extra non-numeric stuff */
489 		ASN_DEBUG("Found non-numeric 0x%2x at %d",
490 			lv, lp - lstart);
491 		state = ST_EXTRASTUFF;
492 		break;
493 	}
494 
495 	switch(state) {
496 	case ST_DIGITS:
497 		/* Everything is cool */
498 		break;
499 	case ST_HEXCOLON:
500 		st->buf[st->size] = 0;	/* Just in case termination */
501 		return XPBD_BODY_CONSUMED;
502 	case ST_HEXDIGIT1:
503 	case ST_HEXDIGIT2:
504 	case ST_SKIPSPHEX:
505 		return XPBD_BROKEN_ENCODING;
506 	default:
507 		if(xer_is_whitespace(lp, lstop - lp)) {
508 			if(state != ST_EXTRASTUFF)
509 				return XPBD_NOT_BODY_IGNORE;
510 			break;
511 		} else {
512 			ASN_DEBUG("INTEGER: No useful digits (state %d)",
513 				state);
514 			return XPBD_BROKEN_ENCODING;	/* No digits */
515 		}
516 		break;
517 	}
518 
519 	value *= sign;	/* Change sign, if needed */
520 
521 	if(asn_long2INTEGER(st, value))
522 		return XPBD_SYSTEM_FAILURE;
523 
524 	return XPBD_BODY_CONSUMED;
525 }
526 
527 asn_dec_rval_t
INTEGER_decode_xer(asn_codec_ctx_t * opt_codec_ctx,asn_TYPE_descriptor_t * td,void ** sptr,const char * opt_mname,const void * buf_ptr,size_t size)528 INTEGER_decode_xer(asn_codec_ctx_t *opt_codec_ctx,
529 	asn_TYPE_descriptor_t *td, void **sptr, const char *opt_mname,
530 		const void *buf_ptr, size_t size) {
531 
532 	return xer_decode_primitive(opt_codec_ctx, td,
533 		sptr, sizeof(INTEGER_t), opt_mname,
534 		buf_ptr, size, INTEGER__xer_body_decode);
535 }
536 
537 asn_enc_rval_t
INTEGER_encode_xer(asn_TYPE_descriptor_t * td,void * sptr,int ilevel,enum xer_encoder_flags_e flags,asn_app_consume_bytes_f * cb,void * app_key)538 INTEGER_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
539 	int ilevel, enum xer_encoder_flags_e flags,
540 		asn_app_consume_bytes_f *cb, void *app_key) {
541 	const INTEGER_t *st = (const INTEGER_t *)sptr;
542 	asn_enc_rval_t er;
543 
544 	(void)ilevel;
545 	(void)flags;
546 
547 	if(!st || !st->buf)
548 		_ASN_ENCODE_FAILED;
549 
550 	er.encoded = INTEGER__dump(td, st, cb, app_key, 1);
551 	if(er.encoded < 0) _ASN_ENCODE_FAILED;
552 
553 	_ASN_ENCODED_OK(er);
554 }
555 
556 asn_dec_rval_t
INTEGER_decode_uper(asn_codec_ctx_t * opt_codec_ctx,asn_TYPE_descriptor_t * td,asn_per_constraints_t * constraints,void ** sptr,asn_per_data_t * pd)557 INTEGER_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
558 	asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
559 	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
560 	asn_dec_rval_t rval = { RC_OK, 0 };
561 	INTEGER_t *st = (INTEGER_t *)*sptr;
562 	asn_per_constraint_t *ct;
563 	int repeat;
564 
565 	(void)opt_codec_ctx;
566 
567 	if(!st) {
568 		st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
569 		if(!st) _ASN_DECODE_FAILED;
570 	}
571 
572 	if(!constraints) constraints = td->per_constraints;
573 	ct = constraints ? &constraints->value : 0;
574 
575 	if(ct && ct->flags & APC_EXTENSIBLE) {
576 		int inext = per_get_few_bits(pd, 1);
577 		if(inext < 0) _ASN_DECODE_STARVED;
578 		if(inext) ct = 0;
579 	}
580 
581 	FREEMEM(st->buf);
582 	st->buf = 0;
583 	st->size = 0;
584 	if(ct) {
585 		if(ct->flags & APC_SEMI_CONSTRAINED) {
586 			st->buf = (uint8_t *)CALLOC(1, 2);
587 			if(!st->buf) _ASN_DECODE_FAILED;
588 			st->size = 1;
589 		} else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
590 			size_t size = (ct->range_bits + 7) >> 3;
591 			st->buf = (uint8_t *)MALLOC(1 + size + 1);
592 			if(!st->buf) _ASN_DECODE_FAILED;
593 			st->size = size;
594 		}
595 	}
596 
597 	/* X.691, #12.2.2 */
598 	if(ct && ct->flags != APC_UNCONSTRAINED) {
599 		/* #10.5.6 */
600 		ASN_DEBUG("Integer with range %d bits", ct->range_bits);
601 		if(ct->range_bits >= 0) {
602 			long value;
603 			if(ct->range_bits == 32) {
604 				long lhalf;
605 				value = per_get_few_bits(pd, 16);
606 				if(value < 0) _ASN_DECODE_STARVED;
607 				lhalf = per_get_few_bits(pd, 16);
608 				if(lhalf < 0) _ASN_DECODE_STARVED;
609 				value = (value << 16) | lhalf;
610 			} else {
611 				value = per_get_few_bits(pd, ct->range_bits);
612 				if(value < 0) _ASN_DECODE_STARVED;
613 			}
614 			ASN_DEBUG("Got value %ld + low %ld",
615 				value, ct->lower_bound);
616 			value += ct->lower_bound;
617 			if((specs && specs->field_unsigned)
618 				? asn_ulong2INTEGER(st, value)
619 				: asn_long2INTEGER(st, value))
620 				_ASN_DECODE_FAILED;
621 			return rval;
622 		}
623 	} else {
624 		ASN_DEBUG("Decoding unconstrained integer %s", td->name);
625 	}
626 
627 	/* X.691, #12.2.3, #12.2.4 */
628 	do {
629 		ssize_t len;
630 		void *p;
631 		int ret;
632 
633 		/* Get the PER length */
634 		len = uper_get_length(pd, -1, &repeat);
635 		if(len < 0) _ASN_DECODE_STARVED;
636 
637 		p = REALLOC(st->buf, st->size + len + 1);
638 		if(!p) _ASN_DECODE_FAILED;
639 		st->buf = (uint8_t *)p;
640 
641 		ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
642 		if(ret < 0) _ASN_DECODE_STARVED;
643 		st->size += len;
644 	} while(repeat);
645 	st->buf[st->size] = 0;	/* JIC */
646 
647 	/* #12.2.3 */
648 	if(ct && ct->lower_bound) {
649 		/*
650 		 * TODO: replace by in-place arithmetics.
651 		 */
652 		long value;
653 		if(asn_INTEGER2long(st, &value))
654 			_ASN_DECODE_FAILED;
655 		if(asn_long2INTEGER(st, value + ct->lower_bound))
656 			_ASN_DECODE_FAILED;
657 	}
658 
659 	return rval;
660 }
661 
662 asn_enc_rval_t
INTEGER_encode_uper(asn_TYPE_descriptor_t * td,asn_per_constraints_t * constraints,void * sptr,asn_per_outp_t * po)663 INTEGER_encode_uper(asn_TYPE_descriptor_t *td,
664 	asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
665 	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
666 	asn_enc_rval_t er;
667 	INTEGER_t *st = (INTEGER_t *)sptr;
668 	const uint8_t *buf;
669 	const uint8_t *end;
670 	asn_per_constraint_t *ct;
671 	long value = 0;
672 
673 	if(!st || st->size == 0) _ASN_ENCODE_FAILED;
674 
675 	if(!constraints) constraints = td->per_constraints;
676 	ct = constraints ? &constraints->value : 0;
677 
678 	er.encoded = 0;
679 
680 	if(ct) {
681 		int inext = 0;
682 		if(specs && specs->field_unsigned) {
683 			unsigned long uval;
684 			if(asn_INTEGER2ulong(st, &uval))
685 				_ASN_ENCODE_FAILED;
686 			/* Check proper range */
687 			if(ct->flags & APC_SEMI_CONSTRAINED) {
688 				if(uval < (unsigned long)ct->lower_bound)
689 					inext = 1;
690 			} else if(ct->range_bits >= 0) {
691 				if(uval < (unsigned long)ct->lower_bound
692 				|| uval > (unsigned long)ct->upper_bound)
693 					inext = 1;
694 			}
695 			ASN_DEBUG("Value %lu (%02x/%d) lb %lu ub %lu %s",
696 				uval, st->buf[0], st->size,
697 				ct->lower_bound, ct->upper_bound,
698 				inext ? "ext" : "fix");
699 			value = uval;
700 		} else {
701 			if(asn_INTEGER2long(st, &value))
702 				_ASN_ENCODE_FAILED;
703 			/* Check proper range */
704 			if(ct->flags & APC_SEMI_CONSTRAINED) {
705 				if(value < ct->lower_bound)
706 					inext = 1;
707 			} else if(ct->range_bits >= 0) {
708 				if(value < ct->lower_bound
709 				|| value > ct->upper_bound)
710 					inext = 1;
711 			}
712 			ASN_DEBUG("Value %ld (%02x/%d) lb %ld ub %ld %s",
713 				value, st->buf[0], st->size,
714 				ct->lower_bound, ct->upper_bound,
715 				inext ? "ext" : "fix");
716 		}
717 		if(ct->flags & APC_EXTENSIBLE) {
718 			if(per_put_few_bits(po, inext, 1))
719 				_ASN_ENCODE_FAILED;
720 			if(inext) ct = 0;
721 		} else if(inext) {
722 			_ASN_ENCODE_FAILED;
723 		}
724 	}
725 
726 
727 	/* X.691, #12.2.2 */
728 	if(ct && ct->range_bits >= 0) {
729 		/* #10.5.6 */
730 		ASN_DEBUG("Encoding integer with range %d bits",
731 			ct->range_bits);
732 		if(ct->range_bits == 32) {
733 			/* TODO: extend to >32 bits */
734 			long v = value - ct->lower_bound;
735 			if(per_put_few_bits(po, v >> 1, 31)
736 			|| per_put_few_bits(po, v, 1))
737 				_ASN_ENCODE_FAILED;
738 		} else {
739 			if(per_put_few_bits(po, value - ct->lower_bound,
740 				ct->range_bits))
741 				_ASN_ENCODE_FAILED;
742 		}
743 		_ASN_ENCODED_OK(er);
744 	}
745 
746 	if(ct && ct->lower_bound) {
747 		ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
748 		/* TODO: adjust lower bound */
749 		_ASN_ENCODE_FAILED;
750 	}
751 
752 	for(buf = st->buf, end = st->buf + st->size; buf < end;) {
753 		ssize_t mayEncode = uper_put_length(po, end - buf);
754 		if(mayEncode < 0)
755 			_ASN_ENCODE_FAILED;
756 		if(per_put_many_bits(po, buf, 8 * mayEncode))
757 			_ASN_ENCODE_FAILED;
758 		buf += mayEncode;
759 	}
760 
761 	_ASN_ENCODED_OK(er);
762 }
763 
764 int
asn_INTEGER2long(const INTEGER_t * iptr,long * lptr)765 asn_INTEGER2long(const INTEGER_t *iptr, long *lptr) {
766 	uint8_t *b, *end;
767 	size_t size;
768 	long l;
769 
770 	/* Sanity checking */
771 	if(!iptr || !iptr->buf || !lptr) {
772 		errno = EINVAL;
773 		return -1;
774 	}
775 
776 	/* Cache the begin/end of the buffer */
777 	b = iptr->buf;	/* Start of the INTEGER buffer */
778 	size = iptr->size;
779 	end = b + size;	/* Where to stop */
780 
781 	if(size > sizeof(long)) {
782 		uint8_t *end1 = end - 1;
783 		/*
784 		 * Slightly more advanced processing,
785 		 * able to >sizeof(long) bytes,
786 		 * when the actual value is small
787 		 * (0x0000000000abcdef would yield a fine 0x00abcdef)
788 		 */
789 		/* Skip out the insignificant leading bytes */
790 		for(; b < end1; b++) {
791 			switch(*b) {
792 			case 0x00: if((b[1] & 0x80) == 0) continue; break;
793 			case 0xff: if((b[1] & 0x80) != 0) continue; break;
794 			}
795 			break;
796 		}
797 
798 		size = end - b;
799 		if(size > sizeof(long)) {
800 			/* Still cannot fit the long */
801 			errno = ERANGE;
802 			return -1;
803 		}
804 	}
805 
806 	/* Shortcut processing of a corner case */
807 	if(end == b) {
808 		*lptr = 0;
809 		return 0;
810 	}
811 
812 	/* Perform the sign initialization */
813 	/* Actually l = -(*b >> 7); gains nothing, yet unreadable! */
814 	if((*b >> 7)) l = -1; else l = 0;
815 
816 	/* Conversion engine */
817 	for(; b < end; b++)
818 		l = (l << 8) | *b;
819 
820 	*lptr = l;
821 	return 0;
822 }
823 
824 int
asn_INTEGER2ulong(const INTEGER_t * iptr,unsigned long * lptr)825 asn_INTEGER2ulong(const INTEGER_t *iptr, unsigned long *lptr) {
826 	uint8_t *b, *end;
827 	unsigned long l;
828 	size_t size;
829 
830 	if(!iptr || !iptr->buf || !lptr) {
831 		errno = EINVAL;
832 		return -1;
833 	}
834 
835 	b = iptr->buf;
836 	size = iptr->size;
837 	end = b + size;
838 
839 	/* If all extra leading bytes are zeroes, ignore them */
840 	for(; size > sizeof(unsigned long); b++, size--) {
841 		if(*b) {
842 			/* Value won't fit unsigned long */
843 			errno = ERANGE;
844 			return -1;
845 		}
846 	}
847 
848 	/* Conversion engine */
849 	for(l = 0; b < end; b++)
850 		l = (l << 8) | *b;
851 
852 	*lptr = l;
853 	return 0;
854 }
855 
856 int
asn_ulong2INTEGER(INTEGER_t * st,unsigned long value)857 asn_ulong2INTEGER(INTEGER_t *st, unsigned long value) {
858 	uint8_t *buf;
859 	uint8_t *end;
860 	uint8_t *b;
861 	int shr;
862 
863 	if(value <= LONG_MAX)
864 		return asn_long2INTEGER(st, value);
865 
866 	buf = (uint8_t *)MALLOC(1 + sizeof(value));
867 	if(!buf) return -1;
868 
869 	end = buf + (sizeof(value) + 1);
870 	buf[0] = 0;
871 	for(b = buf + 1, shr = (sizeof(long)-1)*8; b < end; shr -= 8, b++)
872 		*b = (uint8_t)(value >> shr);
873 
874 	if(st->buf) FREEMEM(st->buf);
875 	st->buf = buf;
876 	st->size = 1 + sizeof(value);
877 
878 	return 0;
879 }
880 
881 int
asn_long2INTEGER(INTEGER_t * st,long value)882 asn_long2INTEGER(INTEGER_t *st, long value) {
883 	uint8_t *buf, *bp;
884 	uint8_t *p;
885 	uint8_t *pstart;
886 	uint8_t *pend1;
887 	int littleEndian = 1;	/* Run-time detection */
888 	int add;
889 
890 	if(!st) {
891 		errno = EINVAL;
892 		return -1;
893 	}
894 
895 	buf = (uint8_t *)MALLOC(sizeof(value));
896 	if(!buf) return -1;
897 
898 	if(*(char *)&littleEndian) {
899 		pstart = (uint8_t *)&value + sizeof(value) - 1;
900 		pend1 = (uint8_t *)&value;
901 		add = -1;
902 	} else {
903 		pstart = (uint8_t *)&value;
904 		pend1 = pstart + sizeof(value) - 1;
905 		add = 1;
906 	}
907 
908 	/*
909 	 * If the contents octet consists of more than one octet,
910 	 * then bits of the first octet and bit 8 of the second octet:
911 	 * a) shall not all be ones; and
912 	 * b) shall not all be zero.
913 	 */
914 	for(p = pstart; p != pend1; p += add) {
915 		switch(*p) {
916 		case 0x00: if((*(p+add) & 0x80) == 0)
917 				continue;
918 			break;
919 		case 0xff: if((*(p+add) & 0x80))
920 				continue;
921 			break;
922 		}
923 		break;
924 	}
925 	/* Copy the integer body */
926 	for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add)
927 		*bp++ = *p;
928 
929 	if(st->buf) FREEMEM(st->buf);
930 	st->buf = buf;
931 	st->size = bp - buf;
932 
933 	return 0;
934 }
935