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