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