OCTET_STRING.c 48.3 KB
Newer Older
Lev Walkin's avatar
Lev Walkin committed
1
/*-
Lev Walkin's avatar
Lev Walkin committed
2
 * Copyright (c) 2003, 2004, 2005, 2006 Lev Walkin <vlm@lionet.info>.
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 <OCTET_STRING.h>
8
#include <BIT_STRING.h>	/* for .bits_unused member */
Lev Walkin's avatar
Lev Walkin committed
9 10 11 12 13
#include <errno.h>

/*
 * OCTET STRING basic type description.
 */
14
static const ber_tlv_tag_t asn_DEF_OCTET_STRING_tags[] = {
Lev Walkin's avatar
Lev Walkin committed
15 16
	(ASN_TAG_CLASS_UNIVERSAL | (4 << 2))
};
17
asn_OCTET_STRING_specifics_t asn_SPC_OCTET_STRING_specs = {
18 19
	sizeof(OCTET_STRING_t),
	offsetof(OCTET_STRING_t, _asn_ctx),
20
	ASN_OSUBV_STR
21
};
22
static asn_per_constraints_t asn_DEF_OCTET_STRING_constraints = {
23 24 25
	{ APC_CONSTRAINED, 8, 8, 0, 255 },
	{ APC_SEMI_CONSTRAINED, -1, -1, 0, 0 },
	0, 0
Lev Walkin's avatar
Lev Walkin committed
26
};
27
asn_TYPE_operation_t asn_OP_OCTET_STRING = {
Lev Walkin's avatar
Lev Walkin committed
28
	OCTET_STRING_free,
29 30
	OCTET_STRING_print,	/* OCTET STRING generally means a non-ascii sequence */
	OCTET_STRING_compare,
Lev Walkin's avatar
Lev Walkin committed
31 32
	OCTET_STRING_decode_ber,
	OCTET_STRING_encode_der,
Lev Walkin's avatar
Lev Walkin committed
33
	OCTET_STRING_decode_xer_hex,
Lev Walkin's avatar
Lev Walkin committed
34
	OCTET_STRING_encode_xer,
Lev Walkin's avatar
Lev Walkin committed
35 36 37 38
#ifdef	ASN_DISABLE_OER_SUPPORT
	0,
	0,
#else
39 40
	OCTET_STRING_decode_oer,
	OCTET_STRING_encode_oer,
Lev Walkin's avatar
Lev Walkin committed
41
#endif  /* ASN_DISABLE_OER_SUPPORT */
Lev Walkin's avatar
Lev Walkin committed
42 43 44 45 46 47 48
#ifdef	ASN_DISABLE_PER_SUPPORT
	0,
	0,
#else
	OCTET_STRING_decode_uper,	/* Unaligned PER decoder */
	OCTET_STRING_encode_uper,	/* Unaligned PER encoder */
#endif	/* ASN_DISABLE_PER_SUPPORT */
49 50 51 52 53 54 55
	0	/* Use generic outmost tag fetcher */
};
asn_TYPE_descriptor_t asn_DEF_OCTET_STRING = {
	"OCTET STRING",		/* Canonical name */
	"OCTET_STRING",		/* XML tag name */
	&asn_OP_OCTET_STRING,
	asn_generic_no_constraint,
56 57 58 59 60 61
	asn_DEF_OCTET_STRING_tags,
	sizeof(asn_DEF_OCTET_STRING_tags)
	  / sizeof(asn_DEF_OCTET_STRING_tags[0]),
	asn_DEF_OCTET_STRING_tags,	/* Same as above */
	sizeof(asn_DEF_OCTET_STRING_tags)
	  / sizeof(asn_DEF_OCTET_STRING_tags[0]),
Lev Walkin's avatar
Lev Walkin committed
62
	0,	/* No OER visible constraints */
Lev Walkin's avatar
Lev Walkin committed
63
	0,	/* No PER visible constraints */
Lev Walkin's avatar
Lev Walkin committed
64
	0, 0,	/* No members */
65
	&asn_SPC_OCTET_STRING_specs
Lev Walkin's avatar
Lev Walkin committed
66 67
};

Lev Walkin's avatar
Lev Walkin committed
68 69 70
#undef	_CH_PHASE
#undef	NEXT_PHASE
#undef	PREV_PHASE
71 72 73 74
#define	_CH_PHASE(ctx, inc) do {					\
		if(ctx->phase == 0)					\
			ctx->context = 0;				\
		ctx->phase += inc;					\
Lev Walkin's avatar
Lev Walkin committed
75 76 77 78
	} while(0)
#define	NEXT_PHASE(ctx)	_CH_PHASE(ctx, +1)
#define	PREV_PHASE(ctx)	_CH_PHASE(ctx, -1)

Lev Walkin's avatar
Lev Walkin committed
79
#undef	ADVANCE
80 81 82 83 84
#define	ADVANCE(num_bytes)	do {					\
		size_t num = (num_bytes);				\
		buf_ptr = ((const char *)buf_ptr) + num;		\
		size -= num;						\
		consumed_myself += num;					\
Lev Walkin's avatar
Lev Walkin committed
85 86
	} while(0)

Lev Walkin's avatar
Lev Walkin committed
87
#undef	RETURN
88
#define	RETURN(_code)	do {						\
Lev Walkin's avatar
Lev Walkin committed
89 90 91 92
		asn_dec_rval_t tmprval;					\
		tmprval.code = _code;					\
		tmprval.consumed = consumed_myself;			\
		return tmprval;						\
Lev Walkin's avatar
Lev Walkin committed
93 94
	} while(0)

Lev Walkin's avatar
Lev Walkin committed
95
#undef	APPEND
96
#define	APPEND(bufptr, bufsize)	do {					\
97 98 99 100 101 102
		size_t _bs = (bufsize);		/* Append size */	\
		size_t _ns = ctx->context;	/* Allocated now */	\
		size_t _es = st->size + _bs;	/* Expected size */	\
		/* int is really a typeof(st->size): */			\
		if((int)_es < 0) RETURN(RC_FAIL);			\
		if(_ns <= _es) {					\
103
			void *ptr;					\
104
			/* Be nice and round to the memory allocator */	\
105 106 107 108
			do { _ns = _ns ? _ns << 1 : 16; }		\
			    while(_ns <= _es);				\
			/* int is really a typeof(st->size): */		\
			if((int)_ns < 0) RETURN(RC_FAIL);		\
109 110
			ptr = REALLOC(st->buf, _ns);			\
			if(ptr) {					\
Lev Walkin's avatar
Lev Walkin committed
111
				st->buf = (uint8_t *)ptr;		\
112
				ctx->context = _ns;			\
113 114 115
			} else {					\
				RETURN(RC_FAIL);			\
			}						\
Lev Walkin's avatar
Lev Walkin committed
116
			ASN_DEBUG("Reallocating into %ld", (long)_ns);	\
117
		}							\
Lev Walkin's avatar
Lev Walkin committed
118
		memcpy(st->buf + st->size, bufptr, _bs);		\
119
		/* Convenient nul-termination */			\
120 121
		st->buf[_es] = '\0';					\
		st->size = _es;						\
Lev Walkin's avatar
Lev Walkin committed
122 123 124 125 126 127 128 129 130
	} while(0)

/*
 * The main reason why ASN.1 is still alive is that too much time and effort
 * is necessary for learning it more or less adequately, thus creating a gut
 * necessity to demonstrate that aquired skill everywhere afterwards.
 * No, I am not going to explain what the following stuff is.
 */
struct _stack_el {
Lev Walkin's avatar
Lev Walkin committed
131 132
    ber_tlv_len_t left;     /* What's left to read (or -1) */
    ber_tlv_len_t got;      /* What was actually processed */
Lev Walkin's avatar
Lev Walkin committed
133
    unsigned cont_level;    /* Depth of subcontainment */
Lev Walkin's avatar
Lev Walkin committed
134 135 136 137 138
    int want_nulls;         /* Want null "end of content" octets? */
    int bits_chopped;       /* Flag in BIT STRING mode */
    ber_tlv_tag_t tag;      /* For debugging purposes */
    struct _stack_el *prev;
    struct _stack_el *next;
Lev Walkin's avatar
Lev Walkin committed
139 140 141 142 143 144 145
};
struct _stack {
	struct _stack_el *tail;
	struct _stack_el *cur_ptr;
};

static struct _stack_el *
146
OS__add_stack_el(struct _stack *st) {
Lev Walkin's avatar
Lev Walkin committed
147 148
	struct _stack_el *nel;

149 150 151
	/*
	 * Reuse the old stack frame or allocate a new one.
	 */
Lev Walkin's avatar
Lev Walkin committed
152 153 154
	if(st->cur_ptr && st->cur_ptr->next) {
		nel = st->cur_ptr->next;
		nel->bits_chopped = 0;
155 156
		nel->got = 0;
		/* Retain the nel->cont_level, it's correct. */
Lev Walkin's avatar
Lev Walkin committed
157
	} else {
Lev Walkin's avatar
Lev Walkin committed
158
		nel = (struct _stack_el *)CALLOC(1, sizeof(struct _stack_el));
Lev Walkin's avatar
Lev Walkin committed
159 160 161 162
		if(nel == NULL)
			return NULL;
	
		if(st->tail) {
163 164
			/* Increase a subcontainment depth */
			nel->cont_level = st->tail->cont_level + 1;
Lev Walkin's avatar
Lev Walkin committed
165 166 167 168 169 170 171 172 173 174 175 176
			st->tail->next = nel;
		}
		nel->prev = st->tail;
		st->tail = nel;
	}

	st->cur_ptr = nel;

	return nel;
}

static struct _stack *
johvik's avatar
johvik committed
177
_new_stack(void) {
178
	return (struct _stack *)CALLOC(1, sizeof(struct _stack));
Lev Walkin's avatar
Lev Walkin committed
179 180 181 182 183
}

/*
 * Decode OCTET STRING type.
 */
