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