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