INTEGER.c 23.9 KB
Newer Older
Lev Walkin's avatar
Lev Walkin committed
1
/*-
2
 * Copyright (c) 2003, 2004, 2005, 2006, 2007 Lev Walkin <vlm@lionet.info>.
Lev Walkin's avatar
Lev Walkin committed
3
 * All rights reserved.
Lev Walkin's avatar
Lev Walkin committed
4
5
 * Redistribution and modifications are permitted subject to BSD license.
 */
Lev Walkin's avatar
Lev Walkin committed
6
#include <asn_internal.h>
Lev Walkin's avatar
Lev Walkin committed
7
#include <INTEGER.h>
8
#include <asn_codecs_prim.h>	/* Encoder and decoder of a primitive type */
Lev Walkin's avatar
Lev Walkin committed
9
10
11
12
13
#include <errno.h>

/*
 * INTEGER basic type description.
 */
Lev Walkin's avatar
Lev Walkin committed
14
static ber_tlv_tag_t asn_DEF_INTEGER_tags[] = {
Lev Walkin's avatar
Lev Walkin committed
15
16
	(ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
};
Lev Walkin's avatar
Lev Walkin committed
17
asn_TYPE_descriptor_t asn_DEF_INTEGER = {
Lev Walkin's avatar
Lev Walkin committed
18
	"INTEGER",
Lev Walkin's avatar
Lev Walkin committed
19
	"INTEGER",
20
	ASN__PRIMITIVE_TYPE_free,
Lev Walkin's avatar
Lev Walkin committed
21
	INTEGER_print,
Lev Walkin's avatar
Lev Walkin committed
22
	asn_generic_no_constraint,
23
	ber_decode_primitive,
Lev Walkin's avatar
Lev Walkin committed
24
	INTEGER_encode_der,
25
	INTEGER_decode_xer,
Lev Walkin's avatar
Lev Walkin committed
26
	INTEGER_encode_xer,
Lev Walkin's avatar
Lev Walkin committed
27
28
29
30
#ifdef	ASN_DISABLE_PER_SUPPORT
	0,
	0,
#else
Lev Walkin's avatar
Lev Walkin committed
31
	INTEGER_decode_uper,	/* Unaligned PER decoder */
Lev Walkin's avatar
Lev Walkin committed
32
	INTEGER_encode_uper,	/* Unaligned PER encoder */
Lev Walkin's avatar
Lev Walkin committed
33
#endif	/* ASN_DISABLE_PER_SUPPORT */
Lev Walkin's avatar
Lev Walkin committed
34
	0, /* Use generic outmost tag fetcher */
Lev Walkin's avatar
Lev Walkin committed
35
36
37
38
	asn_DEF_INTEGER_tags,
	sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
	asn_DEF_INTEGER_tags,	/* Same as above */
	sizeof(asn_DEF_INTEGER_tags) / sizeof(asn_DEF_INTEGER_tags[0]),
Lev Walkin's avatar
Lev Walkin committed
39
	0,	/* No PER visible constraints */
Lev Walkin's avatar
Lev Walkin committed
40
	0, 0,	/* No members */
41
	0	/* No specifics */
Lev Walkin's avatar
Lev Walkin committed
42
43
44
45
46
};

/*
 * Encode INTEGER type using DER.
 */
Lev Walkin's avatar
Lev Walkin committed
47
asn_enc_rval_t
Lev Walkin's avatar
Lev Walkin committed
48
INTEGER_encode_der(asn_TYPE_descriptor_t *td, void *sptr,
Lev Walkin's avatar
Lev Walkin committed
49
50
	int tag_mode, ber_tlv_tag_t tag,
	asn_app_consume_bytes_f *cb, void *app_key) {
51
	INTEGER_t *st = (INTEGER_t *)sptr;
Lev Walkin's avatar
Lev Walkin committed
52
53

	ASN_DEBUG("%s %s as INTEGER (tm=%d)",
54
		cb?"Encoding":"Estimating", td->name, tag_mode);
Lev Walkin's avatar
Lev Walkin committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

	/*
	 * Canonicalize integer in the buffer.
	 * (Remove too long sign extension, remove some first 0x00 bytes)
	 */
	if(st->buf) {
		uint8_t *buf = st->buf;
		uint8_t *end1 = buf + st->size - 1;
		int shift;

		/* Compute the number of superfluous leading bytes */
		for(; buf < end1; buf++) {
			/*
			 * If the contents octets of an integer value encoding
			 * consist of more than one octet, then the bits of the
			 * first octet and bit 8 of the second octet:
			 * a) shall not all be ones; and
			 * b) shall not all be zero.
			 */
			switch(*buf) {
			case 0x00: if((buf[1] & 0x80) == 0)
					continue;
				break;
			case 0xff: if((buf[1] & 0x80))
					continue;
				break;
			}
			break;
		}

		/* Remove leading superfluous bytes from the integer */
		shift = buf - st->buf;
		if(shift) {
			uint8_t *nb = st->buf;
			uint8_t *end;

			st->size -= shift;	/* New size, minus bad bytes */
			end = nb + st->size;

			for(; nb < end; nb++, buf++)
				*nb = *buf;
		}

	} /* if(1) */

100
	return der_encode_primitive(td, sptr, tag_mode, tag, cb, app_key);
Lev Walkin's avatar
Lev Walkin committed
101
102
}

103
static const asn_INTEGER_enum_map_t *INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop);
Lev Walkin's avatar
Lev Walkin committed
104

Lev Walkin's avatar
Lev Walkin committed
105
106
107
/*
 * INTEGER specific human-readable output.
 */