Lev Walkin's avatar
Lev Walkin committed
184
asn_dec_rval_t
185 186
OCTET_STRING_decode_ber(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td,
Lev Walkin's avatar
Lev Walkin committed
187
	void **sptr, const void *buf_ptr, size_t size, int tag_mode) {
188
	asn_OCTET_STRING_specifics_t *specs = td->specifics
Lev Walkin's avatar
Lev Walkin committed
189
				? (asn_OCTET_STRING_specifics_t *)td->specifics
190
				: &asn_SPC_OCTET_STRING_specs;
Lev Walkin's avatar
Lev Walkin committed
191
	BIT_STRING_t *st = (BIT_STRING_t *)*sptr;
Lev Walkin's avatar
Lev Walkin committed
192
	asn_dec_rval_t rval;
193
	asn_struct_ctx_t *ctx;
Lev Walkin's avatar
Lev Walkin committed
194
	ssize_t consumed_myself = 0;
195
	struct _stack *stck;		/* Expectations stack structure */
196
	struct _stack_el *sel = 0;	/* Stack element */
Lev Walkin's avatar
Lev Walkin committed
197
	int tlv_constr;
198
	enum asn_OS_Subvariant type_variant = specs->subvariant;
Lev Walkin's avatar
Lev Walkin committed
199

Lev Walkin's avatar
Lev Walkin committed
200 201
	ASN_DEBUG("Decoding %s as %s (frame %ld)",
		td->name,
202
		(type_variant == ASN_OSUBV_STR) ?
203
			"OCTET STRING" : "OS-SpecialCase",
Lev Walkin's avatar
Lev Walkin committed
204
		(long)size);
Lev Walkin's avatar
Lev Walkin committed
205 206 207 208 209

	/*
	 * Create the string if does not exist.
	 */
	if(st == NULL) {
Lev Walkin's avatar
Lev Walkin committed
210 211
		st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
		if(st == NULL) RETURN(RC_FAIL);
Lev Walkin's avatar
Lev Walkin committed
212 213 214
	}

	/* Restore parsing context */
Lev Walkin's avatar
Lev Walkin committed
215
	ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
Lev Walkin's avatar
Lev Walkin committed
216 217 218 219 220 221

	switch(ctx->phase) {
	case 0:
		/*
		 * Check tags.
		 */
222
		rval = ber_check_tags(opt_codec_ctx, td, ctx,
223
			buf_ptr, size, tag_mode, -1,
Lev Walkin's avatar
Lev Walkin committed
224
			&ctx->left, &tlv_constr);
225 226
		if(rval.code != RC_OK)
			return rval;
Lev Walkin's avatar
Lev Walkin committed
227 228 229 230 231 232

		if(tlv_constr) {
			/*
			 * Complex operation, requires stack of expectations.
			 */
			ctx->ptr = _new_stack();
Lev Walkin's avatar
Lev Walkin committed
233
			if(!ctx->ptr) {
Lev Walkin's avatar
Lev Walkin committed
234 235 236 237 238 239 240
				RETURN(RC_FAIL);
			}
		} else {
			/*
			 * Jump into stackless primitive decoding.
			 */
			_CH_PHASE(ctx, 3);
241
			if(type_variant == ASN_OSUBV_ANY && tag_mode != 1)
242
				APPEND(buf_ptr, rval.consumed);
Lev Walkin's avatar
Lev Walkin committed
243 244 245 246 247 248 249 250 251 252 253
			ADVANCE(rval.consumed);
			goto phase3;
		}

		NEXT_PHASE(ctx);
		/* Fall through */
	case 1:
	phase1:
		/*
		 * Fill the stack with expectations.
		 */
Lev Walkin's avatar
Lev Walkin committed
254
		stck = (struct _stack *)ctx->ptr;
Lev Walkin's avatar
Lev Walkin committed
255 256 257 258
		sel = stck->cur_ptr;
	  do {
		ber_tlv_tag_t tlv_tag;
		ber_tlv_len_t tlv_len;
259
		ber_tlv_tag_t expected_tag;
260
		ssize_t tl, ll, tlvl;
261
				/* This one works even if (sel->left == -1) */
262 263
		size_t Left = ((!sel||(size_t)sel->left >= size)
					?size:(size_t)sel->left);
264

Lev Walkin's avatar
Lev Walkin committed
265

Lev Walkin's avatar
Lev Walkin committed
266
		ASN_DEBUG("%p, s->l=%ld, s->wn=%ld, s->g=%ld\n", sel,
Lev Walkin's avatar
Lev Walkin committed
267 268 269
			(long)(sel?sel->left:0),
			(long)(sel?sel->want_nulls:0),
			(long)(sel?sel->got:0)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
		);
		if(sel && sel->left <= 0 && sel->want_nulls == 0) {
			if(sel->prev) {
				struct _stack_el *prev = sel->prev;
				if(prev->left != -1) {
					if(prev->left < sel->got)
						RETURN(RC_FAIL);
					prev->left -= sel->got;
				}
				prev->got += sel->got;
				sel = stck->cur_ptr = prev;
				if(!sel) break;
				tlv_constr = 1;
				continue;
			} else {
				sel = stck->cur_ptr = 0;
				break;	/* Nothing to wait */
			}
		}

290
		tl = ber_fetch_tag(buf_ptr, Left, &tlv_tag);
Lev Walkin's avatar
Lev Walkin committed
291 292
		ASN_DEBUG("fetch tag(size=%ld,L=%ld), %sstack, left=%ld, wn=%ld, tl=%ld",
			(long)size, (long)Left, sel?"":"!",
Lev Walkin's avatar
Lev Walkin committed
293 294
			(long)(sel?sel->left:0),
			(long)(sel?sel->want_nulls:0),
Lev Walkin's avatar
Lev Walkin committed
295
			(long)tl);
Lev Walkin's avatar
Lev Walkin committed
296 297 298 299 300 301 302 303
		switch(tl) {
		case -1: RETURN(RC_FAIL);
		case 0: RETURN(RC_WMORE);
		}

		tlv_constr = BER_TLV_CONSTRUCTED(buf_ptr);

		ll = ber_fetch_length(tlv_constr,
Lev Walkin's avatar
Lev Walkin committed
304
				(const char *)buf_ptr + tl,Left - tl,&tlv_len);
Lev Walkin's avatar
Lev Walkin committed
305
		ASN_DEBUG("Got tag=%s, tc=%d, left=%ld, tl=%ld, len=%ld, ll=%ld",
Lev Walkin's avatar
Lev Walkin committed
306
			ber_tlv_tag_string(tlv_tag), tlv_constr,
Lev Walkin's avatar
Lev Walkin committed
307
				(long)Left, (long)tl, (long)tlv_len, (long)ll);
Lev Walkin's avatar
Lev Walkin committed
308 309 310 311 312
		switch(ll) {
		case -1: RETURN(RC_FAIL);
		case 0: RETURN(RC_WMORE);
		}

Lev Walkin's avatar
Lev Walkin committed
313
		if(sel && sel->want_nulls
Lev Walkin's avatar
Lev Walkin committed
314 315
			&& ((const uint8_t *)buf_ptr)[0] == 0
			&& ((const uint8_t *)buf_ptr)[1] == 0)
Lev Walkin's avatar
Lev Walkin committed
316
		{
Lev Walkin's avatar
Lev Walkin committed
317 318 319

			ASN_DEBUG("Eat EOC; wn=%d--", sel->want_nulls);

320
			if(type_variant == ASN_OSUBV_ANY
321 322
			&& (tag_mode != 1 || sel->cont_level))
				APPEND("\0\0", 2);
323 324 325 326 327 328 329

			ADVANCE(2);
			sel->got += 2;
			if(sel->left != -1) {
				sel->left -= 2;	/* assert(sel->left >= 2) */
			}

Lev Walkin's avatar
Lev Walkin committed
330 331 332
			sel->want_nulls--;
			if(sel->want_nulls == 0) {
				/* Move to the next expectation */
333
				sel->left = 0;
Lev Walkin's avatar
Lev Walkin committed
334 335
				tlv_constr = 1;
			}
Lev Walkin's avatar
Lev Walkin committed
336 337

			continue;
338 339 340 341 342 343
		}

		/*
		 * Set up expected tags,
		 * depending on ASN.1 type being decoded.
		 */
344
		switch(type_variant) {
345
		case ASN_OSUBV_BIT:
346 347
			/* X.690: 8.6.4.1, NOTE 2 */
			/* Fall through */
348
		case ASN_OSUBV_STR:
349 350
		default:
			if(sel) {
Lev Walkin's avatar
Lev Walkin committed
351
				unsigned level = sel->cont_level;
352 353 354 355 356 357 358 359 360 361 362
				if(level < td->all_tags_count) {
					expected_tag = td->all_tags[level];
					break;
				} else if(td->all_tags_count) {
					expected_tag = td->all_tags
						[td->all_tags_count - 1];
					break;
				}
				/* else, Fall through */
			}
			/* Fall through */
363
		case ASN_OSUBV_ANY:
364 365 366 367 368 369
			expected_tag = tlv_tag;
			break;
		}


		if(tlv_tag != expected_tag) {
Lev Walkin's avatar
Lev Walkin committed
370 371 372 373 374 375 376 377 378 379
			char buf[2][32];
			ber_tlv_tag_snprint(tlv_tag,
				buf[0], sizeof(buf[0]));
			ber_tlv_tag_snprint(td->tags[td->tags_count-1],
				buf[1], sizeof(buf[1]));
			ASN_DEBUG("Tag does not match expectation: %s != %s",
				buf[0], buf[1]);
			RETURN(RC_FAIL);
		}

380 381 382 383 384 385 386 387
		tlvl = tl + ll;	/* Combined length of T and L encoding */
		if((tlv_len + tlvl) < 0) {
			/* tlv_len value is too big */
			ASN_DEBUG("TLV encoding + length (%ld) is too big",
				(long)tlv_len);
			RETURN(RC_FAIL);
		}

Lev Walkin's avatar
Lev Walkin committed
388 389 390
		/*
		 * Append a new expectation.
		 */
391
		sel = OS__add_stack_el(stck);
392 393 394 395 396 397 398 399 400 401 402 403 404
		if(!sel) RETURN(RC_FAIL);

		sel->tag = tlv_tag;

		sel->want_nulls = (tlv_len==-1);
		if(sel->prev && sel->prev->left != -1) {
			/* Check that the parent frame is big enough */
			if(sel->prev->left < tlvl + (tlv_len==-1?0:tlv_len))
				RETURN(RC_FAIL);
			if(tlv_len == -1)
				sel->left = sel->prev->left - tlvl;
			else
				sel->left = tlv_len;
Lev Walkin's avatar
Lev Walkin committed
405
		} else {
406
			sel->left = tlv_len;
Lev Walkin's avatar
Lev Walkin committed
407
		}
408
		if(type_variant == ASN_OSUBV_ANY
409 410
		&& (tag_mode != 1 || sel->cont_level))
			APPEND(buf_ptr, tlvl);
411 412 413
		sel->got += tlvl;
		ADVANCE(tlvl);

Lev Walkin's avatar
Lev Walkin committed
414
		ASN_DEBUG("+EXPECT2 got=%ld left=%ld, wn=%d, clvl=%u",
Lev Walkin's avatar
Lev Walkin committed
415 416
			(long)sel->got, (long)sel->left,
			sel->want_nulls, sel->cont_level);
Lev Walkin's avatar
Lev Walkin committed
417 418 419 420

	  } while(tlv_constr);
		if(sel == NULL) {
			/* Finished operation, "phase out" */
421
			ASN_DEBUG("Phase out");
Lev Walkin's avatar
Lev Walkin committed
422 423 424 425 426 427 428
			_CH_PHASE(ctx, +3);
			break;
		}

		NEXT_PHASE(ctx);
		/* Fall through */
	case 2:
Lev Walkin's avatar
Lev Walkin committed
429
		stck = (struct _stack *)ctx->ptr;
Lev Walkin's avatar
Lev Walkin committed
430
		sel = stck->cur_ptr;
431 432 433
		ASN_DEBUG("Phase 2: Need %ld bytes, size=%ld, alrg=%ld, wn=%d",
			(long)sel->left, (long)size, (long)sel->got,
				sel->want_nulls);
Lev Walkin's avatar
Lev Walkin committed
434 435 436 437 438
	    {
		ber_tlv_len_t len;

		assert(sel->left >= 0);

Lev Walkin's avatar
Lev Walkin committed
439 440
		len = ((ber_tlv_len_t)size < sel->left)
				? (ber_tlv_len_t)size : sel->left;
Lev Walkin's avatar
Lev Walkin committed
441
		if(len > 0) {
442
			if(type_variant == ASN_OSUBV_BIT
443
			&& sel->bits_chopped == 0) {
444
				/* Put the unused-bits-octet away */
Lev Walkin's avatar
Lev Walkin committed
445 446
				st->bits_unused = *(const uint8_t *)buf_ptr;
				APPEND(((const char *)buf_ptr+1), (len - 1));
Lev Walkin's avatar
Lev Walkin committed
447 448 449 450 451 452
				sel->bits_chopped = 1;
			} else {
				APPEND(buf_ptr, len);
			}
			ADVANCE(len);
			sel->left -= len;
453
			sel->got += len;
Lev Walkin's avatar
Lev Walkin committed
454 455
		}

456 457 458
		if(sel->left) {
			ASN_DEBUG("OS left %ld, size = %ld, wn=%d\n",
				(long)sel->left, (long)size, sel->want_nulls);
Lev Walkin's avatar
Lev Walkin committed
459 460
			RETURN(RC_WMORE);
		}
461 462 463

		PREV_PHASE(ctx);
		goto phase1;
Lev Walkin's avatar
Lev Walkin committed
464 465 466 467 468 469 470
	    }
		break;
	case 3:
	phase3:
		/*
		 * Primitive form, no stack required.
		 */
471 472
		assert(ctx->left >= 0);

473
		if(size < (size_t)ctx->left) {
474
			if(!size) RETURN(RC_WMORE);
475
			if(type_variant == ASN_OSUBV_BIT && !ctx->context) {
Lev Walkin's avatar
Lev Walkin committed
476
				st->bits_unused = *(const uint8_t *)buf_ptr;
477 478 479
				ctx->left--;
				ADVANCE(1);
			}
Lev Walkin's avatar
Lev Walkin committed
480
			APPEND(buf_ptr, size);
481
			assert(ctx->context > 0);
Lev Walkin's avatar
Lev Walkin committed
482 483 484 485
			ctx->left -= size;
			ADVANCE(size);
			RETURN(RC_WMORE);
		} else {
486
			if(type_variant == ASN_OSUBV_BIT
487
			&& !ctx->context && ctx->left) {
Lev Walkin's avatar
Lev Walkin committed
488
				st->bits_unused = *(const uint8_t *)buf_ptr;
489 490 491
				ctx->left--;
				ADVANCE(1);
			}
Lev Walkin's avatar
Lev Walkin committed
492 493 494 495 496 497 498 499 500
			APPEND(buf_ptr, ctx->left);
			ADVANCE(ctx->left);
			ctx->left = 0;

			NEXT_PHASE(ctx);
		}
		break;
	}

501 502 503 504 505 506 507 508 509
	if(sel) {
		ASN_DEBUG("3sel p=%p, wn=%d, l=%ld, g=%ld, size=%ld",
			sel->prev, sel->want_nulls,
			(long)sel->left, (long)sel->got, (long)size);
		if(sel->prev || sel->want_nulls > 1 || sel->left > 0) {
			RETURN(RC_WMORE);
		}
	}

Lev Walkin's avatar
Lev Walkin committed
510 511 512
	/*
	 * BIT STRING-specific processing.
	 */
513
	if(type_variant == ASN_OSUBV_BIT && st->size) {
Lev Walkin's avatar
Lev Walkin committed
514
		/* Finalize BIT STRING: zero out unused bits. */
515
		st->buf[st->size-1] &= 0xff << st->bits_unused;
Lev Walkin's avatar
Lev Walkin committed
516 517
	}

Lev Walkin's avatar
Lev Walkin committed
518 519
	ASN_DEBUG("Took %ld bytes to encode %s: [%s]:%ld",
		(long)consumed_myself, td->name,
520
		(type_variant == ASN_OSUBV_STR) ? (char *)st->buf : "<data>",
Lev Walkin's avatar
Lev Walkin committed
521
		(long)st->size);
Lev Walkin's avatar
Lev Walkin committed
522 523


524
	RETURN(RC_OK);
Lev Walkin's avatar
Lev Walkin committed
525 526 527 528 529
}

