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