7c49709eeb2659a2274523adfc587ed714d53dd9
[musl] / src / network / res_mkquery.c
1 #include <resolv.h>
2 #include <string.h>
3 #include <time.h>
4 #include "libc.h"
5
6 int __res_mkquery(int op, const char *dname, int class, int type,
7         const unsigned char *data, int datalen,
8         const unsigned char *newrr, unsigned char *buf, int buflen)
9 {
10         int id, i, j;
11         unsigned char q[280];
12         struct timespec ts;
13         size_t l = strnlen(dname, 254);
14
15         if (l-1>=253 || buflen<18+l || op>15u || class>255u || type>255u)
16                 return -1;
17
18         /* Construct query template - ID will be filled later */
19         memset(q, 0, 18+l);
20         q[2] = op*8 + 1;
21         q[5] = 1;
22         memcpy((char *)q+13, dname, l);
23         for (i=13; q[i]; i=j+1) {
24                 for (j=i; q[j] && q[j] != '.'; j++);
25                 if (j-i-1u > 62u) return -1;
26                 q[i-1] = j-i;
27         }
28         q[i+1] = type;
29         q[i+3] = class;
30
31         /* Make a reasonably unpredictable id */
32         clock_gettime(CLOCK_REALTIME, &ts);
33         id = ts.tv_nsec + ts.tv_nsec/65536UL & 0xffff;
34         q[0] = id/256;
35         q[1] = id;
36
37         memcpy(buf, q, 18+l);
38         return 18+l;
39 }
40
41 weak_alias(__res_mkquery, res_mkquery);