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