/*
 * Encode OCTET STRING type using DER.
 */
Lev Walkin's avatar
Lev Walkin committed
530
asn_enc_rval_t
531
OCTET_STRING_encode_der(asn_TYPE_descriptor_t *td, void *sptr,
Lev Walkin's avatar
Lev Walkin committed
532 533
	int tag_mode, ber_tlv_tag_t tag,
	asn_app_consume_bytes_f *cb, void *app_key) {
534 535
	asn_enc_rval_t er;
	asn_OCTET_STRING_specifics_t *specs = td->specifics
Lev Walkin's avatar
Lev Walkin committed
536
				? (asn_OCTET_STRING_specifics_t *)td->specifics
537
				: &asn_SPC_OCTET_STRING_specs;
538
	BIT_STRING_t *st = (BIT_STRING_t *)sptr;
539
	enum asn_OS_Subvariant type_variant = specs->subvariant;
540
	int fix_last_byte = 0;
Lev Walkin's avatar
Lev Walkin committed
541 542

	ASN_DEBUG("%s %s as OCTET STRING",
Lev Walkin's avatar
Lev Walkin committed
543
		cb?"Estimating":"Encoding", td->name);
Lev Walkin's avatar
Lev Walkin committed
544 545

	/*
546
	 * Write tags.
Lev Walkin's avatar
Lev Walkin committed
547
	 */
548
	if(type_variant != ASN_OSUBV_ANY || tag_mode == 1) {
549
		er.encoded = der_write_tags(td,
550 551 552
				(type_variant == ASN_OSUBV_BIT) + st->size,
			tag_mode, type_variant == ASN_OSUBV_ANY, tag,
			cb, app_key);
553 554 555 556
		if(er.encoded == -1) {
			er.failed_type = td;
			er.structure_ptr = sptr;
			return er;
Lev Walkin's avatar
Lev Walkin committed
557
		}
558 559
	} else {
		/* Disallow: [<tag>] IMPLICIT ANY */
560
		assert(type_variant != ASN_OSUBV_ANY || tag_mode != -1);
561 562 563 564
		er.encoded = 0;
	}

	if(!cb) {
565
		er.encoded += (type_variant == ASN_OSUBV_BIT) + st->size;
566
		ASN__ENCODED_OK(er);
Lev Walkin's avatar
Lev Walkin committed
567 568
	}

569
	/*
570
	 * Prepare to deal with the last octet of BIT STRING.
571
	 */
572
	if(type_variant == ASN_OSUBV_BIT) {
573 574
		uint8_t b = st->bits_unused & 0x07;
		if(b && st->size) fix_last_byte = 1;
575
		ASN__CALLBACK(&b, 1);
576
		er.encoded++;
Lev Walkin's avatar
Lev Walkin committed
577 578
	}

579
	/* Invoke callback for the main part of the buffer */
580
	ASN__CALLBACK(st->buf, st->size - fix_last_byte);
Lev Walkin's avatar
Lev Walkin committed
581

582 583 584
	/* The last octet should be stripped off the unused bits */
	if(fix_last_byte) {
		uint8_t b = st->buf[st->size-1] & (0xff << st->bits_unused);
585
		ASN__CALLBACK(&b, 1);
Lev Walkin's avatar
Lev Walkin committed
586 587
	}

588
	er.encoded += st->size;
589
	ASN__ENCODED_OK(er);
590
cb_failed:
591
	ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
592 593
}

Lev Walkin's avatar
Lev Walkin committed
594
asn_enc_rval_t
595
OCTET_STRING_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
Lev Walkin's avatar
Lev Walkin committed
596 597
	int ilevel, enum xer_encoder_flags_e flags,
		asn_app_consume_bytes_f *cb, void *app_key) {
598
	const char * const h2c = "0123456789ABCDEF";
Lev Walkin's avatar
Lev Walkin committed
599 600 601 602 603 604 605 606
	const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
	asn_enc_rval_t er;
	char scratch[16 * 3 + 4];
	char *p = scratch;
	uint8_t *buf;
	uint8_t *end;
	size_t i;

Lev Walkin's avatar
Lev Walkin committed
607
	if(!st || (!st->buf && st->size))
608
		ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
609 610 611 612 613 614 615 616 617 618 619 620

	er.encoded = 0;

	/*
	 * Dump the contents of the buffer in hexadecimal.
	 */
	buf = st->buf;
	end = buf + st->size;
	if(flags & XER_F_CANONICAL) {
		char *scend = scratch + (sizeof(scratch) - 2);
		for(; buf < end; buf++) {
			if(p >= scend) {
621
				ASN__CALLBACK(scratch, p - scratch);
Lev Walkin's avatar
Lev Walkin committed
622 623 624 625 626 627
				er.encoded += p - scratch;
				p = scratch;
			}
			*p++ = h2c[(*buf >> 4) & 0x0F];
			*p++ = h2c[*buf & 0x0F];
		}
Lev Walkin's avatar
Lev Walkin committed
628

629
		ASN__CALLBACK(scratch, p-scratch);	/* Dump the rest */
Lev Walkin's avatar
Lev Walkin committed
630
		er.encoded += p - scratch;
Lev Walkin's avatar
Lev Walkin committed
631 632 633
	} else {
		for(i = 0; buf < end; buf++, i++) {
			if(!(i % 16) && (i || st->size > 16)) {
634
				ASN__CALLBACK(scratch, p-scratch);
Lev Walkin's avatar
Lev Walkin committed
635 636
				er.encoded += (p-scratch);
				p = scratch;
637
				ASN__TEXT_INDENT(1, ilevel);
Lev Walkin's avatar
Lev Walkin committed
638 639 640 641 642
			}
			*p++ = h2c[(*buf >> 4) & 0x0F];
			*p++ = h2c[*buf & 0x0F];
			*p++ = 0x20;
		}
Lev Walkin's avatar
Lev Walkin committed
643 644
		if(p - scratch) {
			p--;	/* Remove the tail space */
645
			ASN__CALLBACK(scratch, p-scratch); /* Dump the rest */
Lev Walkin's avatar
Lev Walkin committed
646 647
			er.encoded += p - scratch;
			if(st->size > 16)
648
				ASN__TEXT_INDENT(1, ilevel-1);
Lev Walkin's avatar
Lev Walkin committed
649
		}
Lev Walkin's avatar
Lev Walkin committed
650 651
	}

652
	ASN__ENCODED_OK(er);
Lev Walkin's avatar
Lev Walkin committed
653
cb_failed:
654
	ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
655 656
}

