1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include <sys/inotify.h>
10 #include "dbus-path.h"
11 #include "dbus-unit.h"
14 #include "glob-util.h"
15 #include "inotify-util.h"
17 #include "mkdir-label.h"
19 #include "path-util.h"
20 #include "serialize.h"
22 #include "stat-util.h"
23 #include "string-table.h"
24 #include "string-util.h"
25 #include "unit-name.h"
28 static const UnitActiveState state_translation_table
[_PATH_STATE_MAX
] = {
29 [PATH_DEAD
] = UNIT_INACTIVE
,
30 [PATH_WAITING
] = UNIT_ACTIVE
,
31 [PATH_RUNNING
] = UNIT_ACTIVE
,
32 [PATH_FAILED
] = UNIT_FAILED
,
35 static int path_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
37 int path_spec_watch(PathSpec
*s
, sd_event_io_handler_t handler
) {
38 static const int flags_table
[_PATH_TYPE_MAX
] = {
39 [PATH_EXISTS
] = IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
,
40 [PATH_EXISTS_GLOB
] = IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
,
41 [PATH_CHANGED
] = IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CLOSE_WRITE
|IN_CREATE
|IN_DELETE
|IN_MOVED_FROM
|IN_MOVED_TO
,
42 [PATH_MODIFIED
] = IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CLOSE_WRITE
|IN_CREATE
|IN_DELETE
|IN_MOVED_FROM
|IN_MOVED_TO
|IN_MODIFY
,
43 [PATH_DIRECTORY_NOT_EMPTY
] = IN_DELETE_SELF
|IN_MOVE_SELF
|IN_ATTRIB
|IN_CREATE
|IN_MOVED_TO
,
47 char *slash
, *oldslash
= NULL
;
56 s
->inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
57 if (s
->inotify_fd
< 0) {
58 r
= log_error_errno(errno
, "Failed to allocate inotify fd: %m");
62 r
= sd_event_add_io(s
->unit
->manager
->event
, &s
->event_source
, s
->inotify_fd
, EPOLLIN
, handler
, s
);
64 log_error_errno(r
, "Failed to add inotify fd to event loop: %m");
68 (void) sd_event_source_set_description(s
->event_source
, "path");
70 /* This function assumes the path was passed through path_simplify()! */
71 assert(!strstr(s
->path
, "//"));
73 for (slash
= strchr(s
->path
, '/'); ; slash
= strchr(slash
+1, '/')) {
74 bool incomplete
= false;
79 cut
= slash
+ (slash
== s
->path
);
83 flags
= IN_MOVE_SELF
| IN_DELETE_SELF
| IN_ATTRIB
| IN_CREATE
| IN_MOVED_TO
;
86 flags
= flags_table
[s
->type
];
89 /* If this is a symlink watch both the symlink inode and where it points to. If the inode is
90 * not a symlink both calls will install the same watch, which is redundant and doesn't
92 for (int follow_symlink
= 0; follow_symlink
< 2; follow_symlink
++) {
95 SET_FLAG(f
, IN_DONT_FOLLOW
, !follow_symlink
);
97 wd
= inotify_add_watch(s
->inotify_fd
, s
->path
, f
);
99 if (IN_SET(errno
, EACCES
, ENOENT
)) {
100 incomplete
= true; /* This is an expected error, let's accept this
101 * quietly: we have an incomplete watch for
106 /* This second call to inotify_add_watch() should fail like the previous one
107 * and is done for logging the error in a comprehensive way. */
108 wd
= inotify_add_watch_and_warn(s
->inotify_fd
, s
->path
, f
);
117 /* Hmm, we succeeded in adding the watch this time... let's continue. */
130 /* Path exists, we don't need to watch parent too closely. */
132 char *cut2
= oldslash
+ (oldslash
== s
->path
);
136 (void) inotify_add_watch(s
->inotify_fd
, s
->path
, IN_MOVE_SELF
);
137 /* Error is ignored, the worst can happen is we get spurious events. */
148 /* whole path has been iterated over */
155 r
= log_error_errno(errno
, "Failed to add watch on any of the components of %s: %m", s
->path
);
156 /* either EACCESS or ENOENT */
163 path_spec_unwatch(s
);
167 void path_spec_unwatch(PathSpec
*s
) {
170 s
->event_source
= sd_event_source_disable_unref(s
->event_source
);
171 s
->inotify_fd
= safe_close(s
->inotify_fd
);
174 int path_spec_fd_event(PathSpec
*s
, uint32_t revents
) {
175 union inotify_event_buffer buffer
;
176 struct inotify_event
*e
;
181 if (revents
!= EPOLLIN
)
182 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
183 "Got invalid poll event on inotify.");
185 l
= read(s
->inotify_fd
, &buffer
, sizeof(buffer
));
187 if (ERRNO_IS_TRANSIENT(errno
))
190 return log_error_errno(errno
, "Failed to read inotify event: %m");
193 if (IN_SET(s
->type
, PATH_CHANGED
, PATH_MODIFIED
))
194 FOREACH_INOTIFY_EVENT(e
, buffer
, l
)
195 if (s
->primary_wd
== e
->wd
)
201 static bool path_spec_check_good(PathSpec
*s
, bool initial
, bool from_trigger_notify
) {
202 bool b
, good
= false;
207 good
= access(s
->path
, F_OK
) >= 0;
210 case PATH_EXISTS_GLOB
:
211 good
= glob_exists(s
->path
) > 0;
214 case PATH_DIRECTORY_NOT_EMPTY
: {
217 k
= dir_is_empty(s
->path
);
218 good
= !(IN_SET(k
, -ENOENT
, -ENOTDIR
) || k
> 0);
224 b
= access(s
->path
, F_OK
) >= 0;
225 good
= !initial
&& !from_trigger_notify
&& b
!= s
->previous_exists
;
226 s
->previous_exists
= b
;
236 static void path_spec_mkdir(PathSpec
*s
, mode_t mode
) {
239 if (IN_SET(s
->type
, PATH_EXISTS
, PATH_EXISTS_GLOB
))
242 r
= mkdir_p_label(s
->path
, mode
);
244 log_warning_errno(r
, "mkdir(%s) failed: %m", s
->path
);
247 static void path_spec_dump(PathSpec
*s
, FILE *f
, const char *prefix
) {
250 assert_se(type
= path_type_to_string(s
->type
));
251 fprintf(f
, "%s%s: %s\n", prefix
, type
, s
->path
);
254 void path_spec_done(PathSpec
*s
) {
256 assert(s
->inotify_fd
== -1);
261 static void path_init(Unit
*u
) {
265 assert(u
->load_state
== UNIT_STUB
);
267 p
->directory_mode
= 0755;
269 p
->trigger_limit
.interval
= USEC_INFINITY
;
270 p
->trigger_limit
.burst
= UINT_MAX
;
273 void path_free_specs(Path
*p
) {
278 while ((s
= p
->specs
)) {
279 path_spec_unwatch(s
);
280 LIST_REMOVE(spec
, p
->specs
, s
);
286 static void path_done(Unit
*u
) {
294 static int path_add_mount_dependencies(Path
*p
) {
300 LIST_FOREACH(spec
, s
, p
->specs
) {
301 r
= unit_require_mounts_for(UNIT(p
), s
->path
, UNIT_DEPENDENCY_FILE
);
309 static int path_verify(Path
*p
) {
311 assert(UNIT(p
)->load_state
== UNIT_LOADED
);
314 return log_unit_error_errno(UNIT(p
), SYNTHETIC_ERRNO(ENOEXEC
), "Path unit lacks path setting. Refusing.");
319 static int path_add_default_dependencies(Path
*p
) {
324 if (!UNIT(p
)->default_dependencies
)
327 r
= unit_add_dependency_by_name(UNIT(p
), UNIT_BEFORE
, SPECIAL_PATHS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
331 if (MANAGER_IS_SYSTEM(UNIT(p
)->manager
)) {
332 r
= unit_add_two_dependencies_by_name(UNIT(p
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
337 return unit_add_two_dependencies_by_name(UNIT(p
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
340 static int path_add_trigger_dependencies(Path
*p
) {
346 if (UNIT_TRIGGER(UNIT(p
)))
349 r
= unit_load_related_unit(UNIT(p
), ".service", &x
);
353 return unit_add_two_dependencies(UNIT(p
), UNIT_BEFORE
, UNIT_TRIGGERS
, x
, true, UNIT_DEPENDENCY_IMPLICIT
);
356 static int path_add_extras(Path
*p
) {
361 /* To avoid getting pid1 in a busy-loop state (eg: failed condition on associated service),
362 * set a default trigger limit if the user didn't specify any. */
363 if (p
->trigger_limit
.interval
== USEC_INFINITY
)
364 p
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
366 if (p
->trigger_limit
.burst
== UINT_MAX
)
367 p
->trigger_limit
.burst
= 200;
369 r
= path_add_trigger_dependencies(p
);
373 r
= path_add_mount_dependencies(p
);
377 return path_add_default_dependencies(p
);
380 static int path_load(Unit
*u
) {
385 assert(u
->load_state
== UNIT_STUB
);
387 r
= unit_load_fragment_and_dropin(u
, true);
391 if (u
->load_state
!= UNIT_LOADED
)
394 r
= path_add_extras(p
);
398 return path_verify(p
);
401 static void path_dump(Unit
*u
, FILE *f
, const char *prefix
) {
409 trigger
= UNIT_TRIGGER(u
);
415 "%sMakeDirectory: %s\n"
416 "%sDirectoryMode: %04o\n"
417 "%sTriggerLimitIntervalSec: %s\n"
418 "%sTriggerLimitBurst: %u\n",
419 prefix
, path_state_to_string(p
->state
),
420 prefix
, path_result_to_string(p
->result
),
421 prefix
, trigger
? trigger
->id
: "n/a",
422 prefix
, yes_no(p
->make_directory
),
423 prefix
, p
->directory_mode
,
424 prefix
, FORMAT_TIMESPAN(p
->trigger_limit
.interval
, USEC_PER_SEC
),
425 prefix
, p
->trigger_limit
.burst
);
427 LIST_FOREACH(spec
, s
, p
->specs
)
428 path_spec_dump(s
, f
, prefix
);
431 static void path_unwatch(Path
*p
) {
436 LIST_FOREACH(spec
, s
, p
->specs
)
437 path_spec_unwatch(s
);
440 static int path_watch(Path
*p
) {
446 LIST_FOREACH(spec
, s
, p
->specs
) {
447 r
= path_spec_watch(s
, path_dispatch_io
);
455 static void path_set_state(Path
*p
, PathState state
) {
459 if (p
->state
!= state
)
460 bus_unit_send_pending_change_signal(UNIT(p
), false);
462 old_state
= p
->state
;
465 if (!IN_SET(state
, PATH_WAITING
, PATH_RUNNING
))
468 if (state
!= old_state
)
469 log_unit_debug(UNIT(p
), "Changed %s -> %s", path_state_to_string(old_state
), path_state_to_string(state
));
471 unit_notify(UNIT(p
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
474 static void path_enter_waiting(Path
*p
, bool initial
, bool from_trigger_notify
);
476 static int path_coldplug(Unit
*u
) {
480 assert(p
->state
== PATH_DEAD
);
482 if (p
->deserialized_state
!= p
->state
) {
484 if (IN_SET(p
->deserialized_state
, PATH_WAITING
, PATH_RUNNING
))
485 path_enter_waiting(p
, true, false);
487 path_set_state(p
, p
->deserialized_state
);
493 static void path_enter_dead(Path
*p
, PathResult f
) {
496 if (p
->result
== PATH_SUCCESS
)
499 unit_log_result(UNIT(p
), p
->result
== PATH_SUCCESS
, path_result_to_string(p
->result
));
500 path_set_state(p
, p
->result
!= PATH_SUCCESS
? PATH_FAILED
: PATH_DEAD
);
503 static void path_enter_running(Path
*p
) {
504 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
510 /* Don't start job if we are supposed to go down */
511 if (unit_stop_pending(UNIT(p
)))
514 if (!ratelimit_below(&p
->trigger_limit
)) {
515 log_unit_warning(UNIT(p
), "Trigger limit hit, refusing further activation.");
516 path_enter_dead(p
, PATH_FAILURE_TRIGGER_LIMIT_HIT
);
520 trigger
= UNIT_TRIGGER(UNIT(p
));
522 log_unit_error(UNIT(p
), "Unit to trigger vanished.");
523 path_enter_dead(p
, PATH_FAILURE_RESOURCES
);
527 r
= manager_add_job(UNIT(p
)->manager
, JOB_START
, trigger
, JOB_REPLACE
, NULL
, &error
, NULL
);
531 path_set_state(p
, PATH_RUNNING
);
537 log_unit_warning(UNIT(p
), "Failed to queue unit startup job: %s", bus_error_message(&error
, r
));
538 path_enter_dead(p
, PATH_FAILURE_RESOURCES
);
541 static bool path_check_good(Path
*p
, bool initial
, bool from_trigger_notify
) {
546 LIST_FOREACH(spec
, s
, p
->specs
)
547 if (path_spec_check_good(s
, initial
, from_trigger_notify
))
553 static void path_enter_waiting(Path
*p
, bool initial
, bool from_trigger_notify
) {
557 /* If the triggered unit is already running, so are we */
558 trigger
= UNIT_TRIGGER(UNIT(p
));
559 if (trigger
&& !UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(trigger
))) {
560 path_set_state(p
, PATH_RUNNING
);
565 if (path_check_good(p
, initial
, from_trigger_notify
)) {
566 log_unit_debug(UNIT(p
), "Got triggered.");
567 path_enter_running(p
);
575 /* Hmm, so now we have created inotify watches, but the file
576 * might have appeared/been removed by now, so we must
579 if (path_check_good(p
, false, from_trigger_notify
)) {
580 log_unit_debug(UNIT(p
), "Got triggered.");
581 path_enter_running(p
);
585 path_set_state(p
, PATH_WAITING
);
589 log_unit_warning_errno(UNIT(p
), r
, "Failed to enter waiting state: %m");
590 path_enter_dead(p
, PATH_FAILURE_RESOURCES
);
593 static void path_mkdir(Path
*p
) {
598 if (!p
->make_directory
)
601 LIST_FOREACH(spec
, s
, p
->specs
)
602 path_spec_mkdir(s
, p
->directory_mode
);
605 static int path_start(Unit
*u
) {
610 assert(IN_SET(p
->state
, PATH_DEAD
, PATH_FAILED
));
612 r
= unit_test_trigger_loaded(u
);
616 r
= unit_acquire_invocation_id(u
);
622 p
->result
= PATH_SUCCESS
;
623 path_enter_waiting(p
, true, false);
628 static int path_stop(Unit
*u
) {
632 assert(IN_SET(p
->state
, PATH_WAITING
, PATH_RUNNING
));
634 path_enter_dead(p
, PATH_SUCCESS
);
638 static int path_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
646 (void) serialize_item(f
, "state", path_state_to_string(p
->state
));
647 (void) serialize_item(f
, "result", path_result_to_string(p
->result
));
649 LIST_FOREACH(spec
, s
, p
->specs
) {
651 _cleanup_free_
char *escaped
= NULL
;
653 escaped
= cescape(s
->path
);
657 assert_se(type
= path_type_to_string(s
->type
));
658 (void) serialize_item_format(f
, "path-spec", "%s %i %s",
667 static int path_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
675 if (streq(key
, "state")) {
678 state
= path_state_from_string(value
);
680 log_unit_debug(u
, "Failed to parse state value: %s", value
);
682 p
->deserialized_state
= state
;
684 } else if (streq(key
, "result")) {
687 f
= path_result_from_string(value
);
689 log_unit_debug(u
, "Failed to parse result value: %s", value
);
690 else if (f
!= PATH_SUCCESS
)
693 } else if (streq(key
, "path-spec")) {
694 int previous_exists
, skip
= 0;
695 _cleanup_free_
char *type_str
= NULL
;
697 if (sscanf(value
, "%ms %i %n", &type_str
, &previous_exists
, &skip
) < 2)
698 log_unit_debug(u
, "Failed to parse path-spec value: %s", value
);
700 _cleanup_free_
char *unescaped
= NULL
;
705 type
= path_type_from_string(type_str
);
707 log_unit_warning(u
, "Unknown path type \"%s\", ignoring.", type_str
);
711 l
= cunescape(value
+skip
, 0, &unescaped
);
713 log_unit_warning_errno(u
, l
, "Failed to unescape serialize path: %m");
717 LIST_FOREACH(spec
, s
, p
->specs
)
718 if (s
->type
== type
&&
719 path_equal(s
->path
, unescaped
)) {
721 s
->previous_exists
= previous_exists
;
727 log_unit_debug(u
, "Unknown serialization key: %s", key
);
732 _pure_
static UnitActiveState
path_active_state(Unit
*u
) {
735 return state_translation_table
[PATH(u
)->state
];
738 _pure_
static const char *path_sub_state_to_string(Unit
*u
) {
741 return path_state_to_string(PATH(u
)->state
);
744 static int path_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
745 PathSpec
*s
= userdata
;
755 if (!IN_SET(p
->state
, PATH_WAITING
, PATH_RUNNING
))
758 /* log_debug("inotify wakeup on %s.", UNIT(p)->id); */
760 LIST_FOREACH(spec
, s
, p
->specs
)
761 if (path_spec_owns_inotify_fd(s
, fd
))
765 log_error("Got event on unknown fd.");
769 changed
= path_spec_fd_event(s
, revents
);
774 path_enter_running(p
);
776 path_enter_waiting(p
, false, false);
781 path_enter_dead(p
, PATH_FAILURE_RESOURCES
);
785 static void path_trigger_notify(Unit
*u
, Unit
*other
) {
791 /* Invoked whenever the unit we trigger changes state or gains or loses a job */
793 /* Filter out invocations with bogus state */
794 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
796 /* Don't propagate state changes from the triggered unit if we are already down */
797 if (!IN_SET(p
->state
, PATH_WAITING
, PATH_RUNNING
))
800 /* Propagate start limit hit state */
801 if (other
->start_limit_hit
) {
802 path_enter_dead(p
, PATH_FAILURE_UNIT_START_LIMIT_HIT
);
806 /* Don't propagate anything if there's still a job queued */
810 if (p
->state
== PATH_RUNNING
&&
811 UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
))) {
812 log_unit_debug(UNIT(p
), "Got notified about unit deactivation.");
813 path_enter_waiting(p
, false, true);
814 } else if (p
->state
== PATH_WAITING
&&
815 !UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
))) {
816 log_unit_debug(UNIT(p
), "Got notified about unit activation.");
817 path_enter_waiting(p
, false, true);
821 static void path_reset_failed(Unit
*u
) {
826 if (p
->state
== PATH_FAILED
)
827 path_set_state(p
, PATH_DEAD
);
829 p
->result
= PATH_SUCCESS
;
832 static int path_can_start(Unit
*u
) {
838 r
= unit_test_start_limit(u
);
840 path_enter_dead(p
, PATH_FAILURE_START_LIMIT_HIT
);
847 static const char* const path_type_table
[_PATH_TYPE_MAX
] = {
848 [PATH_EXISTS
] = "PathExists",
849 [PATH_EXISTS_GLOB
] = "PathExistsGlob",
850 [PATH_DIRECTORY_NOT_EMPTY
] = "DirectoryNotEmpty",
851 [PATH_CHANGED
] = "PathChanged",
852 [PATH_MODIFIED
] = "PathModified",
855 DEFINE_STRING_TABLE_LOOKUP(path_type
, PathType
);
857 static const char* const path_result_table
[_PATH_RESULT_MAX
] = {
858 [PATH_SUCCESS
] = "success",
859 [PATH_FAILURE_RESOURCES
] = "resources",
860 [PATH_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
861 [PATH_FAILURE_UNIT_START_LIMIT_HIT
] = "unit-start-limit-hit",
862 [PATH_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
865 DEFINE_STRING_TABLE_LOOKUP(path_result
, PathResult
);
867 const UnitVTable path_vtable
= {
868 .object_size
= sizeof(Path
),
874 .private_section
= "Path",
876 .can_transient
= true,
884 .coldplug
= path_coldplug
,
891 .serialize
= path_serialize
,
892 .deserialize_item
= path_deserialize_item
,
894 .active_state
= path_active_state
,
895 .sub_state_to_string
= path_sub_state_to_string
,
897 .trigger_notify
= path_trigger_notify
,
899 .reset_failed
= path_reset_failed
,
901 .bus_set_property
= bus_path_set_property
,
903 .can_start
= path_can_start
,