]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/utils.c
utils: add lxc_append_string()
[mirror_lxc.git] / src / lxc / utils.c
CommitLineData
e3642c43
DL
1/*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
9afe19d6 7 * Daniel Lezcano <daniel.lezcano at free.fr>
e3642c43
DL
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
250b1eec 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
e3642c43
DL
22 */
23
052616eb
ÇO
24#include "config.h"
25
a1e5280d
CB
26#include <assert.h>
27#include <dirent.h>
e3642c43 28#include <errno.h>
a1e5280d
CB
29#include <fcntl.h>
30#include <libgen.h>
d983b93c 31#include <stddef.h>
a1e5280d
CB
32#include <stdio.h>
33#include <stdlib.h>
61a1d519 34#include <string.h>
981f6029 35#include <unistd.h>
e3642c43 36#include <sys/mman.h>
6e4bb2e0 37#include <sys/mount.h>
a1e5280d
CB
38#include <sys/param.h>
39#include <sys/prctl.h>
40#include <sys/stat.h>
9be53773 41#include <sys/types.h>
a1e5280d 42#include <sys/vfs.h>
9be53773 43#include <sys/wait.h>
e3642c43
DL
44
45#include "log.h"
025ed0f3 46#include "lxclock.h"
51d0854c 47#include "namespace.h"
981f6029 48#include "utils.h"
e3642c43 49
5d6ef228
SG
50#ifndef PR_SET_MM
51#define PR_SET_MM 35
52#endif
53
8d2ede58
TA
54#ifndef PR_SET_MM_MAP
55#define PR_SET_MM_MAP 14
553347e4 56
8d2ede58
TA
57struct prctl_mm_map {
58 uint64_t start_code;
59 uint64_t end_code;
60 uint64_t start_data;
61 uint64_t end_data;
62 uint64_t start_brk;
63 uint64_t brk;
64 uint64_t start_stack;
65 uint64_t arg_start;
66 uint64_t arg_end;
67 uint64_t env_start;
68 uint64_t env_end;
69 uint64_t *auxv;
70 uint32_t auxv_size;
71 uint32_t exe_fd;
1adbd020 72};
553347e4
TA
73#endif
74
4928c718
SG
75#ifndef O_PATH
76#define O_PATH 010000000
77#endif
78
79#ifndef O_NOFOLLOW
80#define O_NOFOLLOW 00400000
81#endif
82
e3642c43
DL
83lxc_log_define(lxc_utils, lxc);
84
4295c5de
SH
85/*
86 * if path is btrfs, tries to remove it and any subvolumes beneath it
87 */
88extern bool btrfs_try_remove_subvol(const char *path);
89
0cc417b2
SH
90static int _recursive_rmdir(char *dirname, dev_t pdev,
91 const char *exclude, int level, bool onedev)
60bf62d4 92{
74f96976 93 struct dirent *direntp;
60bf62d4
SH
94 DIR *dir;
95 int ret, failed=0;
96 char pathname[MAXPATHLEN];
18aa217b 97 bool hadexclude = false;
60bf62d4
SH
98
99 dir = opendir(dirname);
100 if (!dir) {
101 ERROR("%s: failed to open %s", __func__, dirname);
4355ab5f 102 return -1;
60bf62d4
SH
103 }
104
74f96976 105 while ((direntp = readdir(dir))) {
60bf62d4
SH
106 struct stat mystat;
107 int rc;
108
109 if (!direntp)
110 break;
111
112 if (!strcmp(direntp->d_name, ".") ||
113 !strcmp(direntp->d_name, ".."))
114 continue;
115
116 rc = snprintf(pathname, MAXPATHLEN, "%s/%s", dirname, direntp->d_name);
117 if (rc < 0 || rc >= MAXPATHLEN) {
118 ERROR("pathname too long");
119 failed=1;
120 continue;
121 }
18aa217b
SH
122
123 if (!level && exclude && !strcmp(direntp->d_name, exclude)) {
124 ret = rmdir(pathname);
125 if (ret < 0) {
126 switch(errno) {
127 case ENOTEMPTY:
0cc417b2 128 INFO("Not deleting snapshot %s", pathname);
18aa217b
SH
129 hadexclude = true;
130 break;
131 case ENOTDIR:
132 ret = unlink(pathname);
133 if (ret)
134 INFO("%s: failed to remove %s", __func__, pathname);
135 break;
136 default:
137 SYSERROR("%s: failed to rmdir %s", __func__, pathname);
138 failed = 1;
139 break;
140 }
141 }
142 continue;
143 }
144
60bf62d4
SH
145 ret = lstat(pathname, &mystat);
146 if (ret) {
147 ERROR("%s: failed to stat %s", __func__, pathname);
4295c5de 148 failed = 1;
60bf62d4
SH
149 continue;
150 }
4295c5de
SH
151 if (onedev && mystat.st_dev != pdev) {
152 /* TODO should we be checking /proc/self/mountinfo for
153 * pathname and not doing this if found? */
154 if (btrfs_try_remove_subvol(pathname))
155 INFO("Removed btrfs subvolume at %s\n", pathname);
60bf62d4 156 continue;
4295c5de 157 }
60bf62d4 158 if (S_ISDIR(mystat.st_mode)) {
0cc417b2 159 if (_recursive_rmdir(pathname, pdev, exclude, level+1, onedev) < 0)
60bf62d4
SH
160 failed=1;
161 } else {
162 if (unlink(pathname) < 0) {
0cc417b2 163 SYSERROR("%s: failed to delete %s", __func__, pathname);
60bf62d4
SH
164 failed=1;
165 }
166 }
167 }
168
4295c5de
SH
169 if (rmdir(dirname) < 0 && !btrfs_try_remove_subvol(dirname) && !hadexclude) {
170 ERROR("%s: failed to delete %s", __func__, dirname);
171 failed=1;
60bf62d4
SH
172 }
173
025ed0f3 174 ret = closedir(dir);
025ed0f3 175 if (ret) {
60bf62d4
SH
176 ERROR("%s: failed to close directory %s", __func__, dirname);
177 failed=1;
178 }
179
4355ab5f 180 return failed ? -1 : 0;
60bf62d4
SH
181}
182
0cc417b2
SH
183/* we have two different magic values for overlayfs, yay */
184#define OVERLAYFS_SUPER_MAGIC 0x794c764f
185#define OVERLAY_SUPER_MAGIC 0x794c7630
186/*
187 * In overlayfs, st_dev is unreliable. so on overlayfs we don't do
188 * the lxc_rmdir_onedev()
189 */
190static bool is_native_overlayfs(const char *path)
191{
192 struct statfs sb;
193
194 if (statfs(path, &sb) < 0)
195 return false;
196 if (sb.f_type == OVERLAYFS_SUPER_MAGIC ||
197 sb.f_type == OVERLAY_SUPER_MAGIC)
198 return true;
199 return false;
200}
201
4355ab5f 202/* returns 0 on success, -1 if there were any failures */
18aa217b 203extern int lxc_rmdir_onedev(char *path, const char *exclude)
60bf62d4
SH
204{
205 struct stat mystat;
0cc417b2
SH
206 bool onedev = true;
207
208 if (is_native_overlayfs(path)) {
209 onedev = false;
210 }
60bf62d4
SH
211
212 if (lstat(path, &mystat) < 0) {
067650d0
SH
213 if (errno == ENOENT)
214 return 0;
60bf62d4 215 ERROR("%s: failed to stat %s", __func__, path);
4355ab5f 216 return -1;
60bf62d4
SH
217 }
218
0cc417b2 219 return _recursive_rmdir(path, mystat.st_dev, exclude, 0, onedev);
60bf62d4
SH
220}
221
9ddaf3bf 222/* borrowed from iproute2 */
7c11d57a 223extern int get_u16(unsigned short *val, const char *arg, int base)
9ddaf3bf
JHS
224{
225 unsigned long res;
226 char *ptr;
227
228 if (!arg || !*arg)
229 return -1;
230
09bbd745 231 errno = 0;
9ddaf3bf 232 res = strtoul(arg, &ptr, base);
09bbd745 233 if (!ptr || ptr == arg || *ptr || res > 0xFFFF || errno != 0)
9ddaf3bf
JHS
234 return -1;
235
236 *val = res;
237
238 return 0;
239}
240
3ce74686 241extern int mkdir_p(const char *dir, mode_t mode)
1b09f2c0 242{
3ce74686
SH
243 const char *tmp = dir;
244 const char *orig = dir;
860fc865
RW
245 char *makeme;
246
247 do {
248 dir = tmp + strspn(tmp, "/");
249 tmp = dir + strcspn(dir, "/");
d74325c4 250 makeme = strndup(orig, dir - orig);
860fc865
RW
251 if (*makeme) {
252 if (mkdir(makeme, mode) && errno != EEXIST) {
959aee9c 253 SYSERROR("failed to create directory '%s'", makeme);
d74325c4 254 free(makeme);
860fc865
RW
255 return -1;
256 }
257 }
d74325c4 258 free(makeme);
860fc865 259 } while(tmp != dir);
1b09f2c0 260
98663823 261 return 0;
1b09f2c0 262}
2a59a681 263
44b9ae4b 264char *get_rundir()
9e60f51d 265{
97a696c6
SG
266 char *rundir;
267 const char *homedir;
9e60f51d 268
d6470e71 269 if (geteuid() == 0) {
c580b8d2 270 rundir = strdup(RUNTIME_PATH);
d6470e71
SG
271 return rundir;
272 }
97a696c6
SG
273
274 rundir = getenv("XDG_RUNTIME_DIR");
44b9ae4b
SG
275 if (rundir) {
276 rundir = strdup(rundir);
277 return rundir;
278 }
97a696c6 279
44b9ae4b
SG
280 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
281 homedir = getenv("HOME");
282 if (!homedir) {
283 ERROR("HOME isn't set in the environment.");
284 return NULL;
97a696c6
SG
285 }
286
44b9ae4b
SG
287 rundir = malloc(sizeof(char) * (17 + strlen(homedir)));
288 sprintf(rundir, "%s/.cache/lxc/run/", homedir);
289
9e60f51d
DE
290 return rundir;
291}
292
9be53773
SH
293int wait_for_pid(pid_t pid)
294{
295 int status, ret;
296
297again:
298 ret = waitpid(pid, &status, 0);
299 if (ret == -1) {
71b9b8ed 300 if (errno == EINTR)
9be53773
SH
301 goto again;
302 return -1;
303 }
304 if (ret != pid)
305 goto again;
306 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
307 return -1;
308 return 0;
309}
c797a220
CS
310
311int lxc_wait_for_pid_status(pid_t pid)
312{
313 int status, ret;
314
315again:
316 ret = waitpid(pid, &status, 0);
317 if (ret == -1) {
318 if (errno == EINTR)
319 goto again;
320 return -1;
321 }
322 if (ret != pid)
323 goto again;
324 return status;
325}
92f023dc 326
650468bb 327ssize_t lxc_write_nointr(int fd, const void* buf, size_t count)
92f023dc 328{
650468bb 329 ssize_t ret;
92f023dc
CS
330again:
331 ret = write(fd, buf, count);
332 if (ret < 0 && errno == EINTR)
333 goto again;
334 return ret;
335}
336
650468bb 337ssize_t lxc_read_nointr(int fd, void* buf, size_t count)
92f023dc 338{
650468bb 339 ssize_t ret;
92f023dc
CS
340again:
341 ret = read(fd, buf, count);
342 if (ret < 0 && errno == EINTR)
343 goto again;
344 return ret;
345}
346
650468bb 347ssize_t lxc_read_nointr_expect(int fd, void* buf, size_t count, const void* expected_buf)
92f023dc 348{
650468bb 349 ssize_t ret;
92f023dc
CS
350 ret = lxc_read_nointr(fd, buf, count);
351 if (ret <= 0)
352 return ret;
650468bb 353 if ((size_t)ret != count)
92f023dc
CS
354 return -1;
355 if (expected_buf && memcmp(buf, expected_buf, count) != 0) {
356 errno = EINVAL;
357 return -1;
358 }
359 return ret;
360}
3ce74686
SH
361
362#if HAVE_LIBGNUTLS
363#include <gnutls/gnutls.h>
364#include <gnutls/crypto.h>
41246cee
DE
365
366__attribute__((constructor))
367static void gnutls_lxc_init(void)
368{
369 gnutls_global_init();
370}
371
3ce74686
SH
372int sha1sum_file(char *fnam, unsigned char *digest)
373{
374 char *buf;
375 int ret;
376 FILE *f;
377 long flen;
378
379 if (!fnam)
380 return -1;
025ed0f3 381 f = fopen_cloexec(fnam, "r");
7be677a8 382 if (!f) {
3ce74686
SH
383 SYSERROR("Error opening template");
384 return -1;
385 }
386 if (fseek(f, 0, SEEK_END) < 0) {
387 SYSERROR("Error seeking to end of template");
dd1d77f9 388 fclose(f);
3ce74686
SH
389 return -1;
390 }
391 if ((flen = ftell(f)) < 0) {
392 SYSERROR("Error telling size of template");
dd1d77f9 393 fclose(f);
3ce74686
SH
394 return -1;
395 }
396 if (fseek(f, 0, SEEK_SET) < 0) {
397 SYSERROR("Error seeking to start of template");
dd1d77f9 398 fclose(f);
3ce74686
SH
399 return -1;
400 }
401 if ((buf = malloc(flen+1)) == NULL) {
402 SYSERROR("Out of memory");
dd1d77f9 403 fclose(f);
3ce74686
SH
404 return -1;
405 }
406 if (fread(buf, 1, flen, f) != flen) {
407 SYSERROR("Failure reading template");
408 free(buf);
dd1d77f9 409 fclose(f);
3ce74686
SH
410 return -1;
411 }
dd1d77f9 412 if (fclose(f) < 0) {
3ce74686
SH
413 SYSERROR("Failre closing template");
414 free(buf);
415 return -1;
416 }
417 buf[flen] = '\0';
418 ret = gnutls_hash_fast(GNUTLS_DIG_SHA1, buf, flen, (void *)digest);
419 free(buf);
420 return ret;
421}
422#endif
61a1d519
CS
423
424char** lxc_va_arg_list_to_argv(va_list ap, size_t skip, int do_strdup)
425{
426 va_list ap2;
427 size_t count = 1 + skip;
428 char **result;
429
430 /* first determine size of argument list, we don't want to reallocate
431 * constantly...
432 */
433 va_copy(ap2, ap);
434 while (1) {
435 char* arg = va_arg(ap2, char*);
436 if (!arg)
437 break;
438 count++;
439 }
440 va_end(ap2);
441
442 result = calloc(count, sizeof(char*));
443 if (!result)
444 return NULL;
445 count = skip;
446 while (1) {
447 char* arg = va_arg(ap, char*);
448 if (!arg)
449 break;
450 arg = do_strdup ? strdup(arg) : arg;
451 if (!arg)
452 goto oom;
453 result[count++] = arg;
454 }
455
456 /* calloc has already set last element to NULL*/
457 return result;
458
459oom:
460 free(result);
461 return NULL;
462}
463
464const char** lxc_va_arg_list_to_argv_const(va_list ap, size_t skip)
465{
466 return (const char**)lxc_va_arg_list_to_argv(ap, skip, 0);
467}
db27c8d7 468
ebec9176
AM
469extern struct lxc_popen_FILE *lxc_popen(const char *command)
470{
471 struct lxc_popen_FILE *fp = NULL;
472 int parent_end = -1, child_end = -1;
473 int pipe_fds[2];
474 pid_t child_pid;
475
476 int r = pipe2(pipe_fds, O_CLOEXEC);
477
478 if (r < 0) {
479 ERROR("pipe2 failure");
480 return NULL;
481 }
482
483 parent_end = pipe_fds[0];
484 child_end = pipe_fds[1];
485
486 child_pid = fork();
487
488 if (child_pid == 0) {
489 /* child */
490 int child_std_end = STDOUT_FILENO;
491
492 if (child_end != child_std_end) {
493 /* dup2() doesn't dup close-on-exec flag */
494 dup2(child_end, child_std_end);
495
496 /* it's safe not to close child_end here
497 * as it's marked close-on-exec anyway
498 */
499 } else {
500 /*
501 * The descriptor is already the one we will use.
502 * But it must not be marked close-on-exec.
503 * Undo the effects.
504 */
57d2be54
SG
505 if (fcntl(child_end, F_SETFD, 0) != 0) {
506 SYSERROR("Failed to remove FD_CLOEXEC from fd.");
507 exit(127);
508 }
ebec9176
AM
509 }
510
511 /*
512 * Unblock signals.
513 * This is the main/only reason
514 * why we do our lousy popen() emulation.
515 */
516 {
517 sigset_t mask;
518 sigfillset(&mask);
519 sigprocmask(SIG_UNBLOCK, &mask, NULL);
520 }
521
522 execl("/bin/sh", "sh", "-c", command, (char *) NULL);
523 exit(127);
524 }
525
526 /* parent */
527
528 close(child_end);
529 child_end = -1;
530
531 if (child_pid < 0) {
532 ERROR("fork failure");
533 goto error;
534 }
535
536 fp = calloc(1, sizeof(*fp));
537 if (!fp) {
538 ERROR("failed to allocate memory");
539 goto error;
540 }
541
542 fp->f = fdopen(parent_end, "r");
543 if (!fp->f) {
544 ERROR("fdopen failure");
545 goto error;
546 }
547
548 fp->child_pid = child_pid;
549
550 return fp;
551
552error:
553
554 if (fp) {
555 if (fp->f) {
556 fclose(fp->f);
557 parent_end = -1; /* so we do not close it second time */
558 }
559
560 free(fp);
561 }
562
ebec9176
AM
563 if (parent_end != -1)
564 close(parent_end);
565
566 return NULL;
567}
568
ebec9176
AM
569extern int lxc_pclose(struct lxc_popen_FILE *fp)
570{
571 FILE *f = NULL;
572 pid_t child_pid = 0;
573 int wstatus = 0;
574 pid_t wait_pid;
575
576 if (fp) {
577 f = fp->f;
578 child_pid = fp->child_pid;
579 /* free memory (we still need to close file stream) */
580 free(fp);
581 fp = NULL;
582 }
583
584 if (!f || fclose(f)) {
585 ERROR("fclose failure");
586 return -1;
587 }
588
589 do {
590 wait_pid = waitpid(child_pid, &wstatus, 0);
591 } while (wait_pid == -1 && errno == EINTR);
592
593 if (wait_pid == -1) {
594 ERROR("waitpid failure");
595 return -1;
596 }
597
598 return wstatus;
599}
600
502657d5
CS
601char *lxc_string_replace(const char *needle, const char *replacement, const char *haystack)
602{
603 ssize_t len = -1, saved_len = -1;
604 char *result = NULL;
605 size_t replacement_len = strlen(replacement);
606 size_t needle_len = strlen(needle);
607
608 /* should be executed exactly twice */
609 while (len == -1 || result == NULL) {
610 char *p;
611 char *last_p;
612 ssize_t part_len;
613
614 if (len != -1) {
615 result = calloc(1, len + 1);
616 if (!result)
617 return NULL;
618 saved_len = len;
619 }
620
621 len = 0;
622
623 for (last_p = (char *)haystack, p = strstr(last_p, needle); p; last_p = p, p = strstr(last_p, needle)) {
624 part_len = (ssize_t)(p - last_p);
625 if (result && part_len > 0)
626 memcpy(&result[len], last_p, part_len);
627 len += part_len;
628 if (result && replacement_len > 0)
629 memcpy(&result[len], replacement, replacement_len);
630 len += replacement_len;
631 p += needle_len;
632 }
633 part_len = strlen(last_p);
634 if (result && part_len > 0)
635 memcpy(&result[len], last_p, part_len);
636 len += part_len;
637 }
638
639 /* make sure we did the same thing twice,
640 * once for calculating length, the other
641 * time for copying data */
642 assert(saved_len == len);
643 /* make sure we didn't overwrite any buffer,
644 * due to calloc the string should be 0-terminated */
645 assert(result[len] == '\0');
646
647 return result;
648}
649
650bool lxc_string_in_array(const char *needle, const char **haystack)
651{
652 for (; haystack && *haystack; haystack++)
653 if (!strcmp(needle, *haystack))
654 return true;
655 return false;
656}
657
658char *lxc_string_join(const char *sep, const char **parts, bool use_as_prefix)
659{
660 char *result;
661 char **p;
662 size_t sep_len = strlen(sep);
663 size_t result_len = use_as_prefix * sep_len;
664
665 /* calculate new string length */
666 for (p = (char **)parts; *p; p++)
667 result_len += (p > (char **)parts) * sep_len + strlen(*p);
668
669 result = calloc(result_len + 1, 1);
670 if (!result)
671 return NULL;
672
673 if (use_as_prefix)
674 strcpy(result, sep);
675 for (p = (char **)parts; *p; p++) {
676 if (p > (char **)parts)
677 strcat(result, sep);
678 strcat(result, *p);
679 }
680
681 return result;
682}
683
684char **lxc_normalize_path(const char *path)
685{
686 char **components;
687 char **p;
688 size_t components_len = 0;
689 size_t pos = 0;
690
691 components = lxc_string_split(path, '/');
692 if (!components)
693 return NULL;
694 for (p = components; *p; p++)
695 components_len++;
696
697 /* resolve '.' and '..' */
698 for (pos = 0; pos < components_len; ) {
699 if (!strcmp(components[pos], ".") || (!strcmp(components[pos], "..") && pos == 0)) {
700 /* eat this element */
701 free(components[pos]);
702 memmove(&components[pos], &components[pos+1], sizeof(char *) * (components_len - pos));
703 components_len--;
704 } else if (!strcmp(components[pos], "..")) {
705 /* eat this and the previous element */
706 free(components[pos - 1]);
707 free(components[pos]);
708 memmove(&components[pos-1], &components[pos+1], sizeof(char *) * (components_len - pos));
709 components_len -= 2;
710 pos--;
711 } else {
712 pos++;
713 }
714 }
715
716 return components;
717}
718
c56a9652 719bool lxc_deslashify(char **path)
aeb3682f 720{
f85b16a1 721 bool ret = false;
c56a9652
CB
722 char *p;
723 char **parts = NULL;
724 size_t n, len;
aeb3682f 725
c56a9652 726 parts = lxc_normalize_path(*path);
aeb3682f
TA
727 if (!parts)
728 return false;
729
c56a9652
CB
730 /* We'll end up here if path == "///" or path == "". */
731 if (!*parts) {
732 len = strlen(*path);
f85b16a1
CB
733 if (!len) {
734 ret = true;
735 goto out;
736 }
c56a9652
CB
737 n = strcspn(*path, "/");
738 if (n == len) {
739 p = strdup("/");
740 if (!p)
f85b16a1 741 goto out;
c56a9652
CB
742 free(*path);
743 *path = p;
f85b16a1
CB
744 ret = true;
745 goto out;
c56a9652
CB
746 }
747 }
748
749 p = lxc_string_join("/", (const char **)parts, **path == '/');
c56a9652 750 if (!p)
f85b16a1 751 goto out;
aeb3682f 752
c56a9652
CB
753 free(*path);
754 *path = p;
f85b16a1 755 ret = true;
c56a9652 756
f85b16a1
CB
757out:
758 lxc_free_array((void **)parts, free);
759 return ret;
aeb3682f
TA
760}
761
24b51482
CS
762char *lxc_append_paths(const char *first, const char *second)
763{
764 size_t len = strlen(first) + strlen(second) + 1;
765 const char *pattern = "%s%s";
766 char *result = NULL;
767
768 if (second[0] != '/') {
769 len += 1;
770 pattern = "%s/%s";
771 }
772
773 result = calloc(1, len);
774 if (!result)
775 return NULL;
776
777 snprintf(result, len, pattern, first, second);
778 return result;
779}
780
502657d5
CS
781bool lxc_string_in_list(const char *needle, const char *haystack, char _sep)
782{
783 char *token, *str, *saveptr = NULL;
784 char sep[2] = { _sep, '\0' };
785
786 if (!haystack || !needle)
787 return 0;
788
789 str = alloca(strlen(haystack)+1);
790 strcpy(str, haystack);
791 for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
792 if (strcmp(needle, token) == 0)
793 return 1;
794 }
795
796 return 0;
797}
798
799char **lxc_string_split(const char *string, char _sep)
800{
801 char *token, *str, *saveptr = NULL;
605ea1f7
CB
802 char sep[2] = {_sep, '\0'};
803 char **tmp = NULL, **result = NULL;
502657d5
CS
804 size_t result_capacity = 0;
805 size_t result_count = 0;
806 int r, saved_errno;
807
808 if (!string)
809 return calloc(1, sizeof(char *));
810
605ea1f7 811 str = alloca(strlen(string) + 1);
502657d5
CS
812 strcpy(str, string);
813 for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
814 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 16);
815 if (r < 0)
816 goto error_out;
817 result[result_count] = strdup(token);
818 if (!result[result_count])
819 goto error_out;
820 result_count++;
821 }
822
823 /* if we allocated too much, reduce it */
605ea1f7
CB
824 tmp = realloc(result, (result_count + 1) * sizeof(char *));
825 if (!tmp)
826 goto error_out;
827 result = tmp;
828 /* Make sure we don't return uninitialized memory. */
829 if (result_count == 0)
830 *result = NULL;
831 return result;
502657d5
CS
832error_out:
833 saved_errno = errno;
834 lxc_free_array((void **)result, free);
835 errno = saved_errno;
836 return NULL;
837}
838
839char **lxc_string_split_and_trim(const char *string, char _sep)
840{
841 char *token, *str, *saveptr = NULL;
842 char sep[2] = { _sep, '\0' };
843 char **result = NULL;
844 size_t result_capacity = 0;
845 size_t result_count = 0;
846 int r, saved_errno;
847 size_t i = 0;
848
849 if (!string)
850 return calloc(1, sizeof(char *));
851
852 str = alloca(strlen(string)+1);
853 strcpy(str, string);
854 for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
855 while (token[0] == ' ' || token[0] == '\t')
856 token++;
857 i = strlen(token);
858 while (i > 0 && (token[i - 1] == ' ' || token[i - 1] == '\t')) {
859 token[i - 1] = '\0';
860 i--;
861 }
862 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 16);
863 if (r < 0)
864 goto error_out;
865 result[result_count] = strdup(token);
866 if (!result[result_count])
867 goto error_out;
868 result_count++;
869 }
870
871 /* if we allocated too much, reduce it */
872 return realloc(result, (result_count + 1) * sizeof(char *));
873error_out:
874 saved_errno = errno;
875 lxc_free_array((void **)result, free);
876 errno = saved_errno;
877 return NULL;
878}
879
880void lxc_free_array(void **array, lxc_free_fn element_free_fn)
881{
882 void **p;
883 for (p = array; p && *p; p++)
884 element_free_fn(*p);
885 free((void*)array);
886}
887
888int lxc_grow_array(void ***array, size_t* capacity, size_t new_size, size_t capacity_increment)
889{
890 size_t new_capacity;
891 void **new_array;
892
893 /* first time around, catch some trivial mistakes of the user
894 * only initializing one of these */
895 if (!*array || !*capacity) {
896 *array = NULL;
897 *capacity = 0;
898 }
899
900 new_capacity = *capacity;
901 while (new_size + 1 > new_capacity)
902 new_capacity += capacity_increment;
903 if (new_capacity != *capacity) {
904 /* we have to reallocate */
905 new_array = realloc(*array, new_capacity * sizeof(void *));
906 if (!new_array)
907 return -1;
908 memset(&new_array[*capacity], 0, (new_capacity - (*capacity)) * sizeof(void *));
909 *array = new_array;
910 *capacity = new_capacity;
911 }
912
913 /* array has sufficient elements */
914 return 0;
915}
916
917size_t lxc_array_len(void **array)
918{
919 void **p;
920 size_t result = 0;
921
922 for (p = array; p && *p; p++)
923 result++;
924
925 return result;
926}
927
0e95426b
CS
928int lxc_write_to_file(const char *filename, const void* buf, size_t count, bool add_newline)
929{
930 int fd, saved_errno;
931 ssize_t ret;
932
933 fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0666);
934 if (fd < 0)
935 return -1;
936 ret = lxc_write_nointr(fd, buf, count);
937 if (ret < 0)
799f29ab 938 goto out_error;
0e95426b
CS
939 if ((size_t)ret != count)
940 goto out_error;
941 if (add_newline) {
942 ret = lxc_write_nointr(fd, "\n", 1);
943 if (ret != 1)
944 goto out_error;
945 }
946 close(fd);
947 return 0;
948
949out_error:
950 saved_errno = errno;
951 close(fd);
952 errno = saved_errno;
953 return -1;
954}
955
956int lxc_read_from_file(const char *filename, void* buf, size_t count)
957{
958 int fd = -1, saved_errno;
959 ssize_t ret;
960
961 fd = open(filename, O_RDONLY | O_CLOEXEC);
962 if (fd < 0)
963 return -1;
964
965 if (!buf || !count) {
966 char buf2[100];
967 size_t count2 = 0;
968 while ((ret = read(fd, buf2, 100)) > 0)
969 count2 += ret;
970 if (ret >= 0)
971 ret = count2;
972 } else {
973 memset(buf, 0, count);
974 ret = read(fd, buf, count);
975 }
976
977 if (ret < 0)
978 ERROR("read %s: %s", filename, strerror(errno));
979
980 saved_errno = errno;
981 close(fd);
982 errno = saved_errno;
983 return ret;
984}
799f29ab
ÇO
985
986void **lxc_append_null_to_array(void **array, size_t count)
987{
988 void **temp;
989
990 /* Append NULL to the array */
991 if (count) {
992 temp = realloc(array, (count + 1) * sizeof(*array));
993 if (!temp) {
84760c11 994 size_t i;
799f29ab
ÇO
995 for (i = 0; i < count; i++)
996 free(array[i]);
997 free(array);
998 return NULL;
999 }
1000 array = temp;
1001 array[count] = NULL;
1002 }
1003 return array;
1004}
508c263e
SH
1005
1006int randseed(bool srand_it)
1007{
1008 /*
1009 srand pre-seed function based on /dev/urandom
1010 */
1011 unsigned int seed=time(NULL)+getpid();
1012
1013 FILE *f;
1014 f = fopen("/dev/urandom", "r");
1015 if (f) {
1016 int ret = fread(&seed, sizeof(seed), 1, f);
1017 if (ret != 1)
1018 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno));
1019 fclose(f);
1020 }
1021
1022 if (srand_it)
1023 srand(seed);
1024
1025 return seed;
1026}
5d897655
SH
1027
1028uid_t get_ns_uid(uid_t orig)
1029{
1030 char *line = NULL;
1031 size_t sz = 0;
1032 uid_t nsid, hostid, range;
1033 FILE *f = fopen("/proc/self/uid_map", "r");
1034 if (!f)
1035 return 0;
1036
1037 while (getline(&line, &sz, f) != -1) {
1038 if (sscanf(line, "%u %u %u", &nsid, &hostid, &range) != 3)
1039 continue;
1040 if (hostid <= orig && hostid + range > orig) {
1041 nsid += orig - hostid;
1042 goto found;
1043 }
1044 }
1045
1046 nsid = 0;
1047found:
1048 fclose(f);
1049 free(line);
1050 return nsid;
1051}
c476bdce
SH
1052
1053bool dir_exists(const char *path)
1054{
1055 struct stat sb;
1056 int ret;
1057
1058 ret = stat(path, &sb);
1059 if (ret < 0)
1060 // could be something other than eexist, just say no
1061 return false;
1062 return S_ISDIR(sb.st_mode);
1063}
93c379f0
ÇO
1064
1065/* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1066 * FNV has good anti collision properties and we're not worried
1067 * about pre-image resistance or one-way-ness, we're just trying to make
1068 * the name unique in the 108 bytes of space we have.
1069 */
1070uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
1071{
1072 unsigned char *bp;
1073
1074 for(bp = buf; bp < (unsigned char *)buf + len; bp++)
1075 {
1076 /* xor the bottom with the current octet */
1077 hval ^= (uint64_t)*bp;
1078
1079 /* gcc optimised:
1080 * multiply by the 64 bit FNV magic prime mod 2^64
1081 */
1082 hval += (hval << 1) + (hval << 4) + (hval << 5) +
1083 (hval << 7) + (hval << 8) + (hval << 40);
1084 }
1085
1086 return hval;
1087}
2c6f3fc9
SH
1088
1089/*
1090 * Detect whether / is mounted MS_SHARED. The only way I know of to
1091 * check that is through /proc/self/mountinfo.
1092 * I'm only checking for /. If the container rootfs or mount location
1093 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1094 * out would be too much work to be worth it.
1095 */
1096#define LINELEN 4096
1097int detect_shared_rootfs(void)
1098{
1099 char buf[LINELEN], *p;
1100 FILE *f;
1101 int i;
1102 char *p2;
1103
1104 f = fopen("/proc/self/mountinfo", "r");
1105 if (!f)
1106 return 0;
1107 while (fgets(buf, LINELEN, f)) {
1108 for (p = buf, i=0; p && i < 4; i++)
b7f954bb 1109 p = strchr(p+1, ' ');
2c6f3fc9
SH
1110 if (!p)
1111 continue;
b7f954bb 1112 p2 = strchr(p+1, ' ');
2c6f3fc9
SH
1113 if (!p2)
1114 continue;
1115 *p2 = '\0';
1116 if (strcmp(p+1, "/") == 0) {
1117 // this is '/'. is it shared?
b7f954bb 1118 p = strchr(p2+1, ' ');
2c6f3fc9
SH
1119 if (p && strstr(p, "shared:")) {
1120 fclose(f);
1121 return 1;
1122 }
1123 }
1124 }
1125 fclose(f);
1126 return 0;
1127}
0e6e3a41 1128
51d0854c
DY
1129bool switch_to_ns(pid_t pid, const char *ns) {
1130 int fd, ret;
1131 char nspath[MAXPATHLEN];
1132
1133 /* Switch to new ns */
1134 ret = snprintf(nspath, MAXPATHLEN, "/proc/%d/ns/%s", pid, ns);
1135 if (ret < 0 || ret >= MAXPATHLEN)
1136 return false;
1137
1138 fd = open(nspath, O_RDONLY);
1139 if (fd < 0) {
1140 SYSERROR("failed to open %s", nspath);
1141 return false;
1142 }
1143
1144 ret = setns(fd, 0);
1145 if (ret) {
1146 SYSERROR("failed to set process %d to %s of %d.", pid, ns, fd);
1147 close(fd);
1148 return false;
1149 }
1150 close(fd);
1151 return true;
1152}
1153
b7f954bb
SH
1154/*
1155 * looking at fs/proc_namespace.c, it appears we can
1156 * actually expect the rootfs entry to very specifically contain
1157 * " - rootfs rootfs "
1158 * IIUC, so long as we've chrooted so that rootfs is not our root,
1159 * the rootfs entry should always be skipped in mountinfo contents.
1160 */
fa454c8e 1161bool detect_ramfs_rootfs(void)
b7f954bb 1162{
b7f954bb 1163 FILE *f;
fa454c8e
CB
1164 char *p, *p2;
1165 char *line = NULL;
1166 size_t len = 0;
b7f954bb 1167 int i;
b7f954bb
SH
1168
1169 f = fopen("/proc/self/mountinfo", "r");
1170 if (!f)
fa454c8e
CB
1171 return false;
1172
1173 while (getline(&line, &len, f) != -1) {
1174 for (p = line, i = 0; p && i < 4; i++)
1175 p = strchr(p + 1, ' ');
b7f954bb
SH
1176 if (!p)
1177 continue;
fa454c8e 1178 p2 = strchr(p + 1, ' ');
b7f954bb
SH
1179 if (!p2)
1180 continue;
1181 *p2 = '\0';
fa454c8e 1182 if (strcmp(p + 1, "/") == 0) {
b7f954bb 1183 // this is '/'. is it the ramfs?
fa454c8e 1184 p = strchr(p2 + 1, '-');
b7f954bb 1185 if (p && strncmp(p, "- rootfs rootfs ", 16) == 0) {
fa454c8e 1186 free(line);
b7f954bb 1187 fclose(f);
fa454c8e 1188 return true;
b7f954bb
SH
1189 }
1190 }
1191 }
fa454c8e 1192 free(line);
b7f954bb 1193 fclose(f);
fa454c8e 1194 return false;
b7f954bb
SH
1195}
1196
9d9c111c 1197char *on_path(char *cmd, const char *rootfs) {
0e6e3a41
SG
1198 char *path = NULL;
1199 char *entry = NULL;
1200 char *saveptr = NULL;
1201 char cmdpath[MAXPATHLEN];
1202 int ret;
1203
1204 path = getenv("PATH");
1205 if (!path)
8afb3e61 1206 return NULL;
0e6e3a41
SG
1207
1208 path = strdup(path);
1209 if (!path)
8afb3e61 1210 return NULL;
0e6e3a41
SG
1211
1212 entry = strtok_r(path, ":", &saveptr);
1213 while (entry) {
9d9c111c
SH
1214 if (rootfs)
1215 ret = snprintf(cmdpath, MAXPATHLEN, "%s/%s/%s", rootfs, entry, cmd);
1216 else
1217 ret = snprintf(cmdpath, MAXPATHLEN, "%s/%s", entry, cmd);
0e6e3a41
SG
1218
1219 if (ret < 0 || ret >= MAXPATHLEN)
1220 goto next_loop;
1221
1222 if (access(cmdpath, X_OK) == 0) {
1223 free(path);
8afb3e61 1224 return strdup(cmdpath);
0e6e3a41
SG
1225 }
1226
1227next_loop:
b707e368 1228 entry = strtok_r(NULL, ":", &saveptr);
0e6e3a41
SG
1229 }
1230
1231 free(path);
8afb3e61 1232 return NULL;
0e6e3a41 1233}
76a26f55
SH
1234
1235bool file_exists(const char *f)
1236{
1237 struct stat statbuf;
1238
1239 return stat(f, &statbuf) == 0;
1240}
9d9c111c 1241
12983ba4
SH
1242bool cgns_supported(void)
1243{
1244 return file_exists("/proc/self/ns/cgroup");
1245}
1246
9d9c111c
SH
1247/* historically lxc-init has been under /usr/lib/lxc and under
1248 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1249 */
1250char *choose_init(const char *rootfs)
1251{
1252 char *retv = NULL;
370ec268
SF
1253 const char *empty = "",
1254 *tmp;
9d9c111c
SH
1255 int ret, env_set = 0;
1256 struct stat mystat;
1257
1258 if (!getenv("PATH")) {
1259 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1260 SYSERROR("Failed to setenv");
1261 env_set = 1;
1262 }
1263
1264 retv = on_path("init.lxc", rootfs);
1265
1266 if (env_set) {
1267 if (unsetenv("PATH"))
1268 SYSERROR("Failed to unsetenv");
1269 }
1270
1271 if (retv)
1272 return retv;
1273
1274 retv = malloc(PATH_MAX);
1275 if (!retv)
1276 return NULL;
1277
1278 if (rootfs)
370ec268 1279 tmp = rootfs;
9d9c111c 1280 else
370ec268
SF
1281 tmp = empty;
1282
1283 ret = snprintf(retv, PATH_MAX, "%s/%s/%s", tmp, SBINDIR, "/init.lxc");
9d9c111c
SH
1284 if (ret < 0 || ret >= PATH_MAX) {
1285 ERROR("pathname too long");
1286 goto out1;
1287 }
1288
1289 ret = stat(retv, &mystat);
1290 if (ret == 0)
1291 return retv;
1292
370ec268 1293 ret = snprintf(retv, PATH_MAX, "%s/%s/%s", tmp, LXCINITDIR, "/lxc/lxc-init");
9d9c111c
SH
1294 if (ret < 0 || ret >= PATH_MAX) {
1295 ERROR("pathname too long");
1296 goto out1;
1297 }
1298
1299 ret = stat(retv, &mystat);
1300 if (ret == 0)
1301 return retv;
1302
370ec268 1303 ret = snprintf(retv, PATH_MAX, "%s/usr/lib/lxc/lxc-init", tmp);
9d9c111c
SH
1304 if (ret < 0 || ret >= PATH_MAX) {
1305 ERROR("pathname too long");
1306 goto out1;
1307 }
1308 ret = stat(retv, &mystat);
1309 if (ret == 0)
1310 return retv;
1311
370ec268 1312 ret = snprintf(retv, PATH_MAX, "%s/sbin/lxc-init", tmp);
9d9c111c
SH
1313 if (ret < 0 || ret >= PATH_MAX) {
1314 ERROR("pathname too long");
1315 goto out1;
1316 }
1317 ret = stat(retv, &mystat);
1318 if (ret == 0)
1319 return retv;
1320
1321 /*
1322 * Last resort, look for the statically compiled init.lxc which we
1323 * hopefully bind-mounted in.
1324 * If we are called during container setup, and we get to this point,
1325 * then the init.lxc.static from the host will need to be bind-mounted
1326 * in. So we return NULL here to indicate that.
1327 */
1328 if (rootfs)
1329 goto out1;
1330
1331 ret = snprintf(retv, PATH_MAX, "/init.lxc.static");
1332 if (ret < 0 || ret >= PATH_MAX) {
1333 WARN("Nonsense - name /lxc.init.static too long");
1334 goto out1;
1335 }
1336 ret = stat(retv, &mystat);
1337 if (ret == 0)
1338 return retv;
1339
1340out1:
1341 free(retv);
1342 return NULL;
1343}
735f2c6e
TA
1344
1345int print_to_file(const char *file, const char *content)
1346{
1347 FILE *f;
1348 int ret = 0;
1349
1350 f = fopen(file, "w");
1351 if (!f)
1352 return -1;
1353 if (fprintf(f, "%s", content) != strlen(content))
1354 ret = -1;
1355 fclose(f);
1356 return ret;
1357}
e1daebd9
SH
1358
1359int is_dir(const char *path)
1360{
1361 struct stat statbuf;
1362 int ret = stat(path, &statbuf);
1363 if (ret == 0 && S_ISDIR(statbuf.st_mode))
1364 return 1;
1365 return 0;
1366}
6010a416
SG
1367
1368/*
1369 * Given the '-t' template option to lxc-create, figure out what to
1370 * do. If the template is a full executable path, use that. If it
1371 * is something like 'sshd', then return $templatepath/lxc-sshd.
1372 * On success return the template, on error return NULL.
1373 */
1374char *get_template_path(const char *t)
1375{
1376 int ret, len;
1377 char *tpath;
1378
1379 if (t[0] == '/' && access(t, X_OK) == 0) {
1380 tpath = strdup(t);
1381 return tpath;
1382 }
1383
1384 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
1385 tpath = malloc(len);
1386 if (!tpath)
1387 return NULL;
1388 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
1389 if (ret < 0 || ret >= len) {
1390 free(tpath);
1391 return NULL;
1392 }
1393 if (access(tpath, X_OK) < 0) {
1394 SYSERROR("bad template: %s", t);
1395 free(tpath);
1396 return NULL;
1397 }
1398
1399 return tpath;
1400}
0a4be28d
TA
1401
1402/*
1403 * Sets the process title to the specified title. Note:
1404 * 1. this function requires root to succeed
1405 * 2. it clears /proc/self/environ
1406 * 3. it may not succed (e.g. if title is longer than /proc/self/environ +
1407 * the original title)
1408 */
1409int setproctitle(char *title)
1410{
058b94fe 1411 static char *proctitle = NULL;
0a4be28d
TA
1412 char buf[2048], *tmp;
1413 FILE *f;
1414 int i, len, ret = 0;
93525c00
TA
1415
1416 /* We don't really need to know all of this stuff, but unfortunately
1417 * PR_SET_MM_MAP requires us to set it all at once, so we have to
1418 * figure it out anyway.
1419 */
1420 unsigned long start_data, end_data, start_brk, start_code, end_code,
1421 start_stack, arg_start, arg_end, env_start, env_end,
1422 brk_val;
1423 struct prctl_mm_map prctl_map;
0a4be28d
TA
1424
1425 f = fopen_cloexec("/proc/self/stat", "r");
1426 if (!f) {
1427 return -1;
1428 }
1429
1430 tmp = fgets(buf, sizeof(buf), f);
1431 fclose(f);
1432 if (!tmp) {
1433 return -1;
1434 }
1435
93525c00
TA
1436 /* Skip the first 25 fields, column 26-28 are start_code, end_code,
1437 * and start_stack */
0a4be28d 1438 tmp = strchr(buf, ' ');
93525c00 1439 for (i = 0; i < 24; i++) {
0a4be28d
TA
1440 if (!tmp)
1441 return -1;
1442 tmp = strchr(tmp+1, ' ');
1443 }
73c1c887
SH
1444 if (!tmp)
1445 return -1;
1446
93525c00
TA
1447 i = sscanf(tmp, "%lu %lu %lu", &start_code, &end_code, &start_stack);
1448 if (i != 3)
0a4be28d 1449 return -1;
93525c00
TA
1450
1451 /* Skip the next 19 fields, column 45-51 are start_data to arg_end */
1452 for (i = 0; i < 19; i++) {
1453 if (!tmp)
1454 return -1;
1455 tmp = strchr(tmp+1, ' ');
0a4be28d
TA
1456 }
1457
93525c00
TA
1458 if (!tmp)
1459 return -1;
1460
1461 i = sscanf(tmp, "%lu %lu %lu %lu %lu %lu %lu",
1462 &start_data,
1463 &end_data,
1464 &start_brk,
1465 &arg_start,
1466 &arg_end,
1467 &env_start,
1468 &env_end);
1469 if (i != 7)
1470 return -1;
1471
96fe6d1d
TA
1472 /* Include the null byte here, because in the calculations below we
1473 * want to have room for it. */
1474 len = strlen(title) + 1;
1475
058b94fe
TA
1476 /* If we don't have enough room by just overwriting the old proctitle,
1477 * let's allocate a new one.
1478 */
1479 if (len > arg_end - arg_start) {
1480 void *m;
1481 m = realloc(proctitle, len);
1482 if (!m)
70642c33 1483 return -1;
058b94fe 1484 proctitle = m;
70642c33 1485
058b94fe 1486 arg_start = (unsigned long) proctitle;
0a4be28d
TA
1487 }
1488
058b94fe
TA
1489 arg_end = arg_start + len;
1490
93525c00 1491 brk_val = syscall(__NR_brk, 0);
0a4be28d 1492
93525c00
TA
1493 prctl_map = (struct prctl_mm_map) {
1494 .start_code = start_code,
1495 .end_code = end_code,
1496 .start_stack = start_stack,
1497 .start_data = start_data,
1498 .end_data = end_data,
1499 .start_brk = start_brk,
1500 .brk = brk_val,
1501 .arg_start = arg_start,
1502 .arg_end = arg_end,
1503 .env_start = env_start,
1504 .env_end = env_end,
1505 .auxv = NULL,
1506 .auxv_size = 0,
1507 .exe_fd = -1,
1508 };
1509
1510 ret = prctl(PR_SET_MM, PR_SET_MM_MAP, (long) &prctl_map, sizeof(prctl_map), 0);
1511 if (ret == 0)
1512 strcpy((char*)arg_start, title);
1513 else
2681c0e7 1514 INFO("setting cmdline failed - %s", strerror(errno));
0a4be28d
TA
1515
1516 return ret;
1517}
ced03a01 1518
592fd47a
SH
1519/*
1520 * @path: a pathname where / replaced with '\0'.
1521 * @offsetp: pointer to int showing which path segment was last seen.
1522 * Updated on return to reflect the next segment.
1523 * @fulllen: full original path length.
1524 * Returns a pointer to the next path segment, or NULL if done.
1525 */
1526static char *get_nextpath(char *path, int *offsetp, int fulllen)
1527{
1528 int offset = *offsetp;
1529
1530 if (offset >= fulllen)
1531 return NULL;
1532
1533 while (path[offset] != '\0' && offset < fulllen)
1534 offset++;
1535 while (path[offset] == '\0' && offset < fulllen)
1536 offset++;
1537
1538 *offsetp = offset;
1539 return (offset < fulllen) ? &path[offset] : NULL;
1540}
1541
1542/*
1543 * Check that @subdir is a subdir of @dir. @len is the length of
1544 * @dir (to avoid having to recalculate it).
1545 */
1546static bool is_subdir(const char *subdir, const char *dir, size_t len)
1547{
1548 size_t subdirlen = strlen(subdir);
1549
1550 if (subdirlen < len)
1551 return false;
1552 if (strncmp(subdir, dir, len) != 0)
1553 return false;
1554 if (dir[len-1] == '/')
1555 return true;
1556 if (subdir[len] == '/' || subdirlen == len)
1557 return true;
1558 return false;
1559}
1560
1561/*
1562 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1563 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1564 */
1565static int check_symlink(int fd)
1566{
1567 struct stat sb;
1568 int ret = fstat(fd, &sb);
1569 if (ret < 0)
1570 return -ENOENT;
1571 if (S_ISLNK(sb.st_mode))
1572 return -ELOOP;
1573 return 0;
1574}
1575
1576/*
1577 * Open a file or directory, provided that it contains no symlinks.
1578 *
1579 * CAVEAT: This function must not be used for other purposes than container
1580 * setup before executing the container's init
1581 */
1582static int open_if_safe(int dirfd, const char *nextpath)
1583{
1584 int newfd = openat(dirfd, nextpath, O_RDONLY | O_NOFOLLOW);
1585 if (newfd >= 0) // was not a symlink, all good
1586 return newfd;
1587
1588 if (errno == ELOOP)
1589 return newfd;
1590
1591 if (errno == EPERM || errno == EACCES) {
1592 /* we're not root (cause we got EPERM) so
1593 try opening with O_PATH */
1594 newfd = openat(dirfd, nextpath, O_PATH | O_NOFOLLOW);
1595 if (newfd >= 0) {
1596 /* O_PATH will return an fd for symlinks. We know
1597 * nextpath wasn't a symlink at last openat, so if fd
1598 * is now a link, then something * fishy is going on
1599 */
1600 int ret = check_symlink(newfd);
1601 if (ret < 0) {
1602 close(newfd);
1603 newfd = ret;
1604 }
1605 }
1606 }
1607
1608 return newfd;
1609}
1610
1611/*
1612 * Open a path intending for mounting, ensuring that the final path
1613 * is inside the container's rootfs.
1614 *
1615 * CAVEAT: This function must not be used for other purposes than container
1616 * setup before executing the container's init
1617 *
1618 * @target: path to be opened
1619 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1620 * would be the container's rootfs.
1621 *
1622 * Return an open fd for the path, or <0 on error.
1623 */
1624static int open_without_symlink(const char *target, const char *prefix_skip)
1625{
1626 int curlen = 0, dirfd, fulllen, i;
1627 char *dup = NULL;
1628
1629 fulllen = strlen(target);
1630
1631 /* make sure prefix-skip makes sense */
01074e5b 1632 if (prefix_skip && strlen(prefix_skip) > 0) {
592fd47a
SH
1633 curlen = strlen(prefix_skip);
1634 if (!is_subdir(target, prefix_skip, curlen)) {
1635 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1636 target, prefix_skip);
1637 return -EINVAL;
1638 }
1639 /*
1640 * get_nextpath() expects the curlen argument to be
1641 * on a (turned into \0) / or before it, so decrement
1642 * curlen to make sure that happens
1643 */
1644 if (curlen)
1645 curlen--;
1646 } else {
1647 prefix_skip = "/";
1648 curlen = 0;
1649 }
1650
1651 /* Make a copy of target which we can hack up, and tokenize it */
1652 if ((dup = strdup(target)) == NULL) {
1653 SYSERROR("Out of memory checking for symbolic link");
1654 return -ENOMEM;
1655 }
1656 for (i = 0; i < fulllen; i++) {
1657 if (dup[i] == '/')
1658 dup[i] = '\0';
1659 }
1660
1661 dirfd = open(prefix_skip, O_RDONLY);
1662 if (dirfd < 0)
1663 goto out;
1664 while (1) {
1665 int newfd, saved_errno;
1666 char *nextpath;
1667
1668 if ((nextpath = get_nextpath(dup, &curlen, fulllen)) == NULL)
1669 goto out;
1670 newfd = open_if_safe(dirfd, nextpath);
1671 saved_errno = errno;
1672 close(dirfd);
1673 dirfd = newfd;
1674 if (newfd < 0) {
1675 errno = saved_errno;
1676 if (errno == ELOOP)
1677 SYSERROR("%s in %s was a symbolic link!", nextpath, target);
592fd47a
SH
1678 goto out;
1679 }
1680 }
1681
1682out:
1683 free(dup);
1684 return dirfd;
1685}
1686
1687/*
1688 * Safely mount a path into a container, ensuring that the mount target
1689 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1690 * uses the host's /)
1691 *
1692 * CAVEAT: This function must not be used for other purposes than container
1693 * setup before executing the container's init
1694 */
1695int safe_mount(const char *src, const char *dest, const char *fstype,
1696 unsigned long flags, const void *data, const char *rootfs)
1697{
1698 int srcfd = -1, destfd, ret, saved_errno;
1699 char srcbuf[50], destbuf[50]; // only needs enough for /proc/self/fd/<fd>
1700 const char *mntsrc = src;
1701
1702 if (!rootfs)
1703 rootfs = "";
1704
1705 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1706 if (flags & MS_BIND && src && src[0] != '/') {
1707 INFO("this is a relative bind mount");
1708 srcfd = open_without_symlink(src, NULL);
1709 if (srcfd < 0)
1710 return srcfd;
1711 ret = snprintf(srcbuf, 50, "/proc/self/fd/%d", srcfd);
1712 if (ret < 0 || ret > 50) {
1713 close(srcfd);
1714 ERROR("Out of memory");
1715 return -EINVAL;
1716 }
1717 mntsrc = srcbuf;
1718 }
1719
1720 destfd = open_without_symlink(dest, rootfs);
1721 if (destfd < 0) {
88e078ba
CB
1722 if (srcfd != -1) {
1723 saved_errno = errno;
592fd47a 1724 close(srcfd);
88e078ba
CB
1725 errno = saved_errno;
1726 }
592fd47a
SH
1727 return destfd;
1728 }
1729
1730 ret = snprintf(destbuf, 50, "/proc/self/fd/%d", destfd);
1731 if (ret < 0 || ret > 50) {
1732 if (srcfd != -1)
1733 close(srcfd);
1734 close(destfd);
1735 ERROR("Out of memory");
1736 return -EINVAL;
1737 }
1738
1739 ret = mount(mntsrc, destbuf, fstype, flags, data);
1740 saved_errno = errno;
1741 if (srcfd != -1)
1742 close(srcfd);
1743 close(destfd);
1744 if (ret < 0) {
1745 errno = saved_errno;
1746 SYSERROR("Failed to mount %s onto %s", src, dest);
1747 return ret;
1748 }
1749
1750 return 0;
1751}
1752
ced03a01
SH
1753/*
1754 * Mount a proc under @rootfs if proc self points to a pid other than
1755 * my own. This is needed to have a known-good proc mount for setting
1756 * up LSMs both at container startup and attach.
1757 *
1758 * @rootfs : the rootfs where proc should be mounted
1759 *
1760 * Returns < 0 on failure, 0 if the correct proc was already mounted
1761 * and 1 if a new proc was mounted.
f267d666
BP
1762 *
1763 * NOTE: not to be called from inside the container namespace!
ced03a01
SH
1764 */
1765int mount_proc_if_needed(const char *rootfs)
1766{
1767 char path[MAXPATHLEN];
1768 char link[20];
1769 int linklen, ret;
fe447886 1770 int mypid;
ced03a01
SH
1771
1772 ret = snprintf(path, MAXPATHLEN, "%s/proc/self", rootfs);
1773 if (ret < 0 || ret >= MAXPATHLEN) {
1774 SYSERROR("proc path name too long");
1775 return -1;
1776 }
1777 memset(link, 0, 20);
1778 linklen = readlink(path, link, 20);
fe447886
SH
1779 mypid = (int)getpid();
1780 INFO("I am %d, /proc/self points to '%s'", mypid, link);
ced03a01 1781 ret = snprintf(path, MAXPATHLEN, "%s/proc", rootfs);
d539a2b2
CB
1782 if (ret < 0 || ret >= MAXPATHLEN) {
1783 SYSERROR("proc path name too long");
1784 return -1;
1785 }
ced03a01
SH
1786 if (linklen < 0) /* /proc not mounted */
1787 goto domount;
fe447886 1788 if (atoi(link) != mypid) {
ced03a01
SH
1789 /* wrong /procs mounted */
1790 umount2(path, MNT_DETACH); /* ignore failure */
1791 goto domount;
1792 }
1793 /* the right proc is already mounted */
1794 return 0;
1795
1796domount:
f267d666
BP
1797 if (!strcmp(rootfs,"")) /* rootfs is NULL */
1798 ret = mount("proc", path, "proc", 0, NULL);
1799 else
1800 ret = safe_mount("proc", path, "proc", 0, NULL, rootfs);
1801
1802 if (ret < 0)
ced03a01 1803 return -1;
f267d666 1804
ced03a01
SH
1805 INFO("Mounted /proc in container for security transition");
1806 return 1;
1807}
69aeabac 1808
f8dd0275 1809int open_devnull(void)
69aeabac 1810{
f8dd0275
AM
1811 int fd = open("/dev/null", O_RDWR);
1812
1813 if (fd < 0)
1814 SYSERROR("Can't open /dev/null");
1815
1816 return fd;
1817}
69aeabac 1818
f8dd0275
AM
1819int set_stdfds(int fd)
1820{
69aeabac
TA
1821 if (fd < 0)
1822 return -1;
1823
1824 if (dup2(fd, 0) < 0)
f8dd0275 1825 return -1;
69aeabac 1826 if (dup2(fd, 1) < 0)
f8dd0275 1827 return -1;
69aeabac 1828 if (dup2(fd, 2) < 0)
f8dd0275
AM
1829 return -1;
1830
1831 return 0;
1832}
1833
1834int null_stdfds(void)
1835{
1836 int ret = -1;
1837 int fd = open_devnull();
1838
1839 if (fd >= 0) {
1840 ret = set_stdfds(fd);
1841 close(fd);
1842 }
69aeabac 1843
69aeabac
TA
1844 return ret;
1845}
ccb4cabe
SH
1846
1847/*
1848 * Return the number of lines in file @fn, or -1 on error
1849 */
1850int lxc_count_file_lines(const char *fn)
1851{
1852 FILE *f;
1853 char *line = NULL;
1854 size_t sz = 0;
1855 int n = 0;
1856
1857 f = fopen_cloexec(fn, "r");
1858 if (!f)
1859 return -1;
1860
1861 while (getline(&line, &sz, f) != -1) {
1862 n++;
1863 }
1864 free(line);
1865 fclose(f);
1866 return n;
1867}
1adbd020 1868
25086a5f
CB
1869void *lxc_strmmap(void *addr, size_t length, int prot, int flags, int fd,
1870 off_t offset)
1adbd020
CB
1871{
1872 void *tmp = NULL, *overlap = NULL;
1873
1874 /* We establish an anonymous mapping that is one byte larger than the
1875 * underlying file. The pages handed to us are zero filled. */
1876 tmp = mmap(addr, length + 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1877 if (tmp == MAP_FAILED)
a1e5280d 1878 return tmp;
1adbd020
CB
1879
1880 /* Now we establish a fixed-address mapping starting at the address we
1881 * received from our anonymous mapping and replace all bytes excluding
1882 * the additional \0-byte with the file. This allows us to use normal
a1e5280d 1883 * string-handling functions. */
1adbd020
CB
1884 overlap = mmap(tmp, length, prot, MAP_FIXED | flags, fd, offset);
1885 if (overlap == MAP_FAILED)
a1e5280d 1886 munmap(tmp, length + 1);
1adbd020 1887
1adbd020
CB
1888 return overlap;
1889}
1890
25086a5f 1891int lxc_strmunmap(void *addr, size_t length)
1adbd020
CB
1892{
1893 return munmap(addr, length + 1);
1894}
330ae3d3
CB
1895
1896/* Check whether a signal is blocked by a process. */
1897bool task_blocking_signal(pid_t pid, int signal)
1898{
1899 bool bret = false;
1900 char *line = NULL;
1901 long unsigned int sigblk = 0;
1902 size_t n = 0;
1903 int ret;
1904 FILE *f;
1905
1906 /* The largest integer that can fit into long int is 2^64. This is a
1907 * 20-digit number. */
1908 size_t len = /* /proc */ 5 + /* /pid-to-str */ 21 + /* /status */ 7 + /* \0 */ 1;
1909 char status[len];
1910
1911 ret = snprintf(status, len, "/proc/%d/status", pid);
1912 if (ret < 0 || ret >= len)
1913 return bret;
1914
1915 f = fopen(status, "r");
1916 if (!f)
1917 return bret;
1918
1919 while (getline(&line, &n, f) != -1) {
1920 if (!strncmp(line, "SigBlk:\t", 8))
1921 if (sscanf(line + 8, "%lx", &sigblk) != 1)
1922 goto out;
1923 }
1924
1925 if (sigblk & signal)
1926 bret = true;
1927
1928out:
1929 free(line);
1930 fclose(f);
1931 return bret;
1932}
000dfda7
CB
1933
1934static int lxc_append_null_to_list(void ***list)
1935{
1936 int newentry = 0;
1937 void **tmp;
1938
1939 if (*list)
1940 for (; (*list)[newentry]; newentry++) {
1941 ;
1942 }
1943
1944 tmp = realloc(*list, (newentry + 2) * sizeof(void **));
1945 if (!tmp)
1946 return -1;
1947
1948 *list = tmp;
1949 (*list)[newentry + 1] = NULL;
1950
1951 return newentry;
1952}
1953
1954int lxc_append_string(char ***list, char *entry)
1955{
1956 int newentry = lxc_append_null_to_list((void ***)list);
1957 char *copy;
1958
1959 copy = strdup(entry);
1960 if (!copy)
1961 return -1;
1962
1963 (*list)[newentry] = copy;
1964
1965 return 0;
1966}