blob: c8cf3a63b3e8c0b23662eaf3a056dea81fa0369d [file] [log] [blame]
Mike Frysinger4c331892022-09-13 05:17:08 -04001/* Copyright 2012 The ChromiumOS Authors
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -07002 * 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 */
Mike Frysingera221d242022-08-02 06:32:10 -040036const char *const log_syscalls[] = {
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070037#if defined(__x86_64__)
Mike Frysingera221d242022-08-02 06:32:10 -040038# if defined(__ANDROID__)
39 "socket", "connect", "fcntl", "writev",
40# else
41 "socket", "connect", "sendto", "writev",
42# endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070043#elif defined(__i386__)
Mike Frysingera221d242022-08-02 06:32:10 -040044# if defined(__ANDROID__)
45 "socketcall", "writev", "fcntl64", "clock_gettime",
46# else
47 "socketcall", "time", "writev",
48# endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070049#elif defined(__arm__)
Mike Frysingera221d242022-08-02 06:32:10 -040050# if defined(__ANDROID__)
51 "clock_gettime", "connect", "fcntl64", "socket", "writev",
52# else
53 "socket", "connect", "gettimeofday", "send", "writev",
54# endif
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080055#elif defined(__aarch64__)
Mike Frysingera221d242022-08-02 06:32:10 -040056# if defined(__ANDROID__)
57 "connect", "fcntl", "sendto", "socket", "writev",
58# else
59 "socket", "connect", "send", "writev",
60# endif
61#elif defined(__hppa__) || \
62 defined(__ia64__) || \
63 defined(__mips__) || \
64 defined(__powerpc__) || \
65 defined(__sparc__)
66 "socket", "connect", "send",
Dylan Reid4ab1a2c2021-11-01 16:17:15 -070067#elif defined(__riscv)
Mike Frysingera221d242022-08-02 06:32:10 -040068# if defined(__ANDROID__)
69 "connect", "fcntl", "sendto", "socket", "writev",
70# else
71 "socket", "connect", "sendto",
72# endif
Xia Lifang592dd7d2022-08-02 11:09:19 +080073#else
Mike Frysingera221d242022-08-02 06:32:10 -040074# error "Unsupported platform"
Xia Lifang592dd7d2022-08-02 11:09:19 +080075#endif
Mike Frysingera221d242022-08-02 06:32:10 -040076};
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070077
Mike Frysinger404d2bb2017-01-17 19:29:00 -050078const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070079
Luis Hector Chavez114a9302017-09-05 20:36:58 -070080/* clang-format off */
81static struct logging_config_t {
82 /* The logging system to use. The default is syslog. */
83 enum logging_system_t logger;
84
85 /* File descriptor to log to. Only used when logger is LOG_TO_FD. */
86 int fd;
87
88 /* Minimum priority to log. Only used when logger is LOG_TO_FD. */
89 int min_priority;
90} logging_config = {
91 .logger = LOG_TO_SYSLOG,
92};
93/* clang-format on */
94
Luis Hector Chavezcc559e82018-07-09 13:26:31 -070095#if defined(USE_EXIT_ON_DIE)
96#define do_abort() exit(1)
97#else
98#define do_abort() abort()
99#endif
100
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700101#if defined(__clang__)
102#define attribute_no_optimize __attribute__((optnone))
103#else
104#define attribute_no_optimize __attribute__((__optimize__(0)))
105#endif
106
107/* Forces the compiler to perform no optimizations on |var|. */
108static void attribute_no_optimize alias(const void *var)
109{
110 (void)var;
111}
112
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700113void do_fatal_log(int priority, const char *format, ...)
114{
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700115 va_list args, stack_args;
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700116 va_start(args, format);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700117 va_copy(stack_args, args);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700118 if (logging_config.logger == LOG_TO_SYSLOG) {
119 vsyslog(priority, format, args);
120 } else {
121 vdprintf(logging_config.fd, format, args);
122 dprintf(logging_config.fd, "\n");
123 }
124 va_end(args);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700125
126 /*
127 * Write another copy of the first few characters of the message into a
128 * stack-based buffer so that it can appear in minidumps. Choosing a
129 * small-ish buffer size since breakpad will only pick up the first few
130 * kilobytes of each stack, so that will prevent this buffer from
131 * kicking out other stack frames.
132 */
133 char log_line[512];
134 vsnprintf(log_line, sizeof(log_line), format, stack_args);
135 va_end(stack_args);
136 alias(log_line);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700137 do_abort();
138}
139
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700140void do_log(int priority, const char *format, ...)
141{
142 if (logging_config.logger == LOG_TO_SYSLOG) {
143 va_list args;
144 va_start(args, format);
145 vsyslog(priority, format, args);
146 va_end(args);
147 return;
148 }
149
150 if (logging_config.min_priority < priority)
151 return;
152
153 va_list args;
154 va_start(args, format);
155 vdprintf(logging_config.fd, format, args);
156 va_end(args);
157 dprintf(logging_config.fd, "\n");
158}
159
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000160/*
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000161 * Returns the syscall nr and optionally populates the index in the pointer
162 * |ind| if it is non-NULL.
163 */
164int lookup_syscall(const char *name, size_t *ind)
165{
166 size_t ind_tmp = 0;
167 const struct syscall_entry *entry = syscall_table;
168 for (; entry->name && entry->nr >= 0; ++entry) {
Mike Frysinger22dc3522022-07-07 19:24:13 -0400169 if (streq(entry->name, name)) {
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000170 if (ind != NULL)
171 *ind = ind_tmp;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700172 return entry->nr;
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000173 }
174 ind_tmp++;
175 }
176 if (ind != NULL)
177 *ind = -1;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700178 return -1;
179}
180
181const char *lookup_syscall_name(int nr)
182{
183 const struct syscall_entry *entry = syscall_table;
184 for (; entry->name && entry->nr >= 0; ++entry)
185 if (entry->nr == nr)
186 return entry->name;
187 return NULL;
188}
189
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400190long int parse_single_constant(char *constant_str, char **endptr)
191{
192 const struct constant_entry *entry = constant_table;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400193 long int res = 0;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400194 for (; entry->name; ++entry) {
Mike Frysinger22dc3522022-07-07 19:24:13 -0400195 if (streq(entry->name, constant_str)) {
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700196 *endptr = constant_str + strlen(constant_str);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400197 return entry->value;
198 }
199 }
200
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400201 errno = 0;
202 res = strtol(constant_str, endptr, 0);
203 if (errno == ERANGE) {
204 if (res == LONG_MAX) {
205 /* See if the constant fits in an unsigned long int. */
206 errno = 0;
207 res = strtoul(constant_str, endptr, 0);
208 if (errno == ERANGE) {
209 /*
210 * On unsigned overflow, use the same convention
211 * as when strtol(3) finds no digits: set
212 * |*endptr| to |constant_str| and return 0.
213 */
214 warn("unsigned overflow: '%s'", constant_str);
215 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700216 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400217 }
218 } else if (res == LONG_MIN) {
219 /*
220 * Same for signed underflow: set |*endptr| to
221 * |constant_str| and return 0.
222 */
223 warn("signed underflow: '%s'", constant_str);
224 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700225 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400226 }
227 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700228 if (**endptr != '\0') {
229 warn("trailing garbage after constant: '%s'", constant_str);
230 *endptr = constant_str;
231 return 0;
232 }
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400233 return res;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400234}
235
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700236static char *tokenize_parenthesized_expression(char **stringp)
237{
238 char *ret = NULL, *found = NULL;
239 size_t paren_count = 1;
240
241 /* If the string is NULL, there are no parens to be found. */
242 if (stringp == NULL || *stringp == NULL)
243 return NULL;
244
245 /* If the string is not on an open paren, the results are undefined. */
246 if (**stringp != '(')
247 return NULL;
248
249 for (found = *stringp + 1; *found; ++found) {
250 switch (*found) {
251 case '(':
252 ++paren_count;
253 break;
254 case ')':
255 --paren_count;
256 if (!paren_count) {
257 *found = '\0';
258 ret = *stringp + 1;
259 *stringp = found + 1;
260 return ret;
261 }
262 break;
263 }
264 }
265
266 /* We got to the end without finding the closing paren. */
267 warn("unclosed parenthesis: '%s'", *stringp);
268 return NULL;
269}
270
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700271long int parse_constant(char *constant_str, char **endptr)
272{
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700273 long int value = 0, current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000274 char *group, *lastpos = constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000275
276 /*
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700277 * If |endptr| is provided, parsing errors are signaled as |endptr|
278 * pointing to |constant_str|.
279 */
280 if (endptr)
281 *endptr = constant_str;
282
283 /*
284 * Try to parse constant expressions. Valid constant expressions are:
285 *
286 * - A number that can be parsed with strtol(3).
287 * - A named constant expression.
288 * - A parenthesized, valid constant expression.
289 * - A valid constant expression prefixed with the unary bitwise
290 * complement operator ~.
291 * - A series of valid constant expressions separated by pipes. Note
292 * that since |constant_str| is an atom, there can be no spaces
293 * between the constant and the pipe.
Luis Hector Chavez21224552015-06-27 18:10:39 +0000294 *
295 * If there is an error parsing any of the constants, the whole process
296 * fails.
297 */
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700298 while (constant_str && *constant_str) {
299 bool negate = false;
300 if (*constant_str == '~') {
301 negate = true;
302 ++constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000303 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700304 if (*constant_str == '(') {
305 group =
306 tokenize_parenthesized_expression(&constant_str);
307 if (group == NULL)
308 return 0;
309 char *end = group;
310 /* Recursively parse the parenthesized subexpression. */
311 current_value = parse_constant(group, &end);
312 if (end == group)
313 return 0;
314 if (constant_str && *constant_str) {
315 /*
316 * If this is not the end of the atom, there
317 * should be another | followed by more stuff.
318 */
319 if (*constant_str != '|') {
320 warn("unterminated constant "
321 "expression: '%s'",
322 constant_str);
323 return 0;
324 }
325 ++constant_str;
326 if (*constant_str == '\0') {
327 warn("unterminated constant "
328 "expression: '%s'",
329 constant_str);
330 return 0;
331 }
332 }
333 lastpos = end;
334 } else {
335 group = tokenize(&constant_str, "|");
336 char *end = group;
337 current_value = parse_single_constant(group, &end);
338 if (end == group)
339 return 0;
340 lastpos = end;
341 }
342 if (negate)
343 current_value = ~current_value;
344 value |= current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000345 }
346 if (endptr)
347 *endptr = lastpos;
348 return value;
349}
350
Martin Pelikánab9eb442017-01-25 11:53:58 +1100351/*
352 * parse_size, specified as a string with a decimal number in bytes,
353 * possibly with one 1-character suffix like "10K" or "6G".
354 * Assumes both pointers are non-NULL.
355 *
356 * Returns 0 on success, negative errno on failure.
357 * Only writes to result on success.
358 */
359int parse_size(size_t *result, const char *sizespec)
360{
361 const char prefixes[] = "KMGTPE";
362 size_t i, multiplier = 1, nsize, size = 0;
363 unsigned long long parsed;
364 const size_t len = strlen(sizespec);
365 char *end;
366
367 if (len == 0 || sizespec[0] == '-')
368 return -EINVAL;
369
370 for (i = 0; i < sizeof(prefixes); ++i) {
371 if (sizespec[len - 1] == prefixes[i]) {
372#if __WORDSIZE == 32
373 if (i >= 3)
374 return -ERANGE;
375#endif
376 multiplier = 1024;
377 while (i-- > 0)
378 multiplier *= 1024;
379 break;
380 }
381 }
382
383 /* We only need size_t but strtoul(3) is too small on IL32P64. */
384 parsed = strtoull(sizespec, &end, 10);
385 if (parsed == ULLONG_MAX)
386 return -errno;
387 if (parsed >= SIZE_MAX)
388 return -ERANGE;
389 if ((multiplier != 1 && end != sizespec + len - 1) ||
390 (multiplier == 1 && end != sizespec + len))
391 return -EINVAL;
392 size = (size_t)parsed;
393
394 nsize = size * multiplier;
395 if (nsize / multiplier != size)
396 return -ERANGE;
397 *result = nsize;
398 return 0;
399}
400
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700401char *strip(char *s)
402{
403 char *end;
404 while (*s && isblank(*s))
405 s++;
406 end = s + strlen(s) - 1;
407 while (end >= s && *end && (isblank(*end) || *end == '\n'))
408 end--;
409 *(end + 1) = '\0';
410 return s;
411}
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800412
Jorge Lucangeli Obesc8b21e12014-06-13 14:26:16 -0700413char *tokenize(char **stringp, const char *delim)
414{
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800415 char *ret = NULL;
416
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500417 /* If the string is NULL, there are no tokens to be found. */
418 if (stringp == NULL || *stringp == NULL)
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800419 return NULL;
420
421 /*
422 * If the delimiter is NULL or empty,
423 * the full string makes up the only token.
424 */
425 if (delim == NULL || *delim == '\0') {
426 ret = *stringp;
427 *stringp = NULL;
428 return ret;
429 }
430
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500431 char *found = strstr(*stringp, delim);
432 if (!found) {
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800433 /*
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500434 * The delimiter was not found, so the full string
435 * makes up the only token, and we're done.
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800436 */
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500437 ret = *stringp;
438 *stringp = NULL;
439 } else {
440 /* There's a token here, possibly empty. That's OK. */
441 *found = '\0';
442 ret = *stringp;
443 *stringp = found + strlen(delim);
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800444 }
445
446 return ret;
447}
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400448
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400449char *path_join(const char *external_path, const char *internal_path)
450{
Mike Frysinger572bab22021-10-27 03:02:44 -0400451 char *path = NULL;
452 return asprintf(&path, "%s/%s", external_path, internal_path) < 0
453 ? NULL
454 : path;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400455}
456
Jorge Lucangeli Obesa8eef8b2022-07-20 19:20:06 -0400457bool path_is_parent(const char *parent, const char *child)
458{
459 /*
460 * -Make sure |child| starts with |parent|.
461 * -Make sure that if |child| is longer than |parent|, either:
462 * --the last character in |parent| is a path separator, or
463 * --the character immediately following |parent| in |child| is a path
464 * separator.
465 */
466 size_t parent_len = strlen(parent);
467 return strncmp(parent, child, parent_len) == 0 &&
468 (strlen(child) > parent_len ? (parent[parent_len - 1] == '/' ||
469 child[parent_len] == '/')
470 : false);
471}
472
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400473void *consumebytes(size_t length, char **buf, size_t *buflength)
474{
475 char *p = *buf;
476 if (length > *buflength)
477 return NULL;
478 *buf += length;
479 *buflength -= length;
480 return p;
481}
482
483char *consumestr(char **buf, size_t *buflength)
484{
485 size_t len = strnlen(*buf, *buflength);
486 if (len == *buflength)
487 /* There's no null-terminator. */
488 return NULL;
489 return consumebytes(len + 1, buf, buflength);
490}
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700491
492void init_logging(enum logging_system_t logger, int fd, int min_priority)
493{
494 logging_config.logger = logger;
495 logging_config.fd = fd;
496 logging_config.min_priority = min_priority;
497}
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100498
499void minijail_free_env(char **env)
500{
501 if (!env)
502 return;
503
504 for (char **entry = env; *entry; ++entry) {
505 free(*entry);
506 }
507
508 free(env);
509}
510
511char **minijail_copy_env(char *const *env)
512{
513 if (!env)
514 return calloc(1, sizeof(char *));
515
516 int len = 0;
517 while (env[len])
518 ++len;
519
520 char **copy = calloc(len + 1, sizeof(char *));
521 if (!copy)
522 return NULL;
523
524 for (char **entry = copy; *env; ++env, ++entry) {
525 *entry = strdup(*env);
526 if (!*entry) {
527 minijail_free_env(copy);
528 return NULL;
529 }
530 }
531
532 return copy;
533}
534
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100535/*
536 * Utility function used by minijail_setenv, minijail_unsetenv and
537 * minijail_getenv, returns true if |name| is found, false if not.
538 * If found, |*i| is |name|'s index. If not, |*i| is the length of |envp|.
539 */
540static bool getenv_index(char **envp, const char *name, int *i) {
541 if (!envp || !name || !i)
542 return false;
543
544 size_t name_len = strlen(name);
545 for (*i = 0; envp[*i]; ++(*i)) {
546 /*
547 * If we find a match the size of |name|, we must check
548 * that the next character is a '=', indicating that
549 * the full varname of envp[i] is exactly |name| and
550 * not just happening to start with |name|.
551 */
552 if (!strncmp(envp[*i], name, name_len) &&
553 (envp[*i][name_len] == '=')) {
554 return true;
555 }
556 }
557 /* No match found, |*i| contains the number of elements in |envp|. */
558 return false;
559}
560
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100561int minijail_setenv(char ***env, const char *name, const char *value,
562 int overwrite)
563{
564 if (!env || !*env || !name || !*name || !value)
565 return EINVAL;
566
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100567 char **dest = NULL;
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100568 int i;
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100569
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100570 /* Look in env to check if this var name already exists. */
571 if (getenv_index(*env, name, &i)) {
572 if (!overwrite)
573 return 0;
574 dest = &(*env)[i];
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100575 }
576
577 char *new_entry = NULL;
578 if (asprintf(&new_entry, "%s=%s", name, value) == -1)
579 return ENOMEM;
580
581 if (dest) {
582 free(*dest);
583 *dest = new_entry;
584 return 0;
585 }
586
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100587 /* getenv_index has set |i| to the length of |env|. */
588 ++i;
589 char **new_env = realloc(*env, (i + 1) * sizeof(char *));
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100590 if (!new_env) {
591 free(new_entry);
592 return ENOMEM;
593 }
594
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100595 new_env[i - 1] = new_entry;
596 new_env[i] = NULL;
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100597 *env = new_env;
598 return 0;
599}
Zi Lin2c794452021-10-13 03:07:07 +0000600
601/*
602 * This is like getline() but supports line wrapping with \.
603 */
604ssize_t getmultiline(char **lineptr, size_t *n, FILE *stream)
605{
606 ssize_t ret = getline(lineptr, n, stream);
607 if (ret < 0)
608 return ret;
609
610 char *line = *lineptr;
611 /* Eat the newline to make processing below easier. */
612 if (ret > 0 && line[ret - 1] == '\n')
613 line[--ret] = '\0';
614
615 /* If the line doesn't end in a backslash, we're done. */
616 if (ret <= 0 || line[ret - 1] != '\\')
617 return ret;
618
619 /* This line ends in a backslash. Get the nextline. */
620 line[--ret] = '\0';
621 size_t next_n = 0;
Mike Frysingere933fce2021-10-02 01:28:06 -0400622 attribute_cleanup_str char *next_line = NULL;
Zi Lin2c794452021-10-13 03:07:07 +0000623 ssize_t next_ret = getmultiline(&next_line, &next_n, stream);
624 if (next_ret == -1) {
Zi Lin2c794452021-10-13 03:07:07 +0000625 /* We couldn't fully read the line, so return an error. */
626 return -1;
627 }
628
629 /* Merge the lines. */
630 *n = ret + next_ret + 2;
631 line = realloc(line, *n);
Mike Frysingere933fce2021-10-02 01:28:06 -0400632 if (!line)
Zi Lin2c794452021-10-13 03:07:07 +0000633 return -1;
Zi Lin2c794452021-10-13 03:07:07 +0000634 line[ret] = ' ';
635 memcpy(&line[ret + 1], next_line, next_ret + 1);
Zi Lin2c794452021-10-13 03:07:07 +0000636 *lineptr = line;
637 return *n - 1;
638}
Stéphane Lesimple66bcc8c2022-01-06 13:11:37 +0100639
640char *minijail_getenv(char **envp, const char *name) {
641 if (!envp || !name)
642 return NULL;
643
644 int i;
645 if (!getenv_index(envp, name, &i))
646 return NULL;
647
648 /* Return a ptr to the value after the '='. */
649 return envp[i] + strlen(name) + 1;
650}
651
652bool minijail_unsetenv(char **envp, const char *name)
653{
654 if (!envp || !name)
655 return false;
656
657 int i;
658 if (!getenv_index(envp, name, &i))
659 return false;
660
661 /* We found a match, replace it by the last entry of the array. */
662 int last;
663 for (last = i; envp[last]; ++last)
664 continue;
665 --last;
666 envp[i] = envp[last];
667 envp[last] = NULL;
668
669 return true;
670}