]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/path.c
tree-wide: remove Lennart's copyright lines
[thirdparty/systemd.git] / src / core / path.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <sys/epoll.h>
5 #include <sys/inotify.h>
6 #include <unistd.h>
7
8 #include "bus-error.h"
9 #include "bus-util.h"
10 #include "dbus-path.h"
11 #include "fd-util.h"
12 #include "fs-util.h"
13 #include "glob-util.h"
14 #include "macro.h"
15 #include "mkdir.h"
16 #include "path.h"
17 #include "special.h"
18 #include "stat-util.h"
19 #include "string-table.h"
20 #include "string-util.h"
21 #include "unit-name.h"
22 #include "unit.h"
23
24 static const UnitActiveState state_translation_table[_PATH_STATE_MAX] = {
25 [PATH_DEAD] = UNIT_INACTIVE,
26 [PATH_WAITING] = UNIT_ACTIVE,
27 [PATH_RUNNING] = UNIT_ACTIVE,
28 [PATH_FAILED] = UNIT_FAILED
29 };
30
31 static int path_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
32
33 int path_spec_watch(PathSpec *s, sd_event_io_handler_t handler) {
34
35 static const int flags_table[_PATH_TYPE_MAX] = {
36 [PATH_EXISTS] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
37 [PATH_EXISTS_GLOB] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
38 [PATH_CHANGED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO,
39 [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,
40 [PATH_DIRECTORY_NOT_EMPTY] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO
41 };
42
43 bool exists = false;
44 char *slash, *oldslash = NULL;
45 int r;
46
47 assert(s);
48 assert(s->unit);
49 assert(handler);
50
51 path_spec_unwatch(s);
52
53 s->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
54 if (s->inotify_fd < 0) {
55 r = -errno;
56 goto fail;
57 }
58
59 r = sd_event_add_io(s->unit->manager->event, &s->event_source, s->inotify_fd, EPOLLIN, handler, s);
60 if (r < 0)
61 goto fail;
62
63 (void) sd_event_source_set_description(s->event_source, "path");
64
65 /* This function assumes the path was passed through path_simplify()! */
66 assert(!strstr(s->path, "//"));
67
68 for (slash = strchr(s->path, '/'); ; slash = strchr(slash+1, '/')) {
69 char *cut = NULL;
70 int flags;
71 char tmp;
72
73 if (slash) {
74 cut = slash + (slash == s->path);
75 tmp = *cut;
76 *cut = '\0';
77
78 flags = IN_MOVE_SELF | IN_DELETE_SELF | IN_ATTRIB | IN_CREATE | IN_MOVED_TO;
79 } else
80 flags = flags_table[s->type];
81
82 r = inotify_add_watch(s->inotify_fd, s->path, flags);
83 if (r < 0) {
84 if (IN_SET(errno, EACCES, ENOENT)) {
85 if (cut)
86 *cut = tmp;
87 break;
88 }
89
90 r = log_warning_errno(errno, "Failed to add watch on %s: %s", s->path, errno == ENOSPC ? "too many watches" : strerror(-r));
91 if (cut)
92 *cut = tmp;
93 goto fail;
94 } else {
95 exists = true;
96
97 /* Path exists, we don't need to watch parent too closely. */
98 if (oldslash) {
99 char *cut2 = oldslash + (oldslash == s->path);
100 char tmp2 = *cut2;
101 *cut2 = '\0';
102
103 (void) inotify_add_watch(s->inotify_fd, s->path, IN_MOVE_SELF);
104 /* Error is ignored, the worst can happen is we get spurious events. */
105
106 *cut2 = tmp2;
107 }
108 }
109
110 if (cut)
111 *cut = tmp;
112
113 if (slash)
114 oldslash = slash;
115 else {
116 /* whole path has been iterated over */
117 s->primary_wd = r;
118 break;
119 }
120 }
121
122 if (!exists) {
123 r = log_error_errno(errno, "Failed to add watch on any of the components of %s: %m", s->path);
124 /* either EACCESS or ENOENT */
125 goto fail;
126 }
127
128 return 0;
129
130 fail:
131 path_spec_unwatch(s);
132 return r;
133 }
134
135 void path_spec_unwatch(PathSpec *s) {
136 assert(s);
137
138 s->event_source = sd_event_source_unref(s->event_source);
139 s->inotify_fd = safe_close(s->inotify_fd);
140 }
141
142 int path_spec_fd_event(PathSpec *s, uint32_t revents) {
143 union inotify_event_buffer buffer;
144 struct inotify_event *e;
145 ssize_t l;
146 int r = 0;
147
148 if (revents != EPOLLIN) {
149 log_error("Got invalid poll event on inotify.");
150 return -EINVAL;
151 }
152
153 l = read(s->inotify_fd, &buffer, sizeof(buffer));
154 if (l < 0) {
155 if (IN_SET(errno, EAGAIN, EINTR))
156 return 0;
157
158 return log_error_errno(errno, "Failed to read inotify event: %m");
159 }
160
161 FOREACH_INOTIFY_EVENT(e, buffer, l) {
162 if (IN_SET(s->type, PATH_CHANGED, PATH_MODIFIED) &&
163 s->primary_wd == e->wd)
164 r = 1;
165 }
166
167 return r;
168 }
169
170 static bool path_spec_check_good(PathSpec *s, bool initial) {
171 bool good = false;
172
173 switch (s->type) {
174
175 case PATH_EXISTS:
176 good = access(s->path, F_OK) >= 0;
177 break;
178
179 case PATH_EXISTS_GLOB:
180 good = glob_exists(s->path) > 0;
181 break;
182
183 case PATH_DIRECTORY_NOT_EMPTY: {
184 int k;
185
186 k = dir_is_empty(s->path);
187 good = !(k == -ENOENT || k > 0);
188 break;
189 }
190
191 case PATH_CHANGED:
192 case PATH_MODIFIED: {
193 bool b;
194
195 b = access(s->path, F_OK) >= 0;
196 good = !initial && b != s->previous_exists;
197 s->previous_exists = b;
198 break;
199 }
200
201 default:
202 ;
203 }
204
205 return good;
206 }
207
208 static void path_spec_mkdir(PathSpec *s, mode_t mode) {
209 int r;
210
211 if (IN_SET(s->type, PATH_EXISTS, PATH_EXISTS_GLOB))
212 return;
213
214 r = mkdir_p_label(s->path, mode);
215 if (r < 0)
216 log_warning_errno(r, "mkdir(%s) failed: %m", s->path);
217 }
218
219 static void path_spec_dump(PathSpec *s, FILE *f, const char *prefix) {
220 fprintf(f,
221 "%s%s: %s\n",
222 prefix,
223 path_type_to_string(s->type),
224 s->path);
225 }
226
227 void path_spec_done(PathSpec *s) {
228 assert(s);
229 assert(s->inotify_fd == -1);
230
231 free(s->path);
232 }
233
234 static void path_init(Unit *u) {
235 Path *p = PATH(u);
236
237 assert(u);
238 assert(u->load_state == UNIT_STUB);
239
240 p->directory_mode = 0755;
241 }
242
243 void path_free_specs(Path *p) {
244 PathSpec *s;
245
246 assert(p);
247
248 while ((s = p->specs)) {
249 path_spec_unwatch(s);
250 LIST_REMOVE(spec, p->specs, s);
251 path_spec_done(s);
252 free(s);
253 }
254 }
255
256 static void path_done(Unit *u) {
257 Path *p = PATH(u);
258
259 assert(p);
260
261 path_free_specs(p);
262 }
263
264 static int path_add_mount_dependencies(Path *p) {
265 PathSpec *s;
266 int r;
267
268 assert(p);
269
270 LIST_FOREACH(spec, s, p->specs) {
271 r = unit_require_mounts_for(UNIT(p), s->path, UNIT_DEPENDENCY_FILE);
272 if (r < 0)
273 return r;
274 }
275
276 return 0;
277 }
278
279 static int path_verify(Path *p) {
280 assert(p);
281
282 if (UNIT(p)->load_state != UNIT_LOADED)
283 return 0;
284
285 if (!p->specs) {
286 log_unit_error(UNIT(p), "Path unit lacks path setting. Refusing.");
287 return -ENOEXEC;
288 }
289
290 return 0;
291 }
292
293 static int path_add_default_dependencies(Path *p) {
294 int r;
295
296 assert(p);
297
298 if (!UNIT(p)->default_dependencies)
299 return 0;
300
301 r = unit_add_dependency_by_name(UNIT(p), UNIT_BEFORE, SPECIAL_PATHS_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT);
302 if (r < 0)
303 return r;
304
305 if (MANAGER_IS_SYSTEM(UNIT(p)->manager)) {
306 r = unit_add_two_dependencies_by_name(UNIT(p), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT);
307 if (r < 0)
308 return r;
309 }
310
311 return unit_add_two_dependencies_by_name(UNIT(p), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT);
312 }
313
314 static int path_add_trigger_dependencies(Path *p) {
315 Unit *x;
316 int r;
317
318 assert(p);
319
320 if (!hashmap_isempty(UNIT(p)->dependencies[UNIT_TRIGGERS]))
321 return 0;
322
323 r = unit_load_related_unit(UNIT(p), ".service", &x);
324 if (r < 0)
325 return r;
326
327 return unit_add_two_dependencies(UNIT(p), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
328 }
329
330 static int path_load(Unit *u) {
331 Path *p = PATH(u);
332 int r;
333
334 assert(u);
335 assert(u->load_state == UNIT_STUB);
336
337 r = unit_load_fragment_and_dropin(u);
338 if (r < 0)
339 return r;
340
341 if (u->load_state == UNIT_LOADED) {
342
343 r = path_add_trigger_dependencies(p);
344 if (r < 0)
345 return r;
346
347 r = path_add_mount_dependencies(p);
348 if (r < 0)
349 return r;
350
351 r = path_add_default_dependencies(p);
352 if (r < 0)
353 return r;
354 }
355
356 return path_verify(p);
357 }
358
359 static void path_dump(Unit *u, FILE *f, const char *prefix) {
360 Path *p = PATH(u);
361 Unit *trigger;
362 PathSpec *s;
363
364 assert(p);
365 assert(f);
366
367 trigger = UNIT_TRIGGER(u);
368
369 fprintf(f,
370 "%sPath State: %s\n"
371 "%sResult: %s\n"
372 "%sUnit: %s\n"
373 "%sMakeDirectory: %s\n"
374 "%sDirectoryMode: %04o\n",
375 prefix, path_state_to_string(p->state),
376 prefix, path_result_to_string(p->result),
377 prefix, trigger ? trigger->id : "n/a",
378 prefix, yes_no(p->make_directory),
379 prefix, p->directory_mode);
380
381 LIST_FOREACH(spec, s, p->specs)
382 path_spec_dump(s, f, prefix);
383 }
384
385 static void path_unwatch(Path *p) {
386 PathSpec *s;
387
388 assert(p);
389
390 LIST_FOREACH(spec, s, p->specs)
391 path_spec_unwatch(s);
392 }
393
394 static int path_watch(Path *p) {
395 int r;
396 PathSpec *s;
397
398 assert(p);
399
400 LIST_FOREACH(spec, s, p->specs) {
401 r = path_spec_watch(s, path_dispatch_io);
402 if (r < 0)
403 return r;
404 }
405
406 return 0;
407 }
408
409 static void path_set_state(Path *p, PathState state) {
410 PathState old_state;
411 assert(p);
412
413 old_state = p->state;
414 p->state = state;
415
416 if (state != PATH_WAITING &&
417 (state != PATH_RUNNING || p->inotify_triggered))
418 path_unwatch(p);
419
420 if (state != old_state)
421 log_unit_debug(UNIT(p), "Changed %s -> %s", path_state_to_string(old_state), path_state_to_string(state));
422
423 unit_notify(UNIT(p), state_translation_table[old_state], state_translation_table[state], 0);
424 }
425
426 static void path_enter_waiting(Path *p, bool initial, bool recheck);
427
428 static int path_coldplug(Unit *u) {
429 Path *p = PATH(u);
430
431 assert(p);
432 assert(p->state == PATH_DEAD);
433
434 if (p->deserialized_state != p->state) {
435
436 if (IN_SET(p->deserialized_state, PATH_WAITING, PATH_RUNNING))
437 path_enter_waiting(p, true, true);
438 else
439 path_set_state(p, p->deserialized_state);
440 }
441
442 return 0;
443 }
444
445 static void path_enter_dead(Path *p, PathResult f) {
446 assert(p);
447
448 if (p->result == PATH_SUCCESS)
449 p->result = f;
450
451 if (p->result != PATH_SUCCESS)
452 log_unit_warning(UNIT(p), "Failed with result '%s'.", path_result_to_string(p->result));
453
454 path_set_state(p, p->result != PATH_SUCCESS ? PATH_FAILED : PATH_DEAD);
455 }
456
457 static void path_enter_running(Path *p) {
458 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
459 Unit *trigger;
460 int r;
461
462 assert(p);
463
464 /* Don't start job if we are supposed to go down */
465 if (unit_stop_pending(UNIT(p)))
466 return;
467
468 trigger = UNIT_TRIGGER(UNIT(p));
469 if (!trigger) {
470 log_unit_error(UNIT(p), "Unit to trigger vanished.");
471 path_enter_dead(p, PATH_FAILURE_RESOURCES);
472 return;
473 }
474
475 r = manager_add_job(UNIT(p)->manager, JOB_START, trigger, JOB_REPLACE, &error, NULL);
476 if (r < 0)
477 goto fail;
478
479 p->inotify_triggered = false;
480
481 r = path_watch(p);
482 if (r < 0)
483 goto fail;
484
485 path_set_state(p, PATH_RUNNING);
486 return;
487
488 fail:
489 log_unit_warning(UNIT(p), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
490 path_enter_dead(p, PATH_FAILURE_RESOURCES);
491 }
492
493 static bool path_check_good(Path *p, bool initial) {
494 PathSpec *s;
495 bool good = false;
496
497 assert(p);
498
499 LIST_FOREACH(spec, s, p->specs) {
500 good = path_spec_check_good(s, initial);
501
502 if (good)
503 break;
504 }
505
506 return good;
507 }
508
509 static void path_enter_waiting(Path *p, bool initial, bool recheck) {
510 int r;
511
512 if (recheck)
513 if (path_check_good(p, initial)) {
514 log_unit_debug(UNIT(p), "Got triggered.");
515 path_enter_running(p);
516 return;
517 }
518
519 r = path_watch(p);
520 if (r < 0)
521 goto fail;
522
523 /* Hmm, so now we have created inotify watches, but the file
524 * might have appeared/been removed by now, so we must
525 * recheck */
526
527 if (recheck)
528 if (path_check_good(p, false)) {
529 log_unit_debug(UNIT(p), "Got triggered.");
530 path_enter_running(p);
531 return;
532 }
533
534 path_set_state(p, PATH_WAITING);
535 return;
536
537 fail:
538 log_unit_warning_errno(UNIT(p), r, "Failed to enter waiting state: %m");
539 path_enter_dead(p, PATH_FAILURE_RESOURCES);
540 }
541
542 static void path_mkdir(Path *p) {
543 PathSpec *s;
544
545 assert(p);
546
547 if (!p->make_directory)
548 return;
549
550 LIST_FOREACH(spec, s, p->specs)
551 path_spec_mkdir(s, p->directory_mode);
552 }
553
554 static int path_start(Unit *u) {
555 Path *p = PATH(u);
556 Unit *trigger;
557 int r;
558
559 assert(p);
560 assert(IN_SET(p->state, PATH_DEAD, PATH_FAILED));
561
562 trigger = UNIT_TRIGGER(u);
563 if (!trigger || trigger->load_state != UNIT_LOADED) {
564 log_unit_error(u, "Refusing to start, unit to trigger not loaded.");
565 return -ENOENT;
566 }
567
568 r = unit_start_limit_test(u);
569 if (r < 0) {
570 path_enter_dead(p, PATH_FAILURE_START_LIMIT_HIT);
571 return r;
572 }
573
574 r = unit_acquire_invocation_id(u);
575 if (r < 0)
576 return r;
577
578 path_mkdir(p);
579
580 p->result = PATH_SUCCESS;
581 path_enter_waiting(p, true, true);
582
583 return 1;
584 }
585
586 static int path_stop(Unit *u) {
587 Path *p = PATH(u);
588
589 assert(p);
590 assert(IN_SET(p->state, PATH_WAITING, PATH_RUNNING));
591
592 path_enter_dead(p, PATH_SUCCESS);
593 return 1;
594 }
595
596 static int path_serialize(Unit *u, FILE *f, FDSet *fds) {
597 Path *p = PATH(u);
598
599 assert(u);
600 assert(f);
601 assert(fds);
602
603 unit_serialize_item(u, f, "state", path_state_to_string(p->state));
604 unit_serialize_item(u, f, "result", path_result_to_string(p->result));
605
606 return 0;
607 }
608
609 static int path_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
610 Path *p = PATH(u);
611
612 assert(u);
613 assert(key);
614 assert(value);
615 assert(fds);
616
617 if (streq(key, "state")) {
618 PathState state;
619
620 state = path_state_from_string(value);
621 if (state < 0)
622 log_unit_debug(u, "Failed to parse state value: %s", value);
623 else
624 p->deserialized_state = state;
625
626 } else if (streq(key, "result")) {
627 PathResult f;
628
629 f = path_result_from_string(value);
630 if (f < 0)
631 log_unit_debug(u, "Failed to parse result value: %s", value);
632 else if (f != PATH_SUCCESS)
633 p->result = f;
634
635 } else
636 log_unit_debug(u, "Unknown serialization key: %s", key);
637
638 return 0;
639 }
640
641 _pure_ static UnitActiveState path_active_state(Unit *u) {
642 assert(u);
643
644 return state_translation_table[PATH(u)->state];
645 }
646
647 _pure_ static const char *path_sub_state_to_string(Unit *u) {
648 assert(u);
649
650 return path_state_to_string(PATH(u)->state);
651 }
652
653 static int path_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
654 PathSpec *s = userdata;
655 Path *p;
656 int changed;
657
658 assert(s);
659 assert(s->unit);
660 assert(fd >= 0);
661
662 p = PATH(s->unit);
663
664 if (!IN_SET(p->state, PATH_WAITING, PATH_RUNNING))
665 return 0;
666
667 /* log_debug("inotify wakeup on %s.", u->id); */
668
669 LIST_FOREACH(spec, s, p->specs)
670 if (path_spec_owns_inotify_fd(s, fd))
671 break;
672
673 if (!s) {
674 log_error("Got event on unknown fd.");
675 goto fail;
676 }
677
678 changed = path_spec_fd_event(s, revents);
679 if (changed < 0)
680 goto fail;
681
682 /* If we are already running, then remember that one event was
683 * dispatched so that we restart the service only if something
684 * actually changed on disk */
685 p->inotify_triggered = true;
686
687 if (changed)
688 path_enter_running(p);
689 else
690 path_enter_waiting(p, false, true);
691
692 return 0;
693
694 fail:
695 path_enter_dead(p, PATH_FAILURE_RESOURCES);
696 return 0;
697 }
698
699 static void path_trigger_notify(Unit *u, Unit *other) {
700 Path *p = PATH(u);
701
702 assert(u);
703 assert(other);
704
705 /* Invoked whenever the unit we trigger changes state or gains
706 * or loses a job */
707
708 if (other->load_state != UNIT_LOADED)
709 return;
710
711 if (p->state == PATH_RUNNING &&
712 UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
713 log_unit_debug(UNIT(p), "Got notified about unit deactivation.");
714
715 /* Hmm, so inotify was triggered since the
716 * last activation, so I guess we need to
717 * recheck what is going on. */
718 path_enter_waiting(p, false, p->inotify_triggered);
719 }
720 }
721
722 static void path_reset_failed(Unit *u) {
723 Path *p = PATH(u);
724
725 assert(p);
726
727 if (p->state == PATH_FAILED)
728 path_set_state(p, PATH_DEAD);
729
730 p->result = PATH_SUCCESS;
731 }
732
733 static const char* const path_type_table[_PATH_TYPE_MAX] = {
734 [PATH_EXISTS] = "PathExists",
735 [PATH_EXISTS_GLOB] = "PathExistsGlob",
736 [PATH_DIRECTORY_NOT_EMPTY] = "DirectoryNotEmpty",
737 [PATH_CHANGED] = "PathChanged",
738 [PATH_MODIFIED] = "PathModified",
739 };
740
741 DEFINE_STRING_TABLE_LOOKUP(path_type, PathType);
742
743 static const char* const path_result_table[_PATH_RESULT_MAX] = {
744 [PATH_SUCCESS] = "success",
745 [PATH_FAILURE_RESOURCES] = "resources",
746 [PATH_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
747 };
748
749 DEFINE_STRING_TABLE_LOOKUP(path_result, PathResult);
750
751 const UnitVTable path_vtable = {
752 .object_size = sizeof(Path),
753
754 .sections =
755 "Unit\0"
756 "Path\0"
757 "Install\0",
758 .private_section = "Path",
759
760 .can_transient = true,
761
762 .init = path_init,
763 .done = path_done,
764 .load = path_load,
765
766 .coldplug = path_coldplug,
767
768 .dump = path_dump,
769
770 .start = path_start,
771 .stop = path_stop,
772
773 .serialize = path_serialize,
774 .deserialize_item = path_deserialize_item,
775
776 .active_state = path_active_state,
777 .sub_state_to_string = path_sub_state_to_string,
778
779 .trigger_notify = path_trigger_notify,
780
781 .reset_failed = path_reset_failed,
782
783 .bus_vtable = bus_path_vtable,
784 .bus_set_property = bus_path_set_property,
785 };