3 * Copyright (c) 2003, 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
4 * Redistribution and modifications are permitted subject to BSD license.
6 #include <asn_internal.h>
7 #include <ber_tlv_length.h>
8 #include <ber_tlv_tag.h>
11 ber_fetch_length(int _is_constructed, const void *bufptr, size_t size,
12 ber_tlv_len_t *len_r) {
13 const uint8_t *buf = (const uint8_t *)bufptr;
17 return 0; /* Want more */
19 oct = *(const uint8_t *)buf;
20 if((oct & 0x80) == 0) {
22 * Short definite length.
24 *len_r = oct; /* & 0x7F */
30 if(_is_constructed && oct == 0x80) {
31 *len_r = -1; /* Indefinite length */
36 /* Reserved in standard for future use. */
40 oct &= 0x7F; /* Leave only the 7 LS bits */
41 for(len = 0, buf++, skipped = 1;
42 oct && (++skipped <= size); buf++, oct--) {
44 /* Verify that we won't overflow. */
45 if(!(len >> ((8 * sizeof(len)) - (8+1)))) {
46 len = (len << 8) | *buf;
48 /* Too large length value. */
54 if(len < 0 || len > RSSIZE_MAX) {
55 /* Length value out of sane range. */
63 return 0; /* Want more */
69 ber_skip_length(const asn_codec_ctx_t *opt_codec_ctx,
70 int _is_constructed, const void *ptr, size_t size) {
71 ber_tlv_len_t vlen; /* Length of V in TLV */
72 ssize_t tl; /* Length of L in TLV */
73 ssize_t ll; /* Length of L in TLV */
77 * Make sure we didn't exceed the maximum stack size.
79 if(ASN__STACK_OVERFLOW_CHECK(opt_codec_ctx))
83 * Determine the size of L in TLV.
85 ll = ber_fetch_length(_is_constructed, ptr, size, &vlen);
86 if(ll <= 0) return ll;
94 return 0; /* Want more */
101 ASN_DEBUG("Skipping indefinite length");
102 for(skip = ll, ptr = ((const char *)ptr) + ll, size -= ll;;) {
106 tl = ber_fetch_tag(ptr, size, &tag);
107 if(tl <= 0) return tl;
109 ll = ber_skip_length(opt_codec_ctx,
110 BER_TLV_CONSTRUCTED(ptr),
111 ((const char *)ptr) + tl, size - tl);
112 if(ll <= 0) return ll;
117 * This may be the end of the indefinite length structure,
118 * two consecutive 0 octets.
119 * Check if it is true.
121 if(((const uint8_t *)ptr)[0] == 0
122 && ((const uint8_t *)ptr)[1] == 0)
125 ptr = ((const char *)ptr) + tl + ll;
133 der_tlv_length_serialize(ber_tlv_len_t len, void *bufp, size_t size) {
134 size_t required_size; /* Size of len encoding */
135 uint8_t *buf = (uint8_t *)bufp;
140 /* Encoded in 1 octet */
141 if(size) *buf = (uint8_t)len;
146 * Compute the size of the subsequent bytes.
148 for(required_size = 1, i = 8; i < 8 * (int)sizeof(len); i += 8) {
155 if(size <= required_size)
156 return required_size + 1;
158 *buf++ = (uint8_t)(0x80 | required_size); /* Length of the encoding */
161 * Produce the len encoding, space permitting.
163 end = buf + required_size;
164 for(i -= 8; buf < end; i -= 8, buf++)
165 *buf = (uint8_t)(len >> i);
167 return required_size + 1;