Lev Walkin's avatar
Lev Walkin committed
108
static ssize_t
Lev Walkin's avatar
Lev Walkin committed
109
110
INTEGER__dump(asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) {
	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
Lev Walkin's avatar
Lev Walkin committed
111
	char scratch[32];	/* Enough for 64-bit integer */
Lev Walkin's avatar
Lev Walkin committed
112
113
114
	uint8_t *buf = st->buf;
	uint8_t *buf_end = st->buf + st->size;
	signed long accum;
Lev Walkin's avatar
Lev Walkin committed
115
	ssize_t wrote = 0;
Lev Walkin's avatar
Lev Walkin committed
116
117
118
	char *p;
	int ret;

Lev Walkin's avatar
Lev Walkin committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
	/*
	 * Advance buf pointer until the start of the value's body.
	 * This will make us able to process large integers using simple case,
	 * when the actual value is small
	 * (0x0000000000abcdef would yield a fine 0x00abcdef)
	 */
	/* Skip the insignificant leading bytes */
	for(; buf < buf_end-1; buf++) {
		switch(*buf) {
		case 0x00: if((buf[1] & 0x80) == 0) continue; break;
		case 0xff: if((buf[1] & 0x80) != 0) continue; break;
		}
		break;
	}

Lev Walkin's avatar
Lev Walkin committed
134
	/* Simple case: the integer size is small */
Lev Walkin's avatar
Lev Walkin committed
135
	if((size_t)(buf_end - buf) <= sizeof(accum)) {
Lev Walkin's avatar
Lev Walkin committed
136
137
138
139
140
141
142
143
144
145
146
147
		const asn_INTEGER_enum_map_t *el;
		size_t scrsize;
		char *scr;

		if(buf == buf_end) {
			accum = 0;
		} else {
			accum = (*buf & 0x80) ? -1 : 0;
			for(; buf < buf_end; buf++)
				accum = (accum << 8) | *buf;
		}

148
		el = INTEGER_map_value2enum(specs, accum);
Lev Walkin's avatar
Lev Walkin committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
		if(el) {
			scrsize = el->enum_len + 32;
			scr = (char *)alloca(scrsize);
			if(plainOrXER == 0)
				ret = snprintf(scr, scrsize,
					"%ld (%s)", accum, el->enum_name);
			else
				ret = snprintf(scr, scrsize,
					"<%s/>", el->enum_name);
		} else if(plainOrXER && specs && specs->strict_enumeration) {
			ASN_DEBUG("ASN.1 forbids dealing with "
				"unknown value of ENUMERATED type");
			errno = EPERM;
			return -1;
		} else {
			scrsize = sizeof(scratch);
			scr = scratch;
166
167
168
			ret = snprintf(scr, scrsize,
				(specs && specs->field_unsigned)
				?"%lu":"%ld", accum);
Lev Walkin's avatar
Lev Walkin committed
169
170
171
172
173
174
175
176
177
178
179
180
		}
		assert(ret > 0 && (size_t)ret < scrsize);
		return (cb(scr, ret, app_key) < 0) ? -1 : ret;
	} else if(plainOrXER && specs && specs->strict_enumeration) {
		/*
		 * Here and earlier, we cannot encode the ENUMERATED values
		 * if there is no corresponding identifier.
		 */
		ASN_DEBUG("ASN.1 forbids dealing with "
			"unknown value of ENUMERATED type");
		errno = EPERM;
		return -1;
Lev Walkin's avatar
Lev Walkin committed
181
182
183
	}

	/* Output in the long xx:yy:zz... format */
Lev Walkin's avatar
Lev Walkin committed
184
	/* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */
Lev Walkin's avatar
Lev Walkin committed
185
	for(p = scratch; buf < buf_end; buf++) {
Lev Walkin's avatar
Lev Walkin committed
186
		static const char *h2c = "0123456789ABCDEF";
Lev Walkin's avatar
Lev Walkin committed
187
		if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) {
Lev Walkin's avatar
Lev Walkin committed
188
			/* Flush buffer */
Lev Walkin's avatar
Lev Walkin committed
189
			if(cb(scratch, p - scratch, app_key) < 0)
Lev Walkin's avatar
Lev Walkin committed
190
				return -1;
Lev Walkin's avatar
Lev Walkin committed
191
			wrote += p - scratch;
Lev Walkin's avatar
Lev Walkin committed
192
193
194
195
			p = scratch;
		}
		*p++ = h2c[*buf >> 4];
		*p++ = h2c[*buf & 0x0F];
Lev Walkin's avatar
Lev Walkin committed
196
		*p++ = 0x3a;	/* ":" */
Lev Walkin's avatar
Lev Walkin committed
197
	}
Lev Walkin's avatar
Lev Walkin committed
198
	if(p != scratch)
Lev Walkin's avatar
Lev Walkin committed
199
		p--;	/* Remove the last ":" */
Lev Walkin's avatar
Lev Walkin committed
200

Lev Walkin's avatar
Lev Walkin committed
201
202
203
204
205
206
207
208
	wrote += p - scratch;
	return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
}

/*
 * INTEGER specific human-readable output.
 */
int
Lev Walkin's avatar
Lev Walkin committed
209
INTEGER_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
Lev Walkin's avatar
Lev Walkin committed
210
211
	asn_app_consume_bytes_f *cb, void *app_key) {
	const INTEGER_t *st = (const INTEGER_t *)sptr;
212
	ssize_t ret;
Lev Walkin's avatar
Lev Walkin committed
213
214
215
216

	(void)td;
	(void)ilevel;

Lev Walkin's avatar
Lev Walkin committed
217
	if(!st || !st->buf)
218
219
		ret = cb("<absent>", 8, app_key);
	else
Lev Walkin's avatar
Lev Walkin committed
220
		ret = INTEGER__dump(td, st, cb, app_key, 0);
Lev Walkin's avatar
Lev Walkin committed
221

222
	return (ret < 0) ? -1 : 0;
Lev Walkin's avatar
Lev Walkin committed
223
224
}

