blob: 48c3059e0d9ee588e8c939c73915506a05428d7a [file] [log] [blame]
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -07001/* 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
Mattias Nisslerb35f2c12020-02-07 13:37:36 +01006#define _GNU_SOURCE
7
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -04008#include "util.h"
9
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070010#include <ctype.h>
Jorge Lucangeli Obesf205fff2016-08-06 09:06:21 -040011#include <errno.h>
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -040012#include <limits.h>
Luis Hector Chavez114a9302017-09-05 20:36:58 -070013#include <stdarg.h>
Luis Hector Chavez466f2312018-10-31 10:44:43 -070014#include <stdbool.h>
Martin Pelikánab9eb442017-01-25 11:53:58 +110015#include <stdint.h>
Luis Hector Chavez40b25742013-09-22 19:44:06 -070016#include <stdio.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070017#include <string.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070018
Luis Hector Chavez40b25742013-09-22 19:44:06 -070019#include "libconstants.h"
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070020#include "libsyscalls.h"
21
Mike Frysingerfccb4c92013-10-19 02:42:07 -040022/*
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
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080026 * #include <syslog.h>
Mike Frysingerfccb4c92013-10-19 02:42:07 -040027 * 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 */
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070036#if defined(__x86_64__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080037#if defined(__ANDROID__)
38const char *log_syscalls[] = {"socket", "connect", "fcntl", "writev"};
Alex Deymo7c6899c2016-01-27 18:24:19 -080039#else
Zach Reiznerb1f517e2018-03-30 16:44:26 -070040const char *log_syscalls[] = {"socket", "connect", "sendto", "writev"};
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080041#endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070042#elif defined(__i386__)
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080043#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080044const char *log_syscalls[] = {"socketcall", "writev", "fcntl64",
45 "clock_gettime"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080046#else
Sonny Rao33d49852018-05-18 13:38:43 -070047const char *log_syscalls[] = {"socketcall", "time", "writev"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080048#endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070049#elif defined(__arm__)
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080050#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080051const char *log_syscalls[] = {"clock_gettime", "connect", "fcntl64", "socket",
52 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080053#else
Sonny Rao33d49852018-05-18 13:38:43 -070054const char *log_syscalls[] = {"socket", "connect", "gettimeofday", "send",
55 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080056#endif
57#elif defined(__aarch64__)
58#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080059const char *log_syscalls[] = {"connect", "fcntl", "sendto", "socket", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080060#else
Sonny Rao33d49852018-05-18 13:38:43 -070061const char *log_syscalls[] = {"socket", "connect", "send", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080062#endif
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080063#elif defined(__powerpc__) || defined(__ia64__) || defined(__hppa__) || \
64 defined(__sparc__) || defined(__mips__)
Mike Frysinger09560862017-09-27 01:13:15 -040065const char *log_syscalls[] = {"socket", "connect", "send"};
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070066#else
67#error "Unsupported platform"
68#endif
69
Mike Frysinger404d2bb2017-01-17 19:29:00 -050070const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070071
Luis Hector Chavez114a9302017-09-05 20:36:58 -070072/* clang-format off */
73static 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
Luis Hector Chavezcc559e82018-07-09 13:26:31 -070087#if defined(USE_EXIT_ON_DIE)
88#define do_abort() exit(1)
89#else
90#define do_abort() abort()
91#endif
92
Luis Hector Chavez31b02652018-07-09 14:14:49 -070093#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|. */
100static void attribute_no_optimize alias(const void *var)
101{
102 (void)var;
103}
104
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700105void do_fatal_log(int priority, const char *format, ...)
106{
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700107 va_list args, stack_args;
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700108 va_start(args, format);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700109 va_copy(stack_args, args);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700110 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);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700117
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);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700129 do_abort();
130}
131
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700132void 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
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700152int lookup_syscall(const char *name)
153{
154 const struct syscall_entry *entry = syscall_table;
155 for (; entry->name && entry->nr >= 0; ++entry)
156 if (!strcmp(entry->name, name))
157 return entry->nr;
158 return -1;
159}
160
161const char *lookup_syscall_name(int nr)
162{
163 const struct syscall_entry *entry = syscall_table;
164 for (; entry->name && entry->nr >= 0; ++entry)
165 if (entry->nr == nr)
166 return entry->name;
167 return NULL;
168}
169
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400170long int parse_single_constant(char *constant_str, char **endptr)
171{
172 const struct constant_entry *entry = constant_table;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400173 long int res = 0;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400174 for (; entry->name; ++entry) {
175 if (!strcmp(entry->name, constant_str)) {
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700176 *endptr = constant_str + strlen(constant_str);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400177 return entry->value;
178 }
179 }
180
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400181 errno = 0;
182 res = strtol(constant_str, endptr, 0);
183 if (errno == ERANGE) {
184 if (res == LONG_MAX) {
185 /* See if the constant fits in an unsigned long int. */
186 errno = 0;
187 res = strtoul(constant_str, endptr, 0);
188 if (errno == ERANGE) {
189 /*
190 * On unsigned overflow, use the same convention
191 * as when strtol(3) finds no digits: set
192 * |*endptr| to |constant_str| and return 0.
193 */
194 warn("unsigned overflow: '%s'", constant_str);
195 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700196 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400197 }
198 } else if (res == LONG_MIN) {
199 /*
200 * Same for signed underflow: set |*endptr| to
201 * |constant_str| and return 0.
202 */
203 warn("signed underflow: '%s'", constant_str);
204 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700205 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400206 }
207 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700208 if (**endptr != '\0') {
209 warn("trailing garbage after constant: '%s'", constant_str);
210 *endptr = constant_str;
211 return 0;
212 }
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400213 return res;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400214}
215
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700216static char *tokenize_parenthesized_expression(char **stringp)
217{
218 char *ret = NULL, *found = NULL;
219 size_t paren_count = 1;
220
221 /* If the string is NULL, there are no parens to be found. */
222 if (stringp == NULL || *stringp == NULL)
223 return NULL;
224
225 /* If the string is not on an open paren, the results are undefined. */
226 if (**stringp != '(')
227 return NULL;
228
229 for (found = *stringp + 1; *found; ++found) {
230 switch (*found) {
231 case '(':
232 ++paren_count;
233 break;
234 case ')':
235 --paren_count;
236 if (!paren_count) {
237 *found = '\0';
238 ret = *stringp + 1;
239 *stringp = found + 1;
240 return ret;
241 }
242 break;
243 }
244 }
245
246 /* We got to the end without finding the closing paren. */
247 warn("unclosed parenthesis: '%s'", *stringp);
248 return NULL;
249}
250
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700251long int parse_constant(char *constant_str, char **endptr)
252{
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700253 long int value = 0, current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000254 char *group, *lastpos = constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000255
256 /*
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700257 * If |endptr| is provided, parsing errors are signaled as |endptr|
258 * pointing to |constant_str|.
259 */
260 if (endptr)
261 *endptr = constant_str;
262
263 /*
264 * Try to parse constant expressions. Valid constant expressions are:
265 *
266 * - A number that can be parsed with strtol(3).
267 * - A named constant expression.
268 * - A parenthesized, valid constant expression.
269 * - A valid constant expression prefixed with the unary bitwise
270 * complement operator ~.
271 * - A series of valid constant expressions separated by pipes. Note
272 * that since |constant_str| is an atom, there can be no spaces
273 * between the constant and the pipe.
Luis Hector Chavez21224552015-06-27 18:10:39 +0000274 *
275 * If there is an error parsing any of the constants, the whole process
276 * fails.
277 */
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700278 while (constant_str && *constant_str) {
279 bool negate = false;
280 if (*constant_str == '~') {
281 negate = true;
282 ++constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000283 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700284 if (*constant_str == '(') {
285 group =
286 tokenize_parenthesized_expression(&constant_str);
287 if (group == NULL)
288 return 0;
289 char *end = group;
290 /* Recursively parse the parenthesized subexpression. */
291 current_value = parse_constant(group, &end);
292 if (end == group)
293 return 0;
294 if (constant_str && *constant_str) {
295 /*
296 * If this is not the end of the atom, there
297 * should be another | followed by more stuff.
298 */
299 if (*constant_str != '|') {
300 warn("unterminated constant "
301 "expression: '%s'",
302 constant_str);
303 return 0;
304 }
305 ++constant_str;
306 if (*constant_str == '\0') {
307 warn("unterminated constant "
308 "expression: '%s'",
309 constant_str);
310 return 0;
311 }
312 }
313 lastpos = end;
314 } else {
315 group = tokenize(&constant_str, "|");
316 char *end = group;
317 current_value = parse_single_constant(group, &end);
318 if (end == group)
319 return 0;
320 lastpos = end;
321 }
322 if (negate)
323 current_value = ~current_value;
324 value |= current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000325 }
326 if (endptr)
327 *endptr = lastpos;
328 return value;
329}
330
Martin Pelikánab9eb442017-01-25 11:53:58 +1100331/*
332 * parse_size, specified as a string with a decimal number in bytes,
333 * possibly with one 1-character suffix like "10K" or "6G".
334 * Assumes both pointers are non-NULL.
335 *
336 * Returns 0 on success, negative errno on failure.
337 * Only writes to result on success.
338 */
339int parse_size(size_t *result, const char *sizespec)
340{
341 const char prefixes[] = "KMGTPE";
342 size_t i, multiplier = 1, nsize, size = 0;
343 unsigned long long parsed;
344 const size_t len = strlen(sizespec);
345 char *end;
346
347 if (len == 0 || sizespec[0] == '-')
348 return -EINVAL;
349
350 for (i = 0; i < sizeof(prefixes); ++i) {
351 if (sizespec[len - 1] == prefixes[i]) {
352#if __WORDSIZE == 32
353 if (i >= 3)
354 return -ERANGE;
355#endif
356 multiplier = 1024;
357 while (i-- > 0)
358 multiplier *= 1024;
359 break;
360 }
361 }
362
363 /* We only need size_t but strtoul(3) is too small on IL32P64. */
364 parsed = strtoull(sizespec, &end, 10);
365 if (parsed == ULLONG_MAX)
366 return -errno;
367 if (parsed >= SIZE_MAX)
368 return -ERANGE;
369 if ((multiplier != 1 && end != sizespec + len - 1) ||
370 (multiplier == 1 && end != sizespec + len))
371 return -EINVAL;
372 size = (size_t)parsed;
373
374 nsize = size * multiplier;
375 if (nsize / multiplier != size)
376 return -ERANGE;
377 *result = nsize;
378 return 0;
379}
380
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700381char *strip(char *s)
382{
383 char *end;
384 while (*s && isblank(*s))
385 s++;
386 end = s + strlen(s) - 1;
387 while (end >= s && *end && (isblank(*end) || *end == '\n'))
388 end--;
389 *(end + 1) = '\0';
390 return s;
391}
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800392
Jorge Lucangeli Obesc8b21e12014-06-13 14:26:16 -0700393char *tokenize(char **stringp, const char *delim)
394{
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800395 char *ret = NULL;
396
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500397 /* If the string is NULL, there are no tokens to be found. */
398 if (stringp == NULL || *stringp == NULL)
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800399 return NULL;
400
401 /*
402 * If the delimiter is NULL or empty,
403 * the full string makes up the only token.
404 */
405 if (delim == NULL || *delim == '\0') {
406 ret = *stringp;
407 *stringp = NULL;
408 return ret;
409 }
410
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500411 char *found = strstr(*stringp, delim);
412 if (!found) {
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800413 /*
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500414 * The delimiter was not found, so the full string
415 * makes up the only token, and we're done.
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800416 */
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500417 ret = *stringp;
418 *stringp = NULL;
419 } else {
420 /* There's a token here, possibly empty. That's OK. */
421 *found = '\0';
422 ret = *stringp;
423 *stringp = found + strlen(delim);
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800424 }
425
426 return ret;
427}
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400428
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400429char *path_join(const char *external_path, const char *internal_path)
430{
431 char *path;
432 size_t pathlen;
433
434 /* One extra char for '/' and one for '\0', hence + 2. */
435 pathlen = strlen(external_path) + strlen(internal_path) + 2;
436 path = malloc(pathlen);
437 snprintf(path, pathlen, "%s/%s", external_path, internal_path);
438
439 return path;
440}
441
442void *consumebytes(size_t length, char **buf, size_t *buflength)
443{
444 char *p = *buf;
445 if (length > *buflength)
446 return NULL;
447 *buf += length;
448 *buflength -= length;
449 return p;
450}
451
452char *consumestr(char **buf, size_t *buflength)
453{
454 size_t len = strnlen(*buf, *buflength);
455 if (len == *buflength)
456 /* There's no null-terminator. */
457 return NULL;
458 return consumebytes(len + 1, buf, buflength);
459}
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700460
461void init_logging(enum logging_system_t logger, int fd, int min_priority)
462{
463 logging_config.logger = logger;
464 logging_config.fd = fd;
465 logging_config.min_priority = min_priority;
466}
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100467
468void minijail_free_env(char **env)
469{
470 if (!env)
471 return;
472
473 for (char **entry = env; *entry; ++entry) {
474 free(*entry);
475 }
476
477 free(env);
478}
479
480char **minijail_copy_env(char *const *env)
481{
482 if (!env)
483 return calloc(1, sizeof(char *));
484
485 int len = 0;
486 while (env[len])
487 ++len;
488
489 char **copy = calloc(len + 1, sizeof(char *));
490 if (!copy)
491 return NULL;
492
493 for (char **entry = copy; *env; ++env, ++entry) {
494 *entry = strdup(*env);
495 if (!*entry) {
496 minijail_free_env(copy);
497 return NULL;
498 }
499 }
500
501 return copy;
502}
503
504int minijail_setenv(char ***env, const char *name, const char *value,
505 int overwrite)
506{
507 if (!env || !*env || !name || !*name || !value)
508 return EINVAL;
509
510 size_t name_len = strlen(name);
511
512 char **dest = NULL;
513 size_t env_len = 0;
514 for (char **entry = *env; *entry; ++entry, ++env_len) {
515 if (!dest && strncmp(name, *entry, name_len) == 0 &&
516 (*entry)[name_len] == '=') {
517 if (!overwrite)
518 return 0;
519
520 dest = entry;
521 }
522 }
523
524 char *new_entry = NULL;
525 if (asprintf(&new_entry, "%s=%s", name, value) == -1)
526 return ENOMEM;
527
528 if (dest) {
529 free(*dest);
530 *dest = new_entry;
531 return 0;
532 }
533
534 env_len++;
535 char **new_env = realloc(*env, (env_len + 1) * sizeof(char *));
536 if (!new_env) {
537 free(new_entry);
538 return ENOMEM;
539 }
540
541 new_env[env_len - 1] = new_entry;
542 new_env[env_len] = NULL;
543 *env = new_env;
544 return 0;
545}