fix excessive stack usage
[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 static void
40 signal_shutdown(int signal)
41 {
42 uloop_end();
43 }
44
45 void
46 signal_setup(void)
47 {
48 signal(SIGPIPE, SIG_IGN);
49 signal(SIGTERM, signal_shutdown);
50 signal(SIGKILL, signal_shutdown);
51 }
52
53 uint32_t
54 rand_time_delta(uint32_t t)
55 {
56 uint32_t val;
57 int fd = open("/dev/urandom", O_RDONLY);
58
59 if (!fd)
60 return t;
61
62 if (read(fd, &val, sizeof(val)) == sizeof(val)) {
63 int range = t / 30;
64
65 srand(val);
66 val = t + (rand() % range) - (range / 2);
67 } else {
68 val = t;
69 }
70
71 close(fd);
72
73 return val;
74 }
75
76 char*
77 get_hostname(void)
78 {
79 static struct utsname utsname;
80
81 if (uname(&utsname) < 0)
82 return NULL;
83
84 return utsname.nodename;
85 }
86
87 void*
88 memdup(const void *d, int l)
89 {
90 void *r = malloc(l);
91 if (!r)
92 return NULL;
93 memcpy(r, d, l);
94 return r;
95 }
96