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