chiark / gitweb /
6308216deeaab1129dc04b54a9baa91f121540ce
[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 <errno.h>
21 #include <stddef.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/stat.h>
26 #include <time.h>
27 #include <unistd.h>
28
29 #include "alloc-util.h"
30 #include "dirent-util.h"
31 #include "fd-util.h"
32 #include "fileio.h"
33 #include "fs-util.h"
34 //#include "log.h"
35 //#include "macro.h"
36 //#include "missing.h"
37 #include "mkdir.h"
38 #include "parse-util.h"
39 #include "path-util.h"
40 #include "stat-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, const char *root, char **ret) {
229         char *t, *s;
230         int r;
231
232         assert(p);
233         assert(ret);
234
235         r = readlink_and_make_absolute(p, &t);
236         if (r < 0)
237                 return r;
238
239         r = chase_symlinks(t, root, 0, &s);
240         if (r < 0)
241                 /* If we can't follow up, then let's return the original string, slightly cleaned up. */
242                 *ret = path_kill_slashes(t);
243         else {
244                 *ret = s;
245                 free(t);
246         }
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         struct dirent *de;
454         size_t bufsize = 0, n = 0;
455         _cleanup_strv_free_ char **l = NULL;
456
457         assert(path);
458
459         /* Returns all files in a directory in *list, and the number
460          * of files as return value. If list is NULL returns only the
461          * number. */
462
463         d = opendir(path);
464         if (!d)
465                 return -errno;
466
467         FOREACH_DIRENT_ALL(de, d, return -errno) {
468                 dirent_ensure_type(d, de);
469
470                 if (!dirent_is_file(de))
471                         continue;
472
473                 if (list) {
474                         /* one extra slot is needed for the terminating NULL */
475                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
476                                 return -ENOMEM;
477
478                         l[n] = strdup(de->d_name);
479                         if (!l[n])
480                                 return -ENOMEM;
481
482                         l[++n] = NULL;
483                 } else
484                         n++;
485         }
486
487         if (list) {
488                 *list = l;
489                 l = NULL; /* avoid freeing */
490         }
491
492         return n;
493 }
494
495 static int getenv_tmp_dir(const char **ret_path) {
496         const char *n;
497         int r, ret = 0;
498
499         assert(ret_path);
500
501         /* We use the same order of environment variables python uses in tempfile.gettempdir():
502          * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
503         FOREACH_STRING(n, "TMPDIR", "TEMP", "TMP") {
504                 const char *e;
505
506                 e = secure_getenv(n);
507                 if (!e)
508                         continue;
509                 if (!path_is_absolute(e)) {
510                         r = -ENOTDIR;
511                         goto next;
512                 }
513                 if (!path_is_safe(e)) {
514                         r = -EPERM;
515                         goto next;
516                 }
517
518                 r = is_dir(e, true);
519                 if (r < 0)
520                         goto next;
521                 if (r == 0) {
522                         r = -ENOTDIR;
523                         goto next;
524                 }
525
526                 *ret_path = e;
527                 return 1;
528
529         next:
530                 /* Remember first error, to make this more debuggable */
531                 if (ret >= 0)
532                         ret = r;
533         }
534
535         if (ret < 0)
536                 return ret;
537
538         *ret_path = NULL;
539         return ret;
540 }
541
542 static int tmp_dir_internal(const char *def, const char **ret) {
543         const char *e;
544         int r, k;
545
546         assert(def);
547         assert(ret);
548
549         r = getenv_tmp_dir(&e);
550         if (r > 0) {
551                 *ret = e;
552                 return 0;
553         }
554
555         k = is_dir(def, true);
556         if (k == 0)
557                 k = -ENOTDIR;
558         if (k < 0)
559                 return r < 0 ? r : k;
560
561         *ret = def;
562         return 0;
563 }
564
565 #if 0 /// UNNEEDED by elogind
566 int var_tmp_dir(const char **ret) {
567
568         /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
569          * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
570          * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
571          * making it a variable that overrides all temporary file storage locations. */
572
573         return tmp_dir_internal("/var/tmp", ret);
574 }
575 #endif // 0
576
577 int tmp_dir(const char **ret) {
578
579         /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
580          * backed by an in-memory file system: /tmp. */
581
582         return tmp_dir_internal("/tmp", ret);
583 }
584
585 #if 0 /// UNNEEDED by elogind
586 int inotify_add_watch_fd(int fd, int what, uint32_t mask) {
587         char path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(int) + 1];
588         int r;
589
590         /* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
591         xsprintf(path, "/proc/self/fd/%i", what);
592
593         r = inotify_add_watch(fd, path, mask);
594         if (r < 0)
595                 return -errno;
596
597         return r;
598 }
599 #endif // 0
600
601 int chase_symlinks(const char *path, const char *original_root, unsigned flags, char **ret) {
602         _cleanup_free_ char *buffer = NULL, *done = NULL, *root = NULL;
603         _cleanup_close_ int fd = -1;
604         unsigned max_follow = 32; /* how many symlinks to follow before giving up and returning ELOOP */
605         bool exists = true;
606         char *todo;
607         int r;
608
609         assert(path);
610
611         /* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
612          * symlinks relative to a root directory, instead of the root of the host.
613          *
614          * Note that "root" primarily matters if we encounter an absolute symlink. It is also used when following
615          * relative symlinks to ensure they cannot be used to "escape" the root directory. The path parameter passed is
616          * assumed to be already prefixed by it, except if the CHASE_PREFIX_ROOT flag is set, in which case it is first
617          * prefixed accordingly.
618          *
619          * Algorithmically this operates on two path buffers: "done" are the components of the path we already
620          * processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
621          * process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
622          * each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
623          * slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
624          * at a minimum.
625          *
626          * Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute path you got
627          * as-is: fully qualified and relative to your host's root. Optionally, specify the root parameter to tell this
628          * function what to do when encountering a symlink with an absolute path as directory: prefix it by the
629          * specified path.
630          *
631          * Note: there's also chase_symlinks_prefix() (see below), which as first step prefixes the passed path by the
632          * passed root. */
633
634         if (original_root) {
635                 r = path_make_absolute_cwd(original_root, &root);
636                 if (r < 0)
637                         return r;
638
639                 if (flags & CHASE_PREFIX_ROOT)
640                         path = prefix_roota(root, path);
641         }
642
643         r = path_make_absolute_cwd(path, &buffer);
644         if (r < 0)
645                 return r;
646
647         fd = open("/", O_CLOEXEC|O_NOFOLLOW|O_PATH);
648         if (fd < 0)
649                 return -errno;
650
651         todo = buffer;
652         for (;;) {
653                 _cleanup_free_ char *first = NULL;
654                 _cleanup_close_ int child = -1;
655                 struct stat st;
656                 size_t n, m;
657
658                 /* Determine length of first component in the path */
659                 n = strspn(todo, "/");                  /* The slashes */
660                 m = n + strcspn(todo + n, "/");         /* The entire length of the component */
661
662                 /* Extract the first component. */
663                 first = strndup(todo, m);
664                 if (!first)
665                         return -ENOMEM;
666
667                 todo += m;
668
669                 /* Just a single slash? Then we reached the end. */
670                 if (isempty(first) || path_equal(first, "/"))
671                         break;
672
673                 /* Just a dot? Then let's eat this up. */
674                 if (path_equal(first, "/."))
675                         continue;
676
677                 /* Two dots? Then chop off the last bit of what we already found out. */
678                 if (path_equal(first, "/..")) {
679                         _cleanup_free_ char *parent = NULL;
680                         int fd_parent = -1;
681
682                         /* If we already are at the top, then going up will not change anything. This is in-line with
683                          * how the kernel handles this. */
684                         if (isempty(done) || path_equal(done, "/"))
685                                 continue;
686
687                         parent = dirname_malloc(done);
688                         if (!parent)
689                                 return -ENOMEM;
690
691                         /* Don't allow this to leave the root dir.  */
692                         if (root &&
693                             path_startswith(done, root) &&
694                             !path_startswith(parent, root))
695                                 continue;
696
697                         free_and_replace(done, parent);
698
699                         fd_parent = openat(fd, "..", O_CLOEXEC|O_NOFOLLOW|O_PATH);
700                         if (fd_parent < 0)
701                                 return -errno;
702
703                         safe_close(fd);
704                         fd = fd_parent;
705
706                         continue;
707                 }
708
709                 /* Otherwise let's see what this is. */
710                 child = openat(fd, first + n, O_CLOEXEC|O_NOFOLLOW|O_PATH);
711                 if (child < 0) {
712
713                         if (errno == ENOENT &&
714                             (flags & CHASE_NONEXISTENT) &&
715                             (isempty(todo) || path_is_safe(todo))) {
716
717                                 /* If CHASE_NONEXISTENT is set, and the path does not exist, then that's OK, return
718                                  * what we got so far. But don't allow this if the remaining path contains "../ or "./"
719                                  * or something else weird. */
720
721                                 if (!strextend(&done, first, todo, NULL))
722                                         return -ENOMEM;
723
724                                 exists = false;
725                                 break;
726                         }
727
728                         return -errno;
729                 }
730
731                 if (fstat(child, &st) < 0)
732                         return -errno;
733
734                 if (S_ISLNK(st.st_mode)) {
735                         char *joined;
736
737                         _cleanup_free_ char *destination = NULL;
738
739                         /* This is a symlink, in this case read the destination. But let's make sure we don't follow
740                          * symlinks without bounds. */
741                         if (--max_follow <= 0)
742                                 return -ELOOP;
743
744                         r = readlinkat_malloc(fd, first + n, &destination);
745                         if (r < 0)
746                                 return r;
747                         if (isempty(destination))
748                                 return -EINVAL;
749
750                         if (path_is_absolute(destination)) {
751
752                                 /* An absolute destination. Start the loop from the beginning, but use the root
753                                  * directory as base. */
754
755                                 safe_close(fd);
756                                 fd = open(root ?: "/", O_CLOEXEC|O_NOFOLLOW|O_PATH);
757                                 if (fd < 0)
758                                         return -errno;
759
760                                 free(done);
761
762                                 /* Note that we do not revalidate the root, we take it as is. */
763                                 if (isempty(root))
764                                         done = NULL;
765                                 else {
766                                         done = strdup(root);
767                                         if (!done)
768                                                 return -ENOMEM;
769                                 }
770
771                         }
772
773                         /* Prefix what's left to do with what we just read, and start the loop again,
774                          * but remain in the current directory. */
775
776                         joined = strjoin("/", destination, todo);
777                         if (!joined)
778                                 return -ENOMEM;
779
780                         free(buffer);
781                         todo = buffer = joined;
782
783                         continue;
784                 }
785
786                 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
787                 if (!done) {
788                         done = first;
789                         first = NULL;
790                 } else {
791                         if (!strextend(&done, first, NULL))
792                                 return -ENOMEM;
793                 }
794
795                 /* And iterate again, but go one directory further down. */
796                 safe_close(fd);
797                 fd = child;
798                 child = -1;
799         }
800
801         if (!done) {
802                 /* Special case, turn the empty string into "/", to indicate the root directory. */
803                 done = strdup("/");
804                 if (!done)
805                         return -ENOMEM;
806         }
807
808         *ret = done;
809         done = NULL;
810
811         return exists;
812 }