Lev Walkin's avatar
Lev Walkin committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
struct e2v_key {
	const char *start;
	const char *stop;
	asn_INTEGER_enum_map_t *vemap;
	unsigned int *evmap;
};
static int
INTEGER__compar_enum2value(const void *kp, const void *am) {
	const struct e2v_key *key = (const struct e2v_key *)kp;
	const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
	const char *ptr, *end, *name;

	/* Remap the element (sort by different criterion) */
	el = key->vemap + key->evmap[el - key->vemap];

	/* Compare strings */
	for(ptr = key->start, end = key->stop, name = el->enum_name;
			ptr < end; ptr++, name++) {
		if(*ptr != *name)
			return *(const unsigned char *)ptr
				- *(const unsigned char *)name;
	}
	return name[0] ? -1 : 0;
}

static const asn_INTEGER_enum_map_t *
251
INTEGER_map_enum2value(asn_INTEGER_specifics_t *specs, const char *lstart, const char *lstop) {
252
	asn_INTEGER_enum_map_t *el_found;
Lev Walkin's avatar
Lev Walkin committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
	int count = specs ? specs->map_count : 0;
	struct e2v_key key;
	const char *lp;

	if(!count) return NULL;

	/* Guaranteed: assert(lstart < lstop); */
	/* Figure out the tag name */
	for(lstart++, lp = lstart; lp < lstop; lp++) {
		switch(*lp) {
		case 9: case 10: case 11: case 12: case 13: case 32: /* WSP */
		case 0x2f: /* '/' */ case 0x3e: /* '>' */
			break;
		default:
			continue;
		}
		break;
	}
	if(lp == lstop) return NULL;	/* No tag found */
	lstop = lp;

	key.start = lstart;
	key.stop = lstop;
	key.vemap = specs->value2enum;
	key.evmap = specs->enum2value;
278
279
280
281
282
283
284
285
	el_found = (asn_INTEGER_enum_map_t *)bsearch(&key,
		specs->value2enum, count, sizeof(specs->value2enum[0]),
		INTEGER__compar_enum2value);
	if(el_found) {
		/* Remap enum2value into value2enum */
		el_found = key.vemap + key.evmap[el_found - key.vemap];
	}
	return el_found;
Lev Walkin's avatar
Lev Walkin committed
286
287
288
289
290
291
292
293
294
295
296
297
}

static int
INTEGER__compar_value2enum(const void *kp, const void *am) {
	long a = *(const long *)kp;
	const asn_INTEGER_enum_map_t *el = (const asn_INTEGER_enum_map_t *)am;
	long b = el->nat_value;
	if(a < b) return -1;
	else if(a == b) return 0;
	else return 1;
}

298
299
const asn_INTEGER_enum_map_t *
INTEGER_map_value2enum(asn_INTEGER_specifics_t *specs, long value) {
Lev Walkin's avatar
Lev Walkin committed
300
301
302
303
304
305
306
	int count = specs ? specs->map_count : 0;
	if(!count) return 0;
	return (asn_INTEGER_enum_map_t *)bsearch(&value, specs->value2enum,
		count, sizeof(specs->value2enum[0]),
		INTEGER__compar_value2enum);
}

Lev Walkin's avatar
Lev Walkin committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
static int
INTEGER_st_prealloc(INTEGER_t *st, int min_size) {
	void *p = MALLOC(min_size + 1);
	if(p) {
		void *b = st->buf;
		st->size = 0;
		st->buf = p;
		FREEMEM(b);
		return 0;
	} else {
		return -1;
	}
}

321
322
323
/*
 * Decode the chunk of XML text encoding INTEGER.
 */
