use lookup array for dns_type_string()
[project/mdnsd.git] / util.c
1 /*
2  * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License version 2.1
6  * as published by the Free Software Foundation
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
13
14 #include <sys/socket.h>
15 #include <sys/ioctl.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/utsname.h>
19 #include <linux/if.h>
20 #include <linux/sockios.h>
21 #include <arpa/inet.h>
22
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <stdlib.h>
29 #include <signal.h>
30
31 #include <libubox/uloop.h>
32
33 #include "dns.h"
34 #include "util.h"
35
36 uint8_t mdns_buf[MDNS_BUF_LEN];
37 int debug = 0;
38
39 char mdns_hostname[HOSTNAME_LEN];
40 char mdns_hostname_local[HOSTNAME_LEN + 6];
41
42 uint32_t
43 rand_time_delta(uint32_t t)
44 {
45         uint32_t val;
46         int fd = open("/dev/urandom", O_RDONLY);
47
48         if (!fd)
49                 return t;
50
51         if (read(fd, &val, sizeof(val)) == sizeof(val)) {
52                 int range = t / 30;
53
54                 srand(val);
55                 val = t + (rand() % range) - (range / 2);
56         } else {
57                 val = t;
58         }
59
60         close(fd);
61
62         return val;
63 }
64
65 void get_hostname(void)
66 {
67         struct utsname utsname;
68
69         mdns_hostname[0] = 0;
70         mdns_hostname_local[0] = 0;
71
72         if (uname(&utsname) < 0)
73                 return;
74
75         snprintf(mdns_hostname, sizeof(mdns_hostname), "%s", utsname.nodename);
76         snprintf(mdns_hostname_local, sizeof(mdns_hostname_local), "%s.local", utsname.nodename);
77 }
78
79 void*
80 memdup(const void *d, int l)
81 {
82         void *r = malloc(l);
83         if (!r)
84                 return NULL;
85         memcpy(r, d, l);
86         return r;
87 }
88