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