chiark / gitweb /
10efd14c6a39db11b9d99f6056c24a9f217d882d
[elogind.git] / unit.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 <assert.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <sys/epoll.h>
26 #include <sys/timerfd.h>
27 #include <sys/poll.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30
31 #include "set.h"
32 #include "unit.h"
33 #include "macro.h"
34 #include "strv.h"
35 #include "load-fragment.h"
36 #include "load-dropin.h"
37 #include "log.h"
38
39 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
40         [UNIT_SERVICE] = &service_vtable,
41         [UNIT_TIMER] = &timer_vtable,
42         [UNIT_SOCKET] = &socket_vtable,
43         [UNIT_TARGET] = &target_vtable,
44         [UNIT_DEVICE] = &device_vtable,
45         [UNIT_MOUNT] = &mount_vtable,
46         [UNIT_AUTOMOUNT] = &automount_vtable,
47         [UNIT_SNAPSHOT] = &snapshot_vtable
48 };
49
50 UnitType unit_name_to_type(const char *n) {
51         UnitType t;
52
53         assert(n);
54
55         for (t = 0; t < _UNIT_TYPE_MAX; t++)
56                 if (endswith(n, unit_vtable[t]->suffix))
57                         return t;
58
59         return _UNIT_TYPE_INVALID;
60 }
61
62 #define VALID_CHARS                             \
63         "0123456789"                            \
64         "abcdefghijklmnopqrstuvwxyz"            \
65         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"            \
66         "-_.\\"
67
68 bool unit_name_is_valid(const char *n) {
69         UnitType t;
70         const char *e, *i;
71
72         assert(n);
73
74         if (strlen(n) >= UNIT_NAME_MAX)
75                 return false;
76
77         t = unit_name_to_type(n);
78         if (t < 0 || t >= _UNIT_TYPE_MAX)
79                 return false;
80
81         if (!(e = strrchr(n, '.')))
82                 return false;
83
84         if (e == n)
85                 return false;
86
87         for (i = n; i < e; i++)
88                 if (!strchr(VALID_CHARS, *i))
89                         return false;
90
91         return true;
92 }
93
94 char *unit_name_change_suffix(const char *n, const char *suffix) {
95         char *e, *r;
96         size_t a, b;
97
98         assert(n);
99         assert(unit_name_is_valid(n));
100         assert(suffix);
101
102         assert_se(e = strrchr(n, '.'));
103         a = e - n;
104         b = strlen(suffix);
105
106         if (!(r = new(char, a + b + 1)))
107                 return NULL;
108
109         memcpy(r, n, a);
110         memcpy(r+a, suffix, b+1);
111
112         return r;
113 }
114
115 Unit *unit_new(Manager *m) {
116         Unit *u;
117
118         assert(m);
119
120         if (!(u = new0(Unit, 1)))
121                 return NULL;
122
123         if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
124                 free(u);
125                 return NULL;
126         }
127
128         u->meta.manager = m;
129         u->meta.type = _UNIT_TYPE_INVALID;
130
131         return u;
132 }
133
134 int unit_add_name(Unit *u, const char *text) {
135         UnitType t;
136         char *s;
137         int r;
138
139         assert(u);
140         assert(text);
141
142         if (!unit_name_is_valid(text))
143                 return -EINVAL;
144
145         if ((t = unit_name_to_type(text)) == _UNIT_TYPE_INVALID)
146                 return -EINVAL;
147
148         if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type)
149                 return -EINVAL;
150
151         if (!(s = strdup(text)))
152                 return -ENOMEM;
153
154         if ((r = set_put(u->meta.names, s)) < 0) {
155                 free(s);
156
157                 if (r == -EEXIST)
158                         return 0;
159
160                 return r;
161         }
162
163         if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
164                 set_remove(u->meta.names, s);
165                 free(s);
166                 return r;
167         }
168
169         if (u->meta.type == _UNIT_TYPE_INVALID)
170                 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
171
172         u->meta.type = t;
173
174         if (!u->meta.id)
175                 u->meta.id = s;
176
177         unit_add_to_dbus_queue(u);
178         return 0;
179 }
180
181 int unit_choose_id(Unit *u, const char *name) {
182         char *s;
183
184         assert(u);
185         assert(name);
186
187         /* Selects one of the names of this unit as the id */
188
189         if (!(s = set_get(u->meta.names, (char*) name)))
190                 return -ENOENT;
191
192         u->meta.id = s;
193
194         unit_add_to_dbus_queue(u);
195         return 0;
196 }
197
198 int unit_set_description(Unit *u, const char *description) {
199         char *s;
200
201         assert(u);
202
203         if (!(s = strdup(description)))
204                 return -ENOMEM;
205
206         free(u->meta.description);
207         u->meta.description = s;
208
209         unit_add_to_dbus_queue(u);
210         return 0;
211 }
212
213 void unit_add_to_load_queue(Unit *u) {
214         assert(u);
215
216         if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
217                 return;
218
219         LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
220         u->meta.in_load_queue = true;
221 }
222
223 void unit_add_to_cleanup_queue(Unit *u) {
224         assert(u);
225
226         if (u->meta.in_cleanup_queue)
227                 return;
228
229         LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
230         u->meta.in_cleanup_queue = true;
231 }
232
233 void unit_add_to_dbus_queue(Unit *u) {
234         assert(u);
235
236         if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue || set_isempty(u->meta.manager->subscribed))
237                 return;
238
239         LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
240         u->meta.in_dbus_queue = true;
241 }
242
243 static void bidi_set_free(Unit *u, Set *s) {
244         Iterator i;
245         Unit *other;
246
247         assert(u);
248
249         /* Frees the set and makes sure we are dropped from the
250          * inverse pointers */
251
252         SET_FOREACH(other, s, i) {
253                 UnitDependency d;
254
255                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
256                         set_remove(other->meta.dependencies[d], u);
257         }
258
259         set_free(s);
260 }
261
262 void unit_free(Unit *u) {
263         UnitDependency d;
264         Iterator i;
265         char *t;
266
267         assert(u);
268
269         bus_unit_send_removed_signal(u);
270
271         /* Detach from next 'bigger' objects */
272
273         cgroup_bonding_free_list(u->meta.cgroup_bondings);
274
275         SET_FOREACH(t, u->meta.names, i)
276                 hashmap_remove_value(u->meta.manager->units, t, u);
277
278         if (u->meta.type != _UNIT_TYPE_INVALID)
279                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
280
281         if (u->meta.in_load_queue)
282                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
283
284         if (u->meta.in_dbus_queue)
285                 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
286
287         if (u->meta.in_cleanup_queue)
288                 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
289
290         if (u->meta.load_state != UNIT_STUB)
291                 if (UNIT_VTABLE(u)->done)
292                         UNIT_VTABLE(u)->done(u);
293
294         /* Free data and next 'smaller' objects */
295         if (u->meta.job)
296                 job_free(u->meta.job);
297
298         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
299                 bidi_set_free(u, u->meta.dependencies[d]);
300
301         free(u->meta.description);
302         free(u->meta.fragment_path);
303
304         while ((t = set_steal_first(u->meta.names)))
305                 free(t);
306         set_free(u->meta.names);
307
308         free(u);
309 }
310
311 UnitActiveState unit_active_state(Unit *u) {
312         assert(u);
313
314         if (u->meta.load_state != UNIT_LOADED)
315                 return UNIT_INACTIVE;
316
317         return UNIT_VTABLE(u)->active_state(u);
318 }
319
320 static void complete_move(Set **s, Set **other) {
321         assert(s);
322         assert(other);
323
324         if (!*other)
325                 return;
326
327         if (*s)
328                 set_move(*s, *other);
329         else {
330                 *s = *other;
331                 *other = NULL;
332         }
333 }
334
335 static void merge_names(Unit *u, Unit *other) {
336         char *t;
337         Iterator i;
338
339         assert(u);
340         assert(other);
341
342         complete_move(&u->meta.names, &other->meta.names);
343
344         while ((t = set_steal_first(other->meta.names)))
345                 free(t);
346
347         set_free(other->meta.names);
348         other->meta.names = NULL;
349         other->meta.id = NULL;
350
351         SET_FOREACH(t, u->meta.names, i)
352                 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
353 }
354
355 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
356         Iterator i;
357         Unit *back;
358         int r;
359
360         assert(u);
361         assert(other);
362         assert(d < _UNIT_DEPENDENCY_MAX);
363
364         SET_FOREACH(back, other->meta.dependencies[d], i) {
365                 UnitDependency k;
366
367                 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
368                         if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
369
370                                 if (r == -EEXIST)
371                                         set_remove(back->meta.dependencies[k], other);
372                                 else
373                                         assert(r == -ENOENT);
374                         }
375         }
376
377         complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
378
379         set_free(other->meta.dependencies[d]);
380         other->meta.dependencies[d] = NULL;
381 }
382
383 int unit_merge(Unit *u, Unit *other) {
384         UnitDependency d;
385
386         assert(u);
387         assert(other);
388         assert(u->meta.manager == other->meta.manager);
389
390         if (other == u)
391                 return 0;
392
393         /* This merges 'other' into 'unit'. FIXME: This does not
394          * rollback on failure. */
395
396         if (u->meta.type != u->meta.type)
397                 return -EINVAL;
398
399         if (other->meta.load_state != UNIT_STUB)
400                 return -EEXIST;
401
402         /* Merge names */
403         merge_names(u, other);
404
405         /* Merge dependencies */
406         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
407                 merge_dependencies(u, other, d);
408
409         unit_add_to_dbus_queue(u);
410
411         other->meta.load_state = UNIT_MERGED;
412         other->meta.merged_into = u;
413
414         unit_add_to_cleanup_queue(other);
415
416         return 0;
417 }
418
419 int unit_merge_by_name(Unit *u, const char *name) {
420         Unit *other;
421
422         assert(u);
423         assert(name);
424
425         if (!(other = manager_get_unit(u->meta.manager, name)))
426                 return unit_add_name(u, name);
427
428         return unit_merge(u, other);
429 }
430
431 Unit* unit_follow_merge(Unit *u) {
432         assert(u);
433
434         while (u->meta.load_state == UNIT_MERGED)
435                 assert_se(u = u->meta.merged_into);
436
437         return u;
438 }
439
440 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
441         int r;
442
443         assert(u);
444         assert(c);
445
446         if (c->output != EXEC_OUTPUT_KERNEL && c->output != EXEC_OUTPUT_SYSLOG)
447                 return 0;
448
449         /* If syslog or kernel logging is requested, make sure our own
450          * logging daemon is run first. */
451
452         if ((r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_LOGGER_SOCKET)) < 0)
453                 return r;
454
455         if (u->meta.manager->running_as != MANAGER_SESSION)
456                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_LOGGER_SOCKET)) < 0)
457                         return r;
458
459         return 0;
460 }
461
462 const char* unit_id(Unit *u) {
463         assert(u);
464
465         if (u->meta.id)
466                 return u->meta.id;
467
468         return set_first(u->meta.names);
469 }
470
471 const char *unit_description(Unit *u) {
472         assert(u);
473
474         if (u->meta.description)
475                 return u->meta.description;
476
477         return unit_id(u);
478 }
479
480 void unit_dump(Unit *u, FILE *f, const char *prefix) {
481         char *t;
482         UnitDependency d;
483         Iterator i;
484         char *p2;
485         const char *prefix2;
486         CGroupBonding *b;
487
488         assert(u);
489
490         if (!prefix)
491                 prefix = "";
492         p2 = strappend(prefix, "\t");
493         prefix2 = p2 ? p2 : prefix;
494
495         fprintf(f,
496                 "%s→ Unit %s:\n"
497                 "%s\tDescription: %s\n"
498                 "%s\tUnit Load State: %s\n"
499                 "%s\tUnit Active State: %s\n",
500                 prefix, unit_id(u),
501                 prefix, unit_description(u),
502                 prefix, unit_load_state_to_string(u->meta.load_state),
503                 prefix, unit_active_state_to_string(unit_active_state(u)));
504
505         SET_FOREACH(t, u->meta.names, i)
506                 fprintf(f, "%s\tName: %s\n", prefix, t);
507
508         if (u->meta.fragment_path)
509                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
510
511         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
512                 Unit *other;
513
514                 if (set_isempty(u->meta.dependencies[d]))
515                         continue;
516
517                 SET_FOREACH(other, u->meta.dependencies[d], i)
518                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), unit_id(other));
519         }
520
521         fprintf(f,
522                 "%s\tRecursive Stop: %s\n"
523                 "%s\tStop When Unneeded: %s\n",
524                 prefix, yes_no(u->meta.recursive_stop),
525                 prefix, yes_no(u->meta.stop_when_unneeded));
526
527         if (u->meta.load_state == UNIT_LOADED) {
528                 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
529                         fprintf(f, "%s\tControlGroup: %s:%s\n",
530                                 prefix, b->controller, b->path);
531
532                 if (UNIT_VTABLE(u)->dump)
533                         UNIT_VTABLE(u)->dump(u, f, prefix2);
534         }
535
536         if (u->meta.job)
537                 job_dump(u->meta.job, f, prefix2);
538
539         free(p2);
540 }
541
542 /* Common implementation for multiple backends */
543 int unit_load_fragment_and_dropin(Unit *u, UnitLoadState *new_state) {
544         int r;
545
546         assert(u);
547         assert(new_state);
548         assert(*new_state == UNIT_STUB || *new_state == UNIT_LOADED);
549
550         /* Load a .service file */
551         if ((r = unit_load_fragment(u, new_state)) < 0)
552                 return r;
553
554         if (*new_state == UNIT_STUB)
555                 return -ENOENT;
556
557         /* Load drop-in directory data */
558         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
559                 return r;
560
561         return 0;
562 }
563
564 /* Common implementation for multiple backends */
565 int unit_load_fragment_and_dropin_optional(Unit *u, UnitLoadState *new_state) {
566         int r;
567
568         assert(u);
569         assert(new_state);
570         assert(*new_state == UNIT_STUB || *new_state == UNIT_LOADED);
571
572         /* Same as unit_load_fragment_and_dropin(), but whether
573          * something can be loaded or not doesn't matter. */
574
575         /* Load a .service file */
576         if ((r = unit_load_fragment(u, new_state)) < 0)
577                 return r;
578
579         if (*new_state == UNIT_STUB)
580                 *new_state = UNIT_LOADED;
581
582         /* Load drop-in directory data */
583         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
584                 return r;
585
586         return 0;
587 }
588
589 int unit_load(Unit *u) {
590         int r;
591         UnitLoadState res;
592
593         assert(u);
594
595         if (u->meta.in_load_queue) {
596                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
597                 u->meta.in_load_queue = false;
598         }
599
600         if (u->meta.load_state != UNIT_STUB)
601                 return 0;
602
603         if (UNIT_VTABLE(u)->init) {
604                 res = UNIT_STUB;
605                 if ((r = UNIT_VTABLE(u)->init(u, &res)) < 0)
606                         goto fail;
607         }
608
609         if (res == UNIT_STUB) {
610                 r = -ENOENT;
611                 goto fail;
612         }
613
614         u->meta.load_state = res;
615         assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
616
617         unit_add_to_dbus_queue(unit_follow_merge(u));
618
619         return 0;
620
621 fail:
622         u->meta.load_state = UNIT_FAILED;
623         unit_add_to_dbus_queue(u);
624
625         log_error("Failed to load configuration for %s: %s", unit_id(u), strerror(-r));
626
627         return r;
628 }
629
630 /* Errors:
631  *         -EBADR:    This unit type does not support starting.
632  *         -EALREADY: Unit is already started.
633  *         -EAGAIN:   An operation is already in progress. Retry later.
634  */
635 int unit_start(Unit *u) {
636         UnitActiveState state;
637
638         assert(u);
639
640         /* If this is already (being) started, then this will
641          * succeed. Note that this will even succeed if this unit is
642          * not startable by the user. This is relied on to detect when
643          * we need to wait for units and when waiting is finished. */
644         state = unit_active_state(u);
645         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
646                 return -EALREADY;
647
648         /* If it is stopped, but we cannot start it, then fail */
649         if (!UNIT_VTABLE(u)->start)
650                 return -EBADR;
651
652         /* We don't suppress calls to ->start() here when we are
653          * already starting, to allow this request to be used as a
654          * "hurry up" call, for example when the unit is in some "auto
655          * restart" state where it waits for a holdoff timer to elapse
656          * before it will start again. */
657
658         unit_add_to_dbus_queue(u);
659         return UNIT_VTABLE(u)->start(u);
660 }
661
662 bool unit_can_start(Unit *u) {
663         assert(u);
664
665         return !!UNIT_VTABLE(u)->start;
666 }
667
668 /* Errors:
669  *         -EBADR:    This unit type does not support stopping.
670  *         -EALREADY: Unit is already stopped.
671  *         -EAGAIN:   An operation is already in progress. Retry later.
672  */
673 int unit_stop(Unit *u) {
674         UnitActiveState state;
675
676         assert(u);
677
678         state = unit_active_state(u);
679         if (state == UNIT_INACTIVE)
680                 return -EALREADY;
681
682         if (!UNIT_VTABLE(u)->stop)
683                 return -EBADR;
684
685         if (state == UNIT_DEACTIVATING)
686                 return 0;
687
688         unit_add_to_dbus_queue(u);
689         return UNIT_VTABLE(u)->stop(u);
690 }
691
692 /* Errors:
693  *         -EBADR:    This unit type does not support reloading.
694  *         -ENOEXEC:  Unit is not started.
695  *         -EAGAIN:   An operation is already in progress. Retry later.
696  */
697 int unit_reload(Unit *u) {
698         UnitActiveState state;
699
700         assert(u);
701
702         if (!unit_can_reload(u))
703                 return -EBADR;
704
705         state = unit_active_state(u);
706         if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
707                 return -EALREADY;
708
709         if (unit_active_state(u) != UNIT_ACTIVE)
710                 return -ENOEXEC;
711
712         unit_add_to_dbus_queue(u);
713         return UNIT_VTABLE(u)->reload(u);
714 }
715
716 bool unit_can_reload(Unit *u) {
717         assert(u);
718
719         if (!UNIT_VTABLE(u)->reload)
720                 return false;
721
722         if (!UNIT_VTABLE(u)->can_reload)
723                 return true;
724
725         return UNIT_VTABLE(u)->can_reload(u);
726 }
727
728 static void unit_check_uneeded(Unit *u) {
729         Iterator i;
730         Unit *other;
731
732         assert(u);
733
734         /* If this service shall be shut down when unneeded then do
735          * so. */
736
737         if (!u->meta.stop_when_unneeded)
738                 return;
739
740         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
741                 return;
742
743         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
744                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
745                         return;
746
747         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRED_BY], i)
748                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
749                         return;
750
751         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
752                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
753                         return;
754
755         log_debug("Service %s is not needed anymore. Stopping.", unit_id(u));
756
757         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
758         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL);
759 }
760
761 static void retroactively_start_dependencies(Unit *u) {
762         Iterator i;
763         Unit *other;
764
765         assert(u);
766         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
767
768         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
769                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
770                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
771
772         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
773                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
774                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
775
776         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
777                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
778                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
779
780         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
781                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
782                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
783
784         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
785                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
786                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
787 }
788
789 static void retroactively_stop_dependencies(Unit *u) {
790         Iterator i;
791         Unit *other;
792
793         assert(u);
794         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
795
796         if (u->meta.recursive_stop) {
797                 /* Pull down units need us recursively if enabled */
798                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
799                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
800                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
801         }
802
803         /* Garbage collect services that might not be needed anymore, if enabled */
804         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
805                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
806                         unit_check_uneeded(other);
807         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
808                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
809                         unit_check_uneeded(other);
810         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
811                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
812                         unit_check_uneeded(other);
813         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
814                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
815                         unit_check_uneeded(other);
816         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUISITE], i)
817                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
818                         unit_check_uneeded(other);
819 }
820
821 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
822         assert(u);
823         assert(os < _UNIT_ACTIVE_STATE_MAX);
824         assert(ns < _UNIT_ACTIVE_STATE_MAX);
825         assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
826         assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
827
828         if (os == ns)
829                 return;
830
831         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
832                 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
833         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
834                 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
835
836         if (u->meta.job) {
837
838                 if (u->meta.job->state == JOB_WAITING)
839
840                         /* So we reached a different state for this
841                          * job. Let's see if we can run it now if it
842                          * failed previously due to EAGAIN. */
843                         job_add_to_run_queue(u->meta.job);
844
845                 else {
846                         assert(u->meta.job->state == JOB_RUNNING);
847
848                         /* Let's check whether this state change
849                          * constitutes a finished job, or maybe
850                          * cotradicts a running job and hence needs to
851                          * invalidate jobs. */
852
853                         switch (u->meta.job->type) {
854
855                         case JOB_START:
856                         case JOB_VERIFY_ACTIVE:
857
858                                 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
859                                         job_finish_and_invalidate(u->meta.job, true);
860                                         return;
861                                 } else if (ns == UNIT_ACTIVATING)
862                                         return;
863                                 else
864                                         job_finish_and_invalidate(u->meta.job, false);
865
866                                 break;
867
868                         case JOB_RELOAD:
869                         case JOB_RELOAD_OR_START:
870
871                                 if (ns == UNIT_ACTIVE) {
872                                         job_finish_and_invalidate(u->meta.job, true);
873                                         return;
874                                 } else if (ns == UNIT_ACTIVATING || ns == UNIT_ACTIVE_RELOADING)
875                                         return;
876                                 else
877                                         job_finish_and_invalidate(u->meta.job, false);
878
879                                 break;
880
881                         case JOB_STOP:
882                         case JOB_RESTART:
883                         case JOB_TRY_RESTART:
884
885                                 if (ns == UNIT_INACTIVE) {
886                                         job_finish_and_invalidate(u->meta.job, true);
887                                         return;
888                                 } else if (ns == UNIT_DEACTIVATING)
889                                         return;
890                                 else
891                                         job_finish_and_invalidate(u->meta.job, false);
892
893                                 break;
894
895                         default:
896                                 assert_not_reached("Job type unknown");
897                         }
898                 }
899         }
900
901         /* If this state change happened without being requested by a
902          * job, then let's retroactively start or stop dependencies */
903
904         if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
905                 retroactively_start_dependencies(u);
906         else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
907                 retroactively_stop_dependencies(u);
908
909         /* Maybe we finished startup and are now ready for being
910          * stopped because unneeded? */
911         unit_check_uneeded(u);
912
913         unit_add_to_dbus_queue(u);
914 }
915
916 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
917         struct epoll_event ev;
918
919         assert(u);
920         assert(fd >= 0);
921         assert(w);
922         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
923
924         zero(ev);
925         ev.data.ptr = w;
926         ev.events = events;
927
928         if (epoll_ctl(u->meta.manager->epoll_fd,
929                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
930                       fd,
931                       &ev) < 0)
932                 return -errno;
933
934         w->fd = fd;
935         w->type = WATCH_FD;
936         w->data.unit = u;
937
938         return 0;
939 }
940
941 void unit_unwatch_fd(Unit *u, Watch *w) {
942         assert(u);
943         assert(w);
944
945         if (w->type == WATCH_INVALID)
946                 return;
947
948         assert(w->type == WATCH_FD);
949         assert(w->data.unit == u);
950         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
951
952         w->fd = -1;
953         w->type = WATCH_INVALID;
954         w->data.unit = NULL;
955 }
956
957 int unit_watch_pid(Unit *u, pid_t pid) {
958         assert(u);
959         assert(pid >= 1);
960
961         return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
962 }
963
964 void unit_unwatch_pid(Unit *u, pid_t pid) {
965         assert(u);
966         assert(pid >= 1);
967
968         hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
969 }
970
971 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
972         struct itimerspec its;
973         int flags, fd;
974         bool ours;
975
976         assert(u);
977         assert(w);
978         assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->data.unit == u));
979
980         /* This will try to reuse the old timer if there is one */
981
982         if (w->type == WATCH_TIMER) {
983                 ours = false;
984                 fd = w->fd;
985         } else {
986                 ours = true;
987                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
988                         return -errno;
989         }
990
991         zero(its);
992
993         if (delay <= 0) {
994                 /* Set absolute time in the past, but not 0, since we
995                  * don't want to disarm the timer */
996                 its.it_value.tv_sec = 0;
997                 its.it_value.tv_nsec = 1;
998
999                 flags = TFD_TIMER_ABSTIME;
1000         } else {
1001                 timespec_store(&its.it_value, delay);
1002                 flags = 0;
1003         }
1004
1005         /* This will also flush the elapse counter */
1006         if (timerfd_settime(fd, flags, &its, NULL) < 0)
1007                 goto fail;
1008
1009         if (w->type == WATCH_INVALID) {
1010                 struct epoll_event ev;
1011
1012                 zero(ev);
1013                 ev.data.ptr = w;
1014                 ev.events = EPOLLIN;
1015
1016                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1017                         goto fail;
1018         }
1019
1020         w->fd = fd;
1021         w->type = WATCH_TIMER;
1022         w->data.unit = u;
1023
1024         return 0;
1025
1026 fail:
1027         if (ours)
1028                 close_nointr_nofail(fd);
1029
1030         return -errno;
1031 }
1032
1033 void unit_unwatch_timer(Unit *u, Watch *w) {
1034         assert(u);
1035         assert(w);
1036
1037         if (w->type == WATCH_INVALID)
1038                 return;
1039
1040         assert(w->type == WATCH_TIMER && w->data.unit == u);
1041
1042         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1043         assert_se(close_nointr(w->fd) == 0);
1044
1045         w->fd = -1;
1046         w->type = WATCH_INVALID;
1047         w->data.unit = NULL;
1048 }
1049
1050 bool unit_job_is_applicable(Unit *u, JobType j) {
1051         assert(u);
1052         assert(j >= 0 && j < _JOB_TYPE_MAX);
1053
1054         switch (j) {
1055
1056         case JOB_VERIFY_ACTIVE:
1057         case JOB_START:
1058                 return true;
1059
1060         case JOB_STOP:
1061         case JOB_RESTART:
1062         case JOB_TRY_RESTART:
1063                 return unit_can_start(u);
1064
1065         case JOB_RELOAD:
1066                 return unit_can_reload(u);
1067
1068         case JOB_RELOAD_OR_START:
1069                 return unit_can_reload(u) && unit_can_start(u);
1070
1071         default:
1072                 assert_not_reached("Invalid job type");
1073         }
1074 }
1075
1076 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
1077
1078         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1079                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1080                 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
1081                 [UNIT_WANTS] = UNIT_WANTED_BY,
1082                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1083                 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
1084                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1085                 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1086                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1087                 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
1088                 [UNIT_BEFORE] = UNIT_AFTER,
1089                 [UNIT_AFTER] = UNIT_BEFORE
1090         };
1091         int r;
1092
1093         assert(u);
1094         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1095         assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
1096         assert(other);
1097
1098         /* We won't allow dependencies on ourselves. We will not
1099          * consider them an error however. */
1100         if (u == other)
1101                 return 0;
1102
1103         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1104                 return r;
1105
1106         if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1107                 return r;
1108
1109         if ((r = set_put(u->meta.dependencies[d], other)) < 0)
1110                 return r;
1111
1112         if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1113                 set_remove(u->meta.dependencies[d], other);
1114                 return r;
1115         }
1116
1117         unit_add_to_dbus_queue(u);
1118         return 0;
1119 }
1120
1121 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
1122         Unit *other;
1123         int r;
1124
1125         if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
1126                 return r;
1127
1128         if ((r = unit_add_dependency(u, d, other)) < 0)
1129                 return r;
1130
1131         return 0;
1132 }
1133
1134 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name) {
1135         Unit *other;
1136         int r;
1137
1138         if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
1139                 return r;
1140
1141         if ((r = unit_add_dependency(other, d, u)) < 0)
1142                 return r;
1143
1144         return 0;
1145 }
1146
1147 int set_unit_path(const char *p) {
1148         char *cwd, *c;
1149         int r;
1150
1151         /* This is mostly for debug purposes */
1152
1153         if (path_is_absolute(p)) {
1154                 if (!(c = strdup(p)))
1155                         return -ENOMEM;
1156         } else {
1157                 if (!(cwd = get_current_dir_name()))
1158                         return -errno;
1159
1160                 r = asprintf(&c, "%s/%s", cwd, p);
1161                 free(cwd);
1162
1163                 if (r < 0)
1164                         return -ENOMEM;
1165         }
1166
1167         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1168                 r = -errno;
1169                 free(c);
1170                 return r;
1171         }
1172
1173         return 0;
1174 }
1175
1176 char *unit_name_escape_path(const char *path, const char *suffix) {
1177         char *r, *t;
1178         const char *f;
1179         size_t a, b;
1180
1181         assert(path);
1182
1183         /* Takes a path and a suffix and prefix and makes a nice
1184          * string suitable as unit name of it, escaping all weird
1185          * chars on the way.
1186          *
1187          * / becomes ., and all chars not alloweed in a unit name get
1188          * escaped as \xFF, including \ and ., of course. This
1189          * escaping is hence reversible.
1190          */
1191
1192         if (!suffix)
1193                 suffix = "";
1194
1195         a = strlen(path);
1196         b = strlen(suffix);
1197
1198         if (!(r = new(char, a*4+b+1)))
1199                 return NULL;
1200
1201         for (f = path, t = r; *f; f++) {
1202                 if (*f == '/')
1203                         *(t++) = '.';
1204                 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
1205                         *(t++) = '\\';
1206                         *(t++) = 'x';
1207                         *(t++) = hexchar(*f > 4);
1208                         *(t++) = hexchar(*f);
1209                 } else
1210                         *(t++) = *f;
1211         }
1212
1213         memcpy(t, suffix, b+1);
1214
1215         return r;
1216 }
1217
1218 char *unit_dbus_path(Unit *u) {
1219         char *p, *e;
1220
1221         assert(u);
1222
1223         if (!(e = bus_path_escape(unit_id(u))))
1224                 return NULL;
1225
1226         if (asprintf(&p, "/org/freedesktop/systemd1/unit/%s", e) < 0) {
1227                 free(e);
1228                 return NULL;
1229         }
1230
1231         free(e);
1232         return p;
1233 }
1234
1235 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1236         CGroupBonding *l;
1237         int r;
1238
1239         assert(u);
1240         assert(b);
1241         assert(b->path);
1242
1243         /* Ensure this hasn't been added yet */
1244         assert(!b->unit);
1245
1246         l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1247         LIST_PREPEND(CGroupBonding, by_path, l, b);
1248
1249         if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1250                 LIST_REMOVE(CGroupBonding, by_path, l, b);
1251                 return r;
1252         }
1253
1254         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1255         b->unit = u;
1256
1257         return 0;
1258 }
1259
1260 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1261         size_t n;
1262         const char *p;
1263         char *controller;
1264         CGroupBonding *b;
1265         int r;
1266
1267         assert(u);
1268         assert(name);
1269
1270         /* Detect controller name */
1271         n = strcspn(name, ":/");
1272
1273         /* Only controller name, no path? No path? */
1274         if (name[n] == 0)
1275                 return -EINVAL;
1276
1277         if (n > 0) {
1278                 if (name[n] != ':')
1279                         return -EINVAL;
1280
1281                 p = name+n+1;
1282         } else
1283                 p = name;
1284
1285         /* Insist in absolute paths */
1286         if (p[0] != '/')
1287                 return -EINVAL;
1288
1289         if (!(controller = strndup(name, n)))
1290                 return -ENOMEM;
1291
1292         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1293                 free(controller);
1294                 return -EEXIST;
1295         }
1296
1297         if (!(b = new0(CGroupBonding, 1))) {
1298                 free(controller);
1299                 return -ENOMEM;
1300         }
1301
1302         b->controller = controller;
1303
1304         if (!(b->path = strdup(p))) {
1305                 r = -ENOMEM;
1306                 goto fail;
1307         }
1308
1309         b->only_us = false;
1310         b->clean_up = false;
1311
1312         if ((r = unit_add_cgroup(u, b)) < 0)
1313                 goto fail;
1314
1315         return 0;
1316
1317 fail:
1318         free(b->path);
1319         free(b->controller);
1320         free(b);
1321
1322         return r;
1323 }
1324
1325 int unit_add_default_cgroup(Unit *u) {
1326         CGroupBonding *b;
1327         int r = -ENOMEM;
1328
1329         assert(u);
1330
1331         /* Adds in the default cgroup data, if it wasn't specified yet */
1332
1333         if (unit_get_default_cgroup(u))
1334                 return 0;
1335
1336         if (!(b = new0(CGroupBonding, 1)))
1337                 return -ENOMEM;
1338
1339         if (!(b->controller = strdup(u->meta.manager->cgroup_controller)))
1340                 goto fail;
1341
1342         if (asprintf(&b->path, "%s/%s", u->meta.manager->cgroup_hierarchy, unit_id(u)) < 0)
1343                 goto fail;
1344
1345         b->clean_up = true;
1346         b->only_us = true;
1347
1348         if ((r = unit_add_cgroup(u, b)) < 0)
1349                 goto fail;
1350
1351         return 0;
1352
1353 fail:
1354         free(b->path);
1355         free(b->controller);
1356         free(b);
1357
1358         return r;
1359 }
1360
1361 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1362         assert(u);
1363
1364         return cgroup_bonding_find_list(u->meta.cgroup_bondings, u->meta.manager->cgroup_controller);
1365 }
1366
1367 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
1368         [UNIT_SERVICE] = "service",
1369         [UNIT_TIMER] = "timer",
1370         [UNIT_SOCKET] = "socket",
1371         [UNIT_TARGET] = "target",
1372         [UNIT_DEVICE] = "device",
1373         [UNIT_MOUNT] = "mount",
1374         [UNIT_AUTOMOUNT] = "automount",
1375         [UNIT_SNAPSHOT] = "snapshot"
1376 };
1377
1378 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
1379
1380 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
1381         [UNIT_STUB] = "stub",
1382         [UNIT_LOADED] = "loaded",
1383         [UNIT_FAILED] = "failed",
1384         [UNIT_MERGED] = "merged"
1385 };
1386
1387 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
1388
1389 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
1390         [UNIT_ACTIVE] = "active",
1391         [UNIT_INACTIVE] = "inactive",
1392         [UNIT_ACTIVATING] = "activating",
1393         [UNIT_DEACTIVATING] = "deactivating"
1394 };
1395
1396 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
1397
1398 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
1399         [UNIT_REQUIRES] = "Requires",
1400         [UNIT_SOFT_REQUIRES] = "SoftRequires",
1401         [UNIT_WANTS] = "Wants",
1402         [UNIT_REQUISITE] = "Requisite",
1403         [UNIT_SOFT_REQUISITE] = "SoftRequisite",
1404         [UNIT_REQUIRED_BY] = "RequiredBy",
1405         [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
1406         [UNIT_WANTED_BY] = "WantedBy",
1407         [UNIT_CONFLICTS] = "Conflicts",
1408         [UNIT_BEFORE] = "Before",
1409         [UNIT_AFTER] = "After",
1410 };
1411
1412 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);