657 658
static const struct OCTET_STRING__xer_escape_table_s {
	const char *string;
Lev Walkin's avatar
Lev Walkin committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
	int size;
} OCTET_STRING__xer_escape_table[] = {
#define	OSXET(s)	{ s, sizeof(s) - 1 }
	OSXET("\074\156\165\154\057\076"),	/* <nul/> */
	OSXET("\074\163\157\150\057\076"),	/* <soh/> */
	OSXET("\074\163\164\170\057\076"),	/* <stx/> */
	OSXET("\074\145\164\170\057\076"),	/* <etx/> */
	OSXET("\074\145\157\164\057\076"),	/* <eot/> */
	OSXET("\074\145\156\161\057\076"),	/* <enq/> */
	OSXET("\074\141\143\153\057\076"),	/* <ack/> */
	OSXET("\074\142\145\154\057\076"),	/* <bel/> */
	OSXET("\074\142\163\057\076"),		/* <bs/> */
	OSXET("\011"),				/* \t */
	OSXET("\012"),				/* \n */
	OSXET("\074\166\164\057\076"),		/* <vt/> */
	OSXET("\074\146\146\057\076"),		/* <ff/> */
	OSXET("\015"),				/* \r */
	OSXET("\074\163\157\057\076"),		/* <so/> */
	OSXET("\074\163\151\057\076"),		/* <si/> */
	OSXET("\074\144\154\145\057\076"),	/* <dle/> */
	OSXET("\074\144\143\061\057\076"),	/* <de1/> */
	OSXET("\074\144\143\062\057\076"),	/* <de2/> */
	OSXET("\074\144\143\063\057\076"),	/* <de3/> */
	OSXET("\074\144\143\064\057\076"),	/* <de4/> */
	OSXET("\074\156\141\153\057\076"),	/* <nak/> */
	OSXET("\074\163\171\156\057\076"),	/* <syn/> */
	OSXET("\074\145\164\142\057\076"),	/* <etb/> */
	OSXET("\074\143\141\156\057\076"),	/* <can/> */
	OSXET("\074\145\155\057\076"),		/* <em/> */
	OSXET("\074\163\165\142\057\076"),	/* <sub/> */
	OSXET("\074\145\163\143\057\076"),	/* <esc/> */
	OSXET("\074\151\163\064\057\076"),	/* <is4/> */
	OSXET("\074\151\163\063\057\076"),	/* <is3/> */
	OSXET("\074\151\163\062\057\076"),	/* <is2/> */
	OSXET("\074\151\163\061\057\076"),	/* <is1/> */
	{ 0, 0 },	/* " " */
	{ 0, 0 },	/* ! */
	{ 0, 0 },	/* \" */
	{ 0, 0 },	/* # */
	{ 0, 0 },	/* $ */
	{ 0, 0 },	/* % */
	OSXET("\046\141\155\160\073"),	/* &amp; */
	{ 0, 0 },	/* ' */
	{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, /* ()*+,-./ */
	{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, /* 01234567 */
	{0,0},{0,0},{0,0},{0,0},			 /* 89:; */
	OSXET("\046\154\164\073"),	/* &lt; */
	{ 0, 0 },	/* = */
	OSXET("\046\147\164\073"),	/* &gt; */
};

Lev Walkin's avatar
Lev Walkin committed
710
static int
711
OS__check_escaped_control_char(const void *buf, int size) {
Lev Walkin's avatar
Lev Walkin committed
712 713 714 715 716 717 718 719
	size_t i;
	/*
	 * Inefficient algorithm which translates the escape sequences
	 * defined above into characters. Returns -1 if not found.
	 * TODO: replace by a faster algorithm (bsearch(), hash or
	 * nested table lookups).
	 */
	for(i = 0; i < 32 /* Don't spend time on the bottom half */; i++) {
720
		const struct OCTET_STRING__xer_escape_table_s *el;
Lev Walkin's avatar
Lev Walkin committed
721 722 723 724 725 726 727 728
		el = &OCTET_STRING__xer_escape_table[i];
		if(el->size == size && memcmp(buf, el->string, size) == 0)
			return i;
	}
	return -1;
}

static int
729
OCTET_STRING__handle_control_chars(void *struct_ptr, const void *chunk_buf, size_t chunk_size) {
Lev Walkin's avatar
Lev Walkin committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
	/*
	 * This might be one of the escape sequences
	 * for control characters. Check it out.
	 * #11.15.5
	 */
	int control_char = OS__check_escaped_control_char(chunk_buf,chunk_size);
	if(control_char >= 0) {
		OCTET_STRING_t *st = (OCTET_STRING_t *)struct_ptr;
		void *p = REALLOC(st->buf, st->size + 2);
		if(p) {
			st->buf = (uint8_t *)p;
			st->buf[st->size++] = control_char;
			st->buf[st->size] = '\0';	/* nul-termination */
			return 0;
		}
	}
	
	return -1;	/* No, it's not */
}

Lev Walkin's avatar
Lev Walkin committed
750
asn_enc_rval_t
Lev Walkin's avatar
Lev Walkin committed
751
OCTET_STRING_encode_xer_utf8(asn_TYPE_descriptor_t *td, void *sptr,
Lev Walkin's avatar
Lev Walkin committed
752 753 754 755
	int ilevel, enum xer_encoder_flags_e flags,
		asn_app_consume_bytes_f *cb, void *app_key) {
	const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
	asn_enc_rval_t er;
Lev Walkin's avatar
Lev Walkin committed
756 757 758
	uint8_t *buf, *end;
	uint8_t *ss;	/* Sequence start */
	ssize_t encoded_len = 0;
Lev Walkin's avatar
Lev Walkin committed
759 760 761 762

	(void)ilevel;	/* Unused argument */
	(void)flags;	/* Unused argument */

Lev Walkin's avatar
Lev Walkin committed
763
	if(!st || (!st->buf && st->size))
764
		ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
765

Lev Walkin's avatar
Lev Walkin committed
766 767 768
	buf = st->buf;
	end = buf + st->size;
	for(ss = buf; buf < end; buf++) {
769
		unsigned int ch = *buf;
Lev Walkin's avatar
Lev Walkin committed
770 771 772 773 774 775 776 777 778 779 780
		int s_len;	/* Special encoding sequence length */

		/*
		 * Escape certain characters: X.680/11.15
		 */
		if(ch < sizeof(OCTET_STRING__xer_escape_table)
			/sizeof(OCTET_STRING__xer_escape_table[0])
		&& (s_len = OCTET_STRING__xer_escape_table[ch].size)) {
			if(((buf - ss) && cb(ss, buf - ss, app_key) < 0)
			|| cb(OCTET_STRING__xer_escape_table[ch].string, s_len,
					app_key) < 0)
781
				ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
782 783 784 785 786 787 788
			encoded_len += (buf - ss) + s_len;
			ss = buf + 1;
		}
	}

	encoded_len += (buf - ss);
	if((buf - ss) && cb(ss, buf - ss, app_key) < 0)
789
		ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
790

Lev Walkin's avatar
Lev Walkin committed
791
	er.encoded = encoded_len;
792
	ASN__ENCODED_OK(er);
Lev Walkin's avatar
Lev Walkin committed
793 794
}

Lev Walkin's avatar
Lev Walkin committed
795 796 797
/*
 * Convert from hexadecimal format (cstring): "AB CD EF"
 */
798
static ssize_t OCTET_STRING__convert_hexadecimal(void *sptr, const void *chunk_buf, size_t chunk_size, int have_more) {
Lev Walkin's avatar
Lev Walkin committed
799
	OCTET_STRING_t *st = (OCTET_STRING_t *)sptr;
800 801 802
	const char *chunk_stop = (const char *)chunk_buf;
	const char *p = chunk_stop;
	const char *pend = p + chunk_size;
Lev Walkin's avatar
Lev Walkin committed
803 804 805 806 807
	unsigned int clv = 0;
	int half = 0;	/* Half bit */
	uint8_t *buf;

	/* Reallocate buffer according to high cap estimation */
Lev Walkin's avatar
Lev Walkin committed
808 809
	size_t new_size = st->size + (chunk_size + 1) / 2;
	void *nptr = REALLOC(st->buf, new_size + 1);
Lev Walkin's avatar
Lev Walkin committed
810 811 812 813 814 815 816 817 818 819
	if(!nptr) return -1;
	st->buf = (uint8_t *)nptr;
	buf = st->buf + st->size;

	/*
	 * If something like " a b c " appears here, the " a b":3 will be
	 * converted, and the rest skipped. That is, unless buf_size is greater
	 * than chunk_size, then it'll be equivalent to "ABC0".
	 */
	for(; p < pend; p++) {
820
		int ch = *(const unsigned char *)p;
Lev Walkin's avatar
Lev Walkin committed
821 822 823 824 825 826 827 828 829 830 831
		switch(ch) {
		case 0x09: case 0x0a: case 0x0c: case 0x0d:
		case 0x20:
			/* Ignore whitespace */
			continue;
		case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: /*01234*/
		case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: /*56789*/
			clv = (clv << 4) + (ch - 0x30);
			break;
		case 0x41: case 0x42: case 0x43:	/* ABC */
		case 0x44: case 0x45: case 0x46:	/* DEF */
Lev Walkin's avatar
oops  
Lev Walkin committed
832
			clv = (clv << 4) + (ch - 0x41 + 10);
Lev Walkin's avatar
Lev Walkin committed
833 834 835
			break;
		case 0x61: case 0x62: case 0x63:	/* abc */
		case 0x64: case 0x65: case 0x66:	/* def */
Lev Walkin's avatar
oops  
Lev Walkin committed
836
			clv = (clv << 4) + (ch - 0x61 + 10);
Lev Walkin's avatar
Lev Walkin committed
837 838 839 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
			break;
		default:
			*buf = 0;	/* JIC */
			return -1;
		}
		if(half++) {
			half = 0;
			*buf++ = clv;
			chunk_stop = p + 1;
		}
	}

	/*
	 * Check partial decoding.
	 */
	if(half) {
		if(have_more) {
			/*
			 * Partial specification is fine,
			 * because no more more PXER_TEXT data is available.
			 */
			*buf++ = clv << 4;
			chunk_stop = p;
		}
	} else {
		chunk_stop = p;
	}

	st->size = buf - st->buf;	/* Adjust the buffer size */
Lev Walkin's avatar
Lev Walkin committed
866
	assert(st->size <= new_size);
Lev Walkin's avatar
Lev Walkin committed
867 868
	st->buf[st->size] = 0;		/* Courtesy termination */

869
	return (chunk_stop - (const char *)chunk_buf);	/* Converted size */
Lev Walkin's avatar
Lev Walkin committed
870 871 872 873 874
}

/*
 * Convert from binary format: "00101011101"
 */
875
static ssize_t OCTET_STRING__convert_binary(void *sptr, const void *chunk_buf, size_t chunk_size, int have_more) {
Lev Walkin's avatar
Lev Walkin committed
876
	BIT_STRING_t *st = (BIT_STRING_t *)sptr;
877 878
	const char *p = (const char *)chunk_buf;
	const char *pend = p + chunk_size;
Lev Walkin's avatar
Lev Walkin committed
879 880 881 882
	int bits_unused = st->bits_unused & 0x7;
	uint8_t *buf;

	/* Reallocate buffer according to high cap estimation */
Lev Walkin's avatar
Lev Walkin committed
883 884
	size_t new_size = st->size + (chunk_size + 7) / 8;
	void *nptr = REALLOC(st->buf, new_size + 1);
Lev Walkin's avatar
Lev Walkin committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	if(!nptr) return -1;
	st->buf = (uint8_t *)nptr;
	buf = st->buf + st->size;

	(void)have_more;

	if(bits_unused == 0)
		bits_unused = 8;
	else if(st->size)
		buf--;

	/*
	 * Convert series of 0 and 1 into the octet string.
	 */
	for(; p < pend; p++) {
900
		int ch = *(const unsigned char *)p;
Lev Walkin's avatar
Lev Walkin committed
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
		switch(ch) {
		case 0x09: case 0x0a: case 0x0c: case 0x0d:
		case 0x20:
			/* Ignore whitespace */
			break;
		case 0x30:
		case 0x31:
			if(bits_unused-- <= 0) {
				*++buf = 0;	/* Clean the cell */
				bits_unused = 7;
			}
			*buf |= (ch&1) << bits_unused;
			break;
		default:
			st->bits_unused = bits_unused;
			return -1;
		}
	}

	if(bits_unused == 8) {
		st->size = buf - st->buf;
		st->bits_unused = 0;
	} else {
		st->size = buf - st->buf + 1;
		st->bits_unused = bits_unused;
	}

Lev Walkin's avatar
Lev Walkin committed
928
	assert(st->size <= new_size);
Lev Walkin's avatar
Lev Walkin committed
929 930 931 932 933 934 935 936 937
	st->buf[st->size] = 0;		/* Courtesy termination */

	return chunk_size;	/* Converted in full */
}

/*
 * Something like strtod(), but with stricter rules.
 */
static int
938
OS__strtoent(int base, const char *buf, const char *end, int32_t *ret_value) {
Lev Walkin's avatar
Lev Walkin committed
939
	int32_t val = 0;
940
	const char *p;
Lev Walkin's avatar
Lev Walkin committed
941 942 943

	for(p = buf; p < end; p++) {
		int ch = *p;
944 945 946 947 948

		/* Strange huge value */
		if((val * base + base) < 0)
			return -1;

Lev Walkin's avatar
Lev Walkin committed
949 950 951 952 953 954 955
		switch(ch) {
		case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: /*01234*/
		case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: /*56789*/
			val = val * base + (ch - 0x30);
			break;
		case 0x41: case 0x42: case 0x43:	/* ABC */
		case 0x44: case 0x45: case 0x46:	/* DEF */
Lev Walkin's avatar
oops  
Lev Walkin committed
956
			val = val * base + (ch - 0x41 + 10);
Lev Walkin's avatar
Lev Walkin committed
957 958 959
			break;
		case 0x61: case 0x62: case 0x63:	/* abc */
		case 0x64: case 0x65: case 0x66:	/* def */
Lev Walkin's avatar
oops  
Lev Walkin committed
960
			val = val * base + (ch - 0x61 + 10);
Lev Walkin's avatar
Lev Walkin committed
961 962
			break;
		case 0x3b:	/* ';' */
963
			*ret_value = val;
Lev Walkin's avatar
Lev Walkin committed
964 965 966 967 968 969
			return (p - buf) + 1;
		default:
			return -1;	/* Character set error */
		}
	}

970
	*ret_value = -1;
Lev Walkin's avatar
Lev Walkin committed
971 972 973 974 975 976
	return (p - buf);
}

/*
 * Convert from the plain UTF-8 format, expanding entity references: "2 &lt; 3"
 */
977
static ssize_t OCTET_STRING__convert_entrefs(void *sptr, const void *chunk_buf, size_t chunk_size, int have_more) {
Lev Walkin's avatar
Lev Walkin committed
978
	OCTET_STRING_t *st = (OCTET_STRING_t *)sptr;
979 980
	const char *p = (const char *)chunk_buf;
	const char *pend = p + chunk_size;
Lev Walkin's avatar
Lev Walkin committed
981 982 983
	uint8_t *buf;

	/* Reallocate buffer */
Lev Walkin's avatar
Lev Walkin committed
984 985
	size_t new_size = st->size + chunk_size;
	void *nptr = REALLOC(st->buf, new_size + 1);
Lev Walkin's avatar
Lev Walkin committed
986 987 988 989 990 991 992 993
	if(!nptr) return -1;
	st->buf = (uint8_t *)nptr;
	buf = st->buf + st->size;

	/*
	 * Convert series of 0 and 1 into the octet string.
	 */
	for(; p < pend; p++) {
994
		int ch = *(const unsigned char *)p;
Lev Walkin's avatar
Lev Walkin committed
995 996 997 998 999 1000 1001 1002 1003 1004
		int len;	/* Length of the rest of the chunk */

		if(ch != 0x26 /* '&' */) {
			*buf++ = ch;
			continue;	/* That was easy... */
		}

		/*
		 * Process entity reference.
		 */
1005
		len = chunk_size - (p - (const char *)chunk_buf);
Lev Walkin's avatar
Lev Walkin committed
1006 1007
		if(len == 1 /* "&" */) goto want_more;
		if(p[1] == 0x23 /* '#' */) {
1008
			const char *pval;	/* Pointer to start of digits */
1009
			int32_t val = 0;	/* Entity reference value */
Lev Walkin's avatar
Lev Walkin committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
			int base;

			if(len == 2 /* "&#" */) goto want_more;
			if(p[2] == 0x78 /* 'x' */)
				pval = p + 3, base = 16;
			else
				pval = p + 2, base = 10;
			len = OS__strtoent(base, pval, p + len, &val);
			if(len == -1) {
				/* Invalid charset. Just copy verbatim. */
				*buf++ = ch;
				continue;
			}
			if(!len || pval[len-1] != 0x3b) goto want_more;
			assert(val > 0);
			p += (pval - p) + len - 1; /* Advance past entref */

			if(val < 0x80) {
				*buf++ = (char)val;
			} else if(val < 0x800) {
				*buf++ = 0xc0 | ((val >> 6));
				*buf++ = 0x80 | ((val & 0x3f));
			} else if(val < 0x10000) {
				*buf++ = 0xe0 | ((val >> 12));
				*buf++ = 0x80 | ((val >> 6) & 0x3f);
				*buf++ = 0x80 | ((val & 0x3f));
			} else if(val < 0x200000) {
				*buf++ = 0xf0 | ((val >> 18));
				*buf++ = 0x80 | ((val >> 12) & 0x3f);
				*buf++ = 0x80 | ((val >> 6) & 0x3f);
				*buf++ = 0x80 | ((val & 0x3f));
			} else if(val < 0x4000000) {
				*buf++ = 0xf8 | ((val >> 24));
				*buf++ = 0x80 | ((val >> 18) & 0x3f);
				*buf++ = 0x80 | ((val >> 12) & 0x3f);
				*buf++ = 0x80 | ((val >> 6) & 0x3f);
				*buf++ = 0x80 | ((val & 0x3f));
			} else {
				*buf++ = 0xfc | ((val >> 30) & 0x1);
				*buf++ = 0x80 | ((val >> 24) & 0x3f);
				*buf++ = 0x80 | ((val >> 18) & 0x3f);
				*buf++ = 0x80 | ((val >> 12) & 0x3f);
				*buf++ = 0x80 | ((val >> 6) & 0x3f);
				*buf++ = 0x80 | ((val & 0x3f));
			}
		} else {
			/*
			 * Ugly, limited parsing of &amp; &gt; &lt;
			 */
			char *sc = (char *)memchr(p, 0x3b, len > 5 ? 5 : len);
			if(!sc) goto want_more;
			if((sc - p) == 4
				&& p[1] == 0x61	/* 'a' */
				&& p[2] == 0x6d	/* 'm' */
				&& p[3] == 0x70	/* 'p' */) {
				*buf++ = 0x26;
				p = sc;
				continue;
			}
			if((sc - p) == 3) {
				if(p[1] == 0x6c) {
					*buf = 0x3c;	/* '<' */
				} else if(p[1] == 0x67) {
					*buf = 0x3e;	/* '>' */
				} else {
					/* Unsupported entity reference */
					*buf++ = ch;
					continue;
				}
				if(p[2] != 0x74) {
					/* Unsupported entity reference */
					*buf++ = ch;
					continue;
				}
				buf++;
				p = sc;
				continue;
			}
			/* Unsupported entity reference */
			*buf++ = ch;
		}

		continue;
	want_more:
		if(have_more) {
			/*
			 * We know that no more data (of the same type)
			 * is coming. Copy the rest verbatim.
			 */
			*buf++ = ch;
			continue;
		}
1102
		chunk_size = (p - (const char *)chunk_buf);
Lev Walkin's avatar
Lev Walkin committed
1103
		/* Processing stalled: need more data */
Lev Walkin's avatar
Lev Walkin committed
1104
		break;
Lev Walkin's avatar
Lev Walkin committed
1105 1106 1107
	}

	st->size = buf - st->buf;
Lev Walkin's avatar
Lev Walkin committed
1108
	assert(st->size <= new_size);
Lev Walkin's avatar
Lev Walkin committed
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
	st->buf[st->size] = 0;		/* Courtesy termination */

	return chunk_size;	/* Converted in full */
}

/*
 * Decode OCTET STRING from the XML element's body.
 */
static asn_dec_rval_t
OCTET_STRING__decode_xer(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td, void **sptr,
Lev Walkin's avatar
Lev Walkin committed
1120
	const char *opt_mname, const void *buf_ptr, size_t size,
Lev Walkin's avatar
Lev Walkin committed
1121
	int (*opt_unexpected_tag_decoder)
1122
		(void *struct_ptr, const void *chunk_buf, size_t chunk_size),
Lev Walkin's avatar
Lev Walkin committed
1123
	ssize_t (*body_receiver)
1124
		(void *struct_ptr, const void *chunk_buf, size_t chunk_size,
Lev Walkin's avatar
Lev Walkin committed
1125 1126
			int have_more)
) {
Lev Walkin's avatar
C++  
Lev Walkin committed
1127
	OCTET_STRING_t *st = (OCTET_STRING_t *)*sptr;
Lev Walkin's avatar
Lev Walkin committed
1128 1129
	asn_OCTET_STRING_specifics_t *specs = td->specifics
				? (asn_OCTET_STRING_specifics_t *)td->specifics
1130
				: &asn_SPC_OCTET_STRING_specs;
Lev Walkin's avatar
Lev Walkin committed
1131 1132
	const char *xml_tag = opt_mname ? opt_mname : td->xml_tag;
	asn_struct_ctx_t *ctx;		/* Per-structure parser context */
Lev Walkin's avatar
Lev Walkin committed
1133 1134
	asn_dec_rval_t rval;		/* Return value from the decoder */
	int st_allocated;
Lev Walkin's avatar
Lev Walkin committed
1135 1136 1137 1138

	/*
	 * Create the string if does not exist.
	 */
Lev Walkin's avatar
Lev Walkin committed
1139
	if(!st) {
1140 1141
		st = (OCTET_STRING_t *)CALLOC(1, specs->struct_size);
		*sptr = (void *)st;
Lev Walkin's avatar
Lev Walkin committed
1142 1143
		if(!st) goto sta_failed;
		st_allocated = 1;
Lev Walkin's avatar
Lev Walkin committed
1144 1145 1146
	} else {
		st_allocated = 0;
	}
Lev Walkin's avatar
Lev Walkin committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
	if(!st->buf) {
		/* This is separate from above section */
		st->buf = (uint8_t *)CALLOC(1, 1);
		if(!st->buf) {
			if(st_allocated) {
				*sptr = 0;
				goto stb_failed;
			} else {
				goto sta_failed;
			}
Lev Walkin's avatar
Lev Walkin committed
1157 1158 1159 1160
		}
	}

	/* Restore parsing context */
Lev Walkin's avatar
Lev Walkin committed
1161
	ctx = (asn_struct_ctx_t *)(((char *)*sptr) + specs->ctx_offset);
Lev Walkin's avatar
Lev Walkin committed
1162 1163 1164

	return xer_decode_general(opt_codec_ctx, ctx, *sptr, xml_tag,
		buf_ptr, size, opt_unexpected_tag_decoder, body_receiver);
Lev Walkin's avatar
Lev Walkin committed
1165 1166 1167 1168 1169 1170 1171

stb_failed:
	FREEMEM(st);
sta_failed:
	rval.code = RC_FAIL;
	rval.consumed = 0;
	return rval;
Lev Walkin's avatar
Lev Walkin committed
1172 1173 1174 1175 1176 1177 1178 1179
}

/*
 * Decode OCTET STRING from the hexadecimal data.
 */
asn_dec_rval_t
OCTET_STRING_decode_xer_hex(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td, void **sptr,
Lev Walkin's avatar
Lev Walkin committed
1180
		const char *opt_mname, const void *buf_ptr, size_t size) {
Lev Walkin's avatar
Lev Walkin committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
	return OCTET_STRING__decode_xer(opt_codec_ctx, td, sptr, opt_mname,
		buf_ptr, size, 0, OCTET_STRING__convert_hexadecimal);
}

/*
 * Decode OCTET STRING from the binary (0/1) data.
 */
asn_dec_rval_t
OCTET_STRING_decode_xer_binary(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td, void **sptr,
Lev Walkin's avatar
Lev Walkin committed
1191
		const char *opt_mname, const void *buf_ptr, size_t size) {
Lev Walkin's avatar
Lev Walkin committed
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
	return OCTET_STRING__decode_xer(opt_codec_ctx, td, sptr, opt_mname,
		buf_ptr, size, 0, OCTET_STRING__convert_binary);
}

/*
 * Decode OCTET STRING from the string (ASCII/UTF-8) data.
 */
asn_dec_rval_t
OCTET_STRING_decode_xer_utf8(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td, void **sptr,
Lev Walkin's avatar
Lev Walkin committed
1202
		const char *opt_mname, const void *buf_ptr, size_t size) {
Lev Walkin's avatar
Lev Walkin committed
1203 1204 1205 1206 1207 1208
	return OCTET_STRING__decode_xer(opt_codec_ctx, td, sptr, opt_mname,
		buf_ptr, size,
		OCTET_STRING__handle_control_chars,
		OCTET_STRING__convert_entrefs);
}

Lev Walkin's avatar
Lev Walkin committed
1209
static int
1210 1211
OCTET_STRING_per_get_characters(asn_per_data_t *po, uint8_t *buf,
		size_t units, unsigned int bpc, unsigned int unit_bits,
Lev Walkin's avatar
Lev Walkin committed
1212
		long lb, long ub, const asn_per_constraints_t *pc) {
1213
	uint8_t *end = buf + units * bpc;
Lev Walkin's avatar
Lev Walkin committed
1214 1215

	ASN_DEBUG("Expanding %d characters into (%ld..%ld):%d",
1216
		(int)units, lb, ub, unit_bits);
Lev Walkin's avatar
Lev Walkin committed
1217 1218

	/* X.691: 27.5.4 */
1219
	if((unsigned long)ub <= ((unsigned long)2 << (unit_bits - 1))) {
Lev Walkin's avatar
Lev Walkin committed
1220 1221
		/* Decode without translation */
		lb = 0;
1222 1223 1224 1225 1226 1227
	} else if(pc && pc->code2value) {
		if(unit_bits > 16)
			return 1;	/* FATAL: can't have constrained
					 * UniversalString with more than
					 * 16 million code points */
		for(; buf < end; buf += bpc) {
Lev Walkin's avatar
Lev Walkin committed
1228
			int value;
1229
			int code = per_get_few_bits(po, unit_bits);
Lev Walkin's avatar
Lev Walkin committed
1230
			if(code < 0) return -1;	/* WMORE */
1231
			value = pc->code2value(code);
Lev Walkin's avatar
Lev Walkin committed
1232 1233 1234 1235 1236 1237
			if(value < 0) {
				ASN_DEBUG("Code %d (0x%02x) is"
					" not in map (%ld..%ld)",
					code, code, lb, ub);
				return 1;	/* FATAL */
			}
1238 1239 1240 1241 1242 1243
			switch(bpc) {
			case 1: *buf = value; break;
			case 2: buf[0] = value >> 8; buf[1] = value; break;
			case 4: buf[0] = value >> 24; buf[1] = value >> 16;
				buf[2] = value >> 8; buf[3] = value; break;
			}
Lev Walkin's avatar
Lev Walkin committed
1244 1245 1246 1247
		}
		return 0;
	}

1248 1249 1250 1251 1252 1253
	/* Shortcut the no-op copying to the aligned structure */
	if(lb == 0 && (unit_bits == 8 * bpc)) {
		return per_get_many_bits(po, buf, 0, unit_bits * units);
	}

	for(; buf < end; buf += bpc) {
Lev Walkin's avatar
Lev Walkin committed
1254 1255 1256 1257 1258 1259 1260 1261
		int code = per_get_few_bits(po, unit_bits);
		int ch = code + lb;
		if(code < 0) return -1;	/* WMORE */
		if(ch > ub) {
			ASN_DEBUG("Code %d is out of range (%ld..%ld)",
				ch, lb, ub);
			return 1;	/* FATAL */
		}
1262 1263 1264 1265 1266 1267
		switch(bpc) {
		case 1: *buf = ch; break;
		case 2: buf[0] = ch >> 8; buf[1] = ch; break;
		case 4: buf[0] = ch >> 24; buf[1] = ch >> 16;
			buf[2] = ch >> 8; buf[3] = ch; break;
		}
Lev Walkin's avatar
Lev Walkin committed
1268 1269 1270 1271 1272 1273
	}

	return 0;
}

static int
1274 1275
OCTET_STRING_per_put_characters(asn_per_outp_t *po, const uint8_t *buf,
		size_t units, unsigned int bpc, unsigned int unit_bits,
Lev Walkin's avatar
Lev Walkin committed
1276
		long lb, long ub, const asn_per_constraints_t *pc) {
1277
	const uint8_t *end = buf + units * bpc;
Lev Walkin's avatar
Lev Walkin committed
1278

1279 1280
	ASN_DEBUG("Squeezing %d characters into (%ld..%ld):%d (%d bpc)",
		(int)units, lb, ub, unit_bits, bpc);
Lev Walkin's avatar
Lev Walkin committed
1281 1282

	/* X.691: 27.5.4 */
1283
	if((unsigned long)ub <= ((unsigned long)2 << (unit_bits - 1))) {
Lev Walkin's avatar
Lev Walkin committed
1284 1285
		/* Encode as is */
		lb = 0;
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
	} else if(pc && pc->value2code) {
		for(; buf < end; buf += bpc) {
			int code;
			uint32_t value;
			switch(bpc) {
			case 1: value = *(const uint8_t *)buf; break;
			case 2: value = (buf[0] << 8) | buf[1]; break;
			case 4: value = (buf[0] << 24) | (buf[1] << 16)
					| (buf[2] << 8) | buf[3]; break;
			default: return -1;
			}
			code = pc->value2code(value);
Lev Walkin's avatar
Lev Walkin committed
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
			if(code < 0) {
				ASN_DEBUG("Character %d (0x%02x) is"
					" not in map (%ld..%ld)",
					*buf, *buf, lb, ub);
				return -1;
			}
			if(per_put_few_bits(po, code, unit_bits))
				return -1;
		}
	}

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
	/* Shortcut the no-op copying to the aligned structure */
	if(lb == 0 && (unit_bits == 8 * bpc)) {
		return per_put_many_bits(po, buf, unit_bits * units);
	}

	for(ub -= lb; buf < end; buf += bpc) {
		int ch;
		uint32_t value;
		switch(bpc) {
		case 1: value = *(const uint8_t *)buf; break;
		case 2: value = (buf[0] << 8) | buf[1]; break;
		case 4: value = (buf[0] << 24) | (buf[1] << 16)
				| (buf[2] << 8) | buf[3]; break;
		default: return -1;
		}
		ch = value - lb;
Lev Walkin's avatar
Lev Walkin committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
		if(ch < 0 || ch > ub) {
			ASN_DEBUG("Character %d (0x%02x)"
			" is out of range (%ld..%ld)",
				*buf, *buf, lb, ub + lb);
			return -1;
		}
		if(per_put_few_bits(po, ch, unit_bits))
			return -1;
	}

	return 0;
}

1338 1339
#ifndef  ASN_DISABLE_PER_SUPPORT

Lev Walkin's avatar
Lev Walkin committed
1340 1341
asn_dec_rval_t
OCTET_STRING_decode_uper(asn_codec_ctx_t *opt_codec_ctx,
Lev Walkin's avatar
Lev Walkin committed
1342 1343 1344 1345
                         asn_TYPE_descriptor_t *td,
                         const asn_per_constraints_t *constraints, void **sptr,
                         asn_per_data_t *pd) {
    asn_OCTET_STRING_specifics_t *specs = td->specifics
Lev Walkin's avatar
Lev Walkin committed
1346
		? (asn_OCTET_STRING_specifics_t *)td->specifics
1347
		: &asn_SPC_OCTET_STRING_specs;
Lev Walkin's avatar
Lev Walkin committed
1348 1349 1350 1351
    const asn_per_constraints_t *pc =
        constraints ? constraints : td->per_constraints;
    const asn_per_constraint_t *cval;
	const asn_per_constraint_t *csiz;
Lev Walkin's avatar
Lev Walkin committed
1352 1353 1354 1355
	asn_dec_rval_t rval = { RC_OK, 0 };
	BIT_STRING_t *st = (BIT_STRING_t *)*sptr;
	ssize_t consumed_myself = 0;
	int repeat;
1356 1357 1358 1359 1360 1361 1362 1363
	enum {
		OS__BPC_BIT	= 0,
		OS__BPC_CHAR	= 1,
		OS__BPC_U16	= 2,
		OS__BPC_U32	= 4
	} bpc;	/* Bytes per character */
	unsigned int unit_bits;
	unsigned int canonical_unit_bits;
Lev Walkin's avatar
Lev Walkin committed
1364 1365 1366

	(void)opt_codec_ctx;

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
	if(pc) {
		cval = &pc->value;
		csiz = &pc->size;
	} else {
		cval = &asn_DEF_OCTET_STRING_constraints.value;
		csiz = &asn_DEF_OCTET_STRING_constraints.size;
	}

	switch(specs->subvariant) {
	default:
	case ASN_OSUBV_ANY:
		ASN_DEBUG("Unrecognized subvariant %d", specs->subvariant);
		RETURN(RC_FAIL);
	case ASN_OSUBV_BIT:
		canonical_unit_bits = unit_bits = 1;
		bpc = OS__BPC_BIT;
		break;
	case ASN_OSUBV_STR:
		canonical_unit_bits = unit_bits = 8;
		if(cval->flags & APC_CONSTRAINED)
			unit_bits = cval->range_bits;
		bpc = OS__BPC_CHAR;
		break;
	case ASN_OSUBV_U16:
		canonical_unit_bits = unit_bits = 16;
		if(cval->flags & APC_CONSTRAINED)
			unit_bits = cval->range_bits;
		bpc = OS__BPC_U16;
		break;
	case ASN_OSUBV_U32:
		canonical_unit_bits = unit_bits = 32;
		if(cval->flags & APC_CONSTRAINED)
			unit_bits = cval->range_bits;
		bpc = OS__BPC_U32;
		break;
	}

Lev Walkin's avatar
Lev Walkin committed
1404 1405 1406 1407 1408 1409 1410 1411
	/*
	 * Allocate the string.
	 */
	if(!st) {
		st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
		if(!st) RETURN(RC_FAIL);
	}

Lev Walkin's avatar
Lev Walkin committed
1412
	ASN_DEBUG("PER Decoding %s size %ld .. %ld bits %d",
1413 1414
		csiz->flags & APC_EXTENSIBLE ? "extensible" : "non-extensible",
		csiz->lower_bound, csiz->upper_bound, csiz->effective_bits);
Lev Walkin's avatar
Lev Walkin committed
1415

1416
	if(csiz->flags & APC_EXTENSIBLE) {
Lev Walkin's avatar
Lev Walkin committed
1417
		int inext = per_get_few_bits(pd, 1);
Lev Walkin's avatar
Lev Walkin committed
1418
		if(inext < 0) RETURN(RC_WMORE);
1419 1420 1421 1422 1423
		if(inext) {
			csiz = &asn_DEF_OCTET_STRING_constraints.size;
			cval = &asn_DEF_OCTET_STRING_constraints.value;
			unit_bits = canonical_unit_bits;
		}
Lev Walkin's avatar
Lev Walkin committed
1424 1425
	}

1426
	if(csiz->effective_bits >= 0) {
Lev Walkin's avatar
Lev Walkin committed
1427
		FREEMEM(st->buf);
1428 1429
		if(bpc) {
			st->size = csiz->upper_bound * bpc;
Lev Walkin's avatar
Lev Walkin committed
1430
		} else {
1431
			st->size = (csiz->upper_bound + 7) >> 3;
Lev Walkin's avatar
Lev Walkin committed
1432 1433 1434 1435 1436 1437 1438 1439
		}
		st->buf = (uint8_t *)MALLOC(st->size + 1);
		if(!st->buf) { st->size = 0; RETURN(RC_FAIL); }
	}

	/* X.691, #16.5: zero-length encoding */
	/* X.691, #16.6: short fixed length encoding (up to 2 octets) */
	/* X.691, #16.7: long fixed length encoding (up to 64K octets) */
1440
	if(csiz->effective_bits == 0) {
Lev Walkin's avatar
Lev Walkin committed
1441
		int ret;
1442 1443 1444 1445 1446 1447
		if(bpc) {
			ASN_DEBUG("Encoding OCTET STRING size %ld",
				csiz->upper_bound);
			ret = OCTET_STRING_per_get_characters(pd, st->buf,
				csiz->upper_bound, bpc, unit_bits,
				cval->lower_bound, cval->upper_bound, pc);
Lev Walkin's avatar
Lev Walkin committed
1448 1449
			if(ret > 0) RETURN(RC_FAIL);
		} else {
1450 1451
			ASN_DEBUG("Encoding BIT STRING size %ld",
				csiz->upper_bound);
Lev Walkin's avatar
Lev Walkin committed
1452
			ret = per_get_many_bits(pd, st->buf, 0,
1453
					    unit_bits * csiz->upper_bound);
Lev Walkin's avatar
Lev Walkin committed
1454
		}
Lev Walkin's avatar
Lev Walkin committed
1455
		if(ret < 0) RETURN(RC_WMORE);
1456
		consumed_myself += unit_bits * csiz->upper_bound;
Lev Walkin's avatar
Lev Walkin committed
1457
		st->buf[st->size] = 0;
1458 1459 1460 1461
		if(bpc == 0) {
			int ubs = (csiz->upper_bound & 0x7);
			st->bits_unused = ubs ? 8 - ubs : 0;
		}
Lev Walkin's avatar
Lev Walkin committed
1462 1463 1464 1465 1466
		RETURN(RC_OK);
	}

	st->size = 0;
	do {
1467
		ssize_t raw_len;
Lev Walkin's avatar
Lev Walkin committed
1468 1469 1470 1471 1472 1473
		ssize_t len_bytes;
		ssize_t len_bits;
		void *p;
		int ret;

		/* Get the PER length */
1474 1475 1476
		raw_len = uper_get_length(pd, csiz->effective_bits, &repeat);
		if(raw_len < 0) RETURN(RC_WMORE);
		raw_len += csiz->lower_bound;
Lev Walkin's avatar
Lev Walkin committed
1477

Lev Walkin's avatar
Lev Walkin committed
1478
		ASN_DEBUG("Got PER length eb %ld, len %ld, %s (%s)",
1479
			(long)csiz->effective_bits, (long)raw_len,
Lev Walkin's avatar
Lev Walkin committed
1480
			repeat ? "repeat" : "once", td->name);
1481 1482 1483 1484 1485
		if(bpc) {
			len_bytes = raw_len * bpc;
			len_bits = len_bytes * unit_bits;
		} else {
			len_bits = raw_len;
Lev Walkin's avatar
Lev Walkin committed
1486 1487 1488 1489 1490 1491 1492 1493 1494
			len_bytes = (len_bits + 7) >> 3;
			if(len_bits & 0x7)
				st->bits_unused = 8 - (len_bits & 0x7);
			/* len_bits be multiple of 16K if repeat is set */
		}
		p = REALLOC(st->buf, st->size + len_bytes + 1);
		if(!p) RETURN(RC_FAIL);
		st->buf = (uint8_t *)p;

1495 1496 1497 1498
		if(bpc) {
			ret = OCTET_STRING_per_get_characters(pd,
				&st->buf[st->size], raw_len, bpc, unit_bits,
				cval->lower_bound, cval->upper_bound, pc);
Lev Walkin's avatar
Lev Walkin committed
1499 1500 1501 1502 1503
			if(ret > 0) RETURN(RC_FAIL);
		} else {
			ret = per_get_many_bits(pd, &st->buf[st->size],
				0, len_bits);
		}
Lev Walkin's avatar
Lev Walkin committed
1504
		if(ret < 0) RETURN(RC_WMORE);
Lev Walkin's avatar
Lev Walkin committed
1505 1506 1507 1508 1509 1510
		st->size += len_bytes;
	} while(repeat);
	st->buf[st->size] = 0;	/* nul-terminate */

	return rval;
}
Lev Walkin's avatar
Lev Walkin committed
1511

Lev Walkin's avatar
Lev Walkin committed
1512 1513
asn_enc_rval_t
OCTET_STRING_encode_uper(asn_TYPE_descriptor_t *td,
Lev Walkin's avatar
Lev Walkin committed
1514 1515 1516
                         const asn_per_constraints_t *constraints, void *sptr,
                         asn_per_outp_t *po) {
    asn_OCTET_STRING_specifics_t *specs = td->specifics
Lev Walkin's avatar
Lev Walkin committed
1517
		? (asn_OCTET_STRING_specifics_t *)td->specifics
1518
		: &asn_SPC_OCTET_STRING_specs;
Lev Walkin's avatar
Lev Walkin committed
1519
	const asn_per_constraints_t *pc = constraints ? constraints
Lev Walkin's avatar
Lev Walkin committed
1520
				: td->per_constraints;
Lev Walkin's avatar
Lev Walkin committed
1521 1522
	const asn_per_constraint_t *cval;
	const asn_per_constraint_t *csiz;
Lev Walkin's avatar
Lev Walkin committed
1523
	const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
1524
	asn_enc_rval_t er = { 0, 0, 0 };
Lev Walkin's avatar
Lev Walkin committed
1525
	int inext = 0;		/* Lies not within extension root */
1526 1527 1528
	unsigned int unit_bits;
	unsigned int canonical_unit_bits;
	unsigned int sizeinunits;
Lev Walkin's avatar
Lev Walkin committed
1529 1530
	const uint8_t *buf;
	int ret;
1531 1532 1533 1534 1535 1536 1537
	enum {
		OS__BPC_BIT	= 0,
		OS__BPC_CHAR	= 1,
		OS__BPC_U16	= 2,
		OS__BPC_U32	= 4
	} bpc;	/* Bytes per character */
	int ct_extensible;
Lev Walkin's avatar
Lev Walkin committed
1538

Lev Walkin's avatar
Lev Walkin committed
1539
	if(!st || (!st->buf && st->size))
1540
		ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
1541

1542 1543 1544 1545 1546 1547
	if(pc) {
		cval = &pc->value;
		csiz = &pc->size;
	} else {
		cval = &asn_DEF_OCTET_STRING_constraints.value;
		csiz = &asn_DEF_OCTET_STRING_constraints.size;
Lev Walkin's avatar
Lev Walkin committed
1548
	}
1549
	ct_extensible = csiz->flags & APC_EXTENSIBLE;
Lev Walkin's avatar
Lev Walkin committed
1550

1551 1552 1553
	switch(specs->subvariant) {
	default:
	case ASN_OSUBV_ANY:
1554
		ASN__ENCODE_FAILED;
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
	case ASN_OSUBV_BIT:
		canonical_unit_bits = unit_bits = 1;
		bpc = OS__BPC_BIT;
		sizeinunits = st->size * 8 - (st->bits_unused & 0x07);
		ASN_DEBUG("BIT STRING of %d bytes, %d bits unused",
				sizeinunits, st->bits_unused);
		break;
	case ASN_OSUBV_STR:
		canonical_unit_bits = unit_bits = 8;
		if(cval->flags & APC_CONSTRAINED)
			unit_bits = cval->range_bits;
		bpc = OS__BPC_CHAR;
		sizeinunits = st->size;
		break;
	case ASN_OSUBV_U16:
		canonical_unit_bits = unit_bits = 16;
		if(cval->flags & APC_CONSTRAINED)
			unit_bits = cval->range_bits;
		bpc = OS__BPC_U16;
1574 1575 1576 1577 1578
		sizeinunits = st->size >> 1;
		if(st->size & 1) {
			ASN_DEBUG("%s string size is not modulo 2", td->name);
			ASN__ENCODE_FAILED;
		}
1579 1580 1581 1582 1583 1584
		break;
	case ASN_OSUBV_U32:
		canonical_unit_bits = unit_bits = 32;
		if(cval->flags & APC_CONSTRAINED)
			unit_bits = cval->range_bits;
		bpc = OS__BPC_U32;
1585 1586 1587 1588 1589
		sizeinunits = st->size >> 2;
		if(st->size & 3) {
			ASN_DEBUG("%s string size is not modulo 4", td->name);
			ASN__ENCODE_FAILED;
		}
1590
		break;
Lev Walkin's avatar
Lev Walkin committed
1591 1592
	}

Lev Walkin's avatar
Lev Walkin committed
1593
	ASN_DEBUG("Encoding %s into %d units of %d bits"
Lev Walkin's avatar
Lev Walkin committed
1594
		" (%ld..%ld, effective %d)%s",
Lev Walkin's avatar
Lev Walkin committed
1595
		td->name, sizeinunits, unit_bits,
1596 1597
		csiz->lower_bound, csiz->upper_bound,
		csiz->effective_bits, ct_extensible ? " EXT" : "");
Lev Walkin's avatar
Lev Walkin committed
1598

Lev Walkin's avatar
Lev Walkin committed
1599
	/* Figure out whether size lies within PER visible constraint */
Lev Walkin's avatar
Lev Walkin committed
1600

1601 1602 1603
	if(csiz->effective_bits >= 0) {
		if((int)sizeinunits < csiz->lower_bound
		|| (int)sizeinunits > csiz->upper_bound) {
Lev Walkin's avatar
Lev Walkin committed
1604
			if(ct_extensible) {
1605 1606 1607
				cval = &asn_DEF_OCTET_STRING_constraints.value;
				csiz = &asn_DEF_OCTET_STRING_constraints.size;
				unit_bits = canonical_unit_bits;
Lev Walkin's avatar
Lev Walkin committed
1608
				inext = 1;
1609
			} else {
1610
				ASN__ENCODE_FAILED;
1611
			}
Lev Walkin's avatar
Lev Walkin committed
1612 1613 1614 1615 1616 1617 1618 1619
		}
	} else {
		inext = 0;
	}

	if(ct_extensible) {
		/* Declare whether length is [not] within extension root */
		if(per_put_few_bits(po, inext, 1))
1620
			ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
1621 1622 1623 1624 1625
	}

	/* X.691, #16.5: zero-length encoding */
	/* X.691, #16.6: short fixed length encoding (up to 2 octets) */
	/* X.691, #16.7: long fixed length encoding (up to 64K octets) */
1626
	if(csiz->effective_bits >= 0) {
Lev Walkin's avatar
Lev Walkin committed
1627
		ASN_DEBUG("Encoding %zu bytes (%ld), length in %d bits",
1628 1629 1630 1631
				st->size, sizeinunits - csiz->lower_bound,
				csiz->effective_bits);
		ret = per_put_few_bits(po, sizeinunits - csiz->lower_bound,
				csiz->effective_bits);
1632
		if(ret) ASN__ENCODE_FAILED;
1633 1634 1635 1636
		if(bpc) {
			ret = OCTET_STRING_per_put_characters(po, st->buf,
				sizeinunits, bpc, unit_bits,
				cval->lower_bound, cval->upper_bound, pc);
Lev Walkin's avatar
Lev Walkin committed
1637 1638 1639 1640
		} else {
			ret = per_put_many_bits(po, st->buf,
				sizeinunits * unit_bits);
		}
1641 1642
		if(ret) ASN__ENCODE_FAILED;
		ASN__ENCODED_OK(er);
Lev Walkin's avatar
Lev Walkin committed
1643 1644
	}

Lev Walkin's avatar
Lev Walkin committed
1645
	ASN_DEBUG("Encoding %zu bytes", st->size);
Lev Walkin's avatar
Lev Walkin committed
1646 1647 1648

	if(sizeinunits == 0) {
		if(uper_put_length(po, 0))
1649 1650
			ASN__ENCODE_FAILED;
		ASN__ENCODED_OK(er);
Lev Walkin's avatar
Lev Walkin committed
1651 1652 1653 1654 1655
	}

	buf = st->buf;
	while(sizeinunits) {
		ssize_t maySave = uper_put_length(po, sizeinunits);
1656
		if(maySave < 0) ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
1657

Lev Walkin's avatar
Lev Walkin committed
1658 1659
		ASN_DEBUG("Encoding %ld of %ld",
			(long)maySave, (long)sizeinunits);
Lev Walkin's avatar
Lev Walkin committed
1660

1661 1662 1663 1664
		if(bpc) {
			ret = OCTET_STRING_per_put_characters(po, buf,
				maySave, bpc, unit_bits,
				cval->lower_bound, cval->upper_bound, pc);
Lev Walkin's avatar
Lev Walkin committed
1665 1666 1667
		} else {
			ret = per_put_many_bits(po, buf, maySave * unit_bits);
		}
1668
		if(ret) ASN__ENCODE_FAILED;
Lev Walkin's avatar
Lev Walkin committed
1669

1670 1671
		if(bpc)
			buf += maySave * bpc;
Lev Walkin's avatar
Lev Walkin committed
1672
		else
1673
			buf += maySave >> 3;
Lev Walkin's avatar
Lev Walkin committed
1674 1675 1676 1677
		sizeinunits -= maySave;
		assert(!(maySave & 0x07) || !sizeinunits);
	}

1678
	ASN__ENCODED_OK(er);
Lev Walkin's avatar
Lev Walkin committed
1679 1680
}

1681 1682
#endif  /* ASN_DISABLE_PER_SUPPORT */

Lev Walkin's avatar
Lev Walkin committed
1683
int
1684
OCTET_STRING_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
Lev Walkin's avatar
Lev Walkin committed
1685
	asn_app_consume_bytes_f *cb, void *app_key) {
1686
	const char * const h2c = "0123456789ABCDEF";
Lev Walkin's avatar
Lev Walkin committed
1687
	const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
Lev Walkin's avatar
Lev Walkin committed
1688 1689 1690 1691 1692 1693
	char scratch[16 * 3 + 4];
	char *p = scratch;
	uint8_t *buf;
	uint8_t *end;
	size_t i;

1694 1695
	(void)td;	/* Unused argument */

Lev Walkin's avatar
Lev Walkin committed
1696 1697
	if(!st || (!st->buf && st->size))
		return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
Lev Walkin's avatar
Lev Walkin committed
1698 1699 1700 1701 1702 1703 1704 1705

	/*
	 * Dump the contents of the buffer in hexadecimal.
	 */
	buf = st->buf;
	end = buf + st->size;
	for(i = 0; buf < end; buf++, i++) {
		if(!(i % 16) && (i || st->size > 16)) {
1706
			if(cb(scratch, p - scratch, app_key) < 0)
Lev Walkin's avatar
Lev Walkin committed
1707
				return -1;
1708
			_i_INDENT(1);
Lev Walkin's avatar
Lev Walkin committed
1709 1710 1711 1712
			p = scratch;
		}
		*p++ = h2c[(*buf >> 4) & 0x0F];
		*p++ = h2c[*buf & 0x0F];
Lev Walkin's avatar
Lev Walkin committed
1713
		*p++ = 0x20;
Lev Walkin's avatar
Lev Walkin committed
1714 1715
	}

Lev Walkin's avatar
Lev Walkin committed
1716 1717
	if(p > scratch) {
		p--;	/* Remove the tail space */
1718
		if(cb(scratch, p - scratch, app_key) < 0)
Lev Walkin's avatar
Lev Walkin committed
1719 1720 1721 1722
			return -1;
	}

	return 0;
Lev Walkin's avatar
Lev Walkin committed
1723 1724 1725
}

int
Lev Walkin's avatar
Lev Walkin committed
1726
OCTET_STRING_print_utf8(asn_TYPE_descriptor_t *td, const void *sptr,
Lev Walkin's avatar
Lev Walkin committed
1727
		int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
Lev Walkin's avatar
Lev Walkin committed
1728
	const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
Lev Walkin's avatar
Lev Walkin committed
1729

1730 1731 1732
	(void)td;	/* Unused argument */
	(void)ilevel;	/* Unused argument */

Lev Walkin's avatar
Lev Walkin committed
1733
	if(st && (st->buf || !st->size)) {
1734
		return (cb(st->buf, st->size, app_key) < 0) ? -1 : 0;
Lev Walkin's avatar
Lev Walkin committed
1735
	} else {
1736
		return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
Lev Walkin's avatar
Lev Walkin committed
1737 1738 1739 1740
	}
}

void
1741
OCTET_STRING_free(const asn_TYPE_descriptor_t *td, void *sptr,
1742 1743
                  enum asn_struct_free_method method) {
	OCTET_STRING_t *st = (OCTET_STRING_t *)sptr;
Lev Walkin's avatar
Lev Walkin committed
1744 1745
	asn_OCTET_STRING_specifics_t *specs;
	asn_struct_ctx_t *ctx;
Lev Walkin's avatar
Lev Walkin committed
1746
	struct _stack *stck;
Lev Walkin's avatar
Lev Walkin committed
1747 1748 1749 1750

	if(!td || !st)
		return;

Lev Walkin's avatar
Lev Walkin committed
1751 1752
	specs = td->specifics
		    ? (asn_OCTET_STRING_specifics_t *)td->specifics
1753
		    : &asn_SPC_OCTET_STRING_specs;
Lev Walkin's avatar
Lev Walkin committed
1754 1755
	ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);

Lev Walkin's avatar
Lev Walkin committed
1756 1757 1758 1759
	ASN_DEBUG("Freeing %s as OCTET STRING", td->name);

	if(st->buf) {
		FREEMEM(st->buf);
Lev Walkin's avatar
Lev Walkin committed
1760
		st->buf = 0;
Lev Walkin's avatar
Lev Walkin committed
1761 1762 1763 1764 1765
	}

	/*
	 * Remove decode-time stack.
	 */
Lev Walkin's avatar
Lev Walkin committed
1766
	stck = (struct _stack *)ctx->ptr;
Lev Walkin's avatar
Lev Walkin committed
1767 1768 1769 1770 1771 1772 1773 1774 1775
	if(stck) {
		while(stck->tail) {
			struct _stack_el *sel = stck->tail;
			stck->tail = sel->prev;
			FREEMEM(sel);
		}
		FREEMEM(stck);
	}

1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    switch(method) {
    case ASFM_FREE_EVERYTHING:
        FREEMEM(sptr);
        break;
    case ASFM_FREE_UNDERLYING:
        break;
    case ASFM_FREE_UNDERLYING_AND_RESET:
        memset(sptr, 0,
               ((asn_OCTET_STRING_specifics_t *)(td->specifics))->struct_size);
        break;
    }
Lev Walkin's avatar
Lev Walkin committed
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
}

