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