/
tmpfiles.c
2922 lines (2339 loc) · 99.5 KB
/
tmpfiles.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: LGPL-2.1+ */
#include <errno.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <getopt.h>
#include <glob.h>
#include <limits.h>
#include <linux/fs.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/xattr.h>
#include <sysexits.h>
#include <time.h>
#include <unistd.h>
#include "sd-path.h"
#include "acl-util.h"
#include "alloc-util.h"
#include "btrfs-util.h"
#include "capability-util.h"
#include "chattr-util.h"
#include "conf-files.h"
#include "copy.h"
#include "def.h"
#include "dirent-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "glob-util.h"
#include "io-util.h"
#include "label.h"
#include "log.h"
#include "macro.h"
#include "missing.h"
#include "mkdir.h"
#include "mount-util.h"
#include "pager.h"
#include "parse-util.h"
#include "path-lookup.h"
#include "path-util.h"
#include "rm-rf.h"
#include "selinux-util.h"
#include "set.h"
#include "specifier.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "umask-util.h"
#include "user-util.h"
#include "util.h"
/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
* them in the file system. This is intended to be used to create
* properly owned directories beneath /tmp, /var/tmp, /run, which are
* volatile and hence need to be recreated on bootup. */
typedef enum ItemType {
/* These ones take file names */
CREATE_FILE = 'f',
TRUNCATE_FILE = 'F',
CREATE_DIRECTORY = 'd',
TRUNCATE_DIRECTORY = 'D',
CREATE_SUBVOLUME = 'v',
CREATE_SUBVOLUME_INHERIT_QUOTA = 'q',
CREATE_SUBVOLUME_NEW_QUOTA = 'Q',
CREATE_FIFO = 'p',
CREATE_SYMLINK = 'L',
CREATE_CHAR_DEVICE = 'c',
CREATE_BLOCK_DEVICE = 'b',
COPY_FILES = 'C',
/* These ones take globs */
WRITE_FILE = 'w',
EMPTY_DIRECTORY = 'e',
SET_XATTR = 't',
RECURSIVE_SET_XATTR = 'T',
SET_ACL = 'a',
RECURSIVE_SET_ACL = 'A',
SET_ATTRIBUTE = 'h',
RECURSIVE_SET_ATTRIBUTE = 'H',
IGNORE_PATH = 'x',
IGNORE_DIRECTORY_PATH = 'X',
REMOVE_PATH = 'r',
RECURSIVE_REMOVE_PATH = 'R',
RELABEL_PATH = 'z',
RECURSIVE_RELABEL_PATH = 'Z',
ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
} ItemType;
typedef struct Item {
ItemType type;
char *path;
char *argument;
char **xattrs;
#if HAVE_ACL
acl_t acl_access;
acl_t acl_default;
#endif
uid_t uid;
gid_t gid;
mode_t mode;
usec_t age;
dev_t major_minor;
unsigned attribute_value;
unsigned attribute_mask;
bool uid_set:1;
bool gid_set:1;
bool mode_set:1;
bool age_set:1;
bool mask_perms:1;
bool attribute_set:1;
bool keep_first_level:1;
bool force:1;
bool done:1;
} Item;
typedef struct ItemArray {
Item *items;
size_t count;
size_t size;
} ItemArray;
typedef enum DirectoryType {
DIRECTORY_RUNTIME = 0,
DIRECTORY_STATE,
DIRECTORY_CACHE,
DIRECTORY_LOGS,
_DIRECTORY_TYPE_MAX,
} DirectoryType;
static bool arg_cat_config = false;
static bool arg_user = false;
static bool arg_create = false;
static bool arg_clean = false;
static bool arg_remove = false;
static bool arg_boot = false;
static bool arg_no_pager = false;
static char **arg_include_prefixes = NULL;
static char **arg_exclude_prefixes = NULL;
static char *arg_root = NULL;
static char *arg_replace = NULL;
#define MAX_DEPTH 256
static OrderedHashmap *items = NULL, *globs = NULL;
static Set *unix_sockets = NULL;
static int specifier_machine_id_safe(char specifier, void *data, void *userdata, char **ret);
static int specifier_directory(char specifier, void *data, void *userdata, char **ret);
static const Specifier specifier_table[] = {
{ 'm', specifier_machine_id_safe, NULL },
{ 'b', specifier_boot_id, NULL },
{ 'H', specifier_host_name, NULL },
{ 'v', specifier_kernel_release, NULL },
{ 'U', specifier_user_id, NULL },
{ 'u', specifier_user_name, NULL },
{ 'h', specifier_user_home, NULL },
{ 't', specifier_directory, UINT_TO_PTR(DIRECTORY_RUNTIME) },
{ 'S', specifier_directory, UINT_TO_PTR(DIRECTORY_STATE) },
{ 'C', specifier_directory, UINT_TO_PTR(DIRECTORY_CACHE) },
{ 'L', specifier_directory, UINT_TO_PTR(DIRECTORY_LOGS) },
{ 'T', specifier_tmp_dir, NULL },
{ 'V', specifier_var_tmp_dir, NULL },
{}
};
static int specifier_machine_id_safe(char specifier, void *data, void *userdata, char **ret) {
int r;
/* If /etc/machine_id is missing or empty (e.g. in a chroot environment)
* return a recognizable error so that the caller can skip the rule
* gracefully. */
r = specifier_machine_id(specifier, data, userdata, ret);
if (IN_SET(r, -ENOENT, -ENOMEDIUM))
return -ENXIO;
return r;
}
static int specifier_directory(char specifier, void *data, void *userdata, char **ret) {
struct table_entry {
uint64_t type;
const char *suffix;
};
static const struct table_entry paths_system[] = {
[DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME },
[DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE },
[DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE },
[DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS },
};
static const struct table_entry paths_user[] = {
[DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME },
[DIRECTORY_STATE] = { SD_PATH_USER_CONFIGURATION },
[DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE },
[DIRECTORY_LOGS] = { SD_PATH_USER_CONFIGURATION, "log" },
};
unsigned i;
const struct table_entry *paths;
assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
paths = arg_user ? paths_user : paths_system;
i = PTR_TO_UINT(data);
assert(i < ELEMENTSOF(paths_system));
return sd_path_home(paths[i].type, paths[i].suffix, ret);
}
static int log_unresolvable_specifier(const char *filename, unsigned line) {
static bool notified = false;
/* In system mode, this is called when /etc is not fully initialized (e.g.
* in a chroot environment) where some specifiers are unresolvable. In user
* mode, this is called when some variables are not defined. These cases are
* not considered as an error so log at LOG_NOTICE only for the first time
* and then downgrade this to LOG_DEBUG for the rest. */
log_full(notified ? LOG_DEBUG : LOG_NOTICE,
"[%s:%u] Failed to resolve specifier: %s, skipping",
filename, line,
arg_user ? "Required $XDG_... variable not defined" : "uninitialized /etc detected");
if (!notified)
log_notice("All rules containing unresolvable specifiers will be skipped.");
notified = true;
return 0;
}
static int user_config_paths(char*** ret) {
_cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
_cleanup_free_ char *persistent_config = NULL, *runtime_config = NULL, *data_home = NULL;
_cleanup_strv_free_ char **res = NULL;
int r;
r = xdg_user_dirs(&config_dirs, &data_dirs);
if (r < 0)
return r;
r = xdg_user_config_dir(&persistent_config, "/user-tmpfiles.d");
if (r < 0 && r != -ENXIO)
return r;
r = xdg_user_runtime_dir(&runtime_config, "/user-tmpfiles.d");
if (r < 0 && r != -ENXIO)
return r;
r = xdg_user_data_dir(&data_home, "/user-tmpfiles.d");
if (r < 0 && r != -ENXIO)
return r;
r = strv_extend_strv_concat(&res, config_dirs, "/user-tmpfiles.d");
if (r < 0)
return r;
r = strv_extend(&res, persistent_config);
if (r < 0)
return r;
r = strv_extend(&res, runtime_config);
if (r < 0)
return r;
r = strv_extend(&res, data_home);
if (r < 0)
return r;
r = strv_extend_strv_concat(&res, data_dirs, "/user-tmpfiles.d");
if (r < 0)
return r;
r = path_strv_make_absolute_cwd(res);
if (r < 0)
return r;
*ret = TAKE_PTR(res);
return 0;
}
static bool needs_glob(ItemType t) {
return IN_SET(t,
WRITE_FILE,
IGNORE_PATH,
IGNORE_DIRECTORY_PATH,
REMOVE_PATH,
RECURSIVE_REMOVE_PATH,
EMPTY_DIRECTORY,
ADJUST_MODE,
RELABEL_PATH,
RECURSIVE_RELABEL_PATH,
SET_XATTR,
RECURSIVE_SET_XATTR,
SET_ACL,
RECURSIVE_SET_ACL,
SET_ATTRIBUTE,
RECURSIVE_SET_ATTRIBUTE);
}
static bool takes_ownership(ItemType t) {
return IN_SET(t,
CREATE_FILE,
TRUNCATE_FILE,
CREATE_DIRECTORY,
EMPTY_DIRECTORY,
TRUNCATE_DIRECTORY,
CREATE_SUBVOLUME,
CREATE_SUBVOLUME_INHERIT_QUOTA,
CREATE_SUBVOLUME_NEW_QUOTA,
CREATE_FIFO,
CREATE_SYMLINK,
CREATE_CHAR_DEVICE,
CREATE_BLOCK_DEVICE,
COPY_FILES,
WRITE_FILE,
IGNORE_PATH,
IGNORE_DIRECTORY_PATH,
REMOVE_PATH,
RECURSIVE_REMOVE_PATH);
}
static struct Item* find_glob(OrderedHashmap *h, const char *match) {
ItemArray *j;
Iterator i;
ORDERED_HASHMAP_FOREACH(j, h, i) {
unsigned n;
for (n = 0; n < j->count; n++) {
Item *item = j->items + n;
if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
return item;
}
}
return NULL;
}
static void load_unix_sockets(void) {
_cleanup_fclose_ FILE *f = NULL;
int r;
if (unix_sockets)
return;
/* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
unix_sockets = set_new(&path_hash_ops);
if (!unix_sockets) {
log_oom();
return;
}
f = fopen("/proc/net/unix", "re");
if (!f) {
log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
"Failed to open /proc/net/unix, ignoring: %m");
goto fail;
}
/* Skip header */
r = read_line(f, LONG_LINE_MAX, NULL);
if (r < 0) {
log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
goto fail;
}
if (r == 0) {
log_warning("Premature end of file reading /proc/net/unix.");
goto fail;
}
for (;;) {
_cleanup_free_ char *line = NULL;
char *p, *s;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0) {
log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
goto fail;
}
if (r == 0) /* EOF */
break;
p = strchr(line, ':');
if (!p)
continue;
if (strlen(p) < 37)
continue;
p += 37;
p += strspn(p, WHITESPACE);
p += strcspn(p, WHITESPACE); /* skip one more word */
p += strspn(p, WHITESPACE);
if (*p != '/')
continue;
s = strdup(p);
if (!s) {
log_oom();
goto fail;
}
path_simplify(s, false);
r = set_consume(unix_sockets, s);
if (r < 0 && r != -EEXIST) {
log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
goto fail;
}
}
return;
fail:
unix_sockets = set_free_free(unix_sockets);
}
static bool unix_socket_alive(const char *fn) {
assert(fn);
load_unix_sockets();
if (unix_sockets)
return !!set_get(unix_sockets, (char*) fn);
/* We don't know, so assume yes */
return true;
}
static int dir_is_mount_point(DIR *d, const char *subdir) {
int mount_id_parent, mount_id;
int r_p, r;
r_p = name_to_handle_at_loop(dirfd(d), ".", NULL, &mount_id_parent, 0);
if (r_p < 0)
r_p = -errno;
r = name_to_handle_at_loop(dirfd(d), subdir, NULL, &mount_id, 0);
if (r < 0)
r = -errno;
/* got no handle; make no assumptions, return error */
if (r_p < 0 && r < 0)
return r_p;
/* got both handles; if they differ, it is a mount point */
if (r_p >= 0 && r >= 0)
return mount_id_parent != mount_id;
/* got only one handle; assume different mount points if one
* of both queries was not supported by the filesystem */
if (IN_SET(r_p, -ENOSYS, -EOPNOTSUPP) || IN_SET(r, -ENOSYS, -EOPNOTSUPP))
return true;
/* return error */
if (r_p < 0)
return r_p;
return r;
}
static DIR* xopendirat_nomod(int dirfd, const char *path) {
DIR *dir;
dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
if (dir)
return dir;
log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
if (errno != EPERM)
return NULL;
dir = xopendirat(dirfd, path, O_NOFOLLOW);
if (!dir)
log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
return dir;
}
static DIR* opendir_nomod(const char *path) {
return xopendirat_nomod(AT_FDCWD, path);
}
static int dir_cleanup(
Item *i,
const char *p,
DIR *d,
const struct stat *ds,
usec_t cutoff,
dev_t rootdev,
bool mountpoint,
int maxdepth,
bool keep_this_level) {
struct dirent *dent;
struct timespec times[2];
bool deleted = false;
int r = 0;
FOREACH_DIRENT_ALL(dent, d, break) {
struct stat s;
usec_t age;
_cleanup_free_ char *sub_path = NULL;
if (dot_or_dot_dot(dent->d_name))
continue;
if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
if (errno == ENOENT)
continue;
/* FUSE, NFS mounts, SELinux might return EACCES */
r = log_full_errno(errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
"stat(%s/%s) failed: %m", p, dent->d_name);
continue;
}
/* Stay on the same filesystem */
if (s.st_dev != rootdev) {
log_debug("Ignoring \"%s/%s\": different filesystem.", p, dent->d_name);
continue;
}
/* Try to detect bind mounts of the same filesystem instance; they
* do not differ in device major/minors. This type of query is not
* supported on all kernels or filesystem types though. */
if (S_ISDIR(s.st_mode) && dir_is_mount_point(d, dent->d_name) > 0) {
log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.",
p, dent->d_name);
continue;
}
sub_path = strjoin(p, "/", dent->d_name);
if (!sub_path) {
r = log_oom();
goto finish;
}
/* Is there an item configured for this path? */
if (ordered_hashmap_get(items, sub_path)) {
log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
continue;
}
if (find_glob(globs, sub_path)) {
log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
continue;
}
if (S_ISDIR(s.st_mode)) {
if (mountpoint &&
streq(dent->d_name, "lost+found") &&
s.st_uid == 0) {
log_debug("Ignoring \"%s\".", sub_path);
continue;
}
if (maxdepth <= 0)
log_warning("Reached max depth on \"%s\".", sub_path);
else {
_cleanup_closedir_ DIR *sub_dir;
int q;
sub_dir = xopendirat_nomod(dirfd(d), dent->d_name);
if (!sub_dir) {
if (errno != ENOENT)
r = log_error_errno(errno, "opendir(%s) failed: %m", sub_path);
continue;
}
q = dir_cleanup(i, sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
if (q < 0)
r = q;
}
/* Note: if you are wondering why we don't
* support the sticky bit for excluding
* directories from cleaning like we do it for
* other file system objects: well, the sticky
* bit already has a meaning for directories,
* so we don't want to overload that. */
if (keep_this_level) {
log_debug("Keeping \"%s\".", sub_path);
continue;
}
/* Ignore ctime, we change it when deleting */
age = timespec_load(&s.st_mtim);
if (age >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
/* Follows spelling in stat(1). */
log_debug("Directory \"%s\": modify time %s is too new.",
sub_path,
format_timestamp_us(a, sizeof(a), age));
continue;
}
age = timespec_load(&s.st_atim);
if (age >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
log_debug("Directory \"%s\": access time %s is too new.",
sub_path,
format_timestamp_us(a, sizeof(a), age));
continue;
}
log_debug("Removing directory \"%s\".", sub_path);
if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0)
if (!IN_SET(errno, ENOENT, ENOTEMPTY))
r = log_error_errno(errno, "rmdir(%s): %m", sub_path);
} else {
/* Skip files for which the sticky bit is
* set. These are semantics we define, and are
* unknown elsewhere. See XDG_RUNTIME_DIR
* specification for details. */
if (s.st_mode & S_ISVTX) {
log_debug("Skipping \"%s\": sticky bit set.", sub_path);
continue;
}
if (mountpoint && S_ISREG(s.st_mode))
if (s.st_uid == 0 && STR_IN_SET(dent->d_name,
".journal",
"aquota.user",
"aquota.group")) {
log_debug("Skipping \"%s\".", sub_path);
continue;
}
/* Ignore sockets that are listed in /proc/net/unix */
if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path)) {
log_debug("Skipping \"%s\": live socket.", sub_path);
continue;
}
/* Ignore device nodes */
if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode)) {
log_debug("Skipping \"%s\": a device.", sub_path);
continue;
}
/* Keep files on this level around if this is
* requested */
if (keep_this_level) {
log_debug("Keeping \"%s\".", sub_path);
continue;
}
age = timespec_load(&s.st_mtim);
if (age >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
/* Follows spelling in stat(1). */
log_debug("File \"%s\": modify time %s is too new.",
sub_path,
format_timestamp_us(a, sizeof(a), age));
continue;
}
age = timespec_load(&s.st_atim);
if (age >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
log_debug("File \"%s\": access time %s is too new.",
sub_path,
format_timestamp_us(a, sizeof(a), age));
continue;
}
age = timespec_load(&s.st_ctim);
if (age >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
log_debug("File \"%s\": change time %s is too new.",
sub_path,
format_timestamp_us(a, sizeof(a), age));
continue;
}
log_debug("unlink \"%s\"", sub_path);
if (unlinkat(dirfd(d), dent->d_name, 0) < 0)
if (errno != ENOENT)
r = log_error_errno(errno, "unlink(%s): %m", sub_path);
deleted = true;
}
}
finish:
if (deleted) {
usec_t age1, age2;
char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX];
/* Restore original directory timestamps */
times[0] = ds->st_atim;
times[1] = ds->st_mtim;
age1 = timespec_load(&ds->st_atim);
age2 = timespec_load(&ds->st_mtim);
log_debug("Restoring access and modification time on \"%s\": %s, %s",
p,
format_timestamp_us(a, sizeof(a), age1),
format_timestamp_us(b, sizeof(b), age2));
if (futimens(dirfd(d), times) < 0)
log_error_errno(errno, "utimensat(%s): %m", p);
}
return r;
}
static bool dangerous_hardlinks(void) {
_cleanup_free_ char *value = NULL;
static int cached = -1;
int r;
/* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
* what the upstream default is. */
if (cached >= 0)
return cached;
r = read_one_line_file("/proc/sys/fs/protected_hardlinks", &value);
if (r < 0) {
log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl: %m");
return true;
}
r = parse_boolean(value);
if (r < 0) {
log_debug_errno(r, "Failed to parse fs.protected_hardlinks sysctl: %m");
return true;
}
cached = r == 0;
return cached;
}
static bool hardlink_vulnerable(const struct stat *st) {
assert(st);
return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && dangerous_hardlinks();
}
static int fd_set_perms(Item *i, int fd, const struct stat *st) {
_cleanup_free_ char *path = NULL;
struct stat stbuf;
int r;
assert(i);
assert(fd);
r = fd_get_path(fd, &path);
if (r < 0)
return r;
if (!i->mode_set && !i->uid_set && !i->gid_set)
goto shortcut;
if (!st) {
if (fstat(fd, &stbuf) < 0)
return log_error_errno(errno, "fstat(%s) failed: %m", path);
st = &stbuf;
}
if (hardlink_vulnerable(st)) {
log_error("Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.", path);
return -EPERM;
}
if (i->mode_set) {
if (S_ISLNK(st->st_mode))
log_debug("Skipping mode fix for symlink %s.", path);
else {
mode_t m = i->mode;
if (i->mask_perms) {
if (!(st->st_mode & 0111))
m &= ~0111;
if (!(st->st_mode & 0222))
m &= ~0222;
if (!(st->st_mode & 0444))
m &= ~0444;
if (!S_ISDIR(st->st_mode))
m &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
}
if (m == (st->st_mode & 07777))
log_debug("\"%s\" has correct mode %o already.", path, st->st_mode);
else {
log_debug("Changing \"%s\" to mode %o.", path, m);
if (fchmod_opath(fd, m) < 0)
return log_error_errno(errno, "fchmod() of %s failed: %m", path);
}
}
}
if ((i->uid_set && i->uid != st->st_uid) ||
(i->gid_set && i->gid != st->st_gid)) {
log_debug("Changing \"%s\" to owner "UID_FMT":"GID_FMT,
path,
i->uid_set ? i->uid : UID_INVALID,
i->gid_set ? i->gid : GID_INVALID);
if (fchownat(fd,
"",
i->uid_set ? i->uid : UID_INVALID,
i->gid_set ? i->gid : GID_INVALID,
AT_EMPTY_PATH) < 0)
return log_error_errno(errno, "fchownat() of %s failed: %m", path);
}
shortcut:
return label_fix(path, 0);
}
static int path_set_perms(Item *i, const char *path) {
_cleanup_close_ int fd = -1;
struct stat stbuf, *st = NULL;
assert(i);
assert(path);
fd = open(path, O_NOFOLLOW|O_CLOEXEC|O_PATH);
if (fd < 0) {
int level = LOG_ERR, r = -errno;
/* Option "e" operates only on existing objects. Do not
* print errors about non-existent files or directories */
if (i->type == EMPTY_DIRECTORY && errno == ENOENT) {
level = LOG_DEBUG;
r = 0;
}
log_full_errno(level, errno, "Adjusting owner and mode for %s failed: %m", path);
return r;
}
if (i->type == EMPTY_DIRECTORY) {
/* FIXME: introduce fd_is_dir() helper ? */
if (fstat(fd, &stbuf) < 0)
return log_error_errno(errno, "Failed to fstat() file %s: %m", path);
if (!S_ISDIR(stbuf.st_mode)) {
log_error("'%s' already exists and is not a directory. ", path);
return -EEXIST;
}
st = &stbuf;
}
return fd_set_perms(i, fd, st);
}
static int parse_xattrs_from_arg(Item *i) {
const char *p;
int r;
assert(i);
assert(i->argument);
p = i->argument;
for (;;) {
_cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
r = extract_first_word(&p, &xattr, NULL, EXTRACT_QUOTES|EXTRACT_CUNESCAPE);
if (r < 0)
log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
if (r <= 0)
break;
r = split_pair(xattr, "=", &name, &value);
if (r < 0) {
log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
continue;
}
if (isempty(name) || isempty(value)) {
log_warning("Malformed extended attribute found, ignoring: %s", xattr);
continue;
}
if (strv_push_pair(&i->xattrs, name, value) < 0)
return log_oom();
name = value = NULL;
}
return 0;
}
static int fd_set_xattrs(Item *i, int fd, const struct stat *st) {
char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
_cleanup_free_ char *path = NULL;
char **name, **value;
int r;
assert(i);
assert(fd);
r = fd_get_path(fd, &path);
if (r < 0)
return r;
xsprintf(procfs_path, "/proc/self/fd/%i", fd);
STRV_FOREACH_PAIR(name, value, i->xattrs) {
log_debug("Setting extended attribute '%s=%s' on %s.", *name, *value, path);
if (setxattr(procfs_path, *name, *value, strlen(*value), 0) < 0)
return log_error_errno(errno, "Setting extended attribute %s=%s on %s failed: %m",
*name, *value, path);
}
return 0;
}
static int path_set_xattrs(Item *i, const char *path) {
_cleanup_close_ int fd = -1;
assert(i);
assert(path);
fd = open(path, O_CLOEXEC|O_NOFOLLOW|O_PATH);
if (fd < 0)
return log_error_errno(errno, "Cannot open '%s': %m", path);
return fd_set_xattrs(i, fd, NULL);
}
static int parse_acls_from_arg(Item *item) {
#if HAVE_ACL
int r;
assert(item);
/* If force (= modify) is set, we will not modify the acl
* afterwards, so the mask can be added now if necessary. */
r = parse_acl(item->argument, &item->acl_access, &item->acl_default, !item->force);
if (r < 0)
log_warning_errno(r, "Failed to parse ACL \"%s\": %m. Ignoring", item->argument);
#else
log_warning_errno(ENOSYS, "ACLs are not supported. Ignoring");
#endif
return 0;
}
#if HAVE_ACL
static int path_set_acl(const char *path, const char *pretty, acl_type_t type, acl_t acl, bool modify) {
_cleanup_(acl_free_charpp) char *t = NULL;
_cleanup_(acl_freep) acl_t dup = NULL;
int r;
/* Returns 0 for success, positive error if already warned,
* negative error otherwise. */
if (modify) {
r = acls_for_file(path, type, acl, &dup);
if (r < 0)
return r;
r = calc_acl_mask_if_needed(&dup);
if (r < 0)
return r;
} else {
dup = acl_dup(acl);
if (!dup)
return -errno;
/* the mask was already added earlier if needed */
}