Rename service_name function to the service_instance_name
[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 <arpa/inet.h>
20
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <signal.h>
28
29 #include <libubox/uloop.h>
30 #include <libubox/utils.h>
31
32 #include "dns.h"
33 #include "util.h"
34
35 uint8_t mdns_buf[MDNS_BUF_LEN];
36 int debug = 0;
37
38 char umdns_host_label[HOSTNAME_LEN];
39 char mdns_hostname_local[HOSTNAME_LEN + 6];
40
41 uint32_t
42 rand_time_delta(uint32_t t)
43 {
44         uint32_t val;
45         int fd = open("/dev/urandom", O_RDONLY);
46
47         if (!fd)
48                 return t;
49
50         if (read(fd, &val, sizeof(val)) == sizeof(val)) {
51                 int range = t / 30;
52
53                 srand(val);
54                 val = t + (rand() % range) - (range / 2);
55         } else {
56                 val = t;
57         }
58
59         close(fd);
60
61         return val;
62 }
63
64 void get_hostname(void)
65 {
66         struct utsname utsname;
67
68         umdns_host_label[0] = 0;
69         mdns_hostname_local[0] = 0;
70
71         if (uname(&utsname) < 0)
72                 return;
73
74         snprintf(umdns_host_label, sizeof(umdns_host_label), "%s", utsname.nodename);
75         snprintf(mdns_hostname_local, sizeof(mdns_hostname_local), "%s.local", utsname.nodename);
76 }
77
78 time_t monotonic_time(void)
79 {
80         struct timespec ts;
81         clock_gettime(CLOCK_MONOTONIC, &ts);
82         return ts.tv_sec;
83 }