chiark / gitweb /
core: do not fail in a container if we can't use setgroups
[elogind.git] / src / basic / fs-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <dirent.h>
21 #include <errno.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <time.h>
28 #include <unistd.h>
29
30 #include "alloc-util.h"
31 #include "dirent-util.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "fs-util.h"
35 //#include "log.h"
36 //#include "macro.h"
37 //#include "missing.h"
38 #include "mkdir.h"
39 #include "parse-util.h"
40 #include "path-util.h"
41 #include "string-util.h"
42 #include "strv.h"
43 //#include "time-util.h"
44 #include "user-util.h"
45 #include "util.h"
46
47 int unlink_noerrno(const char *path) {
48         PROTECT_ERRNO;
49         int r;
50
51         r = unlink(path);
52         if (r < 0)
53                 return -errno;
54
55         return 0;
56 }
57
58 #if 0 /// UNNEEDED by elogind
59 int rmdir_parents(const char *path, const char *stop) {
60         size_t l;
61         int r = 0;
62
63         assert(path);
64         assert(stop);
65
66         l = strlen(path);
67
68         /* Skip trailing slashes */
69         while (l > 0 && path[l-1] == '/')
70                 l--;
71
72         while (l > 0) {
73                 char *t;
74
75                 /* Skip last component */
76                 while (l > 0 && path[l-1] != '/')
77                         l--;
78
79                 /* Skip trailing slashes */
80                 while (l > 0 && path[l-1] == '/')
81                         l--;
82
83                 if (l <= 0)
84                         break;
85
86                 t = strndup(path, l);
87                 if (!t)
88                         return -ENOMEM;
89
90                 if (path_startswith(stop, t)) {
91                         free(t);
92                         return 0;
93                 }
94
95                 r = rmdir(t);
96                 free(t);
97
98                 if (r < 0)
99                         if (errno != ENOENT)
100                                 return -errno;
101         }
102
103         return 0;
104 }
105
106
107 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
108         struct stat buf;
109         int ret;
110
111         ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
112         if (ret >= 0)
113                 return 0;
114
115         /* renameat2() exists since Linux 3.15, btrfs added support for it later.
116          * If it is not implemented, fallback to another method. */
117         if (!IN_SET(errno, EINVAL, ENOSYS))
118                 return -errno;
119
120         /* The link()/unlink() fallback does not work on directories. But
121          * renameat() without RENAME_NOREPLACE gives the same semantics on
122          * directories, except when newpath is an *empty* directory. This is
123          * good enough. */
124         ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
125         if (ret >= 0 && S_ISDIR(buf.st_mode)) {
126                 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
127                 return ret >= 0 ? 0 : -errno;
128         }
129
130         /* If it is not a directory, use the link()/unlink() fallback. */
131         ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
132         if (ret < 0)
133                 return -errno;
134
135         ret = unlinkat(olddirfd, oldpath, 0);
136         if (ret < 0) {
137                 /* backup errno before the following unlinkat() alters it */
138                 ret = errno;
139                 (void) unlinkat(newdirfd, newpath, 0);
140                 errno = ret;
141                 return -errno;
142         }
143
144         return 0;
145 }
146 #endif // 0
147
148 int readlinkat_malloc(int fd, const char *p, char **ret) {
149         size_t l = 100;
150         int r;
151
152         assert(p);
153         assert(ret);
154
155         for (;;) {
156                 char *c;
157                 ssize_t n;
158
159                 c = new(char, l);
160                 if (!c)
161                         return -ENOMEM;
162
163                 n = readlinkat(fd, p, c, l-1);
164                 if (n < 0) {
165                         r = -errno;
166                         free(c);
167                         return r;
168                 }
169
170                 if ((size_t) n < l-1) {
171                         c[n] = 0;
172                         *ret = c;
173                         return 0;
174                 }
175
176                 free(c);
177                 l *= 2;
178         }
179 }
180
181 int readlink_malloc(const char *p, char **ret) {
182         return readlinkat_malloc(AT_FDCWD, p, ret);
183 }
184
185 #if 0 /// UNNEEDED by elogind
186 int readlink_value(const char *p, char **ret) {
187         _cleanup_free_ char *link = NULL;
188         char *value;
189         int r;
190
191         r = readlink_malloc(p, &link);
192         if (r < 0)
193                 return r;
194
195         value = basename(link);
196         if (!value)
197                 return -ENOENT;
198
199         value = strdup(value);
200         if (!value)
201                 return -ENOMEM;
202
203         *ret = value;
204
205         return 0;
206 }
207
208 int readlink_and_make_absolute(const char *p, char **r) {
209         _cleanup_free_ char *target = NULL;
210         char *k;
211         int j;
212
213         assert(p);
214         assert(r);
215
216         j = readlink_malloc(p, &target);
217         if (j < 0)
218                 return j;
219
220         k = file_in_same_dir(p, target);
221         if (!k)
222                 return -ENOMEM;
223
224         *r = k;
225         return 0;
226 }
227
228 int readlink_and_canonicalize(const char *p, char **r) {
229         char *t, *s;
230         int j;
231
232         assert(p);
233         assert(r);
234
235         j = readlink_and_make_absolute(p, &t);
236         if (j < 0)
237                 return j;
238
239         s = canonicalize_file_name(t);
240         if (s) {
241                 free(t);
242                 *r = s;
243         } else
244                 *r = t;
245
246         path_kill_slashes(*r);
247
248         return 0;
249 }
250
251 int readlink_and_make_absolute_root(const char *root, const char *path, char **ret) {
252         _cleanup_free_ char *target = NULL, *t = NULL;
253         const char *full;
254         int r;
255
256         full = prefix_roota(root, path);
257         r = readlink_malloc(full, &target);
258         if (r < 0)
259                 return r;
260
261         t = file_in_same_dir(path, target);
262         if (!t)
263                 return -ENOMEM;
264
265         *ret = t;
266         t = NULL;
267
268         return 0;
269 }
270 #endif // 0
271
272 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
273         assert(path);
274
275         /* Under the assumption that we are running privileged we
276          * first change the access mode and only then hand out
277          * ownership to avoid a window where access is too open. */
278
279         if (mode != MODE_INVALID)
280                 if (chmod(path, mode) < 0)
281                         return -errno;
282
283         if (uid != UID_INVALID || gid != GID_INVALID)
284                 if (chown(path, uid, gid) < 0)
285                         return -errno;
286
287         return 0;
288 }
289
290 int fchmod_umask(int fd, mode_t m) {
291         mode_t u;
292         int r;
293
294         u = umask(0777);
295         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
296         umask(u);
297
298         return r;
299 }
300
301 int fd_warn_permissions(const char *path, int fd) {
302         struct stat st;
303
304         if (fstat(fd, &st) < 0)
305                 return -errno;
306
307         if (st.st_mode & 0111)
308                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
309
310         if (st.st_mode & 0002)
311                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
312
313         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
314                 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
315
316         return 0;
317 }
318
319 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
320         _cleanup_close_ int fd;
321         int r;
322
323         assert(path);
324
325         if (parents)
326                 mkdir_parents(path, 0755);
327
328         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY,
329                         (mode == 0 || mode == MODE_INVALID) ? 0644 : mode);
330         if (fd < 0)
331                 return -errno;
332
333         if (mode != MODE_INVALID) {
334                 r = fchmod(fd, mode);
335                 if (r < 0)
336                         return -errno;
337         }
338
339         if (uid != UID_INVALID || gid != GID_INVALID) {
340                 r = fchown(fd, uid, gid);
341                 if (r < 0)
342                         return -errno;
343         }
344
345         if (stamp != USEC_INFINITY) {
346                 struct timespec ts[2];
347
348                 timespec_store(&ts[0], stamp);
349                 ts[1] = ts[0];
350                 r = futimens(fd, ts);
351         } else
352                 r = futimens(fd, NULL);
353         if (r < 0)
354                 return -errno;
355
356         return 0;
357 }
358
359 int touch(const char *path) {
360         return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
361 }
362
363 #if 0 /// UNNEEDED by elogind
364 int symlink_idempotent(const char *from, const char *to) {
365         _cleanup_free_ char *p = NULL;
366         int r;
367
368         assert(from);
369         assert(to);
370
371         if (symlink(from, to) < 0) {
372                 if (errno != EEXIST)
373                         return -errno;
374
375                 r = readlink_malloc(to, &p);
376                 if (r < 0)
377                         return r;
378
379                 if (!streq(p, from))
380                         return -EINVAL;
381         }
382
383         return 0;
384 }
385
386 int symlink_atomic(const char *from, const char *to) {
387         _cleanup_free_ char *t = NULL;
388         int r;
389
390         assert(from);
391         assert(to);
392
393         r = tempfn_random(to, NULL, &t);
394         if (r < 0)
395                 return r;
396
397         if (symlink(from, t) < 0)
398                 return -errno;
399
400         if (rename(t, to) < 0) {
401                 unlink_noerrno(t);
402                 return -errno;
403         }
404
405         return 0;
406 }
407
408 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
409         _cleanup_free_ char *t = NULL;
410         int r;
411
412         assert(path);
413
414         r = tempfn_random(path, NULL, &t);
415         if (r < 0)
416                 return r;
417
418         if (mknod(t, mode, dev) < 0)
419                 return -errno;
420
421         if (rename(t, path) < 0) {
422                 unlink_noerrno(t);
423                 return -errno;
424         }
425
426         return 0;
427 }
428
429 int mkfifo_atomic(const char *path, mode_t mode) {
430         _cleanup_free_ char *t = NULL;
431         int r;
432
433         assert(path);
434
435         r = tempfn_random(path, NULL, &t);
436         if (r < 0)
437                 return r;
438
439         if (mkfifo(t, mode) < 0)
440                 return -errno;
441
442         if (rename(t, path) < 0) {
443                 unlink_noerrno(t);
444                 return -errno;
445         }
446
447         return 0;
448 }
449 #endif // 0
450
451 int get_files_in_directory(const char *path, char ***list) {
452         _cleanup_closedir_ DIR *d = NULL;
453         size_t bufsize = 0, n = 0;
454         _cleanup_strv_free_ char **l = NULL;
455
456         assert(path);
457
458         /* Returns all files in a directory in *list, and the number
459          * of files as return value. If list is NULL returns only the
460          * number. */
461
462         d = opendir(path);
463         if (!d)
464                 return -errno;
465
466         for (;;) {
467                 struct dirent *de;
468
469                 errno = 0;
470                 de = readdir(d);
471                 if (!de && errno > 0)
472                         return -errno;
473                 if (!de)
474                         break;
475
476                 dirent_ensure_type(d, de);
477
478                 if (!dirent_is_file(de))
479                         continue;
480
481                 if (list) {
482                         /* one extra slot is needed for the terminating NULL */
483                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
484                                 return -ENOMEM;
485
486                         l[n] = strdup(de->d_name);
487                         if (!l[n])
488                                 return -ENOMEM;
489
490                         l[++n] = NULL;
491                 } else
492                         n++;
493         }
494
495         if (list) {
496                 *list = l;
497                 l = NULL; /* avoid freeing */
498         }
499
500         return n;
501 }
502
503 #if 0 /// UNNEEDED by elogind
504 static int getenv_tmp_dir(const char **ret_path) {
505         const char *n;
506         int r, ret = 0;
507
508         assert(ret_path);
509
510         /* We use the same order of environment variables python uses in tempfile.gettempdir():
511          * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
512         FOREACH_STRING(n, "TMPDIR", "TEMP", "TMP") {
513                 const char *e;
514
515                 e = secure_getenv(n);
516                 if (!e)
517                         continue;
518                 if (!path_is_absolute(e)) {
519                         r = -ENOTDIR;
520                         goto next;
521                 }
522                 if (!path_is_safe(e)) {
523                         r = -EPERM;
524                         goto next;
525                 }
526
527                 r = is_dir(e, true);
528                 if (r < 0)
529                         goto next;
530                 if (r == 0) {
531                         r = -ENOTDIR;
532                         goto next;
533                 }
534
535                 *ret_path = e;
536                 return 1;
537
538         next:
539                 /* Remember first error, to make this more debuggable */
540                 if (ret >= 0)
541                         ret = r;
542         }
543
544         if (ret < 0)
545                 return ret;
546
547         *ret_path = NULL;
548         return ret;
549 }
550
551 static int tmp_dir_internal(const char *def, const char **ret) {
552         const char *e;
553         int r, k;
554
555         assert(def);
556         assert(ret);
557
558         r = getenv_tmp_dir(&e);
559         if (r > 0) {
560                 *ret = e;
561                 return 0;
562         }
563
564         k = is_dir(def, true);
565         if (k == 0)
566                 k = -ENOTDIR;
567         if (k < 0)
568                 return r < 0 ? r : k;
569
570         *ret = def;
571         return 0;
572 }
573
574 int var_tmp_dir(const char **ret) {
575
576         /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
577          * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
578          * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
579          * making it a variable that overrides all temporary file storage locations. */
580
581         return tmp_dir_internal("/var/tmp", ret);
582 }
583
584 int tmp_dir(const char **ret) {
585
586         /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
587          * backed by an in-memory file system: /tmp. */
588
589         return tmp_dir_internal("/tmp", ret);
590 }
591
592 int inotify_add_watch_fd(int fd, int what, uint32_t mask) {
593         char path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
594         int r;
595
596         /* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
597         xsprintf(path, "/proc/self/fd/%i", what);
598
599         r = inotify_add_watch(fd, path, mask);
600         if (r < 0)
601                 return -errno;
602
603         return r;
604 }
605 #endif // 0
606
607 int chase_symlinks(const char *path, const char *_root, char **ret) {
608         _cleanup_free_ char *buffer = NULL, *done = NULL, *root = NULL;
609         _cleanup_close_ int fd = -1;
610         unsigned max_follow = 32; /* how many symlinks to follow before giving up and returning ELOOP */
611         char *todo;
612         int r;
613
614         assert(path);
615
616         /* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
617          * symlinks relative to a root directory, instead of the root of the host.
618          *
619          * Note that "root" matters only if we encounter an absolute symlink, it's unused otherwise. Most importantly
620          * this means the path parameter passed in is not prefixed by it.
621          *
622          * Algorithmically this operates on two path buffers: "done" are the components of the path we already
623          * processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
624          * process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
625          * each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
626          * slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
627          * at a minimum. */
628
629         r = path_make_absolute_cwd(path, &buffer);
630         if (r < 0)
631                 return r;
632
633         if (_root) {
634                 r = path_make_absolute_cwd(_root, &root);
635                 if (r < 0)
636                         return r;
637         }
638
639         fd = open("/", O_CLOEXEC|O_NOFOLLOW|O_PATH);
640         if (fd < 0)
641                 return -errno;
642
643         todo = buffer;
644         for (;;) {
645                 _cleanup_free_ char *first = NULL;
646                 _cleanup_close_ int child = -1;
647                 struct stat st;
648                 size_t n, m;
649
650                 /* Determine length of first component in the path */
651                 n = strspn(todo, "/");                  /* The slashes */
652                 m = n + strcspn(todo + n, "/");         /* The entire length of the component */
653
654                 /* Extract the first component. */
655                 first = strndup(todo, m);
656                 if (!first)
657                         return -ENOMEM;
658
659                 todo += m;
660
661                 /* Just a single slash? Then we reached the end. */
662                 if (isempty(first) || path_equal(first, "/"))
663                         break;
664
665                 /* Just a dot? Then let's eat this up. */
666                 if (path_equal(first, "/."))
667                         continue;
668
669                 /* Two dots? Then chop off the last bit of what we already found out. */
670                 if (path_equal(first, "/..")) {
671                         _cleanup_free_ char *parent = NULL;
672                         int fd_parent = -1;
673
674                         if (isempty(done) || path_equal(done, "/"))
675                                 return -EINVAL;
676
677                         parent = dirname_malloc(done);
678                         if (!parent)
679                                 return -ENOMEM;
680
681                         /* Don't allow this to leave the root dir */
682                         if (root &&
683                             path_startswith(done, root) &&
684                             !path_startswith(parent, root))
685                                 return -EINVAL;
686
687                         free(done);
688                         done = parent;
689                         parent = NULL;
690
691                         fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
692                         if (fd_parent < 0)
693                                 return -errno;
694
695                         safe_close(fd);
696                         fd = fd_parent;
697
698                         continue;
699                 }
700
701                 /* Otherwise let's see what this is. */
702                 child = openat(fd, first + n, O_CLOEXEC|O_NOFOLLOW|O_PATH);
703                 if (child < 0)
704                         return -errno;
705
706                 if (fstat(child, &st) < 0)
707                         return -errno;
708
709                 if (S_ISLNK(st.st_mode)) {
710                         _cleanup_free_ char *destination = NULL;
711
712                         /* This is a symlink, in this case read the destination. But let's make sure we don't follow
713                          * symlinks without bounds. */
714                         if (--max_follow <= 0)
715                                 return -ELOOP;
716
717                         r = readlinkat_malloc(fd, first + n, &destination);
718                         if (r < 0)
719                                 return r;
720                         if (isempty(destination))
721                                 return -EINVAL;
722
723                         if (path_is_absolute(destination)) {
724
725                                 /* An absolute destination. Start the loop from the beginning, but use the root
726                                  * directory as base. */
727
728                                 safe_close(fd);
729                                 fd = open(root ?: "/", O_CLOEXEC|O_NOFOLLOW|O_PATH);
730                                 if (fd < 0)
731                                         return -errno;
732
733                                 free(buffer);
734                                 buffer = destination;
735                                 destination = NULL;
736
737                                 todo = buffer;
738                                 free(done);
739
740                                 /* Note that we do not revalidate the root, we take it as is. */
741                                 if (isempty(root))
742                                         done = NULL;
743                                 else {
744                                         done = strdup(root);
745                                         if (!done)
746                                                 return -ENOMEM;
747                                 }
748
749                         } else {
750                                 char *joined;
751
752                                 /* A relative destination. If so, this is what we'll prefix what's left to do with what
753                                  * we just read, and start the loop again, but remain in the current directory. */
754
755                                 joined = strjoin("/", destination, todo, NULL);
756                                 if (!joined)
757                                         return -ENOMEM;
758
759                                 free(buffer);
760                                 todo = buffer = joined;
761                         }
762
763                         continue;
764                 }
765
766                 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
767                 if (!done) {
768                         done = first;
769                         first = NULL;
770                 } else {
771                         if (!strextend(&done, first, NULL))
772                                 return -ENOMEM;
773                 }
774
775                 /* And iterate again, but go one directory further down. */
776                 safe_close(fd);
777                 fd = child;
778                 child = -1;
779         }
780
781         if (!done) {
782                 /* Special case, turn the empty string into "/", to indicate the root directory. */
783                 done = strdup("/");
784                 if (!done)
785                         return -ENOMEM;
786         }
787
788         *ret = done;
789         done = NULL;
790
791         return 0;
792 }