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