324
325
static enum xer_pbd_rval
INTEGER__xer_body_decode(asn_TYPE_descriptor_t *td, void *sptr, const void *chunk_buf, size_t chunk_size) {
Lev Walkin's avatar
Lev Walkin committed
326
	INTEGER_t *st = (INTEGER_t *)sptr;
Lev Walkin's avatar
Lev Walkin committed
327
	long dec_value;
Lev Walkin's avatar
Lev Walkin committed
328
	long hex_value;
Lev Walkin's avatar
Lev Walkin committed
329
330
331
	const char *lp;
	const char *lstart = (const char *)chunk_buf;
	const char *lstop = lstart + chunk_size;
332
	enum {
Lev Walkin's avatar
Lev Walkin committed
333
		ST_LEADSPACE,
Lev Walkin's avatar
Lev Walkin committed
334
		ST_SKIPSPHEX,
335
336
		ST_WAITDIGITS,
		ST_DIGITS,
Lev Walkin's avatar
Lev Walkin committed
337
		ST_DIGITS_TRAILSPACE,
Lev Walkin's avatar
Lev Walkin committed
338
339
		ST_HEXDIGIT1,
		ST_HEXDIGIT2,
Lev Walkin's avatar
Lev Walkin committed
340
		ST_HEXDIGITS_TRAILSPACE,
Lev Walkin's avatar
Lev Walkin committed
341
		ST_HEXCOLON,
Lev Walkin's avatar
Lev Walkin committed
342
343
344
345
346
		ST_END_ENUM,
		ST_UNEXPECTED
	} state = ST_LEADSPACE;
	const char *dec_value_start = 0; /* INVARIANT: always !0 in ST_DIGITS */
	const char *dec_value_end = 0;
Lev Walkin's avatar
Lev Walkin committed
347

Lev Walkin's avatar
Lev Walkin committed
348
	if(chunk_size)
Lev Walkin's avatar
Lev Walkin committed
349
350
		ASN_DEBUG("INTEGER body %ld 0x%2x..0x%2x",
			(long)chunk_size, *lstart, lstop[-1]);
Lev Walkin's avatar
Lev Walkin committed
351

352
353
354
	if(INTEGER_st_prealloc(st, (chunk_size/3) + 1))
		return XPBD_SYSTEM_FAILURE;

355
	/*
Lev Walkin's avatar
Lev Walkin committed
356
357
	 * We may have received a tag here. It will be processed inline.
	 * Use strtoul()-like code and serialize the result.
358
	 */
Lev Walkin's avatar
Lev Walkin committed
359
	for(lp = lstart; lp < lstop; lp++) {
Lev Walkin's avatar
Lev Walkin committed
360
		int lv = *lp;
361
362
		switch(lv) {
		case 0x09: case 0x0a: case 0x0d: case 0x20:
Lev Walkin's avatar
Lev Walkin committed
363
			switch(state) {
Lev Walkin's avatar
Lev Walkin committed
364
365
			case ST_LEADSPACE:
			case ST_DIGITS_TRAILSPACE:
Lev Walkin's avatar
Lev Walkin committed
366
			case ST_HEXDIGITS_TRAILSPACE:
Lev Walkin's avatar
Lev Walkin committed
367
368
			case ST_SKIPSPHEX:
				continue;
Lev Walkin's avatar
Lev Walkin committed
369
370
371
372
			case ST_DIGITS:
				dec_value_end = lp;
				state = ST_DIGITS_TRAILSPACE;
				continue;
Lev Walkin's avatar
Lev Walkin committed
373
374
375
			case ST_HEXCOLON:
				state = ST_HEXDIGITS_TRAILSPACE;
				continue;
Lev Walkin's avatar
Lev Walkin committed
376
377
378
			default:
				break;
			}
379
380
			break;
		case 0x2d:	/* '-' */
Lev Walkin's avatar
Lev Walkin committed
381
382
383
			if(state == ST_LEADSPACE) {
				dec_value = 0;
				dec_value_start = lp;
384
385
386
387
388
				state = ST_WAITDIGITS;
				continue;
			}
			break;
		case 0x2b:	/* '+' */
Lev Walkin's avatar
Lev Walkin committed
389
390
391
			if(state == ST_LEADSPACE) {
				dec_value = 0;
				dec_value_start = lp;
392
393
394
395
396
397
				state = ST_WAITDIGITS;
				continue;
			}
			break;
		case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
		case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
Lev Walkin's avatar
Lev Walkin committed
398
			switch(state) {
Lev Walkin's avatar
Lev Walkin committed
399
			case ST_DIGITS: continue;
Lev Walkin's avatar
Lev Walkin committed
400
401
			case ST_SKIPSPHEX:	/* Fall through */
			case ST_HEXDIGIT1:
Lev Walkin's avatar
Lev Walkin committed
402
				hex_value = (lv - 0x30) << 4;
Lev Walkin's avatar
Lev Walkin committed
403
404
405
				state = ST_HEXDIGIT2;
				continue;
			case ST_HEXDIGIT2:
Lev Walkin's avatar
Lev Walkin committed
406
				hex_value += (lv - 0x30);
Lev Walkin's avatar
Lev Walkin committed
407
				state = ST_HEXCOLON;
Lev Walkin's avatar
Lev Walkin committed
408
				st->buf[st->size++] = (uint8_t)hex_value;
Lev Walkin's avatar
Lev Walkin committed
409
410
411
				continue;
			case ST_HEXCOLON:
				return XPBD_BROKEN_ENCODING;
Lev Walkin's avatar
Lev Walkin committed
412
413
414
415
416
			case ST_LEADSPACE:
				dec_value = 0;
				dec_value_start = lp;
				/* FALL THROUGH */
			case ST_WAITDIGITS:
Lev Walkin's avatar
Lev Walkin committed
417
				state = ST_DIGITS;
Lev Walkin's avatar
Lev Walkin committed
418
				continue;
Lev Walkin's avatar
Lev Walkin committed
419
420
			default:
				break;
421
			}
Lev Walkin's avatar
Lev Walkin committed
422
423
424
			break;
		case 0x3c:	/* '<', start of XML encoded enumeration */
			if(state == ST_LEADSPACE) {
Lev Walkin's avatar
Lev Walkin committed
425
				const asn_INTEGER_enum_map_t *el;
426
				el = INTEGER_map_enum2value(
Lev Walkin's avatar
Lev Walkin committed
427
428
429
430
431
					(asn_INTEGER_specifics_t *)
					td->specifics, lstart, lstop);
				if(el) {
					ASN_DEBUG("Found \"%s\" => %ld",
						el->enum_name, el->nat_value);
Lev Walkin's avatar
Lev Walkin committed
432
433
					dec_value = el->nat_value;
					state = ST_END_ENUM;
434
435
					lp = lstop - 1;
					continue;
Lev Walkin's avatar
Lev Walkin committed
436
437
438
				}
				ASN_DEBUG("Unknown identifier for INTEGER");
			}
439
			return XPBD_BROKEN_ENCODING;
Lev Walkin's avatar
Lev Walkin committed
440
441
442
443
444
445
446
447
448
449
450
451
		case 0x3a:	/* ':' */
			if(state == ST_HEXCOLON) {
				/* This colon is expected */
				state = ST_HEXDIGIT1;
				continue;
			} else if(state == ST_DIGITS) {
				/* The colon here means that we have
				 * decoded the first two hexadecimal
				 * places as a decimal value.
				 * Switch decoding mode. */
				ASN_DEBUG("INTEGER re-evaluate as hex form");
				state = ST_SKIPSPHEX;
Lev Walkin's avatar
Lev Walkin committed
452
				dec_value_start = 0;
Lev Walkin's avatar
Lev Walkin committed
453
454
455
				lp = lstart - 1;
				continue;
			} else {
Lev Walkin's avatar
Lev Walkin committed
456
				ASN_DEBUG("state %d at %ld", state, (long)(lp - lstart));
Lev Walkin's avatar
Lev Walkin committed
457
458
459
460
461
462
463
				break;
			}
		/* [A-Fa-f] */
		case 0x41:case 0x42:case 0x43:case 0x44:case 0x45:case 0x46:
		case 0x61:case 0x62:case 0x63:case 0x64:case 0x65:case 0x66:
			switch(state) {
			case ST_SKIPSPHEX:
Lev Walkin's avatar
Lev Walkin committed
464
			case ST_LEADSPACE: /* Fall through */
Lev Walkin's avatar
Lev Walkin committed
465
			case ST_HEXDIGIT1:
Lev Walkin's avatar
Lev Walkin committed
466
467
468
				hex_value = lv - ((lv < 0x61) ? 0x41 : 0x61);
				hex_value += 10;
				hex_value <<= 4;
Lev Walkin's avatar
Lev Walkin committed
469
470
471
				state = ST_HEXDIGIT2;
				continue;
			case ST_HEXDIGIT2:
Lev Walkin's avatar
Lev Walkin committed
472
473
474
				hex_value += lv - ((lv < 0x61) ? 0x41 : 0x61);
				hex_value += 10;
				st->buf[st->size++] = (uint8_t)hex_value;
Lev Walkin's avatar
Lev Walkin committed
475
476
477
478
479
				state = ST_HEXCOLON;
				continue;
			case ST_DIGITS:
				ASN_DEBUG("INTEGER re-evaluate as hex form");
				state = ST_SKIPSPHEX;
Lev Walkin's avatar
Lev Walkin committed
480
				dec_value_start = 0;
Lev Walkin's avatar
Lev Walkin committed
481
482
483
484
485
486
				lp = lstart - 1;
				continue;
			default:
				break;
			}
			break;
487
		}
488
489

		/* Found extra non-numeric stuff */
Lev Walkin's avatar
Lev Walkin committed
490
		ASN_DEBUG("INTEGER :: Found non-numeric 0x%2x at %ld",
Lev Walkin's avatar
Lev Walkin committed
491
			lv, (long)(lp - lstart));
Lev Walkin's avatar
Lev Walkin committed
492
		state = ST_UNEXPECTED;
Lev Walkin's avatar
Lev Walkin committed
493
		break;
494
495
	}

Lev Walkin's avatar
Lev Walkin committed
496
	switch(state) {
Lev Walkin's avatar
Lev Walkin committed
497
498
499
	case ST_END_ENUM:
		/* Got a complete and valid enumeration encoded as a tag. */
		break;
Lev Walkin's avatar
Lev Walkin committed
500
	case ST_DIGITS:
Lev Walkin's avatar
Lev Walkin committed
501
502
503
504
505
506
507
508
509
510
511
		dec_value_end = lstop;
	case ST_DIGITS_TRAILSPACE:
		/* The last symbol encountered was a digit. */
		switch(asn_strtol(dec_value_start, dec_value_end, &dec_value)) {
		case ASN_STRTOL_OK:
			break;
		case ASN_STRTOL_ERROR_RANGE:
			return XPBD_DECODER_LIMIT;
		case ASN_STRTOL_ERROR_INVAL:
			return XPBD_BROKEN_ENCODING;
		}
Lev Walkin's avatar
Lev Walkin committed
512
513
		break;
	case ST_HEXCOLON:
Lev Walkin's avatar
Lev Walkin committed
514
	case ST_HEXDIGITS_TRAILSPACE:
Lev Walkin's avatar
Lev Walkin committed
515
516
517
518
519
520
		st->buf[st->size] = 0;	/* Just in case termination */
		return XPBD_BODY_CONSUMED;
	case ST_HEXDIGIT1:
	case ST_HEXDIGIT2:
	case ST_SKIPSPHEX:
		return XPBD_BROKEN_ENCODING;
Lev Walkin's avatar
Lev Walkin committed
521
522
523
524
525
	case ST_LEADSPACE:
		/* Content not found */
		return XPBD_NOT_BODY_IGNORE;
	case ST_WAITDIGITS:
	case ST_UNEXPECTED:
Lev Walkin's avatar
Lev Walkin committed
526
527
		ASN_DEBUG("INTEGER: No useful digits (state %d)", state);
		return XPBD_BROKEN_ENCODING;	/* No digits */
528
	}
529

Lev Walkin's avatar
Lev Walkin committed
530
531
532
533
534
	/*
	 * Convert the result of parsing of enumeration or a straight
	 * decimal value into a BER representation.
	 */
	if(asn_long2INTEGER(st, dec_value))
535
		return XPBD_SYSTEM_FAILURE;
536

537
	return XPBD_BODY_CONSUMED;
538
539
540
541
542
}

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,
Lev Walkin's avatar
Lev Walkin committed
543
		const void *buf_ptr, size_t size) {
544
545

	return xer_decode_primitive(opt_codec_ctx, td,
Lev Walkin's avatar
Lev Walkin committed
546
		sptr, sizeof(INTEGER_t), opt_mname,
547
548
549
		buf_ptr, size, INTEGER__xer_body_decode);
}