/*
 * Conversion routines.
 */
int
OCTET_STRING_fromBuf(OCTET_STRING_t *st, const char *str, int len) {
	void *buf;

	if(st == 0 || (str == 0 && len)) {
		errno = EINVAL;
		return -1;
	}

	/*
	 * Clear the OCTET STRING.
	 */
	if(str == NULL) {
Lev Walkin's avatar
Lev Walkin committed
1805 1806
		FREEMEM(st->buf);
		st->buf = 0;
Lev Walkin's avatar
Lev Walkin committed
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
		st->size = 0;
		return 0;
	}

	/* Determine the original string size, if not explicitly given */
	if(len < 0)
		len = strlen(str);

	/* Allocate and fill the memory */
	buf = MALLOC(len + 1);
Lev Walkin's avatar
Lev Walkin committed
1817
	if(buf == NULL)
Lev Walkin's avatar
Lev Walkin committed
1818 1819 1820
		return -1;

	memcpy(buf, str, len);
Lev Walkin's avatar
Lev Walkin committed
1821 1822 1823 1824
	((uint8_t *)buf)[len] = '\0';	/* Couldn't use memcpy(len+1)! */
	FREEMEM(st->buf);
	st->buf = (uint8_t *)buf;
	st->size = len;
Lev Walkin's avatar
Lev Walkin committed
1825 1826 1827 1828 1829

	return 0;
}

