]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/utils.c
utils: add has_fs_type() + is_fs_type()
[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
7935833c 26#define __STDC_FORMAT_MACROS /* Required for PRIu64 to work. */
643c1984 27#include <ctype.h>
a1e5280d 28#include <dirent.h>
e3642c43 29#include <errno.h>
a1e5280d 30#include <fcntl.h>
dbaf55a3 31#include <grp.h>
7935833c 32#include <inttypes.h>
a1e5280d 33#include <libgen.h>
d983b93c 34#include <stddef.h>
a1e5280d
CB
35#include <stdio.h>
36#include <stdlib.h>
61a1d519 37#include <string.h>
981f6029 38#include <unistd.h>
e3642c43 39#include <sys/mman.h>
6e4bb2e0 40#include <sys/mount.h>
a1e5280d
CB
41#include <sys/param.h>
42#include <sys/prctl.h>
43#include <sys/stat.h>
9be53773 44#include <sys/types.h>
a1e5280d 45#include <sys/vfs.h>
9be53773 46#include <sys/wait.h>
e3642c43
DL
47
48#include "log.h"
025ed0f3 49#include "lxclock.h"
51d0854c 50#include "namespace.h"
981f6029 51#include "utils.h"
e3642c43 52
5d6ef228
SG
53#ifndef PR_SET_MM
54#define PR_SET_MM 35
55#endif
56
8d2ede58
TA
57#ifndef PR_SET_MM_MAP
58#define PR_SET_MM_MAP 14
553347e4 59
8d2ede58
TA
60struct prctl_mm_map {
61 uint64_t start_code;
62 uint64_t end_code;
63 uint64_t start_data;
64 uint64_t end_data;
65 uint64_t start_brk;
66 uint64_t brk;
67 uint64_t start_stack;
68 uint64_t arg_start;
69 uint64_t arg_end;
70 uint64_t env_start;
71 uint64_t env_end;
72 uint64_t *auxv;
73 uint32_t auxv_size;
74 uint32_t exe_fd;
1adbd020 75};
553347e4
TA
76#endif
77
4928c718
SG
78#ifndef O_PATH
79#define O_PATH 010000000
80#endif
81
82#ifndef O_NOFOLLOW
83#define O_NOFOLLOW 00400000
84#endif
85
e3642c43
DL
86lxc_log_define(lxc_utils, lxc);
87
4295c5de
SH
88/*
89 * if path is btrfs, tries to remove it and any subvolumes beneath it
90 */
91extern bool btrfs_try_remove_subvol(const char *path);
92
0cc417b2
SH
93static int _recursive_rmdir(char *dirname, dev_t pdev,
94 const char *exclude, int level, bool onedev)
60bf62d4 95{
74f96976 96 struct dirent *direntp;
60bf62d4
SH
97 DIR *dir;
98 int ret, failed=0;
99 char pathname[MAXPATHLEN];
18aa217b 100 bool hadexclude = false;
60bf62d4
SH
101
102 dir = opendir(dirname);
103 if (!dir) {
b103ceac 104 ERROR("failed to open %s", dirname);
4355ab5f 105 return -1;
60bf62d4
SH
106 }
107
74f96976 108 while ((direntp = readdir(dir))) {
60bf62d4
SH
109 struct stat mystat;
110 int rc;
111
112 if (!direntp)
113 break;
114
115 if (!strcmp(direntp->d_name, ".") ||
116 !strcmp(direntp->d_name, ".."))
117 continue;
118
119 rc = snprintf(pathname, MAXPATHLEN, "%s/%s", dirname, direntp->d_name);
120 if (rc < 0 || rc >= MAXPATHLEN) {
121 ERROR("pathname too long");
122 failed=1;
123 continue;
124 }
18aa217b
SH
125
126 if (!level && exclude && !strcmp(direntp->d_name, exclude)) {
127 ret = rmdir(pathname);
128 if (ret < 0) {
129 switch(errno) {
130 case ENOTEMPTY:
0cc417b2 131 INFO("Not deleting snapshot %s", pathname);
18aa217b
SH
132 hadexclude = true;
133 break;
134 case ENOTDIR:
135 ret = unlink(pathname);
136 if (ret)
b103ceac 137 INFO("Failed to remove %s", pathname);
18aa217b
SH
138 break;
139 default:
b103ceac 140 SYSERROR("Failed to rmdir %s", pathname);
18aa217b
SH
141 failed = 1;
142 break;
143 }
144 }
145 continue;
146 }
147
60bf62d4
SH
148 ret = lstat(pathname, &mystat);
149 if (ret) {
b103ceac 150 ERROR("Failed to stat %s", pathname);
4295c5de 151 failed = 1;
60bf62d4
SH
152 continue;
153 }
4295c5de
SH
154 if (onedev && mystat.st_dev != pdev) {
155 /* TODO should we be checking /proc/self/mountinfo for
156 * pathname and not doing this if found? */
157 if (btrfs_try_remove_subvol(pathname))
158 INFO("Removed btrfs subvolume at %s\n", pathname);
60bf62d4 159 continue;
4295c5de 160 }
60bf62d4 161 if (S_ISDIR(mystat.st_mode)) {
0cc417b2 162 if (_recursive_rmdir(pathname, pdev, exclude, level+1, onedev) < 0)
60bf62d4
SH
163 failed=1;
164 } else {
165 if (unlink(pathname) < 0) {
b103ceac 166 SYSERROR("Failed to delete %s", pathname);
60bf62d4
SH
167 failed=1;
168 }
169 }
170 }
171
4295c5de 172 if (rmdir(dirname) < 0 && !btrfs_try_remove_subvol(dirname) && !hadexclude) {
b103ceac 173 ERROR("Failed to delete %s", dirname);
4295c5de 174 failed=1;
60bf62d4
SH
175 }
176
025ed0f3 177 ret = closedir(dir);
025ed0f3 178 if (ret) {
b103ceac 179 ERROR("Failed to close directory %s", dirname);
60bf62d4
SH
180 failed=1;
181 }
182
4355ab5f 183 return failed ? -1 : 0;
60bf62d4
SH
184}
185
0cc417b2
SH
186/* we have two different magic values for overlayfs, yay */
187#define OVERLAYFS_SUPER_MAGIC 0x794c764f
188#define OVERLAY_SUPER_MAGIC 0x794c7630
189/*
190 * In overlayfs, st_dev is unreliable. so on overlayfs we don't do
191 * the lxc_rmdir_onedev()
192 */
193static bool is_native_overlayfs(const char *path)
194{
195 struct statfs sb;
196
197 if (statfs(path, &sb) < 0)
198 return false;
199 if (sb.f_type == OVERLAYFS_SUPER_MAGIC ||
200 sb.f_type == OVERLAY_SUPER_MAGIC)
201 return true;
202 return false;
203}
204
4355ab5f 205/* returns 0 on success, -1 if there were any failures */
18aa217b 206extern int lxc_rmdir_onedev(char *path, const char *exclude)
60bf62d4
SH
207{
208 struct stat mystat;
0cc417b2
SH
209 bool onedev = true;
210
211 if (is_native_overlayfs(path)) {
212 onedev = false;
213 }
60bf62d4
SH
214
215 if (lstat(path, &mystat) < 0) {
067650d0
SH
216 if (errno == ENOENT)
217 return 0;
b103ceac 218 ERROR("Failed to stat %s", path);
4355ab5f 219 return -1;
60bf62d4
SH
220 }
221
0cc417b2 222 return _recursive_rmdir(path, mystat.st_dev, exclude, 0, onedev);
60bf62d4
SH
223}
224
9ddaf3bf 225/* borrowed from iproute2 */
7c11d57a 226extern int get_u16(unsigned short *val, const char *arg, int base)
9ddaf3bf
JHS
227{
228 unsigned long res;
229 char *ptr;
230
231 if (!arg || !*arg)
232 return -1;
233
09bbd745 234 errno = 0;
9ddaf3bf 235 res = strtoul(arg, &ptr, base);
09bbd745 236 if (!ptr || ptr == arg || *ptr || res > 0xFFFF || errno != 0)
9ddaf3bf
JHS
237 return -1;
238
239 *val = res;
240
241 return 0;
242}
243
3ce74686 244extern int mkdir_p(const char *dir, mode_t mode)
1b09f2c0 245{
3ce74686
SH
246 const char *tmp = dir;
247 const char *orig = dir;
860fc865
RW
248 char *makeme;
249
250 do {
251 dir = tmp + strspn(tmp, "/");
252 tmp = dir + strcspn(dir, "/");
d74325c4 253 makeme = strndup(orig, dir - orig);
860fc865
RW
254 if (*makeme) {
255 if (mkdir(makeme, mode) && errno != EEXIST) {
959aee9c 256 SYSERROR("failed to create directory '%s'", makeme);
d74325c4 257 free(makeme);
860fc865
RW
258 return -1;
259 }
260 }
d74325c4 261 free(makeme);
860fc865 262 } while(tmp != dir);
1b09f2c0 263
98663823 264 return 0;
1b09f2c0 265}
2a59a681 266
44b9ae4b 267char *get_rundir()
9e60f51d 268{
97a696c6
SG
269 char *rundir;
270 const char *homedir;
9e60f51d 271
d6470e71 272 if (geteuid() == 0) {
c580b8d2 273 rundir = strdup(RUNTIME_PATH);
d6470e71
SG
274 return rundir;
275 }
97a696c6
SG
276
277 rundir = getenv("XDG_RUNTIME_DIR");
44b9ae4b
SG
278 if (rundir) {
279 rundir = strdup(rundir);
280 return rundir;
281 }
97a696c6 282
44b9ae4b
SG
283 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
284 homedir = getenv("HOME");
285 if (!homedir) {
286 ERROR("HOME isn't set in the environment.");
287 return NULL;
97a696c6
SG
288 }
289
44b9ae4b
SG
290 rundir = malloc(sizeof(char) * (17 + strlen(homedir)));
291 sprintf(rundir, "%s/.cache/lxc/run/", homedir);
292
9e60f51d
DE
293 return rundir;
294}
295
9be53773
SH
296int wait_for_pid(pid_t pid)
297{
298 int status, ret;
299
300again:
301 ret = waitpid(pid, &status, 0);
302 if (ret == -1) {
71b9b8ed 303 if (errno == EINTR)
9be53773
SH
304 goto again;
305 return -1;
306 }
307 if (ret != pid)
308 goto again;
309 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
310 return -1;
311 return 0;
312}
c797a220
CS
313
314int lxc_wait_for_pid_status(pid_t pid)
315{
316 int status, ret;
317
318again:
319 ret = waitpid(pid, &status, 0);
320 if (ret == -1) {
321 if (errno == EINTR)
322 goto again;
323 return -1;
324 }
325 if (ret != pid)
326 goto again;
327 return status;
328}
92f023dc 329
650468bb 330ssize_t lxc_write_nointr(int fd, const void* buf, size_t count)
92f023dc 331{
650468bb 332 ssize_t ret;
92f023dc
CS
333again:
334 ret = write(fd, buf, count);
335 if (ret < 0 && errno == EINTR)
336 goto again;
337 return ret;
338}
339
650468bb 340ssize_t lxc_read_nointr(int fd, void* buf, size_t count)
92f023dc 341{
650468bb 342 ssize_t ret;
92f023dc
CS
343again:
344 ret = read(fd, buf, count);
345 if (ret < 0 && errno == EINTR)
346 goto again;
347 return ret;
348}
349
650468bb 350ssize_t lxc_read_nointr_expect(int fd, void* buf, size_t count, const void* expected_buf)
92f023dc 351{
650468bb 352 ssize_t ret;
92f023dc
CS
353 ret = lxc_read_nointr(fd, buf, count);
354 if (ret <= 0)
355 return ret;
650468bb 356 if ((size_t)ret != count)
92f023dc
CS
357 return -1;
358 if (expected_buf && memcmp(buf, expected_buf, count) != 0) {
359 errno = EINVAL;
360 return -1;
361 }
362 return ret;
363}
3ce74686
SH
364
365#if HAVE_LIBGNUTLS
366#include <gnutls/gnutls.h>
367#include <gnutls/crypto.h>
41246cee
DE
368
369__attribute__((constructor))
370static void gnutls_lxc_init(void)
371{
372 gnutls_global_init();
373}
374
3ce74686
SH
375int sha1sum_file(char *fnam, unsigned char *digest)
376{
377 char *buf;
378 int ret;
379 FILE *f;
380 long flen;
381
382 if (!fnam)
383 return -1;
025ed0f3 384 f = fopen_cloexec(fnam, "r");
7be677a8 385 if (!f) {
3ce74686
SH
386 SYSERROR("Error opening template");
387 return -1;
388 }
389 if (fseek(f, 0, SEEK_END) < 0) {
390 SYSERROR("Error seeking to end of template");
dd1d77f9 391 fclose(f);
3ce74686
SH
392 return -1;
393 }
394 if ((flen = ftell(f)) < 0) {
395 SYSERROR("Error telling size of template");
dd1d77f9 396 fclose(f);
3ce74686
SH
397 return -1;
398 }
399 if (fseek(f, 0, SEEK_SET) < 0) {
400 SYSERROR("Error seeking to start of template");
dd1d77f9 401 fclose(f);
3ce74686
SH
402 return -1;
403 }
404 if ((buf = malloc(flen+1)) == NULL) {
405 SYSERROR("Out of memory");
dd1d77f9 406 fclose(f);
3ce74686
SH
407 return -1;
408 }
409 if (fread(buf, 1, flen, f) != flen) {
410 SYSERROR("Failure reading template");
411 free(buf);
dd1d77f9 412 fclose(f);
3ce74686
SH
413 return -1;
414 }
dd1d77f9 415 if (fclose(f) < 0) {
3ce74686
SH
416 SYSERROR("Failre closing template");
417 free(buf);
418 return -1;
419 }
420 buf[flen] = '\0';
421 ret = gnutls_hash_fast(GNUTLS_DIG_SHA1, buf, flen, (void *)digest);
422 free(buf);
423 return ret;
424}
425#endif
61a1d519
CS
426
427char** lxc_va_arg_list_to_argv(va_list ap, size_t skip, int do_strdup)
428{
429 va_list ap2;
430 size_t count = 1 + skip;
431 char **result;
432
433 /* first determine size of argument list, we don't want to reallocate
434 * constantly...
435 */
436 va_copy(ap2, ap);
437 while (1) {
438 char* arg = va_arg(ap2, char*);
439 if (!arg)
440 break;
441 count++;
442 }
443 va_end(ap2);
444
445 result = calloc(count, sizeof(char*));
446 if (!result)
447 return NULL;
448 count = skip;
449 while (1) {
450 char* arg = va_arg(ap, char*);
451 if (!arg)
452 break;
453 arg = do_strdup ? strdup(arg) : arg;
454 if (!arg)
455 goto oom;
456 result[count++] = arg;
457 }
458
459 /* calloc has already set last element to NULL*/
460 return result;
461
462oom:
463 free(result);
464 return NULL;
465}
466
467const char** lxc_va_arg_list_to_argv_const(va_list ap, size_t skip)
468{
469 return (const char**)lxc_va_arg_list_to_argv(ap, skip, 0);
470}
db27c8d7 471
ebec9176
AM
472extern struct lxc_popen_FILE *lxc_popen(const char *command)
473{
474 struct lxc_popen_FILE *fp = NULL;
475 int parent_end = -1, child_end = -1;
476 int pipe_fds[2];
477 pid_t child_pid;
478
479 int r = pipe2(pipe_fds, O_CLOEXEC);
480
481 if (r < 0) {
482 ERROR("pipe2 failure");
483 return NULL;
484 }
485
486 parent_end = pipe_fds[0];
487 child_end = pipe_fds[1];
488
489 child_pid = fork();
490
491 if (child_pid == 0) {
492 /* child */
493 int child_std_end = STDOUT_FILENO;
494
6e670321
LW
495 close(parent_end);
496 parent_end = -1;
497
ebec9176
AM
498 if (child_end != child_std_end) {
499 /* dup2() doesn't dup close-on-exec flag */
500 dup2(child_end, child_std_end);
501
502 /* it's safe not to close child_end here
503 * as it's marked close-on-exec anyway
504 */
505 } else {
506 /*
507 * The descriptor is already the one we will use.
508 * But it must not be marked close-on-exec.
509 * Undo the effects.
510 */
57d2be54
SG
511 if (fcntl(child_end, F_SETFD, 0) != 0) {
512 SYSERROR("Failed to remove FD_CLOEXEC from fd.");
513 exit(127);
514 }
ebec9176
AM
515 }
516
517 /*
518 * Unblock signals.
519 * This is the main/only reason
520 * why we do our lousy popen() emulation.
521 */
522 {
523 sigset_t mask;
524 sigfillset(&mask);
525 sigprocmask(SIG_UNBLOCK, &mask, NULL);
526 }
527
528 execl("/bin/sh", "sh", "-c", command, (char *) NULL);
529 exit(127);
530 }
531
532 /* parent */
533
534 close(child_end);
535 child_end = -1;
536
537 if (child_pid < 0) {
538 ERROR("fork failure");
539 goto error;
540 }
541
542 fp = calloc(1, sizeof(*fp));
543 if (!fp) {
544 ERROR("failed to allocate memory");
545 goto error;
546 }
547
548 fp->f = fdopen(parent_end, "r");
549 if (!fp->f) {
550 ERROR("fdopen failure");
551 goto error;
552 }
553
554 fp->child_pid = child_pid;
555
556 return fp;
557
558error:
559
560 if (fp) {
561 if (fp->f) {
562 fclose(fp->f);
563 parent_end = -1; /* so we do not close it second time */
564 }
565
566 free(fp);
567 }
568
ebec9176
AM
569 if (parent_end != -1)
570 close(parent_end);
571
572 return NULL;
573}
574
ebec9176
AM
575extern int lxc_pclose(struct lxc_popen_FILE *fp)
576{
577 FILE *f = NULL;
578 pid_t child_pid = 0;
579 int wstatus = 0;
580 pid_t wait_pid;
581
582 if (fp) {
583 f = fp->f;
584 child_pid = fp->child_pid;
585 /* free memory (we still need to close file stream) */
586 free(fp);
587 fp = NULL;
588 }
589
590 if (!f || fclose(f)) {
591 ERROR("fclose failure");
592 return -1;
593 }
594
595 do {
596 wait_pid = waitpid(child_pid, &wstatus, 0);
597 } while (wait_pid == -1 && errno == EINTR);
598
599 if (wait_pid == -1) {
600 ERROR("waitpid failure");
601 return -1;
602 }
603
604 return wstatus;
605}
606
502657d5
CS
607char *lxc_string_replace(const char *needle, const char *replacement, const char *haystack)
608{
609 ssize_t len = -1, saved_len = -1;
610 char *result = NULL;
611 size_t replacement_len = strlen(replacement);
612 size_t needle_len = strlen(needle);
613
614 /* should be executed exactly twice */
615 while (len == -1 || result == NULL) {
616 char *p;
617 char *last_p;
618 ssize_t part_len;
619
620 if (len != -1) {
621 result = calloc(1, len + 1);
622 if (!result)
623 return NULL;
624 saved_len = len;
625 }
626
627 len = 0;
628
629 for (last_p = (char *)haystack, p = strstr(last_p, needle); p; last_p = p, p = strstr(last_p, needle)) {
630 part_len = (ssize_t)(p - last_p);
631 if (result && part_len > 0)
632 memcpy(&result[len], last_p, part_len);
633 len += part_len;
634 if (result && replacement_len > 0)
635 memcpy(&result[len], replacement, replacement_len);
636 len += replacement_len;
637 p += needle_len;
638 }
639 part_len = strlen(last_p);
640 if (result && part_len > 0)
641 memcpy(&result[len], last_p, part_len);
642 len += part_len;
643 }
644
645 /* make sure we did the same thing twice,
646 * once for calculating length, the other
647 * time for copying data */
97bc2422
CB
648 if (saved_len != len) {
649 free(result);
650 return NULL;
651 }
502657d5
CS
652 /* make sure we didn't overwrite any buffer,
653 * due to calloc the string should be 0-terminated */
97bc2422
CB
654 if (result[len] != '\0') {
655 free(result);
656 return NULL;
657 }
502657d5
CS
658
659 return result;
660}
661
662bool lxc_string_in_array(const char *needle, const char **haystack)
663{
664 for (; haystack && *haystack; haystack++)
665 if (!strcmp(needle, *haystack))
666 return true;
667 return false;
668}
669
670char *lxc_string_join(const char *sep, const char **parts, bool use_as_prefix)
671{
672 char *result;
673 char **p;
674 size_t sep_len = strlen(sep);
675 size_t result_len = use_as_prefix * sep_len;
676
677 /* calculate new string length */
678 for (p = (char **)parts; *p; p++)
679 result_len += (p > (char **)parts) * sep_len + strlen(*p);
680
681 result = calloc(result_len + 1, 1);
682 if (!result)
683 return NULL;
684
685 if (use_as_prefix)
686 strcpy(result, sep);
687 for (p = (char **)parts; *p; p++) {
688 if (p > (char **)parts)
689 strcat(result, sep);
690 strcat(result, *p);
691 }
692
693 return result;
694}
695
696char **lxc_normalize_path(const char *path)
697{
698 char **components;
699 char **p;
700 size_t components_len = 0;
701 size_t pos = 0;
702
703 components = lxc_string_split(path, '/');
704 if (!components)
705 return NULL;
706 for (p = components; *p; p++)
707 components_len++;
708
709 /* resolve '.' and '..' */
710 for (pos = 0; pos < components_len; ) {
711 if (!strcmp(components[pos], ".") || (!strcmp(components[pos], "..") && pos == 0)) {
712 /* eat this element */
713 free(components[pos]);
714 memmove(&components[pos], &components[pos+1], sizeof(char *) * (components_len - pos));
715 components_len--;
716 } else if (!strcmp(components[pos], "..")) {
717 /* eat this and the previous element */
718 free(components[pos - 1]);
719 free(components[pos]);
720 memmove(&components[pos-1], &components[pos+1], sizeof(char *) * (components_len - pos));
721 components_len -= 2;
722 pos--;
723 } else {
724 pos++;
725 }
726 }
727
728 return components;
729}
730
c56a9652 731bool lxc_deslashify(char **path)
aeb3682f 732{
f85b16a1 733 bool ret = false;
c56a9652
CB
734 char *p;
735 char **parts = NULL;
736 size_t n, len;
aeb3682f 737
c56a9652 738 parts = lxc_normalize_path(*path);
aeb3682f
TA
739 if (!parts)
740 return false;
741
c56a9652
CB
742 /* We'll end up here if path == "///" or path == "". */
743 if (!*parts) {
744 len = strlen(*path);
f85b16a1
CB
745 if (!len) {
746 ret = true;
747 goto out;
748 }
c56a9652
CB
749 n = strcspn(*path, "/");
750 if (n == len) {
751 p = strdup("/");
752 if (!p)
f85b16a1 753 goto out;
c56a9652
CB
754 free(*path);
755 *path = p;
f85b16a1
CB
756 ret = true;
757 goto out;
c56a9652
CB
758 }
759 }
760
761 p = lxc_string_join("/", (const char **)parts, **path == '/');
c56a9652 762 if (!p)
f85b16a1 763 goto out;
aeb3682f 764
c56a9652
CB
765 free(*path);
766 *path = p;
f85b16a1 767 ret = true;
c56a9652 768
f85b16a1
CB
769out:
770 lxc_free_array((void **)parts, free);
771 return ret;
aeb3682f
TA
772}
773
24b51482
CS
774char *lxc_append_paths(const char *first, const char *second)
775{
776 size_t len = strlen(first) + strlen(second) + 1;
777 const char *pattern = "%s%s";
778 char *result = NULL;
779
780 if (second[0] != '/') {
781 len += 1;
782 pattern = "%s/%s";
783 }
784
785 result = calloc(1, len);
786 if (!result)
787 return NULL;
788
789 snprintf(result, len, pattern, first, second);
790 return result;
791}
792
502657d5
CS
793bool lxc_string_in_list(const char *needle, const char *haystack, char _sep)
794{
795 char *token, *str, *saveptr = NULL;
796 char sep[2] = { _sep, '\0' };
797
798 if (!haystack || !needle)
799 return 0;
800
801 str = alloca(strlen(haystack)+1);
802 strcpy(str, haystack);
803 for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
804 if (strcmp(needle, token) == 0)
805 return 1;
806 }
807
808 return 0;
809}
810
811char **lxc_string_split(const char *string, char _sep)
812{
813 char *token, *str, *saveptr = NULL;
605ea1f7
CB
814 char sep[2] = {_sep, '\0'};
815 char **tmp = NULL, **result = NULL;
502657d5
CS
816 size_t result_capacity = 0;
817 size_t result_count = 0;
818 int r, saved_errno;
819
820 if (!string)
821 return calloc(1, sizeof(char *));
822
605ea1f7 823 str = alloca(strlen(string) + 1);
502657d5
CS
824 strcpy(str, string);
825 for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
826 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 16);
827 if (r < 0)
828 goto error_out;
829 result[result_count] = strdup(token);
830 if (!result[result_count])
831 goto error_out;
832 result_count++;
833 }
834
835 /* if we allocated too much, reduce it */
605ea1f7
CB
836 tmp = realloc(result, (result_count + 1) * sizeof(char *));
837 if (!tmp)
838 goto error_out;
839 result = tmp;
840 /* Make sure we don't return uninitialized memory. */
841 if (result_count == 0)
842 *result = NULL;
843 return result;
502657d5
CS
844error_out:
845 saved_errno = errno;
846 lxc_free_array((void **)result, free);
847 errno = saved_errno;
848 return NULL;
849}
850
851char **lxc_string_split_and_trim(const char *string, char _sep)
852{
853 char *token, *str, *saveptr = NULL;
854 char sep[2] = { _sep, '\0' };
855 char **result = NULL;
856 size_t result_capacity = 0;
857 size_t result_count = 0;
858 int r, saved_errno;
859 size_t i = 0;
860
861 if (!string)
862 return calloc(1, sizeof(char *));
863
864 str = alloca(strlen(string)+1);
865 strcpy(str, string);
866 for (; (token = strtok_r(str, sep, &saveptr)); str = NULL) {
867 while (token[0] == ' ' || token[0] == '\t')
868 token++;
869 i = strlen(token);
870 while (i > 0 && (token[i - 1] == ' ' || token[i - 1] == '\t')) {
871 token[i - 1] = '\0';
872 i--;
873 }
874 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 16);
875 if (r < 0)
876 goto error_out;
877 result[result_count] = strdup(token);
878 if (!result[result_count])
879 goto error_out;
880 result_count++;
881 }
882
883 /* if we allocated too much, reduce it */
884 return realloc(result, (result_count + 1) * sizeof(char *));
885error_out:
886 saved_errno = errno;
887 lxc_free_array((void **)result, free);
888 errno = saved_errno;
889 return NULL;
890}
891
892void lxc_free_array(void **array, lxc_free_fn element_free_fn)
893{
894 void **p;
895 for (p = array; p && *p; p++)
896 element_free_fn(*p);
897 free((void*)array);
898}
899
900int lxc_grow_array(void ***array, size_t* capacity, size_t new_size, size_t capacity_increment)
901{
902 size_t new_capacity;
903 void **new_array;
904
905 /* first time around, catch some trivial mistakes of the user
906 * only initializing one of these */
907 if (!*array || !*capacity) {
908 *array = NULL;
909 *capacity = 0;
910 }
911
912 new_capacity = *capacity;
913 while (new_size + 1 > new_capacity)
914 new_capacity += capacity_increment;
915 if (new_capacity != *capacity) {
916 /* we have to reallocate */
917 new_array = realloc(*array, new_capacity * sizeof(void *));
918 if (!new_array)
919 return -1;
920 memset(&new_array[*capacity], 0, (new_capacity - (*capacity)) * sizeof(void *));
921 *array = new_array;
922 *capacity = new_capacity;
923 }
924
925 /* array has sufficient elements */
926 return 0;
927}
928
929size_t lxc_array_len(void **array)
930{
931 void **p;
932 size_t result = 0;
933
934 for (p = array; p && *p; p++)
935 result++;
936
937 return result;
938}
939
0e95426b
CS
940int lxc_write_to_file(const char *filename, const void* buf, size_t count, bool add_newline)
941{
942 int fd, saved_errno;
943 ssize_t ret;
944
945 fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0666);
946 if (fd < 0)
947 return -1;
948 ret = lxc_write_nointr(fd, buf, count);
949 if (ret < 0)
799f29ab 950 goto out_error;
0e95426b
CS
951 if ((size_t)ret != count)
952 goto out_error;
953 if (add_newline) {
954 ret = lxc_write_nointr(fd, "\n", 1);
955 if (ret != 1)
956 goto out_error;
957 }
958 close(fd);
959 return 0;
960
961out_error:
962 saved_errno = errno;
963 close(fd);
964 errno = saved_errno;
965 return -1;
966}
967
968int lxc_read_from_file(const char *filename, void* buf, size_t count)
969{
970 int fd = -1, saved_errno;
971 ssize_t ret;
972
973 fd = open(filename, O_RDONLY | O_CLOEXEC);
974 if (fd < 0)
975 return -1;
976
977 if (!buf || !count) {
978 char buf2[100];
979 size_t count2 = 0;
980 while ((ret = read(fd, buf2, 100)) > 0)
981 count2 += ret;
982 if (ret >= 0)
983 ret = count2;
984 } else {
985 memset(buf, 0, count);
986 ret = read(fd, buf, count);
987 }
988
989 if (ret < 0)
990 ERROR("read %s: %s", filename, strerror(errno));
991
992 saved_errno = errno;
993 close(fd);
994 errno = saved_errno;
995 return ret;
996}
799f29ab
ÇO
997
998void **lxc_append_null_to_array(void **array, size_t count)
999{
1000 void **temp;
1001
1002 /* Append NULL to the array */
1003 if (count) {
1004 temp = realloc(array, (count + 1) * sizeof(*array));
1005 if (!temp) {
84760c11 1006 size_t i;
799f29ab
ÇO
1007 for (i = 0; i < count; i++)
1008 free(array[i]);
1009 free(array);
1010 return NULL;
1011 }
1012 array = temp;
1013 array[count] = NULL;
1014 }
1015 return array;
1016}
508c263e
SH
1017
1018int randseed(bool srand_it)
1019{
1020 /*
1021 srand pre-seed function based on /dev/urandom
1022 */
091045f8 1023 unsigned int seed = time(NULL) + getpid();
508c263e
SH
1024
1025 FILE *f;
1026 f = fopen("/dev/urandom", "r");
1027 if (f) {
1028 int ret = fread(&seed, sizeof(seed), 1, f);
1029 if (ret != 1)
1030 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno));
1031 fclose(f);
1032 }
1033
1034 if (srand_it)
1035 srand(seed);
1036
1037 return seed;
1038}
5d897655
SH
1039
1040uid_t get_ns_uid(uid_t orig)
1041{
1042 char *line = NULL;
1043 size_t sz = 0;
1044 uid_t nsid, hostid, range;
1045 FILE *f = fopen("/proc/self/uid_map", "r");
1046 if (!f)
1047 return 0;
1048
1049 while (getline(&line, &sz, f) != -1) {
1050 if (sscanf(line, "%u %u %u", &nsid, &hostid, &range) != 3)
1051 continue;
1052 if (hostid <= orig && hostid + range > orig) {
1053 nsid += orig - hostid;
1054 goto found;
1055 }
1056 }
1057
1058 nsid = 0;
1059found:
1060 fclose(f);
1061 free(line);
1062 return nsid;
1063}
c476bdce
SH
1064
1065bool dir_exists(const char *path)
1066{
1067 struct stat sb;
1068 int ret;
1069
1070 ret = stat(path, &sb);
1071 if (ret < 0)
1072 // could be something other than eexist, just say no
1073 return false;
1074 return S_ISDIR(sb.st_mode);
1075}
93c379f0
ÇO
1076
1077/* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1078 * FNV has good anti collision properties and we're not worried
1079 * about pre-image resistance or one-way-ness, we're just trying to make
1080 * the name unique in the 108 bytes of space we have.
1081 */
1082uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
1083{
1084 unsigned char *bp;
1085
1086 for(bp = buf; bp < (unsigned char *)buf + len; bp++)
1087 {
1088 /* xor the bottom with the current octet */
1089 hval ^= (uint64_t)*bp;
1090
1091 /* gcc optimised:
1092 * multiply by the 64 bit FNV magic prime mod 2^64
1093 */
1094 hval += (hval << 1) + (hval << 4) + (hval << 5) +
1095 (hval << 7) + (hval << 8) + (hval << 40);
1096 }
1097
1098 return hval;
1099}
2c6f3fc9
SH
1100
1101/*
1102 * Detect whether / is mounted MS_SHARED. The only way I know of to
1103 * check that is through /proc/self/mountinfo.
1104 * I'm only checking for /. If the container rootfs or mount location
1105 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1106 * out would be too much work to be worth it.
1107 */
2c6f3fc9
SH
1108int detect_shared_rootfs(void)
1109{
eab15c1e 1110 char buf[LXC_LINELEN], *p;
2c6f3fc9
SH
1111 FILE *f;
1112 int i;
1113 char *p2;
1114
1115 f = fopen("/proc/self/mountinfo", "r");
1116 if (!f)
1117 return 0;
eab15c1e
CB
1118 while (fgets(buf, LXC_LINELEN, f)) {
1119 for (p = buf, i = 0; p && i < 4; i++)
1120 p = strchr(p + 1, ' ');
2c6f3fc9
SH
1121 if (!p)
1122 continue;
eab15c1e 1123 p2 = strchr(p + 1, ' ');
2c6f3fc9
SH
1124 if (!p2)
1125 continue;
1126 *p2 = '\0';
eab15c1e 1127 if (strcmp(p + 1, "/") == 0) {
2c6f3fc9 1128 // this is '/'. is it shared?
eab15c1e 1129 p = strchr(p2 + 1, ' ');
2c6f3fc9
SH
1130 if (p && strstr(p, "shared:")) {
1131 fclose(f);
1132 return 1;
1133 }
1134 }
1135 }
1136 fclose(f);
1137 return 0;
1138}
0e6e3a41 1139
51d0854c
DY
1140bool switch_to_ns(pid_t pid, const char *ns) {
1141 int fd, ret;
1142 char nspath[MAXPATHLEN];
1143
1144 /* Switch to new ns */
1145 ret = snprintf(nspath, MAXPATHLEN, "/proc/%d/ns/%s", pid, ns);
1146 if (ret < 0 || ret >= MAXPATHLEN)
1147 return false;
1148
1149 fd = open(nspath, O_RDONLY);
1150 if (fd < 0) {
1151 SYSERROR("failed to open %s", nspath);
1152 return false;
1153 }
1154
1155 ret = setns(fd, 0);
1156 if (ret) {
1157 SYSERROR("failed to set process %d to %s of %d.", pid, ns, fd);
1158 close(fd);
1159 return false;
1160 }
1161 close(fd);
1162 return true;
1163}
1164
b7f954bb
SH
1165/*
1166 * looking at fs/proc_namespace.c, it appears we can
1167 * actually expect the rootfs entry to very specifically contain
1168 * " - rootfs rootfs "
1169 * IIUC, so long as we've chrooted so that rootfs is not our root,
1170 * the rootfs entry should always be skipped in mountinfo contents.
1171 */
fa454c8e 1172bool detect_ramfs_rootfs(void)
b7f954bb 1173{
b7f954bb 1174 FILE *f;
fa454c8e
CB
1175 char *p, *p2;
1176 char *line = NULL;
1177 size_t len = 0;
b7f954bb 1178 int i;
b7f954bb
SH
1179
1180 f = fopen("/proc/self/mountinfo", "r");
1181 if (!f)
fa454c8e
CB
1182 return false;
1183
1184 while (getline(&line, &len, f) != -1) {
1185 for (p = line, i = 0; p && i < 4; i++)
1186 p = strchr(p + 1, ' ');
b7f954bb
SH
1187 if (!p)
1188 continue;
fa454c8e 1189 p2 = strchr(p + 1, ' ');
b7f954bb
SH
1190 if (!p2)
1191 continue;
1192 *p2 = '\0';
fa454c8e 1193 if (strcmp(p + 1, "/") == 0) {
b7f954bb 1194 // this is '/'. is it the ramfs?
fa454c8e 1195 p = strchr(p2 + 1, '-');
b7f954bb 1196 if (p && strncmp(p, "- rootfs rootfs ", 16) == 0) {
fa454c8e 1197 free(line);
b7f954bb 1198 fclose(f);
fa454c8e 1199 return true;
b7f954bb
SH
1200 }
1201 }
1202 }
fa454c8e 1203 free(line);
b7f954bb 1204 fclose(f);
fa454c8e 1205 return false;
b7f954bb
SH
1206}
1207
df6a2945 1208char *on_path(const char *cmd, const char *rootfs) {
0e6e3a41
SG
1209 char *path = NULL;
1210 char *entry = NULL;
1211 char *saveptr = NULL;
1212 char cmdpath[MAXPATHLEN];
1213 int ret;
1214
1215 path = getenv("PATH");
1216 if (!path)
8afb3e61 1217 return NULL;
0e6e3a41
SG
1218
1219 path = strdup(path);
1220 if (!path)
8afb3e61 1221 return NULL;
0e6e3a41
SG
1222
1223 entry = strtok_r(path, ":", &saveptr);
1224 while (entry) {
9d9c111c
SH
1225 if (rootfs)
1226 ret = snprintf(cmdpath, MAXPATHLEN, "%s/%s/%s", rootfs, entry, cmd);
1227 else
1228 ret = snprintf(cmdpath, MAXPATHLEN, "%s/%s", entry, cmd);
0e6e3a41
SG
1229
1230 if (ret < 0 || ret >= MAXPATHLEN)
1231 goto next_loop;
1232
1233 if (access(cmdpath, X_OK) == 0) {
1234 free(path);
8afb3e61 1235 return strdup(cmdpath);
0e6e3a41
SG
1236 }
1237
1238next_loop:
b707e368 1239 entry = strtok_r(NULL, ":", &saveptr);
0e6e3a41
SG
1240 }
1241
1242 free(path);
8afb3e61 1243 return NULL;
0e6e3a41 1244}
76a26f55
SH
1245
1246bool file_exists(const char *f)
1247{
1248 struct stat statbuf;
1249
1250 return stat(f, &statbuf) == 0;
1251}
9d9c111c 1252
12983ba4
SH
1253bool cgns_supported(void)
1254{
1255 return file_exists("/proc/self/ns/cgroup");
1256}
1257
9d9c111c
SH
1258/* historically lxc-init has been under /usr/lib/lxc and under
1259 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1260 */
1261char *choose_init(const char *rootfs)
1262{
1263 char *retv = NULL;
370ec268
SF
1264 const char *empty = "",
1265 *tmp;
9d9c111c 1266 int ret, env_set = 0;
9d9c111c
SH
1267
1268 if (!getenv("PATH")) {
1269 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1270 SYSERROR("Failed to setenv");
1271 env_set = 1;
1272 }
1273
1274 retv = on_path("init.lxc", rootfs);
1275
1276 if (env_set) {
1277 if (unsetenv("PATH"))
1278 SYSERROR("Failed to unsetenv");
1279 }
1280
1281 if (retv)
1282 return retv;
1283
1284 retv = malloc(PATH_MAX);
1285 if (!retv)
1286 return NULL;
1287
1288 if (rootfs)
370ec268 1289 tmp = rootfs;
9d9c111c 1290 else
370ec268
SF
1291 tmp = empty;
1292
1293 ret = snprintf(retv, PATH_MAX, "%s/%s/%s", tmp, SBINDIR, "/init.lxc");
9d9c111c
SH
1294 if (ret < 0 || ret >= PATH_MAX) {
1295 ERROR("pathname too long");
1296 goto out1;
1297 }
e57cd7e9 1298 if (access(retv, X_OK) == 0)
9d9c111c
SH
1299 return retv;
1300
370ec268 1301 ret = snprintf(retv, PATH_MAX, "%s/%s/%s", tmp, LXCINITDIR, "/lxc/lxc-init");
9d9c111c
SH
1302 if (ret < 0 || ret >= PATH_MAX) {
1303 ERROR("pathname too long");
1304 goto out1;
1305 }
e57cd7e9 1306 if (access(retv, X_OK) == 0)
9d9c111c
SH
1307 return retv;
1308
370ec268 1309 ret = snprintf(retv, PATH_MAX, "%s/usr/lib/lxc/lxc-init", tmp);
9d9c111c
SH
1310 if (ret < 0 || ret >= PATH_MAX) {
1311 ERROR("pathname too long");
1312 goto out1;
1313 }
e57cd7e9 1314 if (access(retv, X_OK) == 0)
9d9c111c
SH
1315 return retv;
1316
370ec268 1317 ret = snprintf(retv, PATH_MAX, "%s/sbin/lxc-init", tmp);
9d9c111c
SH
1318 if (ret < 0 || ret >= PATH_MAX) {
1319 ERROR("pathname too long");
1320 goto out1;
1321 }
e57cd7e9 1322 if (access(retv, X_OK) == 0)
9d9c111c
SH
1323 return retv;
1324
1325 /*
1326 * Last resort, look for the statically compiled init.lxc which we
1327 * hopefully bind-mounted in.
1328 * If we are called during container setup, and we get to this point,
1329 * then the init.lxc.static from the host will need to be bind-mounted
1330 * in. So we return NULL here to indicate that.
1331 */
1332 if (rootfs)
1333 goto out1;
1334
1335 ret = snprintf(retv, PATH_MAX, "/init.lxc.static");
1336 if (ret < 0 || ret >= PATH_MAX) {
1337 WARN("Nonsense - name /lxc.init.static too long");
1338 goto out1;
1339 }
e57cd7e9 1340 if (access(retv, X_OK) == 0)
9d9c111c
SH
1341 return retv;
1342
1343out1:
1344 free(retv);
1345 return NULL;
1346}
735f2c6e
TA
1347
1348int print_to_file(const char *file, const char *content)
1349{
1350 FILE *f;
1351 int ret = 0;
1352
1353 f = fopen(file, "w");
1354 if (!f)
1355 return -1;
1356 if (fprintf(f, "%s", content) != strlen(content))
1357 ret = -1;
1358 fclose(f);
1359 return ret;
1360}
e1daebd9
SH
1361
1362int is_dir(const char *path)
1363{
1364 struct stat statbuf;
1365 int ret = stat(path, &statbuf);
1366 if (ret == 0 && S_ISDIR(statbuf.st_mode))
1367 return 1;
1368 return 0;
1369}
6010a416
SG
1370
1371/*
1372 * Given the '-t' template option to lxc-create, figure out what to
1373 * do. If the template is a full executable path, use that. If it
1374 * is something like 'sshd', then return $templatepath/lxc-sshd.
1375 * On success return the template, on error return NULL.
1376 */
1377char *get_template_path(const char *t)
1378{
1379 int ret, len;
1380 char *tpath;
1381
1382 if (t[0] == '/' && access(t, X_OK) == 0) {
1383 tpath = strdup(t);
1384 return tpath;
1385 }
1386
1387 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
1388 tpath = malloc(len);
1389 if (!tpath)
1390 return NULL;
1391 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
1392 if (ret < 0 || ret >= len) {
1393 free(tpath);
1394 return NULL;
1395 }
1396 if (access(tpath, X_OK) < 0) {
1397 SYSERROR("bad template: %s", t);
1398 free(tpath);
1399 return NULL;
1400 }
1401
1402 return tpath;
1403}
0a4be28d
TA
1404
1405/*
7d6c20f2
TA
1406 * Sets the process title to the specified title. Note that this may fail if
1407 * the kernel doesn't support PR_SET_MM_MAP (kernels <3.18).
0a4be28d
TA
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
be69ad43 1461 i = sscanf(tmp, "%lu %lu %lu %*u %*u %lu %lu",
93525c00
TA
1462 &start_data,
1463 &end_data,
1464 &start_brk,
93525c00
TA
1465 &env_start,
1466 &env_end);
be69ad43 1467 if (i != 5)
93525c00
TA
1468 return -1;
1469
96fe6d1d
TA
1470 /* Include the null byte here, because in the calculations below we
1471 * want to have room for it. */
1472 len = strlen(title) + 1;
1473
be69ad43
TA
1474 proctitle = realloc(proctitle, len);
1475 if (!proctitle)
1476 return -1;
0a4be28d 1477
be69ad43 1478 arg_start = (unsigned long) proctitle;
058b94fe
TA
1479 arg_end = arg_start + len;
1480
93525c00 1481 brk_val = syscall(__NR_brk, 0);
0a4be28d 1482
93525c00
TA
1483 prctl_map = (struct prctl_mm_map) {
1484 .start_code = start_code,
1485 .end_code = end_code,
1486 .start_stack = start_stack,
1487 .start_data = start_data,
1488 .end_data = end_data,
1489 .start_brk = start_brk,
1490 .brk = brk_val,
1491 .arg_start = arg_start,
1492 .arg_end = arg_end,
1493 .env_start = env_start,
1494 .env_end = env_end,
1495 .auxv = NULL,
1496 .auxv_size = 0,
1497 .exe_fd = -1,
1498 };
1499
1500 ret = prctl(PR_SET_MM, PR_SET_MM_MAP, (long) &prctl_map, sizeof(prctl_map), 0);
1501 if (ret == 0)
1502 strcpy((char*)arg_start, title);
1503 else
2681c0e7 1504 INFO("setting cmdline failed - %s", strerror(errno));
0a4be28d
TA
1505
1506 return ret;
1507}
ced03a01 1508
592fd47a
SH
1509/*
1510 * @path: a pathname where / replaced with '\0'.
1511 * @offsetp: pointer to int showing which path segment was last seen.
1512 * Updated on return to reflect the next segment.
1513 * @fulllen: full original path length.
1514 * Returns a pointer to the next path segment, or NULL if done.
1515 */
1516static char *get_nextpath(char *path, int *offsetp, int fulllen)
1517{
1518 int offset = *offsetp;
1519
1520 if (offset >= fulllen)
1521 return NULL;
1522
1523 while (path[offset] != '\0' && offset < fulllen)
1524 offset++;
1525 while (path[offset] == '\0' && offset < fulllen)
1526 offset++;
1527
1528 *offsetp = offset;
1529 return (offset < fulllen) ? &path[offset] : NULL;
1530}
1531
1532/*
1533 * Check that @subdir is a subdir of @dir. @len is the length of
1534 * @dir (to avoid having to recalculate it).
1535 */
1536static bool is_subdir(const char *subdir, const char *dir, size_t len)
1537{
1538 size_t subdirlen = strlen(subdir);
1539
1540 if (subdirlen < len)
1541 return false;
1542 if (strncmp(subdir, dir, len) != 0)
1543 return false;
1544 if (dir[len-1] == '/')
1545 return true;
1546 if (subdir[len] == '/' || subdirlen == len)
1547 return true;
1548 return false;
1549}
1550
1551/*
1552 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1553 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1554 */
1555static int check_symlink(int fd)
1556{
1557 struct stat sb;
1558 int ret = fstat(fd, &sb);
1559 if (ret < 0)
1560 return -ENOENT;
1561 if (S_ISLNK(sb.st_mode))
1562 return -ELOOP;
1563 return 0;
1564}
1565
1566/*
1567 * Open a file or directory, provided that it contains no symlinks.
1568 *
1569 * CAVEAT: This function must not be used for other purposes than container
1570 * setup before executing the container's init
1571 */
1572static int open_if_safe(int dirfd, const char *nextpath)
1573{
1574 int newfd = openat(dirfd, nextpath, O_RDONLY | O_NOFOLLOW);
1575 if (newfd >= 0) // was not a symlink, all good
1576 return newfd;
1577
1578 if (errno == ELOOP)
1579 return newfd;
1580
1581 if (errno == EPERM || errno == EACCES) {
1582 /* we're not root (cause we got EPERM) so
1583 try opening with O_PATH */
1584 newfd = openat(dirfd, nextpath, O_PATH | O_NOFOLLOW);
1585 if (newfd >= 0) {
1586 /* O_PATH will return an fd for symlinks. We know
1587 * nextpath wasn't a symlink at last openat, so if fd
1588 * is now a link, then something * fishy is going on
1589 */
1590 int ret = check_symlink(newfd);
1591 if (ret < 0) {
1592 close(newfd);
1593 newfd = ret;
1594 }
1595 }
1596 }
1597
1598 return newfd;
1599}
1600
1601/*
1602 * Open a path intending for mounting, ensuring that the final path
1603 * is inside the container's rootfs.
1604 *
1605 * CAVEAT: This function must not be used for other purposes than container
1606 * setup before executing the container's init
1607 *
1608 * @target: path to be opened
1609 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1610 * would be the container's rootfs.
1611 *
1612 * Return an open fd for the path, or <0 on error.
1613 */
1614static int open_without_symlink(const char *target, const char *prefix_skip)
1615{
1616 int curlen = 0, dirfd, fulllen, i;
1617 char *dup = NULL;
1618
1619 fulllen = strlen(target);
1620
1621 /* make sure prefix-skip makes sense */
01074e5b 1622 if (prefix_skip && strlen(prefix_skip) > 0) {
592fd47a
SH
1623 curlen = strlen(prefix_skip);
1624 if (!is_subdir(target, prefix_skip, curlen)) {
1625 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1626 target, prefix_skip);
1627 return -EINVAL;
1628 }
1629 /*
1630 * get_nextpath() expects the curlen argument to be
1631 * on a (turned into \0) / or before it, so decrement
1632 * curlen to make sure that happens
1633 */
1634 if (curlen)
1635 curlen--;
1636 } else {
1637 prefix_skip = "/";
1638 curlen = 0;
1639 }
1640
1641 /* Make a copy of target which we can hack up, and tokenize it */
1642 if ((dup = strdup(target)) == NULL) {
1643 SYSERROR("Out of memory checking for symbolic link");
1644 return -ENOMEM;
1645 }
1646 for (i = 0; i < fulllen; i++) {
1647 if (dup[i] == '/')
1648 dup[i] = '\0';
1649 }
1650
1651 dirfd = open(prefix_skip, O_RDONLY);
1652 if (dirfd < 0)
1653 goto out;
1654 while (1) {
1655 int newfd, saved_errno;
1656 char *nextpath;
1657
1658 if ((nextpath = get_nextpath(dup, &curlen, fulllen)) == NULL)
1659 goto out;
1660 newfd = open_if_safe(dirfd, nextpath);
1661 saved_errno = errno;
1662 close(dirfd);
1663 dirfd = newfd;
1664 if (newfd < 0) {
1665 errno = saved_errno;
1666 if (errno == ELOOP)
1667 SYSERROR("%s in %s was a symbolic link!", nextpath, target);
592fd47a
SH
1668 goto out;
1669 }
1670 }
1671
1672out:
1673 free(dup);
1674 return dirfd;
1675}
1676
1677/*
1678 * Safely mount a path into a container, ensuring that the mount target
1679 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1680 * uses the host's /)
1681 *
1682 * CAVEAT: This function must not be used for other purposes than container
1683 * setup before executing the container's init
1684 */
1685int safe_mount(const char *src, const char *dest, const char *fstype,
1686 unsigned long flags, const void *data, const char *rootfs)
1687{
1688 int srcfd = -1, destfd, ret, saved_errno;
1689 char srcbuf[50], destbuf[50]; // only needs enough for /proc/self/fd/<fd>
1690 const char *mntsrc = src;
1691
1692 if (!rootfs)
1693 rootfs = "";
1694
1695 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1696 if (flags & MS_BIND && src && src[0] != '/') {
1697 INFO("this is a relative bind mount");
1698 srcfd = open_without_symlink(src, NULL);
1699 if (srcfd < 0)
1700 return srcfd;
1701 ret = snprintf(srcbuf, 50, "/proc/self/fd/%d", srcfd);
1702 if (ret < 0 || ret > 50) {
1703 close(srcfd);
1704 ERROR("Out of memory");
1705 return -EINVAL;
1706 }
1707 mntsrc = srcbuf;
1708 }
1709
1710 destfd = open_without_symlink(dest, rootfs);
1711 if (destfd < 0) {
88e078ba
CB
1712 if (srcfd != -1) {
1713 saved_errno = errno;
592fd47a 1714 close(srcfd);
88e078ba
CB
1715 errno = saved_errno;
1716 }
592fd47a
SH
1717 return destfd;
1718 }
1719
1720 ret = snprintf(destbuf, 50, "/proc/self/fd/%d", destfd);
1721 if (ret < 0 || ret > 50) {
1722 if (srcfd != -1)
1723 close(srcfd);
1724 close(destfd);
1725 ERROR("Out of memory");
1726 return -EINVAL;
1727 }
1728
1729 ret = mount(mntsrc, destbuf, fstype, flags, data);
1730 saved_errno = errno;
1731 if (srcfd != -1)
1732 close(srcfd);
1733 close(destfd);
1734 if (ret < 0) {
1735 errno = saved_errno;
1736 SYSERROR("Failed to mount %s onto %s", src, dest);
1737 return ret;
1738 }
1739
1740 return 0;
1741}
1742
ced03a01
SH
1743/*
1744 * Mount a proc under @rootfs if proc self points to a pid other than
1745 * my own. This is needed to have a known-good proc mount for setting
1746 * up LSMs both at container startup and attach.
1747 *
1748 * @rootfs : the rootfs where proc should be mounted
1749 *
1750 * Returns < 0 on failure, 0 if the correct proc was already mounted
1751 * and 1 if a new proc was mounted.
f267d666
BP
1752 *
1753 * NOTE: not to be called from inside the container namespace!
ced03a01 1754 */
943144d9 1755int lxc_mount_proc_if_needed(const char *rootfs)
ced03a01
SH
1756{
1757 char path[MAXPATHLEN];
6b1ba5d6
CB
1758 int link_to_pid, linklen, mypid, ret;
1759 char link[LXC_NUMSTRLEN64] = {0};
ced03a01
SH
1760
1761 ret = snprintf(path, MAXPATHLEN, "%s/proc/self", rootfs);
1762 if (ret < 0 || ret >= MAXPATHLEN) {
1763 SYSERROR("proc path name too long");
1764 return -1;
1765 }
fc2ad9dc 1766
6b1ba5d6 1767 linklen = readlink(path, link, LXC_NUMSTRLEN64);
fc2ad9dc 1768
ced03a01 1769 ret = snprintf(path, MAXPATHLEN, "%s/proc", rootfs);
d539a2b2
CB
1770 if (ret < 0 || ret >= MAXPATHLEN) {
1771 SYSERROR("proc path name too long");
1772 return -1;
1773 }
fc2ad9dc
CB
1774
1775 /* /proc not mounted */
1776 if (linklen < 0) {
1777 if (mkdir(path, 0755) && errno != EEXIST)
1778 return -1;
ced03a01 1779 goto domount;
6b1ba5d6
CB
1780 } else if (linklen >= LXC_NUMSTRLEN64) {
1781 link[linklen - 1] = '\0';
1782 ERROR("readlink returned truncated content: \"%s\"", link);
1783 return -1;
fc2ad9dc
CB
1784 }
1785
6b1ba5d6
CB
1786 mypid = getpid();
1787 INFO("I am %d, /proc/self points to \"%s\"", mypid, link);
1788
2d036cca
CB
1789 if (lxc_safe_int(link, &link_to_pid) < 0)
1790 return -1;
fc2ad9dc 1791
6b1ba5d6
CB
1792 /* correct procfs is already mounted */
1793 if (link_to_pid == mypid)
1794 return 0;
fc2ad9dc 1795
6b1ba5d6
CB
1796 ret = umount2(path, MNT_DETACH);
1797 if (ret < 0)
1798 WARN("failed to umount \"%s\" with MNT_DETACH", path);
ced03a01
SH
1799
1800domount:
fc2ad9dc 1801 /* rootfs is NULL */
6b1ba5d6 1802 if (!strcmp(rootfs, ""))
f267d666
BP
1803 ret = mount("proc", path, "proc", 0, NULL);
1804 else
1805 ret = safe_mount("proc", path, "proc", 0, NULL, rootfs);
f267d666 1806 if (ret < 0)
ced03a01 1807 return -1;
f267d666 1808
fc2ad9dc 1809 INFO("mounted /proc in container for security transition");
ced03a01
SH
1810 return 1;
1811}
69aeabac 1812
f8dd0275 1813int open_devnull(void)
69aeabac 1814{
f8dd0275
AM
1815 int fd = open("/dev/null", O_RDWR);
1816
1817 if (fd < 0)
1818 SYSERROR("Can't open /dev/null");
1819
1820 return fd;
1821}
69aeabac 1822
f8dd0275
AM
1823int set_stdfds(int fd)
1824{
bbbf65ee
CB
1825 int ret;
1826
69aeabac
TA
1827 if (fd < 0)
1828 return -1;
1829
bbbf65ee
CB
1830 ret = dup2(fd, STDIN_FILENO);
1831 if (ret < 0)
f8dd0275 1832 return -1;
bbbf65ee
CB
1833
1834 ret = dup2(fd, STDOUT_FILENO);
1835 if (ret < 0)
f8dd0275 1836 return -1;
bbbf65ee
CB
1837
1838 ret = dup2(fd, STDERR_FILENO);
1839 if (ret < 0)
f8dd0275
AM
1840 return -1;
1841
1842 return 0;
1843}
1844
1845int null_stdfds(void)
1846{
1847 int ret = -1;
1848 int fd = open_devnull();
1849
1850 if (fd >= 0) {
1851 ret = set_stdfds(fd);
1852 close(fd);
1853 }
69aeabac 1854
69aeabac
TA
1855 return ret;
1856}
ccb4cabe
SH
1857
1858/*
1859 * Return the number of lines in file @fn, or -1 on error
1860 */
1861int lxc_count_file_lines(const char *fn)
1862{
1863 FILE *f;
1864 char *line = NULL;
1865 size_t sz = 0;
1866 int n = 0;
1867
1868 f = fopen_cloexec(fn, "r");
1869 if (!f)
1870 return -1;
1871
1872 while (getline(&line, &sz, f) != -1) {
1873 n++;
1874 }
1875 free(line);
1876 fclose(f);
1877 return n;
1878}
1adbd020 1879
25086a5f
CB
1880void *lxc_strmmap(void *addr, size_t length, int prot, int flags, int fd,
1881 off_t offset)
1adbd020
CB
1882{
1883 void *tmp = NULL, *overlap = NULL;
1884
1885 /* We establish an anonymous mapping that is one byte larger than the
1886 * underlying file. The pages handed to us are zero filled. */
1887 tmp = mmap(addr, length + 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1888 if (tmp == MAP_FAILED)
a1e5280d 1889 return tmp;
1adbd020
CB
1890
1891 /* Now we establish a fixed-address mapping starting at the address we
1892 * received from our anonymous mapping and replace all bytes excluding
1893 * the additional \0-byte with the file. This allows us to use normal
a1e5280d 1894 * string-handling functions. */
1adbd020
CB
1895 overlap = mmap(tmp, length, prot, MAP_FIXED | flags, fd, offset);
1896 if (overlap == MAP_FAILED)
a1e5280d 1897 munmap(tmp, length + 1);
1adbd020 1898
1adbd020
CB
1899 return overlap;
1900}
1901
25086a5f 1902int lxc_strmunmap(void *addr, size_t length)
1adbd020
CB
1903{
1904 return munmap(addr, length + 1);
1905}
330ae3d3
CB
1906
1907/* Check whether a signal is blocked by a process. */
de3c491b 1908/* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
eab15c1e 1909#define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
330ae3d3
CB
1910bool task_blocking_signal(pid_t pid, int signal)
1911{
1912 bool bret = false;
1913 char *line = NULL;
1914 long unsigned int sigblk = 0;
1915 size_t n = 0;
1916 int ret;
1917 FILE *f;
1918
de3c491b 1919 char status[__PROC_STATUS_LEN];
330ae3d3 1920
de3c491b
CB
1921 ret = snprintf(status, __PROC_STATUS_LEN, "/proc/%d/status", pid);
1922 if (ret < 0 || ret >= __PROC_STATUS_LEN)
330ae3d3
CB
1923 return bret;
1924
1925 f = fopen(status, "r");
1926 if (!f)
1927 return bret;
1928
1929 while (getline(&line, &n, f) != -1) {
6fbcbe3b
CB
1930 if (strncmp(line, "SigBlk:\t", 8))
1931 continue;
1932
1933 if (sscanf(line + 8, "%lx", &sigblk) != 1)
1934 goto out;
330ae3d3
CB
1935 }
1936
6fbcbe3b 1937 if (sigblk & (1LU << (signal - 1)))
330ae3d3
CB
1938 bret = true;
1939
1940out:
1941 free(line);
1942 fclose(f);
1943 return bret;
1944}
000dfda7
CB
1945
1946static int lxc_append_null_to_list(void ***list)
1947{
1948 int newentry = 0;
1949 void **tmp;
1950
1951 if (*list)
1952 for (; (*list)[newentry]; newentry++) {
1953 ;
1954 }
1955
1956 tmp = realloc(*list, (newentry + 2) * sizeof(void **));
1957 if (!tmp)
1958 return -1;
1959
1960 *list = tmp;
1961 (*list)[newentry + 1] = NULL;
1962
1963 return newentry;
1964}
1965
1966int lxc_append_string(char ***list, char *entry)
1967{
000dfda7 1968 char *copy;
a54694f8
CB
1969 int newentry;
1970
1971 newentry = lxc_append_null_to_list((void ***)list);
1972 if (newentry < 0)
1973 return -1;
000dfda7
CB
1974
1975 copy = strdup(entry);
1976 if (!copy)
1977 return -1;
1978
1979 (*list)[newentry] = copy;
1980
1981 return 0;
1982}
a687256f
CB
1983
1984int lxc_preserve_ns(const int pid, const char *ns)
1985{
1986 int ret;
a052913d
CB
1987/* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1988#define __NS_PATH_LEN 50
1989 char path[__NS_PATH_LEN];
a687256f 1990
4d8ac866
CB
1991 /* This way we can use this function to also check whether namespaces
1992 * are supported by the kernel by passing in the NULL or the empty
1993 * string.
1994 */
a052913d 1995 ret = snprintf(path, __NS_PATH_LEN, "/proc/%d/ns%s%s", pid,
4d8ac866
CB
1996 !ns || strcmp(ns, "") == 0 ? "" : "/",
1997 !ns || strcmp(ns, "") == 0 ? "" : ns);
a052913d 1998 if (ret < 0 || (size_t)ret >= __NS_PATH_LEN)
a687256f
CB
1999 return -1;
2000
2001 return open(path, O_RDONLY | O_CLOEXEC);
2002}
6bc2eafe
CB
2003
2004int lxc_safe_uint(const char *numstr, unsigned int *converted)
2005{
2006 char *err = NULL;
2007 unsigned long int uli;
2008
643c1984
CB
2009 while (isspace(*numstr))
2010 numstr++;
2011
2012 if (*numstr == '-')
2013 return -EINVAL;
2014
6bc2eafe
CB
2015 errno = 0;
2016 uli = strtoul(numstr, &err, 0);
643c1984 2017 if (errno == ERANGE && uli == ULONG_MAX)
ff0e49c7 2018 return -ERANGE;
6bc2eafe 2019
643c1984 2020 if (err == numstr || *err != '\0')
6bc2eafe
CB
2021 return -EINVAL;
2022
2023 if (uli > UINT_MAX)
2024 return -ERANGE;
2025
8c57d930 2026 *converted = (unsigned int)uli;
6bc2eafe
CB
2027 return 0;
2028}
b5f845e7 2029
681188c1
CB
2030int lxc_safe_ulong(const char *numstr, unsigned long *converted)
2031{
2032 char *err = NULL;
2033 unsigned long int uli;
2034
2035 while (isspace(*numstr))
2036 numstr++;
2037
2038 if (*numstr == '-')
2039 return -EINVAL;
2040
2041 errno = 0;
2042 uli = strtoul(numstr, &err, 0);
2043 if (errno == ERANGE && uli == ULONG_MAX)
2044 return -ERANGE;
2045
2046 if (err == numstr || *err != '\0')
2047 return -EINVAL;
2048
2049 *converted = uli;
2050 return 0;
2051}
2052
b5f845e7
CB
2053int lxc_safe_int(const char *numstr, int *converted)
2054{
2055 char *err = NULL;
2056 signed long int sli;
2057
2058 errno = 0;
2059 sli = strtol(numstr, &err, 0);
643c1984 2060 if (errno == ERANGE && (sli == LONG_MAX || sli == LONG_MIN))
ff0e49c7 2061 return -ERANGE;
643c1984
CB
2062
2063 if (errno != 0 && sli == 0)
ff0e49c7 2064 return -EINVAL;
b5f845e7 2065
643c1984 2066 if (err == numstr || *err != '\0')
b5f845e7
CB
2067 return -EINVAL;
2068
643c1984 2069 if (sli > INT_MAX || sli < INT_MIN)
b5f845e7
CB
2070 return -ERANGE;
2071
2072 *converted = (int)sli;
2073 return 0;
2074}
8c57d930
CB
2075
2076int lxc_safe_long(const char *numstr, long int *converted)
2077{
2078 char *err = NULL;
2079 signed long int sli;
2080
2081 errno = 0;
2082 sli = strtol(numstr, &err, 0);
643c1984 2083 if (errno == ERANGE && (sli == LONG_MAX || sli == LONG_MIN))
ff0e49c7 2084 return -ERANGE;
8c57d930 2085
643c1984 2086 if (errno != 0 && sli == 0)
ff0e49c7 2087 return -EINVAL;
8c57d930 2088
643c1984
CB
2089 if (err == numstr || *err != '\0')
2090 return -EINVAL;
8c57d930
CB
2091
2092 *converted = sli;
2093 return 0;
2094}
dbaf55a3
CB
2095
2096int lxc_switch_uid_gid(uid_t uid, gid_t gid)
2097{
2098 if (setgid(gid) < 0) {
2099 SYSERROR("Failed to switch to gid %d.", gid);
2100 return -errno;
2101 }
2102 NOTICE("Switched to gid %d.", gid);
2103
2104 if (setuid(uid) < 0) {
2105 SYSERROR("Failed to switch to uid %d.", uid);
2106 return -errno;
2107 }
2108 NOTICE("Switched to uid %d.", uid);
2109
2110 return 0;
2111}
2112
2113/* Simple covenience function which enables uniform logging. */
2114int lxc_setgroups(int size, gid_t list[])
2115{
2116 if (setgroups(size, list) < 0) {
2117 SYSERROR("Failed to setgroups().");
2118 return -errno;
2119 }
2120 NOTICE("Dropped additional groups.");
2121
2122 return 0;
2123}
c6868a1f
CB
2124
2125static int lxc_get_unused_loop_dev_legacy(char *loop_name)
2126{
2127 struct dirent *dp;
2128 struct loop_info64 lo64;
2129 DIR *dir;
2130 int dfd = -1, fd = -1, ret = -1;
2131
2132 dir = opendir("/dev");
2133 if (!dir)
2134 return -1;
2135
2136 while ((dp = readdir(dir))) {
2137 if (!dp)
2138 break;
2139
2140 if (strncmp(dp->d_name, "loop", 4) != 0)
2141 continue;
2142
2143 dfd = dirfd(dir);
2144 if (dfd < 0)
2145 continue;
2146
2147 fd = openat(dfd, dp->d_name, O_RDWR);
2148 if (fd < 0)
2149 continue;
2150
2151 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
2152 if (ret < 0) {
2153 if (ioctl(fd, LOOP_GET_STATUS64, &lo64) == 0 ||
2154 errno != ENXIO) {
2155 close(fd);
2156 fd = -1;
2157 continue;
2158 }
2159 }
2160
2161 ret = snprintf(loop_name, LO_NAME_SIZE, "/dev/%s", dp->d_name);
2162 if (ret < 0 || ret >= LO_NAME_SIZE) {
2163 close(fd);
2164 fd = -1;
2165 continue;
2166 }
2167
2168 break;
2169 }
2170
2171 closedir(dir);
2172
2173 if (fd < 0)
2174 return -1;
2175
2176 return fd;
2177}
2178
2179static int lxc_get_unused_loop_dev(char *name_loop)
2180{
2181 int loop_nr, ret;
2182 int fd_ctl = -1, fd_tmp = -1;
2183
2184 fd_ctl = open("/dev/loop-control", O_RDWR | O_CLOEXEC);
2185 if (fd_ctl < 0)
2186 return -ENODEV;
2187
2188 loop_nr = ioctl(fd_ctl, LOOP_CTL_GET_FREE);
2189 if (loop_nr < 0)
2190 goto on_error;
2191
2192 ret = snprintf(name_loop, LO_NAME_SIZE, "/dev/loop%d", loop_nr);
2193 if (ret < 0 || ret >= LO_NAME_SIZE)
2194 goto on_error;
2195
2196 fd_tmp = open(name_loop, O_RDWR | O_CLOEXEC);
2197 if (fd_tmp < 0)
2198 goto on_error;
2199
2200on_error:
2201 close(fd_ctl);
2202 return fd_tmp;
2203}
2204
2205int lxc_prepare_loop_dev(const char *source, char *loop_dev, int flags)
2206{
2207 int ret;
2208 struct loop_info64 lo64;
2209 int fd_img = -1, fret = -1, fd_loop = -1;
2210
2211 fd_loop = lxc_get_unused_loop_dev(loop_dev);
2212 if (fd_loop < 0) {
2213 if (fd_loop == -ENODEV)
2214 fd_loop = lxc_get_unused_loop_dev_legacy(loop_dev);
2215 else
2216 goto on_error;
2217 }
2218
2219 fd_img = open(source, O_RDWR | O_CLOEXEC);
2220 if (fd_img < 0)
2221 goto on_error;
2222
2223 ret = ioctl(fd_loop, LOOP_SET_FD, fd_img);
2224 if (ret < 0)
2225 goto on_error;
2226
2227 memset(&lo64, 0, sizeof(lo64));
2228 lo64.lo_flags = flags;
2229
2230 ret = ioctl(fd_loop, LOOP_SET_STATUS64, &lo64);
2231 if (ret < 0)
2232 goto on_error;
2233
2234 fret = 0;
2235
2236on_error:
2237 if (fd_img >= 0)
2238 close(fd_img);
2239
2240 if (fret < 0 && fd_loop >= 0) {
2241 close(fd_loop);
2242 fd_loop = -1;
2243 }
2244
2245 return fd_loop;
2246}
74251e49
CB
2247
2248int lxc_unstack_mountpoint(const char *path, bool lazy)
2249{
2250 int ret;
2251 int umounts = 0;
2252
2253pop_stack:
2254 ret = umount2(path, lazy ? MNT_DETACH : 0);
2255 if (ret < 0) {
2256 /* We consider anything else than EINVAL deadly to prevent going
2257 * into an infinite loop. (The other alternative is constantly
2258 * parsing /proc/self/mountinfo which is yucky and probably
2259 * racy.)
2260 */
2261 if (errno != EINVAL)
2262 return -errno;
2263 } else {
b4a40f7b
CB
2264 /* Just stop counting when this happens. That'd just be so
2265 * stupid that we won't even bother trying to report back the
2266 * correct value anymore.
2267 */
2268 if (umounts != INT_MAX)
2269 umounts++;
74251e49
CB
2270 /* We succeeded in umounting. Make sure that there's no other
2271 * mountpoint stacked underneath.
2272 */
74251e49
CB
2273 goto pop_stack;
2274 }
2275
2276 return umounts;
2277}
ea3a694f
CB
2278
2279int run_command(char *buf, size_t buf_size, int (*child_fn)(void *), void *args)
2280{
2281 pid_t child;
2282 int ret, fret, pipefd[2];
2283 ssize_t bytes;
2284
2285 /* Make sure our callers do not receive unitialized memory. */
2286 if (buf_size > 0 && buf)
2287 buf[0] = '\0';
2288
2289 if (pipe(pipefd) < 0) {
2290 SYSERROR("failed to create pipe");
2291 return -1;
2292 }
2293
2294 child = fork();
2295 if (child < 0) {
2296 close(pipefd[0]);
2297 close(pipefd[1]);
2298 SYSERROR("failed to create new process");
2299 return -1;
2300 }
2301
2302 if (child == 0) {
2303 /* Close the read-end of the pipe. */
2304 close(pipefd[0]);
2305
2306 /* Redirect std{err,out} to write-end of the
2307 * pipe.
2308 */
2309 ret = dup2(pipefd[1], STDOUT_FILENO);
2310 if (ret >= 0)
2311 ret = dup2(pipefd[1], STDERR_FILENO);
2312
2313 /* Close the write-end of the pipe. */
2314 close(pipefd[1]);
2315
2316 if (ret < 0) {
2317 SYSERROR("failed to duplicate std{err,out} file descriptor");
2318 exit(EXIT_FAILURE);
2319 }
2320
2321 /* Does not return. */
2322 child_fn(args);
2323 ERROR("failed to exec command");
2324 exit(EXIT_FAILURE);
2325 }
2326
2327 /* close the write-end of the pipe */
2328 close(pipefd[1]);
2329
2330 bytes = read(pipefd[0], buf, (buf_size > 0) ? (buf_size - 1) : 0);
2331 if (bytes > 0)
2332 buf[bytes - 1] = '\0';
2333
2334 fret = wait_for_pid(child);
2335 /* close the read-end of the pipe */
2336 close(pipefd[0]);
2337
2338 return fret;
2339}
04ad7ffe
CB
2340
2341char *must_make_path(const char *first, ...)
2342{
2343 va_list args;
2344 char *cur, *dest;
2345 size_t full_len = strlen(first);
2346
2347 dest = must_copy_string(first);
2348
2349 va_start(args, first);
2350 while ((cur = va_arg(args, char *)) != NULL) {
2351 full_len += strlen(cur);
2352 if (cur[0] != '/')
2353 full_len++;
2354 dest = must_realloc(dest, full_len + 1);
2355 if (cur[0] != '/')
2356 strcat(dest, "/");
2357 strcat(dest, cur);
2358 }
2359 va_end(args);
2360
2361 return dest;
2362}
2363
2364char *must_copy_string(const char *entry)
2365{
2366 char *ret;
2367
2368 if (!entry)
2369 return NULL;
2370 do {
2371 ret = strdup(entry);
2372 } while (!ret);
2373
2374 return ret;
2375}
2376
2377void *must_realloc(void *orig, size_t sz)
2378{
2379 void *ret;
2380
2381 do {
2382 ret = realloc(orig, sz);
2383 } while (!ret);
2384
2385 return ret;
2386}
a035c53a
CB
2387
2388bool is_fs_type(const struct statfs *fs, fs_type_magic magic_val)
2389{
2390 return (fs->f_type == (fs_type_magic)magic_val);
2391}
2392
2393bool has_fs_type(const char *path, fs_type_magic magic_val)
2394{
2395 bool has_type;
2396 int ret;
2397 struct statfs sb;
2398
2399 ret = statfs(path, &sb);
2400 if (ret < 0)
2401 return false;
2402
2403 has_type = is_fs_type(&sb, magic_val);
2404 if (!has_type && magic_val == RAMFS_MAGIC)
2405 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2406
2407 return has_type;
2408}