Dominick Meglio's new ares_expand_string() function
[platform/upstream/c-ares.git] / ares_expand_string.c
1 /* Copyright 1998 by the Massachusetts Institute of Technology.
2  *
3  * Permission to use, copy, modify, and distribute this
4  * software and its documentation for any purpose and without
5  * fee is hereby granted, provided that the above copyright
6  * notice appear in all copies and that both that copyright
7  * notice and this permission notice appear in supporting
8  * documentation, and that the name of M.I.T. not be used in
9  * advertising or publicity pertaining to distribution of the
10  * software without specific, written prior permission.
11  * M.I.T. makes no representations about the suitability of
12  * this software for any purpose.  It is provided "as is"
13  * without express or implied warranty.
14  */
15
16 #include <sys/types.h>
17
18 #ifdef WIN32
19 #include "nameser.h"
20 #else
21 #include <netinet/in.h>
22 #include <arpa/nameser.h>
23 #endif
24
25 #include <string.h>
26 #include <stdlib.h>
27 #include "ares.h"
28 #include "ares_private.h" /* for the memdebug */
29
30 /* Simply decodes a length-encoded character string. The first byte of the
31  * input is the length of the string to be returned and the bytes thereafter
32  * are the characters of the string. The returned result will be NULL
33  * terminated.
34  */
35 int ares_expand_string(const unsigned char *encoded,
36                        const unsigned char *abuf,
37                        int alen,
38                        unsigned char **s,
39                        long *enclen)
40 {
41   unsigned char *q;
42   long len;
43   if (encoded == abuf+alen)
44     return ARES_EBADSTR;
45
46   len = *encoded;
47   if (encoded+len+1 > abuf+alen)
48     return ARES_EBADSTR;
49
50   encoded++;
51
52   *s = malloc(len+1);
53   if (*s == NULL)
54     return ARES_ENOMEM;
55   q = *s; 
56   strncpy((char *)q, (char *)encoded, len);
57   q[len] = '\0';
58
59   *s = q;
60
61   *enclen = len+1; 
62
63   return ARES_SUCCESS;
64 }
65