chiark / gitweb /
sysv: properly handle Provides LSB header
[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_dbus_queue(Unit *u) {
224         assert(u);
225
226         if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue || set_isempty(u->meta.manager->subscribed))
227                 return;
228
229         LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
230         u->meta.in_dbus_queue = true;
231 }
232
233 static void bidi_set_free(Unit *u, Set *s) {
234         Iterator i;
235         Unit *other;
236
237         assert(u);
238
239         /* Frees the set and makes sure we are dropped from the
240          * inverse pointers */
241
242         SET_FOREACH(other, s, i) {
243                 UnitDependency d;
244
245                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
246                         set_remove(other->meta.dependencies[d], u);
247         }
248
249         set_free(s);
250 }
251
252 void unit_free(Unit *u) {
253         UnitDependency d;
254         Iterator i;
255         char *t;
256
257         assert(u);
258
259         bus_unit_send_removed_signal(u);
260
261         /* Detach from next 'bigger' objects */
262
263         cgroup_bonding_free_list(u->meta.cgroup_bondings);
264
265         SET_FOREACH(t, u->meta.names, i)
266                 hashmap_remove_value(u->meta.manager->units, t, u);
267
268         if (u->meta.type != _UNIT_TYPE_INVALID)
269                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
270
271         if (u->meta.in_load_queue)
272                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
273
274         if (u->meta.in_dbus_queue)
275                 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
276
277         if (u->meta.load_state == UNIT_LOADED)
278                 if (UNIT_VTABLE(u)->done)
279                         UNIT_VTABLE(u)->done(u);
280
281         /* Free data and next 'smaller' objects */
282         if (u->meta.job)
283                 job_free(u->meta.job);
284
285         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
286                 bidi_set_free(u, u->meta.dependencies[d]);
287
288         free(u->meta.description);
289         free(u->meta.fragment_path);
290
291         while ((t = set_steal_first(u->meta.names)))
292                 free(t);
293         set_free(u->meta.names);
294
295         free(u);
296 }
297
298 UnitActiveState unit_active_state(Unit *u) {
299         assert(u);
300
301         if (u->meta.load_state != UNIT_LOADED)
302                 return UNIT_INACTIVE;
303
304         return UNIT_VTABLE(u)->active_state(u);
305 }
306
307 static int ensure_merge(Set **s, Set *other) {
308
309         if (!other)
310                 return 0;
311
312         if (*s)
313                 return set_merge(*s, other);
314
315         if (!(*s = set_copy(other)))
316                 return -ENOMEM;
317
318         return 0;
319 }
320
321 /* FIXME: Does not rollback on failure! Needs to fix special unit
322  * pointers. Needs to merge names and dependencies properly.*/
323 int unit_merge(Unit *u, Unit *other) {
324         int r;
325         UnitDependency d;
326
327         assert(u);
328         assert(other);
329         assert(u->meta.manager == other->meta.manager);
330
331         /* This merges 'other' into 'unit'. FIXME: This does not
332          * rollback on failure. */
333
334         if (u->meta.type != u->meta.type)
335                 return -EINVAL;
336
337         if (u->meta.load_state != UNIT_STUB)
338                 return -EINVAL;
339
340         /* Merge names */
341         if ((r = ensure_merge(&u->meta.names, other->meta.names)) < 0)
342                 return r;
343
344         /* Merge dependencies */
345         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
346                 /* fixme, the inverse mapping is missing */
347                 if ((r = ensure_merge(&u->meta.dependencies[d], other->meta.dependencies[d])) < 0)
348                         return r;
349
350         unit_add_to_dbus_queue(u);
351
352         return 0;
353 }
354
355 const char* unit_id(Unit *u) {
356         assert(u);
357
358         if (u->meta.id)
359                 return u->meta.id;
360
361         return set_first(u->meta.names);
362 }
363
364 const char *unit_description(Unit *u) {
365         assert(u);
366
367         if (u->meta.description)
368                 return u->meta.description;
369
370         return unit_id(u);
371 }
372
373 void unit_dump(Unit *u, FILE *f, const char *prefix) {
374         char *t;
375         UnitDependency d;
376         Iterator i;
377         char *p2;
378         const char *prefix2;
379         CGroupBonding *b;
380
381         assert(u);
382
383         if (!prefix)
384                 prefix = "";
385         p2 = strappend(prefix, "\t");
386         prefix2 = p2 ? p2 : prefix;
387
388         fprintf(f,
389                 "%s→ Unit %s:\n"
390                 "%s\tDescription: %s\n"
391                 "%s\tUnit Load State: %s\n"
392                 "%s\tUnit Active State: %s\n"
393                 "%s\tRecursive Stop: %s\n"
394                 "%s\tStop When Unneeded: %s\n",
395                 prefix, unit_id(u),
396                 prefix, unit_description(u),
397                 prefix, unit_load_state_to_string(u->meta.load_state),
398                 prefix, unit_active_state_to_string(unit_active_state(u)),
399                 prefix, yes_no(u->meta.recursive_stop),
400                 prefix, yes_no(u->meta.stop_when_unneeded));
401
402         if (u->meta.fragment_path)
403                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
404
405         SET_FOREACH(t, u->meta.names, i)
406                 fprintf(f, "%s\tName: %s\n", prefix, t);
407
408         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
409                 Unit *other;
410
411                 if (set_isempty(u->meta.dependencies[d]))
412                         continue;
413
414                 SET_FOREACH(other, u->meta.dependencies[d], i)
415                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), unit_id(other));
416         }
417
418         LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
419                 fprintf(f, "%s\tControlGroup: %s:%s\n",
420                         prefix, b->controller, b->path);
421
422         if (UNIT_VTABLE(u)->dump)
423                 UNIT_VTABLE(u)->dump(u, f, prefix2);
424
425         if (u->meta.job)
426                 job_dump(u->meta.job, f, prefix2);
427
428         free(p2);
429 }
430
431 /* Common implementation for multiple backends */
432 int unit_load_fragment_and_dropin(Unit *u) {
433         int r, ret;
434
435         assert(u);
436
437         /* Load a .socket file */
438         if ((r = unit_load_fragment(u)) < 0)
439                 return r;
440
441         ret = r > 0;
442
443         /* Load drop-in directory data */
444         if ((r = unit_load_dropin(u)) < 0)
445                 return r;
446
447         return ret;
448 }
449
450 int unit_load(Unit *u) {
451         int r;
452
453         assert(u);
454
455         if (u->meta.in_load_queue) {
456                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
457                 u->meta.in_load_queue = false;
458         }
459
460         if (u->meta.load_state != UNIT_STUB)
461                 return 0;
462
463         if (UNIT_VTABLE(u)->init)
464                 if ((r = UNIT_VTABLE(u)->init(u)) < 0)
465                         goto fail;
466
467         u->meta.load_state = UNIT_LOADED;
468         unit_add_to_dbus_queue(u);
469         return 0;
470
471 fail:
472         u->meta.load_state = UNIT_FAILED;
473         unit_add_to_dbus_queue(u);
474         return r;
475 }
476
477 /* Errors:
478  *         -EBADR:    This unit type does not support starting.
479  *         -EALREADY: Unit is already started.
480  *         -EAGAIN:   An operation is already in progress. Retry later.
481  */
482 int unit_start(Unit *u) {
483         UnitActiveState state;
484
485         assert(u);
486
487         /* If this is already (being) started, then this will
488          * succeed. Note that this will even succeed if this unit is
489          * not startable by the user. This is relied on to detect when
490          * we need to wait for units and when waiting is finished. */
491         state = unit_active_state(u);
492         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
493                 return -EALREADY;
494
495         /* If it is stopped, but we cannot start it, then fail */
496         if (!UNIT_VTABLE(u)->start)
497                 return -EBADR;
498
499         /* We don't suppress calls to ->start() here when we are
500          * already starting, to allow this request to be used as a
501          * "hurry up" call, for example when the unit is in some "auto
502          * restart" state where it waits for a holdoff timer to elapse
503          * before it will start again. */
504
505         unit_add_to_dbus_queue(u);
506         return UNIT_VTABLE(u)->start(u);
507 }
508
509 bool unit_can_start(Unit *u) {
510         assert(u);
511
512         return !!UNIT_VTABLE(u)->start;
513 }
514
515 /* Errors:
516  *         -EBADR:    This unit type does not support stopping.
517  *         -EALREADY: Unit is already stopped.
518  *         -EAGAIN:   An operation is already in progress. Retry later.
519  */
520 int unit_stop(Unit *u) {
521         UnitActiveState state;
522
523         assert(u);
524
525         state = unit_active_state(u);
526         if (state == UNIT_INACTIVE)
527                 return -EALREADY;
528
529         if (!UNIT_VTABLE(u)->stop)
530                 return -EBADR;
531
532         if (state == UNIT_DEACTIVATING)
533                 return 0;
534
535         unit_add_to_dbus_queue(u);
536         return UNIT_VTABLE(u)->stop(u);
537 }
538
539 /* Errors:
540  *         -EBADR:    This unit type does not support reloading.
541  *         -ENOEXEC:  Unit is not started.
542  *         -EAGAIN:   An operation is already in progress. Retry later.
543  */
544 int unit_reload(Unit *u) {
545         UnitActiveState state;
546
547         assert(u);
548
549         if (!unit_can_reload(u))
550                 return -EBADR;
551
552         state = unit_active_state(u);
553         if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
554                 return -EALREADY;
555
556         if (unit_active_state(u) != UNIT_ACTIVE)
557                 return -ENOEXEC;
558
559         unit_add_to_dbus_queue(u);
560         return UNIT_VTABLE(u)->reload(u);
561 }
562
563 bool unit_can_reload(Unit *u) {
564         assert(u);
565
566         if (!UNIT_VTABLE(u)->reload)
567                 return false;
568
569         if (!UNIT_VTABLE(u)->can_reload)
570                 return true;
571
572         return UNIT_VTABLE(u)->can_reload(u);
573 }
574
575 static void unit_check_uneeded(Unit *u) {
576         Iterator i;
577         Unit *other;
578
579         assert(u);
580
581         /* If this service shall be shut down when unneeded then do
582          * so. */
583
584         if (!u->meta.stop_when_unneeded)
585                 return;
586
587         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
588                 return;
589
590         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
591                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
592                         return;
593
594         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRED_BY], i)
595                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
596                         return;
597
598         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
599                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
600                         return;
601
602         log_debug("Service %s is not needed anymore. Stopping.", unit_id(u));
603
604         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
605         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL);
606 }
607
608 static void retroactively_start_dependencies(Unit *u) {
609         Iterator i;
610         Unit *other;
611
612         assert(u);
613         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
614
615         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
616                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
617                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
618
619         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
620                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
621                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
622
623         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
624                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
625                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
626
627         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
628                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
629                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
630
631         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
632                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
633                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
634 }
635
636 static void retroactively_stop_dependencies(Unit *u) {
637         Iterator i;
638         Unit *other;
639
640         assert(u);
641         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
642
643         if (u->meta.recursive_stop) {
644                 /* Pull down units need us recursively if enabled */
645                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
646                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
647                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
648         }
649
650         /* Garbage collect services that might not be needed anymore, if enabled */
651         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
652                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
653                         unit_check_uneeded(other);
654         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
655                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
656                         unit_check_uneeded(other);
657         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
658                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
659                         unit_check_uneeded(other);
660         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
661                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
662                         unit_check_uneeded(other);
663         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUISITE], i)
664                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
665                         unit_check_uneeded(other);
666 }
667
668 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
669         assert(u);
670         assert(os < _UNIT_ACTIVE_STATE_MAX);
671         assert(ns < _UNIT_ACTIVE_STATE_MAX);
672         assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
673         assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
674
675         if (os == ns)
676                 return;
677
678         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
679                 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
680         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
681                 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
682
683         if (u->meta.job) {
684
685                 if (u->meta.job->state == JOB_WAITING)
686
687                         /* So we reached a different state for this
688                          * job. Let's see if we can run it now if it
689                          * failed previously due to EAGAIN. */
690                         job_add_to_run_queue(u->meta.job);
691
692                 else {
693                         assert(u->meta.job->state == JOB_RUNNING);
694
695                         /* Let's check whether this state change
696                          * constitutes a finished job, or maybe
697                          * cotradicts a running job and hence needs to
698                          * invalidate jobs. */
699
700                         switch (u->meta.job->type) {
701
702                         case JOB_START:
703                         case JOB_VERIFY_ACTIVE:
704
705                                 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
706                                         job_finish_and_invalidate(u->meta.job, true);
707                                         return;
708                                 } else if (ns == UNIT_ACTIVATING)
709                                         return;
710                                 else
711                                         job_finish_and_invalidate(u->meta.job, false);
712
713                                 break;
714
715                         case JOB_RELOAD:
716                         case JOB_RELOAD_OR_START:
717
718                                 if (ns == UNIT_ACTIVE) {
719                                         job_finish_and_invalidate(u->meta.job, true);
720                                         return;
721                                 } else if (ns == UNIT_ACTIVATING || ns == UNIT_ACTIVE_RELOADING)
722                                         return;
723                                 else
724                                         job_finish_and_invalidate(u->meta.job, false);
725
726                                 break;
727
728                         case JOB_STOP:
729                         case JOB_RESTART:
730                         case JOB_TRY_RESTART:
731
732                                 if (ns == UNIT_INACTIVE) {
733                                         job_finish_and_invalidate(u->meta.job, true);
734                                         return;
735                                 } else if (ns == UNIT_DEACTIVATING)
736                                         return;
737                                 else
738                                         job_finish_and_invalidate(u->meta.job, false);
739
740                                 break;
741
742                         default:
743                                 assert_not_reached("Job type unknown");
744                         }
745                 }
746         }
747
748         /* If this state change happened without being requested by a
749          * job, then let's retroactively start or stop dependencies */
750
751         if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
752                 retroactively_start_dependencies(u);
753         else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
754                 retroactively_stop_dependencies(u);
755
756         /* Maybe we finished startup and are now ready for being
757          * stopped because unneeded? */
758         unit_check_uneeded(u);
759
760         unit_add_to_dbus_queue(u);
761 }
762
763 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
764         struct epoll_event ev;
765
766         assert(u);
767         assert(fd >= 0);
768         assert(w);
769         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
770
771         zero(ev);
772         ev.data.ptr = w;
773         ev.events = events;
774
775         if (epoll_ctl(u->meta.manager->epoll_fd,
776                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
777                       fd,
778                       &ev) < 0)
779                 return -errno;
780
781         w->fd = fd;
782         w->type = WATCH_FD;
783         w->data.unit = u;
784
785         return 0;
786 }
787
788 void unit_unwatch_fd(Unit *u, Watch *w) {
789         assert(u);
790         assert(w);
791
792         if (w->type == WATCH_INVALID)
793                 return;
794
795         assert(w->type == WATCH_FD);
796         assert(w->data.unit == u);
797         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
798
799         w->fd = -1;
800         w->type = WATCH_INVALID;
801         w->data.unit = NULL;
802 }
803
804 int unit_watch_pid(Unit *u, pid_t pid) {
805         assert(u);
806         assert(pid >= 1);
807
808         return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
809 }
810
811 void unit_unwatch_pid(Unit *u, pid_t pid) {
812         assert(u);
813         assert(pid >= 1);
814
815         hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
816 }
817
818 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
819         struct itimerspec its;
820         int flags, fd;
821         bool ours;
822
823         assert(u);
824         assert(w);
825         assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->data.unit == u));
826
827         /* This will try to reuse the old timer if there is one */
828
829         if (w->type == WATCH_TIMER) {
830                 ours = false;
831                 fd = w->fd;
832         } else {
833                 ours = true;
834                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
835                         return -errno;
836         }
837
838         zero(its);
839
840         if (delay <= 0) {
841                 /* Set absolute time in the past, but not 0, since we
842                  * don't want to disarm the timer */
843                 its.it_value.tv_sec = 0;
844                 its.it_value.tv_nsec = 1;
845
846                 flags = TFD_TIMER_ABSTIME;
847         } else {
848                 timespec_store(&its.it_value, delay);
849                 flags = 0;
850         }
851
852         /* This will also flush the elapse counter */
853         if (timerfd_settime(fd, flags, &its, NULL) < 0)
854                 goto fail;
855
856         if (w->type == WATCH_INVALID) {
857                 struct epoll_event ev;
858
859                 zero(ev);
860                 ev.data.ptr = w;
861                 ev.events = EPOLLIN;
862
863                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
864                         goto fail;
865         }
866
867         w->fd = fd;
868         w->type = WATCH_TIMER;
869         w->data.unit = u;
870
871         return 0;
872
873 fail:
874         if (ours)
875                 close_nointr_nofail(fd);
876
877         return -errno;
878 }
879
880 void unit_unwatch_timer(Unit *u, Watch *w) {
881         assert(u);
882         assert(w);
883
884         if (w->type == WATCH_INVALID)
885                 return;
886
887         assert(w->type == WATCH_TIMER && w->data.unit == u);
888
889         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
890         assert_se(close_nointr(w->fd) == 0);
891
892         w->fd = -1;
893         w->type = WATCH_INVALID;
894         w->data.unit = NULL;
895 }
896
897 bool unit_job_is_applicable(Unit *u, JobType j) {
898         assert(u);
899         assert(j >= 0 && j < _JOB_TYPE_MAX);
900
901         switch (j) {
902
903         case JOB_VERIFY_ACTIVE:
904         case JOB_START:
905                 return true;
906
907         case JOB_STOP:
908         case JOB_RESTART:
909         case JOB_TRY_RESTART:
910                 return unit_can_start(u);
911
912         case JOB_RELOAD:
913                 return unit_can_reload(u);
914
915         case JOB_RELOAD_OR_START:
916                 return unit_can_reload(u) && unit_can_start(u);
917
918         default:
919                 assert_not_reached("Invalid job type");
920         }
921 }
922
923 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
924
925         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
926                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
927                 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
928                 [UNIT_WANTS] = UNIT_WANTED_BY,
929                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
930                 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
931                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
932                 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
933                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
934                 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
935                 [UNIT_BEFORE] = UNIT_AFTER,
936                 [UNIT_AFTER] = UNIT_BEFORE
937         };
938         int r;
939
940         assert(u);
941         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
942         assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
943         assert(other);
944
945         /* We won't allow dependencies on ourselves. We will not
946          * consider them an error however. */
947         if (u == other)
948                 return 0;
949
950         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
951                 return r;
952
953         if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
954                 return r;
955
956         if ((r = set_put(u->meta.dependencies[d], other)) < 0)
957                 return r;
958
959         if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
960                 set_remove(u->meta.dependencies[d], other);
961                 return r;
962         }
963
964         unit_add_to_dbus_queue(u);
965         return 0;
966 }
967
968 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
969         Unit *other;
970         int r;
971
972         if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
973                 return r;
974
975         if ((r = unit_add_dependency(u, d, other)) < 0)
976                 return r;
977
978         return 0;
979 }
980
981 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name) {
982         Unit *other;
983         int r;
984
985         if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
986                 return r;
987
988         if ((r = unit_add_dependency(other, d, u)) < 0)
989                 return r;
990
991         return 0;
992 }
993
994 int set_unit_path(const char *p) {
995         char *cwd, *c;
996         int r;
997
998         /* This is mostly for debug purposes */
999
1000         if (path_is_absolute(p)) {
1001                 if (!(c = strdup(p)))
1002                         return -ENOMEM;
1003         } else {
1004                 if (!(cwd = get_current_dir_name()))
1005                         return -errno;
1006
1007                 r = asprintf(&c, "%s/%s", cwd, p);
1008                 free(cwd);
1009
1010                 if (r < 0)
1011                         return -ENOMEM;
1012         }
1013
1014         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1015                 r = -errno;
1016                 free(c);
1017                 return r;
1018         }
1019
1020         return 0;
1021 }
1022
1023 char *unit_name_escape_path(const char *path, const char *suffix) {
1024         char *r, *t;
1025         const char *f;
1026         size_t a, b;
1027
1028         assert(path);
1029
1030         /* Takes a path and a suffix and prefix and makes a nice
1031          * string suitable as unit name of it, escaping all weird
1032          * chars on the way.
1033          *
1034          * / becomes ., and all chars not alloweed in a unit name get
1035          * escaped as \xFF, including \ and ., of course. This
1036          * escaping is hence reversible.
1037          */
1038
1039         if (!suffix)
1040                 suffix = "";
1041
1042         a = strlen(path);
1043         b = strlen(suffix);
1044
1045         if (!(r = new(char, a*4+b+1)))
1046                 return NULL;
1047
1048         for (f = path, t = r; *f; f++) {
1049                 if (*f == '/')
1050                         *(t++) = '.';
1051                 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
1052                         *(t++) = '\\';
1053                         *(t++) = 'x';
1054                         *(t++) = hexchar(*f > 4);
1055                         *(t++) = hexchar(*f);
1056                 } else
1057                         *(t++) = *f;
1058         }
1059
1060         memcpy(t, suffix, b+1);
1061
1062         return r;
1063 }
1064
1065 char *unit_dbus_path(Unit *u) {
1066         char *p, *e;
1067
1068         assert(u);
1069
1070         if (!(e = bus_path_escape(unit_id(u))))
1071                 return NULL;
1072
1073         if (asprintf(&p, "/org/freedesktop/systemd1/unit/%s", e) < 0) {
1074                 free(e);
1075                 return NULL;
1076         }
1077
1078         free(e);
1079         return p;
1080 }
1081
1082 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1083         CGroupBonding *l;
1084         int r;
1085
1086         assert(u);
1087         assert(b);
1088         assert(b->path);
1089
1090         /* Ensure this hasn't been added yet */
1091         assert(!b->unit);
1092
1093         l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1094         LIST_PREPEND(CGroupBonding, by_path, l, b);
1095
1096         if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1097                 LIST_REMOVE(CGroupBonding, by_path, l, b);
1098                 return r;
1099         }
1100
1101         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1102         b->unit = u;
1103
1104         return 0;
1105 }
1106
1107 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1108         size_t n;
1109         const char *p;
1110         char *controller;
1111         CGroupBonding *b;
1112         int r;
1113
1114         assert(u);
1115         assert(name);
1116
1117         /* Detect controller name */
1118         n = strcspn(name, ":/");
1119
1120         /* Only controller name, no path? No path? */
1121         if (name[n] == 0)
1122                 return -EINVAL;
1123
1124         if (n > 0) {
1125                 if (name[n] != ':')
1126                         return -EINVAL;
1127
1128                 p = name+n+1;
1129         } else
1130                 p = name;
1131
1132         /* Insist in absolute paths */
1133         if (p[0] != '/')
1134                 return -EINVAL;
1135
1136         if (!(controller = strndup(name, n)))
1137                 return -ENOMEM;
1138
1139         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1140                 free(controller);
1141                 return -EEXIST;
1142         }
1143
1144         if (!(b = new0(CGroupBonding, 1))) {
1145                 free(controller);
1146                 return -ENOMEM;
1147         }
1148
1149         b->controller = controller;
1150
1151         if (!(b->path = strdup(p))) {
1152                 r = -ENOMEM;
1153                 goto fail;
1154         }
1155
1156         b->only_us = false;
1157         b->clean_up = false;
1158
1159         if ((r = unit_add_cgroup(u, b)) < 0)
1160                 goto fail;
1161
1162         return 0;
1163
1164 fail:
1165         free(b->path);
1166         free(b->controller);
1167         free(b);
1168
1169         return r;
1170 }
1171
1172 int unit_add_default_cgroup(Unit *u) {
1173         CGroupBonding *b;
1174         int r = -ENOMEM;
1175
1176         assert(u);
1177
1178         /* Adds in the default cgroup data, if it wasn't specified yet */
1179
1180         if (unit_get_default_cgroup(u))
1181                 return 0;
1182
1183         if (!(b = new0(CGroupBonding, 1)))
1184                 return -ENOMEM;
1185
1186         if (!(b->controller = strdup(u->meta.manager->cgroup_controller)))
1187                 goto fail;
1188
1189         if (asprintf(&b->path, "%s/%s", u->meta.manager->cgroup_hierarchy, unit_id(u)) < 0)
1190                 goto fail;
1191
1192         b->clean_up = true;
1193         b->only_us = true;
1194
1195         if ((r = unit_add_cgroup(u, b)) < 0)
1196                 goto fail;
1197
1198         return 0;
1199
1200 fail:
1201         free(b->path);
1202         free(b->controller);
1203         free(b);
1204
1205         return r;
1206 }
1207
1208 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1209         assert(u);
1210
1211         return cgroup_bonding_find_list(u->meta.cgroup_bondings, u->meta.manager->cgroup_controller);
1212 }
1213
1214 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
1215         [UNIT_SERVICE] = "service",
1216         [UNIT_TIMER] = "timer",
1217         [UNIT_SOCKET] = "socket",
1218         [UNIT_TARGET] = "target",
1219         [UNIT_DEVICE] = "device",
1220         [UNIT_MOUNT] = "mount",
1221         [UNIT_AUTOMOUNT] = "automount",
1222         [UNIT_SNAPSHOT] = "snapshot"
1223 };
1224
1225 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
1226
1227 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
1228         [UNIT_STUB] = "stub",
1229         [UNIT_LOADED] = "loaded",
1230         [UNIT_FAILED] = "failed"
1231 };
1232
1233 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
1234
1235 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
1236         [UNIT_ACTIVE] = "active",
1237         [UNIT_INACTIVE] = "inactive",
1238         [UNIT_ACTIVATING] = "activating",
1239         [UNIT_DEACTIVATING] = "deactivating"
1240 };
1241
1242 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
1243
1244 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
1245         [UNIT_REQUIRES] = "Requires",
1246         [UNIT_SOFT_REQUIRES] = "SoftRequires",
1247         [UNIT_WANTS] = "Wants",
1248         [UNIT_REQUISITE] = "Requisite",
1249         [UNIT_SOFT_REQUISITE] = "SoftRequisite",
1250         [UNIT_REQUIRED_BY] = "RequiredBy",
1251         [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
1252         [UNIT_WANTED_BY] = "WantedBy",
1253         [UNIT_CONFLICTS] = "Conflicts",
1254         [UNIT_BEFORE] = "Before",
1255         [UNIT_AFTER] = "After",
1256 };
1257
1258 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);