blob: 0926866d2924b2e308ec62b2b7027beda3d1e2af [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
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000152/*
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000153 * Returns the syscall nr and optionally populates the index in the pointer
154 * |ind| if it is non-NULL.
155 */
156int 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;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700164 return entry->nr;
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000165 }
166 ind_tmp++;
167 }
168 if (ind != NULL)
169 *ind = -1;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700170 return -1;
171}
172
173const 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
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400182long int parse_single_constant(char *constant_str, char **endptr)
183{
184 const struct constant_entry *entry = constant_table;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400185 long int res = 0;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400186 for (; entry->name; ++entry) {
187 if (!strcmp(entry->name, constant_str)) {
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700188 *endptr = constant_str + strlen(constant_str);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400189 return entry->value;
190 }
191 }
192
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400193 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;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700208 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400209 }
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;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700217 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400218 }
219 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700220 if (**endptr != '\0') {
221 warn("trailing garbage after constant: '%s'", constant_str);
222 *endptr = constant_str;
223 return 0;
224 }
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400225 return res;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400226}
227
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700228static 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
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700263long int parse_constant(char *constant_str, char **endptr)
264{
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700265 long int value = 0, current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000266 char *group, *lastpos = constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000267
268 /*
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700269 * 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.
Luis Hector Chavez21224552015-06-27 18:10:39 +0000286 *
287 * If there is an error parsing any of the constants, the whole process
288 * fails.
289 */
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700290 while (constant_str && *constant_str) {
291 bool negate = false;
292 if (*constant_str == '~') {
293 negate = true;
294 ++constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000295 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700296 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;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000337 }
338 if (endptr)
339 *endptr = lastpos;
340 return value;
341}
342
Martin Pelikánab9eb442017-01-25 11:53:58 +1100343/*
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 */
351int 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
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700393char *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}
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800404
Jorge Lucangeli Obesc8b21e12014-06-13 14:26:16 -0700405char *tokenize(char **stringp, const char *delim)
406{
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800407 char *ret = NULL;
408
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500409 /* If the string is NULL, there are no tokens to be found. */
410 if (stringp == NULL || *stringp == NULL)
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800411 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
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500423 char *found = strstr(*stringp, delim);
424 if (!found) {
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800425 /*
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500426 * The delimiter was not found, so the full string
427 * makes up the only token, and we're done.
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800428 */
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500429 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);
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800436 }
437
438 return ret;
439}
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400440
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400441char *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);
Mike Frysinger1036cd82020-08-28 00:15:59 -0400449 if (path)
450 snprintf(path, pathlen, "%s/%s", external_path, internal_path);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400451
452 return path;
453}
454
455void *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
465char *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}
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700473
474void 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}
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100480
481void 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
493char **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
517int 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}