Lev Walkin's avatar
Lev Walkin committed
550
asn_enc_rval_t
Lev Walkin's avatar
Lev Walkin committed
551
INTEGER_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
Lev Walkin's avatar
Lev Walkin committed
552
553
554
555
556
557
558
559
	int ilevel, enum xer_encoder_flags_e flags,
		asn_app_consume_bytes_f *cb, void *app_key) {
	const INTEGER_t *st = (const INTEGER_t *)sptr;
	asn_enc_rval_t er;

	(void)ilevel;
	(void)flags;
	
Lev Walkin's avatar
Lev Walkin committed
560
	if(!st || !st->buf)
Lev Walkin's avatar
Lev Walkin committed
561
562
		_ASN_ENCODE_FAILED;

Lev Walkin's avatar
Lev Walkin committed
563
	er.encoded = INTEGER__dump(td, st, cb, app_key, 1);
Lev Walkin's avatar
Lev Walkin committed
564
565
	if(er.encoded < 0) _ASN_ENCODE_FAILED;

Lev Walkin's avatar
Lev Walkin committed
566
567
568
	_ASN_ENCODED_OK(er);
}

Lev Walkin's avatar
Lev Walkin committed
569
570
#ifndef	ASN_DISABLE_PER_SUPPORT

Lev Walkin's avatar
Lev Walkin committed
571
572
573
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) {
574
	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
Lev Walkin's avatar
Lev Walkin committed
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
	asn_dec_rval_t rval = { RC_OK, 0 };
	INTEGER_t *st = (INTEGER_t *)*sptr;
	asn_per_constraint_t *ct;
	int repeat;

	(void)opt_codec_ctx;

	if(!st) {
		st = (INTEGER_t *)(*sptr = CALLOC(1, sizeof(*st)));
		if(!st) _ASN_DECODE_FAILED;
	}

	if(!constraints) constraints = td->per_constraints;
	ct = constraints ? &constraints->value : 0;

	if(ct && ct->flags & APC_EXTENSIBLE) {
		int inext = per_get_few_bits(pd, 1);
Lev Walkin's avatar
Lev Walkin committed
592
		if(inext < 0) _ASN_DECODE_STARVED;
Lev Walkin's avatar
Lev Walkin committed
593
594
595
596
		if(inext) ct = 0;
	}

	FREEMEM(st->buf);
597
598
	st->buf = 0;
	st->size = 0;
Lev Walkin's avatar
Lev Walkin committed
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
	if(ct) {
		if(ct->flags & APC_SEMI_CONSTRAINED) {
			st->buf = (uint8_t *)CALLOC(1, 2);
			if(!st->buf) _ASN_DECODE_FAILED;
			st->size = 1;
		} else if(ct->flags & APC_CONSTRAINED && ct->range_bits >= 0) {
			size_t size = (ct->range_bits + 7) >> 3;
			st->buf = (uint8_t *)MALLOC(1 + size + 1);
			if(!st->buf) _ASN_DECODE_FAILED;
			st->size = size;
		}
	}

	/* X.691, #12.2.2 */
	if(ct && ct->flags != APC_UNCONSTRAINED) {
		/* #10.5.6 */
		ASN_DEBUG("Integer with range %d bits", ct->range_bits);
		if(ct->range_bits >= 0) {
617
618
619
620
621
622
623
624
625
626
627
628
			long value;
			if(ct->range_bits == 32) {
				long lhalf;
				value = per_get_few_bits(pd, 16);
				if(value < 0) _ASN_DECODE_STARVED;
				lhalf = per_get_few_bits(pd, 16);
				if(lhalf < 0) _ASN_DECODE_STARVED;
				value = (value << 16) | lhalf;
			} else {
				value = per_get_few_bits(pd, ct->range_bits);
				if(value < 0) _ASN_DECODE_STARVED;
			}
Lev Walkin's avatar
Lev Walkin committed
629
630
631
			ASN_DEBUG("Got value %ld + low %ld",
				value, ct->lower_bound);
			value += ct->lower_bound;
632
633
634
			if((specs && specs->field_unsigned)
				? asn_ulong2INTEGER(st, value)
				: asn_long2INTEGER(st, value))
Lev Walkin's avatar
Lev Walkin committed
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
				_ASN_DECODE_FAILED;
			return rval;
		}
	} else {
		ASN_DEBUG("Decoding unconstrained integer %s", td->name);
	}

	/* X.691, #12.2.3, #12.2.4 */
	do {
		ssize_t len;
		void *p;
		int ret;

		/* Get the PER length */
		len = uper_get_length(pd, -1, &repeat);
Lev Walkin's avatar
Lev Walkin committed
650
		if(len < 0) _ASN_DECODE_STARVED;
Lev Walkin's avatar
Lev Walkin committed
651
652
653
654
655
656

		p = REALLOC(st->buf, st->size + len + 1);
		if(!p) _ASN_DECODE_FAILED;
		st->buf = (uint8_t *)p;

		ret = per_get_many_bits(pd, &st->buf[st->size], 0, 8 * len);
Lev Walkin's avatar
Lev Walkin committed
657
		if(ret < 0) _ASN_DECODE_STARVED;
Lev Walkin's avatar
Lev Walkin committed
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
		st->size += len;
	} while(repeat);
	st->buf[st->size] = 0;	/* JIC */

	/* #12.2.3 */
	if(ct && ct->lower_bound) {
		/*
		 * TODO: replace by in-place arithmetics.
		 */
		long value;
		if(asn_INTEGER2long(st, &value))
			_ASN_DECODE_FAILED;
		if(asn_long2INTEGER(st, value + ct->lower_bound))
			_ASN_DECODE_FAILED;
	}

	return rval;
Lev Walkin's avatar
Lev Walkin committed
675
676
}

