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