2
* Copyright (c) 2003, 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
3
* Redistribution and modifications are permitted subject to BSD license.
5
#include <asn_internal.h>
6
#include <ber_tlv_tag.h>
10
ber_fetch_tag(const void *ptr, size_t size, ber_tlv_tag_t *tag_r) {
18
val = *(const uint8_t *)ptr;
20
if((val &= 0x1F) != 0x1F) {
22
* Simple form: everything encoded in a single octet.
23
* Tag Class is encoded using two least significant bits.
25
*tag_r = (val << 2) | tclass;
30
* Each octet contains 7 bits of useful information.
31
* The MSB is 0 if it is the last octet of the tag.
33
for(val = 0, ptr = ((const char *)ptr) + 1, skipped = 2;
35
ptr = ((const char *)ptr) + 1, skipped++) {
36
unsigned int oct = *(const uint8_t *)ptr;
38
val = (val << 7) | (oct & 0x7F);
40
* Make sure there are at least 9 bits spare
41
* at the MS side of a value.
43
if(val >> ((8 * sizeof(val)) - 9)) {
45
* We would not be able to accomodate
51
val = (val << 7) | oct;
52
*tag_r = (val << 2) | tclass;
57
return 0; /* Want more */
62
ber_tlv_tag_fwrite(ber_tlv_tag_t tag, FILE *f) {
63
char buf[sizeof("[APPLICATION ]") + 32];
66
ret = ber_tlv_tag_snprint(tag, buf, sizeof(buf));
67
if(ret >= (ssize_t)sizeof(buf) || ret < 2) {
72
return fwrite(buf, 1, ret, f);
76
ber_tlv_tag_snprint(ber_tlv_tag_t tag, char *buf, size_t size) {
81
case ASN_TAG_CLASS_UNIVERSAL: type = "UNIVERSAL "; break;
82
case ASN_TAG_CLASS_APPLICATION: type = "APPLICATION "; break;
83
case ASN_TAG_CLASS_CONTEXT: type = ""; break;
84
case ASN_TAG_CLASS_PRIVATE: type = "PRIVATE "; break;
87
ret = snprintf(buf, size, "[%s%u]", type, ((unsigned)tag) >> 2);
88
if(ret <= 0 && size) buf[0] = '\0'; /* against broken libc's */
94
ber_tlv_tag_string(ber_tlv_tag_t tag) {
95
static char buf[sizeof("[APPLICATION ]") + 32];
97
(void)ber_tlv_tag_snprint(tag, buf, sizeof(buf));
104
ber_tlv_tag_serialize(ber_tlv_tag_t tag, void *bufp, size_t size) {
105
int tclass = BER_TAG_CLASS(tag);
106
ber_tlv_tag_t tval = BER_TAG_VALUE(tag);
107
uint8_t *buf = (uint8_t *)bufp;
109
size_t required_size;
113
/* Encoded in 1 octet */
114
if(size) buf[0] = (tclass << 6) | tval;
117
*buf++ = (tclass << 6) | 0x1F;
122
* Compute the size of the subsequent bytes.
124
for(required_size = 1, i = 7; i < 8 * sizeof(tval); i += 7) {
131
if(size < required_size)
132
return required_size + 1;
135
* Fill in the buffer, space permitting.
137
end = buf + required_size - 1;
138
for(i -= 7; buf < end; i -= 7, buf++)
139
*buf = 0x80 | ((tval >> i) & 0x7F);
140
*buf = (tval & 0x7F); /* Last octet without high bit */
142
return required_size + 1;