Lev Walkin's avatar
Lev Walkin committed
677
678
679
asn_enc_rval_t
INTEGER_encode_uper(asn_TYPE_descriptor_t *td,
	asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
680
	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
Lev Walkin's avatar
Lev Walkin committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
	asn_enc_rval_t er;
	INTEGER_t *st = (INTEGER_t *)sptr;
	const uint8_t *buf;
	const uint8_t *end;
	asn_per_constraint_t *ct;
	long value = 0;

	if(!st || st->size == 0) _ASN_ENCODE_FAILED;

	if(!constraints) constraints = td->per_constraints;
	ct = constraints ? &constraints->value : 0;

	er.encoded = 0;

	if(ct) {
		int inext = 0;
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
		if(specs && specs->field_unsigned) {
			unsigned long uval;
			if(asn_INTEGER2ulong(st, &uval))
				_ASN_ENCODE_FAILED;
			/* Check proper range */
			if(ct->flags & APC_SEMI_CONSTRAINED) {
				if(uval < (unsigned long)ct->lower_bound)
					inext = 1;
			} else if(ct->range_bits >= 0) {
				if(uval < (unsigned long)ct->lower_bound
				|| uval > (unsigned long)ct->upper_bound)
					inext = 1;
			}
			ASN_DEBUG("Value %lu (%02x/%d) lb %lu ub %lu %s",
				uval, st->buf[0], st->size,
				ct->lower_bound, ct->upper_bound,
				inext ? "ext" : "fix");
			value = uval;
		} else {
			if(asn_INTEGER2long(st, &value))
				_ASN_ENCODE_FAILED;
			/* Check proper range */
			if(ct->flags & APC_SEMI_CONSTRAINED) {
				if(value < ct->lower_bound)
					inext = 1;
			} else if(ct->range_bits >= 0) {
				if(value < ct->lower_bound
				|| value > ct->upper_bound)
					inext = 1;
			}
			ASN_DEBUG("Value %ld (%02x/%d) lb %ld ub %ld %s",
				value, st->buf[0], st->size,
				ct->lower_bound, ct->upper_bound,
				inext ? "ext" : "fix");
Lev Walkin's avatar
Lev Walkin committed
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
		}
		if(ct->flags & APC_EXTENSIBLE) {
			if(per_put_few_bits(po, inext, 1))
				_ASN_ENCODE_FAILED;
			if(inext) ct = 0;
		} else if(inext) {
			_ASN_ENCODE_FAILED;
		}
	}


	/* X.691, #12.2.2 */
	if(ct && ct->range_bits >= 0) {
		/* #10.5.6 */
		ASN_DEBUG("Encoding integer with range %d bits",
			ct->range_bits);
747
748
749
750
751
752
753
754
		if(ct->range_bits == 32) {
			/* TODO: extend to >32 bits */
			long v = value - ct->lower_bound;
			if(per_put_few_bits(po, v >> 1, 31)
			|| per_put_few_bits(po, v, 1))
				_ASN_ENCODE_FAILED;
		} else {
			if(per_put_few_bits(po, value - ct->lower_bound,
Lev Walkin's avatar
Lev Walkin committed
755
				ct->range_bits))
756
757
				_ASN_ENCODE_FAILED;
		}
Lev Walkin's avatar
Lev Walkin committed
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
		_ASN_ENCODED_OK(er);
	}

	if(ct && ct->lower_bound) {
		ASN_DEBUG("Adjust lower bound to %ld", ct->lower_bound);
		/* TODO: adjust lower bound */
		_ASN_ENCODE_FAILED;
	}

	for(buf = st->buf, end = st->buf + st->size; buf < end;) {
		ssize_t mayEncode = uper_put_length(po, end - buf);
		if(mayEncode < 0)
			_ASN_ENCODE_FAILED;
		if(per_put_many_bits(po, buf, 8 * mayEncode))
			_ASN_ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
773
		buf += mayEncode;
Lev Walkin's avatar
Lev Walkin committed
774
775
776
777
778
	}

	_ASN_ENCODED_OK(er);
}

