aboutsummaryrefslogtreecommitdiff
path: root/common.c
blob: f930ee00c517a535d25487c5b611a3fc892fe654 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
 * dhcpcd - DHCP client daemon
 * Copyright (c) 2006-2015 Roy Marples <roy@marples.name>
 * All rights reserved

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifdef __APPLE__
#  include <mach/mach_time.h>
#  include <mach/kern_return.h>
#endif

#include <sys/param.h>
#include <sys/time.h>

#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#ifdef BSD
#  include <paths.h>
#endif
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>

#include "common.h"
#include "dhcpcd.h"
#include "if-options.h"

#ifndef _PATH_DEVNULL
#  define _PATH_DEVNULL "/dev/null"
#endif

const char *
get_hostname(char *buf, size_t buflen, int short_hostname)
{
	char *p;

	if (gethostname(buf, buflen) != 0)
		return NULL;
	buf[buflen - 1] = '\0';
	if (strcmp(buf, "(none)") == 0 ||
	    strcmp(buf, "localhost") == 0 ||
	    strncmp(buf, "localhost.", strlen("localhost.")) == 0 ||
	    buf[0] == '.')
		return NULL;

	if (short_hostname) {
		p = strchr(buf, '.');
		if (p)
			*p = '\0';
	}

	return buf;
}

/* Handy function to get the time.
 * We only care about time advancements, not the actual time itself
 * Which is why we use CLOCK_MONOTONIC, but it is not available on all
 * platforms.
 */
#define NO_MONOTONIC "host does not support a monotonic clock - timing can skew"
int
get_monotonic(struct timespec *ts)
{

#if defined(_POSIX_MONOTONIC_CLOCK) && defined(CLOCK_MONOTONIC)
	return clock_gettime(CLOCK_MONOTONIC, ts);
#elif defined(__APPLE__)
	/* We can use mach kernel functions here.
	 * This is crap though - why can't they implement clock_gettime?*/
	static struct mach_timebase_info info = { 0, 0 };
	static double factor = 0.0;
	uint64_t nano;
	long rem;

	if (!posix_clock_set) {
		if (mach_timebase_info(&info) == KERN_SUCCESS) {
			factor = (double)info.numer / (double)info.denom;
			clock_monotonic = posix_clock_set = 1;
		}
	}
	if (clock_monotonic) {
		nano = mach_absolute_time();
		if ((info.denom != 1 || info.numer != 1) && factor != 0.0)
			nano *= factor;
		ts->tv_sec = nano / NSEC_PER_SEC;
		ts->tv_nsec = nano % NSEC_PER_SEC;
		if (ts->tv_nsec < 0) {
			ts->tv_sec--;
			ts->tv_nsec += NSEC_PER_SEC;
		}
		return 0;
	}
#endif

#if 0
	/* Something above failed, so fall back to gettimeofday */
	if (!posix_clock_set) {
		logger(NULL, LOG_WARNING, NO_MONOTONIC);
		posix_clock_set = 1;
	}
#endif
	{
		struct timeval tv;
		if (gettimeofday(&tv, NULL) == 0) {
			TIMEVAL_TO_TIMESPEC(&tv, ts);
			return 0;
		}
	}

	return -1;
}

#if USE_LOGFILE
void
logger_open(struct dhcpcd_ctx *ctx)
{

	if (ctx->logfile) {
		int f = O_CREAT | O_APPEND | O_TRUNC;

#ifdef O_CLOEXEC
		f |= O_CLOEXEC;
#endif
		ctx->log_fd = open(ctx->logfile, O_WRONLY | f, 0644);
		if (ctx->log_fd == -1)
			warn("open: %s", ctx->logfile);
#ifndef O_CLOEXEC
		else {
			if (fcntl(ctx->log_fd, F_GETFD, &f) == -1 ||
			    fcntl(ctx->log_fd, F_SETFD, f | FD_CLOEXEC) == -1)
				warn("fcntl: %s", ctx->logfile);
		}
#endif
	} else
		openlog(PACKAGE, LOG_PID, LOG_DAEMON);
}

void
logger_close(struct dhcpcd_ctx *ctx)
{

	if (ctx->log_fd != -1) {
		close(ctx->log_fd);
		ctx->log_fd = -1;
	}
	closelog();
}

