Moving in e2sim originally from it/test/simulators
[sim/e2-interface.git] / e2sim / ASN1c / OCTET_STRING.c
1 /*****************************************************************************
2 #                                                                            *
3 # Copyright 2019 AT&T Intellectual Property                                  *
4 #                                                                            *
5 # Licensed under the Apache License, Version 2.0 (the "License");            *
6 # you may not use this file except in compliance with the License.           *
7 # You may obtain a copy of the License at                                    *
8 #                                                                            *
9 #      http://www.apache.org/licenses/LICENSE-2.0                            *
10 #                                                                            *
11 # Unless required by applicable law or agreed to in writing, software        *
12 # distributed under the License is distributed on an "AS IS" BASIS,          *
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
14 # See the License for the specific language governing permissions and        *
15 # limitations under the License.                                             *
16 #                                                                            *
17 ******************************************************************************/
18
19 /*-
20  * Copyright (c) 2003-2017 Lev Walkin <vlm@lionet.info>.
21  * All rights reserved.
22  * Redistribution and modifications are permitted subject to BSD license.
23  */
24 #include <asn_internal.h>
25 #include <OCTET_STRING.h>
26 #include <BIT_STRING.h> /* for .bits_unused member */
27 #include <errno.h>
28
29 /*
30  * OCTET STRING basic type description.
31  */
32 static const ber_tlv_tag_t asn_DEF_OCTET_STRING_tags[] = {
33         (ASN_TAG_CLASS_UNIVERSAL | (4 << 2))
34 };
35 asn_OCTET_STRING_specifics_t asn_SPC_OCTET_STRING_specs = {
36         sizeof(OCTET_STRING_t),
37         offsetof(OCTET_STRING_t, _asn_ctx),
38         ASN_OSUBV_STR
39 };
40
41 asn_TYPE_operation_t asn_OP_OCTET_STRING = {
42         OCTET_STRING_free,
43         OCTET_STRING_print,     /* OCTET STRING generally means a non-ascii sequence */
44         OCTET_STRING_compare,
45         OCTET_STRING_decode_ber,
46         OCTET_STRING_encode_der,
47         OCTET_STRING_decode_xer_hex,
48         OCTET_STRING_encode_xer,
49 #ifdef  ASN_DISABLE_OER_SUPPORT
50         0,
51         0,
52 #else
53         OCTET_STRING_decode_oer,
54         OCTET_STRING_encode_oer,
55 #endif  /* ASN_DISABLE_OER_SUPPORT */
56 #ifdef  ASN_DISABLE_PER_SUPPORT
57         0,
58         0,
59         0,
60         0,
61 #else
62         OCTET_STRING_decode_uper,       /* Unaligned PER decoder */
63         OCTET_STRING_encode_uper,       /* Unaligned PER encoder */
64         OCTET_STRING_decode_aper,       /* Aligned PER decoder */
65         OCTET_STRING_encode_aper,       /* Aligned PER encoder */
66 #endif  /* ASN_DISABLE_PER_SUPPORT */
67         OCTET_STRING_random_fill,
68         0       /* Use generic outmost tag fetcher */
69 };
70 asn_TYPE_descriptor_t asn_DEF_OCTET_STRING = {
71         "OCTET STRING",         /* Canonical name */
72         "OCTET_STRING",         /* XML tag name */
73         &asn_OP_OCTET_STRING,
74         asn_DEF_OCTET_STRING_tags,
75         sizeof(asn_DEF_OCTET_STRING_tags)
76           / sizeof(asn_DEF_OCTET_STRING_tags[0]),
77         asn_DEF_OCTET_STRING_tags,      /* Same as above */
78         sizeof(asn_DEF_OCTET_STRING_tags)
79           / sizeof(asn_DEF_OCTET_STRING_tags[0]),
80         { 0, 0, asn_generic_no_constraint },
81         0, 0,   /* No members */
82         &asn_SPC_OCTET_STRING_specs
83 };
84
85 #undef  _CH_PHASE
86 #undef  NEXT_PHASE
87 #undef  PREV_PHASE
88 #define _CH_PHASE(ctx, inc) do {                                        \
89                 if(ctx->phase == 0)                                     \
90                         ctx->context = 0;                               \
91                 ctx->phase += inc;                                      \
92         } while(0)
93 #define NEXT_PHASE(ctx) _CH_PHASE(ctx, +1)
94 #define PREV_PHASE(ctx) _CH_PHASE(ctx, -1)
95
96 #undef  ADVANCE
97 #define ADVANCE(num_bytes)      do {                                    \
98                 size_t num = (num_bytes);                               \
99                 buf_ptr = ((const char *)buf_ptr) + num;                \
100                 size -= num;                                            \
101                 consumed_myself += num;                                 \
102         } while(0)
103
104 #undef  RETURN
105 #define RETURN(_code)   do {                                            \
106                 asn_dec_rval_t tmprval;                                 \
107                 tmprval.code = _code;                                   \
108                 tmprval.consumed = consumed_myself;                     \
109                 return tmprval;                                         \
110         } while(0)
111
112 #undef  APPEND
113 #define APPEND(bufptr, bufsize) do {                                    \
114                 size_t _bs = (bufsize);         /* Append size */       \
115                 size_t _ns = ctx->context;      /* Allocated now */     \
116                 size_t _es = st->size + _bs;    /* Expected size */     \
117                 /* int is really a typeof(st->size): */                 \
118                 if((int)_es < 0) RETURN(RC_FAIL);                       \
119                 if(_ns <= _es) {                                        \
120                         void *ptr;                                      \
121                         /* Be nice and round to the memory allocator */ \
122                         do { _ns = _ns ? _ns << 1 : 16; }               \
123                             while(_ns <= _es);                          \
124                         /* int is really a typeof(st->size): */         \
125                         if((int)_ns < 0) RETURN(RC_FAIL);               \
126                         ptr = REALLOC(st->buf, _ns);                    \
127                         if(ptr) {                                       \
128                                 st->buf = (uint8_t *)ptr;               \
129                                 ctx->context = _ns;                     \
130                         } else {                                        \
131                                 RETURN(RC_FAIL);                        \
132                         }                                               \
133                         ASN_DEBUG("Reallocating into %ld", (long)_ns);  \
134                 }                                                       \
135                 memcpy(st->buf + st->size, bufptr, _bs);                \
136                 /* Convenient nul-termination */                        \
137                 st->buf[_es] = '\0';                                    \
138                 st->size = _es;                                         \
139         } while(0)
140
141 /*
142  * The main reason why ASN.1 is still alive is that too much time and effort
143  * is necessary for learning it more or less adequately, thus creating a gut
144  * necessity to demonstrate that aquired skill everywhere afterwards.
145  * No, I am not going to explain what the following stuff is.
146  */
147 struct _stack_el {
148     ber_tlv_len_t left;     /* What's left to read (or -1) */
149     ber_tlv_len_t got;      /* What was actually processed */
150     unsigned cont_level;    /* Depth of subcontainment */
151     int want_nulls;         /* Want null "end of content" octets? */
152     int bits_chopped;       /* Flag in BIT STRING mode */
153     ber_tlv_tag_t tag;      /* For debugging purposes */
154     struct _stack_el *prev;
155     struct _stack_el *next;
156 };
157 struct _stack {
158         struct _stack_el *tail;
159         struct _stack_el *cur_ptr;
160 };
161
162 static struct _stack_el *
163 OS__add_stack_el(struct _stack *st) {
164         struct _stack_el *nel;
165
166         /*
167          * Reuse the old stack frame or allocate a new one.
168          */
169         if(st->cur_ptr && st->cur_ptr->next) {
170                 nel = st->cur_ptr->next;
171                 nel->bits_chopped = 0;
172                 nel->got = 0;
173                 /* Retain the nel->cont_level, it's correct. */
174         } else {
175                 nel = (struct _stack_el *)CALLOC(1, sizeof(struct _stack_el));
176                 if(nel == NULL)
177                         return NULL;
178         
179                 if(st->tail) {
180                         /* Increase a subcontainment depth */
181                         nel->cont_level = st->tail->cont_level + 1;
182                         st->tail->next = nel;
183                 }
184                 nel->prev = st->tail;
185                 st->tail = nel;
186         }
187
188         st->cur_ptr = nel;
189
190         return nel;
191 }
192
193 static struct _stack *
194 _new_stack(void) {
195         return (struct _stack *)CALLOC(1, sizeof(struct _stack));
196 }
197
198 /*
199  * Decode OCTET STRING type.
200  */
201 asn_dec_rval_t
202 OCTET_STRING_decode_ber(const asn_codec_ctx_t *opt_codec_ctx,
203                         const asn_TYPE_descriptor_t *td, void **sptr,
204                         const void *buf_ptr, size_t size, int tag_mode) {
205     const asn_OCTET_STRING_specifics_t *specs = td->specifics
206                                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
207                                 : &asn_SPC_OCTET_STRING_specs;
208         BIT_STRING_t *st = (BIT_STRING_t *)*sptr;
209         asn_dec_rval_t rval;
210         asn_struct_ctx_t *ctx;
211         ssize_t consumed_myself = 0;
212         struct _stack *stck;            /* Expectations stack structure */
213         struct _stack_el *sel = 0;      /* Stack element */
214         int tlv_constr;
215         enum asn_OS_Subvariant type_variant = specs->subvariant;
216
217         ASN_DEBUG("Decoding %s as %s (frame %ld)",
218                 td->name,
219                 (type_variant == ASN_OSUBV_STR) ?
220                         "OCTET STRING" : "OS-SpecialCase",
221                 (long)size);
222
223         /*
224          * Create the string if does not exist.
225          */
226         if(st == NULL) {
227                 st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
228                 if(st == NULL) RETURN(RC_FAIL);
229         }
230
231         /* Restore parsing context */
232         ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
233
234         switch(ctx->phase) {
235         case 0:
236                 /*
237                  * Check tags.
238                  */
239                 rval = ber_check_tags(opt_codec_ctx, td, ctx,
240                         buf_ptr, size, tag_mode, -1,
241                         &ctx->left, &tlv_constr);
242                 if(rval.code != RC_OK)
243                         return rval;
244
245                 if(tlv_constr) {
246                         /*
247                          * Complex operation, requires stack of expectations.
248                          */
249                         ctx->ptr = _new_stack();
250                         if(!ctx->ptr) {
251                                 RETURN(RC_FAIL);
252                         }
253                 } else {
254                         /*
255                          * Jump into stackless primitive decoding.
256                          */
257                         _CH_PHASE(ctx, 3);
258                         if(type_variant == ASN_OSUBV_ANY && tag_mode != 1)
259                                 APPEND(buf_ptr, rval.consumed);
260                         ADVANCE(rval.consumed);
261                         goto phase3;
262                 }
263
264                 NEXT_PHASE(ctx);
265                 /* Fall through */
266         case 1:
267         phase1:
268                 /*
269                  * Fill the stack with expectations.
270                  */
271                 stck = (struct _stack *)ctx->ptr;
272                 sel = stck->cur_ptr;
273           do {
274                 ber_tlv_tag_t tlv_tag;
275                 ber_tlv_len_t tlv_len;
276                 ber_tlv_tag_t expected_tag;
277                 ssize_t tl, ll, tlvl;
278                                 /* This one works even if (sel->left == -1) */
279                 size_t Left = ((!sel||(size_t)sel->left >= size)
280                                         ?size:(size_t)sel->left);
281
282
283                 ASN_DEBUG("%p, s->l=%ld, s->wn=%ld, s->g=%ld\n", (void *)sel,
284                         (long)(sel?sel->left:0),
285                         (long)(sel?sel->want_nulls:0),
286                         (long)(sel?sel->got:0)
287                 );
288                 if(sel && sel->left <= 0 && sel->want_nulls == 0) {
289                         if(sel->prev) {
290                                 struct _stack_el *prev = sel->prev;
291                                 if(prev->left != -1) {
292                                         if(prev->left < sel->got)
293                                                 RETURN(RC_FAIL);
294                                         prev->left -= sel->got;
295                                 }
296                                 prev->got += sel->got;
297                                 sel = stck->cur_ptr = prev;
298                                 if(!sel) break;
299                                 tlv_constr = 1;
300                                 continue;
301                         } else {
302                                 sel = stck->cur_ptr = 0;
303                                 break;  /* Nothing to wait */
304                         }
305                 }
306
307                 tl = ber_fetch_tag(buf_ptr, Left, &tlv_tag);
308                 ASN_DEBUG("fetch tag(size=%ld,L=%ld), %sstack, left=%ld, wn=%ld, tl=%ld",
309                         (long)size, (long)Left, sel?"":"!",
310                         (long)(sel?sel->left:0),
311                         (long)(sel?sel->want_nulls:0),
312                         (long)tl);
313                 switch(tl) {
314                 case -1: RETURN(RC_FAIL);
315                 case 0: RETURN(RC_WMORE);
316                 }
317
318                 tlv_constr = BER_TLV_CONSTRUCTED(buf_ptr);
319
320                 ll = ber_fetch_length(tlv_constr,
321                                 (const char *)buf_ptr + tl,Left - tl,&tlv_len);
322                 ASN_DEBUG("Got tag=%s, tc=%d, left=%ld, tl=%ld, len=%ld, ll=%ld",
323                         ber_tlv_tag_string(tlv_tag), tlv_constr,
324                                 (long)Left, (long)tl, (long)tlv_len, (long)ll);
325                 switch(ll) {
326                 case -1: RETURN(RC_FAIL);
327                 case 0: RETURN(RC_WMORE);
328                 }
329
330                 if(sel && sel->want_nulls
331                         && ((const uint8_t *)buf_ptr)[0] == 0
332                         && ((const uint8_t *)buf_ptr)[1] == 0)
333                 {
334
335                         ASN_DEBUG("Eat EOC; wn=%d--", sel->want_nulls);
336
337                         if(type_variant == ASN_OSUBV_ANY
338                         && (tag_mode != 1 || sel->cont_level))
339                                 APPEND("\0\0", 2);
340
341                         ADVANCE(2);
342                         sel->got += 2;
343                         if(sel->left != -1) {
344                                 sel->left -= 2; /* assert(sel->left >= 2) */
345                         }
346
347                         sel->want_nulls--;
348                         if(sel->want_nulls == 0) {
349                                 /* Move to the next expectation */
350                                 sel->left = 0;
351                                 tlv_constr = 1;
352                         }
353
354                         continue;
355                 }
356
357                 /*
358                  * Set up expected tags,
359                  * depending on ASN.1 type being decoded.
360                  */
361                 switch(type_variant) {
362                 case ASN_OSUBV_BIT:
363                         /* X.690: 8.6.4.1, NOTE 2 */
364                         /* Fall through */
365                 case ASN_OSUBV_STR:
366                 default:
367                         if(sel) {
368                                 unsigned level = sel->cont_level;
369                                 if(level < td->all_tags_count) {
370                                         expected_tag = td->all_tags[level];
371                                         break;
372                                 } else if(td->all_tags_count) {
373                                         expected_tag = td->all_tags
374                                                 [td->all_tags_count - 1];
375                                         break;
376                                 }
377                                 /* else, Fall through */
378                         }
379                         /* Fall through */
380                 case ASN_OSUBV_ANY:
381                         expected_tag = tlv_tag;
382                         break;
383                 }
384
385
386                 if(tlv_tag != expected_tag) {
387                         char buf[2][32];
388                         ber_tlv_tag_snprint(tlv_tag,
389                                 buf[0], sizeof(buf[0]));
390                         ber_tlv_tag_snprint(td->tags[td->tags_count-1],
391                                 buf[1], sizeof(buf[1]));
392                         ASN_DEBUG("Tag does not match expectation: %s != %s",
393                                 buf[0], buf[1]);
394                         RETURN(RC_FAIL);
395                 }
396
397                 tlvl = tl + ll; /* Combined length of T and L encoding */
398                 if((tlv_len + tlvl) < 0) {
399                         /* tlv_len value is too big */
400                         ASN_DEBUG("TLV encoding + length (%ld) is too big",
401                                 (long)tlv_len);
402                         RETURN(RC_FAIL);
403                 }
404
405                 /*
406                  * Append a new expectation.
407                  */
408                 sel = OS__add_stack_el(stck);
409                 if(!sel) RETURN(RC_FAIL);
410
411                 sel->tag = tlv_tag;
412
413                 sel->want_nulls = (tlv_len==-1);
414                 if(sel->prev && sel->prev->left != -1) {
415                         /* Check that the parent frame is big enough */
416                         if(sel->prev->left < tlvl + (tlv_len==-1?0:tlv_len))
417                                 RETURN(RC_FAIL);
418                         if(tlv_len == -1)
419                                 sel->left = sel->prev->left - tlvl;
420                         else
421                                 sel->left = tlv_len;
422                 } else {
423                         sel->left = tlv_len;
424                 }
425                 if(type_variant == ASN_OSUBV_ANY
426                 && (tag_mode != 1 || sel->cont_level))
427                         APPEND(buf_ptr, tlvl);
428                 sel->got += tlvl;
429                 ADVANCE(tlvl);
430
431                 ASN_DEBUG("+EXPECT2 got=%ld left=%ld, wn=%d, clvl=%u",
432                         (long)sel->got, (long)sel->left,
433                         sel->want_nulls, sel->cont_level);
434
435           } while(tlv_constr);
436                 if(sel == NULL) {
437                         /* Finished operation, "phase out" */
438                         ASN_DEBUG("Phase out");
439                         _CH_PHASE(ctx, +3);
440                         break;
441                 }
442
443                 NEXT_PHASE(ctx);
444                 /* Fall through */
445         case 2:
446                 stck = (struct _stack *)ctx->ptr;
447                 sel = stck->cur_ptr;
448                 ASN_DEBUG("Phase 2: Need %ld bytes, size=%ld, alrg=%ld, wn=%d",
449                         (long)sel->left, (long)size, (long)sel->got,
450                                 sel->want_nulls);
451             {
452                 ber_tlv_len_t len;
453
454                 assert(sel->left >= 0);
455
456                 len = ((ber_tlv_len_t)size < sel->left)
457                                 ? (ber_tlv_len_t)size : sel->left;
458                 if(len > 0) {
459                         if(type_variant == ASN_OSUBV_BIT
460                         && sel->bits_chopped == 0) {
461                                 /* Put the unused-bits-octet away */
462                                 st->bits_unused = *(const uint8_t *)buf_ptr;
463                                 APPEND(((const char *)buf_ptr+1), (len - 1));
464                                 sel->bits_chopped = 1;
465                         } else {
466                                 APPEND(buf_ptr, len);
467                         }
468                         ADVANCE(len);
469                         sel->left -= len;
470                         sel->got += len;
471                 }
472
473                 if(sel->left) {
474                         ASN_DEBUG("OS left %ld, size = %ld, wn=%d\n",
475                                 (long)sel->left, (long)size, sel->want_nulls);
476                         RETURN(RC_WMORE);
477                 }
478
479                 PREV_PHASE(ctx);
480                 goto phase1;
481             }
482                 break;
483         case 3:
484         phase3:
485                 /*
486                  * Primitive form, no stack required.
487                  */
488                 assert(ctx->left >= 0);
489
490                 if(size < (size_t)ctx->left) {
491                         if(!size) RETURN(RC_WMORE);
492                         if(type_variant == ASN_OSUBV_BIT && !ctx->context) {
493                                 st->bits_unused = *(const uint8_t *)buf_ptr;
494                                 ctx->left--;
495                                 ADVANCE(1);
496                         }
497                         APPEND(buf_ptr, size);
498                         assert(ctx->context > 0);
499                         ctx->left -= size;
500                         ADVANCE(size);
501                         RETURN(RC_WMORE);
502                 } else {
503                         if(type_variant == ASN_OSUBV_BIT
504                         && !ctx->context && ctx->left) {
505                                 st->bits_unused = *(const uint8_t *)buf_ptr;
506                                 ctx->left--;
507                                 ADVANCE(1);
508                         }
509                         APPEND(buf_ptr, ctx->left);
510                         ADVANCE(ctx->left);
511                         ctx->left = 0;
512
513                         NEXT_PHASE(ctx);
514                 }
515                 break;
516         }
517
518         if(sel) {
519                 ASN_DEBUG("3sel p=%p, wn=%d, l=%ld, g=%ld, size=%ld",
520                         (void *)sel->prev, sel->want_nulls,
521                         (long)sel->left, (long)sel->got, (long)size);
522                 if(sel->prev || sel->want_nulls > 1 || sel->left > 0) {
523                         RETURN(RC_WMORE);
524                 }
525         }
526
527         /*
528          * BIT STRING-specific processing.
529          */
530         if(type_variant == ASN_OSUBV_BIT) {
531         if(st->size) {
532                         if(st->bits_unused < 0 || st->bits_unused > 7) {
533                                 RETURN(RC_FAIL);
534                         }
535                         /* Finalize BIT STRING: zero out unused bits. */
536                         st->buf[st->size-1] &= 0xff << st->bits_unused;
537                 } else {
538                         if(st->bits_unused) {
539                                 RETURN(RC_FAIL);
540                         }
541                 }
542         }
543
544         ASN_DEBUG("Took %ld bytes to encode %s: [%s]:%ld",
545                 (long)consumed_myself, td->name,
546                 (type_variant == ASN_OSUBV_STR) ? (char *)st->buf : "<data>",
547                 (long)st->size);
548
549
550         RETURN(RC_OK);
551 }
552
553 /*
554  * Encode OCTET STRING type using DER.
555  */
556 asn_enc_rval_t
557 OCTET_STRING_encode_der(const asn_TYPE_descriptor_t *td, const void *sptr,
558                         int tag_mode, ber_tlv_tag_t tag,
559                         asn_app_consume_bytes_f *cb, void *app_key) {
560     asn_enc_rval_t er = { 0, 0, 0 };
561         const asn_OCTET_STRING_specifics_t *specs = td->specifics
562                                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
563                                 : &asn_SPC_OCTET_STRING_specs;
564         const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
565         enum asn_OS_Subvariant type_variant = specs->subvariant;
566         int fix_last_byte = 0;
567
568         ASN_DEBUG("%s %s as OCTET STRING",
569                 cb?"Estimating":"Encoding", td->name);
570
571         /*
572          * Write tags.
573          */
574         if(type_variant != ASN_OSUBV_ANY || tag_mode == 1) {
575                 er.encoded = der_write_tags(td,
576                                 (type_variant == ASN_OSUBV_BIT) + st->size,
577                         tag_mode, type_variant == ASN_OSUBV_ANY, tag,
578                         cb, app_key);
579                 if(er.encoded == -1) {
580                         er.failed_type = td;
581                         er.structure_ptr = sptr;
582                         return er;
583                 }
584         } else {
585                 /* Disallow: [<tag>] IMPLICIT ANY */
586                 assert(type_variant != ASN_OSUBV_ANY || tag_mode != -1);
587                 er.encoded = 0;
588         }
589
590         if(!cb) {
591                 er.encoded += (type_variant == ASN_OSUBV_BIT) + st->size;
592                 ASN__ENCODED_OK(er);
593         }
594
595         /*
596          * Prepare to deal with the last octet of BIT STRING.
597          */
598         if(type_variant == ASN_OSUBV_BIT) {
599                 uint8_t b = st->bits_unused & 0x07;
600                 if(b && st->size) fix_last_byte = 1;
601                 ASN__CALLBACK(&b, 1);
602         }
603
604         /* Invoke callback for the main part of the buffer */
605         ASN__CALLBACK(st->buf, st->size - fix_last_byte);
606
607         /* The last octet should be stripped off the unused bits */
608         if(fix_last_byte) {
609                 uint8_t b = st->buf[st->size-1] & (0xff << st->bits_unused);
610                 ASN__CALLBACK(&b, 1);
611         }
612
613         ASN__ENCODED_OK(er);
614 cb_failed:
615         ASN__ENCODE_FAILED;
616 }
617
618 asn_enc_rval_t
619 OCTET_STRING_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr,
620                         int ilevel, enum xer_encoder_flags_e flags,
621                         asn_app_consume_bytes_f *cb, void *app_key) {
622     const char * const h2c = "0123456789ABCDEF";
623         const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
624         asn_enc_rval_t er = { 0, 0, 0 };
625         char scratch[16 * 3 + 4];
626         char *p = scratch;
627         uint8_t *buf;
628         uint8_t *end;
629         size_t i;
630
631         if(!st || (!st->buf && st->size))
632                 ASN__ENCODE_FAILED;
633
634         er.encoded = 0;
635
636         /*
637          * Dump the contents of the buffer in hexadecimal.
638          */
639         buf = st->buf;
640         end = buf + st->size;
641         if(flags & XER_F_CANONICAL) {
642                 char *scend = scratch + (sizeof(scratch) - 2);
643                 for(; buf < end; buf++) {
644                         if(p >= scend) {
645                                 ASN__CALLBACK(scratch, p - scratch);
646                                 p = scratch;
647                         }
648                         *p++ = h2c[(*buf >> 4) & 0x0F];
649                         *p++ = h2c[*buf & 0x0F];
650                 }
651
652                 ASN__CALLBACK(scratch, p-scratch);      /* Dump the rest */
653         } else {
654                 for(i = 0; buf < end; buf++, i++) {
655                         if(!(i % 16) && (i || st->size > 16)) {
656                                 ASN__CALLBACK(scratch, p-scratch);
657                                 p = scratch;
658                                 ASN__TEXT_INDENT(1, ilevel);
659                         }
660                         *p++ = h2c[(*buf >> 4) & 0x0F];
661                         *p++ = h2c[*buf & 0x0F];
662                         *p++ = 0x20;
663                 }
664                 if(p - scratch) {
665                         p--;    /* Remove the tail space */
666                         ASN__CALLBACK(scratch, p-scratch); /* Dump the rest */
667                         if(st->size > 16)
668                                 ASN__TEXT_INDENT(1, ilevel-1);
669                 }
670         }
671
672         ASN__ENCODED_OK(er);
673 cb_failed:
674         ASN__ENCODE_FAILED;
675 }
676
677 static const struct OCTET_STRING__xer_escape_table_s {
678         const char *string;
679         int size;
680 } OCTET_STRING__xer_escape_table[] = {
681 #define OSXET(s)        { s, sizeof(s) - 1 }
682         OSXET("\074\156\165\154\057\076"),      /* <nul/> */
683         OSXET("\074\163\157\150\057\076"),      /* <soh/> */
684         OSXET("\074\163\164\170\057\076"),      /* <stx/> */
685         OSXET("\074\145\164\170\057\076"),      /* <etx/> */
686         OSXET("\074\145\157\164\057\076"),      /* <eot/> */
687         OSXET("\074\145\156\161\057\076"),      /* <enq/> */
688         OSXET("\074\141\143\153\057\076"),      /* <ack/> */
689         OSXET("\074\142\145\154\057\076"),      /* <bel/> */
690         OSXET("\074\142\163\057\076"),          /* <bs/> */
691         OSXET("\011"),                          /* \t */
692         OSXET("\012"),                          /* \n */
693         OSXET("\074\166\164\057\076"),          /* <vt/> */
694         OSXET("\074\146\146\057\076"),          /* <ff/> */
695         OSXET("\015"),                          /* \r */
696         OSXET("\074\163\157\057\076"),          /* <so/> */
697         OSXET("\074\163\151\057\076"),          /* <si/> */
698         OSXET("\074\144\154\145\057\076"),      /* <dle/> */
699         OSXET("\074\144\143\061\057\076"),      /* <de1/> */
700         OSXET("\074\144\143\062\057\076"),      /* <de2/> */
701         OSXET("\074\144\143\063\057\076"),      /* <de3/> */
702         OSXET("\074\144\143\064\057\076"),      /* <de4/> */
703         OSXET("\074\156\141\153\057\076"),      /* <nak/> */
704         OSXET("\074\163\171\156\057\076"),      /* <syn/> */
705         OSXET("\074\145\164\142\057\076"),      /* <etb/> */
706         OSXET("\074\143\141\156\057\076"),      /* <can/> */
707         OSXET("\074\145\155\057\076"),          /* <em/> */
708         OSXET("\074\163\165\142\057\076"),      /* <sub/> */
709         OSXET("\074\145\163\143\057\076"),      /* <esc/> */
710         OSXET("\074\151\163\064\057\076"),      /* <is4/> */
711         OSXET("\074\151\163\063\057\076"),      /* <is3/> */
712         OSXET("\074\151\163\062\057\076"),      /* <is2/> */
713         OSXET("\074\151\163\061\057\076"),      /* <is1/> */
714         { 0, 0 },       /* " " */
715         { 0, 0 },       /* ! */
716         { 0, 0 },       /* \" */
717         { 0, 0 },       /* # */
718         { 0, 0 },       /* $ */
719         { 0, 0 },       /* % */
720         OSXET("\046\141\155\160\073"),  /* &amp; */
721         { 0, 0 },       /* ' */
722         {0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, /* ()*+,-./ */
723         {0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, /* 01234567 */
724         {0,0},{0,0},{0,0},{0,0},                         /* 89:; */
725         OSXET("\046\154\164\073"),      /* &lt; */
726         { 0, 0 },       /* = */
727         OSXET("\046\147\164\073"),      /* &gt; */
728 };
729
730 static int
731 OS__check_escaped_control_char(const void *buf, int size) {
732         size_t i;
733         /*
734          * Inefficient algorithm which translates the escape sequences
735          * defined above into characters. Returns -1 if not found.
736          * TODO: replace by a faster algorithm (bsearch(), hash or
737          * nested table lookups).
738          */
739         for(i = 0; i < 32 /* Don't spend time on the bottom half */; i++) {
740                 const struct OCTET_STRING__xer_escape_table_s *el;
741                 el = &OCTET_STRING__xer_escape_table[i];
742                 if(el->size == size && memcmp(buf, el->string, size) == 0)
743                         return i;
744         }
745         return -1;
746 }
747
748 static int
749 OCTET_STRING__handle_control_chars(void *struct_ptr, const void *chunk_buf, size_t chunk_size) {
750         /*
751          * This might be one of the escape sequences
752          * for control characters. Check it out.
753          * #11.15.5
754          */
755         int control_char = OS__check_escaped_control_char(chunk_buf,chunk_size);
756         if(control_char >= 0) {
757                 OCTET_STRING_t *st = (OCTET_STRING_t *)struct_ptr;
758                 void *p = REALLOC(st->buf, st->size + 2);
759                 if(p) {
760                         st->buf = (uint8_t *)p;
761                         st->buf[st->size++] = control_char;
762                         st->buf[st->size] = '\0';       /* nul-termination */
763                         return 0;
764                 }
765         }
766         
767         return -1;      /* No, it's not */
768 }
769
770 asn_enc_rval_t
771 OCTET_STRING_encode_xer_utf8(const asn_TYPE_descriptor_t *td, const void *sptr,
772                              int ilevel, enum xer_encoder_flags_e flags,
773                              asn_app_consume_bytes_f *cb, void *app_key) {
774         const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
775         asn_enc_rval_t er = { 0, 0, 0 };
776         uint8_t *buf, *end;
777         uint8_t *ss;    /* Sequence start */
778         ssize_t encoded_len = 0;
779
780         (void)ilevel;   /* Unused argument */
781         (void)flags;    /* Unused argument */
782
783         if(!st || (!st->buf && st->size))
784                 ASN__ENCODE_FAILED;
785
786         buf = st->buf;
787         end = buf + st->size;
788         for(ss = buf; buf < end; buf++) {
789                 unsigned int ch = *buf;
790                 int s_len;      /* Special encoding sequence length */
791
792                 /*
793                  * Escape certain characters: X.680/11.15
794                  */
795                 if(ch < sizeof(OCTET_STRING__xer_escape_table)
796                         /sizeof(OCTET_STRING__xer_escape_table[0])
797                 && (s_len = OCTET_STRING__xer_escape_table[ch].size)) {
798                         if(((buf - ss) && cb(ss, buf - ss, app_key) < 0)
799                         || cb(OCTET_STRING__xer_escape_table[ch].string, s_len,
800                                         app_key) < 0)
801                                 ASN__ENCODE_FAILED;
802                         encoded_len += (buf - ss) + s_len;
803                         ss = buf + 1;
804                 }
805         }
806
807         encoded_len += (buf - ss);
808         if((buf - ss) && cb(ss, buf - ss, app_key) < 0)
809                 ASN__ENCODE_FAILED;
810
811         er.encoded = encoded_len;
812         ASN__ENCODED_OK(er);
813 }
814
815 /*
816  * Convert from hexadecimal format (cstring): "AB CD EF"
817  */
818 static ssize_t OCTET_STRING__convert_hexadecimal(void *sptr, const void *chunk_buf, size_t chunk_size, int have_more) {
819         OCTET_STRING_t *st = (OCTET_STRING_t *)sptr;
820         const char *chunk_stop = (const char *)chunk_buf;
821         const char *p = chunk_stop;
822         const char *pend = p + chunk_size;
823         unsigned int clv = 0;
824         int half = 0;   /* Half bit */
825         uint8_t *buf;
826
827         /* Reallocate buffer according to high cap estimation */
828         size_t new_size = st->size + (chunk_size + 1) / 2;
829         void *nptr = REALLOC(st->buf, new_size + 1);
830         if(!nptr) return -1;
831         st->buf = (uint8_t *)nptr;
832         buf = st->buf + st->size;
833
834         /*
835          * If something like " a b c " appears here, the " a b":3 will be
836          * converted, and the rest skipped. That is, unless buf_size is greater
837          * than chunk_size, then it'll be equivalent to "ABC0".
838          */
839         for(; p < pend; p++) {
840                 int ch = *(const unsigned char *)p;
841                 switch(ch) {
842                 case 0x09: case 0x0a: case 0x0c: case 0x0d:
843                 case 0x20:
844                         /* Ignore whitespace */
845                         continue;
846                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: /*01234*/
847                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: /*56789*/
848                         clv = (clv << 4) + (ch - 0x30);
849                         break;
850                 case 0x41: case 0x42: case 0x43:        /* ABC */
851                 case 0x44: case 0x45: case 0x46:        /* DEF */
852                         clv = (clv << 4) + (ch - 0x41 + 10);
853                         break;
854                 case 0x61: case 0x62: case 0x63:        /* abc */
855                 case 0x64: case 0x65: case 0x66:        /* def */
856                         clv = (clv << 4) + (ch - 0x61 + 10);
857                         break;
858                 default:
859                         *buf = 0;       /* JIC */
860                         return -1;
861                 }
862                 if(half++) {
863                         half = 0;
864                         *buf++ = clv;
865                         chunk_stop = p + 1;
866                 }
867         }
868
869         /*
870          * Check partial decoding.
871          */
872         if(half) {
873                 if(have_more) {
874                         /*
875                          * Partial specification is fine,
876                          * because no more more PXER_TEXT data is available.
877                          */
878                         *buf++ = clv << 4;
879                         chunk_stop = p;
880                 }
881         } else {
882                 chunk_stop = p;
883         }
884
885         st->size = buf - st->buf;       /* Adjust the buffer size */
886         assert(st->size <= new_size);
887         st->buf[st->size] = 0;          /* Courtesy termination */
888
889         return (chunk_stop - (const char *)chunk_buf);  /* Converted size */
890 }
891
892 /*
893  * Convert from binary format: "00101011101"
894  */
895 static ssize_t OCTET_STRING__convert_binary(void *sptr, const void *chunk_buf, size_t chunk_size, int have_more) {
896         BIT_STRING_t *st = (BIT_STRING_t *)sptr;
897         const char *p = (const char *)chunk_buf;
898         const char *pend = p + chunk_size;
899         int bits_unused = st->bits_unused & 0x7;
900         uint8_t *buf;
901
902         /* Reallocate buffer according to high cap estimation */
903         size_t new_size = st->size + (chunk_size + 7) / 8;
904         void *nptr = REALLOC(st->buf, new_size + 1);
905         if(!nptr) return -1;
906         st->buf = (uint8_t *)nptr;
907         buf = st->buf + st->size;
908
909         (void)have_more;
910
911         if(bits_unused == 0)
912                 bits_unused = 8;
913         else if(st->size)
914                 buf--;
915
916         /*
917          * Convert series of 0 and 1 into the octet string.
918          */
919         for(; p < pend; p++) {
920                 int ch = *(const unsigned char *)p;
921                 switch(ch) {
922                 case 0x09: case 0x0a: case 0x0c: case 0x0d:
923                 case 0x20:
924                         /* Ignore whitespace */
925                         break;
926                 case 0x30:
927                 case 0x31:
928                         if(bits_unused-- <= 0) {
929                                 *++buf = 0;     /* Clean the cell */
930                                 bits_unused = 7;
931                         }
932                         *buf |= (ch&1) << bits_unused;
933                         break;
934                 default:
935                         st->bits_unused = bits_unused;
936                         return -1;
937                 }
938         }
939
940         if(bits_unused == 8) {
941                 st->size = buf - st->buf;
942                 st->bits_unused = 0;
943         } else {
944                 st->size = buf - st->buf + 1;
945                 st->bits_unused = bits_unused;
946         }
947
948         assert(st->size <= new_size);
949         st->buf[st->size] = 0;          /* Courtesy termination */
950
951         return chunk_size;      /* Converted in full */
952 }
953
954 /*
955  * Something like strtod(), but with stricter rules.
956  */
957 static int
958 OS__strtoent(int base, const char *buf, const char *end, int32_t *ret_value) {
959         const int32_t last_unicode_codepoint = 0x10ffff;
960         int32_t val = 0;
961         const char *p;
962
963         for(p = buf; p < end; p++) {
964                 int ch = *p;
965
966                 switch(ch) {
967                 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: /*01234*/
968                 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: /*56789*/
969                         val = val * base + (ch - 0x30);
970                         break;
971                 case 0x41: case 0x42: case 0x43:        /* ABC */
972                 case 0x44: case 0x45: case 0x46:        /* DEF */
973                         val = val * base + (ch - 0x41 + 10);
974                         break;
975                 case 0x61: case 0x62: case 0x63:        /* abc */
976                 case 0x64: case 0x65: case 0x66:        /* def */
977                         val = val * base + (ch - 0x61 + 10);
978                         break;
979                 case 0x3b:      /* ';' */
980                         *ret_value = val;
981                         return (p - buf) + 1;
982                 default:
983                         return -1;      /* Character set error */
984                 }
985
986                 /* Value exceeds the Unicode range. */
987                 if(val > last_unicode_codepoint) {
988                         return -1;
989                 }
990         }
991
992         *ret_value = -1;
993         return (p - buf);
994 }
995
996 /*
997  * Convert from the plain UTF-8 format, expanding entity references: "2 &lt; 3"
998  */
999 static ssize_t
1000 OCTET_STRING__convert_entrefs(void *sptr, const void *chunk_buf,
1001                               size_t chunk_size, int have_more) {
1002     OCTET_STRING_t *st = (OCTET_STRING_t *)sptr;
1003         const char *p = (const char *)chunk_buf;
1004         const char *pend = p + chunk_size;
1005         uint8_t *buf;
1006
1007         /* Reallocate buffer */
1008         size_t new_size = st->size + chunk_size;
1009         void *nptr = REALLOC(st->buf, new_size + 1);
1010         if(!nptr) return -1;
1011         st->buf = (uint8_t *)nptr;
1012         buf = st->buf + st->size;
1013
1014         /*
1015          * Convert series of 0 and 1 into the octet string.
1016          */
1017         for(; p < pend; p++) {
1018                 int ch = *(const unsigned char *)p;
1019                 int len;        /* Length of the rest of the chunk */
1020
1021                 if(ch != 0x26 /* '&' */) {
1022                         *buf++ = ch;
1023                         continue;       /* That was easy... */
1024                 }
1025
1026                 /*
1027                  * Process entity reference.
1028                  */
1029                 len = chunk_size - (p - (const char *)chunk_buf);
1030                 if(len == 1 /* "&" */) goto want_more;
1031                 if(p[1] == 0x23 /* '#' */) {
1032                         const char *pval;       /* Pointer to start of digits */
1033                         int32_t val = 0;        /* Entity reference value */
1034                         int base;
1035
1036                         if(len == 2 /* "&#" */) goto want_more;
1037                         if(p[2] == 0x78 /* 'x' */)
1038                                 pval = p + 3, base = 16;
1039                         else
1040                                 pval = p + 2, base = 10;
1041                         len = OS__strtoent(base, pval, p + len, &val);
1042                         if(len == -1) {
1043                                 /* Invalid charset. Just copy verbatim. */
1044                                 *buf++ = ch;
1045                                 continue;
1046                         }
1047                         if(!len || pval[len-1] != 0x3b) goto want_more;
1048                         assert(val > 0);
1049                         p += (pval - p) + len - 1; /* Advance past entref */
1050
1051                         if(val < 0x80) {
1052                                 *buf++ = (char)val;
1053                         } else if(val < 0x800) {
1054                                 *buf++ = 0xc0 | ((val >> 6));
1055                                 *buf++ = 0x80 | ((val & 0x3f));
1056                         } else if(val < 0x10000) {
1057                                 *buf++ = 0xe0 | ((val >> 12));
1058                                 *buf++ = 0x80 | ((val >> 6) & 0x3f);
1059                                 *buf++ = 0x80 | ((val & 0x3f));
1060                         } else if(val < 0x200000) {
1061                                 *buf++ = 0xf0 | ((val >> 18));
1062                                 *buf++ = 0x80 | ((val >> 12) & 0x3f);
1063                                 *buf++ = 0x80 | ((val >> 6) & 0x3f);
1064                                 *buf++ = 0x80 | ((val & 0x3f));
1065                         } else if(val < 0x4000000) {
1066                                 *buf++ = 0xf8 | ((val >> 24));
1067                                 *buf++ = 0x80 | ((val >> 18) & 0x3f);
1068                                 *buf++ = 0x80 | ((val >> 12) & 0x3f);
1069                                 *buf++ = 0x80 | ((val >> 6) & 0x3f);
1070                                 *buf++ = 0x80 | ((val & 0x3f));
1071                         } else {
1072                                 *buf++ = 0xfc | ((val >> 30) & 0x1);
1073                                 *buf++ = 0x80 | ((val >> 24) & 0x3f);
1074                                 *buf++ = 0x80 | ((val >> 18) & 0x3f);
1075                                 *buf++ = 0x80 | ((val >> 12) & 0x3f);
1076                                 *buf++ = 0x80 | ((val >> 6) & 0x3f);
1077                                 *buf++ = 0x80 | ((val & 0x3f));
1078                         }
1079                 } else {
1080                         /*
1081                          * Ugly, limited parsing of &amp; &gt; &lt;
1082                          */
1083                         char *sc = (char *)memchr(p, 0x3b, len > 5 ? 5 : len);
1084                         if(!sc) goto want_more;
1085                         if((sc - p) == 4
1086                                 && p[1] == 0x61 /* 'a' */
1087                                 && p[2] == 0x6d /* 'm' */
1088                                 && p[3] == 0x70 /* 'p' */) {
1089                                 *buf++ = 0x26;
1090                                 p = sc;
1091                                 continue;
1092                         }
1093                         if((sc - p) == 3) {
1094                                 if(p[1] == 0x6c) {
1095                                         *buf = 0x3c;    /* '<' */
1096                                 } else if(p[1] == 0x67) {
1097                                         *buf = 0x3e;    /* '>' */
1098                                 } else {
1099                                         /* Unsupported entity reference */
1100                                         *buf++ = ch;
1101                                         continue;
1102                                 }
1103                                 if(p[2] != 0x74) {
1104                                         /* Unsupported entity reference */
1105                                         *buf++ = ch;
1106                                         continue;
1107                                 }
1108                                 buf++;
1109                                 p = sc;
1110                                 continue;
1111                         }
1112                         /* Unsupported entity reference */
1113                         *buf++ = ch;
1114                 }
1115
1116                 continue;
1117         want_more:
1118                 if(have_more) {
1119                         /*
1120                          * We know that no more data (of the same type)
1121                          * is coming. Copy the rest verbatim.
1122                          */
1123                         *buf++ = ch;
1124                         continue;
1125                 }
1126                 chunk_size = (p - (const char *)chunk_buf);
1127                 /* Processing stalled: need more data */
1128                 break;
1129         }
1130
1131         st->size = buf - st->buf;
1132         assert(st->size <= new_size);
1133         st->buf[st->size] = 0;          /* Courtesy termination */
1134
1135         return chunk_size;      /* Converted in full */
1136 }
1137
1138 /*
1139  * Decode OCTET STRING from the XML element's body.
1140  */
1141 static asn_dec_rval_t
1142 OCTET_STRING__decode_xer(
1143     const asn_codec_ctx_t *opt_codec_ctx, const asn_TYPE_descriptor_t *td,
1144     void **sptr, const char *opt_mname, const void *buf_ptr, size_t size,
1145     int (*opt_unexpected_tag_decoder)(void *struct_ptr, const void *chunk_buf,
1146                                       size_t chunk_size),
1147     ssize_t (*body_receiver)(void *struct_ptr, const void *chunk_buf,
1148                              size_t chunk_size, int have_more)) {
1149     OCTET_STRING_t *st = (OCTET_STRING_t *)*sptr;
1150         const asn_OCTET_STRING_specifics_t *specs = td->specifics
1151                                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
1152                                 : &asn_SPC_OCTET_STRING_specs;
1153         const char *xml_tag = opt_mname ? opt_mname : td->xml_tag;
1154         asn_struct_ctx_t *ctx;          /* Per-structure parser context */
1155         asn_dec_rval_t rval;            /* Return value from the decoder */
1156         int st_allocated;
1157
1158         /*
1159          * Create the string if does not exist.
1160          */
1161         if(!st) {
1162                 st = (OCTET_STRING_t *)CALLOC(1, specs->struct_size);
1163                 *sptr = (void *)st;
1164                 if(!st) goto sta_failed;
1165                 st_allocated = 1;
1166         } else {
1167                 st_allocated = 0;
1168         }
1169         if(!st->buf) {
1170                 /* This is separate from above section */
1171                 st->buf = (uint8_t *)CALLOC(1, 1);
1172                 if(!st->buf) {
1173                         if(st_allocated) {
1174                                 *sptr = 0;
1175                                 goto stb_failed;
1176                         } else {
1177                                 goto sta_failed;
1178                         }
1179                 }
1180         }
1181
1182         /* Restore parsing context */
1183         ctx = (asn_struct_ctx_t *)(((char *)*sptr) + specs->ctx_offset);
1184
1185         return xer_decode_general(opt_codec_ctx, ctx, *sptr, xml_tag,
1186                 buf_ptr, size, opt_unexpected_tag_decoder, body_receiver);
1187
1188 stb_failed:
1189         FREEMEM(st);
1190 sta_failed:
1191         rval.code = RC_FAIL;
1192         rval.consumed = 0;
1193         return rval;
1194 }
1195
1196 /*
1197  * Decode OCTET STRING from the hexadecimal data.
1198  */
1199 asn_dec_rval_t
1200 OCTET_STRING_decode_xer_hex(const asn_codec_ctx_t *opt_codec_ctx,
1201                             const asn_TYPE_descriptor_t *td, void **sptr,
1202                             const char *opt_mname, const void *buf_ptr,
1203                             size_t size) {
1204     return OCTET_STRING__decode_xer(opt_codec_ctx, td, sptr, opt_mname,
1205                 buf_ptr, size, 0, OCTET_STRING__convert_hexadecimal);
1206 }
1207
1208 /*
1209  * Decode OCTET STRING from the binary (0/1) data.
1210  */
1211 asn_dec_rval_t
1212 OCTET_STRING_decode_xer_binary(const asn_codec_ctx_t *opt_codec_ctx,
1213                                const asn_TYPE_descriptor_t *td, void **sptr,
1214                                const char *opt_mname, const void *buf_ptr,
1215                                size_t size) {
1216     return OCTET_STRING__decode_xer(opt_codec_ctx, td, sptr, opt_mname,
1217                 buf_ptr, size, 0, OCTET_STRING__convert_binary);
1218 }
1219
1220 /*
1221  * Decode OCTET STRING from the string (ASCII/UTF-8) data.
1222  */
1223 asn_dec_rval_t
1224 OCTET_STRING_decode_xer_utf8(const asn_codec_ctx_t *opt_codec_ctx,
1225                              const asn_TYPE_descriptor_t *td, void **sptr,
1226                              const char *opt_mname, const void *buf_ptr,
1227                              size_t size) {
1228     return OCTET_STRING__decode_xer(opt_codec_ctx, td, sptr, opt_mname,
1229                 buf_ptr, size,
1230                 OCTET_STRING__handle_control_chars,
1231                 OCTET_STRING__convert_entrefs);
1232 }
1233
1234 #ifndef  ASN_DISABLE_PER_SUPPORT
1235
1236 static int
1237 OCTET_STRING_per_get_characters(asn_per_data_t *po, uint8_t *buf,
1238                 size_t units, unsigned int bpc, unsigned int unit_bits,
1239                 long lb, long ub, const asn_per_constraints_t *pc) {
1240         uint8_t *end = buf + units * bpc;
1241
1242         ASN_DEBUG("Expanding %d characters into (%ld..%ld):%d",
1243                 (int)units, lb, ub, unit_bits);
1244
1245         /* X.691: 27.5.4 */
1246         if((unsigned long)ub <= ((unsigned long)2 << (unit_bits - 1))) {
1247                 /* Decode without translation */
1248                 lb = 0;
1249         } else if(pc && pc->code2value) {
1250                 if(unit_bits > 16)
1251                         return 1;       /* FATAL: can't have constrained
1252                                          * UniversalString with more than
1253                                          * 16 million code points */
1254                 for(; buf < end; buf += bpc) {
1255                         int value;
1256                         int code = per_get_few_bits(po, unit_bits);
1257                         if(code < 0) return -1; /* WMORE */
1258                         value = pc->code2value(code);
1259                         if(value < 0) {
1260                                 ASN_DEBUG("Code %d (0x%02x) is"
1261                                         " not in map (%ld..%ld)",
1262                                         code, code, lb, ub);
1263                                 return 1;       /* FATAL */
1264                         }
1265                         switch(bpc) {
1266                         case 1: *buf = value; break;
1267                         case 2: buf[0] = value >> 8; buf[1] = value; break;
1268                         case 4: buf[0] = value >> 24; buf[1] = value >> 16;
1269                                 buf[2] = value >> 8; buf[3] = value; break;
1270                         }
1271                 }
1272                 return 0;
1273         }
1274
1275         /* Shortcut the no-op copying to the aligned structure */
1276         if(lb == 0 && (unit_bits == 8 * bpc)) {
1277                 return per_get_many_bits(po, buf, 0, unit_bits * units);
1278         }
1279
1280         for(; buf < end; buf += bpc) {
1281                 int32_t code = per_get_few_bits(po, unit_bits);
1282                 int32_t ch = code + lb;
1283                 if(code < 0) return -1; /* WMORE */
1284                 if(ch > ub) {
1285                         ASN_DEBUG("Code %d is out of range (%ld..%ld)",
1286                                 ch, lb, ub);
1287                         return 1;       /* FATAL */
1288                 }
1289                 switch(bpc) {
1290                 case 1: *buf = ch; break;
1291                 case 2: buf[0] = ch >> 8; buf[1] = ch; break;
1292                 case 4: buf[0] = ch >> 24; buf[1] = ch >> 16;
1293                         buf[2] = ch >> 8; buf[3] = ch; break;
1294                 }
1295         }
1296
1297         return 0;
1298 }
1299
1300 static int
1301 OCTET_STRING_per_put_characters(asn_per_outp_t *po, const uint8_t *buf,
1302                 size_t units, unsigned int bpc, unsigned int unit_bits,
1303                 long lb, long ub, const asn_per_constraints_t *pc) {
1304         const uint8_t *end = buf + units * bpc;
1305
1306         ASN_DEBUG("Squeezing %d characters into (%ld..%ld):%d (%d bpc)",
1307                 (int)units, lb, ub, unit_bits, bpc);
1308
1309         /* X.691: 27.5.4 */
1310         if((unsigned long)ub <= ((unsigned long)2 << (unit_bits - 1))) {
1311                 /* Encode as is */
1312                 lb = 0;
1313         } else if(pc && pc->value2code) {
1314                 for(; buf < end; buf += bpc) {
1315                         int code;
1316                         uint32_t value;
1317                         switch(bpc) {
1318                         case 1: value = *(const uint8_t *)buf; break;
1319                         case 2: value = (buf[0] << 8) | buf[1]; break;
1320                         case 4: value = (buf[0] << 24) | (buf[1] << 16)
1321                                         | (buf[2] << 8) | buf[3]; break;
1322                         default: return -1;
1323                         }
1324                         code = pc->value2code(value);
1325                         if(code < 0) {
1326                                 ASN_DEBUG("Character %d (0x%02x) is"
1327                                         " not in map (%ld..%ld)",
1328                                         *buf, *buf, lb, ub);
1329                                 return -1;
1330                         }
1331                         if(per_put_few_bits(po, code, unit_bits))
1332                                 return -1;
1333                 }
1334         }
1335
1336         /* Shortcut the no-op copying to the aligned structure */
1337         if(lb == 0 && (unit_bits == 8 * bpc)) {
1338                 return per_put_many_bits(po, buf, unit_bits * units);
1339         }
1340
1341     for(ub -= lb; buf < end; buf += bpc) {
1342         int ch;
1343         uint32_t value;
1344         switch(bpc) {
1345         case 1:
1346             value = *(const uint8_t *)buf;
1347             break;
1348         case 2:
1349             value = (buf[0] << 8) | buf[1];
1350             break;
1351         case 4:
1352             value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1353             break;
1354         default:
1355             return -1;
1356         }
1357         ch = value - lb;
1358         if(ch < 0 || ch > ub) {
1359             ASN_DEBUG("Character %d (0x%02x) is out of range (%ld..%ld)", *buf,
1360                       value, lb, ub + lb);
1361             return -1;
1362         }
1363         if(per_put_few_bits(po, ch, unit_bits)) return -1;
1364     }
1365
1366     return 0;
1367 }
1368
1369 static asn_per_constraints_t asn_DEF_OCTET_STRING_constraints = {
1370         { APC_CONSTRAINED, 8, 8, 0, 255 },
1371         { APC_SEMI_CONSTRAINED, -1, -1, 0, 0 },
1372         0, 0
1373 };
1374
1375 asn_dec_rval_t
1376 OCTET_STRING_decode_uper(const asn_codec_ctx_t *opt_codec_ctx,
1377                          const asn_TYPE_descriptor_t *td,
1378                          const asn_per_constraints_t *constraints, void **sptr,
1379                          asn_per_data_t *pd) {
1380     const asn_OCTET_STRING_specifics_t *specs = td->specifics
1381                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
1382                 : &asn_SPC_OCTET_STRING_specs;
1383     const asn_per_constraints_t *pc =
1384         constraints ? constraints : td->encoding_constraints.per_constraints;
1385     const asn_per_constraint_t *cval;
1386         const asn_per_constraint_t *csiz;
1387         asn_dec_rval_t rval = { RC_OK, 0 };
1388         OCTET_STRING_t *st = (OCTET_STRING_t *)*sptr;
1389         ssize_t consumed_myself = 0;
1390         int repeat;
1391         enum {
1392                 OS__BPC_CHAR    = 1,
1393                 OS__BPC_U16     = 2,
1394                 OS__BPC_U32     = 4
1395         } bpc;  /* Bytes per character */
1396         unsigned int unit_bits;
1397         unsigned int canonical_unit_bits;
1398
1399         (void)opt_codec_ctx;
1400
1401         if(pc) {
1402                 cval = &pc->value;
1403                 csiz = &pc->size;
1404         } else {
1405                 cval = &asn_DEF_OCTET_STRING_constraints.value;
1406                 csiz = &asn_DEF_OCTET_STRING_constraints.size;
1407         }
1408
1409         switch(specs->subvariant) {
1410         default:
1411         case ASN_OSUBV_ANY:
1412         case ASN_OSUBV_BIT:
1413                 ASN_DEBUG("Unrecognized subvariant %d", specs->subvariant);
1414                 RETURN(RC_FAIL);
1415                 break;
1416         case ASN_OSUBV_STR:
1417                 canonical_unit_bits = unit_bits = 8;
1418                 if(cval->flags & APC_CONSTRAINED)
1419                         unit_bits = cval->range_bits;
1420                 bpc = OS__BPC_CHAR;
1421                 break;
1422         case ASN_OSUBV_U16:
1423                 canonical_unit_bits = unit_bits = 16;
1424                 if(cval->flags & APC_CONSTRAINED)
1425                         unit_bits = cval->range_bits;
1426                 bpc = OS__BPC_U16;
1427                 break;
1428         case ASN_OSUBV_U32:
1429                 canonical_unit_bits = unit_bits = 32;
1430                 if(cval->flags & APC_CONSTRAINED)
1431                         unit_bits = cval->range_bits;
1432                 bpc = OS__BPC_U32;
1433                 break;
1434         }
1435
1436         /*
1437          * Allocate the string.
1438          */
1439         if(!st) {
1440                 st = (OCTET_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
1441                 if(!st) RETURN(RC_FAIL);
1442         }
1443
1444         ASN_DEBUG("PER Decoding %s size %ld .. %ld bits %d",
1445                 csiz->flags & APC_EXTENSIBLE ? "extensible" : "non-extensible",
1446                 csiz->lower_bound, csiz->upper_bound, csiz->effective_bits);
1447
1448         if(csiz->flags & APC_EXTENSIBLE) {
1449                 int inext = per_get_few_bits(pd, 1);
1450                 if(inext < 0) RETURN(RC_WMORE);
1451                 if(inext) {
1452                         csiz = &asn_DEF_OCTET_STRING_constraints.size;
1453                         unit_bits = canonical_unit_bits;
1454                 }
1455         }
1456
1457         if(csiz->effective_bits >= 0) {
1458                 FREEMEM(st->buf);
1459                 if(bpc) {
1460                         st->size = csiz->upper_bound * bpc;
1461                 } else {
1462                         st->size = (csiz->upper_bound + 7) >> 3;
1463                 }
1464                 st->buf = (uint8_t *)MALLOC(st->size + 1);
1465                 if(!st->buf) { st->size = 0; RETURN(RC_FAIL); }
1466         }
1467
1468         /* X.691, #16.5: zero-length encoding */
1469         /* X.691, #16.6: short fixed length encoding (up to 2 octets) */
1470         /* X.691, #16.7: long fixed length encoding (up to 64K octets) */
1471         if(csiz->effective_bits == 0) {
1472                 int ret;
1473                 if(bpc) {
1474                         ASN_DEBUG("Encoding OCTET STRING size %ld",
1475                                 csiz->upper_bound);
1476                         ret = OCTET_STRING_per_get_characters(pd, st->buf,
1477                                 csiz->upper_bound, bpc, unit_bits,
1478                                 cval->lower_bound, cval->upper_bound, pc);
1479                         if(ret > 0) RETURN(RC_FAIL);
1480                 } else {
1481                         ASN_DEBUG("Encoding BIT STRING size %ld",
1482                                 csiz->upper_bound);
1483                         ret = per_get_many_bits(pd, st->buf, 0,
1484                                             unit_bits * csiz->upper_bound);
1485                 }
1486                 if(ret < 0) RETURN(RC_WMORE);
1487                 consumed_myself += unit_bits * csiz->upper_bound;
1488                 st->buf[st->size] = 0;
1489                 RETURN(RC_OK);
1490         }
1491
1492         st->size = 0;
1493         do {
1494                 ssize_t raw_len;
1495                 ssize_t len_bytes;
1496                 void *p;
1497                 int ret;
1498
1499                 /* Get the PER length */
1500                 raw_len = uper_get_length(pd, csiz->effective_bits, csiz->lower_bound,
1501                                           &repeat);
1502                 if(raw_len < 0) RETURN(RC_WMORE);
1503                 if(raw_len == 0 && st->buf) break;
1504
1505                 ASN_DEBUG("Got PER length eb %ld, len %ld, %s (%s)",
1506                         (long)csiz->effective_bits, (long)raw_len,
1507                         repeat ? "repeat" : "once", td->name);
1508         len_bytes = raw_len * bpc;
1509                 p = REALLOC(st->buf, st->size + len_bytes + 1);
1510                 if(!p) RETURN(RC_FAIL);
1511                 st->buf = (uint8_t *)p;
1512
1513         ret = OCTET_STRING_per_get_characters(pd, &st->buf[st->size], raw_len,
1514                                               bpc, unit_bits, cval->lower_bound,
1515                                               cval->upper_bound, pc);
1516         if(ret > 0) RETURN(RC_FAIL);
1517                 if(ret < 0) RETURN(RC_WMORE);
1518                 st->size += len_bytes;
1519         } while(repeat);
1520         st->buf[st->size] = 0;  /* nul-terminate */
1521
1522         return rval;
1523 }
1524
1525 asn_enc_rval_t
1526 OCTET_STRING_encode_uper(const asn_TYPE_descriptor_t *td,
1527                          const asn_per_constraints_t *constraints,
1528                          const void *sptr, asn_per_outp_t *po) {
1529     const asn_OCTET_STRING_specifics_t *specs = td->specifics
1530                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
1531                 : &asn_SPC_OCTET_STRING_specs;
1532         const asn_per_constraints_t *pc = constraints ? constraints
1533                                 : td->encoding_constraints.per_constraints;
1534         const asn_per_constraint_t *cval;
1535         const asn_per_constraint_t *csiz;
1536         const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
1537         asn_enc_rval_t er = { 0, 0, 0 };
1538         int inext = 0;          /* Lies not within extension root */
1539         unsigned int unit_bits;
1540         unsigned int canonical_unit_bits;
1541         size_t size_in_units;
1542         const uint8_t *buf;
1543         int ret;
1544         enum {
1545                 OS__BPC_CHAR    = 1,
1546                 OS__BPC_U16     = 2,
1547                 OS__BPC_U32     = 4
1548         } bpc;  /* Bytes per character */
1549         int ct_extensible;
1550
1551         if(!st || (!st->buf && st->size))
1552                 ASN__ENCODE_FAILED;
1553
1554         if(pc) {
1555                 cval = &pc->value;
1556                 csiz = &pc->size;
1557         } else {
1558                 cval = &asn_DEF_OCTET_STRING_constraints.value;
1559                 csiz = &asn_DEF_OCTET_STRING_constraints.size;
1560         }
1561         ct_extensible = csiz->flags & APC_EXTENSIBLE;
1562
1563         switch(specs->subvariant) {
1564         default:
1565         case ASN_OSUBV_ANY:
1566         case ASN_OSUBV_BIT:
1567                 ASN__ENCODE_FAILED;
1568         case ASN_OSUBV_STR:
1569                 canonical_unit_bits = unit_bits = 8;
1570                 if(cval->flags & APC_CONSTRAINED)
1571                         unit_bits = cval->range_bits;
1572                 bpc = OS__BPC_CHAR;
1573                 size_in_units = st->size;
1574                 break;
1575         case ASN_OSUBV_U16:
1576                 canonical_unit_bits = unit_bits = 16;
1577                 if(cval->flags & APC_CONSTRAINED)
1578                         unit_bits = cval->range_bits;
1579                 bpc = OS__BPC_U16;
1580                 size_in_units = st->size >> 1;
1581                 if(st->size & 1) {
1582                         ASN_DEBUG("%s string size is not modulo 2", td->name);
1583                         ASN__ENCODE_FAILED;
1584                 }
1585                 break;
1586         case ASN_OSUBV_U32:
1587                 canonical_unit_bits = unit_bits = 32;
1588                 if(cval->flags & APC_CONSTRAINED)
1589                         unit_bits = cval->range_bits;
1590                 bpc = OS__BPC_U32;
1591                 size_in_units = st->size >> 2;
1592                 if(st->size & 3) {
1593                         ASN_DEBUG("%s string size is not modulo 4", td->name);
1594                         ASN__ENCODE_FAILED;
1595                 }
1596                 break;
1597         }
1598
1599         ASN_DEBUG("Encoding %s into %" ASN_PRI_SIZE " units of %d bits"
1600                 " (%ld..%ld, effective %d)%s",
1601                 td->name, size_in_units, unit_bits,
1602                 csiz->lower_bound, csiz->upper_bound,
1603                 csiz->effective_bits, ct_extensible ? " EXT" : "");
1604
1605         /* Figure out whether size lies within PER visible constraint */
1606
1607     if(csiz->effective_bits >= 0) {
1608         if((ssize_t)size_in_units < csiz->lower_bound
1609            || (ssize_t)size_in_units > csiz->upper_bound) {
1610             if(ct_extensible) {
1611                 csiz = &asn_DEF_OCTET_STRING_constraints.size;
1612                 unit_bits = canonical_unit_bits;
1613                 inext = 1;
1614             } else {
1615                 ASN__ENCODE_FAILED;
1616             }
1617         }
1618     } else {
1619         inext = 0;
1620     }
1621
1622     if(ct_extensible) {
1623                 /* Declare whether length is [not] within extension root */
1624                 if(per_put_few_bits(po, inext, 1))
1625                         ASN__ENCODE_FAILED;
1626         }
1627
1628     if(csiz->effective_bits >= 0 && !inext) {
1629         ASN_DEBUG("Encoding %" ASN_PRI_SIZE " bytes (%ld), length in %d bits", st->size,
1630                   size_in_units - csiz->lower_bound, csiz->effective_bits);
1631         ret = per_put_few_bits(po, size_in_units - csiz->lower_bound,
1632                                csiz->effective_bits);
1633         if(ret) ASN__ENCODE_FAILED;
1634         ret = OCTET_STRING_per_put_characters(po, st->buf, size_in_units, bpc,
1635                                               unit_bits, cval->lower_bound,
1636                                               cval->upper_bound, pc);
1637         if(ret) ASN__ENCODE_FAILED;
1638         ASN__ENCODED_OK(er);
1639     }
1640
1641     ASN_DEBUG("Encoding %" ASN_PRI_SIZE " bytes", st->size);
1642
1643     buf = st->buf;
1644     ASN_DEBUG("Encoding %" ASN_PRI_SIZE " in units", size_in_units);
1645     do {
1646         int need_eom = 0;
1647         ssize_t may_save = uper_put_length(po, size_in_units, &need_eom);
1648         if(may_save < 0) ASN__ENCODE_FAILED;
1649
1650         ASN_DEBUG("Encoding %" ASN_PRI_SSIZE " of %" ASN_PRI_SIZE "%s", may_save, size_in_units,
1651                   need_eom ? ",+EOM" : "");
1652
1653         ret = OCTET_STRING_per_put_characters(po, buf, may_save, bpc, unit_bits,
1654                                               cval->lower_bound,
1655                                               cval->upper_bound, pc);
1656         if(ret) ASN__ENCODE_FAILED;
1657
1658         buf += may_save * bpc;
1659         size_in_units -= may_save;
1660         assert(!(may_save & 0x07) || !size_in_units);
1661         if(need_eom && uper_put_length(po, 0, 0))
1662             ASN__ENCODE_FAILED; /* End of Message length */
1663     } while(size_in_units);
1664
1665     ASN__ENCODED_OK(er);
1666 }
1667
1668 asn_dec_rval_t
1669 OCTET_STRING_decode_aper(const asn_codec_ctx_t *opt_codec_ctx,
1670                          const asn_TYPE_descriptor_t *td,
1671                          const asn_per_constraints_t *constraints,
1672                          void **sptr, asn_per_data_t *pd) {
1673
1674         const asn_OCTET_STRING_specifics_t *specs = td->specifics
1675                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
1676                 : &asn_SPC_OCTET_STRING_specs;
1677         const asn_per_constraints_t *pc = constraints ? constraints
1678                                 : td->encoding_constraints.per_constraints;
1679         const asn_per_constraint_t *cval;
1680         const asn_per_constraint_t *csiz;
1681         asn_dec_rval_t rval = { RC_OK, 0 };
1682         BIT_STRING_t *st = (BIT_STRING_t *)*sptr;
1683         ssize_t consumed_myself = 0;
1684         int repeat;
1685         enum {
1686                 OS__BPC_BIT     = 0,
1687                 OS__BPC_CHAR    = 1,
1688                 OS__BPC_U16     = 2,
1689                 OS__BPC_U32     = 4
1690         } bpc;  /* Bytes per character */
1691         unsigned int unit_bits;
1692         unsigned int canonical_unit_bits;
1693
1694         (void)opt_codec_ctx;
1695
1696         if(pc) {
1697                 cval = &pc->value;
1698                 csiz = &pc->size;
1699         } else {
1700                 cval = &asn_DEF_OCTET_STRING_constraints.value;
1701                 csiz = &asn_DEF_OCTET_STRING_constraints.size;
1702         }
1703
1704         switch(specs->subvariant) {
1705         default:
1706 /*      case ASN_OSUBV_ANY:
1707                 ASN_DEBUG("Unrecognized subvariant %d", specs->subvariant);
1708                 RETURN(RC_FAIL);
1709 */
1710         case ASN_OSUBV_BIT:
1711                 canonical_unit_bits = unit_bits = 1;
1712                 bpc = OS__BPC_BIT;
1713                 break;
1714         case ASN_OSUBV_ANY:
1715         case ASN_OSUBV_STR:
1716                 canonical_unit_bits = unit_bits = 8;
1717 /*              if(cval->flags & APC_CONSTRAINED)
1718                         unit_bits = cval->range_bits;
1719 */
1720                 bpc = OS__BPC_CHAR;
1721                 break;
1722         case ASN_OSUBV_U16:
1723                 canonical_unit_bits = unit_bits = 16;
1724                 if(cval->flags & APC_CONSTRAINED)
1725                         unit_bits = cval->range_bits;
1726                 bpc = OS__BPC_U16;
1727                 break;
1728         case ASN_OSUBV_U32:
1729                 canonical_unit_bits = unit_bits = 32;
1730                 if(cval->flags & APC_CONSTRAINED)
1731                         unit_bits = cval->range_bits;
1732                 bpc = OS__BPC_U32;
1733                 break;
1734         }
1735
1736         /*
1737          * Allocate the string.
1738          */
1739         if(!st) {
1740                 st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
1741                 if(!st) RETURN(RC_FAIL);
1742         }
1743
1744         ASN_DEBUG("PER Decoding %s size %ld .. %ld bits %d",
1745                 csiz->flags & APC_EXTENSIBLE ? "extensible" : "non-extensible",
1746                 csiz->lower_bound, csiz->upper_bound, csiz->effective_bits);
1747
1748         if(csiz->flags & APC_EXTENSIBLE) {
1749                 int inext = per_get_few_bits(pd, 1);
1750                 if(inext < 0) RETURN(RC_WMORE);
1751                 if(inext) {
1752                         csiz = &asn_DEF_OCTET_STRING_constraints.size;
1753                         cval = &asn_DEF_OCTET_STRING_constraints.value;
1754                         unit_bits = canonical_unit_bits;
1755                 }
1756         }
1757
1758         if(csiz->effective_bits >= 0) {
1759                 FREEMEM(st->buf);
1760                 if(bpc) {
1761                         st->size = csiz->upper_bound * bpc;
1762                 } else {
1763                         st->size = (csiz->upper_bound + 7) >> 3;
1764                 }
1765                 st->buf = (uint8_t *)MALLOC(st->size + 1);
1766                 if(!st->buf) { st->size = 0; RETURN(RC_FAIL); }
1767         }
1768
1769         /* X.691, #16.5: zero-length encoding */
1770         /* X.691, #16.6: short fixed length encoding (up to 2 octets) */
1771         /* X.691, #16.7: long fixed length encoding (up to 64K octets) */
1772         if(csiz->effective_bits == 0) {
1773                 int ret;
1774                 if (st->size > 2) { /* X.691 #16 NOTE 1 */
1775                         if (aper_get_align(pd) < 0)
1776                                 RETURN(RC_FAIL);
1777                 }
1778                 if(bpc) {
1779                         ASN_DEBUG("Decoding OCTET STRING size %ld",
1780                                 csiz->upper_bound);
1781                         ret = OCTET_STRING_per_get_characters(pd, st->buf,
1782                                 csiz->upper_bound, bpc, unit_bits,
1783                                 cval->lower_bound, cval->upper_bound, pc);
1784                         if(ret > 0) RETURN(RC_FAIL);
1785                 } else {
1786                         ASN_DEBUG("Decoding BIT STRING size %ld",
1787                                 csiz->upper_bound);
1788                         ret = per_get_many_bits(pd, st->buf, 0,
1789                                             unit_bits * csiz->upper_bound);
1790                 }
1791                 if(ret < 0) RETURN(RC_WMORE);
1792                 consumed_myself += unit_bits * csiz->upper_bound;
1793                 st->buf[st->size] = 0;
1794                 if(bpc == 0) {
1795                         int ubs = (csiz->upper_bound & 0x7);
1796                         st->bits_unused = ubs ? 8 - ubs : 0;
1797                 }
1798                 RETURN(RC_OK);
1799         }
1800
1801         st->size = 0;
1802         do {
1803                 ssize_t raw_len;
1804                 ssize_t len_bytes;
1805                 ssize_t len_bits;
1806                 void *p;
1807                 int ret;
1808
1809                 /* Get the PER length */
1810                 if (csiz->upper_bound - csiz->lower_bound == 0)
1811                         /* Indefinite length case */
1812                         raw_len = aper_get_length(pd, -1, csiz->effective_bits, &repeat);
1813                 else
1814                         raw_len = aper_get_length(pd, csiz->upper_bound - csiz->lower_bound + 1, csiz->effective_bits, &repeat);
1815                 repeat = 0;
1816                 if(raw_len < 0) RETURN(RC_WMORE);
1817                 raw_len += csiz->lower_bound;
1818
1819                 ASN_DEBUG("Got PER length eb %ld, len %ld, %s (%s)",
1820                         (long)csiz->effective_bits, (long)raw_len,
1821                         repeat ? "repeat" : "once", td->name);
1822
1823                 if (raw_len > 2) { /* X.691 #16 NOTE 1 */
1824                         if (aper_get_align(pd) < 0)
1825                                 RETURN(RC_FAIL);
1826                 }
1827
1828                 if(bpc) {
1829                         len_bytes = raw_len * bpc;
1830                         len_bits = len_bytes * unit_bits;
1831                 } else {
1832                         len_bits = raw_len;
1833                         len_bytes = (len_bits + 7) >> 3;
1834                         if(len_bits & 0x7)
1835                                 st->bits_unused = 8 - (len_bits & 0x7);
1836                         /* len_bits be multiple of 16K if repeat is set */
1837                 }
1838                 p = REALLOC(st->buf, st->size + len_bytes + 1);
1839                 if(!p) RETURN(RC_FAIL);
1840                 st->buf = (uint8_t *)p;
1841
1842                 if(bpc) {
1843                         ret = OCTET_STRING_per_get_characters(pd,
1844                                 &st->buf[st->size], raw_len, bpc, unit_bits,
1845                                 cval->lower_bound, cval->upper_bound, pc);
1846                         if(ret > 0) RETURN(RC_FAIL);
1847                 } else {
1848                         ret = per_get_many_bits(pd, &st->buf[st->size],
1849                                 0, len_bits);
1850                 }
1851                 if(ret < 0) RETURN(RC_WMORE);
1852                 st->size += len_bytes;
1853         } while(repeat);
1854         st->buf[st->size] = 0;  /* nul-terminate */
1855
1856         return rval;
1857 }
1858
1859 asn_enc_rval_t
1860 OCTET_STRING_encode_aper(const asn_TYPE_descriptor_t *td,
1861                          const asn_per_constraints_t *constraints,
1862                          const void *sptr, asn_per_outp_t *po) {
1863
1864         const asn_OCTET_STRING_specifics_t *specs = td->specifics
1865                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
1866                 : &asn_SPC_OCTET_STRING_specs;
1867         const asn_per_constraints_t *pc = constraints ? constraints
1868         : td->encoding_constraints.per_constraints;
1869         const asn_per_constraint_t *cval;
1870         const asn_per_constraint_t *csiz;
1871         const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
1872         asn_enc_rval_t er = { 0, 0, 0 };
1873         int inext = 0;          /* Lies not within extension root */
1874         unsigned int unit_bits;
1875         unsigned int canonical_unit_bits;
1876         unsigned int sizeinunits;
1877         const uint8_t *buf;
1878         int ret;
1879         enum {
1880                 OS__BPC_BIT     = 0,
1881                 OS__BPC_CHAR    = 1,
1882                 OS__BPC_U16     = 2,
1883                 OS__BPC_U32     = 4
1884         } bpc;  /* Bytes per character */
1885         int ct_extensible;
1886
1887         if(!st || (!st->buf && st->size))
1888                 ASN__ENCODE_FAILED;
1889
1890         if(pc) {
1891                 cval = &pc->value;
1892                 csiz = &pc->size;
1893         } else {
1894                 cval = &asn_DEF_OCTET_STRING_constraints.value;
1895                 csiz = &asn_DEF_OCTET_STRING_constraints.size;
1896         }
1897         ct_extensible = csiz->flags & APC_EXTENSIBLE;
1898
1899         switch(specs->subvariant) {
1900                 default:
1901                         /*         case ASN_OSUBV_ANY:
1902                                          ASN__ENCODE_FAILED;
1903                         */
1904                 case ASN_OSUBV_BIT:
1905                         canonical_unit_bits = unit_bits = 1;
1906                         bpc = OS__BPC_BIT;
1907                         sizeinunits = st->size * 8 - (st->bits_unused & 0x07);
1908                         ASN_DEBUG("BIT STRING of %d bytes",
1909                                                                 sizeinunits);
1910                 break;
1911         case ASN_OSUBV_ANY:
1912         case ASN_OSUBV_STR:
1913                 canonical_unit_bits = unit_bits = 8;
1914 /*              if(cval->flags & APC_CONSTRAINED)
1915                         unit_bits = 8;
1916 */
1917                 bpc = OS__BPC_CHAR;
1918                 sizeinunits = st->size;
1919                 break;
1920         case ASN_OSUBV_U16:
1921                 canonical_unit_bits = unit_bits = 16;
1922                 if(cval->flags & APC_CONSTRAINED)
1923                         unit_bits = cval->range_bits;
1924                 bpc = OS__BPC_U16;
1925                 sizeinunits = st->size / 2;
1926                 break;
1927         case ASN_OSUBV_U32:
1928                 canonical_unit_bits = unit_bits = 32;
1929                 if(cval->flags & APC_CONSTRAINED)
1930                         unit_bits = cval->range_bits;
1931                 bpc = OS__BPC_U32;
1932                 sizeinunits = st->size / 4;
1933                 break;
1934         }
1935
1936         ASN_DEBUG("Encoding %s into %d units of %d bits"
1937                 " (%ld..%ld, effective %d)%s",
1938                 td->name, sizeinunits, unit_bits,
1939                 csiz->lower_bound, csiz->upper_bound,
1940                 csiz->effective_bits, ct_extensible ? " EXT" : "");
1941
1942         /* Figure out wheter size lies within PER visible constraint */
1943
1944         if(csiz->effective_bits >= 0) {
1945                 if((int)sizeinunits < csiz->lower_bound
1946                 || (int)sizeinunits > csiz->upper_bound) {
1947                         if(ct_extensible) {
1948                                 cval = &asn_DEF_OCTET_STRING_constraints.value;
1949                                 csiz = &asn_DEF_OCTET_STRING_constraints.size;
1950                                 unit_bits = canonical_unit_bits;
1951                                 inext = 1;
1952                         } else
1953                                 ASN__ENCODE_FAILED;
1954                 }
1955         } else {
1956                 inext = 0;
1957         }
1958
1959
1960         if(ct_extensible) {
1961                 /* Declare whether length is [not] within extension root */
1962                 if(per_put_few_bits(po, inext, 1))
1963                         ASN__ENCODE_FAILED;
1964         }
1965
1966         /* X.691, #16.5: zero-length encoding */
1967         /* X.691, #16.6: short fixed length encoding (up to 2 octets) */
1968         /* X.691, #16.7: long fixed length encoding (up to 64K octets) */
1969         if(csiz->effective_bits >= 0) {
1970                 ASN_DEBUG("Encoding %lu bytes (%ld), length in %d bits",
1971                                 st->size, sizeinunits - csiz->lower_bound,
1972                                 csiz->effective_bits);
1973                 if (csiz->effective_bits > 0) {
1974                         ret = aper_put_length(po, csiz->upper_bound - csiz->lower_bound + 1, sizeinunits - csiz->lower_bound);
1975                         if(ret) ASN__ENCODE_FAILED;
1976                 }
1977                 if (st->size > 2) { /* X.691 #16 NOTE 1 */
1978                         if (aper_put_align(po) < 0)
1979                                 ASN__ENCODE_FAILED;
1980                 }
1981                 if(bpc) {
1982                         ret = OCTET_STRING_per_put_characters(po, st->buf,
1983                                 sizeinunits, bpc, unit_bits,
1984                                 cval->lower_bound, cval->upper_bound, pc);
1985                 } else {
1986                         ret = per_put_many_bits(po, st->buf,
1987                                 sizeinunits * unit_bits);
1988                 }
1989                 if(ret) ASN__ENCODE_FAILED;
1990                 ASN__ENCODED_OK(er);
1991         }
1992
1993         ASN_DEBUG("Encoding %lu bytes", st->size);
1994
1995         if(sizeinunits == 0) {
1996                 if(aper_put_length(po, -1, 0))
1997                         ASN__ENCODE_FAILED;
1998                 ASN__ENCODED_OK(er);
1999         }
2000
2001         buf = st->buf;
2002         while(sizeinunits) {
2003                 ssize_t maySave = aper_put_length(po, -1, sizeinunits);
2004
2005                 if(maySave < 0) ASN__ENCODE_FAILED;
2006
2007                 ASN_DEBUG("Encoding %ld of %ld",
2008                         (long)maySave, (long)sizeinunits);
2009
2010                 if(bpc) {
2011                         ret = OCTET_STRING_per_put_characters(po, buf,
2012                                 maySave, bpc, unit_bits,
2013                                 cval->lower_bound, cval->upper_bound, pc);
2014                 } else {
2015                         ret = per_put_many_bits(po, buf, maySave * unit_bits);
2016                 }
2017                 if(ret) ASN__ENCODE_FAILED;
2018
2019                 if(bpc)
2020                         buf += maySave * bpc;
2021                 else
2022                         buf += maySave >> 3;
2023                 sizeinunits -= maySave;
2024                 assert(!(maySave & 0x07) || !sizeinunits);
2025         }
2026
2027         ASN__ENCODED_OK(er);
2028 }
2029
2030 #endif  /* ASN_DISABLE_PER_SUPPORT */
2031
2032 int
2033 OCTET_STRING_print(const asn_TYPE_descriptor_t *td, const void *sptr,
2034                    int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
2035     const char * const h2c = "0123456789ABCDEF";
2036         const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
2037         char scratch[16 * 3 + 4];
2038         char *p = scratch;
2039         uint8_t *buf;
2040         uint8_t *end;
2041         size_t i;
2042
2043         (void)td;       /* Unused argument */
2044
2045         if(!st || (!st->buf && st->size))
2046                 return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
2047
2048         /*
2049          * Dump the contents of the buffer in hexadecimal.
2050          */
2051         buf = st->buf;
2052         end = buf + st->size;
2053         for(i = 0; buf < end; buf++, i++) {
2054                 if(!(i % 16) && (i || st->size > 16)) {
2055                         if(cb(scratch, p - scratch, app_key) < 0)
2056                                 return -1;
2057                         _i_INDENT(1);
2058                         p = scratch;
2059                 }
2060                 *p++ = h2c[(*buf >> 4) & 0x0F];
2061                 *p++ = h2c[*buf & 0x0F];
2062                 *p++ = 0x20;
2063         }
2064
2065         if(p > scratch) {
2066                 p--;    /* Remove the tail space */
2067                 if(cb(scratch, p - scratch, app_key) < 0)
2068                         return -1;
2069         }
2070
2071         return 0;
2072 }
2073
2074 int
2075 OCTET_STRING_print_utf8(const asn_TYPE_descriptor_t *td, const void *sptr,
2076                         int ilevel, asn_app_consume_bytes_f *cb,
2077                         void *app_key) {
2078     const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr;
2079
2080         (void)td;       /* Unused argument */
2081         (void)ilevel;   /* Unused argument */
2082
2083         if(st && (st->buf || !st->size)) {
2084                 return (cb(st->buf, st->size, app_key) < 0) ? -1 : 0;
2085         } else {
2086                 return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
2087         }
2088 }
2089
2090 void
2091 OCTET_STRING_free(const asn_TYPE_descriptor_t *td, void *sptr,
2092                   enum asn_struct_free_method method) {
2093         OCTET_STRING_t *st = (OCTET_STRING_t *)sptr;
2094         const asn_OCTET_STRING_specifics_t *specs;
2095         asn_struct_ctx_t *ctx;
2096         struct _stack *stck;
2097
2098         if(!td || !st)
2099                 return;
2100
2101         specs = td->specifics
2102                     ? (const asn_OCTET_STRING_specifics_t *)td->specifics
2103                     : &asn_SPC_OCTET_STRING_specs;
2104         ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
2105
2106         ASN_DEBUG("Freeing %s as OCTET STRING", td->name);
2107
2108         if(st->buf) {
2109                 FREEMEM(st->buf);
2110                 st->buf = 0;
2111         }
2112
2113         /*
2114          * Remove decode-time stack.
2115          */
2116         stck = (struct _stack *)ctx->ptr;
2117         if(stck) {
2118                 while(stck->tail) {
2119                         struct _stack_el *sel = stck->tail;
2120                         stck->tail = sel->prev;
2121                         FREEMEM(sel);
2122                 }
2123                 FREEMEM(stck);
2124         }
2125
2126     switch(method) {
2127     case ASFM_FREE_EVERYTHING:
2128         FREEMEM(sptr);
2129         break;
2130     case ASFM_FREE_UNDERLYING:
2131         break;
2132     case ASFM_FREE_UNDERLYING_AND_RESET:
2133         memset(sptr, 0,
2134                td->specifics
2135                    ? ((const asn_OCTET_STRING_specifics_t *)(td->specifics))
2136                          ->struct_size
2137                    : sizeof(OCTET_STRING_t));
2138         break;
2139     }
2140 }
2141
2142 /*
2143  * Conversion routines.
2144  */
2145 int
2146 OCTET_STRING_fromBuf(OCTET_STRING_t *st, const char *str, int len) {
2147         void *buf;
2148
2149         if(st == 0 || (str == 0 && len)) {
2150                 errno = EINVAL;
2151                 return -1;
2152         }
2153
2154         /*
2155          * Clear the OCTET STRING.
2156          */
2157         if(str == NULL) {
2158                 FREEMEM(st->buf);
2159                 st->buf = 0;
2160                 st->size = 0;
2161                 return 0;
2162         }
2163
2164         /* Determine the original string size, if not explicitly given */
2165         if(len < 0)
2166                 len = strlen(str);
2167
2168         /* Allocate and fill the memory */
2169         buf = MALLOC(len + 1);
2170         if(buf == NULL)
2171                 return -1;
2172
2173         memcpy(buf, str, len);
2174         ((uint8_t *)buf)[len] = '\0';   /* Couldn't use memcpy(len+1)! */
2175         FREEMEM(st->buf);
2176         st->buf = (uint8_t *)buf;
2177         st->size = len;
2178
2179         return 0;
2180 }
2181
2182 OCTET_STRING_t *
2183 OCTET_STRING_new_fromBuf(const asn_TYPE_descriptor_t *td, const char *str,
2184                          int len) {
2185     const asn_OCTET_STRING_specifics_t *specs =
2186         td->specifics ? (const asn_OCTET_STRING_specifics_t *)td->specifics
2187                       : &asn_SPC_OCTET_STRING_specs;
2188     OCTET_STRING_t *st;
2189
2190         st = (OCTET_STRING_t *)CALLOC(1, specs->struct_size);
2191         if(st && str && OCTET_STRING_fromBuf(st, str, len)) {
2192                 FREEMEM(st);
2193                 st = NULL;
2194         }
2195
2196         return st;
2197 }
2198
2199 /*
2200  * Lexicographically compare the common prefix of both strings,
2201  * and if it is the same return -1 for the smallest string.
2202  */
2203 int
2204 OCTET_STRING_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
2205                      const void *bptr) {
2206     const asn_OCTET_STRING_specifics_t *specs = td->specifics;
2207     const OCTET_STRING_t *a = aptr;
2208     const OCTET_STRING_t *b = bptr;
2209
2210     assert(!specs || specs->subvariant != ASN_OSUBV_BIT);
2211
2212     if(a && b) {
2213         size_t common_prefix_size = a->size <= b->size ? a->size : b->size;
2214         int ret = memcmp(a->buf, b->buf, common_prefix_size);
2215         if(ret == 0) {
2216             /* Figure out which string with equal prefixes is longer. */
2217             if(a->size < b->size) {
2218                 return -1;
2219             } else if(a->size > b->size) {
2220                 return 1;
2221             } else {
2222                 return 0;
2223             }
2224         } else {
2225             return ret < 0 ? -1 : 1;
2226         }
2227     } else if(!a && !b) {
2228         return 0;
2229     } else if(!a) {
2230         return -1;
2231     } else {
2232         return 1;
2233     }
2234
2235 }
2236
2237 /*
2238  * Biased function for randomizing character values around their limits.
2239  */
2240 static uint32_t
2241 OCTET_STRING__random_char(unsigned long lb, unsigned long ub) {
2242     assert(lb <= ub);
2243     switch(asn_random_between(0, 16)) {
2244     case 0:
2245         if(lb < ub) return lb + 1;
2246         /* Fall through */
2247     case 1:
2248         return lb;
2249     case 2:
2250         if(lb < ub) return ub - 1;
2251         /* Fall through */
2252     case 3:
2253         return ub;
2254     default:
2255         return asn_random_between(lb, ub);
2256     }
2257 }
2258
2259
2260 size_t
2261 OCTET_STRING_random_length_constrained(
2262     const asn_TYPE_descriptor_t *td,
2263     const asn_encoding_constraints_t *constraints, size_t max_length) {
2264     const unsigned lengths[] = {0,     1,     2,     3,     4,     8,
2265                                 126,   127,   128,   16383, 16384, 16385,
2266                                 65534, 65535, 65536, 65537};
2267     size_t rnd_len;
2268
2269     /* Figure out how far we should go */
2270     rnd_len = lengths[asn_random_between(
2271         0, sizeof(lengths) / sizeof(lengths[0]) - 1)];
2272
2273     if(!constraints || !constraints->per_constraints)
2274         constraints = &td->encoding_constraints;
2275     if(constraints->per_constraints) {
2276         const asn_per_constraint_t *pc = &constraints->per_constraints->size;
2277         if(pc->flags & APC_CONSTRAINED) {
2278             long suggested_upper_bound = pc->upper_bound < (ssize_t)max_length
2279                                              ? pc->upper_bound
2280                                              : (ssize_t)max_length;
2281             if(max_length <= (size_t)pc->lower_bound) {
2282                 return pc->lower_bound;
2283             }
2284             if(pc->flags & APC_EXTENSIBLE) {
2285                 switch(asn_random_between(0, 5)) {
2286                 case 0:
2287                     if(pc->lower_bound > 0) {
2288                         rnd_len = pc->lower_bound - 1;
2289                         break;
2290                     }
2291                     /* Fall through */
2292                 case 1:
2293                     rnd_len = pc->upper_bound + 1;
2294                     break;
2295                 case 2:
2296                     /* Keep rnd_len from the table */
2297                     if(rnd_len <= max_length) {
2298                         break;
2299                     }
2300                     /* Fall through */
2301                 default:
2302                     rnd_len = asn_random_between(pc->lower_bound,
2303                                                  suggested_upper_bound);
2304                 }
2305             } else {
2306                 rnd_len =
2307                     asn_random_between(pc->lower_bound, suggested_upper_bound);
2308             }
2309         } else {
2310             rnd_len = asn_random_between(0, max_length);
2311         }
2312     } else if(rnd_len > max_length) {
2313         rnd_len = asn_random_between(0, max_length);
2314     }
2315
2316     return rnd_len;
2317 }
2318
2319 asn_random_fill_result_t
2320 OCTET_STRING_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
2321                          const asn_encoding_constraints_t *constraints,
2322                          size_t max_length) {
2323         const asn_OCTET_STRING_specifics_t *specs = td->specifics
2324                                 ? (const asn_OCTET_STRING_specifics_t *)td->specifics
2325                                 : &asn_SPC_OCTET_STRING_specs;
2326     asn_random_fill_result_t result_ok = {ARFILL_OK, 1};
2327     asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
2328     asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
2329     unsigned int unit_bytes = 1;
2330     unsigned long clb = 0;  /* Lower bound on char */
2331     unsigned long cub = 255;  /* Higher bound on char value */
2332     uint8_t *buf;
2333     uint8_t *bend;
2334     uint8_t *b;
2335     size_t rnd_len;
2336     OCTET_STRING_t *st;
2337
2338     if(max_length == 0 && !*sptr) return result_skipped;
2339
2340     switch(specs->subvariant) {
2341     default:
2342     case ASN_OSUBV_ANY:
2343         return result_failed;
2344     case ASN_OSUBV_BIT:
2345         /* Handled by BIT_STRING itself. */
2346         return result_failed;
2347     case ASN_OSUBV_STR:
2348         unit_bytes = 1;
2349         clb = 0;
2350         cub = 255;
2351         break;
2352     case ASN_OSUBV_U16:
2353         unit_bytes = 2;
2354         clb = 0;
2355         cub = 65535;
2356         break;
2357     case ASN_OSUBV_U32:
2358         unit_bytes = 4;
2359         clb = 0;
2360         cub = 0x10FFFF;
2361         break;
2362     }
2363
2364     if(!constraints || !constraints->per_constraints)
2365         constraints = &td->encoding_constraints;
2366     if(constraints->per_constraints) {
2367         const asn_per_constraint_t *pc = &constraints->per_constraints->value;
2368         if(pc->flags & APC_SEMI_CONSTRAINED) {
2369             clb = pc->lower_bound;
2370         } else if(pc->flags & APC_CONSTRAINED) {
2371             clb = pc->lower_bound;
2372             cub = pc->upper_bound;
2373         }
2374     }
2375
2376     rnd_len =
2377         OCTET_STRING_random_length_constrained(td, constraints, max_length);
2378
2379     buf = CALLOC(unit_bytes, rnd_len + 1);
2380     if(!buf) return result_failed;
2381
2382     bend = &buf[unit_bytes * rnd_len];
2383
2384     switch(unit_bytes) {
2385     case 1:
2386         for(b = buf; b < bend; b += unit_bytes) {
2387             *(uint8_t *)b = OCTET_STRING__random_char(clb, cub);
2388         }
2389         *(uint8_t *)b = 0;
2390         break;
2391     case 2:
2392         for(b = buf; b < bend; b += unit_bytes) {
2393             uint32_t code = OCTET_STRING__random_char(clb, cub);
2394             b[0] = code >> 8;
2395             b[1] = code;
2396         }
2397         *(uint16_t *)b = 0;
2398         break;
2399     case 4:
2400         for(b = buf; b < bend; b += unit_bytes) {
2401             uint32_t code = OCTET_STRING__random_char(clb, cub);
2402             b[0] = code >> 24;
2403             b[1] = code >> 16;
2404             b[2] = code >> 8;
2405             b[3] = code;
2406         }
2407         *(uint32_t *)b = 0;
2408         break;
2409     }
2410
2411     if(*sptr) {
2412         st = *sptr;
2413         FREEMEM(st->buf);
2414     } else {
2415         st = (OCTET_STRING_t *)(*sptr = CALLOC(1, specs->struct_size));
2416         if(!st) {
2417             FREEMEM(buf);
2418             return result_failed;
2419         }
2420     }
2421
2422     st->buf = buf;
2423     st->size = unit_bytes * rnd_len;
2424
2425     result_ok.length = st->size;
2426     return result_ok;
2427 }