chiark / gitweb /
binfmt: move sources to subdirectory
[elogind.git] / src / path.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/inotify.h>
23 #include <sys/epoll.h>
24 #include <sys/ioctl.h>
25 #include <errno.h>
26 #include <unistd.h>
27
28 #include "unit.h"
29 #include "unit-name.h"
30 #include "path.h"
31 #include "dbus-path.h"
32 #include "special.h"
33 #include "bus-errors.h"
34
35 static const UnitActiveState state_translation_table[_PATH_STATE_MAX] = {
36         [PATH_DEAD] = UNIT_INACTIVE,
37         [PATH_WAITING] = UNIT_ACTIVE,
38         [PATH_RUNNING] = UNIT_ACTIVE,
39         [PATH_FAILED] = UNIT_FAILED
40 };
41
42 int pathspec_watch(PathSpec *s, Unit *u) {
43         static const int flags_table[_PATH_TYPE_MAX] = {
44                 [PATH_EXISTS] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
45                 [PATH_EXISTS_GLOB] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB,
46                 [PATH_CHANGED] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CLOSE_WRITE|IN_CREATE|IN_DELETE|IN_MOVED_FROM|IN_MOVED_TO,
47                 [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,
48                 [PATH_DIRECTORY_NOT_EMPTY] = IN_DELETE_SELF|IN_MOVE_SELF|IN_ATTRIB|IN_CREATE|IN_MOVED_TO
49         };
50
51         bool exists = false;
52         char *k, *slash;
53         int r;
54
55         assert(u);
56         assert(s);
57
58         pathspec_unwatch(s, u);
59
60         if (!(k = strdup(s->path)))
61                 return -ENOMEM;
62
63         if ((s->inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC)) < 0) {
64                 r = -errno;
65                 goto fail;
66         }
67
68         if (unit_watch_fd(u, s->inotify_fd, EPOLLIN, &s->watch) < 0) {
69                 r = -errno;
70                 goto fail;
71         }
72
73         if ((s->primary_wd = inotify_add_watch(s->inotify_fd, k, flags_table[s->type])) >= 0)
74                 exists = true;
75
76         do {
77                 int flags;
78
79                 /* This assumes the path was passed through path_kill_slashes()! */
80                 if (!(slash = strrchr(k, '/')))
81                         break;
82
83                 /* Trim the path at the last slash. Keep the slash if it's the root dir. */
84                 slash[slash == k] = 0;
85
86                 flags = IN_MOVE_SELF;
87                 if (!exists)
88                         flags |= IN_DELETE_SELF | IN_ATTRIB | IN_CREATE | IN_MOVED_TO;
89
90                 if (inotify_add_watch(s->inotify_fd, k, flags) >= 0)
91                         exists = true;
92         } while (slash != k);
93
94         return 0;
95
96 fail:
97         free(k);
98
99         pathspec_unwatch(s, u);
100         return r;
101 }
102
103 void pathspec_unwatch(PathSpec *s, Unit *u) {
104
105         if (s->inotify_fd < 0)
106                 return;
107
108         unit_unwatch_fd(u, &s->watch);
109
110         close_nointr_nofail(s->inotify_fd);
111         s->inotify_fd = -1;
112 }
113
114 int pathspec_fd_event(PathSpec *s, uint32_t events) {
115         uint8_t *buf = NULL;
116         struct inotify_event *e;
117         ssize_t k;
118         int l;
119         int r = 0;
120
121         if (events != EPOLLIN) {
122                 log_error("Got Invalid poll event on inotify.");
123                 r = -EINVAL;
124                 goto out;
125         }
126
127         if (ioctl(s->inotify_fd, FIONREAD, &l) < 0) {
128                 log_error("FIONREAD failed: %m");
129                 r = -errno;
130                 goto out;
131         }
132
133         assert(l > 0);
134
135         if (!(buf = malloc(l))) {
136                 log_error("Failed to allocate buffer: %m");
137                 r = -errno;
138                 goto out;
139         }
140
141         if ((k = read(s->inotify_fd, buf, l)) < 0) {
142                 log_error("Failed to read inotify event: %m");
143                 r = -errno;
144                 goto out;
145         }
146
147         e = (struct inotify_event*) buf;
148
149         while (k > 0) {
150                 size_t step;
151
152                 if ((s->type == PATH_CHANGED || s->type == PATH_MODIFIED) &&
153                     s->primary_wd == e->wd)
154                         r = 1;
155
156                 step = sizeof(struct inotify_event) + e->len;
157                 assert(step <= (size_t) k);
158
159                 e = (struct inotify_event*) ((uint8_t*) e + step);
160                 k -= step;
161         }
162 out:
163         free(buf);
164         return r;
165 }
166
167 static bool pathspec_check_good(PathSpec *s, bool initial) {
168         bool good = false;
169
170         switch (s->type) {
171
172         case PATH_EXISTS:
173                 good = access(s->path, F_OK) >= 0;
174                 break;
175
176         case PATH_EXISTS_GLOB:
177                 good = glob_exists(s->path) > 0;
178                 break;
179
180         case PATH_DIRECTORY_NOT_EMPTY: {
181                 int k;
182
183                 k = dir_is_empty(s->path);
184                 good = !(k == -ENOENT || k > 0);
185                 break;
186         }
187
188         case PATH_CHANGED:
189         case PATH_MODIFIED: {
190                 bool b;
191
192                 b = access(s->path, F_OK) >= 0;
193                 good = !initial && b != s->previous_exists;
194                 s->previous_exists = b;
195                 break;
196         }
197
198         default:
199                 ;
200         }
201
202         return good;
203 }
204
205 static bool pathspec_startswith(PathSpec *s, const char *what) {
206         return path_startswith(s->path, what);
207 }
208
209 static void pathspec_mkdir(PathSpec *s, mode_t mode) {
210         int r;
211
212         if (s->type == PATH_EXISTS || s->type == PATH_EXISTS_GLOB)
213                 return;
214
215         if ((r = mkdir_p(s->path, mode)) < 0)
216                 log_warning("mkdir(%s) failed: %s", s->path, strerror(-r));
217 }
218
219 static void pathspec_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 pathspec_done(PathSpec *s) {
228         assert(s->inotify_fd == -1);
229         free(s->path);
230 }
231
232 static void path_init(Unit *u) {
233         Path *p = PATH(u);
234
235         assert(u);
236         assert(u->meta.load_state == UNIT_STUB);
237
238         p->directory_mode = 0755;
239 }
240
241 static void path_done(Unit *u) {
242         Path *p = PATH(u);
243         PathSpec *s;
244
245         assert(p);
246
247         while ((s = p->specs)) {
248                 pathspec_unwatch(s, u);
249                 LIST_REMOVE(PathSpec, spec, p->specs, s);
250                 pathspec_done(s);
251                 free(s);
252         }
253 }
254
255 int path_add_one_mount_link(Path *p, Mount *m) {
256         PathSpec *s;
257         int r;
258
259         assert(p);
260         assert(m);
261
262         if (p->meta.load_state != UNIT_LOADED ||
263             m->meta.load_state != UNIT_LOADED)
264                 return 0;
265
266         LIST_FOREACH(spec, s, p->specs) {
267
268                 if (!pathspec_startswith(s, m->where))
269                         continue;
270
271                 if ((r = unit_add_two_dependencies(UNIT(p), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
272                         return r;
273         }
274
275         return 0;
276 }
277
278 static int path_add_mount_links(Path *p) {
279         Meta *other;
280         int r;
281
282         assert(p);
283
284         LIST_FOREACH(units_by_type, other, p->meta.manager->units_by_type[UNIT_MOUNT])
285                 if ((r = path_add_one_mount_link(p, (Mount*) other)) < 0)
286                         return r;
287
288         return 0;
289 }
290
291 static int path_verify(Path *p) {
292         assert(p);
293
294         if (p->meta.load_state != UNIT_LOADED)
295                 return 0;
296
297         if (!p->specs) {
298                 log_error("%s lacks path setting. Refusing.", p->meta.id);
299                 return -EINVAL;
300         }
301
302         return 0;
303 }
304
305 static int path_add_default_dependencies(Path *p) {
306         int r;
307
308         assert(p);
309
310         if (p->meta.manager->running_as == MANAGER_SYSTEM) {
311                 if ((r = unit_add_dependency_by_name(UNIT(p), UNIT_BEFORE, SPECIAL_BASIC_TARGET, NULL, true)) < 0)
312                         return r;
313
314                 if ((r = unit_add_two_dependencies_by_name(UNIT(p), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
315                         return r;
316         }
317
318         return unit_add_two_dependencies_by_name(UNIT(p), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
319 }
320
321 static int path_load(Unit *u) {
322         Path *p = PATH(u);
323         int r;
324
325         assert(u);
326         assert(u->meta.load_state == UNIT_STUB);
327
328         if ((r = unit_load_fragment_and_dropin(u)) < 0)
329                 return r;
330
331         if (u->meta.load_state == UNIT_LOADED) {
332
333                 if (!p->unit)
334                         if ((r = unit_load_related_unit(u, ".service", &p->unit)))
335                                 return r;
336
337                 if ((r = unit_add_dependency(u, UNIT_BEFORE, p->unit, true)) < 0)
338                         return r;
339
340                 if ((r = path_add_mount_links(p)) < 0)
341                         return r;
342
343                 if (p->meta.default_dependencies)
344                         if ((r = path_add_default_dependencies(p)) < 0)
345                                 return r;
346         }
347
348         return path_verify(p);
349 }
350
351 static void path_dump(Unit *u, FILE *f, const char *prefix) {
352         Path *p = PATH(u);
353         PathSpec *s;
354
355         assert(p);
356         assert(f);
357
358         fprintf(f,
359                 "%sPath State: %s\n"
360                 "%sUnit: %s\n"
361                 "%sMakeDirectory: %s\n"
362                 "%sDirectoryMode: %04o\n",
363                 prefix, path_state_to_string(p->state),
364                 prefix, p->unit->meta.id,
365                 prefix, yes_no(p->make_directory),
366                 prefix, p->directory_mode);
367
368         LIST_FOREACH(spec, s, p->specs)
369                 pathspec_dump(s, f, prefix);
370 }
371
372 static void path_unwatch(Path *p) {
373         PathSpec *s;
374
375         assert(p);
376
377         LIST_FOREACH(spec, s, p->specs)
378                 pathspec_unwatch(s, UNIT(p));
379 }
380
381 static int path_watch(Path *p) {
382         int r;
383         PathSpec *s;
384
385         assert(p);
386
387         LIST_FOREACH(spec, s, p->specs)
388                 if ((r = pathspec_watch(s, UNIT(p))) < 0)
389                         return r;
390
391         return 0;
392 }
393
394 static void path_set_state(Path *p, PathState state) {
395         PathState old_state;
396         assert(p);
397
398         old_state = p->state;
399         p->state = state;
400
401         if (state != PATH_WAITING &&
402             (state != PATH_RUNNING || p->inotify_triggered))
403                 path_unwatch(p);
404
405         if (state != old_state)
406                 log_debug("%s changed %s -> %s",
407                           p->meta.id,
408                           path_state_to_string(old_state),
409                           path_state_to_string(state));
410
411         unit_notify(UNIT(p), state_translation_table[old_state], state_translation_table[state], true);
412 }
413
414 static void path_enter_waiting(Path *p, bool initial, bool recheck);
415
416 static int path_coldplug(Unit *u) {
417         Path *p = PATH(u);
418
419         assert(p);
420         assert(p->state == PATH_DEAD);
421
422         if (p->deserialized_state != p->state) {
423
424                 if (p->deserialized_state == PATH_WAITING ||
425                     p->deserialized_state == PATH_RUNNING)
426                         path_enter_waiting(p, true, true);
427                 else
428                         path_set_state(p, p->deserialized_state);
429         }
430
431         return 0;
432 }
433
434 static void path_enter_dead(Path *p, bool success) {
435         assert(p);
436
437         if (!success)
438                 p->failure = true;
439
440         path_set_state(p, p->failure ? PATH_FAILED : PATH_DEAD);
441 }
442
443 static void path_enter_running(Path *p) {
444         int r;
445         DBusError error;
446
447         assert(p);
448         dbus_error_init(&error);
449
450         /* Don't start job if we are supposed to go down */
451         if (p->meta.job && p->meta.job->type == JOB_STOP)
452                 return;
453
454         if ((r = manager_add_job(p->meta.manager, JOB_START, p->unit, JOB_REPLACE, true, &error, NULL)) < 0)
455                 goto fail;
456
457         p->inotify_triggered = false;
458
459         if ((r = path_watch(p)) < 0)
460                 goto fail;
461
462         path_set_state(p, PATH_RUNNING);
463         return;
464
465 fail:
466         log_warning("%s failed to queue unit startup job: %s", p->meta.id, bus_error(&error, r));
467         path_enter_dead(p, false);
468
469         dbus_error_free(&error);
470 }
471
472 static bool path_check_good(Path *p, bool initial) {
473         PathSpec *s;
474         bool good = false;
475
476         assert(p);
477
478         LIST_FOREACH(spec, s, p->specs) {
479                 good = pathspec_check_good(s, initial);
480
481                 if (good)
482                         break;
483         }
484
485         return good;
486 }
487
488 static void path_enter_waiting(Path *p, bool initial, bool recheck) {
489         int r;
490
491         if (recheck)
492                 if (path_check_good(p, initial)) {
493                         log_debug("%s got triggered.", p->meta.id);
494                         path_enter_running(p);
495                         return;
496                 }
497
498         if ((r = path_watch(p)) < 0)
499                 goto fail;
500
501         /* Hmm, so now we have created inotify watches, but the file
502          * might have appeared/been removed by now, so we must
503          * recheck */
504
505         if (recheck)
506                 if (path_check_good(p, false)) {
507                         log_debug("%s got triggered.", p->meta.id);
508                         path_enter_running(p);
509                         return;
510                 }
511
512         path_set_state(p, PATH_WAITING);
513         return;
514
515 fail:
516         log_warning("%s failed to enter waiting state: %s", p->meta.id, strerror(-r));
517         path_enter_dead(p, false);
518 }
519
520 static void path_mkdir(Path *p) {
521         PathSpec *s;
522
523         assert(p);
524
525         if (!p->make_directory)
526                 return;
527
528         LIST_FOREACH(spec, s, p->specs)
529                 pathspec_mkdir(s, p->directory_mode);
530 }
531
532 static int path_start(Unit *u) {
533         Path *p = PATH(u);
534
535         assert(p);
536         assert(p->state == PATH_DEAD || p->state == PATH_FAILED);
537
538         if (p->unit->meta.load_state != UNIT_LOADED)
539                 return -ENOENT;
540
541         path_mkdir(p);
542
543         p->failure = false;
544         path_enter_waiting(p, true, true);
545
546         return 0;
547 }
548
549 static int path_stop(Unit *u) {
550         Path *p = PATH(u);
551
552         assert(p);
553         assert(p->state == PATH_WAITING || p->state == PATH_RUNNING);
554
555         path_enter_dead(p, true);
556         return 0;
557 }
558
559 static int path_serialize(Unit *u, FILE *f, FDSet *fds) {
560         Path *p = PATH(u);
561
562         assert(u);
563         assert(f);
564         assert(fds);
565
566         unit_serialize_item(u, f, "state", path_state_to_string(p->state));
567
568         return 0;
569 }
570
571 static int path_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
572         Path *p = PATH(u);
573
574         assert(u);
575         assert(key);
576         assert(value);
577         assert(fds);
578
579         if (streq(key, "state")) {
580                 PathState state;
581
582                 if ((state = path_state_from_string(value)) < 0)
583                         log_debug("Failed to parse state value %s", value);
584                 else
585                         p->deserialized_state = state;
586         } else
587                 log_debug("Unknown serialization key '%s'", key);
588
589         return 0;
590 }
591
592 static UnitActiveState path_active_state(Unit *u) {
593         assert(u);
594
595         return state_translation_table[PATH(u)->state];
596 }
597
598 static const char *path_sub_state_to_string(Unit *u) {
599         assert(u);
600
601         return path_state_to_string(PATH(u)->state);
602 }
603
604 static void path_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
605         Path *p = PATH(u);
606         PathSpec *s;
607         int changed;
608
609         assert(p);
610         assert(fd >= 0);
611
612         if (p->state != PATH_WAITING &&
613             p->state != PATH_RUNNING)
614                 return;
615
616         /* log_debug("inotify wakeup on %s.", u->meta.id); */
617
618         LIST_FOREACH(spec, s, p->specs)
619                 if (pathspec_owns_inotify_fd(s, fd))
620                         break;
621
622         if (!s) {
623                 log_error("Got event on unknown fd.");
624                 goto fail;
625         }
626
627         changed = pathspec_fd_event(s, events);
628         if (changed < 0)
629                 goto fail;
630
631         /* If we are already running, then remember that one event was
632          * dispatched so that we restart the service only if something
633          * actually changed on disk */
634         p->inotify_triggered = true;
635
636         if (changed)
637                 path_enter_running(p);
638         else
639                 path_enter_waiting(p, false, true);
640
641         return;
642
643 fail:
644         path_enter_dead(p, false);
645 }
646
647 void path_unit_notify(Unit *u, UnitActiveState new_state) {
648         char *n;
649         int r;
650         Iterator i;
651
652         if (u->meta.type == UNIT_PATH)
653                 return;
654
655         SET_FOREACH(n, u->meta.names, i) {
656                 char *k;
657                 Unit *t;
658                 Path *p;
659
660                 if (!(k = unit_name_change_suffix(n, ".path"))) {
661                         r = -ENOMEM;
662                         goto fail;
663                 }
664
665                 t = manager_get_unit(u->meta.manager, k);
666                 free(k);
667
668                 if (!t)
669                         continue;
670
671                 if (t->meta.load_state != UNIT_LOADED)
672                         continue;
673
674                 p = PATH(t);
675
676                 if (p->unit != u)
677                         continue;
678
679                 if (p->state == PATH_RUNNING && new_state == UNIT_INACTIVE) {
680                         log_debug("%s got notified about unit deactivation.", p->meta.id);
681
682                         /* Hmm, so inotify was triggered since the
683                          * last activation, so I guess we need to
684                          * recheck what is going on. */
685                         path_enter_waiting(p, false, p->inotify_triggered);
686                 }
687         }
688
689         return;
690
691 fail:
692         log_error("Failed find path unit: %s", strerror(-r));
693 }
694
695 static void path_reset_failed(Unit *u) {
696         Path *p = PATH(u);
697
698         assert(p);
699
700         if (p->state == PATH_FAILED)
701                 path_set_state(p, PATH_DEAD);
702
703         p->failure = false;
704 }
705
706 static const char* const path_state_table[_PATH_STATE_MAX] = {
707         [PATH_DEAD] = "dead",
708         [PATH_WAITING] = "waiting",
709         [PATH_RUNNING] = "running",
710         [PATH_FAILED] = "failed"
711 };
712
713 DEFINE_STRING_TABLE_LOOKUP(path_state, PathState);
714
715 static const char* const path_type_table[_PATH_TYPE_MAX] = {
716         [PATH_EXISTS] = "PathExists",
717         [PATH_EXISTS_GLOB] = "PathExistsGlob",
718         [PATH_CHANGED] = "PathChanged",
719         [PATH_MODIFIED] = "PathModified",
720         [PATH_DIRECTORY_NOT_EMPTY] = "DirectoryNotEmpty"
721 };
722
723 DEFINE_STRING_TABLE_LOOKUP(path_type, PathType);
724
725 const UnitVTable path_vtable = {
726         .suffix = ".path",
727         .sections =
728                 "Unit\0"
729                 "Path\0"
730                 "Install\0",
731
732         .init = path_init,
733         .done = path_done,
734         .load = path_load,
735
736         .coldplug = path_coldplug,
737
738         .dump = path_dump,
739
740         .start = path_start,
741         .stop = path_stop,
742
743         .serialize = path_serialize,
744         .deserialize_item = path_deserialize_item,
745
746         .active_state = path_active_state,
747         .sub_state_to_string = path_sub_state_to_string,
748
749         .fd_event = path_fd_event,
750
751         .reset_failed = path_reset_failed,
752
753         .bus_interface = "org.freedesktop.systemd1.Path",
754         .bus_message_handler = bus_path_message_handler
755 };