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_tag.h>
11 ber_fetch_tag(const void *ptr, size_t size, ber_tlv_tag_t *tag_r) {
19 val = *(const uint8_t *)ptr;
21 if((val &= 0x1F) != 0x1F) {
23 * Simple form: everything encoded in a single octet.
24 * Tag Class is encoded using two least significant bits.
26 *tag_r = (val << 2) | tclass;
31 * Each octet contains 7 bits of useful information.
32 * The MSB is 0 if it is the last octet of the tag.
34 for(val = 0, ptr = ((const char *)ptr) + 1, skipped = 2;
36 ptr = ((const char *)ptr) + 1, skipped++) {
37 unsigned int oct = *(const uint8_t *)ptr;
39 val = (val << 7) | (oct & 0x7F);
41 * Make sure there are at least 9 bits spare
42 * at the MS side of a value.
44 if(val >> ((8 * sizeof(val)) - 9)) {
46 * We would not be able to accomodate
52 val = (val << 7) | oct;
53 *tag_r = (val << 2) | tclass;
58 return 0; /* Want more */
63 ber_tlv_tag_fwrite(ber_tlv_tag_t tag, FILE *f) {
64 char buf[sizeof("[APPLICATION ]") + 32];
67 ret = ber_tlv_tag_snprint(tag, buf, sizeof(buf));
68 if(ret >= (ssize_t)sizeof(buf) || ret < 2) {
73 return fwrite(buf, 1, ret, f);
77 ber_tlv_tag_snprint(ber_tlv_tag_t tag, char *buf, size_t size) {
82 case ASN_TAG_CLASS_UNIVERSAL: type = "UNIVERSAL "; break;
83 case ASN_TAG_CLASS_APPLICATION: type = "APPLICATION "; break;
84 case ASN_TAG_CLASS_CONTEXT: type = ""; break;
85 case ASN_TAG_CLASS_PRIVATE: type = "PRIVATE "; break;
88 ret = snprintf(buf, size, "[%s%u]", type, ((unsigned)tag) >> 2);
89 if(ret <= 0 && size) buf[0] = '\0'; /* against broken libc's */
95 ber_tlv_tag_string(ber_tlv_tag_t tag) {
96 static char buf[sizeof("[APPLICATION ]") + 32];
98 (void)ber_tlv_tag_snprint(tag, buf, sizeof(buf));
105 ber_tlv_tag_serialize(ber_tlv_tag_t tag, void *bufp, size_t size) {
106 int tclass = BER_TAG_CLASS(tag);
107 ber_tlv_tag_t tval = BER_TAG_VALUE(tag);
108 uint8_t *buf = (uint8_t *)bufp;
110 size_t required_size;
114 /* Encoded in 1 octet */
115 if(size) buf[0] = (tclass << 6) | tval;
118 *buf++ = (tclass << 6) | 0x1F;
123 * Compute the size of the subsequent bytes.
125 for(required_size = 1, i = 7; i < 8 * sizeof(tval); i += 7) {
132 if(size < required_size)
133 return required_size + 1;
136 * Fill in the buffer, space permitting.
138 end = buf + required_size - 1;
139 for(i -= 7; buf < end; i -= 7, buf++)
140 *buf = 0x80 | ((tval >> i) & 0x7F);
141 *buf = (tval & 0x7F); /* Last octet without high bit */
143 return required_size + 1;