Moving in e2sim originally from it/test/simulators
[sim/e2-interface.git] / e2sim / ASN1c / ber_decoder.c
1 /*****************************************************************************
2 #                                                                            *
3 # Copyright 2019 AT&T Intellectual Property                                  *
4 #                                                                            *
5 # Licensed under the Apache License, Version 2.0 (the "License");            *
6 # you may not use this file except in compliance with the License.           *
7 # You may obtain a copy of the License at                                    *
8 #                                                                            *
9 #      http://www.apache.org/licenses/LICENSE-2.0                            *
10 #                                                                            *
11 # Unless required by applicable law or agreed to in writing, software        *
12 # distributed under the License is distributed on an "AS IS" BASIS,          *
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
14 # See the License for the specific language governing permissions and        *
15 # limitations under the License.                                             *
16 #                                                                            *
17 ******************************************************************************/
18
19 /*-
20  * Copyright (c) 2003, 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
21  * Redistribution and modifications are permitted subject to BSD license.
22  */
23 #include <asn_internal.h>
24
25 #undef  ADVANCE
26 #define ADVANCE(num_bytes)      do {                                    \
27                 size_t num = num_bytes;                                 \
28                 ptr = ((const char *)ptr) + num;                        \
29                 size -= num;                                            \
30                 consumed_myself += num;                                 \
31         } while(0)
32 #undef  RETURN
33 #define RETURN(_code)   do {                                            \
34                 asn_dec_rval_t rval;                                    \
35                 rval.code = _code;                                      \
36                 if(opt_ctx) opt_ctx->step = step; /* Save context */    \
37                 if(_code == RC_OK || opt_ctx)                           \
38                         rval.consumed = consumed_myself;                \
39                 else                                                    \
40                         rval.consumed = 0;      /* Context-free */      \
41                 return rval;                                            \
42         } while(0)
43
44 /*
45  * The BER decoder of any type.
46  */
47 asn_dec_rval_t
48 ber_decode(const asn_codec_ctx_t *opt_codec_ctx,
49            const asn_TYPE_descriptor_t *type_descriptor, void **struct_ptr,
50            const void *ptr, size_t size) {
51     asn_codec_ctx_t s_codec_ctx;
52
53         /*
54          * Stack checker requires that the codec context
55          * must be allocated on the stack.
56          */
57         if(opt_codec_ctx) {
58                 if(opt_codec_ctx->max_stack_size) {
59                         s_codec_ctx = *opt_codec_ctx;
60                         opt_codec_ctx = &s_codec_ctx;
61                 }
62         } else {
63                 /* If context is not given, be security-conscious anyway */
64                 memset(&s_codec_ctx, 0, sizeof(s_codec_ctx));
65                 s_codec_ctx.max_stack_size = ASN__DEFAULT_STACK_MAX;
66                 opt_codec_ctx = &s_codec_ctx;
67         }
68
69         /*
70          * Invoke type-specific decoder.
71          */
72         return type_descriptor->op->ber_decoder(opt_codec_ctx, type_descriptor,
73                 struct_ptr,     /* Pointer to the destination structure */
74                 ptr, size,      /* Buffer and its size */
75                 0               /* Default tag mode is 0 */
76                 );
77 }
78
79 /*
80  * Check the set of <TL<TL<TL...>>> tags matches the definition.
81  */
82 asn_dec_rval_t
83 ber_check_tags(const asn_codec_ctx_t *opt_codec_ctx,
84                const asn_TYPE_descriptor_t *td, asn_struct_ctx_t *opt_ctx,
85                const void *ptr, size_t size, int tag_mode, int last_tag_form,
86                ber_tlv_len_t *last_length, int *opt_tlv_form) {
87     ssize_t consumed_myself = 0;
88         ssize_t tag_len;
89         ssize_t len_len;
90         ber_tlv_tag_t tlv_tag;
91         ber_tlv_len_t tlv_len;
92         ber_tlv_len_t limit_len = -1;
93         int expect_00_terminators = 0;
94         int tlv_constr = -1;    /* If CHOICE, opt_tlv_form is not given */
95         int step = opt_ctx ? opt_ctx->step : 0; /* Where we left previously */
96         int tagno;
97
98         /*
99          * Make sure we didn't exceed the maximum stack size.
100          */
101         if(ASN__STACK_OVERFLOW_CHECK(opt_codec_ctx))
102                 RETURN(RC_FAIL);
103
104         /*
105          * So what does all this implicit skip stuff mean?
106          * Imagine two types,
107          *      A ::= [5] IMPLICIT      T
108          *      B ::= [2] EXPLICIT      T
109          * Where T is defined as
110          *      T ::= [4] IMPLICIT SEQUENCE { ... }
111          * 
112          * Let's say, we are starting to decode type A, given the
113          * following TLV stream: <5> <0>. What does this mean?
114          * It means that the type A contains type T which is,
115          * in turn, empty.
116          * Remember though, that we are still in A. We cannot
117          * just pass control to the type T decoder. Why? Because
118          * the type T decoder expects <4> <0>, not <5> <0>.
119          * So, we must make sure we are going to receive <5> while
120          * still in A, then pass control to the T decoder, indicating
121          * that the tag <4> was implicitly skipped. The decoder of T
122          * hence will be prepared to treat <4> as valid tag, and decode
123          * it appropriately.
124          */
125
126         tagno = step    /* Continuing where left previously */
127                 + (tag_mode==1?-1:0)
128                 ;
129         ASN_DEBUG("ber_check_tags(%s, size=%ld, tm=%d, step=%d, tagno=%d)",
130                 td->name, (long)size, tag_mode, step, tagno);
131         /* assert(td->tags_count >= 1) May not be the case for CHOICE or ANY */
132
133         if(tag_mode == 0 && tagno == (int)td->tags_count) {
134                 /*
135                  * This must be the _untagged_ ANY type,
136                  * which outermost tag isn't known in advance.
137                  * Fetch the tag and length separately.
138                  */
139                 tag_len = ber_fetch_tag(ptr, size, &tlv_tag);
140                 switch(tag_len) {
141                 case -1: RETURN(RC_FAIL);
142                 case 0: RETURN(RC_WMORE);
143                 }
144                 tlv_constr = BER_TLV_CONSTRUCTED(ptr);
145                 len_len = ber_fetch_length(tlv_constr,
146                         (const char *)ptr + tag_len, size - tag_len, &tlv_len);
147                 switch(len_len) {
148                 case -1: RETURN(RC_FAIL);
149                 case 0: RETURN(RC_WMORE);
150                 }
151                 ASN_DEBUG("Advancing %ld in ANY case",
152                         (long)(tag_len + len_len));
153                 ADVANCE(tag_len + len_len);
154         } else {
155                 assert(tagno < (int)td->tags_count);    /* At least one loop */
156         }
157         for((void)tagno; tagno < (int)td->tags_count; tagno++, step++) {
158
159                 /*
160                  * Fetch and process T from TLV.
161                  */
162                 tag_len = ber_fetch_tag(ptr, size, &tlv_tag);
163                         ASN_DEBUG("Fetching tag from {%p,%ld}: "
164                                 "len %ld, step %d, tagno %d got %s",
165                                 ptr, (long)size,
166                                 (long)tag_len, step, tagno,
167                                 ber_tlv_tag_string(tlv_tag));
168                 switch(tag_len) {
169                 case -1: RETURN(RC_FAIL);
170                 case 0: RETURN(RC_WMORE);
171                 }
172
173                 tlv_constr = BER_TLV_CONSTRUCTED(ptr);
174
175                 /*
176                  * If {I}, don't check anything.
177                  * If {I,B,C}, check B and C unless we're at I.
178                  */
179                 if(tag_mode != 0 && step == 0) {
180                         /*
181                          * We don't expect tag to match here.
182                          * It's just because we don't know how the tag
183                          * is supposed to look like.
184                          */
185                 } else {
186                     assert(tagno >= 0); /* Guaranteed by the code above */
187                     if(tlv_tag != td->tags[tagno]) {
188                         /*
189                          * Unexpected tag. Too bad.
190                          */
191                         ASN_DEBUG("Expected: %s, "
192                                 "expectation failed (tn=%d, tm=%d)",
193                                 ber_tlv_tag_string(td->tags[tagno]),
194                                 tagno, tag_mode
195                         );
196                         RETURN(RC_FAIL);
197                     }
198                 }
199
200                 /*
201                  * Attention: if there are more tags expected,
202                  * ensure that the current tag is presented
203                  * in constructed form (it contains other tags!).
204                  * If this one is the last one, check that the tag form
205                  * matches the one given in descriptor.
206                  */
207                 if(tagno < ((int)td->tags_count - 1)) {
208                         if(tlv_constr == 0) {
209                                 ASN_DEBUG("tlv_constr = %d, expfail",
210                                         tlv_constr);
211                                 RETURN(RC_FAIL);
212                         }
213                 } else {
214                         if(last_tag_form != tlv_constr
215                         && last_tag_form != -1) {
216                                 ASN_DEBUG("last_tag_form %d != %d",
217                                         last_tag_form, tlv_constr);
218                                 RETURN(RC_FAIL);
219                         }
220                 }
221
222                 /*
223                  * Fetch and process L from TLV.
224                  */
225                 len_len = ber_fetch_length(tlv_constr,
226                         (const char *)ptr + tag_len, size - tag_len, &tlv_len);
227                 ASN_DEBUG("Fetching len = %ld", (long)len_len);
228                 switch(len_len) {
229                 case -1: RETURN(RC_FAIL);
230                 case 0: RETURN(RC_WMORE);
231                 }
232
233                 /*
234                  * FIXME
235                  * As of today, the chain of tags
236                  * must either contain several indefinite length TLVs,
237                  * or several definite length ones.
238                  * No mixing is allowed.
239                  */
240                 if(tlv_len == -1) {
241                         /*
242                          * Indefinite length.
243                          */
244                         if(limit_len == -1) {
245                                 expect_00_terminators++;
246                         } else {
247                                 ASN_DEBUG("Unexpected indefinite length "
248                                         "in a chain of definite lengths");
249                                 RETURN(RC_FAIL);
250                         }
251                         ADVANCE(tag_len + len_len);
252                         continue;
253                 } else {
254                         if(expect_00_terminators) {
255                                 ASN_DEBUG("Unexpected definite length "
256                                         "in a chain of indefinite lengths");
257                                 RETURN(RC_FAIL);
258                         }
259                 }
260
261                 /*
262                  * Check that multiple TLVs specify ever decreasing length,
263                  * which is consistent.
264                  */
265                 if(limit_len == -1) {
266                         limit_len    = tlv_len + tag_len + len_len;
267                         if(limit_len < 0) {
268                                 /* Too great tlv_len value? */
269                                 RETURN(RC_FAIL);
270                         }
271                 } else if(limit_len != tlv_len + tag_len + len_len) {
272                         /*
273                          * Inner TLV specifies length which is inconsistent
274                          * with the outer TLV's length value.
275                          */
276                         ASN_DEBUG("Outer TLV is %ld and inner is %ld",
277                                 (long)limit_len, (long)tlv_len);
278                         RETURN(RC_FAIL);
279                 }
280
281                 ADVANCE(tag_len + len_len);
282
283                 limit_len -= (tag_len + len_len);
284                 if((ssize_t)size > limit_len) {
285                         /*
286                          * Make sure that we won't consume more bytes
287                          * from the parent frame than the inferred limit.
288                          */
289                         size = limit_len;
290                 }
291         }
292
293         if(opt_tlv_form)
294                 *opt_tlv_form = tlv_constr;
295         if(expect_00_terminators)
296                 *last_length = -expect_00_terminators;
297         else
298                 *last_length = tlv_len;
299
300         RETURN(RC_OK);
301 }