blob: 8a542d69f16f018df66ed6e90ef6616a5acee180 [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__)
Mike Frysinger70674982021-11-23 00:07:14 -050038const char *const log_syscalls[] = {"socket", "connect", "fcntl", "writev"};
Alex Deymo7c6899c2016-01-27 18:24:19 -080039#else
Mike Frysinger70674982021-11-23 00:07:14 -050040const char *const 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__)
Mike Frysinger70674982021-11-23 00:07:14 -050044const char *const log_syscalls[] = {"socketcall", "writev", "fcntl64",
45 "clock_gettime"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080046#else
Mike Frysinger70674982021-11-23 00:07:14 -050047const char *const 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__)
Mike Frysinger70674982021-11-23 00:07:14 -050051const char *const log_syscalls[] = {"clock_gettime", "connect", "fcntl64",
52 "socket", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080053#else
Mike Frysinger70674982021-11-23 00:07:14 -050054const char *const 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__)
Mike Frysinger70674982021-11-23 00:07:14 -050059const char *const log_syscalls[] = {"connect", "fcntl", "sendto", "socket",
60 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080061#else
Mike Frysinger70674982021-11-23 00:07:14 -050062const char *const log_syscalls[] = {"socket", "connect", "send", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080063#endif
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080064#elif defined(__powerpc__) || defined(__ia64__) || defined(__hppa__) || \
Mike Frysinger70674982021-11-23 00:07:14 -050065 defined(__sparc__) || defined(__mips__)
66const char *const log_syscalls[] = {"socket", "connect", "send"};
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070067#else
68#error "Unsupported platform"
69#endif
70
Mike Frysinger404d2bb2017-01-17 19:29:00 -050071const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070072
Luis Hector Chavez114a9302017-09-05 20:36:58 -070073/* clang-format off */
74static struct logging_config_t {
75 /* The logging system to use. The default is syslog. */
76 enum logging_system_t logger;
77
78 /* File descriptor to log to. Only used when logger is LOG_TO_FD. */
79 int fd;
80
81 /* Minimum priority to log. Only used when logger is LOG_TO_FD. */
82 int min_priority;
83} logging_config = {
84 .logger = LOG_TO_SYSLOG,
85};
86/* clang-format on */
87
Luis Hector Chavezcc559e82018-07-09 13:26:31 -070088#if defined(USE_EXIT_ON_DIE)
89#define do_abort() exit(1)
90#else
91#define do_abort() abort()
92#endif
93
Luis Hector Chavez31b02652018-07-09 14:14:49 -070094#if defined(__clang__)
95#define attribute_no_optimize __attribute__((optnone))
96#else
97#define attribute_no_optimize __attribute__((__optimize__(0)))
98#endif
99
100/* Forces the compiler to perform no optimizations on |var|. */
101static void attribute_no_optimize alias(const void *var)
102{
103 (void)var;
104}
105
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700106void do_fatal_log(int priority, const char *format, ...)
107{
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700108 va_list args, stack_args;
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700109 va_start(args, format);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700110 va_copy(stack_args, args);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700111 if (logging_config.logger == LOG_TO_SYSLOG) {
112 vsyslog(priority, format, args);
113 } else {
114 vdprintf(logging_config.fd, format, args);
115 dprintf(logging_config.fd, "\n");
116 }
117 va_end(args);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700118
119 /*
120 * Write another copy of the first few characters of the message into a
121 * stack-based buffer so that it can appear in minidumps. Choosing a
122 * small-ish buffer size since breakpad will only pick up the first few
123 * kilobytes of each stack, so that will prevent this buffer from
124 * kicking out other stack frames.
125 */
126 char log_line[512];
127 vsnprintf(log_line, sizeof(log_line), format, stack_args);
128 va_end(stack_args);
129 alias(log_line);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700130 do_abort();
131}
132
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700133void do_log(int priority, const char *format, ...)
134{
135 if (logging_config.logger == LOG_TO_SYSLOG) {
136 va_list args;
137 va_start(args, format);
138 vsyslog(priority, format, args);
139 va_end(args);
140 return;
141 }
142
143 if (logging_config.min_priority < priority)
144 return;
145
146 va_list args;
147 va_start(args, format);
148 vdprintf(logging_config.fd, format, args);
149 va_end(args);
150 dprintf(logging_config.fd, "\n");
151}
152
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000153/*
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000154 * Returns the syscall nr and optionally populates the index in the pointer
155 * |ind| if it is non-NULL.
156 */
157int lookup_syscall(const char *name, size_t *ind)
158{
159 size_t ind_tmp = 0;
160 const struct syscall_entry *entry = syscall_table;
161 for (; entry->name && entry->nr >= 0; ++entry) {
162 if (!strcmp(entry->name, name)) {
163 if (ind != NULL)
164 *ind = ind_tmp;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700165 return entry->nr;
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000166 }
167 ind_tmp++;
168 }
169 if (ind != NULL)
170 *ind = -1;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700171 return -1;
172}
173
174const char *lookup_syscall_name(int nr)
175{
176 const struct syscall_entry *entry = syscall_table;
177 for (; entry->name && entry->nr >= 0; ++entry)
178 if (entry->nr == nr)
179 return entry->name;
180 return NULL;
181}
182
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400183long int parse_single_constant(char *constant_str, char **endptr)
184{
185 const struct constant_entry *entry = constant_table;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400186 long int res = 0;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400187 for (; entry->name; ++entry) {
188 if (!strcmp(entry->name, constant_str)) {
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700189 *endptr = constant_str + strlen(constant_str);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400190 return entry->value;
191 }
192 }
193
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400194 errno = 0;
195 res = strtol(constant_str, endptr, 0);
196 if (errno == ERANGE) {
197 if (res == LONG_MAX) {
198 /* See if the constant fits in an unsigned long int. */
199 errno = 0;
200 res = strtoul(constant_str, endptr, 0);
201 if (errno == ERANGE) {
202 /*
203 * On unsigned overflow, use the same convention
204 * as when strtol(3) finds no digits: set
205 * |*endptr| to |constant_str| and return 0.
206 */
207 warn("unsigned overflow: '%s'", constant_str);
208 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700209 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400210 }
211 } else if (res == LONG_MIN) {
212 /*
213 * Same for signed underflow: set |*endptr| to
214 * |constant_str| and return 0.
215 */
216 warn("signed underflow: '%s'", constant_str);
217 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700218 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400219 }
220 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700221 if (**endptr != '\0') {
222 warn("trailing garbage after constant: '%s'", constant_str);
223 *endptr = constant_str;
224 return 0;
225 }
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400226 return res;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400227}
228
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700229static char *tokenize_parenthesized_expression(char **stringp)
230{
231 char *ret = NULL, *found = NULL;
232 size_t paren_count = 1;
233
234 /* If the string is NULL, there are no parens to be found. */
235 if (stringp == NULL || *stringp == NULL)
236 return NULL;
237
238 /* If the string is not on an open paren, the results are undefined. */
239 if (**stringp != '(')
240 return NULL;
241
242 for (found = *stringp + 1; *found; ++found) {
243 switch (*found) {
244 case '(':
245 ++paren_count;
246 break;
247 case ')':
248 --paren_count;
249 if (!paren_count) {
250 *found = '\0';
251 ret = *stringp + 1;
252 *stringp = found + 1;
253 return ret;
254 }
255 break;
256 }
257 }
258
259 /* We got to the end without finding the closing paren. */
260 warn("unclosed parenthesis: '%s'", *stringp);
261 return NULL;
262}
263
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700264long int parse_constant(char *constant_str, char **endptr)
265{
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700266 long int value = 0, current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000267 char *group, *lastpos = constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000268
269 /*
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700270 * If |endptr| is provided, parsing errors are signaled as |endptr|
271 * pointing to |constant_str|.
272 */
273 if (endptr)
274 *endptr = constant_str;
275
276 /*
277 * Try to parse constant expressions. Valid constant expressions are:
278 *
279 * - A number that can be parsed with strtol(3).
280 * - A named constant expression.
281 * - A parenthesized, valid constant expression.
282 * - A valid constant expression prefixed with the unary bitwise
283 * complement operator ~.
284 * - A series of valid constant expressions separated by pipes. Note
285 * that since |constant_str| is an atom, there can be no spaces
286 * between the constant and the pipe.
Luis Hector Chavez21224552015-06-27 18:10:39 +0000287 *
288 * If there is an error parsing any of the constants, the whole process
289 * fails.
290 */
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700291 while (constant_str && *constant_str) {
292 bool negate = false;
293 if (*constant_str == '~') {
294 negate = true;
295 ++constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000296 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700297 if (*constant_str == '(') {
298 group =
299 tokenize_parenthesized_expression(&constant_str);
300 if (group == NULL)
301 return 0;
302 char *end = group;
303 /* Recursively parse the parenthesized subexpression. */
304 current_value = parse_constant(group, &end);
305 if (end == group)
306 return 0;
307 if (constant_str && *constant_str) {
308 /*
309 * If this is not the end of the atom, there
310 * should be another | followed by more stuff.
311 */
312 if (*constant_str != '|') {
313 warn("unterminated constant "
314 "expression: '%s'",
315 constant_str);
316 return 0;
317 }
318 ++constant_str;
319 if (*constant_str == '\0') {
320 warn("unterminated constant "
321 "expression: '%s'",
322 constant_str);
323 return 0;
324 }
325 }
326 lastpos = end;
327 } else {
328 group = tokenize(&constant_str, "|");
329 char *end = group;
330 current_value = parse_single_constant(group, &end);
331 if (end == group)
332 return 0;
333 lastpos = end;
334 }
335 if (negate)
336 current_value = ~current_value;
337 value |= current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000338 }
339 if (endptr)
340 *endptr = lastpos;
341 return value;
342}
343
Martin Pelikánab9eb442017-01-25 11:53:58 +1100344/*
345 * parse_size, specified as a string with a decimal number in bytes,
346 * possibly with one 1-character suffix like "10K" or "6G".
347 * Assumes both pointers are non-NULL.
348 *
349 * Returns 0 on success, negative errno on failure.
350 * Only writes to result on success.
351 */
352int parse_size(size_t *result, const char *sizespec)
353{
354 const char prefixes[] = "KMGTPE";
355 size_t i, multiplier = 1, nsize, size = 0;
356 unsigned long long parsed;
357 const size_t len = strlen(sizespec);
358 char *end;
359
360 if (len == 0 || sizespec[0] == '-')
361 return -EINVAL;
362
363 for (i = 0; i < sizeof(prefixes); ++i) {
364 if (sizespec[len - 1] == prefixes[i]) {
365#if __WORDSIZE == 32
366 if (i >= 3)
367 return -ERANGE;
368#endif
369 multiplier = 1024;
370 while (i-- > 0)
371 multiplier *= 1024;
372 break;
373 }
374 }
375
376 /* We only need size_t but strtoul(3) is too small on IL32P64. */
377 parsed = strtoull(sizespec, &end, 10);
378 if (parsed == ULLONG_MAX)
379 return -errno;
380 if (parsed >= SIZE_MAX)
381 return -ERANGE;
382 if ((multiplier != 1 && end != sizespec + len - 1) ||
383 (multiplier == 1 && end != sizespec + len))
384 return -EINVAL;
385 size = (size_t)parsed;
386
387 nsize = size * multiplier;
388 if (nsize / multiplier != size)
389 return -ERANGE;
390 *result = nsize;
391 return 0;
392}
393
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700394char *strip(char *s)
395{
396 char *end;
397 while (*s && isblank(*s))
398 s++;
399 end = s + strlen(s) - 1;
400 while (end >= s && *end && (isblank(*end) || *end == '\n'))
401 end--;
402 *(end + 1) = '\0';
403 return s;
404}
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800405
Jorge Lucangeli Obesc8b21e12014-06-13 14:26:16 -0700406char *tokenize(char **stringp, const char *delim)
407{
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800408 char *ret = NULL;
409
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500410 /* If the string is NULL, there are no tokens to be found. */
411 if (stringp == NULL || *stringp == NULL)
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800412 return NULL;
413
414 /*
415 * If the delimiter is NULL or empty,
416 * the full string makes up the only token.
417 */
418 if (delim == NULL || *delim == '\0') {
419 ret = *stringp;
420 *stringp = NULL;
421 return ret;
422 }
423
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500424 char *found = strstr(*stringp, delim);
425 if (!found) {
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800426 /*
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500427 * The delimiter was not found, so the full string
428 * makes up the only token, and we're done.
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800429 */
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500430 ret = *stringp;
431 *stringp = NULL;
432 } else {
433 /* There's a token here, possibly empty. That's OK. */
434 *found = '\0';
435 ret = *stringp;
436 *stringp = found + strlen(delim);
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800437 }
438
439 return ret;
440}
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400441
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400442char *path_join(const char *external_path, const char *internal_path)
443{
Mike Frysinger572bab22021-10-27 03:02:44 -0400444 char *path = NULL;
445 return asprintf(&path, "%s/%s", external_path, internal_path) < 0
446 ? NULL
447 : path;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400448}
449
450void *consumebytes(size_t length, char **buf, size_t *buflength)
451{
452 char *p = *buf;
453 if (length > *buflength)
454 return NULL;
455 *buf += length;
456 *buflength -= length;
457 return p;
458}
459
460char *consumestr(char **buf, size_t *buflength)
461{
462 size_t len = strnlen(*buf, *buflength);
463 if (len == *buflength)
464 /* There's no null-terminator. */
465 return NULL;
466 return consumebytes(len + 1, buf, buflength);
467}
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700468
469void init_logging(enum logging_system_t logger, int fd, int min_priority)
470{
471 logging_config.logger = logger;
472 logging_config.fd = fd;
473 logging_config.min_priority = min_priority;
474}
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100475
476void minijail_free_env(char **env)
477{
478 if (!env)
479 return;
480
481 for (char **entry = env; *entry; ++entry) {
482 free(*entry);
483 }
484
485 free(env);
486}
487
488char **minijail_copy_env(char *const *env)
489{
490 if (!env)
491 return calloc(1, sizeof(char *));
492
493 int len = 0;
494 while (env[len])
495 ++len;
496
497 char **copy = calloc(len + 1, sizeof(char *));
498 if (!copy)
499 return NULL;
500
501 for (char **entry = copy; *env; ++env, ++entry) {
502 *entry = strdup(*env);
503 if (!*entry) {
504 minijail_free_env(copy);
505 return NULL;
506 }
507 }
508
509 return copy;
510}
511
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100512/*
513 * Utility function used by minijail_setenv, minijail_unsetenv and
514 * minijail_getenv, returns true if |name| is found, false if not.
515 * If found, |*i| is |name|'s index. If not, |*i| is the length of |envp|.
516 */
517static bool getenv_index(char **envp, const char *name, int *i) {
518 if (!envp || !name || !i)
519 return false;
520
521 size_t name_len = strlen(name);
522 for (*i = 0; envp[*i]; ++(*i)) {
523 /*
524 * If we find a match the size of |name|, we must check
525 * that the next character is a '=', indicating that
526 * the full varname of envp[i] is exactly |name| and
527 * not just happening to start with |name|.
528 */
529 if (!strncmp(envp[*i], name, name_len) &&
530 (envp[*i][name_len] == '=')) {
531 return true;
532 }
533 }
534 /* No match found, |*i| contains the number of elements in |envp|. */
535 return false;
536}
537
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100538int minijail_setenv(char ***env, const char *name, const char *value,
539 int overwrite)
540{
541 if (!env || !*env || !name || !*name || !value)
542 return EINVAL;
543
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100544 char **dest = NULL;
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100545 int i;
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100546
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100547 /* Look in env to check if this var name already exists. */
548 if (getenv_index(*env, name, &i)) {
549 if (!overwrite)
550 return 0;
551 dest = &(*env)[i];
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100552 }
553
554 char *new_entry = NULL;
555 if (asprintf(&new_entry, "%s=%s", name, value) == -1)
556 return ENOMEM;
557
558 if (dest) {
559 free(*dest);
560 *dest = new_entry;
561 return 0;
562 }
563
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100564 /* getenv_index has set |i| to the length of |env|. */
565 ++i;
566 char **new_env = realloc(*env, (i + 1) * sizeof(char *));
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100567 if (!new_env) {
568 free(new_entry);
569 return ENOMEM;
570 }
571
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100572 new_env[i - 1] = new_entry;
573 new_env[i] = NULL;
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100574 *env = new_env;
575 return 0;
576}
Zi Lin2c794452021-10-13 03:07:07 +0000577
578/*
579 * This is like getline() but supports line wrapping with \.
580 */
581ssize_t getmultiline(char **lineptr, size_t *n, FILE *stream)
582{
583 ssize_t ret = getline(lineptr, n, stream);
584 if (ret < 0)
585 return ret;
586
587 char *line = *lineptr;
588 /* Eat the newline to make processing below easier. */
589 if (ret > 0 && line[ret - 1] == '\n')
590 line[--ret] = '\0';
591
592 /* If the line doesn't end in a backslash, we're done. */
593 if (ret <= 0 || line[ret - 1] != '\\')
594 return ret;
595
596 /* This line ends in a backslash. Get the nextline. */
597 line[--ret] = '\0';
598 size_t next_n = 0;
Mike Frysingere933fce2021-10-02 01:28:06 -0400599 attribute_cleanup_str char *next_line = NULL;
Zi Lin2c794452021-10-13 03:07:07 +0000600 ssize_t next_ret = getmultiline(&next_line, &next_n, stream);
601 if (next_ret == -1) {
Zi Lin2c794452021-10-13 03:07:07 +0000602 /* We couldn't fully read the line, so return an error. */
603 return -1;
604 }
605
606 /* Merge the lines. */
607 *n = ret + next_ret + 2;
608 line = realloc(line, *n);
Mike Frysingere933fce2021-10-02 01:28:06 -0400609 if (!line)
Zi Lin2c794452021-10-13 03:07:07 +0000610 return -1;
Zi Lin2c794452021-10-13 03:07:07 +0000611 line[ret] = ' ';
612 memcpy(&line[ret + 1], next_line, next_ret + 1);
Zi Lin2c794452021-10-13 03:07:07 +0000613 *lineptr = line;
614 return *n - 1;
615}
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100616
617char *minijail_getenv(char **envp, const char *name) {
618 if (!envp || !name)
619 return NULL;
620
621 int i;
622 if (!getenv_index(envp, name, &i))
623 return NULL;
624
625 /* Return a ptr to the value after the '='. */
626 return envp[i] + strlen(name) + 1;
627}
628
629bool minijail_unsetenv(char **envp, const char *name)
630{
631 if (!envp || !name)
632 return false;
633
634 int i;
635 if (!getenv_index(envp, name, &i))
636 return false;
637
638 /* We found a match, replace it by the last entry of the array. */
639 int last;
640 for (last = i; envp[last]; ++last)
641 continue;
642 --last;
643 envp[i] = envp[last];
644 envp[last] = NULL;
645
646 return true;
647}