summaryrefslogtreecommitdiffstats
path: root/util.c
blob: f5cfdb864cc08857bf90a61d36ea7c3d4109599c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
 * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 2.1
 * as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <signal.h>

#include <libubox/uloop.h>
#include <libubox/utils.h>

#include "dns.h"
#include "util.h"

uint8_t mdns_buf[MDNS_BUF_LEN];
int debug = 0;

char umdns_host_label[HOSTNAME_LEN];
char mdns_hostname_local[HOSTNAME_LEN + 6];

uint32_t
rand_time_delta(uint32_t t)
{
	uint32_t val;
	int fd = open("/dev/urandom", O_RDONLY);

	if (!fd)
		return t;

	if (read(fd, &val, sizeof(val)) == sizeof(val)) {
		int range = t / 30;

		srand(val);
		val = t + (rand() % range) - (range / 2);
	} else {
		val = t;
	}

	close(fd);

	return val;
}

void get_hostname(void)
{
	struct utsname utsname;

	umdns_host_label[0] = 0;
	mdns_hostname_local[0] = 0;

	if (uname(&utsname) < 0)
		return;

	snprintf(umdns_host_label, sizeof(umdns_host_label), "%s", utsname.nodename);
	snprintf(mdns_hostname_local, sizeof(mdns_hostname_local), "%s.local", utsname.nodename);
}

time_t monotonic_time(void)
{
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return ts.tv_sec;
}