1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <stddef.h>
5 #include <stdlib.h>
6 #include <linux/falloc.h>
7 #include <linux/magic.h>
8 #include <unistd.h>
9 
10 #include "alloc-util.h"
11 #include "dirent-util.h"
12 #include "fd-util.h"
13 #include "fileio.h"
14 #include "fs-util.h"
15 #include "hostname-util.h"
16 #include "log.h"
17 #include "macro.h"
18 #include "missing_fcntl.h"
19 #include "missing_fs.h"
20 #include "missing_syscall.h"
21 #include "mkdir.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "random-util.h"
26 #include "ratelimit.h"
27 #include "stat-util.h"
28 #include "stdio-util.h"
29 #include "string-util.h"
30 #include "strv.h"
31 #include "time-util.h"
32 #include "tmpfile-util.h"
33 #include "umask-util.h"
34 #include "user-util.h"
35 #include "util.h"
36 
unlink_noerrno(const char * path)37 int unlink_noerrno(const char *path) {
38         PROTECT_ERRNO;
39         return RET_NERRNO(unlink(path));
40 }
41 
rmdir_parents(const char * path,const char * stop)42 int rmdir_parents(const char *path, const char *stop) {
43         char *p;
44         int r;
45 
46         assert(path);
47         assert(stop);
48 
49         if (!path_is_safe(path))
50                 return -EINVAL;
51 
52         if (!path_is_safe(stop))
53                 return -EINVAL;
54 
55         p = strdupa_safe(path);
56 
57         for (;;) {
58                 char *slash = NULL;
59 
60                 /* skip the last component. */
61                 r = path_find_last_component(p, /* accept_dot_dot= */ false, (const char **) &slash, NULL);
62                 if (r <= 0)
63                         return r;
64                 if (slash == p)
65                         return 0;
66 
67                 assert(*slash == '/');
68                 *slash = '\0';
69 
70                 if (path_startswith_full(stop, p, /* accept_dot_dot= */ false))
71                         return 0;
72 
73                 if (rmdir(p) < 0 && errno != ENOENT)
74                         return -errno;
75         }
76 }
77 
rename_noreplace(int olddirfd,const char * oldpath,int newdirfd,const char * newpath)78 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
79         int r;
80 
81         /* Try the ideal approach first */
82         if (renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE) >= 0)
83                 return 0;
84 
85         /* renameat2() exists since Linux 3.15, btrfs and FAT added support for it later. If it is not implemented,
86          * fall back to a different method. */
87         if (!ERRNO_IS_NOT_SUPPORTED(errno) && errno != EINVAL)
88                 return -errno;
89 
90         /* Let's try to use linkat()+unlinkat() as fallback. This doesn't work on directories and on some file systems
91          * that do not support hard links (such as FAT, most prominently), but for files it's pretty close to what we
92          * want — though not atomic (i.e. for a short period both the new and the old filename will exist). */
93         if (linkat(olddirfd, oldpath, newdirfd, newpath, 0) >= 0) {
94 
95                 r = RET_NERRNO(unlinkat(olddirfd, oldpath, 0));
96                 if (r < 0) {
97                         (void) unlinkat(newdirfd, newpath, 0);
98                         return r;
99                 }
100 
101                 return 0;
102         }
103 
104         if (!ERRNO_IS_NOT_SUPPORTED(errno) && !IN_SET(errno, EINVAL, EPERM)) /* FAT returns EPERM on link()… */
105                 return -errno;
106 
107         /* OK, neither RENAME_NOREPLACE nor linkat()+unlinkat() worked. Let's then fall back to the racy TOCTOU
108          * vulnerable accessat(F_OK) check followed by classic, replacing renameat(), we have nothing better. */
109 
110         if (faccessat(newdirfd, newpath, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
111                 return -EEXIST;
112         if (errno != ENOENT)
113                 return -errno;
114 
115         return RET_NERRNO(renameat(olddirfd, oldpath, newdirfd, newpath));
116 }
117 
readlinkat_malloc(int fd,const char * p,char ** ret)118 int readlinkat_malloc(int fd, const char *p, char **ret) {
119         size_t l = PATH_MAX;
120 
121         assert(p);
122 
123         for (;;) {
124                 _cleanup_free_ char *c = NULL;
125                 ssize_t n;
126 
127                 c = new(char, l+1);
128                 if (!c)
129                         return -ENOMEM;
130 
131                 n = readlinkat(fd, p, c, l);
132                 if (n < 0)
133                         return -errno;
134 
135                 if ((size_t) n < l) {
136                         c[n] = 0;
137 
138                         if (ret)
139                                 *ret = TAKE_PTR(c);
140 
141                         return 0;
142                 }
143 
144                 if (l > (SSIZE_MAX-1)/2) /* readlinkat() returns an ssize_t, and we want an extra byte for a
145                                           * trailing NUL, hence do an overflow check relative to SSIZE_MAX-1
146                                           * here */
147                         return -EFBIG;
148 
149                 l *= 2;
150         }
151 }
152 
readlink_malloc(const char * p,char ** ret)153 int readlink_malloc(const char *p, char **ret) {
154         return readlinkat_malloc(AT_FDCWD, p, ret);
155 }
156 
readlink_value(const char * p,char ** ret)157 int readlink_value(const char *p, char **ret) {
158         _cleanup_free_ char *link = NULL, *name = NULL;
159         int r;
160 
161         assert(p);
162         assert(ret);
163 
164         r = readlink_malloc(p, &link);
165         if (r < 0)
166                 return r;
167 
168         r = path_extract_filename(link, &name);
169         if (r < 0)
170                 return r;
171         if (r == O_DIRECTORY)
172                 return -EINVAL;
173 
174         *ret = TAKE_PTR(name);
175         return 0;
176 }
177 
readlink_and_make_absolute(const char * p,char ** r)178 int readlink_and_make_absolute(const char *p, char **r) {
179         _cleanup_free_ char *target = NULL;
180         char *k;
181         int j;
182 
183         assert(p);
184         assert(r);
185 
186         j = readlink_malloc(p, &target);
187         if (j < 0)
188                 return j;
189 
190         k = file_in_same_dir(p, target);
191         if (!k)
192                 return -ENOMEM;
193 
194         *r = k;
195         return 0;
196 }
197 
chmod_and_chown(const char * path,mode_t mode,uid_t uid,gid_t gid)198 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
199         _cleanup_close_ int fd = -1;
200 
201         assert(path);
202 
203         fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW); /* Let's acquire an O_PATH fd, as precaution to change
204                                                        * mode/owner on the same file */
205         if (fd < 0)
206                 return -errno;
207 
208         return fchmod_and_chown(fd, mode, uid, gid);
209 }
210 
fchmod_and_chown_with_fallback(int fd,const char * path,mode_t mode,uid_t uid,gid_t gid)211 int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
212         bool do_chown, do_chmod;
213         struct stat st;
214         int r;
215 
216         /* Change ownership and access mode of the specified fd. Tries to do so safely, ensuring that at no
217          * point in time the access mode is above the old access mode under the old ownership or the new
218          * access mode under the new ownership. Note: this call tries hard to leave the access mode
219          * unaffected if the uid/gid is changed, i.e. it undoes implicit suid/sgid dropping the kernel does
220          * on chown().
221          *
222          * This call is happy with O_PATH fds.
223          *
224          * If path is given, allow a fallback path which does not use /proc/self/fd/. On any normal system
225          * /proc will be mounted, but in certain improperly assembled environments it might not be. This is
226          * less secure (potential TOCTOU), so should only be used after consideration. */
227 
228         if (fstat(fd, &st) < 0)
229                 return -errno;
230 
231         do_chown =
232                 (uid != UID_INVALID && st.st_uid != uid) ||
233                 (gid != GID_INVALID && st.st_gid != gid);
234 
235         do_chmod =
236                 !S_ISLNK(st.st_mode) && /* chmod is not defined on symlinks */
237                 ((mode != MODE_INVALID && ((st.st_mode ^ mode) & 07777) != 0) ||
238                  do_chown); /* If we change ownership, make sure we reset the mode afterwards, since chown()
239                              * modifies the access mode too */
240 
241         if (mode == MODE_INVALID)
242                 mode = st.st_mode; /* If we only shall do a chown(), save original mode, since chown() might break it. */
243         else if ((mode & S_IFMT) != 0 && ((mode ^ st.st_mode) & S_IFMT) != 0)
244                 return -EINVAL; /* insist on the right file type if it was specified */
245 
246         if (do_chown && do_chmod) {
247                 mode_t minimal = st.st_mode & mode; /* the subset of the old and the new mask */
248 
249                 if (((minimal ^ st.st_mode) & 07777) != 0) {
250                         r = fchmod_opath(fd, minimal & 07777);
251                         if (r < 0) {
252                                 if (!path || r != -ENOSYS)
253                                         return r;
254 
255                                 /* Fallback path which doesn't use /proc/self/fd/. */
256                                 if (chmod(path, minimal & 07777) < 0)
257                                         return -errno;
258                         }
259                 }
260         }
261 
262         if (do_chown)
263                 if (fchownat(fd, "", uid, gid, AT_EMPTY_PATH) < 0)
264                         return -errno;
265 
266         if (do_chmod) {
267                 r = fchmod_opath(fd, mode & 07777);
268                 if (r < 0) {
269                         if (!path || r != -ENOSYS)
270                                 return r;
271 
272                         /* Fallback path which doesn't use /proc/self/fd/. */
273                         if (chmod(path, mode & 07777) < 0)
274                                 return -errno;
275                 }
276         }
277 
278         return do_chown || do_chmod;
279 }
280 
fchmod_umask(int fd,mode_t m)281 int fchmod_umask(int fd, mode_t m) {
282         _cleanup_umask_ mode_t u = umask(0777);
283 
284         return RET_NERRNO(fchmod(fd, m & (~u)));
285 }
286 
fchmod_opath(int fd,mode_t m)287 int fchmod_opath(int fd, mode_t m) {
288         /* This function operates also on fd that might have been opened with
289          * O_PATH. Indeed fchmodat() doesn't have the AT_EMPTY_PATH flag like
290          * fchownat() does. */
291 
292         if (chmod(FORMAT_PROC_FD_PATH(fd), m) < 0) {
293                 if (errno != ENOENT)
294                         return -errno;
295 
296                 if (proc_mounted() == 0)
297                         return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
298 
299                 return -ENOENT;
300         }
301 
302         return 0;
303 }
304 
futimens_opath(int fd,const struct timespec ts[2])305 int futimens_opath(int fd, const struct timespec ts[2]) {
306         /* Similar to fchmod_path() but for futimens() */
307 
308         if (utimensat(AT_FDCWD, FORMAT_PROC_FD_PATH(fd), ts, 0) < 0) {
309                 if (errno != ENOENT)
310                         return -errno;
311 
312                 if (proc_mounted() == 0)
313                         return -ENOSYS; /* if we have no /proc/, the concept is not implementable */
314 
315                 return -ENOENT;
316         }
317 
318         return 0;
319 }
320 
stat_warn_permissions(const char * path,const struct stat * st)321 int stat_warn_permissions(const char *path, const struct stat *st) {
322         assert(path);
323         assert(st);
324 
325         /* Don't complain if we are reading something that is not a file, for example /dev/null */
326         if (!S_ISREG(st->st_mode))
327                 return 0;
328 
329         if (st->st_mode & 0111)
330                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
331 
332         if (st->st_mode & 0002)
333                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
334 
335         if (getpid_cached() == 1 && (st->st_mode & 0044) != 0044)
336                 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);
337 
338         return 0;
339 }
340 
fd_warn_permissions(const char * path,int fd)341 int fd_warn_permissions(const char *path, int fd) {
342         struct stat st;
343 
344         assert(path);
345         assert(fd >= 0);
346 
347         if (fstat(fd, &st) < 0)
348                 return -errno;
349 
350         return stat_warn_permissions(path, &st);
351 }
352 
touch_file(const char * path,bool parents,usec_t stamp,uid_t uid,gid_t gid,mode_t mode)353 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
354         _cleanup_close_ int fd = -1;
355         int r, ret;
356 
357         assert(path);
358 
359         /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
360          * itself which is updated, not its target
361          *
362          * Returns the first error we encounter, but tries to apply as much as possible. */
363 
364         if (parents)
365                 (void) mkdir_parents(path, 0755);
366 
367         /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
368          * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
369          * won't trigger any driver magic or so. */
370         fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
371         if (fd < 0) {
372                 if (errno != ENOENT)
373                         return -errno;
374 
375                 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
376                  * here, and nothing else */
377                 fd = open(path, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, IN_SET(mode, 0, MODE_INVALID) ? 0644 : mode);
378                 if (fd < 0)
379                         return -errno;
380         }
381 
382         /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
383          * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object — which is
384          * something fchown(), fchmod(), futimensat() don't allow. */
385         ret = fchmod_and_chown(fd, mode, uid, gid);
386 
387         if (stamp != USEC_INFINITY) {
388                 struct timespec ts[2];
389 
390                 timespec_store(&ts[0], stamp);
391                 ts[1] = ts[0];
392                 r = futimens_opath(fd, ts);
393         } else
394                 r = futimens_opath(fd, NULL);
395         if (r < 0 && ret >= 0)
396                 return r;
397 
398         return ret;
399 }
400 
touch(const char * path)401 int touch(const char *path) {
402         return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
403 }
404 
symlink_idempotent(const char * from,const char * to,bool make_relative)405 int symlink_idempotent(const char *from, const char *to, bool make_relative) {
406         _cleanup_free_ char *relpath = NULL;
407         int r;
408 
409         assert(from);
410         assert(to);
411 
412         if (make_relative) {
413                 _cleanup_free_ char *parent = NULL;
414 
415                 r = path_extract_directory(to, &parent);
416                 if (r < 0)
417                         return r;
418 
419                 r = path_make_relative(parent, from, &relpath);
420                 if (r < 0)
421                         return r;
422 
423                 from = relpath;
424         }
425 
426         if (symlink(from, to) < 0) {
427                 _cleanup_free_ char *p = NULL;
428 
429                 if (errno != EEXIST)
430                         return -errno;
431 
432                 r = readlink_malloc(to, &p);
433                 if (r == -EINVAL) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
434                         return -EEXIST;
435                 if (r < 0) /* Any other error? In that case propagate it as is */
436                         return r;
437 
438                 if (!streq(p, from)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
439                         return -EEXIST;
440         }
441 
442         return 0;
443 }
444 
symlink_atomic(const char * from,const char * to)445 int symlink_atomic(const char *from, const char *to) {
446         _cleanup_free_ char *t = NULL;
447         int r;
448 
449         assert(from);
450         assert(to);
451 
452         r = tempfn_random(to, NULL, &t);
453         if (r < 0)
454                 return r;
455 
456         if (symlink(from, t) < 0)
457                 return -errno;
458 
459         if (rename(t, to) < 0) {
460                 unlink_noerrno(t);
461                 return -errno;
462         }
463 
464         return 0;
465 }
466 
mknod_atomic(const char * path,mode_t mode,dev_t dev)467 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
468         _cleanup_free_ char *t = NULL;
469         int r;
470 
471         assert(path);
472 
473         r = tempfn_random(path, NULL, &t);
474         if (r < 0)
475                 return r;
476 
477         if (mknod(t, mode, dev) < 0)
478                 return -errno;
479 
480         if (rename(t, path) < 0) {
481                 unlink_noerrno(t);
482                 return -errno;
483         }
484 
485         return 0;
486 }
487 
mkfifo_atomic(const char * path,mode_t mode)488 int mkfifo_atomic(const char *path, mode_t mode) {
489         _cleanup_free_ char *t = NULL;
490         int r;
491 
492         assert(path);
493 
494         r = tempfn_random(path, NULL, &t);
495         if (r < 0)
496                 return r;
497 
498         if (mkfifo(t, mode) < 0)
499                 return -errno;
500 
501         if (rename(t, path) < 0) {
502                 unlink_noerrno(t);
503                 return -errno;
504         }
505 
506         return 0;
507 }
508 
mkfifoat_atomic(int dirfd,const char * path,mode_t mode)509 int mkfifoat_atomic(int dirfd, const char *path, mode_t mode) {
510         _cleanup_free_ char *t = NULL;
511         int r;
512 
513         assert(path);
514 
515         if (path_is_absolute(path))
516                 return mkfifo_atomic(path, mode);
517 
518         /* We're only interested in the (random) filename.  */
519         r = tempfn_random_child("", NULL, &t);
520         if (r < 0)
521                 return r;
522 
523         if (mkfifoat(dirfd, t, mode) < 0)
524                 return -errno;
525 
526         if (renameat(dirfd, t, dirfd, path) < 0) {
527                 unlink_noerrno(t);
528                 return -errno;
529         }
530 
531         return 0;
532 }
533 
get_files_in_directory(const char * path,char *** list)534 int get_files_in_directory(const char *path, char ***list) {
535         _cleanup_strv_free_ char **l = NULL;
536         _cleanup_closedir_ DIR *d = NULL;
537         size_t n = 0;
538 
539         assert(path);
540 
541         /* Returns all files in a directory in *list, and the number
542          * of files as return value. If list is NULL returns only the
543          * number. */
544 
545         d = opendir(path);
546         if (!d)
547                 return -errno;
548 
549         FOREACH_DIRENT_ALL(de, d, return -errno) {
550                 if (!dirent_is_file(de))
551                         continue;
552 
553                 if (list) {
554                         /* one extra slot is needed for the terminating NULL */
555                         if (!GREEDY_REALLOC(l, n + 2))
556                                 return -ENOMEM;
557 
558                         l[n] = strdup(de->d_name);
559                         if (!l[n])
560                                 return -ENOMEM;
561 
562                         l[++n] = NULL;
563                 } else
564                         n++;
565         }
566 
567         if (list)
568                 *list = TAKE_PTR(l);
569 
570         return n;
571 }
572 
getenv_tmp_dir(const char ** ret_path)573 static int getenv_tmp_dir(const char **ret_path) {
574         int r, ret = 0;
575 
576         assert(ret_path);
577 
578         /* We use the same order of environment variables python uses in tempfile.gettempdir():
579          * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
580         FOREACH_STRING(n, "TMPDIR", "TEMP", "TMP") {
581                 const char *e;
582 
583                 e = secure_getenv(n);
584                 if (!e)
585                         continue;
586                 if (!path_is_absolute(e)) {
587                         r = -ENOTDIR;
588                         goto next;
589                 }
590                 if (!path_is_normalized(e)) {
591                         r = -EPERM;
592                         goto next;
593                 }
594 
595                 r = is_dir(e, true);
596                 if (r < 0)
597                         goto next;
598                 if (r == 0) {
599                         r = -ENOTDIR;
600                         goto next;
601                 }
602 
603                 *ret_path = e;
604                 return 1;
605 
606         next:
607                 /* Remember first error, to make this more debuggable */
608                 if (ret >= 0)
609                         ret = r;
610         }
611 
612         if (ret < 0)
613                 return ret;
614 
615         *ret_path = NULL;
616         return ret;
617 }
618 
tmp_dir_internal(const char * def,const char ** ret)619 static int tmp_dir_internal(const char *def, const char **ret) {
620         const char *e;
621         int r, k;
622 
623         assert(def);
624         assert(ret);
625 
626         r = getenv_tmp_dir(&e);
627         if (r > 0) {
628                 *ret = e;
629                 return 0;
630         }
631 
632         k = is_dir(def, true);
633         if (k == 0)
634                 k = -ENOTDIR;
635         if (k < 0)
636                 return r < 0 ? r : k;
637 
638         *ret = def;
639         return 0;
640 }
641 
var_tmp_dir(const char ** ret)642 int var_tmp_dir(const char **ret) {
643 
644         /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
645          * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
646          * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
647          * making it a variable that overrides all temporary file storage locations. */
648 
649         return tmp_dir_internal("/var/tmp", ret);
650 }
651 
tmp_dir(const char ** ret)652 int tmp_dir(const char **ret) {
653 
654         /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
655          * backed by an in-memory file system: /tmp. */
656 
657         return tmp_dir_internal("/tmp", ret);
658 }
659 
unlink_or_warn(const char * filename)660 int unlink_or_warn(const char *filename) {
661         if (unlink(filename) < 0 && errno != ENOENT)
662                 /* If the file doesn't exist and the fs simply was read-only (in which
663                  * case unlink() returns EROFS even if the file doesn't exist), don't
664                  * complain */
665                 if (errno != EROFS || access(filename, F_OK) >= 0)
666                         return log_error_errno(errno, "Failed to remove \"%s\": %m", filename);
667 
668         return 0;
669 }
670 
access_fd(int fd,int mode)671 int access_fd(int fd, int mode) {
672         /* Like access() but operates on an already open fd */
673 
674         if (access(FORMAT_PROC_FD_PATH(fd), mode) < 0) {
675                 if (errno != ENOENT)
676                         return -errno;
677 
678                 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's
679                  * make things debuggable and distinguish the two. */
680 
681                 if (proc_mounted() == 0)
682                         return -ENOSYS;  /* /proc is not available or not set up properly, we're most likely in some chroot
683                                           * environment. */
684 
685                 return -EBADF; /* The directory exists, hence it's the fd that doesn't. */
686         }
687 
688         return 0;
689 }
690 
unlink_tempfilep(char (* p)[])691 void unlink_tempfilep(char (*p)[]) {
692         /* If the file is created with mkstemp(), it will (almost always)
693          * change the suffix. Treat this as a sign that the file was
694          * successfully created. We ignore both the rare case where the
695          * original suffix is used and unlink failures. */
696         if (!endswith(*p, ".XXXXXX"))
697                 (void) unlink_noerrno(*p);
698 }
699 
unlinkat_deallocate(int fd,const char * name,UnlinkDeallocateFlags flags)700 int unlinkat_deallocate(int fd, const char *name, UnlinkDeallocateFlags flags) {
701         _cleanup_close_ int truncate_fd = -1;
702         struct stat st;
703         off_t l, bs;
704 
705         assert((flags & ~(UNLINK_REMOVEDIR|UNLINK_ERASE)) == 0);
706 
707         /* Operates like unlinkat() but also deallocates the file contents if it is a regular file and there's no other
708          * link to it. This is useful to ensure that other processes that might have the file open for reading won't be
709          * able to keep the data pinned on disk forever. This call is particular useful whenever we execute clean-up
710          * jobs ("vacuuming"), where we want to make sure the data is really gone and the disk space released and
711          * returned to the free pool.
712          *
713          * Deallocation is preferably done by FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE (��) if supported, which means
714          * the file won't change size. That's a good thing since we shouldn't needlessly trigger SIGBUS in other
715          * programs that have mmap()ed the file. (The assumption here is that changing file contents to all zeroes
716          * underneath those programs is the better choice than simply triggering SIGBUS in them which truncation does.)
717          * However if hole punching is not implemented in the kernel or file system we'll fall back to normal file
718          * truncation (��), as our goal of deallocating the data space trumps our goal of being nice to readers (��).
719          *
720          * Note that we attempt deallocation, but failure to succeed with that is not considered fatal, as long as the
721          * primary job – to delete the file – is accomplished. */
722 
723         if (!FLAGS_SET(flags, UNLINK_REMOVEDIR)) {
724                 truncate_fd = openat(fd, name, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
725                 if (truncate_fd < 0) {
726 
727                         /* If this failed because the file doesn't exist propagate the error right-away. Also,
728                          * AT_REMOVEDIR wasn't set, and we tried to open the file for writing, which means EISDIR is
729                          * returned when this is a directory but we are not supposed to delete those, hence propagate
730                          * the error right-away too. */
731                         if (IN_SET(errno, ENOENT, EISDIR))
732                                 return -errno;
733 
734                         if (errno != ELOOP) /* don't complain if this is a symlink */
735                                 log_debug_errno(errno, "Failed to open file '%s' for deallocation, ignoring: %m", name);
736                 }
737         }
738 
739         if (unlinkat(fd, name, FLAGS_SET(flags, UNLINK_REMOVEDIR) ? AT_REMOVEDIR : 0) < 0)
740                 return -errno;
741 
742         if (truncate_fd < 0) /* Don't have a file handle, can't do more ☹️ */
743                 return 0;
744 
745         if (fstat(truncate_fd, &st) < 0) {
746                 log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring: %m", name);
747                 return 0;
748         }
749 
750         if (!S_ISREG(st.st_mode))
751                 return 0;
752 
753         if (FLAGS_SET(flags, UNLINK_ERASE) && st.st_size > 0 && st.st_nlink == 0) {
754                 uint64_t left = st.st_size;
755                 char buffer[64 * 1024];
756 
757                 /* If erasing is requested, let's overwrite the file with random data once before deleting
758                  * it. This isn't going to give you shred(1) semantics, but hopefully should be good enough
759                  * for stuff backed by tmpfs at least.
760                  *
761                  * Note that we only erase like this if the link count of the file is zero. If it is higher it
762                  * is still linked by someone else and we'll leave it to them to remove it securely
763                  * eventually! */
764 
765                 random_bytes(buffer, sizeof(buffer));
766 
767                 while (left > 0) {
768                         ssize_t n;
769 
770                         n = write(truncate_fd, buffer, MIN(sizeof(buffer), left));
771                         if (n < 0) {
772                                 log_debug_errno(errno, "Failed to erase data in file '%s', ignoring.", name);
773                                 break;
774                         }
775 
776                         assert(left >= (size_t) n);
777                         left -= n;
778                 }
779 
780                 /* Let's refresh metadata */
781                 if (fstat(truncate_fd, &st) < 0) {
782                         log_debug_errno(errno, "Failed to stat file '%s' for deallocation, ignoring: %m", name);
783                         return 0;
784                 }
785         }
786 
787         /* Don't dallocate if there's nothing to deallocate or if the file is linked elsewhere */
788         if (st.st_blocks == 0 || st.st_nlink > 0)
789                 return 0;
790 
791         /* If this is a regular file, it actually took up space on disk and there are no other links it's time to
792          * punch-hole/truncate this to release the disk space. */
793 
794         bs = MAX(st.st_blksize, 512);
795         l = DIV_ROUND_UP(st.st_size, bs) * bs; /* Round up to next block size */
796 
797         if (fallocate(truncate_fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, 0, l) >= 0)
798                 return 0; /* Successfully punched a hole! �� */
799 
800         /* Fall back to truncation */
801         if (ftruncate(truncate_fd, 0) < 0) {
802                 log_debug_errno(errno, "Failed to truncate file to 0, ignoring: %m");
803                 return 0;
804         }
805 
806         return 0;
807 }
808 
open_parent(const char * path,int flags,mode_t mode)809 int open_parent(const char *path, int flags, mode_t mode) {
810         _cleanup_free_ char *parent = NULL;
811         int r;
812 
813         r = path_extract_directory(path, &parent);
814         if (r < 0)
815                 return r;
816 
817         /* Let's insist on O_DIRECTORY since the parent of a file or directory is a directory. Except if we open an
818          * O_TMPFILE file, because in that case we are actually create a regular file below the parent directory. */
819 
820         if (FLAGS_SET(flags, O_PATH))
821                 flags |= O_DIRECTORY;
822         else if (!FLAGS_SET(flags, O_TMPFILE))
823                 flags |= O_DIRECTORY|O_RDONLY;
824 
825         return RET_NERRNO(open(parent, flags, mode));
826 }
827 
conservative_renameat(int olddirfd,const char * oldpath,int newdirfd,const char * newpath)828 int conservative_renameat(
829                 int olddirfd, const char *oldpath,
830                 int newdirfd, const char *newpath) {
831 
832         _cleanup_close_ int old_fd = -1, new_fd = -1;
833         struct stat old_stat, new_stat;
834 
835         /* Renames the old path to thew new path, much like renameat() — except if both are regular files and
836          * have the exact same contents and basic file attributes already. In that case remove the new file
837          * instead. This call is useful for reducing inotify wakeups on files that are updated but don't
838          * actually change. This function is written in a style that we rather rename too often than suppress
839          * too much. i.e. whenever we are in doubt we rather rename than fail. After all reducing inotify
840          * events is an optimization only, not more. */
841 
842         old_fd = openat(olddirfd, oldpath, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
843         if (old_fd < 0)
844                 goto do_rename;
845 
846         new_fd = openat(newdirfd, newpath, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
847         if (new_fd < 0)
848                 goto do_rename;
849 
850         if (fstat(old_fd, &old_stat) < 0)
851                 goto do_rename;
852 
853         if (!S_ISREG(old_stat.st_mode))
854                 goto do_rename;
855 
856         if (fstat(new_fd, &new_stat) < 0)
857                 goto do_rename;
858 
859         if (stat_inode_same(&new_stat, &old_stat))
860                 goto is_same;
861 
862         if (old_stat.st_mode != new_stat.st_mode ||
863             old_stat.st_size != new_stat.st_size ||
864             old_stat.st_uid != new_stat.st_uid ||
865             old_stat.st_gid != new_stat.st_gid)
866                 goto do_rename;
867 
868         for (;;) {
869                 uint8_t buf1[16*1024];
870                 uint8_t buf2[sizeof(buf1)];
871                 ssize_t l1, l2;
872 
873                 l1 = read(old_fd, buf1, sizeof(buf1));
874                 if (l1 < 0)
875                         goto do_rename;
876 
877                 if (l1 == sizeof(buf1))
878                         /* Read the full block, hence read a full block in the other file too */
879 
880                         l2 = read(new_fd, buf2, l1);
881                 else {
882                         assert((size_t) l1 < sizeof(buf1));
883 
884                         /* Short read. This hence was the last block in the first file, and then came
885                          * EOF. Read one byte more in the second file, so that we can verify we hit EOF there
886                          * too. */
887 
888                         assert((size_t) (l1 + 1) <= sizeof(buf2));
889                         l2 = read(new_fd, buf2, l1 + 1);
890                 }
891                 if (l2 != l1)
892                         goto do_rename;
893 
894                 if (memcmp(buf1, buf2, l1) != 0)
895                         goto do_rename;
896 
897                 if ((size_t) l1 < sizeof(buf1)) /* We hit EOF on the first file, and the second file too, hence exit
898                                                  * now. */
899                         break;
900         }
901 
902 is_same:
903         /* Everything matches? Then don't rename, instead remove the source file, and leave the existing
904          * destination in place */
905 
906         if (unlinkat(olddirfd, oldpath, 0) < 0)
907                 goto do_rename;
908 
909         return 0;
910 
911 do_rename:
912         if (renameat(olddirfd, oldpath, newdirfd, newpath) < 0)
913                 return -errno;
914 
915         return 1;
916 }
917 
posix_fallocate_loop(int fd,uint64_t offset,uint64_t size)918 int posix_fallocate_loop(int fd, uint64_t offset, uint64_t size) {
919         RateLimit rl;
920         int r;
921 
922         r = posix_fallocate(fd, offset, size); /* returns positive errnos on error */
923         if (r != EINTR)
924                 return -r; /* Let's return negative errnos, like common in our codebase */
925 
926         /* On EINTR try a couple of times more, but protect against busy looping
927          * (not more than 16 times per 10s) */
928         rl = (RateLimit) { 10 * USEC_PER_SEC, 16 };
929         while (ratelimit_below(&rl)) {
930                 r = posix_fallocate(fd, offset, size);
931                 if (r != EINTR)
932                         return -r;
933         }
934 
935         return -EINTR;
936 }
937 
parse_cifs_service(const char * s,char ** ret_host,char ** ret_service,char ** ret_path)938 int parse_cifs_service(
939                 const char *s,
940                 char **ret_host,
941                 char **ret_service,
942                 char **ret_path) {
943 
944         _cleanup_free_ char *h = NULL, *ss = NULL, *x = NULL;
945         const char *p, *e, *d;
946         char delimiter;
947 
948         /* Parses a CIFS service in form of //host/service/path… and splitting it in three parts. The last
949          * part is optional, in which case NULL is returned there. To maximize compatibility syntax with
950          * backslashes instead of slashes is accepted too. */
951 
952         if (!s)
953                 return -EINVAL;
954 
955         p = startswith(s, "//");
956         if (!p) {
957                 p = startswith(s, "\\\\");
958                 if (!p)
959                         return -EINVAL;
960         }
961 
962         delimiter = s[0];
963         e = strchr(p, delimiter);
964         if (!e)
965                 return -EINVAL;
966 
967         h = strndup(p, e - p);
968         if (!h)
969                 return -ENOMEM;
970 
971         if (!hostname_is_valid(h, 0))
972                 return -EINVAL;
973 
974         e++;
975 
976         d = strchrnul(e, delimiter);
977 
978         ss = strndup(e, d - e);
979         if (!ss)
980                 return -ENOMEM;
981 
982         if (!filename_is_valid(ss))
983                 return -EINVAL;
984 
985         if (!isempty(d)) {
986                 x = strdup(skip_leading_chars(d, CHAR_TO_STR(delimiter)));
987                 if (!x)
988                         return -EINVAL;
989 
990                 /* Make sure to convert Windows-style "\" → Unix-style / */
991                 for (char *i = x; *i; i++)
992                         if (*i == delimiter)
993                                 *i = '/';
994 
995                 if (!path_is_valid(x))
996                         return -EINVAL;
997 
998                 path_simplify(x);
999                 if (!path_is_normalized(x))
1000                         return -EINVAL;
1001         }
1002 
1003         if (ret_host)
1004                 *ret_host = TAKE_PTR(h);
1005         if (ret_service)
1006                 *ret_service = TAKE_PTR(ss);
1007         if (ret_path)
1008                 *ret_path = TAKE_PTR(x);
1009 
1010         return 0;
1011 }
1012 
open_mkdir_at(int dirfd,const char * path,int flags,mode_t mode)1013 int open_mkdir_at(int dirfd, const char *path, int flags, mode_t mode) {
1014         _cleanup_close_ int fd = -1, parent_fd = -1;
1015         _cleanup_free_ char *fname = NULL;
1016         bool made;
1017         int r;
1018 
1019         /* Creates a directory with mkdirat() and then opens it, in the "most atomic" fashion we can
1020          * do. Guarantees that the returned fd refers to a directory. If O_EXCL is specified will fail if the
1021          * dir already exists. Otherwise will open an existing dir, but only if it is one.  */
1022 
1023         if (flags & ~(O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_EXCL|O_NOATIME|O_NOFOLLOW|O_PATH))
1024                 return -EINVAL;
1025         if ((flags & O_ACCMODE) != O_RDONLY)
1026                 return -EINVAL;
1027 
1028         /* Note that O_DIRECTORY|O_NOFOLLOW is implied, but we allow specifying it anyway. The following
1029          * flags actually make sense to specify: O_CLOEXEC, O_EXCL, O_NOATIME, O_PATH */
1030 
1031         if (isempty(path))
1032                 return -EINVAL;
1033 
1034         if (!filename_is_valid(path)) {
1035                 _cleanup_free_ char *parent = NULL;
1036 
1037                 /* If this is not a valid filename, it's a path. Let's open the parent directory then, so
1038                  * that we can pin it, and operate below it. */
1039 
1040                 r = path_extract_directory(path, &parent);
1041                 if (r < 0)
1042                         return r;
1043 
1044                 r = path_extract_filename(path, &fname);
1045                 if (r < 0)
1046                         return r;
1047 
1048                 parent_fd = openat(dirfd, parent, O_PATH|O_DIRECTORY|O_CLOEXEC);
1049                 if (parent_fd < 0)
1050                         return -errno;
1051 
1052                 dirfd = parent_fd;
1053                 path = fname;
1054         }
1055 
1056         r = RET_NERRNO(mkdirat(dirfd, path, mode));
1057         if (r == -EEXIST) {
1058                 if (FLAGS_SET(flags, O_EXCL))
1059                         return -EEXIST;
1060 
1061                 made = false;
1062         } else if (r < 0)
1063                 return r;
1064         else
1065                 made = true;
1066 
1067         fd = RET_NERRNO(openat(dirfd, path, (flags & ~O_EXCL)|O_DIRECTORY|O_NOFOLLOW));
1068         if (fd < 0) {
1069                 if (fd == -ENOENT)  /* We got ENOENT? then someone else immediately removed it after we
1070                                      * created it. In that case let's return immediately without unlinking
1071                                      * anything, because there simply isn't anything to unlink anymore. */
1072                         return -ENOENT;
1073                 if (fd == -ELOOP)   /* is a symlink? exists already → created by someone else, don't unlink */
1074                         return -EEXIST;
1075                 if (fd == -ENOTDIR) /* not a directory? exists already → created by someone else, don't unlink */
1076                         return -EEXIST;
1077 
1078                 if (made)
1079                         (void) unlinkat(dirfd, path, AT_REMOVEDIR);
1080 
1081                 return fd;
1082         }
1083 
1084         return TAKE_FD(fd);
1085 }
1086 
openat_report_new(int dirfd,const char * pathname,int flags,mode_t mode,bool * ret_newly_created)1087 int openat_report_new(int dirfd, const char *pathname, int flags, mode_t mode, bool *ret_newly_created) {
1088         unsigned attempts = 7;
1089         int fd;
1090 
1091         /* Just like openat(), but adds one thing: optionally returns whether we created the file anew or if
1092          * it already existed before. This is only relevant if O_CREAT is set without O_EXCL, and thus will
1093          * shortcut to openat() otherwise */
1094 
1095         if (!ret_newly_created)
1096                 return RET_NERRNO(openat(dirfd, pathname, flags, mode));
1097 
1098         if (!FLAGS_SET(flags, O_CREAT) || FLAGS_SET(flags, O_EXCL)) {
1099                 fd = openat(dirfd, pathname, flags, mode);
1100                 if (fd < 0)
1101                         return -errno;
1102 
1103                 *ret_newly_created = FLAGS_SET(flags, O_CREAT);
1104                 return fd;
1105         }
1106 
1107         for (;;) {
1108                 /* First, attempt to open without O_CREAT/O_EXCL, i.e. open existing file */
1109                 fd = openat(dirfd, pathname, flags & ~(O_CREAT | O_EXCL), mode);
1110                 if (fd >= 0) {
1111                         *ret_newly_created = false;
1112                         return fd;
1113                 }
1114                 if (errno != ENOENT)
1115                         return -errno;
1116 
1117                 /* So the file didn't exist yet, hence create it with O_CREAT/O_EXCL. */
1118                 fd = openat(dirfd, pathname, flags | O_CREAT | O_EXCL, mode);
1119                 if (fd >= 0) {
1120                         *ret_newly_created = true;
1121                         return fd;
1122                 }
1123                 if (errno != EEXIST)
1124                         return -errno;
1125 
1126                 /* Hmm, so now we got EEXIST? So it apparently exists now? If so, let's try to open again
1127                  * without the two flags. But let's not spin forever, hence put a limit on things */
1128 
1129                 if (--attempts == 0) /* Give up eventually, somebody is playing with us */
1130                         return -EEXIST;
1131         }
1132 }
1133