chiark / gitweb /
socket: fix error handling
[elogind.git] / src / 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 #include "unit-name.h"
39 #include "specifier.h"
40 #include "dbus-unit.h"
41
42 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
43         [UNIT_SERVICE] = &service_vtable,
44         [UNIT_TIMER] = &timer_vtable,
45         [UNIT_SOCKET] = &socket_vtable,
46         [UNIT_TARGET] = &target_vtable,
47         [UNIT_DEVICE] = &device_vtable,
48         [UNIT_MOUNT] = &mount_vtable,
49         [UNIT_AUTOMOUNT] = &automount_vtable,
50         [UNIT_SNAPSHOT] = &snapshot_vtable,
51         [UNIT_SWAP] = &swap_vtable
52 };
53
54 Unit *unit_new(Manager *m) {
55         Unit *u;
56
57         assert(m);
58
59         if (!(u = new0(Unit, 1)))
60                 return NULL;
61
62         if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
63                 free(u);
64                 return NULL;
65         }
66
67         u->meta.manager = m;
68         u->meta.type = _UNIT_TYPE_INVALID;
69
70         return u;
71 }
72
73 bool unit_has_name(Unit *u, const char *name) {
74         assert(u);
75         assert(name);
76
77         return !!set_get(u->meta.names, (char*) name);
78 }
79
80 int unit_add_name(Unit *u, const char *text) {
81         UnitType t;
82         char *s = NULL, *i = NULL;
83         int r;
84
85         assert(u);
86         assert(text);
87
88         if (unit_name_is_template(text)) {
89                 if (!u->meta.instance)
90                         return -EINVAL;
91
92                 s = unit_name_replace_instance(text, u->meta.instance);
93         } else
94                 s = strdup(text);
95
96         if (!s)
97                 return -ENOMEM;
98
99         if (!unit_name_is_valid(s)) {
100                 r = -EINVAL;
101                 goto fail;
102         }
103
104         assert_se((t = unit_name_to_type(s)) >= 0);
105
106         if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type) {
107                 r = -EINVAL;
108                 goto fail;
109         }
110
111         if ((r = unit_name_to_instance(s, &i)) < 0)
112                 goto fail;
113
114         if (i && unit_vtable[t]->no_instances)
115                 goto fail;
116
117         if (u->meta.type != _UNIT_TYPE_INVALID && !streq_ptr(u->meta.instance, i)) {
118                 r = -EINVAL;
119                 goto fail;
120         }
121
122         if (unit_vtable[t]->no_alias &&
123             !set_isempty(u->meta.names) &&
124             !set_get(u->meta.names, s)) {
125                 r = -EEXIST;
126                 goto fail;
127         }
128
129         if (hashmap_size(u->meta.manager->units) >= MANAGER_MAX_NAMES) {
130                 r = -E2BIG;
131                 goto fail;
132         }
133
134         if ((r = set_put(u->meta.names, s)) < 0) {
135                 if (r == -EEXIST)
136                         r = 0;
137                 goto fail;
138         }
139
140         if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
141                 set_remove(u->meta.names, s);
142                 goto fail;
143         }
144
145         if (u->meta.type == _UNIT_TYPE_INVALID) {
146
147                 u->meta.type = t;
148                 u->meta.id = s;
149                 u->meta.instance = i;
150
151                 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
152
153                 if (UNIT_VTABLE(u)->init)
154                         UNIT_VTABLE(u)->init(u);
155         } else
156                 free(i);
157
158         unit_add_to_dbus_queue(u);
159         return 0;
160
161 fail:
162         free(s);
163         free(i);
164
165         return r;
166 }
167
168 int unit_choose_id(Unit *u, const char *name) {
169         char *s, *t = NULL;
170
171         assert(u);
172         assert(name);
173
174         if (unit_name_is_template(name)) {
175
176                 if (!u->meta.instance)
177                         return -EINVAL;
178
179                 if (!(t = unit_name_replace_instance(name, u->meta.instance)))
180                         return -ENOMEM;
181
182                 name = t;
183         }
184
185         /* Selects one of the names of this unit as the id */
186         s = set_get(u->meta.names, (char*) name);
187         free(t);
188
189         if (!s)
190                 return -ENOENT;
191
192         u->meta.id = s;
193         unit_add_to_dbus_queue(u);
194
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 bool unit_check_gc(Unit *u) {
214         assert(u);
215
216         if (u->meta.load_state == UNIT_STUB)
217                 return true;
218
219         if (UNIT_VTABLE(u)->no_gc)
220                 return true;
221
222         if (u->meta.job)
223                 return true;
224
225         if (unit_active_state(u) != UNIT_INACTIVE)
226                 return true;
227
228         if (UNIT_VTABLE(u)->check_gc)
229                 if (UNIT_VTABLE(u)->check_gc(u))
230                         return true;
231
232         return false;
233 }
234
235 void unit_add_to_load_queue(Unit *u) {
236         assert(u);
237         assert(u->meta.type != _UNIT_TYPE_INVALID);
238
239         if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
240                 return;
241
242         LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
243         u->meta.in_load_queue = true;
244 }
245
246 void unit_add_to_cleanup_queue(Unit *u) {
247         assert(u);
248
249         if (u->meta.in_cleanup_queue)
250                 return;
251
252         LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
253         u->meta.in_cleanup_queue = true;
254 }
255
256 void unit_add_to_gc_queue(Unit *u) {
257         assert(u);
258
259         if (u->meta.in_gc_queue || u->meta.in_cleanup_queue)
260                 return;
261
262         if (unit_check_gc(u))
263                 return;
264
265         LIST_PREPEND(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
266         u->meta.in_gc_queue = true;
267
268         u->meta.manager->n_in_gc_queue ++;
269
270         if (u->meta.manager->gc_queue_timestamp <= 0)
271                 u->meta.manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
272 }
273
274 void unit_add_to_dbus_queue(Unit *u) {
275         assert(u);
276         assert(u->meta.type != _UNIT_TYPE_INVALID);
277
278         if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue)
279                 return;
280
281         if (set_isempty(u->meta.manager->subscribed)) {
282                 u->meta.sent_dbus_new_signal = true;
283                 return;
284         }
285
286         LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
287         u->meta.in_dbus_queue = true;
288 }
289
290 static void bidi_set_free(Unit *u, Set *s) {
291         Iterator i;
292         Unit *other;
293
294         assert(u);
295
296         /* Frees the set and makes sure we are dropped from the
297          * inverse pointers */
298
299         SET_FOREACH(other, s, i) {
300                 UnitDependency d;
301
302                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
303                         set_remove(other->meta.dependencies[d], u);
304
305                 unit_add_to_gc_queue(other);
306         }
307
308         set_free(s);
309 }
310
311 void unit_free(Unit *u) {
312         UnitDependency d;
313         Iterator i;
314         char *t;
315
316         assert(u);
317
318         bus_unit_send_removed_signal(u);
319
320         /* Detach from next 'bigger' objects */
321         SET_FOREACH(t, u->meta.names, i)
322                 hashmap_remove_value(u->meta.manager->units, t, u);
323
324         if (u->meta.type != _UNIT_TYPE_INVALID)
325                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
326
327         if (u->meta.in_load_queue)
328                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
329
330         if (u->meta.in_dbus_queue)
331                 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
332
333         if (u->meta.in_cleanup_queue)
334                 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
335
336         if (u->meta.in_gc_queue) {
337                 LIST_REMOVE(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
338                 u->meta.manager->n_in_gc_queue--;
339         }
340
341         /* Free data and next 'smaller' objects */
342         if (u->meta.job)
343                 job_free(u->meta.job);
344
345         if (u->meta.load_state != UNIT_STUB)
346                 if (UNIT_VTABLE(u)->done)
347                         UNIT_VTABLE(u)->done(u);
348
349         cgroup_bonding_free_list(u->meta.cgroup_bondings);
350
351         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
352                 bidi_set_free(u, u->meta.dependencies[d]);
353
354         free(u->meta.description);
355         free(u->meta.fragment_path);
356
357         while ((t = set_steal_first(u->meta.names)))
358                 free(t);
359         set_free(u->meta.names);
360
361         free(u->meta.instance);
362
363         free(u);
364 }
365
366 UnitActiveState unit_active_state(Unit *u) {
367         assert(u);
368
369         if (u->meta.load_state != UNIT_LOADED)
370                 return UNIT_INACTIVE;
371
372         return UNIT_VTABLE(u)->active_state(u);
373 }
374
375 const char* unit_sub_state_to_string(Unit *u) {
376         assert(u);
377
378         return UNIT_VTABLE(u)->sub_state_to_string(u);
379 }
380
381 static void complete_move(Set **s, Set **other) {
382         assert(s);
383         assert(other);
384
385         if (!*other)
386                 return;
387
388         if (*s)
389                 set_move(*s, *other);
390         else {
391                 *s = *other;
392                 *other = NULL;
393         }
394 }
395
396 static void merge_names(Unit *u, Unit *other) {
397         char *t;
398         Iterator i;
399
400         assert(u);
401         assert(other);
402
403         complete_move(&u->meta.names, &other->meta.names);
404
405         while ((t = set_steal_first(other->meta.names)))
406                 free(t);
407
408         set_free(other->meta.names);
409         other->meta.names = NULL;
410         other->meta.id = NULL;
411
412         SET_FOREACH(t, u->meta.names, i)
413                 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
414 }
415
416 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
417         Iterator i;
418         Unit *back;
419         int r;
420
421         assert(u);
422         assert(other);
423         assert(d < _UNIT_DEPENDENCY_MAX);
424
425         SET_FOREACH(back, other->meta.dependencies[d], i) {
426                 UnitDependency k;
427
428                 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
429                         if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
430
431                                 if (r == -EEXIST)
432                                         set_remove(back->meta.dependencies[k], other);
433                                 else
434                                         assert(r == -ENOENT);
435                         }
436         }
437
438         complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
439
440         set_free(other->meta.dependencies[d]);
441         other->meta.dependencies[d] = NULL;
442 }
443
444 int unit_merge(Unit *u, Unit *other) {
445         UnitDependency d;
446
447         assert(u);
448         assert(other);
449         assert(u->meta.manager == other->meta.manager);
450         assert(u->meta.type != _UNIT_TYPE_INVALID);
451
452         other = unit_follow_merge(other);
453
454         if (other == u)
455                 return 0;
456
457         if (u->meta.type != other->meta.type)
458                 return -EINVAL;
459
460         if (!streq_ptr(u->meta.instance, other->meta.instance))
461                 return -EINVAL;
462
463         if (other->meta.load_state != UNIT_STUB &&
464             other->meta.load_state != UNIT_FAILED)
465                 return -EEXIST;
466
467         if (other->meta.job)
468                 return -EEXIST;
469
470         if (unit_active_state(other) != UNIT_INACTIVE)
471                 return -EEXIST;
472
473         /* Merge names */
474         merge_names(u, other);
475
476         /* Merge dependencies */
477         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
478                 merge_dependencies(u, other, d);
479
480         other->meta.load_state = UNIT_MERGED;
481         other->meta.merged_into = u;
482
483         /* If there is still some data attached to the other node, we
484          * don't need it anymore, and can free it. */
485         if (other->meta.load_state != UNIT_STUB)
486                 if (UNIT_VTABLE(other)->done)
487                         UNIT_VTABLE(other)->done(other);
488
489         unit_add_to_dbus_queue(u);
490         unit_add_to_cleanup_queue(other);
491
492         return 0;
493 }
494
495 int unit_merge_by_name(Unit *u, const char *name) {
496         Unit *other;
497         int r;
498         char *s = NULL;
499
500         assert(u);
501         assert(name);
502
503         if (unit_name_is_template(name)) {
504                 if (!u->meta.instance)
505                         return -EINVAL;
506
507                 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
508                         return -ENOMEM;
509
510                 name = s;
511         }
512
513         if (!(other = manager_get_unit(u->meta.manager, name)))
514                 r = unit_add_name(u, name);
515         else
516                 r = unit_merge(u, other);
517
518         free(s);
519         return r;
520 }
521
522 Unit* unit_follow_merge(Unit *u) {
523         assert(u);
524
525         while (u->meta.load_state == UNIT_MERGED)
526                 assert_se(u = u->meta.merged_into);
527
528         return u;
529 }
530
531 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
532         int r;
533
534         assert(u);
535         assert(c);
536
537         if (c->std_output != EXEC_OUTPUT_KMSG &&
538             c->std_output != EXEC_OUTPUT_SYSLOG &&
539             c->std_error != EXEC_OUTPUT_KMSG &&
540             c->std_error != EXEC_OUTPUT_SYSLOG)
541                 return 0;
542
543         /* If syslog or kernel logging is requested, make sure our own
544          * logging daemon is run first. */
545
546         if ((r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
547                 return r;
548
549         if (u->meta.manager->running_as != MANAGER_SESSION)
550                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
551                         return r;
552
553         return 0;
554 }
555
556 const char *unit_description(Unit *u) {
557         assert(u);
558
559         if (u->meta.description)
560                 return u->meta.description;
561
562         return u->meta.id;
563 }
564
565 void unit_dump(Unit *u, FILE *f, const char *prefix) {
566         char *t;
567         UnitDependency d;
568         Iterator i;
569         char *p2;
570         const char *prefix2;
571         CGroupBonding *b;
572         char
573                 timestamp1[FORMAT_TIMESTAMP_MAX],
574                 timestamp2[FORMAT_TIMESTAMP_MAX],
575                 timestamp3[FORMAT_TIMESTAMP_MAX],
576                 timestamp4[FORMAT_TIMESTAMP_MAX];
577
578         assert(u);
579         assert(u->meta.type >= 0);
580
581         if (!prefix)
582                 prefix = "";
583         p2 = strappend(prefix, "\t");
584         prefix2 = p2 ? p2 : prefix;
585
586         fprintf(f,
587                 "%s-> Unit %s:\n"
588                 "%s\tDescription: %s\n"
589                 "%s\tInstance: %s\n"
590                 "%s\tUnit Load State: %s\n"
591                 "%s\tUnit Active State: %s\n"
592                 "%s\tInactive Exit Timestamp: %s\n"
593                 "%s\tActive Enter Timestamp: %s\n"
594                 "%s\tActive Exit Timestamp: %s\n"
595                 "%s\tInactive Enter Timestamp: %s\n"
596                 "%s\tGC Check Good: %s\n",
597                 prefix, u->meta.id,
598                 prefix, unit_description(u),
599                 prefix, strna(u->meta.instance),
600                 prefix, unit_load_state_to_string(u->meta.load_state),
601                 prefix, unit_active_state_to_string(unit_active_state(u)),
602                 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp)),
603                 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp)),
604                 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp)),
605                 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp)),
606                 prefix, yes_no(unit_check_gc(u)));
607
608         SET_FOREACH(t, u->meta.names, i)
609                 fprintf(f, "%s\tName: %s\n", prefix, t);
610
611         if (u->meta.fragment_path)
612                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
613
614         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
615                 Unit *other;
616
617                 SET_FOREACH(other, u->meta.dependencies[d], i)
618                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
619         }
620
621         if (u->meta.load_state == UNIT_LOADED) {
622                 fprintf(f,
623                         "%s\tRecursive Stop: %s\n"
624                         "%s\tStop When Unneeded: %s\n",
625                         prefix, yes_no(u->meta.recursive_stop),
626                         prefix, yes_no(u->meta.stop_when_unneeded));
627
628                 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
629                         fprintf(f, "%s\tControlGroup: %s:%s\n",
630                                 prefix, b->controller, b->path);
631
632                 if (UNIT_VTABLE(u)->dump)
633                         UNIT_VTABLE(u)->dump(u, f, prefix2);
634
635         } else if (u->meta.load_state == UNIT_MERGED)
636                 fprintf(f,
637                         "%s\tMerged into: %s\n",
638                         prefix, u->meta.merged_into->meta.id);
639
640         if (u->meta.job)
641                 job_dump(u->meta.job, f, prefix2);
642
643         free(p2);
644 }
645
646 /* Common implementation for multiple backends */
647 int unit_load_fragment_and_dropin(Unit *u) {
648         int r;
649
650         assert(u);
651
652         /* Load a .service file */
653         if ((r = unit_load_fragment(u)) < 0)
654                 return r;
655
656         if (u->meta.load_state == UNIT_STUB)
657                 return -ENOENT;
658
659         /* Load drop-in directory data */
660         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
661                 return r;
662
663         return 0;
664 }
665
666 /* Common implementation for multiple backends */
667 int unit_load_fragment_and_dropin_optional(Unit *u) {
668         int r;
669
670         assert(u);
671
672         /* Same as unit_load_fragment_and_dropin(), but whether
673          * something can be loaded or not doesn't matter. */
674
675         /* Load a .service file */
676         if ((r = unit_load_fragment(u)) < 0)
677                 return r;
678
679         if (u->meta.load_state == UNIT_STUB)
680                 u->meta.load_state = UNIT_LOADED;
681
682         /* Load drop-in directory data */
683         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
684                 return r;
685
686         return 0;
687 }
688
689 /* Common implementation for multiple backends */
690 int unit_load_nop(Unit *u) {
691         assert(u);
692
693         if (u->meta.load_state == UNIT_STUB)
694                 u->meta.load_state = UNIT_LOADED;
695
696         return 0;
697 }
698
699 int unit_load(Unit *u) {
700         int r;
701
702         assert(u);
703
704         if (u->meta.in_load_queue) {
705                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
706                 u->meta.in_load_queue = false;
707         }
708
709         if (u->meta.type == _UNIT_TYPE_INVALID)
710                 return -EINVAL;
711
712         if (u->meta.load_state != UNIT_STUB)
713                 return 0;
714
715         if (UNIT_VTABLE(u)->load)
716                 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
717                         goto fail;
718
719         if (u->meta.load_state == UNIT_STUB) {
720                 r = -ENOENT;
721                 goto fail;
722         }
723
724         assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
725
726         unit_add_to_dbus_queue(unit_follow_merge(u));
727         unit_add_to_gc_queue(u);
728
729         return 0;
730
731 fail:
732         u->meta.load_state = UNIT_FAILED;
733         unit_add_to_dbus_queue(u);
734
735         log_debug("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
736
737         return r;
738 }
739
740 /* Errors:
741  *         -EBADR:     This unit type does not support starting.
742  *         -EALREADY:  Unit is already started.
743  *         -EAGAIN:    An operation is already in progress. Retry later.
744  *         -ECANCELED: Too many requests for now.
745  */
746 int unit_start(Unit *u) {
747         UnitActiveState state;
748
749         assert(u);
750
751         /* If this is already (being) started, then this will
752          * succeed. Note that this will even succeed if this unit is
753          * not startable by the user. This is relied on to detect when
754          * we need to wait for units and when waiting is finished. */
755         state = unit_active_state(u);
756         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
757                 return -EALREADY;
758
759         /* If it is stopped, but we cannot start it, then fail */
760         if (!UNIT_VTABLE(u)->start)
761                 return -EBADR;
762
763         /* We don't suppress calls to ->start() here when we are
764          * already starting, to allow this request to be used as a
765          * "hurry up" call, for example when the unit is in some "auto
766          * restart" state where it waits for a holdoff timer to elapse
767          * before it will start again. */
768
769         unit_add_to_dbus_queue(u);
770         return UNIT_VTABLE(u)->start(u);
771 }
772
773 bool unit_can_start(Unit *u) {
774         assert(u);
775
776         return !!UNIT_VTABLE(u)->start;
777 }
778
779 /* Errors:
780  *         -EBADR:    This unit type does not support stopping.
781  *         -EALREADY: Unit is already stopped.
782  *         -EAGAIN:   An operation is already in progress. Retry later.
783  */
784 int unit_stop(Unit *u) {
785         UnitActiveState state;
786
787         assert(u);
788
789         state = unit_active_state(u);
790         if (state == UNIT_INACTIVE)
791                 return -EALREADY;
792
793         if (!UNIT_VTABLE(u)->stop)
794                 return -EBADR;
795
796         unit_add_to_dbus_queue(u);
797         return UNIT_VTABLE(u)->stop(u);
798 }
799
800 /* Errors:
801  *         -EBADR:    This unit type does not support reloading.
802  *         -ENOEXEC:  Unit is not started.
803  *         -EAGAIN:   An operation is already in progress. Retry later.
804  */
805 int unit_reload(Unit *u) {
806         UnitActiveState state;
807
808         assert(u);
809
810         if (!unit_can_reload(u))
811                 return -EBADR;
812
813         state = unit_active_state(u);
814         if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
815                 return -EALREADY;
816
817         if (unit_active_state(u) != UNIT_ACTIVE)
818                 return -ENOEXEC;
819
820         unit_add_to_dbus_queue(u);
821         return UNIT_VTABLE(u)->reload(u);
822 }
823
824 bool unit_can_reload(Unit *u) {
825         assert(u);
826
827         if (!UNIT_VTABLE(u)->reload)
828                 return false;
829
830         if (!UNIT_VTABLE(u)->can_reload)
831                 return true;
832
833         return UNIT_VTABLE(u)->can_reload(u);
834 }
835
836 static void unit_check_uneeded(Unit *u) {
837         Iterator i;
838         Unit *other;
839
840         assert(u);
841
842         /* If this service shall be shut down when unneeded then do
843          * so. */
844
845         if (!u->meta.stop_when_unneeded)
846                 return;
847
848         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
849                 return;
850
851         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
852                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
853                         return;
854
855         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
856                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
857                         return;
858
859         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
860                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
861                         return;
862
863         log_debug("Service %s is not needed anymore. Stopping.", u->meta.id);
864
865         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
866         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL);
867 }
868
869 static void retroactively_start_dependencies(Unit *u) {
870         Iterator i;
871         Unit *other;
872
873         assert(u);
874         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
875
876         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
877                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
878                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
879
880         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
881                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
882                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
883
884         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
885                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
886                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
887
888         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
889                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
890                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
891
892         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
893                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
894                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
895 }
896
897 static void retroactively_stop_dependencies(Unit *u) {
898         Iterator i;
899         Unit *other;
900
901         assert(u);
902         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
903
904         if (u->meta.recursive_stop) {
905                 /* Pull down units need us recursively if enabled */
906                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
907                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
908                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
909         }
910
911         /* Garbage collect services that might not be needed anymore, if enabled */
912         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
913                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
914                         unit_check_uneeded(other);
915         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
916                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
917                         unit_check_uneeded(other);
918         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
919                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
920                         unit_check_uneeded(other);
921         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
922                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
923                         unit_check_uneeded(other);
924         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
925                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
926                         unit_check_uneeded(other);
927 }
928
929 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
930         bool unexpected = false;
931         usec_t ts;
932
933         assert(u);
934         assert(os < _UNIT_ACTIVE_STATE_MAX);
935         assert(ns < _UNIT_ACTIVE_STATE_MAX);
936
937         /* Note that this is called for all low-level state changes,
938          * even if they might map to the same high-level
939          * UnitActiveState! That means that ns == os is OK an expected
940          * behaviour here. For example: if a mount point is remounted
941          * this function will be called too and the utmp code below
942          * relies on that! */
943
944         ts = now(CLOCK_REALTIME);
945
946         if (os == UNIT_INACTIVE && ns != UNIT_INACTIVE)
947                 u->meta.inactive_exit_timestamp = ts;
948         else if (os != UNIT_INACTIVE && ns == UNIT_INACTIVE)
949                 u->meta.inactive_enter_timestamp = ts;
950
951         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
952                 u->meta.active_enter_timestamp = ts;
953         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
954                 u->meta.active_exit_timestamp = ts;
955
956         if (u->meta.job) {
957
958                 if (u->meta.job->state == JOB_WAITING)
959
960                         /* So we reached a different state for this
961                          * job. Let's see if we can run it now if it
962                          * failed previously due to EAGAIN. */
963                         job_add_to_run_queue(u->meta.job);
964
965                 else {
966                         assert(u->meta.job->state == JOB_RUNNING);
967
968                         /* Let's check whether this state change
969                          * constitutes a finished job, or maybe
970                          * cotradicts a running job and hence needs to
971                          * invalidate jobs. */
972
973                         switch (u->meta.job->type) {
974
975                         case JOB_START:
976                         case JOB_VERIFY_ACTIVE:
977
978                                 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
979                                         job_finish_and_invalidate(u->meta.job, true);
980                                 else if (ns != UNIT_ACTIVATING) {
981                                         unexpected = true;
982                                         job_finish_and_invalidate(u->meta.job, false);
983                                 }
984
985                                 break;
986
987                         case JOB_RELOAD:
988                         case JOB_RELOAD_OR_START:
989
990                                 if (ns == UNIT_ACTIVE)
991                                         job_finish_and_invalidate(u->meta.job, true);
992                                 else if (ns != UNIT_ACTIVATING && ns != UNIT_ACTIVE_RELOADING) {
993                                         unexpected = true;
994                                         job_finish_and_invalidate(u->meta.job, false);
995                                 }
996
997                                 break;
998
999                         case JOB_STOP:
1000                         case JOB_RESTART:
1001                         case JOB_TRY_RESTART:
1002
1003                                 if (ns == UNIT_INACTIVE)
1004                                         job_finish_and_invalidate(u->meta.job, true);
1005                                 else if (ns != UNIT_DEACTIVATING) {
1006                                         unexpected = true;
1007                                         job_finish_and_invalidate(u->meta.job, false);
1008                                 }
1009
1010                                 break;
1011
1012                         default:
1013                                 assert_not_reached("Job type unknown");
1014                         }
1015                 }
1016         }
1017
1018         /* If this state change happened without being requested by a
1019          * job, then let's retroactively start or stop dependencies */
1020
1021         if (unexpected) {
1022                 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1023                         retroactively_start_dependencies(u);
1024                 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1025                         retroactively_stop_dependencies(u);
1026         }
1027
1028         /* Some names are special */
1029         if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1030                 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1031                         /* The bus just might have become available,
1032                          * hence try to connect to it, if we aren't
1033                          * yet connected. */
1034                         bus_init_system(u->meta.manager);
1035                         bus_init_api(u->meta.manager);
1036                 }
1037
1038                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1039                         /* The syslog daemon just might have become
1040                          * available, hence try to connect to it, if
1041                          * we aren't yet connected. */
1042                         log_open();
1043
1044                 if (u->meta.type == UNIT_MOUNT)
1045                         /* Another directory became available, let's
1046                          * check if that is enough to write our utmp
1047                          * entry. */
1048                         manager_write_utmp_reboot(u->meta.manager);
1049
1050                 if (u->meta.type == UNIT_TARGET)
1051                         /* A target got activated, maybe this is a runlevel? */
1052                         manager_write_utmp_runlevel(u->meta.manager, u);
1053
1054         } else if (!UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1055
1056                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1057                         /* The syslog daemon might just have
1058                          * terminated, hence try to disconnect from
1059                          * it. */
1060                         log_close_syslog();
1061
1062                 /* We don't care about D-Bus here, since we'll get an
1063                  * asynchronous notification for it anyway. */
1064         }
1065
1066         /* Maybe we finished startup and are now ready for being
1067          * stopped because unneeded? */
1068         unit_check_uneeded(u);
1069
1070         unit_add_to_dbus_queue(u);
1071         unit_add_to_gc_queue(u);
1072 }
1073
1074 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1075         struct epoll_event ev;
1076
1077         assert(u);
1078         assert(fd >= 0);
1079         assert(w);
1080         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1081
1082         zero(ev);
1083         ev.data.ptr = w;
1084         ev.events = events;
1085
1086         if (epoll_ctl(u->meta.manager->epoll_fd,
1087                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1088                       fd,
1089                       &ev) < 0)
1090                 return -errno;
1091
1092         w->fd = fd;
1093         w->type = WATCH_FD;
1094         w->data.unit = u;
1095
1096         return 0;
1097 }
1098
1099 void unit_unwatch_fd(Unit *u, Watch *w) {
1100         assert(u);
1101         assert(w);
1102
1103         if (w->type == WATCH_INVALID)
1104                 return;
1105
1106         assert(w->type == WATCH_FD);
1107         assert(w->data.unit == u);
1108         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1109
1110         w->fd = -1;
1111         w->type = WATCH_INVALID;
1112         w->data.unit = NULL;
1113 }
1114
1115 int unit_watch_pid(Unit *u, pid_t pid) {
1116         assert(u);
1117         assert(pid >= 1);
1118
1119         /* Watch a specific PID. We only support one unit watching
1120          * each PID for now. */
1121
1122         return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
1123 }
1124
1125 void unit_unwatch_pid(Unit *u, pid_t pid) {
1126         assert(u);
1127         assert(pid >= 1);
1128
1129         hashmap_remove_value(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
1130 }
1131
1132 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1133         struct itimerspec its;
1134         int flags, fd;
1135         bool ours;
1136
1137         assert(u);
1138         assert(w);
1139         assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->data.unit == u));
1140
1141         /* This will try to reuse the old timer if there is one */
1142
1143         if (w->type == WATCH_TIMER) {
1144                 ours = false;
1145                 fd = w->fd;
1146         } else {
1147                 ours = true;
1148                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1149                         return -errno;
1150         }
1151
1152         zero(its);
1153
1154         if (delay <= 0) {
1155                 /* Set absolute time in the past, but not 0, since we
1156                  * don't want to disarm the timer */
1157                 its.it_value.tv_sec = 0;
1158                 its.it_value.tv_nsec = 1;
1159
1160                 flags = TFD_TIMER_ABSTIME;
1161         } else {
1162                 timespec_store(&its.it_value, delay);
1163                 flags = 0;
1164         }
1165
1166         /* This will also flush the elapse counter */
1167         if (timerfd_settime(fd, flags, &its, NULL) < 0)
1168                 goto fail;
1169
1170         if (w->type == WATCH_INVALID) {
1171                 struct epoll_event ev;
1172
1173                 zero(ev);
1174                 ev.data.ptr = w;
1175                 ev.events = EPOLLIN;
1176
1177                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1178                         goto fail;
1179         }
1180
1181         w->fd = fd;
1182         w->type = WATCH_TIMER;
1183         w->data.unit = u;
1184
1185         return 0;
1186
1187 fail:
1188         if (ours)
1189                 close_nointr_nofail(fd);
1190
1191         return -errno;
1192 }
1193
1194 void unit_unwatch_timer(Unit *u, Watch *w) {
1195         assert(u);
1196         assert(w);
1197
1198         if (w->type == WATCH_INVALID)
1199                 return;
1200
1201         assert(w->type == WATCH_TIMER && w->data.unit == u);
1202
1203         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1204         close_nointr_nofail(w->fd);
1205
1206         w->fd = -1;
1207         w->type = WATCH_INVALID;
1208         w->data.unit = NULL;
1209 }
1210
1211 bool unit_job_is_applicable(Unit *u, JobType j) {
1212         assert(u);
1213         assert(j >= 0 && j < _JOB_TYPE_MAX);
1214
1215         switch (j) {
1216
1217         case JOB_VERIFY_ACTIVE:
1218         case JOB_START:
1219                 return true;
1220
1221         case JOB_STOP:
1222         case JOB_RESTART:
1223         case JOB_TRY_RESTART:
1224                 return unit_can_start(u);
1225
1226         case JOB_RELOAD:
1227                 return unit_can_reload(u);
1228
1229         case JOB_RELOAD_OR_START:
1230                 return unit_can_reload(u) && unit_can_start(u);
1231
1232         default:
1233                 assert_not_reached("Invalid job type");
1234         }
1235 }
1236
1237 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1238
1239         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1240                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1241                 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1242                 [UNIT_WANTS] = UNIT_WANTED_BY,
1243                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1244                 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1245                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1246                 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1247                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1248                 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
1249                 [UNIT_BEFORE] = UNIT_AFTER,
1250                 [UNIT_AFTER] = UNIT_BEFORE,
1251                 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1252                 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1253         };
1254         int r, q = 0, v = 0, w = 0;
1255
1256         assert(u);
1257         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1258         assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
1259         assert(other);
1260
1261         /* We won't allow dependencies on ourselves. We will not
1262          * consider them an error however. */
1263         if (u == other)
1264                 return 0;
1265
1266         if (UNIT_VTABLE(u)->no_requires &&
1267             (d == UNIT_REQUIRES ||
1268              d == UNIT_REQUIRES_OVERRIDABLE ||
1269              d == UNIT_REQUISITE ||
1270              d == UNIT_REQUISITE_OVERRIDABLE)) {
1271                     return -EINVAL;
1272         }
1273
1274         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0 ||
1275             (r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1276                 return r;
1277
1278         if (add_reference)
1279                 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1280                     (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1281                         return r;
1282
1283         if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1284                 return q;
1285
1286         if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1287                 r = v;
1288                 goto fail;
1289         }
1290
1291         if (add_reference) {
1292                 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1293                         r = w;
1294                         goto fail;
1295                 }
1296
1297                 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1298                         goto fail;
1299         }
1300
1301         unit_add_to_dbus_queue(u);
1302         return 0;
1303
1304 fail:
1305         if (q > 0)
1306                 set_remove(u->meta.dependencies[d], other);
1307
1308         if (v > 0)
1309                 set_remove(other->meta.dependencies[inverse_table[d]], u);
1310
1311         if (w > 0)
1312                 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1313
1314         return r;
1315 }
1316
1317 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1318         char *s;
1319
1320         assert(u);
1321         assert(name || path);
1322
1323         if (!name)
1324                 name = file_name_from_path(path);
1325
1326         if (!unit_name_is_template(name)) {
1327                 *p = NULL;
1328                 return name;
1329         }
1330
1331         if (u->meta.instance)
1332                 s = unit_name_replace_instance(name, u->meta.instance);
1333         else {
1334                 char *i;
1335
1336                 if (!(i = unit_name_to_prefix(u->meta.id)))
1337                         return NULL;
1338
1339                 s = unit_name_replace_instance(name, i);
1340                 free(i);
1341         }
1342
1343         if (!s)
1344                 return NULL;
1345
1346         *p = s;
1347         return s;
1348 }
1349
1350 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1351         Unit *other;
1352         int r;
1353         char *s;
1354
1355         assert(u);
1356         assert(name || path);
1357
1358         if (!(name = resolve_template(u, name, path, &s)))
1359                 return -ENOMEM;
1360
1361         if ((r = manager_load_unit(u->meta.manager, name, path, &other)) < 0)
1362                 goto finish;
1363
1364         r = unit_add_dependency(u, d, other, add_reference);
1365
1366 finish:
1367         free(s);
1368         return r;
1369 }
1370
1371 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1372         Unit *other;
1373         int r;
1374         char *s;
1375
1376         assert(u);
1377         assert(name || path);
1378
1379         if (!(name = resolve_template(u, name, path, &s)))
1380                 return -ENOMEM;
1381
1382         if ((r = manager_load_unit(u->meta.manager, name, path, &other)) < 0)
1383                 goto finish;
1384
1385         r = unit_add_dependency(other, d, u, add_reference);
1386
1387 finish:
1388         free(s);
1389         return r;
1390 }
1391
1392 int set_unit_path(const char *p) {
1393         char *cwd, *c;
1394         int r;
1395
1396         /* This is mostly for debug purposes */
1397
1398         if (path_is_absolute(p)) {
1399                 if (!(c = strdup(p)))
1400                         return -ENOMEM;
1401         } else {
1402                 if (!(cwd = get_current_dir_name()))
1403                         return -errno;
1404
1405                 r = asprintf(&c, "%s/%s", cwd, p);
1406                 free(cwd);
1407
1408                 if (r < 0)
1409                         return -ENOMEM;
1410         }
1411
1412         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1413                 r = -errno;
1414                 free(c);
1415                 return r;
1416         }
1417
1418         return 0;
1419 }
1420
1421 char *unit_dbus_path(Unit *u) {
1422         char *p, *e;
1423
1424         assert(u);
1425
1426         if (!(e = bus_path_escape(u->meta.id)))
1427                 return NULL;
1428
1429         if (asprintf(&p, "/org/freedesktop/systemd1/unit/%s", e) < 0) {
1430                 free(e);
1431                 return NULL;
1432         }
1433
1434         free(e);
1435         return p;
1436 }
1437
1438 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1439         CGroupBonding *l;
1440         int r;
1441
1442         assert(u);
1443         assert(b);
1444         assert(b->path);
1445
1446         /* Ensure this hasn't been added yet */
1447         assert(!b->unit);
1448
1449         l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1450         LIST_PREPEND(CGroupBonding, by_path, l, b);
1451
1452         if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1453                 LIST_REMOVE(CGroupBonding, by_path, l, b);
1454                 return r;
1455         }
1456
1457         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1458         b->unit = u;
1459
1460         return 0;
1461 }
1462
1463 static char *default_cgroup_path(Unit *u) {
1464         char *p;
1465         int r;
1466
1467         assert(u);
1468
1469         if (u->meta.instance) {
1470                 char *t;
1471
1472                 if (!(t = unit_name_template(u->meta.id)))
1473                         return NULL;
1474
1475                 r = asprintf(&p, "%s/%s/%s", u->meta.manager->cgroup_hierarchy, t, u->meta.instance);
1476                 free(t);
1477         } else
1478                 r = asprintf(&p, "%s/%s", u->meta.manager->cgroup_hierarchy, u->meta.id);
1479
1480         return r < 0 ? NULL : p;
1481 }
1482
1483 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1484         size_t n;
1485         char *controller = NULL, *path = NULL;
1486         CGroupBonding *b = NULL;
1487         int r;
1488
1489         assert(u);
1490         assert(name);
1491
1492         /* Detect controller name */
1493         n = strcspn(name, ":");
1494
1495         if (name[n] == 0 ||
1496             (name[n] == ':' && name[n+1] == 0)) {
1497
1498                 /* Only controller name, no path? */
1499
1500                 if (!(path = default_cgroup_path(u)))
1501                         return -ENOMEM;
1502
1503         } else {
1504                 const char *p;
1505
1506                 /* Controller name, and path. */
1507                 p = name+n+1;
1508
1509                 if (!path_is_absolute(p))
1510                         return -EINVAL;
1511
1512                 if (!(path = strdup(p)))
1513                         return -ENOMEM;
1514         }
1515
1516         if (n > 0)
1517                 controller = strndup(name, n);
1518         else
1519                 controller = strdup(u->meta.manager->cgroup_controller);
1520
1521         if (!controller) {
1522                 r = -ENOMEM;
1523                 goto fail;
1524         }
1525
1526         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1527                 r = -EEXIST;
1528                 goto fail;
1529         }
1530
1531         if (!(b = new0(CGroupBonding, 1))) {
1532                 r = -ENOMEM;
1533                 goto fail;
1534         }
1535
1536         b->controller = controller;
1537         b->path = path;
1538         b->only_us = false;
1539         b->clean_up = false;
1540
1541         if ((r = unit_add_cgroup(u, b)) < 0)
1542                 goto fail;
1543
1544         return 0;
1545
1546 fail:
1547         free(path);
1548         free(controller);
1549         free(b);
1550
1551         return r;
1552 }
1553
1554 int unit_add_default_cgroup(Unit *u) {
1555         CGroupBonding *b;
1556         int r = -ENOMEM;
1557
1558         assert(u);
1559
1560         /* Adds in the default cgroup data, if it wasn't specified yet */
1561
1562         if (unit_get_default_cgroup(u))
1563                 return 0;
1564
1565         if (!(b = new0(CGroupBonding, 1)))
1566                 return -ENOMEM;
1567
1568         if (!(b->controller = strdup(u->meta.manager->cgroup_controller)))
1569                 goto fail;
1570
1571         if (!(b->path = default_cgroup_path(u)))
1572                 goto fail;
1573
1574         b->clean_up = true;
1575         b->only_us = true;
1576
1577         if ((r = unit_add_cgroup(u, b)) < 0)
1578                 goto fail;
1579
1580         return 0;
1581
1582 fail:
1583         free(b->path);
1584         free(b->controller);
1585         free(b);
1586
1587         return r;
1588 }
1589
1590 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1591         assert(u);
1592
1593         return cgroup_bonding_find_list(u->meta.cgroup_bondings, u->meta.manager->cgroup_controller);
1594 }
1595
1596 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
1597         char *t;
1598         int r;
1599
1600         assert(u);
1601         assert(type);
1602         assert(_found);
1603
1604         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1605                 return -ENOMEM;
1606
1607         assert(!unit_has_name(u, t));
1608
1609         r = manager_load_unit(u->meta.manager, t, NULL, _found);
1610         free(t);
1611
1612         assert(r < 0 || *_found != u);
1613
1614         return r;
1615 }
1616
1617 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
1618         Unit *found;
1619         char *t;
1620
1621         assert(u);
1622         assert(type);
1623         assert(_found);
1624
1625         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1626                 return -ENOMEM;
1627
1628         assert(!unit_has_name(u, t));
1629
1630         found = manager_get_unit(u->meta.manager, t);
1631         free(t);
1632
1633         if (!found)
1634                 return -ENOENT;
1635
1636         *_found = found;
1637         return 0;
1638 }
1639
1640 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
1641         Unit *u = userdata;
1642         assert(u);
1643
1644         return unit_name_to_prefix_and_instance(u->meta.id);
1645 }
1646
1647 static char *specifier_prefix(char specifier, void *data, void *userdata) {
1648         Unit *u = userdata;
1649         assert(u);
1650
1651         return unit_name_to_prefix(u->meta.id);
1652 }
1653
1654 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
1655         Unit *u = userdata;
1656         char *p, *r;
1657
1658         assert(u);
1659
1660         if (!(p = unit_name_to_prefix(u->meta.id)))
1661                 return NULL;
1662
1663         r = unit_name_unescape(p);
1664         free(p);
1665
1666         return r;
1667 }
1668
1669 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
1670         Unit *u = userdata;
1671         assert(u);
1672
1673         if (u->meta.instance)
1674                 return unit_name_unescape(u->meta.instance);
1675
1676         return strdup("");
1677 }
1678
1679 char *unit_name_printf(Unit *u, const char* format) {
1680
1681         /*
1682          * This will use the passed string as format string and
1683          * replace the following specifiers:
1684          *
1685          * %n: the full id of the unit                 (foo@bar.waldo)
1686          * %N: the id of the unit without the suffix   (foo@bar)
1687          * %p: the prefix                              (foo)
1688          * %i: the instance                            (bar)
1689          */
1690
1691         const Specifier table[] = {
1692                 { 'n', specifier_string,              u->meta.id },
1693                 { 'N', specifier_prefix_and_instance, NULL },
1694                 { 'p', specifier_prefix,              NULL },
1695                 { 'i', specifier_string,              u->meta.instance },
1696                 { 0, NULL, NULL }
1697         };
1698
1699         assert(u);
1700         assert(format);
1701
1702         return specifier_printf(format, table, u);
1703 }
1704
1705 char *unit_full_printf(Unit *u, const char *format) {
1706
1707         /* This is similar to unit_name_printf() but also supports
1708          * unescaping */
1709
1710         const Specifier table[] = {
1711                 { 'n', specifier_string,              u->meta.id },
1712                 { 'N', specifier_prefix_and_instance, NULL },
1713                 { 'p', specifier_prefix,              NULL },
1714                 { 'P', specifier_prefix_unescaped,    NULL },
1715                 { 'i', specifier_string,              u->meta.instance },
1716                 { 'I', specifier_instance_unescaped,  NULL },
1717                 { 0, NULL, NULL }
1718         };
1719
1720         assert(u);
1721         assert(format);
1722
1723         return specifier_printf(format, table, u);
1724 }
1725
1726 char **unit_full_printf_strv(Unit *u, char **l) {
1727         size_t n;
1728         char **r, **i, **j;
1729
1730         /* Applies unit_full_printf to every entry in l */
1731
1732         assert(u);
1733
1734         n = strv_length(l);
1735         if (!(r = new(char*, n+1)))
1736                 return NULL;
1737
1738         for (i = l, j = r; *i; i++, j++)
1739                 if (!(*j = unit_full_printf(u, *i)))
1740                         goto fail;
1741
1742         *j = NULL;
1743         return r;
1744
1745 fail:
1746         j--;
1747         while (j >= r)
1748                 free(*j);
1749
1750         free(r);
1751
1752         return NULL;
1753 }
1754
1755 int unit_watch_bus_name(Unit *u, const char *name) {
1756         assert(u);
1757         assert(name);
1758
1759         /* Watch a specific name on the bus. We only support one unit
1760          * watching each name for now. */
1761
1762         return hashmap_put(u->meta.manager->watch_bus, name, u);
1763 }
1764
1765 void unit_unwatch_bus_name(Unit *u, const char *name) {
1766         assert(u);
1767         assert(name);
1768
1769         hashmap_remove_value(u->meta.manager->watch_bus, name, u);
1770 }
1771
1772 bool unit_can_serialize(Unit *u) {
1773         assert(u);
1774
1775         return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
1776 }
1777
1778 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
1779         int r;
1780
1781         assert(u);
1782         assert(f);
1783         assert(fds);
1784
1785         if (!unit_can_serialize(u))
1786                 return 0;
1787
1788         if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
1789                 return r;
1790
1791         /* End marker */
1792         fputc('\n', f);
1793         return 0;
1794 }
1795
1796 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
1797         va_list ap;
1798
1799         assert(u);
1800         assert(f);
1801         assert(key);
1802         assert(format);
1803
1804         fputs(key, f);
1805         fputc('=', f);
1806
1807         va_start(ap, format);
1808         vfprintf(f, format, ap);
1809         va_end(ap);
1810
1811         fputc('\n', f);
1812 }
1813
1814 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
1815         assert(u);
1816         assert(f);
1817         assert(key);
1818         assert(value);
1819
1820         fprintf(f, "%s=%s\n", key, value);
1821 }
1822
1823 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
1824         int r;
1825
1826         assert(u);
1827         assert(f);
1828         assert(fds);
1829
1830         if (!unit_can_serialize(u))
1831                 return 0;
1832
1833         for (;;) {
1834                 char line[1024], *l, *v;
1835                 size_t k;
1836
1837                 if (!fgets(line, sizeof(line), f)) {
1838                         if (feof(f))
1839                                 return 0;
1840                         return -errno;
1841                 }
1842
1843                 l = strstrip(line);
1844
1845                 /* End marker */
1846                 if (l[0] == 0)
1847                         return 0;
1848
1849                 k = strcspn(l, "=");
1850
1851                 if (l[k] == '=') {
1852                         l[k] = 0;
1853                         v = l+k+1;
1854                 } else
1855                         v = l+k;
1856
1857                 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
1858                         return r;
1859         }
1860 }
1861
1862 int unit_add_node_link(Unit *u, const char *what, bool wants) {
1863         Unit *device;
1864         char *e;
1865         int r;
1866
1867         assert(u);
1868
1869         if (!what)
1870                 return 0;
1871
1872         /* Adds in links to the device node that this unit is based on */
1873
1874         if (!is_device_path(what))
1875                 return 0;
1876
1877         if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
1878                 return -ENOMEM;
1879
1880         r = manager_load_unit(u->meta.manager, e, NULL, &device);
1881         free(e);
1882
1883         if (r < 0)
1884                 return r;
1885
1886         if ((r = unit_add_dependency(u, UNIT_AFTER, device, true)) < 0)
1887                 return r;
1888
1889         if ((r = unit_add_dependency(u, UNIT_REQUIRES, device, true)) < 0)
1890                 return r;
1891
1892         if (wants)
1893                 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
1894                         return r;
1895
1896         return 0;
1897 }
1898
1899 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
1900         [UNIT_SERVICE] = "service",
1901         [UNIT_TIMER] = "timer",
1902         [UNIT_SOCKET] = "socket",
1903         [UNIT_TARGET] = "target",
1904         [UNIT_DEVICE] = "device",
1905         [UNIT_MOUNT] = "mount",
1906         [UNIT_AUTOMOUNT] = "automount",
1907         [UNIT_SNAPSHOT] = "snapshot",
1908         [UNIT_SWAP] = "swap"
1909 };
1910
1911 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
1912
1913 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
1914         [UNIT_STUB] = "stub",
1915         [UNIT_LOADED] = "loaded",
1916         [UNIT_FAILED] = "failed",
1917         [UNIT_MERGED] = "merged"
1918 };
1919
1920 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
1921
1922 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
1923         [UNIT_ACTIVE] = "active",
1924         [UNIT_INACTIVE] = "inactive",
1925         [UNIT_ACTIVATING] = "activating",
1926         [UNIT_DEACTIVATING] = "deactivating"
1927 };
1928
1929 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
1930
1931 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
1932         [UNIT_REQUIRES] = "Requires",
1933         [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
1934         [UNIT_WANTS] = "Wants",
1935         [UNIT_REQUISITE] = "Requisite",
1936         [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
1937         [UNIT_REQUIRED_BY] = "RequiredBy",
1938         [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
1939         [UNIT_WANTED_BY] = "WantedBy",
1940         [UNIT_CONFLICTS] = "Conflicts",
1941         [UNIT_BEFORE] = "Before",
1942         [UNIT_AFTER] = "After",
1943         [UNIT_REFERENCES] = "References",
1944         [UNIT_REFERENCED_BY] = "ReferencedBy"
1945 };
1946
1947 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);
1948
1949 static const char* const kill_mode_table[_KILL_MODE_MAX] = {
1950         [KILL_CONTROL_GROUP] = "control-group",
1951         [KILL_PROCESS_GROUP] = "process-group",
1952         [KILL_PROCESS] = "process",
1953         [KILL_NONE] = "none"
1954 };
1955
1956 DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);