void
logger(struct dhcpcd_ctx *ctx, int pri, const char *fmt, ...)
{
	va_list va;
	int serrno;
#ifndef HAVE_PRINTF_M
	char fmt_cpy[1024];
#endif

	if (pri >= LOG_DEBUG && ctx && !(ctx->options & DHCPCD_DEBUG))
		return;

	serrno = errno;
	va_start(va, fmt);

#ifndef HAVE_PRINTF_M
	/* Print strerrno(errno) in place of %m */
	if (ctx == NULL || !(ctx->options & DHCPCD_QUIET) || ctx->log_fd != -1)
	{
		const char *p;
		char *fp = fmt_cpy, *serr = NULL;
		size_t fmt_left = sizeof(fmt_cpy) - 1, fmt_wrote;

		for (p = fmt; *p != '\0'; p++) {
			if (p[0] == '%' && p[1] == '%') {
				if (fmt_left < 2)
					break;
				*fp++ = '%';
				*fp++ = '%';
				fmt_left -= 2;
				p++;
			} else if (p[0] == '%' && p[1] == 'm') {
				if (serr == NULL)
					serr = strerror(serrno);
				fmt_wrote = strlcpy(fp, serr, fmt_left);
				if (fmt_wrote > fmt_left)
					break;
				fp += fmt_wrote;
				fmt_left -= fmt_wrote;
				p++;
			} else {
				*fp++ = *p;
				--fmt_left;
			}
			if (fmt_left == 0)
				break;
		}
		*fp++ = '\0';
		fmt = fmt_cpy;
	}

#endif

	if (ctx == NULL || !(ctx->options & DHCPCD_QUIET)) {
		va_list vac;

		va_copy(vac, va);
		vfprintf(pri <= LOG_ERR ? stderr : stdout, fmt, vac);
		fputc('\n', pri <= LOG_ERR ? stderr : stdout);
		va_end(vac);
	}

#ifdef HAVE_PRINTF_M
	errno = serrno;
#endif
	if (ctx && ctx->log_fd != -1) {
		struct timeval tv;
		char buf[32];

		/* Write the time, syslog style. month day time - */
		if (gettimeofday(&tv, NULL) != -1) {
			time_t now;
			struct tm tmnow;

			tzset();
			now = tv.tv_sec;
			localtime_r(&now, &tmnow);
			strftime(buf, sizeof(buf), "%b %d %T ", &tmnow);
			dprintf(ctx->log_fd, "%s", buf);
		}

		vdprintf(ctx->log_fd, fmt, va);
		dprintf(ctx->log_fd, "\n");
	} else
		vsyslog(pri, fmt, va);
	va_end(va);
}
#endif

ssize_t
setvar(struct dhcpcd_ctx *ctx,
    char ***e, const char *prefix, const char *var, const char *value)
{
	size_t len = strlen(var) + strlen(value) + 3;

	if (prefix)
		len += strlen(prefix) + 1;
	**e = malloc(len);
	if (**e == NULL) {
		logger(ctx, LOG_ERR, "%s: %m", __func__);
		return -1;
	}
	if (prefix)
		snprintf(**e, len, "%s_%s=%s", prefix, var, value);
	else
		snprintf(**e, len, "%s=%s", var, value);
	(*e)++;
	return (ssize_t)len;
}

ssize_t
setvard(struct dhcpcd_ctx *ctx,
    char ***e, const char *prefix, const char *var, size_t value)
{
	char buffer[32];

	snprintf(buffer, sizeof(buffer), "%zu", value);
	return setvar(ctx, e, prefix, var, buffer);
}


time_t
uptime(void)
{
	struct timespec tv;

	if (get_monotonic(&tv) == -1)
		return -1;
	return tv.tv_sec;
}

char *
hwaddr_ntoa(const unsigned char *hwaddr, size_t hwlen, char *buf, size_t buflen)
{
	char *p;
	size_t i;

	if (buf == NULL) {
		return NULL;
	}

	if (hwlen * 3 > buflen) {
		errno = ENOBUFS;
		return 0;
	}

	p = buf;
	for (i = 0; i < hwlen; i++) {
		if (i > 0)
			*p ++= ':';
		p += snprintf(p, 3, "%.2x", hwaddr[i]);
	}
	*p ++= '\0';
	return buf;
}

size_t
hwaddr_aton(unsigned char *buffer, const char *addr)
{
	char c[3];
	const char *p = addr;
	unsigned char *bp = buffer;
	size_t len = 0;

	c[2] = '\0';
	while (*p) {
		c[0] = *p++;
		c[1] = *p++;
		/* Ensure that digits are hex */
		if (isxdigit((unsigned char)c[0]) == 0 ||
		    isxdigit((unsigned char)c[1]) == 0)
		{
			errno = EINVAL;
			return 0;
		}
		/* We should have at least two entries 00:01 */
		if (len == 0 && *p == '\0') {
			errno = EINVAL;
			return 0;
		}
		/* Ensure that next data is EOL or a seperator with data */
		if (!(*p == '\0' || (*p == ':' && *(p + 1) != '\0'))) {
			errno = EINVAL;
			return 0;
		}
		if (*p)
			p++;
		if (bp)
			*bp++ = (unsigned char)strtol(c, NULL, 16);
		len++;
	}
	return len;
}