]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/utils.c
log: change DEBUG, INFO, TRACE, NOTICE macro using strerror to SYS* macro
[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 SYSDEBUG("unable to fread /dev/urandom, fallback to time+pid rand seed");
1084
1085 fclose(f);
1086 }
1087
1088 if (srand_it)
1089 srand(seed);
1090
1091 return seed;
1092 }
1093
1094 uid_t get_ns_uid(uid_t orig)
1095 {
1096 char *line = NULL;
1097 size_t sz = 0;
1098 uid_t nsid, hostid, range;
1099 FILE *f = fopen("/proc/self/uid_map", "r");
1100 if (!f)
1101 return 0;
1102
1103 while (getline(&line, &sz, f) != -1) {
1104 if (sscanf(line, "%u %u %u", &nsid, &hostid, &range) != 3)
1105 continue;
1106 if (hostid <= orig && hostid + range > orig) {
1107 nsid += orig - hostid;
1108 goto found;
1109 }
1110 }
1111
1112 nsid = 0;
1113 found:
1114 fclose(f);
1115 free(line);
1116 return nsid;
1117 }
1118
1119 bool dir_exists(const char *path)
1120 {
1121 struct stat sb;
1122 int ret;
1123
1124 ret = stat(path, &sb);
1125 if (ret < 0)
1126 /* Could be something other than eexist, just say "no". */
1127 return false;
1128 return S_ISDIR(sb.st_mode);
1129 }
1130
1131 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1132 * FNV has good anti collision properties and we're not worried
1133 * about pre-image resistance or one-way-ness, we're just trying to make
1134 * the name unique in the 108 bytes of space we have.
1135 */
1136 uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
1137 {
1138 unsigned char *bp;
1139
1140 for(bp = buf; bp < (unsigned char *)buf + len; bp++)
1141 {
1142 /* xor the bottom with the current octet */
1143 hval ^= (uint64_t)*bp;
1144
1145 /* gcc optimised:
1146 * multiply by the 64 bit FNV magic prime mod 2^64
1147 */
1148 hval += (hval << 1) + (hval << 4) + (hval << 5) +
1149 (hval << 7) + (hval << 8) + (hval << 40);
1150 }
1151
1152 return hval;
1153 }
1154
1155 /*
1156 * Detect whether / is mounted MS_SHARED. The only way I know of to
1157 * check that is through /proc/self/mountinfo.
1158 * I'm only checking for /. If the container rootfs or mount location
1159 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1160 * out would be too much work to be worth it.
1161 */
1162 int detect_shared_rootfs(void)
1163 {
1164 char buf[LXC_LINELEN], *p;
1165 FILE *f;
1166 int i;
1167 char *p2;
1168
1169 f = fopen("/proc/self/mountinfo", "r");
1170 if (!f)
1171 return 0;
1172 while (fgets(buf, LXC_LINELEN, f)) {
1173 for (p = buf, i = 0; p && i < 4; i++)
1174 p = strchr(p + 1, ' ');
1175 if (!p)
1176 continue;
1177 p2 = strchr(p + 1, ' ');
1178 if (!p2)
1179 continue;
1180 *p2 = '\0';
1181 if (strcmp(p + 1, "/") == 0) {
1182 /* This is '/'. Is it shared? */
1183 p = strchr(p2 + 1, ' ');
1184 if (p && strstr(p, "shared:")) {
1185 fclose(f);
1186 return 1;
1187 }
1188 }
1189 }
1190 fclose(f);
1191 return 0;
1192 }
1193
1194 bool switch_to_ns(pid_t pid, const char *ns) {
1195 int fd, ret;
1196 char nspath[MAXPATHLEN];
1197
1198 /* Switch to new ns */
1199 ret = snprintf(nspath, MAXPATHLEN, "/proc/%d/ns/%s", pid, ns);
1200 if (ret < 0 || ret >= MAXPATHLEN)
1201 return false;
1202
1203 fd = open(nspath, O_RDONLY);
1204 if (fd < 0) {
1205 SYSERROR("failed to open %s", nspath);
1206 return false;
1207 }
1208
1209 ret = setns(fd, 0);
1210 if (ret) {
1211 SYSERROR("failed to set process %d to %s of %d.", pid, ns, fd);
1212 close(fd);
1213 return false;
1214 }
1215 close(fd);
1216 return true;
1217 }
1218
1219 /*
1220 * looking at fs/proc_namespace.c, it appears we can
1221 * actually expect the rootfs entry to very specifically contain
1222 * " - rootfs rootfs "
1223 * IIUC, so long as we've chrooted so that rootfs is not our root,
1224 * the rootfs entry should always be skipped in mountinfo contents.
1225 */
1226 bool detect_ramfs_rootfs(void)
1227 {
1228 FILE *f;
1229 char *p, *p2;
1230 char *line = NULL;
1231 size_t len = 0;
1232 int i;
1233
1234 f = fopen("/proc/self/mountinfo", "r");
1235 if (!f)
1236 return false;
1237
1238 while (getline(&line, &len, f) != -1) {
1239 for (p = line, i = 0; p && i < 4; i++)
1240 p = strchr(p + 1, ' ');
1241 if (!p)
1242 continue;
1243 p2 = strchr(p + 1, ' ');
1244 if (!p2)
1245 continue;
1246 *p2 = '\0';
1247 if (strcmp(p + 1, "/") == 0) {
1248 /* This is '/'. Is it the ramfs? */
1249 p = strchr(p2 + 1, '-');
1250 if (p && strncmp(p, "- rootfs rootfs ", 16) == 0) {
1251 free(line);
1252 fclose(f);
1253 return true;
1254 }
1255 }
1256 }
1257 free(line);
1258 fclose(f);
1259 return false;
1260 }
1261
1262 char *on_path(const char *cmd, const char *rootfs) {
1263 char *path = NULL;
1264 char *entry = NULL;
1265 char *saveptr = NULL;
1266 char cmdpath[MAXPATHLEN];
1267 int ret;
1268
1269 path = getenv("PATH");
1270 if (!path)
1271 return NULL;
1272
1273 path = strdup(path);
1274 if (!path)
1275 return NULL;
1276
1277 entry = strtok_r(path, ":", &saveptr);
1278 while (entry) {
1279 if (rootfs)
1280 ret = snprintf(cmdpath, MAXPATHLEN, "%s/%s/%s", rootfs, entry, cmd);
1281 else
1282 ret = snprintf(cmdpath, MAXPATHLEN, "%s/%s", entry, cmd);
1283
1284 if (ret < 0 || ret >= MAXPATHLEN)
1285 goto next_loop;
1286
1287 if (access(cmdpath, X_OK) == 0) {
1288 free(path);
1289 return strdup(cmdpath);
1290 }
1291
1292 next_loop:
1293 entry = strtok_r(NULL, ":", &saveptr);
1294 }
1295
1296 free(path);
1297 return NULL;
1298 }
1299
1300 bool file_exists(const char *f)
1301 {
1302 struct stat statbuf;
1303
1304 return stat(f, &statbuf) == 0;
1305 }
1306
1307 bool cgns_supported(void)
1308 {
1309 return file_exists("/proc/self/ns/cgroup");
1310 }
1311
1312 /* historically lxc-init has been under /usr/lib/lxc and under
1313 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1314 */
1315 char *choose_init(const char *rootfs)
1316 {
1317 char *retv = NULL;
1318 const char *empty = "",
1319 *tmp;
1320 int ret, env_set = 0;
1321
1322 if (!getenv("PATH")) {
1323 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1324 SYSERROR("Failed to setenv");
1325 env_set = 1;
1326 }
1327
1328 retv = on_path("init.lxc", rootfs);
1329
1330 if (env_set) {
1331 if (unsetenv("PATH"))
1332 SYSERROR("Failed to unsetenv");
1333 }
1334
1335 if (retv)
1336 return retv;
1337
1338 retv = malloc(PATH_MAX);
1339 if (!retv)
1340 return NULL;
1341
1342 if (rootfs)
1343 tmp = rootfs;
1344 else
1345 tmp = empty;
1346
1347 ret = snprintf(retv, PATH_MAX, "%s/%s/%s", tmp, SBINDIR, "/init.lxc");
1348 if (ret < 0 || ret >= PATH_MAX) {
1349 ERROR("pathname too long");
1350 goto out1;
1351 }
1352 if (access(retv, X_OK) == 0)
1353 return retv;
1354
1355 ret = snprintf(retv, PATH_MAX, "%s/%s/%s", tmp, LXCINITDIR, "/lxc/lxc-init");
1356 if (ret < 0 || ret >= PATH_MAX) {
1357 ERROR("pathname too long");
1358 goto out1;
1359 }
1360 if (access(retv, X_OK) == 0)
1361 return retv;
1362
1363 ret = snprintf(retv, PATH_MAX, "%s/usr/lib/lxc/lxc-init", tmp);
1364 if (ret < 0 || ret >= PATH_MAX) {
1365 ERROR("pathname too long");
1366 goto out1;
1367 }
1368 if (access(retv, X_OK) == 0)
1369 return retv;
1370
1371 ret = snprintf(retv, PATH_MAX, "%s/sbin/lxc-init", tmp);
1372 if (ret < 0 || ret >= PATH_MAX) {
1373 ERROR("pathname too long");
1374 goto out1;
1375 }
1376 if (access(retv, X_OK) == 0)
1377 return retv;
1378
1379 /*
1380 * Last resort, look for the statically compiled init.lxc which we
1381 * hopefully bind-mounted in.
1382 * If we are called during container setup, and we get to this point,
1383 * then the init.lxc.static from the host will need to be bind-mounted
1384 * in. So we return NULL here to indicate that.
1385 */
1386 if (rootfs)
1387 goto out1;
1388
1389 ret = snprintf(retv, PATH_MAX, "/init.lxc.static");
1390 if (ret < 0 || ret >= PATH_MAX) {
1391 WARN("Nonsense - name /lxc.init.static too long");
1392 goto out1;
1393 }
1394 if (access(retv, X_OK) == 0)
1395 return retv;
1396
1397 out1:
1398 free(retv);
1399 return NULL;
1400 }
1401
1402 int print_to_file(const char *file, const char *content)
1403 {
1404 FILE *f;
1405 int ret = 0;
1406
1407 f = fopen(file, "w");
1408 if (!f)
1409 return -1;
1410 if (fprintf(f, "%s", content) != strlen(content))
1411 ret = -1;
1412 fclose(f);
1413 return ret;
1414 }
1415
1416 int is_dir(const char *path)
1417 {
1418 struct stat statbuf;
1419 int ret = stat(path, &statbuf);
1420 if (ret == 0 && S_ISDIR(statbuf.st_mode))
1421 return 1;
1422 return 0;
1423 }
1424
1425 /*
1426 * Given the '-t' template option to lxc-create, figure out what to
1427 * do. If the template is a full executable path, use that. If it
1428 * is something like 'sshd', then return $templatepath/lxc-sshd.
1429 * On success return the template, on error return NULL.
1430 */
1431 char *get_template_path(const char *t)
1432 {
1433 int ret, len;
1434 char *tpath;
1435
1436 if (t[0] == '/' && access(t, X_OK) == 0) {
1437 tpath = strdup(t);
1438 return tpath;
1439 }
1440
1441 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
1442 tpath = malloc(len);
1443 if (!tpath)
1444 return NULL;
1445 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
1446 if (ret < 0 || ret >= len) {
1447 free(tpath);
1448 return NULL;
1449 }
1450 if (access(tpath, X_OK) < 0) {
1451 SYSERROR("bad template: %s", t);
1452 free(tpath);
1453 return NULL;
1454 }
1455
1456 return tpath;
1457 }
1458
1459 /*
1460 * @path: a pathname where / replaced with '\0'.
1461 * @offsetp: pointer to int showing which path segment was last seen.
1462 * Updated on return to reflect the next segment.
1463 * @fulllen: full original path length.
1464 * Returns a pointer to the next path segment, or NULL if done.
1465 */
1466 static char *get_nextpath(char *path, int *offsetp, int fulllen)
1467 {
1468 int offset = *offsetp;
1469
1470 if (offset >= fulllen)
1471 return NULL;
1472
1473 while (path[offset] != '\0' && offset < fulllen)
1474 offset++;
1475 while (path[offset] == '\0' && offset < fulllen)
1476 offset++;
1477
1478 *offsetp = offset;
1479 return (offset < fulllen) ? &path[offset] : NULL;
1480 }
1481
1482 /*
1483 * Check that @subdir is a subdir of @dir. @len is the length of
1484 * @dir (to avoid having to recalculate it).
1485 */
1486 static bool is_subdir(const char *subdir, const char *dir, size_t len)
1487 {
1488 size_t subdirlen = strlen(subdir);
1489
1490 if (subdirlen < len)
1491 return false;
1492 if (strncmp(subdir, dir, len) != 0)
1493 return false;
1494 if (dir[len-1] == '/')
1495 return true;
1496 if (subdir[len] == '/' || subdirlen == len)
1497 return true;
1498 return false;
1499 }
1500
1501 /*
1502 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1503 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1504 */
1505 static int check_symlink(int fd)
1506 {
1507 struct stat sb;
1508 int ret = fstat(fd, &sb);
1509 if (ret < 0)
1510 return -ENOENT;
1511 if (S_ISLNK(sb.st_mode))
1512 return -ELOOP;
1513 return 0;
1514 }
1515
1516 /*
1517 * Open a file or directory, provided that it contains no symlinks.
1518 *
1519 * CAVEAT: This function must not be used for other purposes than container
1520 * setup before executing the container's init
1521 */
1522 static int open_if_safe(int dirfd, const char *nextpath)
1523 {
1524 int newfd = openat(dirfd, nextpath, O_RDONLY | O_NOFOLLOW);
1525 if (newfd >= 0) /* Was not a symlink, all good. */
1526 return newfd;
1527
1528 if (errno == ELOOP)
1529 return newfd;
1530
1531 if (errno == EPERM || errno == EACCES) {
1532 /* We're not root (cause we got EPERM) so try opening with
1533 * O_PATH.
1534 */
1535 newfd = openat(dirfd, nextpath, O_PATH | O_NOFOLLOW);
1536 if (newfd >= 0) {
1537 /* O_PATH will return an fd for symlinks. We know
1538 * nextpath wasn't a symlink at last openat, so if fd is
1539 * now a link, then something * fishy is going on.
1540 */
1541 int ret = check_symlink(newfd);
1542 if (ret < 0) {
1543 close(newfd);
1544 newfd = ret;
1545 }
1546 }
1547 }
1548
1549 return newfd;
1550 }
1551
1552 /*
1553 * Open a path intending for mounting, ensuring that the final path
1554 * is inside the container's rootfs.
1555 *
1556 * CAVEAT: This function must not be used for other purposes than container
1557 * setup before executing the container's init
1558 *
1559 * @target: path to be opened
1560 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1561 * would be the container's rootfs.
1562 *
1563 * Return an open fd for the path, or <0 on error.
1564 */
1565 static int open_without_symlink(const char *target, const char *prefix_skip)
1566 {
1567 int curlen = 0, dirfd, fulllen, i;
1568 char *dup = NULL;
1569
1570 fulllen = strlen(target);
1571
1572 /* make sure prefix-skip makes sense */
1573 if (prefix_skip && strlen(prefix_skip) > 0) {
1574 curlen = strlen(prefix_skip);
1575 if (!is_subdir(target, prefix_skip, curlen)) {
1576 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1577 target, prefix_skip);
1578 return -EINVAL;
1579 }
1580 /*
1581 * get_nextpath() expects the curlen argument to be
1582 * on a (turned into \0) / or before it, so decrement
1583 * curlen to make sure that happens
1584 */
1585 if (curlen)
1586 curlen--;
1587 } else {
1588 prefix_skip = "/";
1589 curlen = 0;
1590 }
1591
1592 /* Make a copy of target which we can hack up, and tokenize it */
1593 if ((dup = strdup(target)) == NULL) {
1594 SYSERROR("Out of memory checking for symbolic link");
1595 return -ENOMEM;
1596 }
1597 for (i = 0; i < fulllen; i++) {
1598 if (dup[i] == '/')
1599 dup[i] = '\0';
1600 }
1601
1602 dirfd = open(prefix_skip, O_RDONLY);
1603 if (dirfd < 0)
1604 goto out;
1605 while (1) {
1606 int newfd, saved_errno;
1607 char *nextpath;
1608
1609 if ((nextpath = get_nextpath(dup, &curlen, fulllen)) == NULL)
1610 goto out;
1611 newfd = open_if_safe(dirfd, nextpath);
1612 saved_errno = errno;
1613 close(dirfd);
1614 dirfd = newfd;
1615 if (newfd < 0) {
1616 errno = saved_errno;
1617 if (errno == ELOOP)
1618 SYSERROR("%s in %s was a symbolic link!", nextpath, target);
1619 goto out;
1620 }
1621 }
1622
1623 out:
1624 free(dup);
1625 return dirfd;
1626 }
1627
1628 /*
1629 * Safely mount a path into a container, ensuring that the mount target
1630 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1631 * uses the host's /)
1632 *
1633 * CAVEAT: This function must not be used for other purposes than container
1634 * setup before executing the container's init
1635 */
1636 int safe_mount(const char *src, const char *dest, const char *fstype,
1637 unsigned long flags, const void *data, const char *rootfs)
1638 {
1639 int destfd, ret, saved_errno;
1640 /* Only needs enough for /proc/self/fd/<fd>. */
1641 char srcbuf[50], destbuf[50];
1642 int srcfd = -1;
1643 const char *mntsrc = src;
1644
1645 if (!rootfs)
1646 rootfs = "";
1647
1648 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1649 if (flags & MS_BIND && src && src[0] != '/') {
1650 INFO("this is a relative bind mount");
1651 srcfd = open_without_symlink(src, NULL);
1652 if (srcfd < 0)
1653 return srcfd;
1654 ret = snprintf(srcbuf, 50, "/proc/self/fd/%d", srcfd);
1655 if (ret < 0 || ret > 50) {
1656 close(srcfd);
1657 ERROR("Out of memory");
1658 return -EINVAL;
1659 }
1660 mntsrc = srcbuf;
1661 }
1662
1663 destfd = open_without_symlink(dest, rootfs);
1664 if (destfd < 0) {
1665 if (srcfd != -1) {
1666 saved_errno = errno;
1667 close(srcfd);
1668 errno = saved_errno;
1669 }
1670 return destfd;
1671 }
1672
1673 ret = snprintf(destbuf, 50, "/proc/self/fd/%d", destfd);
1674 if (ret < 0 || ret > 50) {
1675 if (srcfd != -1)
1676 close(srcfd);
1677 close(destfd);
1678 ERROR("Out of memory");
1679 return -EINVAL;
1680 }
1681
1682 ret = mount(mntsrc, destbuf, fstype, flags, data);
1683 saved_errno = errno;
1684 if (srcfd != -1)
1685 close(srcfd);
1686 close(destfd);
1687 if (ret < 0) {
1688 errno = saved_errno;
1689 SYSERROR("Failed to mount %s onto %s", src ? src : "(null)", dest);
1690 return ret;
1691 }
1692
1693 return 0;
1694 }
1695
1696 /*
1697 * Mount a proc under @rootfs if proc self points to a pid other than
1698 * my own. This is needed to have a known-good proc mount for setting
1699 * up LSMs both at container startup and attach.
1700 *
1701 * @rootfs : the rootfs where proc should be mounted
1702 *
1703 * Returns < 0 on failure, 0 if the correct proc was already mounted
1704 * and 1 if a new proc was mounted.
1705 *
1706 * NOTE: not to be called from inside the container namespace!
1707 */
1708 int lxc_mount_proc_if_needed(const char *rootfs)
1709 {
1710 char path[MAXPATHLEN];
1711 int link_to_pid, linklen, mypid, ret;
1712 char link[LXC_NUMSTRLEN64] = {0};
1713
1714 ret = snprintf(path, MAXPATHLEN, "%s/proc/self", rootfs);
1715 if (ret < 0 || ret >= MAXPATHLEN) {
1716 SYSERROR("proc path name too long");
1717 return -1;
1718 }
1719
1720 linklen = readlink(path, link, LXC_NUMSTRLEN64);
1721
1722 ret = snprintf(path, MAXPATHLEN, "%s/proc", rootfs);
1723 if (ret < 0 || ret >= MAXPATHLEN) {
1724 SYSERROR("proc path name too long");
1725 return -1;
1726 }
1727
1728 /* /proc not mounted */
1729 if (linklen < 0) {
1730 if (mkdir(path, 0755) && errno != EEXIST)
1731 return -1;
1732 goto domount;
1733 } else if (linklen >= LXC_NUMSTRLEN64) {
1734 link[linklen - 1] = '\0';
1735 ERROR("readlink returned truncated content: \"%s\"", link);
1736 return -1;
1737 }
1738
1739 mypid = lxc_raw_getpid();
1740 INFO("I am %d, /proc/self points to \"%s\"", mypid, link);
1741
1742 if (lxc_safe_int(link, &link_to_pid) < 0)
1743 return -1;
1744
1745 /* correct procfs is already mounted */
1746 if (link_to_pid == mypid)
1747 return 0;
1748
1749 ret = umount2(path, MNT_DETACH);
1750 if (ret < 0)
1751 WARN("failed to umount \"%s\" with MNT_DETACH", path);
1752
1753 domount:
1754 /* rootfs is NULL */
1755 if (!strcmp(rootfs, ""))
1756 ret = mount("proc", path, "proc", 0, NULL);
1757 else
1758 ret = safe_mount("proc", path, "proc", 0, NULL, rootfs);
1759 if (ret < 0)
1760 return -1;
1761
1762 INFO("mounted /proc in container for security transition");
1763 return 1;
1764 }
1765
1766 int open_devnull(void)
1767 {
1768 int fd = open("/dev/null", O_RDWR);
1769
1770 if (fd < 0)
1771 SYSERROR("Can't open /dev/null");
1772
1773 return fd;
1774 }
1775
1776 int set_stdfds(int fd)
1777 {
1778 int ret;
1779
1780 if (fd < 0)
1781 return -1;
1782
1783 ret = dup2(fd, STDIN_FILENO);
1784 if (ret < 0)
1785 return -1;
1786
1787 ret = dup2(fd, STDOUT_FILENO);
1788 if (ret < 0)
1789 return -1;
1790
1791 ret = dup2(fd, STDERR_FILENO);
1792 if (ret < 0)
1793 return -1;
1794
1795 return 0;
1796 }
1797
1798 int null_stdfds(void)
1799 {
1800 int ret = -1;
1801 int fd = open_devnull();
1802
1803 if (fd >= 0) {
1804 ret = set_stdfds(fd);
1805 close(fd);
1806 }
1807
1808 return ret;
1809 }
1810
1811 /*
1812 * Return the number of lines in file @fn, or -1 on error
1813 */
1814 int lxc_count_file_lines(const char *fn)
1815 {
1816 FILE *f;
1817 char *line = NULL;
1818 size_t sz = 0;
1819 int n = 0;
1820
1821 f = fopen_cloexec(fn, "r");
1822 if (!f)
1823 return -1;
1824
1825 while (getline(&line, &sz, f) != -1) {
1826 n++;
1827 }
1828 free(line);
1829 fclose(f);
1830 return n;
1831 }
1832
1833 /* Check whether a signal is blocked by a process. */
1834 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1835 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1836 bool task_blocks_signal(pid_t pid, int signal)
1837 {
1838 int ret;
1839 char status[__PROC_STATUS_LEN];
1840 FILE *f;
1841 uint64_t sigblk = 0, one = 1;
1842 size_t n = 0;
1843 bool bret = false;
1844 char *line = NULL;
1845
1846 ret = snprintf(status, __PROC_STATUS_LEN, "/proc/%d/status", pid);
1847 if (ret < 0 || ret >= __PROC_STATUS_LEN)
1848 return bret;
1849
1850 f = fopen(status, "r");
1851 if (!f)
1852 return bret;
1853
1854 while (getline(&line, &n, f) != -1) {
1855 char *numstr;
1856
1857 if (strncmp(line, "SigBlk:", 7))
1858 continue;
1859
1860 numstr = lxc_trim_whitespace_in_place(line + 7);
1861 ret = lxc_safe_uint64(numstr, &sigblk, 16);
1862 if (ret < 0)
1863 goto out;
1864
1865 break;
1866 }
1867
1868 if (sigblk & (one << (signal - 1)))
1869 bret = true;
1870
1871 out:
1872 free(line);
1873 fclose(f);
1874 return bret;
1875 }
1876
1877 static int lxc_append_null_to_list(void ***list)
1878 {
1879 int newentry = 0;
1880 void **tmp;
1881
1882 if (*list)
1883 for (; (*list)[newentry]; newentry++) {
1884 ;
1885 }
1886
1887 tmp = realloc(*list, (newentry + 2) * sizeof(void **));
1888 if (!tmp)
1889 return -1;
1890
1891 *list = tmp;
1892 (*list)[newentry + 1] = NULL;
1893
1894 return newentry;
1895 }
1896
1897 int lxc_append_string(char ***list, char *entry)
1898 {
1899 char *copy;
1900 int newentry;
1901
1902 newentry = lxc_append_null_to_list((void ***)list);
1903 if (newentry < 0)
1904 return -1;
1905
1906 copy = strdup(entry);
1907 if (!copy)
1908 return -1;
1909
1910 (*list)[newentry] = copy;
1911
1912 return 0;
1913 }
1914
1915 int lxc_preserve_ns(const int pid, const char *ns)
1916 {
1917 int ret;
1918 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1919 #define __NS_PATH_LEN 50
1920 char path[__NS_PATH_LEN];
1921
1922 /* This way we can use this function to also check whether namespaces
1923 * are supported by the kernel by passing in the NULL or the empty
1924 * string.
1925 */
1926 ret = snprintf(path, __NS_PATH_LEN, "/proc/%d/ns%s%s", pid,
1927 !ns || strcmp(ns, "") == 0 ? "" : "/",
1928 !ns || strcmp(ns, "") == 0 ? "" : ns);
1929 errno = EFBIG;
1930 if (ret < 0 || (size_t)ret >= __NS_PATH_LEN)
1931 return -EFBIG;
1932
1933 return open(path, O_RDONLY | O_CLOEXEC);
1934 }
1935
1936 int lxc_safe_uint(const char *numstr, unsigned int *converted)
1937 {
1938 char *err = NULL;
1939 unsigned long int uli;
1940
1941 while (isspace(*numstr))
1942 numstr++;
1943
1944 if (*numstr == '-')
1945 return -EINVAL;
1946
1947 errno = 0;
1948 uli = strtoul(numstr, &err, 0);
1949 if (errno == ERANGE && uli == ULONG_MAX)
1950 return -ERANGE;
1951
1952 if (err == numstr || *err != '\0')
1953 return -EINVAL;
1954
1955 if (uli > UINT_MAX)
1956 return -ERANGE;
1957
1958 *converted = (unsigned int)uli;
1959 return 0;
1960 }
1961
1962 int lxc_safe_ulong(const char *numstr, unsigned long *converted)
1963 {
1964 char *err = NULL;
1965 unsigned long int uli;
1966
1967 while (isspace(*numstr))
1968 numstr++;
1969
1970 if (*numstr == '-')
1971 return -EINVAL;
1972
1973 errno = 0;
1974 uli = strtoul(numstr, &err, 0);
1975 if (errno == ERANGE && uli == ULONG_MAX)
1976 return -ERANGE;
1977
1978 if (err == numstr || *err != '\0')
1979 return -EINVAL;
1980
1981 *converted = uli;
1982 return 0;
1983 }
1984
1985 int lxc_safe_uint64(const char *numstr, uint64_t *converted, int base)
1986 {
1987 char *err = NULL;
1988 uint64_t u;
1989
1990 while (isspace(*numstr))
1991 numstr++;
1992
1993 if (*numstr == '-')
1994 return -EINVAL;
1995
1996 errno = 0;
1997 u = strtoull(numstr, &err, base);
1998 if (errno == ERANGE && u == ULLONG_MAX)
1999 return -ERANGE;
2000
2001 if (err == numstr || *err != '\0')
2002 return -EINVAL;
2003
2004 *converted = u;
2005 return 0;
2006 }
2007
2008 int lxc_safe_int(const char *numstr, int *converted)
2009 {
2010 char *err = NULL;
2011 signed long int sli;
2012
2013 errno = 0;
2014 sli = strtol(numstr, &err, 0);
2015 if (errno == ERANGE && (sli == LONG_MAX || sli == LONG_MIN))
2016 return -ERANGE;
2017
2018 if (errno != 0 && sli == 0)
2019 return -EINVAL;
2020
2021 if (err == numstr || *err != '\0')
2022 return -EINVAL;
2023
2024 if (sli > INT_MAX || sli < INT_MIN)
2025 return -ERANGE;
2026
2027 *converted = (int)sli;
2028 return 0;
2029 }
2030
2031 int lxc_safe_long(const char *numstr, long int *converted)
2032 {
2033 char *err = NULL;
2034 signed long int sli;
2035
2036 errno = 0;
2037 sli = strtol(numstr, &err, 0);
2038 if (errno == ERANGE && (sli == LONG_MAX || sli == LONG_MIN))
2039 return -ERANGE;
2040
2041 if (errno != 0 && sli == 0)
2042 return -EINVAL;
2043
2044 if (err == numstr || *err != '\0')
2045 return -EINVAL;
2046
2047 *converted = sli;
2048 return 0;
2049 }
2050
2051 int lxc_safe_long_long(const char *numstr, long long int *converted)
2052 {
2053 char *err = NULL;
2054 signed long long int sli;
2055
2056 errno = 0;
2057 sli = strtoll(numstr, &err, 0);
2058 if (errno == ERANGE && (sli == LLONG_MAX || sli == LLONG_MIN))
2059 return -ERANGE;
2060
2061 if (errno != 0 && sli == 0)
2062 return -EINVAL;
2063
2064 if (err == numstr || *err != '\0')
2065 return -EINVAL;
2066
2067 *converted = sli;
2068 return 0;
2069 }
2070
2071 int lxc_switch_uid_gid(uid_t uid, gid_t gid)
2072 {
2073 if (setgid(gid) < 0) {
2074 SYSERROR("Failed to switch to gid %d.", gid);
2075 return -errno;
2076 }
2077 NOTICE("Switched to gid %d.", gid);
2078
2079 if (setuid(uid) < 0) {
2080 SYSERROR("Failed to switch to uid %d.", uid);
2081 return -errno;
2082 }
2083 NOTICE("Switched to uid %d.", uid);
2084
2085 return 0;
2086 }
2087
2088 /* Simple covenience function which enables uniform logging. */
2089 int lxc_setgroups(int size, gid_t list[])
2090 {
2091 if (setgroups(size, list) < 0) {
2092 SYSERROR("Failed to setgroups().");
2093 return -errno;
2094 }
2095 NOTICE("Dropped additional groups.");
2096
2097 return 0;
2098 }
2099
2100 static int lxc_get_unused_loop_dev_legacy(char *loop_name)
2101 {
2102 struct dirent *dp;
2103 struct loop_info64 lo64;
2104 DIR *dir;
2105 int dfd = -1, fd = -1, ret = -1;
2106
2107 dir = opendir("/dev");
2108 if (!dir)
2109 return -1;
2110
2111 while ((dp = readdir(dir))) {
2112 if (strncmp(dp->d_name, "loop", 4) != 0)
2113 continue;
2114
2115 dfd = dirfd(dir);
2116 if (dfd < 0)
2117 continue;
2118
2119 fd = openat(dfd, dp->d_name, O_RDWR);
2120 if (fd < 0)
2121 continue;
2122
2123 ret = ioctl(fd, LOOP_GET_STATUS64, &lo64);
2124 if (ret < 0) {
2125 if (ioctl(fd, LOOP_GET_STATUS64, &lo64) == 0 ||
2126 errno != ENXIO) {
2127 close(fd);
2128 fd = -1;
2129 continue;
2130 }
2131 }
2132
2133 ret = snprintf(loop_name, LO_NAME_SIZE, "/dev/%s", dp->d_name);
2134 if (ret < 0 || ret >= LO_NAME_SIZE) {
2135 close(fd);
2136 fd = -1;
2137 continue;
2138 }
2139
2140 break;
2141 }
2142
2143 closedir(dir);
2144
2145 if (fd < 0)
2146 return -1;
2147
2148 return fd;
2149 }
2150
2151 static int lxc_get_unused_loop_dev(char *name_loop)
2152 {
2153 int loop_nr, ret;
2154 int fd_ctl = -1, fd_tmp = -1;
2155
2156 fd_ctl = open("/dev/loop-control", O_RDWR | O_CLOEXEC);
2157 if (fd_ctl < 0)
2158 return -ENODEV;
2159
2160 loop_nr = ioctl(fd_ctl, LOOP_CTL_GET_FREE);
2161 if (loop_nr < 0)
2162 goto on_error;
2163
2164 ret = snprintf(name_loop, LO_NAME_SIZE, "/dev/loop%d", loop_nr);
2165 if (ret < 0 || ret >= LO_NAME_SIZE)
2166 goto on_error;
2167
2168 fd_tmp = open(name_loop, O_RDWR | O_CLOEXEC);
2169 if (fd_tmp < 0)
2170 goto on_error;
2171
2172 on_error:
2173 close(fd_ctl);
2174 return fd_tmp;
2175 }
2176
2177 int lxc_prepare_loop_dev(const char *source, char *loop_dev, int flags)
2178 {
2179 int ret;
2180 struct loop_info64 lo64;
2181 int fd_img = -1, fret = -1, fd_loop = -1;
2182
2183 fd_loop = lxc_get_unused_loop_dev(loop_dev);
2184 if (fd_loop < 0) {
2185 if (fd_loop == -ENODEV)
2186 fd_loop = lxc_get_unused_loop_dev_legacy(loop_dev);
2187 else
2188 goto on_error;
2189 }
2190
2191 fd_img = open(source, O_RDWR | O_CLOEXEC);
2192 if (fd_img < 0)
2193 goto on_error;
2194
2195 ret = ioctl(fd_loop, LOOP_SET_FD, fd_img);
2196 if (ret < 0)
2197 goto on_error;
2198
2199 memset(&lo64, 0, sizeof(lo64));
2200 lo64.lo_flags = flags;
2201
2202 ret = ioctl(fd_loop, LOOP_SET_STATUS64, &lo64);
2203 if (ret < 0)
2204 goto on_error;
2205
2206 fret = 0;
2207
2208 on_error:
2209 if (fd_img >= 0)
2210 close(fd_img);
2211
2212 if (fret < 0 && fd_loop >= 0) {
2213 close(fd_loop);
2214 fd_loop = -1;
2215 }
2216
2217 return fd_loop;
2218 }
2219
2220 int lxc_unstack_mountpoint(const char *path, bool lazy)
2221 {
2222 int ret;
2223 int umounts = 0;
2224
2225 pop_stack:
2226 ret = umount2(path, lazy ? MNT_DETACH : 0);
2227 if (ret < 0) {
2228 /* We consider anything else than EINVAL deadly to prevent going
2229 * into an infinite loop. (The other alternative is constantly
2230 * parsing /proc/self/mountinfo which is yucky and probably
2231 * racy.)
2232 */
2233 if (errno != EINVAL)
2234 return -errno;
2235 } else {
2236 /* Just stop counting when this happens. That'd just be so
2237 * stupid that we won't even bother trying to report back the
2238 * correct value anymore.
2239 */
2240 if (umounts != INT_MAX)
2241 umounts++;
2242 /* We succeeded in umounting. Make sure that there's no other
2243 * mountpoint stacked underneath.
2244 */
2245 goto pop_stack;
2246 }
2247
2248 return umounts;
2249 }
2250
2251 int run_command(char *buf, size_t buf_size, int (*child_fn)(void *), void *args)
2252 {
2253 pid_t child;
2254 int ret, fret, pipefd[2];
2255 ssize_t bytes;
2256
2257 /* Make sure our callers do not receive uninitialized memory. */
2258 if (buf_size > 0 && buf)
2259 buf[0] = '\0';
2260
2261 if (pipe(pipefd) < 0) {
2262 SYSERROR("failed to create pipe");
2263 return -1;
2264 }
2265
2266 child = lxc_raw_clone(0);
2267 if (child < 0) {
2268 close(pipefd[0]);
2269 close(pipefd[1]);
2270 SYSERROR("failed to create new process");
2271 return -1;
2272 }
2273
2274 if (child == 0) {
2275 /* Close the read-end of the pipe. */
2276 close(pipefd[0]);
2277
2278 /* Redirect std{err,out} to write-end of the
2279 * pipe.
2280 */
2281 ret = dup2(pipefd[1], STDOUT_FILENO);
2282 if (ret >= 0)
2283 ret = dup2(pipefd[1], STDERR_FILENO);
2284
2285 /* Close the write-end of the pipe. */
2286 close(pipefd[1]);
2287
2288 if (ret < 0) {
2289 SYSERROR("failed to duplicate std{err,out} file descriptor");
2290 _exit(EXIT_FAILURE);
2291 }
2292
2293 /* Does not return. */
2294 child_fn(args);
2295 ERROR("failed to exec command");
2296 _exit(EXIT_FAILURE);
2297 }
2298
2299 /* close the write-end of the pipe */
2300 close(pipefd[1]);
2301
2302 if (buf && buf_size > 0) {
2303 bytes = read(pipefd[0], buf, buf_size - 1);
2304 if (bytes > 0)
2305 buf[bytes - 1] = '\0';
2306 }
2307
2308 fret = wait_for_pid(child);
2309 /* close the read-end of the pipe */
2310 close(pipefd[0]);
2311
2312 return fret;
2313 }
2314
2315 char *must_make_path(const char *first, ...)
2316 {
2317 va_list args;
2318 char *cur, *dest;
2319 size_t full_len = strlen(first);
2320 size_t buf_len;
2321
2322 dest = must_copy_string(first);
2323
2324 va_start(args, first);
2325 while ((cur = va_arg(args, char *)) != NULL) {
2326 full_len += strlen(cur);
2327 if (cur[0] != '/')
2328 full_len++;
2329
2330 buf_len = full_len + 1;
2331 dest = must_realloc(dest, buf_len);
2332
2333 if (cur[0] != '/')
2334 (void)strlcat(dest, "/", buf_len);
2335 (void)strlcat(dest, cur, buf_len);
2336 }
2337 va_end(args);
2338
2339 return dest;
2340 }
2341
2342 char *must_append_path(char *first, ...)
2343 {
2344 char *cur;
2345 size_t full_len;
2346 va_list args;
2347 char *dest = first;
2348 size_t buf_len;
2349
2350 full_len = strlen(first);
2351 va_start(args, first);
2352 while ((cur = va_arg(args, char *)) != NULL) {
2353 full_len += strlen(cur);
2354 if (cur[0] != '/')
2355 full_len++;
2356
2357 buf_len = full_len + 1;
2358 dest = must_realloc(dest, buf_len);
2359
2360 if (cur[0] != '/')
2361 (void)strlcat(dest, "/", buf_len);
2362 (void)strlcat(dest, cur, buf_len);
2363 }
2364 va_end(args);
2365
2366 return dest;
2367 }
2368
2369 char *must_copy_string(const char *entry)
2370 {
2371 char *ret;
2372
2373 if (!entry)
2374 return NULL;
2375 do {
2376 ret = strdup(entry);
2377 } while (!ret);
2378
2379 return ret;
2380 }
2381
2382 void *must_realloc(void *orig, size_t sz)
2383 {
2384 void *ret;
2385
2386 do {
2387 ret = realloc(orig, sz);
2388 } while (!ret);
2389
2390 return ret;
2391 }
2392
2393 bool is_fs_type(const struct statfs *fs, fs_type_magic magic_val)
2394 {
2395 return (fs->f_type == (fs_type_magic)magic_val);
2396 }
2397
2398 bool has_fs_type(const char *path, fs_type_magic magic_val)
2399 {
2400 bool has_type;
2401 int ret;
2402 struct statfs sb;
2403
2404 ret = statfs(path, &sb);
2405 if (ret < 0)
2406 return false;
2407
2408 has_type = is_fs_type(&sb, magic_val);
2409 if (!has_type && magic_val == RAMFS_MAGIC)
2410 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2411
2412 return has_type;
2413 }
2414
2415 bool lxc_nic_exists(char *nic)
2416 {
2417 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2418 char path[__LXC_SYS_CLASS_NET_LEN];
2419 int ret;
2420 struct stat sb;
2421
2422 if (!strcmp(nic, "none"))
2423 return true;
2424
2425 ret = snprintf(path, __LXC_SYS_CLASS_NET_LEN, "/sys/class/net/%s", nic);
2426 if (ret < 0 || (size_t)ret >= __LXC_SYS_CLASS_NET_LEN)
2427 return false;
2428
2429 ret = stat(path, &sb);
2430 if (ret < 0)
2431 return false;
2432
2433 return true;
2434 }
2435
2436 int lxc_make_tmpfile(char *template, bool rm)
2437 {
2438 int fd, ret;
2439 mode_t msk;
2440
2441 msk = umask(0022);
2442 fd = mkstemp(template);
2443 umask(msk);
2444 if (fd < 0)
2445 return -1;
2446
2447 if (!rm)
2448 return fd;
2449
2450 ret = unlink(template);
2451 if (ret < 0) {
2452 close(fd);
2453 return -1;
2454 }
2455
2456 return fd;
2457 }
2458
2459 int parse_byte_size_string(const char *s, int64_t *converted)
2460 {
2461 int ret, suffix_len;
2462 long long int conv;
2463 int64_t mltpl, overflow;
2464 char *end;
2465 char dup[LXC_NUMSTRLEN64 + 2];
2466 char suffix[3] = {0};
2467
2468 if (!s || !strcmp(s, ""))
2469 return -EINVAL;
2470
2471 end = stpncpy(dup, s, sizeof(dup) - 1);
2472 if (*end != '\0')
2473 return -EINVAL;
2474
2475 if (isdigit(*(end - 1)))
2476 suffix_len = 0;
2477 else if (isalpha(*(end - 1)))
2478 suffix_len = 1;
2479 else
2480 return -EINVAL;
2481
2482 if (suffix_len > 0 && (end - 2) == dup && !isdigit(*(end - 2)))
2483 return -EINVAL;
2484
2485 if (suffix_len > 0 && isalpha(*(end - 2)))
2486 suffix_len++;
2487
2488 if (suffix_len > 0) {
2489 memcpy(suffix, end - suffix_len, suffix_len);
2490 *(suffix + suffix_len) = '\0';
2491 *(end - suffix_len) = '\0';
2492 }
2493 dup[lxc_char_right_gc(dup, strlen(dup))] = '\0';
2494
2495 ret = lxc_safe_long_long(dup, &conv);
2496 if (ret < 0)
2497 return -ret;
2498
2499 if (suffix_len != 2) {
2500 *converted = conv;
2501 return 0;
2502 }
2503
2504 if (strcasecmp(suffix, "KB") == 0)
2505 mltpl = 1024;
2506 else if (strcasecmp(suffix, "MB") == 0)
2507 mltpl = 1024 * 1024;
2508 else if (strcasecmp(suffix, "GB") == 0)
2509 mltpl = 1024 * 1024 * 1024;
2510 else
2511 return -EINVAL;
2512
2513 overflow = conv * mltpl;
2514 if (conv != 0 && (overflow / conv) != mltpl)
2515 return -ERANGE;
2516
2517 *converted = overflow;
2518 return 0;
2519 }
2520
2521 uint64_t lxc_find_next_power2(uint64_t n)
2522 {
2523 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2524 * valid power of two.
2525 */
2526 if (n == 0)
2527 return 0;
2528
2529 if (!(n & (n - 1)))
2530 return n;
2531
2532 while (n & (n - 1))
2533 n = n & (n - 1);
2534
2535 n = n << 1;
2536 return n;
2537 }
2538
2539 int lxc_set_death_signal(int signal)
2540 {
2541 int ret;
2542 pid_t ppid;
2543
2544 ret = prctl(PR_SET_PDEATHSIG, signal, 0, 0, 0);
2545
2546 /* Check whether we have been orphaned. */
2547 ppid = (pid_t)syscall(SYS_getppid);
2548 if (ppid == 1) {
2549 pid_t self;
2550
2551 self = lxc_raw_getpid();
2552 ret = kill(self, SIGKILL);
2553 if (ret < 0)
2554 return -1;
2555 }
2556
2557 if (ret < 0) {
2558 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal);
2559 return -1;
2560 }
2561
2562 return 0;
2563 }
2564
2565 void remove_trailing_newlines(char *l)
2566 {
2567 char *p = l;
2568
2569 while (*p)
2570 p++;
2571
2572 while (--p >= l && *p == '\n')
2573 *p = '\0';
2574 }