Lev Walkin's avatar
Lev Walkin committed
779
780
#endif	/* ASN_DISABLE_PER_SUPPORT */

Lev Walkin's avatar
Lev Walkin committed
781
int
Lev Walkin's avatar
Lev Walkin committed
782
asn_INTEGER2long(const INTEGER_t *iptr, long *lptr) {
Lev Walkin's avatar
Lev Walkin committed
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
	uint8_t *b, *end;
	size_t size;
	long l;

	/* Sanity checking */
	if(!iptr || !iptr->buf || !lptr) {
		errno = EINVAL;
		return -1;
	}

	/* Cache the begin/end of the buffer */
	b = iptr->buf;	/* Start of the INTEGER buffer */
	size = iptr->size;
	end = b + size;	/* Where to stop */

	if(size > sizeof(long)) {
		uint8_t *end1 = end - 1;
		/*
		 * Slightly more advanced processing,
		 * able to >sizeof(long) bytes,
		 * when the actual value is small
		 * (0x0000000000abcdef would yield a fine 0x00abcdef)
		 */
		/* Skip out the insignificant leading bytes */
		for(; b < end1; b++) {
			switch(*b) {
			case 0x00: if((b[1] & 0x80) == 0) continue; break;
			case 0xff: if((b[1] & 0x80) != 0) continue; break;
			}
			break;
		}

		size = end - b;
		if(size > sizeof(long)) {
			/* Still cannot fit the long */
			errno = ERANGE;
			return -1;
		}
	}

	/* Shortcut processing of a corner case */
	if(end == b) {
		*lptr = 0;
		return 0;
	}

	/* Perform the sign initialization */
	/* Actually l = -(*b >> 7); gains nothing, yet unreadable! */
	if((*b >> 7)) l = -1; else l = 0;

	/* Conversion engine */
	for(; b < end; b++)
		l = (l << 8) | *b;

	*lptr = l;
	return 0;
}
840

