]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/path.c
coccinelle: make use of SYNTHETIC_ERRNO
[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 "serialize.h"
18 #include "special.h"
19 #include "stat-util.h"
20 #include "string-table.h"
21 #include "string-util.h"
22 #include "unit-name.h"
23 #include "unit.h"
24
25 static const UnitActiveState state_translation_table[_PATH_STATE_MAX] = {
26 [PATH_DEAD] = UNIT_INACTIVE,
27 [PATH_WAITING] = UNIT_ACTIVE,
28 [PATH_RUNNING] = UNIT_ACTIVE,
29 [PATH_FAILED] = UNIT_FAILED
30 };
31
32 static int path_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
33
34 int path_spec_watch(PathSpec *s, sd_event_io_handler_t handler) {
35
36 static const int flags_table[_PATH_TYPE_MAX] = {
37 [PATH_EXISTS] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
38 [PATH_EXISTS_GLOB] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
39 [PATH_CHANGED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO,
40 [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,
41 [PATH_DIRECTORY_NOT_EMPTY] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO
42 };
43
44 bool exists = false;
45 char *slash, *oldslash = NULL;
46 int r;
47
48 assert(s);
49 assert(s->unit);
50 assert(handler);
51
52 path_spec_unwatch(s);
53
54 s->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
55 if (s->inotify_fd < 0) {
56 r = -errno;
57 goto fail;
58 }
59
60 r = sd_event_add_io(s->unit->manager->event, &s->event_source, s->inotify_fd, EPOLLIN, handler, s);
61 if (r < 0)
62 goto fail;
63
64 (void) sd_event_source_set_description(s->event_source, "path");
65
66 /* This function assumes the path was passed through path_simplify()! */
67 assert(!strstr(s->path, "//"));
68
69 for (slash = strchr(s->path, '/'); ; slash = strchr(slash+1, '/')) {
70 char *cut = NULL;
71 int flags;
72 char tmp;
73
74 if (slash) {
75 cut = slash + (slash == s->path);
76 tmp = *cut;
77 *cut = '\0';
78
79 flags = IN_MOVE_SELF | IN_DELETE_SELF | IN_ATTRIB | IN_CREATE | IN_MOVED_TO;
80 } else
81 flags = flags_table[s->type];
82
83 r = inotify_add_watch(s->inotify_fd, s->path, flags);
84 if (r < 0) {
85 if (IN_SET(errno, EACCES, ENOENT)) {
86 if (cut)
87 *cut = tmp;
88 break;
89 }
90
91 r = log_warning_errno(errno, "Failed to add watch on %s: %s", s->path, errno == ENOSPC ? "too many watches" : strerror(-r));
92 if (cut)
93 *cut = tmp;
94 goto fail;
95 } else {
96 exists = true;
97
98 /* Path exists, we don't need to watch parent too closely. */
99 if (oldslash) {
100 char *cut2 = oldslash + (oldslash == s->path);
101 char tmp2 = *cut2;
102 *cut2 = '\0';
103
104 (void) inotify_add_watch(s->inotify_fd, s->path, IN_MOVE_SELF);
105 /* Error is ignored, the worst can happen is we get spurious events. */
106
107 *cut2 = tmp2;
108 }
109 }
110
111 if (cut)
112 *cut = tmp;
113
114 if (slash)
115 oldslash = slash;
116 else {
117 /* whole path has been iterated over */
118 s->primary_wd = r;
119 break;
120 }
121 }
122
123 if (!exists) {
124 r = log_error_errno(errno, "Failed to add watch on any of the components of %s: %m", s->path);
125 /* either EACCESS or ENOENT */
126 goto fail;
127 }
128
129 return 0;
130
131 fail:
132 path_spec_unwatch(s);
133 return r;
134 }
135
136 void path_spec_unwatch(PathSpec *s) {
137 assert(s);
138
139 s->event_source = sd_event_source_unref(s->event_source);
140 s->inotify_fd = safe_close(s->inotify_fd);
141 }
142
143 int path_spec_fd_event(PathSpec *s, uint32_t revents) {
144 union inotify_event_buffer buffer;
145 struct inotify_event *e;
146 ssize_t l;
147 int r = 0;
148
149 if (revents != EPOLLIN)
150 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
151 "Got invalid poll event on inotify.");
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, 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, 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, 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 unit_log_result(UNIT(p), p->result == PATH_SUCCESS, path_result_to_string(p->result));
452 path_set_state(p, p->result != PATH_SUCCESS ? PATH_FAILED : PATH_DEAD);
453 }
454
455 static void path_enter_running(Path *p) {
456 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
457 Unit *trigger;
458 int r;
459
460 assert(p);
461
462 /* Don't start job if we are supposed to go down */
463 if (unit_stop_pending(UNIT(p)))
464 return;
465
466 trigger = UNIT_TRIGGER(UNIT(p));
467 if (!trigger) {
468 log_unit_error(UNIT(p), "Unit to trigger vanished.");
469 path_enter_dead(p, PATH_FAILURE_RESOURCES);
470 return;
471 }
472
473 r = manager_add_job(UNIT(p)->manager, JOB_START, trigger, JOB_REPLACE, &error, NULL);
474 if (r < 0)
475 goto fail;
476
477 p->inotify_triggered = false;
478
479 r = path_watch(p);
480 if (r < 0)
481 goto fail;
482
483 path_set_state(p, PATH_RUNNING);
484 return;
485
486 fail:
487 log_unit_warning(UNIT(p), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
488 path_enter_dead(p, PATH_FAILURE_RESOURCES);
489 }
490
491 static bool path_check_good(Path *p, bool initial) {
492 PathSpec *s;
493 bool good = false;
494
495 assert(p);
496
497 LIST_FOREACH(spec, s, p->specs) {
498 good = path_spec_check_good(s, initial);
499
500 if (good)
501 break;
502 }
503
504 return good;
505 }
506
507 static void path_enter_waiting(Path *p, bool initial, bool recheck) {
508 int r;
509
510 if (recheck)
511 if (path_check_good(p, initial)) {
512 log_unit_debug(UNIT(p), "Got triggered.");
513 path_enter_running(p);
514 return;
515 }
516
517 r = path_watch(p);
518 if (r < 0)
519 goto fail;
520
521 /* Hmm, so now we have created inotify watches, but the file
522 * might have appeared/been removed by now, so we must
523 * recheck */
524
525 if (recheck)
526 if (path_check_good(p, false)) {
527 log_unit_debug(UNIT(p), "Got triggered.");
528 path_enter_running(p);
529 return;
530 }
531
532 path_set_state(p, PATH_WAITING);
533 return;
534
535 fail:
536 log_unit_warning_errno(UNIT(p), r, "Failed to enter waiting state: %m");
537 path_enter_dead(p, PATH_FAILURE_RESOURCES);
538 }
539
540 static void path_mkdir(Path *p) {
541 PathSpec *s;
542
543 assert(p);
544
545 if (!p->make_directory)
546 return;
547
548 LIST_FOREACH(spec, s, p->specs)
549 path_spec_mkdir(s, p->directory_mode);
550 }
551
552 static int path_start(Unit *u) {
553 Path *p = PATH(u);
554 Unit *trigger;
555 int r;
556
557 assert(p);
558 assert(IN_SET(p->state, PATH_DEAD, PATH_FAILED));
559
560 trigger = UNIT_TRIGGER(u);
561 if (!trigger || trigger->load_state != UNIT_LOADED) {
562 log_unit_error(u, "Refusing to start, unit to trigger not loaded.");
563 return -ENOENT;
564 }
565
566 r = unit_start_limit_test(u);
567 if (r < 0) {
568 path_enter_dead(p, PATH_FAILURE_START_LIMIT_HIT);
569 return r;
570 }
571
572 r = unit_acquire_invocation_id(u);
573 if (r < 0)
574 return r;
575
576 path_mkdir(p);
577
578 p->result = PATH_SUCCESS;
579 path_enter_waiting(p, true, true);
580
581 return 1;
582 }
583
584 static int path_stop(Unit *u) {
585 Path *p = PATH(u);
586
587 assert(p);
588 assert(IN_SET(p->state, PATH_WAITING, PATH_RUNNING));
589
590 path_enter_dead(p, PATH_SUCCESS);
591 return 1;
592 }
593
594 static int path_serialize(Unit *u, FILE *f, FDSet *fds) {
595 Path *p = PATH(u);
596
597 assert(u);
598 assert(f);
599 assert(fds);
600
601 (void) serialize_item(f, "state", path_state_to_string(p->state));
602 (void) serialize_item(f, "result", path_result_to_string(p->result));
603
604 return 0;
605 }
606
607 static int path_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
608 Path *p = PATH(u);
609
610 assert(u);
611 assert(key);
612 assert(value);
613 assert(fds);
614
615 if (streq(key, "state")) {
616 PathState state;
617
618 state = path_state_from_string(value);
619 if (state < 0)
620 log_unit_debug(u, "Failed to parse state value: %s", value);
621 else
622 p->deserialized_state = state;
623
624 } else if (streq(key, "result")) {
625 PathResult f;
626
627 f = path_result_from_string(value);
628 if (f < 0)
629 log_unit_debug(u, "Failed to parse result value: %s", value);
630 else if (f != PATH_SUCCESS)
631 p->result = f;
632
633 } else
634 log_unit_debug(u, "Unknown serialization key: %s", key);
635
636 return 0;
637 }
638
639 _pure_ static UnitActiveState path_active_state(Unit *u) {
640 assert(u);
641
642 return state_translation_table[PATH(u)->state];
643 }
644
645 _pure_ static const char *path_sub_state_to_string(Unit *u) {
646 assert(u);
647
648 return path_state_to_string(PATH(u)->state);
649 }
650
651 static int path_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
652 PathSpec *s = userdata;
653 Path *p;
654 int changed;
655
656 assert(s);
657 assert(s->unit);
658 assert(fd >= 0);
659
660 p = PATH(s->unit);
661
662 if (!IN_SET(p->state, PATH_WAITING, PATH_RUNNING))
663 return 0;
664
665 /* log_debug("inotify wakeup on %s.", u->id); */
666
667 LIST_FOREACH(spec, s, p->specs)
668 if (path_spec_owns_inotify_fd(s, fd))
669 break;
670
671 if (!s) {
672 log_error("Got event on unknown fd.");
673 goto fail;
674 }
675
676 changed = path_spec_fd_event(s, revents);
677 if (changed < 0)
678 goto fail;
679
680 /* If we are already running, then remember that one event was
681 * dispatched so that we restart the service only if something
682 * actually changed on disk */
683 p->inotify_triggered = true;
684
685 if (changed)
686 path_enter_running(p);
687 else
688 path_enter_waiting(p, false, true);
689
690 return 0;
691
692 fail:
693 path_enter_dead(p, PATH_FAILURE_RESOURCES);
694 return 0;
695 }
696
697 static void path_trigger_notify(Unit *u, Unit *other) {
698 Path *p = PATH(u);
699
700 assert(u);
701 assert(other);
702
703 /* Invoked whenever the unit we trigger changes state or gains
704 * or loses a job */
705
706 if (other->load_state != UNIT_LOADED)
707 return;
708
709 if (p->state == PATH_RUNNING &&
710 UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
711 log_unit_debug(UNIT(p), "Got notified about unit deactivation.");
712
713 /* Hmm, so inotify was triggered since the
714 * last activation, so I guess we need to
715 * recheck what is going on. */
716 path_enter_waiting(p, false, p->inotify_triggered);
717 }
718 }
719
720 static void path_reset_failed(Unit *u) {
721 Path *p = PATH(u);
722
723 assert(p);
724
725 if (p->state == PATH_FAILED)
726 path_set_state(p, PATH_DEAD);
727
728 p->result = PATH_SUCCESS;
729 }
730
731 static const char* const path_type_table[_PATH_TYPE_MAX] = {
732 [PATH_EXISTS] = "PathExists",
733 [PATH_EXISTS_GLOB] = "PathExistsGlob",
734 [PATH_DIRECTORY_NOT_EMPTY] = "DirectoryNotEmpty",
735 [PATH_CHANGED] = "PathChanged",
736 [PATH_MODIFIED] = "PathModified",
737 };
738
739 DEFINE_STRING_TABLE_LOOKUP(path_type, PathType);
740
741 static const char* const path_result_table[_PATH_RESULT_MAX] = {
742 [PATH_SUCCESS] = "success",
743 [PATH_FAILURE_RESOURCES] = "resources",
744 [PATH_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
745 };
746
747 DEFINE_STRING_TABLE_LOOKUP(path_result, PathResult);
748
749 const UnitVTable path_vtable = {
750 .object_size = sizeof(Path),
751
752 .sections =
753 "Unit\0"
754 "Path\0"
755 "Install\0",
756 .private_section = "Path",
757
758 .can_transient = true,
759
760 .init = path_init,
761 .done = path_done,
762 .load = path_load,
763
764 .coldplug = path_coldplug,
765
766 .dump = path_dump,
767
768 .start = path_start,
769 .stop = path_stop,
770
771 .serialize = path_serialize,
772 .deserialize_item = path_deserialize_item,
773
774 .active_state = path_active_state,
775 .sub_state_to_string = path_sub_state_to_string,
776
777 .trigger_notify = path_trigger_notify,
778
779 .reset_failed = path_reset_failed,
780
781 .bus_vtable = bus_path_vtable,
782 .bus_set_property = bus_path_set_property,
783 };