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
lookup_syscall(const char * name)152 int 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
lookup_syscall_name(int nr)161 const 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
parse_single_constant(char * constant_str,char ** endptr)170 long int parse_single_constant(char *constant_str, char **endptr)
171 {
172 const struct constant_entry *entry = constant_table;
173 long int res = 0;
174 for (; entry->name; ++entry) {
175 if (!strcmp(entry->name, constant_str)) {
176 *endptr = constant_str + strlen(constant_str);
177 return entry->value;
178 }
179 }
180
181 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;
196 return 0;
197 }
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;
205 return 0;
206 }
207 }
208 if (**endptr != '\0') {
209 warn("trailing garbage after constant: '%s'", constant_str);
210 *endptr = constant_str;
211 return 0;
212 }
213 return res;
214 }
215
tokenize_parenthesized_expression(char ** stringp)216 static 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
parse_constant(char * constant_str,char ** endptr)251 long int parse_constant(char *constant_str, char **endptr)
252 {
253 long int value = 0, current_value;
254 char *group, *lastpos = constant_str;
255
256 /*
257 * 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.
274 *
275 * If there is an error parsing any of the constants, the whole process
276 * fails.
277 */
278 while (constant_str && *constant_str) {
279 bool negate = false;
280 if (*constant_str == '~') {
281 negate = true;
282 ++constant_str;
283 }
284 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;
325 }
326 if (endptr)
327 *endptr = lastpos;
328 return value;
329 }
330
331 /*
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 */
parse_size(size_t * result,const char * sizespec)339 int 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
strip(char * s)381 char *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 }
392
tokenize(char ** stringp,const char * delim)393 char *tokenize(char **stringp, const char *delim)
394 {
395 char *ret = NULL;
396
397 /* If the string is NULL, there are no tokens to be found. */
398 if (stringp == NULL || *stringp == NULL)
399 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
411 char *found = strstr(*stringp, delim);
412 if (!found) {
413 /*
414 * The delimiter was not found, so the full string
415 * makes up the only token, and we're done.
416 */
417 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);
424 }
425
426 return ret;
427 }
428
path_join(const char * external_path,const char * internal_path)429 char *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
consumebytes(size_t length,char ** buf,size_t * buflength)442 void *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
consumestr(char ** buf,size_t * buflength)452 char *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 }
460
init_logging(enum logging_system_t logger,int fd,int min_priority)461 void 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 }
467
minijail_free_env(char ** env)468 void 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
minijail_copy_env(char * const * env)480 char **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
minijail_setenv(char *** env,const char * name,const char * value,int overwrite)504 int 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 }
546