1/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 */
5
6#include "util.h"
7
8#include <ctype.h>
9#include <errno.h>
10#include <limits.h>
11#include <stdarg.h>
12#include <stdint.h>
13#include <stdio.h>
14#include <string.h>
15
16#include "libconstants.h"
17#include "libsyscalls.h"
18
19/*
20 * These are syscalls used by the syslog() C library call.  You can find them
21 * by running a simple test program.  See below for x86_64 behavior:
22 * $ cat test.c
23 * #include <syslog.h>
24 * main() { syslog(0, "foo"); }
25 * $ gcc test.c -static
26 * $ strace ./a.out
27 * ...
28 * socket(PF_FILE, SOCK_DGRAM|SOCK_CLOEXEC, 0) = 3 <- look for socket connection
29 * connect(...)                                    <- important
30 * sendto(...)                                     <- important
31 * exit_group(0)                                   <- finish!
32 */
33#if defined(__x86_64__)
34#if defined(__ANDROID__)
35const char *log_syscalls[] = {"socket", "connect", "fcntl", "writev"};
36#else
37const char *log_syscalls[] = {"socket", "connect", "sendto"};
38#endif
39#elif defined(__i386__)
40#if defined(__ANDROID__)
41const char *log_syscalls[] = {"socketcall", "writev", "fcntl64",
42			      "clock_gettime"};
43#else
44const char *log_syscalls[] = {"socketcall", "time"};
45#endif
46#elif defined(__arm__)
47#if defined(__ANDROID__)
48const char *log_syscalls[] = {"clock_gettime", "connect", "fcntl64", "socket",
49			      "writev"};
50#else
51const char *log_syscalls[] = {"socket", "connect", "gettimeofday", "send"};
52#endif
53#elif defined(__aarch64__)
54#if defined(__ANDROID__)
55const char *log_syscalls[] = {"connect", "fcntl", "sendto", "socket", "writev"};
56#else
57const char *log_syscalls[] = {"socket", "connect", "send"};
58#endif
59#elif defined(__powerpc__) || defined(__ia64__) || defined(__hppa__) ||        \
60      defined(__sparc__) || defined(__mips__)
61const char *log_syscalls[] = {"socket", "connect", "send"};
62#else
63#error "Unsupported platform"
64#endif
65
66const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
67
68/* clang-format off */
69static struct logging_config_t {
70	/* The logging system to use. The default is syslog. */
71	enum logging_system_t logger;
72
73	/* File descriptor to log to. Only used when logger is LOG_TO_FD. */
74	int fd;
75
76	/* Minimum priority to log. Only used when logger is LOG_TO_FD. */
77	int min_priority;
78} logging_config = {
79	.logger = LOG_TO_SYSLOG,
80};
81/* clang-format on */
82
83void do_log(int priority, const char *format, ...)
84{
85	if (logging_config.logger == LOG_TO_SYSLOG) {
86		va_list args;
87		va_start(args, format);
88		vsyslog(priority, format, args);
89		va_end(args);
90		return;
91	}
92
93	if (logging_config.min_priority < priority)
94		return;
95
96	va_list args;
97	va_start(args, format);
98	vdprintf(logging_config.fd, format, args);
99	va_end(args);
100	dprintf(logging_config.fd, "\n");
101}
102
103int lookup_syscall(const char *name)
104{
105	const struct syscall_entry *entry = syscall_table;
106	for (; entry->name && entry->nr >= 0; ++entry)
107		if (!strcmp(entry->name, name))
108			return entry->nr;
109	return -1;
110}
111
112const char *lookup_syscall_name(int nr)
113{
114	const struct syscall_entry *entry = syscall_table;
115	for (; entry->name && entry->nr >= 0; ++entry)
116		if (entry->nr == nr)
117			return entry->name;
118	return NULL;
119}
120
121long int parse_single_constant(char *constant_str, char **endptr)
122{
123	const struct constant_entry *entry = constant_table;
124	long int res = 0;
125	for (; entry->name; ++entry) {
126		if (!strcmp(entry->name, constant_str)) {
127			if (endptr)
128				*endptr = constant_str + strlen(constant_str);
129
130			return entry->value;
131		}
132	}
133
134	errno = 0;
135	res = strtol(constant_str, endptr, 0);
136	if (errno == ERANGE) {
137		if (res == LONG_MAX) {
138			/* See if the constant fits in an unsigned long int. */
139			errno = 0;
140			res = strtoul(constant_str, endptr, 0);
141			if (errno == ERANGE) {
142				/*
143				 * On unsigned overflow, use the same convention
144				 * as when strtol(3) finds no digits: set
145				 * |*endptr| to |constant_str| and return 0.
146				 */
147				warn("unsigned overflow: '%s'", constant_str);
148				*endptr = constant_str;
149				res = 0;
150			}
151		} else if (res == LONG_MIN) {
152			/*
153			 * Same for signed underflow: set |*endptr| to
154			 * |constant_str| and return 0.
155			 */
156			warn("signed underflow: '%s'", constant_str);
157			*endptr = constant_str;
158			res = 0;
159		}
160	}
161	return res;
162}
163
164long int parse_constant(char *constant_str, char **endptr)
165{
166	long int value = 0;
167	char *group, *lastpos = constant_str;
168	char *original_constant_str = constant_str;
169
170	/*
171	 * Try to parse constants separated by pipes.  Note that since
172	 * |constant_str| is an atom, there can be no spaces between the
173	 * constant and the pipe.  Constants can be either a named constant
174	 * defined in libconstants.gen.c or a number parsed with strtol(3).
175	 *
176	 * If there is an error parsing any of the constants, the whole process
177	 * fails.
178	 */
179	while ((group = tokenize(&constant_str, "|")) != NULL) {
180		char *end = group;
181		value |= parse_single_constant(group, &end);
182		if (end == group) {
183			lastpos = original_constant_str;
184			value = 0;
185			break;
186		}
187		lastpos = end;
188	}
189	if (endptr)
190		*endptr = lastpos;
191	return value;
192}
193
194/*
195 * parse_size, specified as a string with a decimal number in bytes,
196 * possibly with one 1-character suffix like "10K" or "6G".
197 * Assumes both pointers are non-NULL.
198 *
199 * Returns 0 on success, negative errno on failure.
200 * Only writes to result on success.
201 */
202int parse_size(size_t *result, const char *sizespec)
203{
204	const char prefixes[] = "KMGTPE";
205	size_t i, multiplier = 1, nsize, size = 0;
206	unsigned long long parsed;
207	const size_t len = strlen(sizespec);
208	char *end;
209
210	if (len == 0 || sizespec[0] == '-')
211		return -EINVAL;
212
213	for (i = 0; i < sizeof(prefixes); ++i) {
214		if (sizespec[len - 1] == prefixes[i]) {
215#if __WORDSIZE == 32
216			if (i >= 3)
217				return -ERANGE;
218#endif
219			multiplier = 1024;
220			while (i-- > 0)
221				multiplier *= 1024;
222			break;
223		}
224	}
225
226	/* We only need size_t but strtoul(3) is too small on IL32P64. */
227	parsed = strtoull(sizespec, &end, 10);
228	if (parsed == ULLONG_MAX)
229		return -errno;
230	if (parsed >= SIZE_MAX)
231		return -ERANGE;
232	if ((multiplier != 1 && end != sizespec + len - 1) ||
233	    (multiplier == 1 && end != sizespec + len))
234		return -EINVAL;
235	size = (size_t)parsed;
236
237	nsize = size * multiplier;
238	if (nsize / multiplier != size)
239		return -ERANGE;
240	*result = nsize;
241	return 0;
242}
243
244char *strip(char *s)
245{
246	char *end;
247	while (*s && isblank(*s))
248		s++;
249	end = s + strlen(s) - 1;
250	while (end >= s && *end && (isblank(*end) || *end == '\n'))
251		end--;
252	*(end + 1) = '\0';
253	return s;
254}
255
256char *tokenize(char **stringp, const char *delim)
257{
258	char *ret = NULL;
259
260	/* If the string is NULL, there are no tokens to be found. */
261	if (stringp == NULL || *stringp == NULL)
262		return NULL;
263
264	/*
265	 * If the delimiter is NULL or empty,
266	 * the full string makes up the only token.
267	 */
268	if (delim == NULL || *delim == '\0') {
269		ret = *stringp;
270		*stringp = NULL;
271		return ret;
272	}
273
274	char *found = strstr(*stringp, delim);
275	if (!found) {
276		/*
277		 * The delimiter was not found, so the full string
278		 * makes up the only token, and we're done.
279		 */
280		ret = *stringp;
281		*stringp = NULL;
282	} else {
283		/* There's a token here, possibly empty.  That's OK. */
284		*found = '\0';
285		ret = *stringp;
286		*stringp = found + strlen(delim);
287	}
288
289	return ret;
290}
291
292char *path_join(const char *external_path, const char *internal_path)
293{
294	char *path;
295	size_t pathlen;
296
297	/* One extra char for '/' and one for '\0', hence + 2. */
298	pathlen = strlen(external_path) + strlen(internal_path) + 2;
299	path = malloc(pathlen);
300	snprintf(path, pathlen, "%s/%s", external_path, internal_path);
301
302	return path;
303}
304
305void *consumebytes(size_t length, char **buf, size_t *buflength)
306{
307	char *p = *buf;
308	if (length > *buflength)
309		return NULL;
310	*buf += length;
311	*buflength -= length;
312	return p;
313}
314
315char *consumestr(char **buf, size_t *buflength)
316{
317	size_t len = strnlen(*buf, *buflength);
318	if (len == *buflength)
319		/* There's no null-terminator. */
320		return NULL;
321	return consumebytes(len + 1, buf, buflength);
322}
323
324void init_logging(enum logging_system_t logger, int fd, int min_priority)
325{
326	logging_config.logger = logger;
327	logging_config.fd = fd;
328	logging_config.min_priority = min_priority;
329}
330