1 /**
2  * @file cstr.c  DNS character strings encoding
3  *
4  * Copyright (C) 2010 Creytiv.com
5  */
6 #include <string.h>
7 #include <re_types.h>
8 #include <re_fmt.h>
9 #include <re_list.h>
10 #include <re_mem.h>
11 #include <re_mbuf.h>
12 #include <re_dns.h>
13 
14 
15 /**
16  * Encode a DNS character string into a memory buffer
17  *
18  * @param mb  Memory buffer to encode into
19  * @param str Character string
20  *
21  * @return 0 if success, otherwise errorcode
22  */
dns_cstr_encode(struct mbuf * mb,const char * str)23 int dns_cstr_encode(struct mbuf *mb, const char *str)
24 {
25 	uint8_t len;
26 	int err = 0;
27 
28 	if (!mb || !str)
29 		return EINVAL;
30 
31 	len = (uint8_t)strlen(str);
32 
33 	err |= mbuf_write_u8(mb, len);
34 	err |= mbuf_write_mem(mb, (const uint8_t *)str, len);
35 
36 	return err;
37 }
38 
39 
40 /**
41  * Decode a DNS character string from a memory buffer
42  *
43  * @param mb  Memory buffer to decode from
44  * @param str Pointer to allocated character string
45  *
46  * @return 0 if success, otherwise errorcode
47  */
dns_cstr_decode(struct mbuf * mb,char ** str)48 int dns_cstr_decode(struct mbuf *mb, char **str)
49 {
50 	uint8_t len;
51 
52 	if (!mb || !str || (mbuf_get_left(mb) < 1))
53 		return EINVAL;
54 
55 	len = mbuf_read_u8(mb);
56 
57 	if (mbuf_get_left(mb) < len)
58 		return EBADMSG;
59 
60 	return mbuf_strdup(mb, str, len);
61 }
62