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