2 * Copyright (c) 2003, 2004, 2005 Lev Walkin <vlm@lionet.info>.
4 * Redistribution and modifications are permitted subject to BSD license.
6 #include <asn_internal.h>
7 #include <constr_SET_OF.h>
8 #include <asn_SET_OF.h>
11 * Number of bytes left for this structure.
12 * (ctx->left) indicates the number of bytes _transferred_ for the structure.
13 * (size) contains the number of bytes in the buffer passed.
15 #define LEFT ((size<(size_t)ctx->left)?size:(size_t)ctx->left)
18 * If the subprocessor function returns with an indication that it wants
19 * more data, it may well be a fatal decoding problem, because the
20 * size is constrained by the <TLV>'s L, even if the buffer size allows
22 * For example, consider the buffer containing the following TLVs:
23 * <T:5><L:1><V> <T:6>...
24 * The TLV length clearly indicates that one byte is expected in V, but
25 * if the V processor returns with "want more data" even if the buffer
26 * contains way more data than the V processor have seen.
28 #define SIZE_VIOLATION (ctx->left >= 0 && (size_t)ctx->left <= size)
31 * This macro "eats" the part of the buffer which is definitely "consumed",
32 * i.e. was correctly converted into local representation or rightfully skipped.
35 #define ADVANCE(num_bytes) do { \
36 size_t num = num_bytes; \
37 ptr = ((const char *)ptr) + num;\
41 consumed_myself += num; \
45 * Switch to the next phase of parsing.
49 #define NEXT_PHASE(ctx) do { \
53 #define PHASE_OUT(ctx) do { ctx->phase = 10; } while(0)
56 * Return a standardized complex structure.
59 #define RETURN(_code) do { \
61 rval.consumed = consumed_myself;\
66 * The decoder of the SET OF type.
69 SET_OF_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
70 void **struct_ptr, const void *ptr, size_t size, int tag_mode) {
72 * Bring closer parts of structure description.
74 asn_SET_OF_specifics_t *specs = (asn_SET_OF_specifics_t *)td->specifics;
75 asn_TYPE_member_t *elm = td->elements; /* Single one */
78 * Parts of the structure being constructed.
80 void *st = *struct_ptr; /* Target structure. */
81 asn_struct_ctx_t *ctx; /* Decoder context */
83 ber_tlv_tag_t tlv_tag; /* T from TLV */
84 asn_dec_rval_t rval; /* Return code from subparsers */
86 ssize_t consumed_myself = 0; /* Consumed bytes from ptr */
88 ASN_DEBUG("Decoding %s as SET OF", td->name);
91 * Create the target structure if it is not present already.
94 st = *struct_ptr = CALLOC(1, specs->struct_size);
101 * Restore parsing context.
103 ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
106 * Start to parse where left previously
112 * Check that the set of tags associated with given structure
113 * perfectly fits our expectations.
116 rval = ber_check_tags(opt_codec_ctx, td, ctx, ptr, size,
117 tag_mode, 1, &ctx->left, 0);
118 if(rval.code != RC_OK) {
119 ASN_DEBUG("%s tagging check failed: %d",
120 td->name, rval.code);
125 ctx->left += rval.consumed; /* ?Substracted below! */
126 ADVANCE(rval.consumed);
128 ASN_DEBUG("Structure consumes %ld bytes, "
129 "buffer %ld", (long)ctx->left, (long)size);
136 * From the place where we've left it previously,
137 * try to decode the next item.
139 for(;; ctx->step = 0) {
140 ssize_t tag_len; /* Length of TLV's T */
146 * MICROPHASE 1: Synchronize decoding.
150 ASN_DEBUG("End of SET OF %s", td->name);
152 * No more things to decode.
160 * Fetch the T from TLV.
162 tag_len = ber_fetch_tag(ptr, LEFT, &tlv_tag);
164 case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE);
166 case -1: RETURN(RC_FAIL);
169 if(ctx->left < 0 && ((const uint8_t *)ptr)[0] == 0) {
175 } else if(((const uint8_t *)ptr)[1] == 0) {
177 * Found the terminator of the
178 * indefinite length structure.
184 /* Outmost tag may be unknown and cannot be fetched/compared */
185 if(elm->tag != (ber_tlv_tag_t)-1) {
186 if(BER_TAGS_EQUAL(tlv_tag, elm->tag)) {
188 * The new list member of expected type has arrived.
191 ASN_DEBUG("Unexpected tag %s fixed SET OF %s",
192 ber_tlv_tag_string(tlv_tag), td->name);
193 ASN_DEBUG("%s SET OF has tag %s",
194 td->name, ber_tlv_tag_string(elm->tag));
200 * MICROPHASE 2: Invoke the member-specific decoder.
202 ctx->step |= 1; /* Confirm entering next microphase */
206 * Invoke the member fetch routine according to member's type
208 rval = elm->type->ber_decoder(opt_codec_ctx,
209 elm->type, &ctx->ptr, ptr, LEFT, 0);
210 ASN_DEBUG("In %s SET OF %s code %d consumed %d",
211 td->name, elm->type->name,
212 rval.code, (int)rval.consumed);
216 asn_anonymous_set_ *list = _A_SET_FROM_VOID(st);
217 if(ASN_SET_ADD(list, ctx->ptr) != 0)
223 case RC_WMORE: /* More data expected */
224 if(!SIZE_VIOLATION) {
225 ADVANCE(rval.consumed);
229 case RC_FAIL: /* Fatal error */
233 ADVANCE(rval.consumed);
234 } /* for(all list members) */
239 * Read in all "end of content" TLVs.
241 while(ctx->left < 0) {
243 if(LEFT > 0 && ((const char *)ptr)[0] != 0) {
250 if(((const char *)ptr)[0] == 0
251 && ((const char *)ptr)[1] == 0) {
266 * Internally visible buffer holding a single encoded element.
273 /* Append bytes to the above structure */
274 static int _el_addbytes(const void *buffer, size_t size, void *el_buf_ptr) {
275 struct _el_buffer *el_buf = (struct _el_buffer *)el_buf_ptr;
277 if(el_buf->length + size > el_buf->size)
280 memcpy(el_buf->buf + el_buf->length, buffer, size);
282 el_buf->length += size;
285 static int _el_buf_cmp(const void *ap, const void *bp) {
286 const struct _el_buffer *a = (const struct _el_buffer *)ap;
287 const struct _el_buffer *b = (const struct _el_buffer *)bp;
291 if(a->length < b->length)
292 common_len = a->length;
294 common_len = b->length;
296 ret = memcmp(a->buf, b->buf, common_len);
298 if(a->length < b->length)
300 else if(a->length > b->length)
308 * The DER encoder of the SET OF type.
311 SET_OF_encode_der(asn_TYPE_descriptor_t *td, void *ptr,
312 int tag_mode, ber_tlv_tag_t tag,
313 asn_app_consume_bytes_f *cb, void *app_key) {
314 asn_TYPE_member_t *elm = td->elements;
315 asn_TYPE_descriptor_t *elm_type = elm->type;
316 der_type_encoder_f *der_encoder = elm_type->der_encoder;
317 asn_anonymous_set_ *list = _A_SET_FROM_VOID(ptr);
318 size_t computed_size = 0;
319 ssize_t encoding_size = 0;
320 struct _el_buffer *encoded_els;
321 ssize_t eels_count = 0;
322 size_t max_encoded_len = 1;
323 asn_enc_rval_t erval;
327 ASN_DEBUG("Estimating size for SET OF %s", td->name);
330 * Gather the length of the underlying members sequence.
332 for(edx = 0; edx < list->count; edx++) {
333 void *memb_ptr = list->array[edx];
334 if(!memb_ptr) continue;
335 erval = der_encoder(elm_type, memb_ptr, 0, elm->tag, 0, 0);
336 if(erval.encoded == -1)
338 computed_size += erval.encoded;
340 /* Compute maximum encoding's size */
341 if(max_encoded_len < (size_t)erval.encoded)
342 max_encoded_len = erval.encoded;
346 * Encode the TLV for the sequence itself.
348 encoding_size = der_write_tags(td, computed_size, tag_mode, 1, tag,
350 if(encoding_size == -1) {
352 erval.failed_type = td;
353 erval.structure_ptr = ptr;
356 computed_size += encoding_size;
358 if(!cb || list->count == 0) {
359 erval.encoded = computed_size;
360 _ASN_ENCODED_OK(erval);
364 * DER mandates dynamic sorting of the SET OF elements
365 * according to their encodings. Build an array of the
368 encoded_els = (struct _el_buffer *)MALLOC(
369 list->count * sizeof(encoded_els[0]));
370 if(encoded_els == NULL) {
372 erval.failed_type = td;
373 erval.structure_ptr = ptr;
377 ASN_DEBUG("Encoding members of %s SET OF", td->name);
380 * Encode all members.
382 for(edx = 0; edx < list->count; edx++) {
383 void *memb_ptr = list->array[edx];
384 struct _el_buffer *encoded_el = &encoded_els[eels_count];
386 if(!memb_ptr) continue;
389 * Prepare space for encoding.
391 encoded_el->buf = (uint8_t *)MALLOC(max_encoded_len);
392 if(encoded_el->buf) {
393 encoded_el->length = 0;
394 encoded_el->size = max_encoded_len;
396 for(edx--; edx >= 0; edx--)
397 FREEMEM(encoded_els[edx].buf);
398 FREEMEM(encoded_els);
400 erval.failed_type = td;
401 erval.structure_ptr = ptr;
406 * Encode the member into the prepared space.
408 erval = der_encoder(elm_type, memb_ptr, 0, elm->tag,
409 _el_addbytes, encoded_el);
410 if(erval.encoded == -1) {
411 for(; edx >= 0; edx--)
412 FREEMEM(encoded_els[edx].buf);
413 FREEMEM(encoded_els);
416 encoding_size += erval.encoded;
421 * Sort the encoded elements according to their encoding.
423 qsort(encoded_els, eels_count, sizeof(encoded_els[0]), _el_buf_cmp);
426 * Report encoded elements to the application.
427 * Dispose of temporary sorted members table.
430 for(edx = 0; edx < eels_count; edx++) {
431 struct _el_buffer *encoded_el = &encoded_els[edx];
432 /* Report encoded chunks to the application */
434 && cb(encoded_el->buf, encoded_el->length, app_key) < 0)
436 FREEMEM(encoded_el->buf);
438 FREEMEM(encoded_els);
440 if(ret || computed_size != (size_t)encoding_size) {
442 * Standard callback failed, or
443 * encoded size is not equal to the computed size.
446 erval.failed_type = td;
447 erval.structure_ptr = ptr;
449 erval.encoded = computed_size;
452 _ASN_ENCODED_OK(erval);
456 #define XER_ADVANCE(num_bytes) do { \
457 size_t num = num_bytes; \
458 buf_ptr = ((const char *)buf_ptr) + num;\
460 consumed_myself += num; \
464 * Decode the XER (XML) data.
467 SET_OF_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
468 void **struct_ptr, const char *opt_mname,
469 const void *buf_ptr, size_t size) {
471 * Bring closer parts of structure description.
473 asn_SET_OF_specifics_t *specs = (asn_SET_OF_specifics_t *)td->specifics;
474 asn_TYPE_member_t *element = td->elements;
476 const char *xml_tag = opt_mname ? opt_mname : td->xml_tag;
479 * ... and parts of the structure being constructed.
481 void *st = *struct_ptr; /* Target structure. */
482 asn_struct_ctx_t *ctx; /* Decoder context */
484 asn_dec_rval_t rval; /* Return value from a decoder */
485 ssize_t consumed_myself = 0; /* Consumed bytes from ptr */
488 * Create the target structure if it is not present already.
491 st = *struct_ptr = CALLOC(1, specs->struct_size);
492 if(st == 0) RETURN(RC_FAIL);
495 /* Which tag is expected for the downstream */
496 if(specs->as_XMLValueList) {
497 elm_tag = (specs->as_XMLValueList == 1) ? 0 : "";
499 elm_tag = (*element->name)
500 ? element->name : element->type->xml_tag;
504 * Restore parsing context.
506 ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset);
509 * Phases of XER/XML processing:
510 * Phase 0: Check that the opening tag matches our expectations.
511 * Phase 1: Processing body and reacting on closing tag.
512 * Phase 2: Processing inner type.
514 for(; ctx->phase <= 2;) {
515 pxer_chunk_type_e ch_type; /* XER chunk type */
516 ssize_t ch_size; /* Chunk size */
517 xer_check_tag_e tcv; /* Tag check value */
520 * Go inside the inner member of a set.
522 if(ctx->phase == 2) {
523 asn_dec_rval_t tmprval;
525 /* Invoke the inner type decoder, m.b. multiple times */
526 ASN_DEBUG("XER/SET OF element [%s]", elm_tag);
527 tmprval = element->type->xer_decoder(opt_codec_ctx,
528 element->type, &ctx->ptr, elm_tag,
530 if(tmprval.code == RC_OK) {
531 asn_anonymous_set_ *list = _A_SET_FROM_VOID(st);
532 if(ASN_SET_ADD(list, ctx->ptr) != 0)
535 XER_ADVANCE(tmprval.consumed);
537 XER_ADVANCE(tmprval.consumed);
538 RETURN(tmprval.code);
540 ctx->phase = 1; /* Back to body processing */
541 ASN_DEBUG("XER/SET OF phase => %d", ctx->phase);
546 * Get the next part of the XML stream.
548 ch_size = xer_next_token(&ctx->context,
549 buf_ptr, size, &ch_type);
551 case -1: RETURN(RC_FAIL);
552 case 0: RETURN(RC_WMORE);
555 case PXER_COMMENT: /* Got XML comment */
556 case PXER_TEXT: /* Ignore free-standing text */
557 XER_ADVANCE(ch_size); /* Skip silently */
560 break; /* Check the rest down there */
564 tcv = xer_check_tag(buf_ptr, ch_size, xml_tag);
565 ASN_DEBUG("XER/SET OF: tcv = %d, ph=%d t=%s",
566 tcv, ctx->phase, xml_tag);
569 if(ctx->phase == 0) break;
573 if(ctx->phase == 0) {
574 /* No more things to decode */
575 XER_ADVANCE(ch_size);
576 ctx->phase = 3; /* Phase out */
581 if(ctx->phase == 0) {
582 XER_ADVANCE(ch_size);
583 ctx->phase = 1; /* Processing body phase */
590 ASN_DEBUG("XER/SET OF: tcv=%d, ph=%d", tcv, ctx->phase);
591 if(ctx->phase == 1) {
593 * Process a single possible member.
603 ASN_DEBUG("Unexpected XML tag in SET OF");
607 ctx->phase = 3; /* "Phase out" on hard failure */
613 typedef struct xer_tmp_enc_s {
619 SET_OF_encode_xer_callback(const void *buffer, size_t size, void *key) {
620 xer_tmp_enc_t *t = (xer_tmp_enc_t *)key;
621 if(t->offset + size >= t->size) {
622 size_t newsize = (t->size << 2) + size;
623 void *p = REALLOC(t->buffer, newsize);
628 memcpy((char *)t->buffer + t->offset, buffer, size);
633 SET_OF_xer_order(const void *aptr, const void *bptr) {
634 const xer_tmp_enc_t *a = (const xer_tmp_enc_t *)aptr;
635 const xer_tmp_enc_t *b = (const xer_tmp_enc_t *)bptr;
636 size_t minlen = a->offset;
638 if(b->offset < minlen) minlen = b->offset;
639 /* Well-formed UTF-8 has this nice lexicographical property... */
640 ret = memcmp(a->buffer, b->buffer, minlen);
641 if(ret != 0) return ret;
642 if(a->offset == b->offset)
644 if(a->offset == minlen)
651 SET_OF_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
652 int ilevel, enum xer_encoder_flags_e flags,
653 asn_app_consume_bytes_f *cb, void *app_key) {
655 asn_SET_OF_specifics_t *specs = (asn_SET_OF_specifics_t *)td->specifics;
656 asn_TYPE_member_t *elm = td->elements;
657 asn_anonymous_set_ *list = _A_SET_FROM_VOID(sptr);
658 const char *mname = specs->as_XMLValueList
659 ? 0 : ((*elm->name) ? elm->name : elm->type->xml_tag);
660 size_t mlen = mname ? strlen(mname) : 0;
661 int xcan = (flags & XER_F_CANONICAL);
662 xer_tmp_enc_t *encs = 0;
663 size_t encs_count = 0;
664 void *original_app_key = app_key;
665 asn_app_consume_bytes_f *original_cb = cb;
668 if(!sptr) _ASN_ENCODE_FAILED;
671 encs = (xer_tmp_enc_t *)MALLOC(list->count * sizeof(encs[0]));
672 if(!encs) _ASN_ENCODE_FAILED;
673 cb = SET_OF_encode_xer_callback;
678 for(i = 0; i < list->count; i++) {
679 asn_enc_rval_t tmper;
681 void *memb_ptr = list->array[i];
682 if(!memb_ptr) continue;
685 memset(&encs[encs_count], 0, sizeof(encs[0]));
686 app_key = &encs[encs_count];
691 if(!xcan) _i_ASN_TEXT_INDENT(1, ilevel);
692 _ASN_CALLBACK3("<", 1, mname, mlen, ">", 1);
695 if(!xcan && specs->as_XMLValueList == 1)
696 _i_ASN_TEXT_INDENT(1, ilevel + 1);
697 tmper = elm->type->xer_encoder(elm->type, memb_ptr,
698 ilevel + (specs->as_XMLValueList != 2),
700 if(tmper.encoded == -1) {
701 td = tmper.failed_type;
702 sptr = tmper.structure_ptr;
705 if(tmper.encoded == 0 && specs->as_XMLValueList) {
706 const char *name = elm->type->xml_tag;
707 size_t len = strlen(name);
708 _ASN_CALLBACK3("<", 1, name, len, "/>", 2);
712 _ASN_CALLBACK3("</", 2, mname, mlen, ">", 1);
716 er.encoded += (2 * mlen) + tmper.encoded;
719 if(!xcan) _i_ASN_TEXT_INDENT(1, ilevel - 1);
722 xer_tmp_enc_t *enc = encs;
723 xer_tmp_enc_t *end = encs + encs_count;
724 ssize_t control_size = 0;
727 app_key = original_app_key;
728 qsort(encs, encs_count, sizeof(encs[0]), SET_OF_xer_order);
730 for(; enc < end; enc++) {
731 _ASN_CALLBACK(enc->buffer, enc->offset);
732 FREEMEM(enc->buffer);
734 control_size += enc->offset;
736 assert(control_size == er.encoded);
743 er.structure_ptr = sptr;
746 while(encs_count-- > 0) {
747 if(encs[encs_count].buffer)
748 FREEMEM(encs[encs_count].buffer);
756 SET_OF_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
757 asn_app_consume_bytes_f *cb, void *app_key) {
758 asn_TYPE_member_t *elm = td->elements;
759 const asn_anonymous_set_ *list = _A_CSET_FROM_VOID(sptr);
763 if(!sptr) return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
766 if(cb(td->name, strlen(td->name), app_key) < 0
767 || cb(" ::= {", 6, app_key) < 0)
770 for(i = 0; i < list->count; i++) {
771 const void *memb_ptr = list->array[i];
772 if(!memb_ptr) continue;
776 ret = elm->type->print_struct(elm->type, memb_ptr,
777 ilevel + 1, cb, app_key);
784 return (cb("}", 1, app_key) < 0) ? -1 : 0;
788 SET_OF_free(asn_TYPE_descriptor_t *td, void *ptr, int contents_only) {
790 asn_TYPE_member_t *elm = td->elements;
791 asn_anonymous_set_ *list = _A_SET_FROM_VOID(ptr);
795 * Could not use set_of_empty() because of (*free)
798 for(i = 0; i < list->count; i++) {
799 void *memb_ptr = list->array[i];
801 ASN_STRUCT_FREE(*elm->type, memb_ptr);
803 list->count = 0; /* No meaningful elements left */
805 asn_set_empty(list); /* Remove (list->array) */
814 SET_OF_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
815 asn_app_constraint_failed_f *ctfailcb, void *app_key) {
816 asn_TYPE_member_t *elm = td->elements;
817 asn_constr_check_f *constr;
818 const asn_anonymous_set_ *list = _A_CSET_FROM_VOID(sptr);
822 _ASN_CTFAIL(app_key, td,
823 "%s: value not given (%s:%d)",
824 td->name, __FILE__, __LINE__);
828 constr = elm->memb_constraints;
829 if(!constr) constr = elm->type->check_constraints;
832 * Iterate over the members of an array.
833 * Validate each in turn, until one fails.
835 for(i = 0; i < list->count; i++) {
836 const void *memb_ptr = list->array[i];
839 if(!memb_ptr) continue;
841 ret = constr(elm->type, memb_ptr, ctfailcb, app_key);
846 * Cannot inherit it eralier:
847 * need to make sure we get the updated version.
849 if(!elm->memb_constraints)
850 elm->memb_constraints = elm->type->check_constraints;
856 SET_OF_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
857 asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
859 asn_SET_OF_specifics_t *specs = (asn_SET_OF_specifics_t *)td->specifics;
860 asn_TYPE_member_t *elm = td->elements; /* Single one */
862 asn_anonymous_set_ *list;
863 asn_per_constraint_t *ct;
867 if(_ASN_STACK_OVERFLOW_CHECK(opt_codec_ctx))
871 * Create the target structure if it is not present already.
874 st = *sptr = CALLOC(1, specs->struct_size);
875 if(!st) _ASN_DECODE_FAILED;
877 list = _A_SET_FROM_VOID(st);
879 /* Figure out which constraints to use */
880 if(constraints) ct = &constraints->size;
881 else if(td->per_constraints) ct = &td->per_constraints->size;
884 if(ct && ct->flags & APC_EXTENSIBLE) {
885 int value = per_get_few_bits(pd, 1);
886 if(value < 0) _ASN_DECODE_STARVED;
887 if(value) ct = 0; /* Not restricted! */
890 if(ct && ct->effective_bits >= 0) {
891 /* X.691, #19.5: No length determinant */
892 nelems = per_get_few_bits(pd, ct->effective_bits);
893 ASN_DEBUG("Preparing to fetch %ld+%ld elements from %s",
894 (long)nelems, ct->lower_bound, td->name);
895 if(nelems < 0) _ASN_DECODE_STARVED;
896 nelems += ct->lower_bound;
904 nelems = uper_get_length(pd,
905 ct ? ct->effective_bits : -1, &repeat);
906 ASN_DEBUG("Got to decode %d elements (eff %d)",
907 (int)nelems, ct ? ct->effective_bits : -1);
908 if(nelems < 0) _ASN_DECODE_STARVED;
911 for(i = 0; i < nelems; i++) {
913 ASN_DEBUG("SET OF %s decoding", elm->type->name);
914 rv = elm->type->uper_decoder(opt_codec_ctx, elm->type,
915 elm->per_constraints, &ptr, pd);
916 ASN_DEBUG("%s SET OF %s decoded %d, %p",
917 td->name, elm->type->name, rv.code, ptr);
918 if(rv.code == RC_OK) {
919 if(ASN_SET_ADD(list, ptr) == 0)
921 ASN_DEBUG("Failed to add element into %s",
926 ASN_DEBUG("Failed decoding %s of %s (SET OF)",
927 elm->type->name, td->name);
929 if(ptr) ASN_STRUCT_FREE(*elm->type, ptr);
933 nelems = -1; /* Allow uper_get_length() */
936 ASN_DEBUG("Decoded %s as SET OF", td->name);