OCTET_STRING_t *
1830 1831
OCTET_STRING_new_fromBuf(asn_TYPE_descriptor_t *td, const char *str, int len) {
	asn_OCTET_STRING_specifics_t *specs = td->specifics
Lev Walkin's avatar
Lev Walkin committed
1832
				? (asn_OCTET_STRING_specifics_t *)td->specifics
1833
				: &asn_SPC_OCTET_STRING_specs;
Lev Walkin's avatar
Lev Walkin committed
1834 1835
	OCTET_STRING_t *st;

1836
	st = (OCTET_STRING_t *)CALLOC(1, specs->struct_size);
Lev Walkin's avatar
Lev Walkin committed
1837
	if(st && str && OCTET_STRING_fromBuf(st, str, len)) {
Lev Walkin's avatar
Lev Walkin committed
1838
		FREEMEM(st);
Lev Walkin's avatar
Lev Walkin committed
1839 1840 1841 1842 1843 1844
		st = NULL;
	}

	return st;
}

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
/*
 * Lexicographically compare the common prefix of both strings,
 * and if it is the same return -1 for the smallest string.
 */
int
OCTET_STRING_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
                     const void *bptr) {
    const OCTET_STRING_t *a = aptr;
    const OCTET_STRING_t *b = bptr;

    (void)td;

    if(a && b) {
        size_t common_prefix_size = a->size <= b->size ? a->size : b->size;
        int ret = memcmp(a->buf, b->buf, common_prefix_size);
        if(ret == 0) {
            /* Figure out which string with equal prefixes is longer. */
            if(a->size < b->size) {
                return -1;
            } else if(a->size > b->size) {
                return 1;
            } else {
Lev Walkin's avatar
Lev Walkin committed
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
                asn_OCTET_STRING_specifics_t *specs = td->specifics;
                if(specs && specs->subvariant == ASN_OSUBV_BIT) {
                    const BIT_STRING_t *ba = aptr;
                    const BIT_STRING_t *bb = bptr;
                    if(ba->bits_unused > bb->bits_unused) {
                        return -1;
                    } else if(ba->bits_unused < bb->bits_unused) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
                return 0;
            }
        } else {
            return ret;
        }
    } else if(!a && !b) {
        return 0;
    } else if(!a) {
        return -1;
    } else {
        return 1;
    }

}