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