841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
int
asn_INTEGER2ulong(const INTEGER_t *iptr, unsigned long *lptr) {
	uint8_t *b, *end;
	unsigned long l;
	size_t size;

	if(!iptr || !iptr->buf || !lptr) {
		errno = EINVAL;
		return -1;
	}

	b = iptr->buf;
	size = iptr->size;
	end = b + size;

	/* If all extra leading bytes are zeroes, ignore them */
	for(; size > sizeof(unsigned long); b++, size--) {
		if(*b) {
			/* Value won't fit unsigned long */
			errno = ERANGE;
			return -1;
		}
	}

	/* Conversion engine */
	for(l = 0; b < end; b++)
		l = (l << 8) | *b;

	*lptr = l;
	return 0;
}

int
asn_ulong2INTEGER(INTEGER_t *st, unsigned long value) {
	uint8_t *buf;
	uint8_t *end;
	uint8_t *b;
	int shr;

	if(value <= LONG_MAX)
		return asn_long2INTEGER(st, value);

	buf = (uint8_t *)MALLOC(1 + sizeof(value));
	if(!buf) return -1;

	end = buf + (sizeof(value) + 1);
	buf[0] = 0;
888
889
	for(b = buf + 1, shr = (sizeof(long)-1)*8; b < end; shr -= 8, b++)
		*b = (uint8_t)(value >> shr);
890
891
892
893
894
895
896
897

	if(st->buf) FREEMEM(st->buf);
	st->buf = buf;
	st->size = 1 + sizeof(value);

	return 0;
}

898
899
900
901
902
903
int
asn_long2INTEGER(INTEGER_t *st, long value) {
	uint8_t *buf, *bp;
	uint8_t *p;
	uint8_t *pstart;
	uint8_t *pend1;
Lev Walkin's avatar
Lev Walkin committed
904
905
	int littleEndian = 1;	/* Run-time detection */
	int add;
906
907
908
909
910
911

	if(!st) {
		errno = EINVAL;
		return -1;
	}

Lev Walkin's avatar
Lev Walkin committed
912
	buf = (uint8_t *)MALLOC(sizeof(value));
913
914
	if(!buf) return -1;

Lev Walkin's avatar
Lev Walkin committed
915
916
917
918
919
920
921
922
923
924
	if(*(char *)&littleEndian) {
		pstart = (uint8_t *)&value + sizeof(value) - 1;
		pend1 = (uint8_t *)&value;
		add = -1;
	} else {
		pstart = (uint8_t *)&value;
		pend1 = pstart + sizeof(value) - 1;
		add = 1;
	}

925
926
927
928
929
930
	/*
	 * If the contents octet consists of more than one octet,
	 * then bits of the first octet and bit 8 of the second octet:
	 * a) shall not all be ones; and
	 * b) shall not all be zero.
	 */
Lev Walkin's avatar
alpha64    
Lev Walkin committed
931
	for(p = pstart; p != pend1; p += add) {
932
		switch(*p) {
Lev Walkin's avatar
alpha64    
Lev Walkin committed
933
		case 0x00: if((*(p+add) & 0x80) == 0)
934
935
				continue;
			break;
Lev Walkin's avatar
alpha64    
Lev Walkin committed
936
		case 0xff: if((*(p+add) & 0x80))
937
938
939
940
941
942
				continue;
			break;
		}
		break;
	}
	/* Copy the integer body */
Lev Walkin's avatar
alpha64    
Lev Walkin committed
943
944
	for(pstart = p, bp = buf, pend1 += add; p != pend1; p += add)
		*bp++ = *p;
945
946
947

	if(st->buf) FREEMEM(st->buf);
	st->buf = buf;
Lev Walkin's avatar
alpha64    
Lev Walkin committed
948
	st->size = bp - buf;
949
950
951

	return 0;
}
Lev Walkin's avatar
Lev Walkin committed
952

Lev Walkin's avatar
Lev Walkin committed
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
enum asn_strtol_result_e
asn_strtol(const char *str, const char *end, long *lp) {
	int sign = 1;
	long l;

	const long upper_boundary = LONG_MAX / 10;
	long last_digit_max = LONG_MAX % 10;

	if(str >= end) return ASN_STRTOL_ERROR_INVAL;

	switch(*str) {
	case '-':
		last_digit_max++;
		sign = -1;
	case '+':
		str++;
	}

	if(str >= end) return ASN_STRTOL_ERROR_INVAL;

	for(l = 0; str < end; str++) {
		switch(*str) {
		case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
		case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: {
			int d = *str - '0';
			if(l < upper_boundary) {
				l = l * 10 + d;
			} else if(l == upper_boundary) {
				if(d <= last_digit_max) {
					if(sign > 0) {
						l = l * 10 + d;
					} else {
						sign = 1;
						l = -l * 10 - d;
					}
				} else {
					return ASN_STRTOL_ERROR_RANGE;
				}
			} else {
				return ASN_STRTOL_ERROR_RANGE;
			}
		    }
		    continue;
		default:
			return ASN_STRTOL_ERROR_INVAL;
		}
	}

	*lp = sign * l;
	return ASN_STRTOL_OK;
Lev Walkin's avatar
Lev Walkin committed
1003
1004
}