chiark / gitweb /
add first_word() call
[elogind.git] / unit.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 #include <assert.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <sys/epoll.h>
7 #include <sys/timerfd.h>
8 #include <sys/poll.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11
12 #include "set.h"
13 #include "unit.h"
14 #include "macro.h"
15 #include "strv.h"
16 #include "load-fragment.h"
17 #include "load-dropin.h"
18 #include "log.h"
19
20 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
21         [UNIT_SERVICE] = &service_vtable,
22         [UNIT_TIMER] = &timer_vtable,
23         [UNIT_SOCKET] = &socket_vtable,
24         [UNIT_TARGET] = &target_vtable,
25         [UNIT_DEVICE] = &device_vtable,
26         [UNIT_MOUNT] = &mount_vtable,
27         [UNIT_AUTOMOUNT] = &automount_vtable,
28         [UNIT_SNAPSHOT] = &snapshot_vtable
29 };
30
31 UnitType unit_name_to_type(const char *n) {
32         UnitType t;
33
34         assert(n);
35
36         for (t = 0; t < _UNIT_TYPE_MAX; t++)
37                 if (endswith(n, unit_vtable[t]->suffix))
38                         return t;
39
40         return _UNIT_TYPE_INVALID;
41 }
42
43 #define VALID_CHARS                             \
44         "0123456789"                            \
45         "abcdefghijklmnopqrstuvwxyz"            \
46         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"            \
47         "-_.\\"
48
49 bool unit_name_is_valid(const char *n) {
50         UnitType t;
51         const char *e, *i;
52
53         assert(n);
54
55         if (strlen(n) >= UNIT_NAME_MAX)
56                 return false;
57
58         t = unit_name_to_type(n);
59         if (t < 0 || t >= _UNIT_TYPE_MAX)
60                 return false;
61
62         if (!(e = strrchr(n, '.')))
63                 return false;
64
65         if (e == n)
66                 return false;
67
68         for (i = n; i < e; i++)
69                 if (!strchr(VALID_CHARS, *i))
70                         return false;
71
72         return true;
73 }
74
75 char *unit_name_change_suffix(const char *n, const char *suffix) {
76         char *e, *r;
77         size_t a, b;
78
79         assert(n);
80         assert(unit_name_is_valid(n));
81         assert(suffix);
82
83         assert_se(e = strrchr(n, '.'));
84         a = e - n;
85         b = strlen(suffix);
86
87         if (!(r = new(char, a + b + 1)))
88                 return NULL;
89
90         memcpy(r, n, a);
91         memcpy(r+a, suffix, b+1);
92
93         return r;
94 }
95
96 Unit *unit_new(Manager *m) {
97         Unit *u;
98
99         assert(m);
100
101         if (!(u = new0(Unit, 1)))
102                 return NULL;
103
104         if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
105                 free(u);
106                 return NULL;
107         }
108
109         u->meta.manager = m;
110         u->meta.type = _UNIT_TYPE_INVALID;
111
112         return u;
113 }
114
115 int unit_add_name(Unit *u, const char *text) {
116         UnitType t;
117         char *s;
118         int r;
119
120         assert(u);
121         assert(text);
122
123         if (!unit_name_is_valid(text))
124                 return -EINVAL;
125
126         if ((t = unit_name_to_type(text)) == _UNIT_TYPE_INVALID)
127                 return -EINVAL;
128
129         if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type)
130                 return -EINVAL;
131
132         if (!(s = strdup(text)))
133                 return -ENOMEM;
134
135         if ((r = set_put(u->meta.names, s)) < 0) {
136                 free(s);
137
138                 if (r == -EEXIST)
139                         return 0;
140
141                 return r;
142         }
143
144         if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
145                 set_remove(u->meta.names, s);
146                 free(s);
147                 return r;
148         }
149
150         if (u->meta.type == _UNIT_TYPE_INVALID)
151                 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
152
153         u->meta.type = t;
154
155         if (!u->meta.id)
156                 u->meta.id = s;
157
158         return 0;
159 }
160
161 int unit_choose_id(Unit *u, const char *name) {
162         char *s;
163
164         assert(u);
165         assert(name);
166
167         /* Selects one of the names of this unit as the id */
168
169         if (!(s = set_get(u->meta.names, (char*) name)))
170                 return -ENOENT;
171
172         u->meta.id = s;
173         return 0;
174 }
175
176 int unit_set_description(Unit *u, const char *description) {
177         char *s;
178
179         assert(u);
180
181         if (!(s = strdup(description)))
182                 return -ENOMEM;
183
184         free(u->meta.description);
185         u->meta.description = s;
186         return 0;
187 }
188
189 void unit_add_to_load_queue(Unit *u) {
190         assert(u);
191
192         if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
193                 return;
194
195         LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
196         u->meta.in_load_queue = true;
197 }
198
199 static void bidi_set_free(Unit *u, Set *s) {
200         Iterator i;
201         Unit *other;
202
203         assert(u);
204
205         /* Frees the set and makes sure we are dropped from the
206          * inverse pointers */
207
208         SET_FOREACH(other, s, i) {
209                 UnitDependency d;
210
211                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
212                         set_remove(other->meta.dependencies[d], u);
213         }
214
215         set_free(s);
216 }
217
218 void unit_free(Unit *u) {
219         UnitDependency d;
220         Iterator i;
221         char *t;
222
223         assert(u);
224
225         /* Detach from next 'bigger' objects */
226
227         SET_FOREACH(t, u->meta.names, i)
228                 hashmap_remove_value(u->meta.manager->units, t, u);
229
230         if (u->meta.type != _UNIT_TYPE_INVALID)
231                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
232
233         if (u->meta.in_load_queue)
234                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
235
236         if (u->meta.load_state == UNIT_LOADED)
237                 if (UNIT_VTABLE(u)->done)
238                         UNIT_VTABLE(u)->done(u);
239
240         /* Free data and next 'smaller' objects */
241         if (u->meta.job)
242                 job_free(u->meta.job);
243
244         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
245                 bidi_set_free(u, u->meta.dependencies[d]);
246
247         free(u->meta.description);
248         free(u->meta.load_path);
249
250         while ((t = set_steal_first(u->meta.names)))
251                 free(t);
252         set_free(u->meta.names);
253
254         free(u);
255 }
256
257 UnitActiveState unit_active_state(Unit *u) {
258         assert(u);
259
260         if (u->meta.load_state != UNIT_LOADED)
261                 return UNIT_INACTIVE;
262
263         return UNIT_VTABLE(u)->active_state(u);
264 }
265
266 static int ensure_merge(Set **s, Set *other) {
267
268         if (!other)
269                 return 0;
270
271         if (*s)
272                 return set_merge(*s, other);
273
274         if (!(*s = set_copy(other)))
275                 return -ENOMEM;
276
277         return 0;
278 }
279
280 /* FIXME: Does not rollback on failure! Needs to fix special unit
281  * pointers. Needs to merge names and dependencies properly.*/
282 int unit_merge(Unit *u, Unit *other) {
283         int r;
284         UnitDependency d;
285
286         assert(u);
287         assert(other);
288         assert(u->meta.manager == other->meta.manager);
289
290         /* This merges 'other' into 'unit'. FIXME: This does not
291          * rollback on failure. */
292
293         if (u->meta.type != u->meta.type)
294                 return -EINVAL;
295
296         if (u->meta.load_state != UNIT_STUB)
297                 return -EINVAL;
298
299         /* Merge names */
300         if ((r = ensure_merge(&u->meta.names, other->meta.names)) < 0)
301                 return r;
302
303         /* Merge dependencies */
304         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
305                 /* fixme, the inverse mapping is missing */
306                 if ((r = ensure_merge(&u->meta.dependencies[d], other->meta.dependencies[d])) < 0)
307                         return r;
308
309         return 0;
310 }
311
312 const char* unit_id(Unit *u) {
313         assert(u);
314
315         if (u->meta.id)
316                 return u->meta.id;
317
318         return set_first(u->meta.names);
319 }
320
321 const char *unit_description(Unit *u) {
322         assert(u);
323
324         if (u->meta.description)
325                 return u->meta.description;
326
327         return unit_id(u);
328 }
329
330 void unit_dump(Unit *u, FILE *f, const char *prefix) {
331
332         static const char* const load_state_table[_UNIT_LOAD_STATE_MAX] = {
333                 [UNIT_STUB] = "stub",
334                 [UNIT_LOADED] = "loaded",
335                 [UNIT_FAILED] = "failed"
336         };
337
338         static const char* const active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
339                 [UNIT_ACTIVE] = "active",
340                 [UNIT_INACTIVE] = "inactive",
341                 [UNIT_ACTIVATING] = "activating",
342                 [UNIT_DEACTIVATING] = "deactivating"
343         };
344
345         static const char* const dependency_table[_UNIT_DEPENDENCY_MAX] = {
346                 [UNIT_REQUIRES] = "Requires",
347                 [UNIT_SOFT_REQUIRES] = "SoftRequires",
348                 [UNIT_WANTS] = "Wants",
349                 [UNIT_REQUISITE] = "Requisite",
350                 [UNIT_SOFT_REQUISITE] = "SoftRequisite",
351                 [UNIT_REQUIRED_BY] = "RequiredBy",
352                 [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
353                 [UNIT_WANTED_BY] = "WantedBy",
354                 [UNIT_CONFLICTS] = "Conflicts",
355                 [UNIT_BEFORE] = "Before",
356                 [UNIT_AFTER] = "After",
357         };
358
359         char *t;
360         UnitDependency d;
361         Iterator i;
362         char *prefix2;
363
364         assert(u);
365
366         if (!prefix)
367                 prefix = "";
368         prefix2 = strappend(prefix, "\t");
369         if (!prefix2)
370                 prefix2 = "";
371
372         fprintf(f,
373                 "%s→ Unit %s:\n"
374                 "%s\tDescription: %s\n"
375                 "%s\tUnit Load State: %s\n"
376                 "%s\tUnit Active State: %s\n"
377                 "%s\tRecursive Deactivate: %s\n"
378                 "%s\tStop When Unneeded: %s\n",
379                 prefix, unit_id(u),
380                 prefix, unit_description(u),
381                 prefix, load_state_table[u->meta.load_state],
382                 prefix, active_state_table[unit_active_state(u)],
383                 prefix, yes_no(u->meta.recursive_stop),
384                 prefix, yes_no(u->meta.stop_when_unneeded));
385
386         if (u->meta.load_path)
387                 fprintf(f, "%s\tLoad Path: %s\n", prefix, u->meta.load_path);
388
389         SET_FOREACH(t, u->meta.names, i)
390                 fprintf(f, "%s\tName: %s\n", prefix, t);
391
392         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
393                 Unit *other;
394
395                 if (set_isempty(u->meta.dependencies[d]))
396                         continue;
397
398                 SET_FOREACH(other, u->meta.dependencies[d], i)
399                         fprintf(f, "%s\t%s: %s\n", prefix, dependency_table[d], unit_id(other));
400         }
401
402         if (UNIT_VTABLE(u)->dump)
403                 UNIT_VTABLE(u)->dump(u, f, prefix2);
404
405         if (u->meta.job)
406                 job_dump(u->meta.job, f, prefix2);
407
408         free(prefix2);
409 }
410
411 /* Common implementation for multiple backends */
412 int unit_load_fragment_and_dropin(Unit *u) {
413         int r, ret;
414
415         assert(u);
416
417         /* Load a .socket file */
418         if ((r = unit_load_fragment(u)) < 0)
419                 return r;
420
421         ret = r > 0;
422
423         /* Load drop-in directory data */
424         if ((r = unit_load_dropin(u)) < 0)
425                 return r;
426
427         return ret;
428 }
429
430 int unit_load(Unit *u) {
431         int r;
432
433         assert(u);
434
435         if (u->meta.in_load_queue) {
436                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
437                 u->meta.in_load_queue = false;
438         }
439
440         if (u->meta.load_state != UNIT_STUB)
441                 return 0;
442
443         if (UNIT_VTABLE(u)->init)
444                 if ((r = UNIT_VTABLE(u)->init(u)) < 0)
445                         goto fail;
446
447         u->meta.load_state = UNIT_LOADED;
448         return 0;
449
450 fail:
451         u->meta.load_state = UNIT_FAILED;
452         return r;
453 }
454
455 /* Errors:
456  *         -EBADR:    This unit type does not support starting.
457  *         -EALREADY: Unit is already started.
458  *         -EAGAIN:   An operation is already in progress. Retry later.
459  */
460 int unit_start(Unit *u) {
461         UnitActiveState state;
462
463         assert(u);
464
465         if (!UNIT_VTABLE(u)->start)
466                 return -EBADR;
467
468         state = unit_active_state(u);
469         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
470                 return -EALREADY;
471
472         /* We don't suppress calls to ->start() here when we are
473          * already starting, to allow this request to be used as a
474          * "hurry up" call, for example when the unit is in some "auto
475          * restart" state where it waits for a holdoff timer to elapse
476          * before it will start again. */
477
478         return UNIT_VTABLE(u)->start(u);
479 }
480
481 bool unit_can_start(Unit *u) {
482         assert(u);
483
484         return !!UNIT_VTABLE(u)->start;
485 }
486
487 /* Errors:
488  *         -EBADR:    This unit type does not support stopping.
489  *         -EALREADY: Unit is already stopped.
490  *         -EAGAIN:   An operation is already in progress. Retry later.
491  */
492 int unit_stop(Unit *u) {
493         UnitActiveState state;
494
495         assert(u);
496
497         if (!UNIT_VTABLE(u)->stop)
498                 return -EBADR;
499
500         state = unit_active_state(u);
501         if (state == UNIT_INACTIVE)
502                 return -EALREADY;
503
504         if (state == UNIT_DEACTIVATING)
505                 return 0;
506
507         return UNIT_VTABLE(u)->stop(u);
508 }
509
510 /* Errors:
511  *         -EBADR:    This unit type does not support reloading.
512  *         -ENOEXEC:  Unit is not started.
513  *         -EAGAIN:   An operation is already in progress. Retry later.
514  */
515 int unit_reload(Unit *u) {
516         UnitActiveState state;
517
518         assert(u);
519
520         if (!unit_can_reload(u))
521                 return -EBADR;
522
523         state = unit_active_state(u);
524         if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
525                 return -EALREADY;
526
527         if (unit_active_state(u) != UNIT_ACTIVE)
528                 return -ENOEXEC;
529
530         return UNIT_VTABLE(u)->reload(u);
531 }
532
533 bool unit_can_reload(Unit *u) {
534         assert(u);
535
536         if (!UNIT_VTABLE(u)->reload)
537                 return false;
538
539         if (!UNIT_VTABLE(u)->can_reload)
540                 return true;
541
542         return UNIT_VTABLE(u)->can_reload(u);
543 }
544
545 static void unit_check_uneeded(Unit *u) {
546         Iterator i;
547         Unit *other;
548
549         assert(u);
550
551         /* If this service shall be shut down when unneeded then do
552          * so. */
553
554         if (!u->meta.stop_when_unneeded)
555                 return;
556
557         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
558                 return;
559
560         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
561                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
562                         return;
563
564         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRED_BY], i)
565                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
566                         return;
567
568         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
569                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
570                         return;
571
572         log_debug("Service %s is not needed anymore. Stopping.", unit_id(u));
573
574         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
575         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL);
576 }
577
578 static void retroactively_start_dependencies(Unit *u) {
579         Iterator i;
580         Unit *other;
581
582         assert(u);
583         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
584
585         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
586                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
587                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
588
589         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
590                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
591                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
592
593         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
594                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
595                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
596
597         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
598                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
599                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
600
601         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
602                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
603                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
604 }
605
606 static void retroactively_stop_dependencies(Unit *u) {
607         Iterator i;
608         Unit *other;
609
610         assert(u);
611         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
612
613         if (u->meta.recursive_stop) {
614                 /* Pull down units need us recursively if enabled */
615                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
616                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
617                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
618         }
619
620         /* Garbage collect services that might not be needed anymore, if enabled */
621         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
622                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
623                         unit_check_uneeded(other);
624         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
625                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
626                         unit_check_uneeded(other);
627         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
628                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
629                         unit_check_uneeded(other);
630         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
631                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
632                         unit_check_uneeded(other);
633         SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUISITE], i)
634                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
635                         unit_check_uneeded(other);
636 }
637
638 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
639         assert(u);
640         assert(os < _UNIT_ACTIVE_STATE_MAX);
641         assert(ns < _UNIT_ACTIVE_STATE_MAX);
642         assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
643         assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
644
645         if (os == ns)
646                 return;
647
648         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
649                 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
650         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
651                 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
652
653         if (u->meta.job) {
654
655                 if (u->meta.job->state == JOB_WAITING)
656
657                         /* So we reached a different state for this
658                          * job. Let's see if we can run it now if it
659                          * failed previously due to EAGAIN. */
660                         job_schedule_run(u->meta.job);
661
662                 else {
663                         assert(u->meta.job->state == JOB_RUNNING);
664
665                         /* Let's check whether this state change
666                          * constitutes a finished job, or maybe
667                          * cotradicts a running job and hence needs to
668                          * invalidate jobs. */
669
670                         switch (u->meta.job->type) {
671
672                         case JOB_START:
673                         case JOB_VERIFY_ACTIVE:
674
675                                 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
676                                         job_finish_and_invalidate(u->meta.job, true);
677                                         return;
678                                 } else if (ns == UNIT_ACTIVATING)
679                                         return;
680                                 else
681                                         job_finish_and_invalidate(u->meta.job, false);
682
683                                 break;
684
685                         case JOB_RELOAD:
686                         case JOB_RELOAD_OR_START:
687
688                                 if (ns == UNIT_ACTIVE) {
689                                         job_finish_and_invalidate(u->meta.job, true);
690                                         return;
691                                 } else if (ns == UNIT_ACTIVATING || ns == UNIT_ACTIVE_RELOADING)
692                                         return;
693                                 else
694                                         job_finish_and_invalidate(u->meta.job, false);
695
696                                 break;
697
698                         case JOB_STOP:
699                         case JOB_RESTART:
700                         case JOB_TRY_RESTART:
701
702                                 if (ns == UNIT_INACTIVE) {
703                                         job_finish_and_invalidate(u->meta.job, true);
704                                         return;
705                                 } else if (ns == UNIT_DEACTIVATING)
706                                         return;
707                                 else
708                                         job_finish_and_invalidate(u->meta.job, false);
709
710                                 break;
711
712                         default:
713                                 assert_not_reached("Job type unknown");
714                         }
715                 }
716         }
717
718         /* If this state change happened without being requested by a
719          * job, then let's retroactively start or stop dependencies */
720
721         if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
722                 retroactively_start_dependencies(u);
723         else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
724                 retroactively_stop_dependencies(u);
725
726         /* Maybe we finished startup and are now ready for being
727          * stopped because unneeded? */
728         unit_check_uneeded(u);
729 }
730
731 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
732         struct epoll_event ev;
733
734         assert(u);
735         assert(fd >= 0);
736         assert(w);
737         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->unit == u));
738
739         zero(ev);
740         ev.data.ptr = w;
741         ev.events = events;
742
743         if (epoll_ctl(u->meta.manager->epoll_fd,
744                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
745                       fd,
746                       &ev) < 0)
747                 return -errno;
748
749         w->fd = fd;
750         w->type = WATCH_FD;
751         w->unit = u;
752
753         return 0;
754 }
755
756 void unit_unwatch_fd(Unit *u, Watch *w) {
757         assert(u);
758         assert(w);
759
760         if (w->type == WATCH_INVALID)
761                 return;
762
763         assert(w->type == WATCH_FD && w->unit == u);
764         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
765
766         w->fd = -1;
767         w->type = WATCH_INVALID;
768         w->unit = NULL;
769 }
770
771 int unit_watch_pid(Unit *u, pid_t pid) {
772         assert(u);
773         assert(pid >= 1);
774
775         return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
776 }
777
778 void unit_unwatch_pid(Unit *u, pid_t pid) {
779         assert(u);
780         assert(pid >= 1);
781
782         hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
783 }
784
785 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
786         struct itimerspec its;
787         int flags, fd;
788         bool ours;
789
790         assert(u);
791         assert(w);
792         assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->unit == u));
793
794         /* This will try to reuse the old timer if there is one */
795
796         if (w->type == WATCH_TIMER) {
797                 ours = false;
798                 fd = w->fd;
799         } else {
800                 ours = true;
801                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
802                         return -errno;
803         }
804
805         zero(its);
806
807         if (delay <= 0) {
808                 /* Set absolute time in the past, but not 0, since we
809                  * don't want to disarm the timer */
810                 its.it_value.tv_sec = 0;
811                 its.it_value.tv_nsec = 1;
812
813                 flags = TFD_TIMER_ABSTIME;
814         } else {
815                 timespec_store(&its.it_value, delay);
816                 flags = 0;
817         }
818
819         /* This will also flush the elapse counter */
820         if (timerfd_settime(fd, flags, &its, NULL) < 0)
821                 goto fail;
822
823         if (w->type == WATCH_INVALID) {
824                 struct epoll_event ev;
825
826                 zero(ev);
827                 ev.data.ptr = w;
828                 ev.events = EPOLLIN;
829
830                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
831                         goto fail;
832         }
833
834         w->fd = fd;
835         w->type = WATCH_TIMER;
836         w->unit = u;
837
838         return 0;
839
840 fail:
841         if (ours)
842                 assert_se(close_nointr(fd) == 0);
843
844         return -errno;
845 }
846
847 void unit_unwatch_timer(Unit *u, Watch *w) {
848         assert(u);
849         assert(w);
850
851         if (w->type == WATCH_INVALID)
852                 return;
853
854         assert(w->type == WATCH_TIMER && w->unit == u);
855
856         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
857         assert_se(close_nointr(w->fd) == 0);
858
859         w->fd = -1;
860         w->type = WATCH_INVALID;
861         w->unit = NULL;
862 }
863
864 bool unit_job_is_applicable(Unit *u, JobType j) {
865         assert(u);
866         assert(j >= 0 && j < _JOB_TYPE_MAX);
867
868         switch (j) {
869
870         case JOB_VERIFY_ACTIVE:
871         case JOB_START:
872                 return true;
873
874         case JOB_STOP:
875         case JOB_RESTART:
876         case JOB_TRY_RESTART:
877                 return unit_can_start(u);
878
879         case JOB_RELOAD:
880                 return unit_can_reload(u);
881
882         case JOB_RELOAD_OR_START:
883                 return unit_can_reload(u) && unit_can_start(u);
884
885         default:
886                 assert_not_reached("Invalid job type");
887         }
888 }
889
890 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
891
892         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
893                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
894                 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
895                 [UNIT_WANTS] = UNIT_WANTED_BY,
896                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
897                 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
898                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
899                 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
900                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
901                 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
902                 [UNIT_BEFORE] = UNIT_AFTER,
903                 [UNIT_AFTER] = UNIT_BEFORE
904         };
905         int r;
906
907         assert(u);
908         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
909         assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
910         assert(other);
911
912         /* We won't allow dependencies on ourselves. We will not
913          * consider them an error however. */
914         if (u == other)
915                 return 0;
916
917         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
918                 return r;
919
920         if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
921                 return r;
922
923         if ((r = set_put(u->meta.dependencies[d], other)) < 0)
924                 return r;
925
926         if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
927                 set_remove(u->meta.dependencies[d], other);
928                 return r;
929         }
930
931         return 0;
932 }
933
934 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
935         Unit *other;
936         int r;
937
938         if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
939                 return r;
940
941         if ((r = unit_add_dependency(u, d, other)) < 0)
942                 return r;
943
944         return 0;
945 }
946
947 const char *unit_path(void) {
948         char *e;
949
950         if ((e = getenv("UNIT_PATH")))
951                 if (path_is_absolute(e))
952                     return e;
953
954         return UNIT_PATH;
955 }
956
957 int set_unit_path(const char *p) {
958         char *cwd, *c;
959         int r;
960
961         /* This is mostly for debug purposes */
962
963         if (path_is_absolute(p)) {
964                 if (!(c = strdup(p)))
965                         return -ENOMEM;
966         } else {
967                 if (!(cwd = get_current_dir_name()))
968                         return -errno;
969
970                 r = asprintf(&c, "%s/%s", cwd, p);
971                 free(cwd);
972
973                 if (r < 0)
974                         return -ENOMEM;
975         }
976
977         if (setenv("UNIT_PATH", c, 0) < 0) {
978                 r = -errno;
979                 free(c);
980                 return r;
981         }
982
983         return 0;
984 }
985
986 char *unit_name_escape_path(const char *prefix, const char *path, const char *suffix) {
987         char *r, *t;
988         const char *f;
989         size_t a, b, c;
990
991         assert(path);
992
993         /* Takes a path and a suffix and prefix and makes a nice
994          * string suitable as unit name of it, escaping all weird
995          * chars on the way.
996          *
997          * / becomes ., and all chars not alloweed in a unit name get
998          * escaped as \xFF, including \ and ., of course. This
999          * escaping is hence reversible.
1000          */
1001
1002         if (!prefix)
1003                 prefix = "";
1004
1005         if (!suffix)
1006                 suffix = "";
1007
1008         a = strlen(prefix);
1009         b = strlen(path);
1010         c = strlen(suffix);
1011
1012         if (!(r = new(char, a+b*4+c+1)))
1013                 return NULL;
1014
1015         memcpy(r, prefix, a);
1016
1017         for (f = path, t = r+a; *f; f++) {
1018                 if (*f == '/')
1019                         *(t++) = '.';
1020                 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
1021                         *(t++) = '\\';
1022                         *(t++) = 'x';
1023                         *(t++) = hexchar(*f > 4);
1024                         *(t++) = hexchar(*f);
1025                 } else
1026                         *(t++) = *f;
1027         }
1028
1029         memcpy(t, suffix, c+1);
1030
1031         return r;
1032 }