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 #define _GNU_SOURCE
7 
8 #include "util.h"
9 
10 #include <ctype.h>
11 #include <errno.h>
12 #include <limits.h>
13 #include <stdarg.h>
14 #include <stdbool.h>
15 #include <stdint.h>
16 #include <stdio.h>
17 #include <string.h>
18 
19 #include "libconstants.h"
20 #include "libsyscalls.h"
21 
22 /*
23  * These are syscalls used by the syslog() C library call.  You can find them
24  * by running a simple test program.  See below for x86_64 behavior:
25  * $ cat test.c
26  * #include <syslog.h>
27  * main() { syslog(0, "foo"); }
28  * $ gcc test.c -static
29  * $ strace ./a.out
30  * ...
31  * socket(PF_FILE, SOCK_DGRAM|SOCK_CLOEXEC, 0) = 3 <- look for socket connection
32  * connect(...)                                    <- important
33  * sendto(...)                                     <- important
34  * exit_group(0)                                   <- finish!
35  */
36 #if defined(__x86_64__)
37 #if defined(__ANDROID__)
38 const char *log_syscalls[] = {"socket", "connect", "fcntl", "writev"};
39 #else
40 const char *log_syscalls[] = {"socket", "connect", "sendto", "writev"};
41 #endif
42 #elif defined(__i386__)
43 #if defined(__ANDROID__)
44 const char *log_syscalls[] = {"socketcall", "writev", "fcntl64",
45 			      "clock_gettime"};
46 #else
47 const char *log_syscalls[] = {"socketcall", "time", "writev"};
48 #endif
49 #elif defined(__arm__)
50 #if defined(__ANDROID__)
51 const char *log_syscalls[] = {"clock_gettime", "connect", "fcntl64", "socket",
52 			      "writev"};
53 #else
54 const char *log_syscalls[] = {"socket", "connect", "gettimeofday", "send",
55 			      "writev"};
56 #endif
57 #elif defined(__aarch64__)
58 #if defined(__ANDROID__)
59 const char *log_syscalls[] = {"connect", "fcntl", "sendto", "socket", "writev"};
60 #else
61 const char *log_syscalls[] = {"socket", "connect", "send", "writev"};
62 #endif
63 #elif defined(__powerpc__) || defined(__ia64__) || defined(__hppa__) ||        \
64       defined(__sparc__) || defined(__mips__)
65 const char *log_syscalls[] = {"socket", "connect", "send"};
66 #else
67 #error "Unsupported platform"
68 #endif
69 
70 const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
71 
72 /* clang-format off */
73 static struct logging_config_t {
74 	/* The logging system to use. The default is syslog. */
75 	enum logging_system_t logger;
76 
77 	/* File descriptor to log to. Only used when logger is LOG_TO_FD. */
78 	int fd;
79 
80 	/* Minimum priority to log. Only used when logger is LOG_TO_FD. */
81 	int min_priority;
82 } logging_config = {
83 	.logger = LOG_TO_SYSLOG,
84 };
85 /* clang-format on */
86 
87 #if defined(USE_EXIT_ON_DIE)
88 #define do_abort() exit(1)
89 #else
90 #define do_abort() abort()
91 #endif
92 
93 #if defined(__clang__)
94 #define attribute_no_optimize __attribute__((optnone))
95 #else
96 #define attribute_no_optimize __attribute__((__optimize__(0)))
97 #endif
98 
99 /* Forces the compiler to perform no optimizations on |var|. */
alias(const void * var)100 static void attribute_no_optimize alias(const void *var)
101 {
102 	(void)var;
103 }
104 
do_fatal_log(int priority,const char * format,...)105 void do_fatal_log(int priority, const char *format, ...)
106 {
107 	va_list args, stack_args;
108 	va_start(args, format);
109 	va_copy(stack_args, args);
110 	if (logging_config.logger == LOG_TO_SYSLOG) {
111 		vsyslog(priority, format, args);
112 	} else {
113 		vdprintf(logging_config.fd, format, args);
114 		dprintf(logging_config.fd, "\n");
115 	}
116 	va_end(args);
117 
118 	/*
119 	 * Write another copy of the first few characters of the message into a
120 	 * stack-based buffer so that it can appear in minidumps. Choosing a
121 	 * small-ish buffer size since breakpad will only pick up the first few
122 	 * kilobytes of each stack, so that will prevent this buffer from
123 	 * kicking out other stack frames.
124 	 */
125 	char log_line[512];
126 	vsnprintf(log_line, sizeof(log_line), format, stack_args);
127 	va_end(stack_args);
128 	alias(log_line);
129 	do_abort();
130 }
131 
do_log(int priority,const char * format,...)132 void do_log(int priority, const char *format, ...)
133 {
134 	if (logging_config.logger == LOG_TO_SYSLOG) {
135 		va_list args;
136 		va_start(args, format);
137 		vsyslog(priority, format, args);
138 		va_end(args);
139 		return;
140 	}
141 
142 	if (logging_config.min_priority < priority)
143 		return;
144 
145 	va_list args;
146 	va_start(args, format);
147 	vdprintf(logging_config.fd, format, args);
148 	va_end(args);
149 	dprintf(logging_config.fd, "\n");
150 }
151 
152 /*
153  * Returns the syscall nr and optionally populates the index in the pointer
154  * |ind| if it is non-NULL.
155  */
lookup_syscall(const char * name,size_t * ind)156 int lookup_syscall(const char *name, size_t *ind)
157 {
158 	size_t ind_tmp = 0;
159 	const struct syscall_entry *entry = syscall_table;
160 	for (; entry->name && entry->nr >= 0; ++entry) {
161 		if (!strcmp(entry->name, name)) {
162 			if (ind != NULL)
163 				*ind = ind_tmp;
164 			return entry->nr;
165 		}
166 		ind_tmp++;
167 	}
168 	if (ind != NULL)
169 		*ind = -1;
170 	return -1;
171 }
172 
lookup_syscall_name(int nr)173 const char *lookup_syscall_name(int nr)
174 {
175 	const struct syscall_entry *entry = syscall_table;
176 	for (; entry->name && entry->nr >= 0; ++entry)
177 		if (entry->nr == nr)
178 			return entry->name;
179 	return NULL;
180 }
181 
parse_single_constant(char * constant_str,char ** endptr)182 long int parse_single_constant(char *constant_str, char **endptr)
183 {
184 	const struct constant_entry *entry = constant_table;
185 	long int res = 0;
186 	for (; entry->name; ++entry) {
187 		if (!strcmp(entry->name, constant_str)) {
188 			*endptr = constant_str + strlen(constant_str);
189 			return entry->value;
190 		}
191 	}
192 
193 	errno = 0;
194 	res = strtol(constant_str, endptr, 0);
195 	if (errno == ERANGE) {
196 		if (res == LONG_MAX) {
197 			/* See if the constant fits in an unsigned long int. */
198 			errno = 0;
199 			res = strtoul(constant_str, endptr, 0);
200 			if (errno == ERANGE) {
201 				/*
202 				 * On unsigned overflow, use the same convention
203 				 * as when strtol(3) finds no digits: set
204 				 * |*endptr| to |constant_str| and return 0.
205 				 */
206 				warn("unsigned overflow: '%s'", constant_str);
207 				*endptr = constant_str;
208 				return 0;
209 			}
210 		} else if (res == LONG_MIN) {
211 			/*
212 			 * Same for signed underflow: set |*endptr| to
213 			 * |constant_str| and return 0.
214 			 */
215 			warn("signed underflow: '%s'", constant_str);
216 			*endptr = constant_str;
217 			return 0;
218 		}
219 	}
220 	if (**endptr != '\0') {
221 		warn("trailing garbage after constant: '%s'", constant_str);
222 		*endptr = constant_str;
223 		return 0;
224 	}
225 	return res;
226 }
227 
tokenize_parenthesized_expression(char ** stringp)228 static char *tokenize_parenthesized_expression(char **stringp)
229 {
230 	char *ret = NULL, *found = NULL;
231 	size_t paren_count = 1;
232 
233 	/* If the string is NULL, there are no parens to be found. */
234 	if (stringp == NULL || *stringp == NULL)
235 		return NULL;
236 
237 	/* If the string is not on an open paren, the results are undefined. */
238 	if (**stringp != '(')
239 		return NULL;
240 
241 	for (found = *stringp + 1; *found; ++found) {
242 		switch (*found) {
243 		case '(':
244 			++paren_count;
245 			break;
246 		case ')':
247 			--paren_count;
248 			if (!paren_count) {
249 				*found = '\0';
250 				ret = *stringp + 1;
251 				*stringp = found + 1;
252 				return ret;
253 			}
254 			break;
255 		}
256 	}
257 
258 	/* We got to the end without finding the closing paren. */
259 	warn("unclosed parenthesis: '%s'", *stringp);
260 	return NULL;
261 }
262 
parse_constant(char * constant_str,char ** endptr)263 long int parse_constant(char *constant_str, char **endptr)
264 {
265 	long int value = 0, current_value;
266 	char *group, *lastpos = constant_str;
267 
268 	/*
269 	 * If |endptr| is provided, parsing errors are signaled as |endptr|
270 	 * pointing to |constant_str|.
271 	 */
272 	if (endptr)
273 		*endptr = constant_str;
274 
275 	/*
276 	 * Try to parse constant expressions. Valid constant expressions are:
277 	 *
278 	 * - A number that can be parsed with strtol(3).
279 	 * - A named constant expression.
280 	 * - A parenthesized, valid constant expression.
281 	 * - A valid constant expression prefixed with the unary bitwise
282 	 *   complement operator ~.
283 	 * - A series of valid constant expressions separated by pipes.  Note
284 	 *   that since |constant_str| is an atom, there can be no spaces
285 	 *   between the constant and the pipe.
286 	 *
287 	 * If there is an error parsing any of the constants, the whole process
288 	 * fails.
289 	 */
290 	while (constant_str && *constant_str) {
291 		bool negate = false;
292 		if (*constant_str == '~') {
293 			negate = true;
294 			++constant_str;
295 		}
296 		if (*constant_str == '(') {
297 			group =
298 			    tokenize_parenthesized_expression(&constant_str);
299 			if (group == NULL)
300 				return 0;
301 			char *end = group;
302 			/* Recursively parse the parenthesized subexpression. */
303 			current_value = parse_constant(group, &end);
304 			if (end == group)
305 				return 0;
306 			if (constant_str && *constant_str) {
307 				/*
308 				 * If this is not the end of the atom, there
309 				 * should be another | followed by more stuff.
310 				 */
311 				if (*constant_str != '|') {
312 					warn("unterminated constant "
313 					     "expression: '%s'",
314 					     constant_str);
315 					return 0;
316 				}
317 				++constant_str;
318 				if (*constant_str == '\0') {
319 					warn("unterminated constant "
320 					     "expression: '%s'",
321 					     constant_str);
322 					return 0;
323 				}
324 			}
325 			lastpos = end;
326 		} else {
327 			group = tokenize(&constant_str, "|");
328 			char *end = group;
329 			current_value = parse_single_constant(group, &end);
330 			if (end == group)
331 				return 0;
332 			lastpos = end;
333 		}
334 		if (negate)
335 			current_value = ~current_value;
336 		value |= current_value;
337 	}
338 	if (endptr)
339 		*endptr = lastpos;
340 	return value;
341 }
342 
343 /*
344  * parse_size, specified as a string with a decimal number in bytes,
345  * possibly with one 1-character suffix like "10K" or "6G".
346  * Assumes both pointers are non-NULL.
347  *
348  * Returns 0 on success, negative errno on failure.
349  * Only writes to result on success.
350  */
parse_size(size_t * result,const char * sizespec)351 int parse_size(size_t *result, const char *sizespec)
352 {
353 	const char prefixes[] = "KMGTPE";
354 	size_t i, multiplier = 1, nsize, size = 0;
355 	unsigned long long parsed;
356 	const size_t len = strlen(sizespec);
357 	char *end;
358 
359 	if (len == 0 || sizespec[0] == '-')
360 		return -EINVAL;
361 
362 	for (i = 0; i < sizeof(prefixes); ++i) {
363 		if (sizespec[len - 1] == prefixes[i]) {
364 #if __WORDSIZE == 32
365 			if (i >= 3)
366 				return -ERANGE;
367 #endif
368 			multiplier = 1024;
369 			while (i-- > 0)
370 				multiplier *= 1024;
371 			break;
372 		}
373 	}
374 
375 	/* We only need size_t but strtoul(3) is too small on IL32P64. */
376 	parsed = strtoull(sizespec, &end, 10);
377 	if (parsed == ULLONG_MAX)
378 		return -errno;
379 	if (parsed >= SIZE_MAX)
380 		return -ERANGE;
381 	if ((multiplier != 1 && end != sizespec + len - 1) ||
382 	    (multiplier == 1 && end != sizespec + len))
383 		return -EINVAL;
384 	size = (size_t)parsed;
385 
386 	nsize = size * multiplier;
387 	if (nsize / multiplier != size)
388 		return -ERANGE;
389 	*result = nsize;
390 	return 0;
391 }
392 
strip(char * s)393 char *strip(char *s)
394 {
395 	char *end;
396 	while (*s && isblank(*s))
397 		s++;
398 	end = s + strlen(s) - 1;
399 	while (end >= s && *end && (isblank(*end) || *end == '\n'))
400 		end--;
401 	*(end + 1) = '\0';
402 	return s;
403 }
404 
tokenize(char ** stringp,const char * delim)405 char *tokenize(char **stringp, const char *delim)
406 {
407 	char *ret = NULL;
408 
409 	/* If the string is NULL, there are no tokens to be found. */
410 	if (stringp == NULL || *stringp == NULL)
411 		return NULL;
412 
413 	/*
414 	 * If the delimiter is NULL or empty,
415 	 * the full string makes up the only token.
416 	 */
417 	if (delim == NULL || *delim == '\0') {
418 		ret = *stringp;
419 		*stringp = NULL;
420 		return ret;
421 	}
422 
423 	char *found = strstr(*stringp, delim);
424 	if (!found) {
425 		/*
426 		 * The delimiter was not found, so the full string
427 		 * makes up the only token, and we're done.
428 		 */
429 		ret = *stringp;
430 		*stringp = NULL;
431 	} else {
432 		/* There's a token here, possibly empty.  That's OK. */
433 		*found = '\0';
434 		ret = *stringp;
435 		*stringp = found + strlen(delim);
436 	}
437 
438 	return ret;
439 }
440 
path_join(const char * external_path,const char * internal_path)441 char *path_join(const char *external_path, const char *internal_path)
442 {
443 	char *path;
444 	size_t pathlen;
445 
446 	/* One extra char for '/' and one for '\0', hence + 2. */
447 	pathlen = strlen(external_path) + strlen(internal_path) + 2;
448 	path = malloc(pathlen);
449 	if (path)
450 		snprintf(path, pathlen, "%s/%s", external_path, internal_path);
451 
452 	return path;
453 }
454 
consumebytes(size_t length,char ** buf,size_t * buflength)455 void *consumebytes(size_t length, char **buf, size_t *buflength)
456 {
457 	char *p = *buf;
458 	if (length > *buflength)
459 		return NULL;
460 	*buf += length;
461 	*buflength -= length;
462 	return p;
463 }
464 
consumestr(char ** buf,size_t * buflength)465 char *consumestr(char **buf, size_t *buflength)
466 {
467 	size_t len = strnlen(*buf, *buflength);
468 	if (len == *buflength)
469 		/* There's no null-terminator. */
470 		return NULL;
471 	return consumebytes(len + 1, buf, buflength);
472 }
473 
init_logging(enum logging_system_t logger,int fd,int min_priority)474 void init_logging(enum logging_system_t logger, int fd, int min_priority)
475 {
476 	logging_config.logger = logger;
477 	logging_config.fd = fd;
478 	logging_config.min_priority = min_priority;
479 }
480 
minijail_free_env(char ** env)481 void minijail_free_env(char **env)
482 {
483 	if (!env)
484 		return;
485 
486 	for (char **entry = env; *entry; ++entry) {
487 		free(*entry);
488 	}
489 
490 	free(env);
491 }
492 
minijail_copy_env(char * const * env)493 char **minijail_copy_env(char *const *env)
494 {
495 	if (!env)
496 		return calloc(1, sizeof(char *));
497 
498 	int len = 0;
499 	while (env[len])
500 		++len;
501 
502 	char **copy = calloc(len + 1, sizeof(char *));
503 	if (!copy)
504 		return NULL;
505 
506 	for (char **entry = copy; *env; ++env, ++entry) {
507 		*entry = strdup(*env);
508 		if (!*entry) {
509 			minijail_free_env(copy);
510 			return NULL;
511 		}
512 	}
513 
514 	return copy;
515 }
516 
minijail_setenv(char *** env,const char * name,const char * value,int overwrite)517 int minijail_setenv(char ***env, const char *name, const char *value,
518 		    int overwrite)
519 {
520 	if (!env || !*env || !name || !*name || !value)
521 		return EINVAL;
522 
523 	size_t name_len = strlen(name);
524 
525 	char **dest = NULL;
526 	size_t env_len = 0;
527 	for (char **entry = *env; *entry; ++entry, ++env_len) {
528 		if (!dest && strncmp(name, *entry, name_len) == 0 &&
529 		    (*entry)[name_len] == '=') {
530 			if (!overwrite)
531 				return 0;
532 
533 			dest = entry;
534 		}
535 	}
536 
537 	char *new_entry = NULL;
538 	if (asprintf(&new_entry, "%s=%s", name, value) == -1)
539 		return ENOMEM;
540 
541 	if (dest) {
542 		free(*dest);
543 		*dest = new_entry;
544 		return 0;
545 	}
546 
547 	env_len++;
548 	char **new_env = realloc(*env, (env_len + 1) * sizeof(char *));
549 	if (!new_env) {
550 		free(new_entry);
551 		return ENOMEM;
552 	}
553 
554 	new_env[env_len - 1] = new_entry;
555 	new_env[env_len] = NULL;
556 	*env = new_env;
557 	return 0;
558 }
559