chiark / gitweb /
cgroup: add cgroupsification
[elogind.git] / service.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 <errno.h>
23 #include <signal.h>
24 #include <dirent.h>
25 #include <unistd.h>
26
27 #include "unit.h"
28 #include "service.h"
29 #include "load-fragment.h"
30 #include "load-dropin.h"
31 #include "log.h"
32 #include "strv.h"
33
34 #define COMMENTS "#;\n"
35 #define NEWLINES "\n\r"
36 #define LINE_MAX 4096
37
38 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
39         [SERVICE_DEAD] = UNIT_INACTIVE,
40         [SERVICE_START_PRE] = UNIT_ACTIVATING,
41         [SERVICE_START] = UNIT_ACTIVATING,
42         [SERVICE_START_POST] = UNIT_ACTIVATING,
43         [SERVICE_RUNNING] = UNIT_ACTIVE,
44         [SERVICE_RELOAD] = UNIT_ACTIVE_RELOADING,
45         [SERVICE_STOP] = UNIT_DEACTIVATING,
46         [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
47         [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
48         [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
49         [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
50         [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
51         [SERVICE_MAINTAINANCE] = UNIT_INACTIVE,
52         [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
53 };
54
55 static void service_done(Unit *u) {
56         Service *s = SERVICE(u);
57
58         assert(s);
59
60         free(s->pid_file);
61         s->pid_file = NULL;
62
63         free(s->sysv_path);
64         s->sysv_path = NULL;
65
66         exec_context_done(&s->exec_context);
67         exec_command_free_array(s->exec_command, _SERVICE_EXEC_MAX);
68         s->control_command = NULL;
69
70         /* This will leak a process, but at least no memory or any of
71          * our resources */
72         if (s->main_pid > 0) {
73                 unit_unwatch_pid(u, s->main_pid);
74                 s->main_pid = 0;
75         }
76
77         if (s->control_pid > 0) {
78                 unit_unwatch_pid(u, s->control_pid);
79                 s->control_pid = 0;
80         }
81
82         unit_unwatch_timer(u, &s->timer_watch);
83 }
84
85 static int sysv_translate_name(const char *name, char **_r) {
86
87         static const char * const table[] = {
88                 "$local_fs",  SPECIAL_LOCAL_FS_TARGET,
89                 "$network",   SPECIAL_NETWORK_TARGET,
90                 "$named",     SPECIAL_NSS_LOOKUP_TARGET,
91                 "$portmap",   SPECIAL_RPCBIND_TARGET,
92                 "$remote_fs", SPECIAL_REMOTE_FS_TARGET,
93                 "$syslog",    SPECIAL_SYSLOG_TARGET,
94                 "$time",      SPECIAL_RTC_SET_TARGET
95         };
96
97         unsigned i;
98         char *r;
99
100         for (i = 0; i < ELEMENTSOF(table); i += 2)
101                 if (streq(table[i], name)) {
102                         if (!(r = strdup(table[i+1])))
103                                 return -ENOMEM;
104
105                         goto finish;
106                 }
107
108         if (*name == '$')
109                 return 0;
110
111         if (asprintf(&r, "%s.service", name) < 0)
112                 return -ENOMEM;
113
114 finish:
115
116         if (_r)
117                 *_r = r;
118
119         return 1;
120 }
121
122 static int sysv_chkconfig_order(Service *s) {
123         Meta *other;
124         int r;
125
126         assert(s);
127
128         if (s->sysv_start_priority < 0)
129                 return 0;
130
131         /* If no LSB header is found we try to order init scripts via
132          * the start priority of the chkconfig header. */
133
134         LIST_FOREACH(units_per_type, other, UNIT(s)->meta.manager->units_per_type[UNIT_SERVICE]) {
135                 Service *t;
136                 UnitDependency d;
137
138                 t = (Service*) other;
139
140                 if (s == t)
141                         continue;
142
143                 if (t->sysv_start_priority < 0)
144                         continue;
145
146                 if (t->sysv_start_priority < s->sysv_start_priority)
147                         d = UNIT_AFTER;
148                 else if (t->sysv_start_priority > s->sysv_start_priority)
149                         d = UNIT_BEFORE;
150                 else
151                         continue;
152
153                 /* FIXME: Maybe we should compare the name here lexicographically? */
154
155                 if (!(r = unit_add_dependency(UNIT(s), d, UNIT(t))) < 0)
156                         return r;
157         }
158
159         return 0;
160 }
161
162 static ExecCommand *exec_command_new(const char *path, const char *arg1) {
163         ExecCommand *c;
164
165         if (!(c = new0(ExecCommand, 1)))
166                 return NULL;
167
168         if (!(c->path = strdup(path))) {
169                 free(c);
170                 return NULL;
171         }
172
173         if (!(c->argv = strv_new(path, arg1, NULL))) {
174                 free(c->path);
175                 free(c);
176                 return NULL;
177         }
178
179         return c;
180 }
181
182 static int sysv_exec_commands(Service *s) {
183         ExecCommand *c;
184
185         assert(s);
186         assert(s->sysv_path);
187
188         if (!(c = exec_command_new(s->sysv_path, "start")))
189                 return -ENOMEM;
190         exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
191
192         if (!(c = exec_command_new(s->sysv_path, "stop")))
193                 return -ENOMEM;
194         exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
195
196         if (!(c = exec_command_new(s->sysv_path, "reload")))
197                 return -ENOMEM;
198         exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
199
200         return 0;
201 }
202
203 static int service_load_sysv_path(Service *s, const char *path) {
204         FILE *f;
205         Unit *u;
206         unsigned line = 0;
207         int r;
208         enum {
209                 NORMAL,
210                 DESCRIPTION,
211                 LSB,
212                 LSB_DESCRIPTION
213         } state = NORMAL;
214         bool has_lsb = false;
215
216         u = UNIT(s);
217
218         if (!(f = fopen(path, "re"))) {
219                 r = errno == ENOENT ? 0 : -errno;
220                 goto finish;
221         }
222
223         s->type = SERVICE_FORKING;
224         s->restart = SERVICE_ONCE;
225
226         free(s->sysv_path);
227         if (!(s->sysv_path = strdup(path))) {
228                 r = -ENOMEM;
229                 goto finish;
230         }
231
232         while (!feof(f)) {
233                 char l[LINE_MAX], *t;
234
235                 if (!fgets(l, sizeof(l), f)) {
236                         if (feof(f))
237                                 break;
238
239                         r = -errno;
240                         log_error("Failed to read configuration file '%s': %s", path, strerror(-r));
241                         goto finish;
242                 }
243
244                 line++;
245
246                 t = strstrip(l);
247                 if (*t != '#')
248                         continue;
249
250                 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
251                         state = LSB;
252                         has_lsb = true;
253                         continue;
254                 }
255
256                 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
257                         state = NORMAL;
258                         continue;
259                 }
260
261                 t++;
262                 t += strspn(t, WHITESPACE);
263
264                 if (state == NORMAL) {
265
266                         /* Try to parse Red Hat style chkconfig headers */
267
268                         if (startswith(t, "chkconfig:")) {
269                                 int start_priority;
270
271                                 state = NORMAL;
272
273                                 if (sscanf(t+10, "%*15s %i %*i",
274                                            &start_priority) != 1) {
275
276                                         log_warning("[%s:%u] Failed to parse chkconfig line. Ignoring.", path, line);
277                                         continue;
278                                 }
279
280                                 if (start_priority < 0 || start_priority > 99) {
281                                         log_warning("[%s:%u] Start priority out of range. Ignoring.", path, line);
282                                         continue;
283                                 }
284
285                                 s->sysv_start_priority = start_priority;
286
287                         } else if (startswith(t, "description:")) {
288
289                                 size_t k = strlen(t);
290                                 char *d;
291
292                                 if (t[k-1] == '\\') {
293                                         state = DESCRIPTION;
294                                         t[k-1] = 0;
295                                 }
296
297                                 if (!(d = strdup(strstrip(t+12)))) {
298                                         r = -ENOMEM;
299                                         goto finish;
300                                 }
301
302                                 free(u->meta.description);
303                                 u->meta.description = d;
304
305                         } else if (startswith(t, "pidfile:")) {
306
307                                 char *fn;
308
309                                 state = NORMAL;
310
311                                 fn = strstrip(t+8);
312                                 if (!path_is_absolute(fn)) {
313                                         log_warning("[%s:%u] PID file not absolute. Ignoring.", path, line);
314                                         continue;
315                                 }
316
317                                 if (!(fn = strdup(fn))) {
318                                         r = -ENOMEM;
319                                         goto finish;
320                                 }
321
322                                 free(s->pid_file);
323                                 s->pid_file = fn;
324                         }
325
326                 } else if (state == DESCRIPTION) {
327
328                         /* Try to parse Red Hat style description
329                          * continuation */
330
331                         size_t k = strlen(t);
332                         char *d;
333
334                         if (t[k-1] == '\\')
335                                 t[k-1] = 0;
336                         else
337                                 state = NORMAL;
338
339                         assert(u->meta.description);
340                         if (asprintf(&d, "%s %s", u->meta.description, strstrip(t)) < 0) {
341                                 r = -ENOMEM;
342                                 goto finish;
343                         }
344
345                         free(u->meta.description);
346                         u->meta.description = d;
347
348                 } else if (state == LSB || state == LSB_DESCRIPTION) {
349
350                         if (startswith(t, "Provides:")) {
351                                 char *i, *w;
352                                 size_t z;
353
354                                 state = LSB;
355
356                                 FOREACH_WORD(w, z, t+9, i) {
357                                         char *n, *m;
358
359                                         if (!(n = strndup(w, z))) {
360                                                 r = -ENOMEM;
361                                                 goto finish;
362                                         }
363
364                                         r = sysv_translate_name(n, &m);
365                                         free(n);
366
367                                         if (r < 0)
368                                                 goto finish;
369
370                                         if (r == 0)
371                                                 continue;
372
373                                         r = unit_add_name(u, m);
374                                         free(m);
375
376                                         if (r < 0)
377                                                 goto finish;
378                                 }
379
380                         } else if (startswith(t, "Required-Start:") ||
381                                    startswith(t, "Should-Start:")) {
382                                 char *i, *w;
383                                 size_t z;
384
385                                 state = LSB;
386
387                                 FOREACH_WORD(w, z, strchr(t, ':')+1, i) {
388                                         char *n, *m;
389
390                                         if (!(n = strndup(w, z))) {
391                                                 r = -ENOMEM;
392                                                 goto finish;
393                                         }
394
395                                         r = sysv_translate_name(n, &m);
396                                         free(n);
397
398                                         if (r < 0)
399                                                 goto finish;
400
401                                         if (r == 0)
402                                                 continue;
403
404                                         if (!(r = unit_add_dependency_by_name(u, UNIT_AFTER, m)) < 0) {
405                                                 free(m);
406                                                 goto finish;
407                                         }
408
409                                         r = unit_add_dependency_by_name(
410                                                         u,
411                                                         startswith(t, "Required-Start:") ? UNIT_REQUIRES : UNIT_WANTS,
412                                                         m);
413                                         free(m);
414
415                                         if (r < 0)
416                                                 goto finish;
417                                 }
418
419                         } else if (startswith(t, "Description:")) {
420                                 char *d;
421
422                                 state = LSB_DESCRIPTION;
423
424                                 if (!(d = strdup(strstrip(t+12)))) {
425                                         r = -ENOMEM;
426                                         goto finish;
427                                 }
428
429                                 free(u->meta.description);
430                                 u->meta.description = d;
431
432                         } else if (startswith(t, "Short-Description:") && !u->meta.description) {
433                                 char *d;
434
435                                 /* We use the short description only
436                                  * if no long description is set. */
437
438                                 state = LSB;
439
440                                 if (!(d = strdup(strstrip(t+18)))) {
441                                         r = -ENOMEM;
442                                         goto finish;
443                                 }
444
445                                 free(u->meta.description);
446                                 u->meta.description = d;
447
448                         } else if (state == LSB_DESCRIPTION) {
449
450                                 if (startswith(l, "#\t") || startswith(l, "#  ")) {
451                                         char *d;
452
453                                         assert(u->meta.description);
454                                         if (asprintf(&d, "%s %s", u->meta.description, t) < 0) {
455                                                 r = -ENOMEM;
456                                                 goto finish;
457                                         }
458
459                                         free(u->meta.description);
460                                         u->meta.description = d;
461                                 } else
462                                         state = LSB;
463                         }
464                 }
465         }
466
467         /* If the init script has no LSB header, then let's
468          * enforce the ordering via the chkconfig
469          * priorities */
470
471         if (!has_lsb)
472                 if ((r = sysv_chkconfig_order(s)) < 0)
473                         goto finish;
474
475         if ((r = sysv_exec_commands(s)) < 0)
476                 goto finish;
477
478         r = 1;
479
480 finish:
481
482         if (f)
483                 fclose(f);
484
485         return r;
486 }
487
488 static int service_load_sysv_name(Service *s, const char *name) {
489         char **p;
490
491         assert(s);
492         assert(name);
493
494         STRV_FOREACH(p, UNIT(s)->meta.manager->sysvinit_path) {
495                 char *path;
496                 int r;
497
498                 if (asprintf(&path, "%s/%s", *p, name) < 0)
499                         return -ENOMEM;
500
501                 assert(endswith(path, ".service"));
502                 path[strlen(path)-8] = 0;
503
504                 r = service_load_sysv_path(s, path);
505                 free(path);
506
507                 if (r >= 0)
508                         return r;
509         }
510
511         return 0;
512 }
513
514 static int service_load_sysv(Service *s) {
515         const char *t;
516         Iterator i;
517         int r;
518
519         assert(s);
520
521         /* Load service data from SysV init scripts, preferably with
522          * LSB headers ... */
523
524         if (strv_isempty(UNIT(s)->meta.manager->sysvinit_path))
525                 return 0;
526
527         if ((t = unit_id(UNIT(s))))
528                 if ((r = service_load_sysv_name(s, t)) != 0)
529                         return r;
530
531         SET_FOREACH(t, UNIT(s)->meta.names, i)
532                 if ((r == service_load_sysv_name(s, t)) != 0)
533                         return r;
534
535         return 0;
536 }
537
538 static int service_init(Unit *u) {
539         int r;
540         Service *s = SERVICE(u);
541
542         assert(s);
543
544         /* First, reset everything to the defaults, in case this is a
545          * reload */
546
547         s->type = 0;
548         s->restart = 0;
549
550         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
551         s->restart_usec = DEFAULT_RESTART_USEC;
552
553         exec_context_init(&s->exec_context);
554
555         s->timer_watch.type = WATCH_INVALID;
556
557         s->state = SERVICE_DEAD;
558
559         s->sysv_start_priority = -1;
560         s->permissions_start_only = false;
561         s->root_directory_start_only = false;
562
563         RATELIMIT_INIT(s->ratelimit, 10*USEC_PER_SEC, 5);
564
565         /* Load a .service file */
566         if ((r = unit_load_fragment(u)) < 0) {
567                 service_done(u);
568                 return r;
569         }
570
571         /* Load a classic init script as a fallback, if we couldn*t find anything */
572         if (r == 0)
573                 if ((r = service_load_sysv(s)) <= 0) {
574                         service_done(u);
575                         return r < 0 ? r : -ENOENT;
576                 }
577
578         /* Load dropin directory data */
579         if ((r = unit_load_dropin(u)) < 0) {
580                 service_done(u);
581                 return r;
582         }
583
584         /* Add default cgroup */
585         if ((r = unit_add_default_cgroup(u)) < 0) {
586                 service_done(u);
587                 return r;
588         }
589
590         return 0;
591 }
592
593 static void service_dump(Unit *u, FILE *f, const char *prefix) {
594
595         ServiceExecCommand c;
596         Service *s = SERVICE(u);
597         const char *prefix2;
598         char *p2;
599
600         assert(s);
601
602         p2 = strappend(prefix, "\t");
603         prefix2 = p2 ? p2 : prefix;
604
605         fprintf(f,
606                 "%sService State: %s\n"
607                 "%sPermissionsStartOnly: %s\n"
608                 "%sRootDirectoryStartOnly: %s\n"
609                 "%sValidNoProcess: %s\n",
610                 prefix, service_state_to_string(s->state),
611                 prefix, yes_no(s->permissions_start_only),
612                 prefix, yes_no(s->root_directory_start_only),
613                 prefix, yes_no(s->valid_no_process));
614
615         if (s->pid_file)
616                 fprintf(f,
617                         "%sPIDFile: %s\n",
618                         prefix, s->pid_file);
619
620
621         exec_context_dump(&s->exec_context, f, prefix);
622
623         for (c = 0; c < _SERVICE_EXEC_MAX; c++) {
624
625                 if (!s->exec_command[c])
626                         continue;
627
628                 fprintf(f, "%s→ %s:\n",
629                         prefix, service_exec_command_to_string(c));
630
631                 exec_command_dump_list(s->exec_command[c], f, prefix2);
632         }
633
634         if (s->sysv_path)
635                 fprintf(f,
636                         "%sSysV Init Script Path: %s\n",
637                         prefix, s->sysv_path);
638
639         if (s->sysv_start_priority >= 0)
640                 fprintf(f,
641                         "%sSysV Start Priority: %i\n",
642                         prefix, s->sysv_start_priority);
643
644         free(p2);
645 }
646
647 static int service_load_pid_file(Service *s) {
648         char *k;
649         unsigned long p;
650         int r;
651
652         assert(s);
653
654         if (s->main_pid_known)
655                 return 0;
656
657         if (!s->pid_file)
658                 return -ENOENT;
659
660         if ((r = read_one_line_file(s->pid_file, &k)) < 0)
661                 return r;
662
663         if ((r = safe_atolu(k, &p)) < 0) {
664                 free(k);
665                 return r;
666         }
667
668         if ((unsigned long) (pid_t) p != p)
669                 return -ERANGE;
670
671         s->main_pid = p;
672         s->main_pid_known = true;
673
674         return 0;
675 }
676
677 static int service_get_sockets(Service *s, Set **_set) {
678         Set *set;
679         Iterator i;
680         char *t;
681         int r;
682
683         assert(s);
684         assert(_set);
685
686         /* Collects all Socket objects that belong to this
687          * service. Note that a service might have multiple sockets
688          * via multiple names. */
689
690         if (!(set = set_new(NULL, NULL)))
691                 return -ENOMEM;
692
693         SET_FOREACH(t, UNIT(s)->meta.names, i) {
694                 char *k;
695                 Unit *p;
696
697                 /* Look for all socket objects that go by any of our
698                  * units and collect their fds */
699
700                 if (!(k = unit_name_change_suffix(t, ".socket"))) {
701                         r = -ENOMEM;
702                         goto fail;
703                 }
704
705                 p = manager_get_unit(UNIT(s)->meta.manager, k);
706                 free(k);
707
708                 if (!p) continue;
709
710                 if ((r = set_put(set, p)) < 0)
711                         goto fail;
712         }
713
714         *_set = set;
715         return 0;
716
717 fail:
718         set_free(set);
719         return r;
720 }
721
722
723 static int service_notify_sockets(Service *s) {
724         Iterator i;
725         Set *set;
726         Socket *sock;
727         int r;
728
729         assert(s);
730
731         /* Notifies all our sockets when we die */
732
733         if ((r = service_get_sockets(s, &set)) < 0)
734                 return r;
735
736         SET_FOREACH(sock, set, i)
737                 socket_notify_service_dead(sock);
738
739         set_free(set);
740
741         return 0;
742 }
743
744 static void service_set_state(Service *s, ServiceState state) {
745         ServiceState old_state;
746         assert(s);
747
748         old_state = s->state;
749         s->state = state;
750
751         if (state != SERVICE_START_PRE &&
752             state != SERVICE_START &&
753             state != SERVICE_START_POST &&
754             state != SERVICE_RELOAD &&
755             state != SERVICE_STOP &&
756             state != SERVICE_STOP_SIGTERM &&
757             state != SERVICE_STOP_SIGKILL &&
758             state != SERVICE_STOP_POST &&
759             state != SERVICE_FINAL_SIGTERM &&
760             state != SERVICE_FINAL_SIGKILL &&
761             state != SERVICE_AUTO_RESTART)
762                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
763
764         if (state != SERVICE_START &&
765             state != SERVICE_START_POST &&
766             state != SERVICE_RUNNING &&
767             state != SERVICE_RELOAD &&
768             state != SERVICE_STOP &&
769             state != SERVICE_STOP_SIGTERM &&
770             state != SERVICE_STOP_SIGKILL)
771                 if (s->main_pid > 0) {
772                         unit_unwatch_pid(UNIT(s), s->main_pid);
773                         s->main_pid = 0;
774                 }
775
776         if (state != SERVICE_START_PRE &&
777             state != SERVICE_START &&
778             state != SERVICE_START_POST &&
779             state != SERVICE_RELOAD &&
780             state != SERVICE_STOP &&
781             state != SERVICE_STOP_SIGTERM &&
782             state != SERVICE_STOP_SIGKILL &&
783             state != SERVICE_STOP_POST &&
784             state != SERVICE_FINAL_SIGTERM &&
785             state != SERVICE_FINAL_SIGKILL)
786                 if (s->control_pid > 0) {
787                         unit_unwatch_pid(UNIT(s), s->control_pid);
788                         s->control_pid = 0;
789                 }
790
791         if (state != SERVICE_START_PRE &&
792             state != SERVICE_START &&
793             state != SERVICE_START_POST &&
794             state != SERVICE_RELOAD &&
795             state != SERVICE_STOP &&
796             state != SERVICE_STOP_POST)
797                 s->control_command = NULL;
798
799         if (state == SERVICE_DEAD ||
800             state == SERVICE_STOP ||
801             state == SERVICE_STOP_SIGTERM ||
802             state == SERVICE_STOP_SIGKILL ||
803             state == SERVICE_STOP_POST ||
804             state == SERVICE_FINAL_SIGTERM ||
805             state == SERVICE_FINAL_SIGKILL ||
806             state == SERVICE_MAINTAINANCE ||
807             state == SERVICE_AUTO_RESTART)
808                 service_notify_sockets(s);
809
810         log_debug("%s changed %s â†’ %s", unit_id(UNIT(s)), service_state_to_string(old_state), service_state_to_string(state));
811
812         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
813 }
814
815 static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
816         Iterator i;
817         int r;
818         int *rfds = NULL;
819         unsigned rn_fds = 0;
820         Set *set;
821         Socket *sock;
822
823         assert(s);
824         assert(fds);
825         assert(n_fds);
826
827         if ((r = service_get_sockets(s, &set)) < 0)
828                 return r;
829
830         SET_FOREACH(sock, set, i) {
831                 int *cfds;
832                 unsigned cn_fds;
833
834                 if ((r = socket_collect_fds(sock, &cfds, &cn_fds)) < 0)
835                         goto fail;
836
837                 if (!cfds)
838                         continue;
839
840                 if (!rfds) {
841                         rfds = cfds;
842                         rn_fds = cn_fds;
843                 } else {
844                         int *t;
845
846                         if (!(t = new(int, rn_fds+cn_fds))) {
847                                 free(cfds);
848                                 r = -ENOMEM;
849                                 goto fail;
850                         }
851
852                         memcpy(t, rfds, rn_fds);
853                         memcpy(t+rn_fds, cfds, cn_fds);
854                         free(rfds);
855                         free(cfds);
856
857                         rfds = t;
858                         rn_fds = rn_fds+cn_fds;
859                 }
860         }
861
862         *fds = rfds;
863         *n_fds = rn_fds;
864
865         set_free(set);
866
867         return 0;
868
869 fail:
870         set_free(set);
871         free(rfds);
872
873         return r;
874 }
875
876 static int service_spawn(
877                 Service *s,
878                 ExecCommand *c,
879                 bool timeout,
880                 bool pass_fds,
881                 bool apply_permissions,
882                 bool apply_chroot,
883                 pid_t *_pid) {
884
885         pid_t pid;
886         int r;
887         int *fds = NULL;
888         unsigned n_fds = 0;
889
890         assert(s);
891         assert(c);
892         assert(_pid);
893
894         if (pass_fds)
895                 if ((r = service_collect_fds(s, &fds, &n_fds)) < 0)
896                         goto fail;
897
898         if (timeout) {
899                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
900                         goto fail;
901         } else
902                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
903
904         if ((r = exec_spawn(c,
905                             &s->exec_context,
906                             fds, n_fds,
907                             apply_permissions,
908                             apply_chroot,
909                             UNIT(s)->meta.cgroup_bondings,
910                             &pid)) < 0)
911                 goto fail;
912
913         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
914                 /* FIXME: we need to do something here */
915                 goto fail;
916
917         free(fds);
918         *_pid = pid;
919
920         return 0;
921
922 fail:
923         free(fds);
924
925         if (timeout)
926                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
927
928         return r;
929 }
930
931 static void service_enter_dead(Service *s, bool success, bool allow_restart) {
932         int r;
933         assert(s);
934
935         if (!success)
936                 s->failure = true;
937
938         if (allow_restart &&
939             (s->restart == SERVICE_RESTART_ALWAYS ||
940              (s->restart == SERVICE_RESTART_ON_SUCCESS && !s->failure))) {
941
942                 if ((r = unit_watch_timer(UNIT(s), s->restart_usec, &s->timer_watch)) < 0)
943                         goto fail;
944
945                 service_set_state(s, SERVICE_AUTO_RESTART);
946         } else
947                 service_set_state(s, s->failure ? SERVICE_MAINTAINANCE : SERVICE_DEAD);
948
949         return;
950
951 fail:
952         log_warning("%s failed to run install restart timer: %s", unit_id(UNIT(s)), strerror(-r));
953         service_enter_dead(s, false, false);
954 }
955
956 static void service_enter_signal(Service *s, ServiceState state, bool success);
957
958 static void service_enter_stop_post(Service *s, bool success) {
959         int r;
960         assert(s);
961
962         if (!success)
963                 s->failure = true;
964
965         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST]))
966                 if ((r = service_spawn(s,
967                                        s->control_command,
968                                        true,
969                                        false,
970                                        !s->permissions_start_only,
971                                        !s->root_directory_start_only,
972                                        &s->control_pid)) < 0)
973                         goto fail;
974
975
976         service_set_state(s, SERVICE_STOP_POST);
977
978         if (!s->control_command)
979                 service_enter_dead(s, true, true);
980
981         return;
982
983 fail:
984         log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
985         service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
986 }
987
988 static void service_enter_signal(Service *s, ServiceState state, bool success) {
989         int r;
990         bool sent = false;
991
992         assert(s);
993
994         if (!success)
995                 s->failure = true;
996
997         if (s->main_pid > 0 || s->control_pid > 0) {
998                 int sig;
999
1000                 sig = (state == SERVICE_STOP_SIGTERM || state == SERVICE_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
1001
1002                 r = 0;
1003                 if (s->main_pid > 0) {
1004                         if (kill(s->main_pid, sig) < 0 && errno != ESRCH)
1005                                 r = -errno;
1006                         else
1007                                 sent = true;
1008                 }
1009
1010                 if (s->control_pid > 0) {
1011                         if (kill(s->control_pid, sig) < 0 && errno != ESRCH)
1012                                 r = -errno;
1013                         else
1014                                 sent = true;
1015                 }
1016
1017                 if (r < 0)
1018                         goto fail;
1019         }
1020
1021         service_set_state(s, state);
1022
1023         if (s->main_pid <= 0 && s->control_pid <= 0)
1024                 service_enter_dead(s, true, true);
1025
1026         return;
1027
1028 fail:
1029         log_warning("%s failed to kill processes: %s", unit_id(UNIT(s)), strerror(-r));
1030
1031         if (sent)  {
1032                 s->failure = true;
1033                 service_set_state(s, state);
1034         } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
1035                 service_enter_stop_post(s, false);
1036         else
1037                 service_enter_dead(s, false, true);
1038 }
1039
1040 static void service_enter_stop(Service *s, bool success) {
1041         int r;
1042         assert(s);
1043
1044         if (!success)
1045                 s->failure = true;
1046
1047         if ((s->control_command = s->exec_command[SERVICE_EXEC_STOP]))
1048                 if ((r = service_spawn(s,
1049                                        s->control_command,
1050                                        true,
1051                                        false,
1052                                        !s->permissions_start_only,
1053                                        !s->root_directory_start_only,
1054                                        &s->control_pid)) < 0)
1055                         goto fail;
1056
1057         service_set_state(s, SERVICE_STOP);
1058
1059         if (!s->control_command)
1060                 service_enter_signal(s, SERVICE_STOP_SIGTERM, true);
1061
1062         return;
1063
1064 fail:
1065         log_warning("%s failed to run stop executable: %s", unit_id(UNIT(s)), strerror(-r));
1066         service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1067 }
1068
1069 static void service_enter_start_post(Service *s) {
1070         int r;
1071         assert(s);
1072
1073         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_POST]))
1074                 if ((r = service_spawn(s,
1075                                        s->control_command,
1076                                        true,
1077                                        false,
1078                                        !s->permissions_start_only,
1079                                        !s->root_directory_start_only,
1080                                        &s->control_pid)) < 0)
1081                         goto fail;
1082
1083
1084         service_set_state(s, SERVICE_START_POST);
1085
1086         if (!s->control_command)
1087                 service_set_state(s, SERVICE_RUNNING);
1088
1089         return;
1090
1091 fail:
1092         log_warning("%s failed to run start-post executable: %s", unit_id(UNIT(s)), strerror(-r));
1093         service_enter_stop(s, false);
1094 }
1095
1096 static void service_enter_start(Service *s) {
1097         pid_t pid;
1098         int r;
1099
1100         assert(s);
1101
1102         assert(s->exec_command[SERVICE_EXEC_START]);
1103         assert(!s->exec_command[SERVICE_EXEC_START]->command_next);
1104
1105         if ((r = service_spawn(s,
1106                                s->exec_command[SERVICE_EXEC_START],
1107                                s->type == SERVICE_FORKING,
1108                                true,
1109                                true,
1110                                true,
1111                                &pid)) < 0)
1112                 goto fail;
1113
1114         service_set_state(s, SERVICE_START);
1115
1116         if (s->type == SERVICE_SIMPLE) {
1117                 /* For simple services we immediately start
1118                  * the START_POST binaries. */
1119
1120                 s->main_pid = pid;
1121                 s->main_pid_known = true;
1122                 service_enter_start_post(s);
1123
1124         } else  if (s->type == SERVICE_FORKING) {
1125
1126                 /* For forking services we wait until the start
1127                  * process exited. */
1128
1129                 s->control_pid = pid;
1130                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1131         } else if (s->type == SERVICE_FINISH) {
1132
1133                 /* For finishing services we wait until the start
1134                  * process exited, too, but it is our main process. */
1135
1136                 s->main_pid = pid;
1137                 s->control_command = s->exec_command[SERVICE_EXEC_START];
1138         } else
1139                 assert_not_reached("Unknown service type");
1140
1141         return;
1142
1143 fail:
1144         log_warning("%s failed to run start exectuable: %s", unit_id(UNIT(s)), strerror(-r));
1145         service_enter_stop(s, false);
1146 }
1147
1148 static void service_enter_start_pre(Service *s) {
1149         int r;
1150
1151         assert(s);
1152
1153         if ((s->control_command = s->exec_command[SERVICE_EXEC_START_PRE]))
1154                 if ((r = service_spawn(s,
1155                                        s->control_command,
1156                                        true,
1157                                        false,
1158                                        !s->permissions_start_only,
1159                                        !s->root_directory_start_only,
1160                                        &s->control_pid)) < 0)
1161                         goto fail;
1162
1163         service_set_state(s, SERVICE_START_PRE);
1164
1165         if (!s->control_command)
1166                 service_enter_start(s);
1167
1168         return;
1169
1170 fail:
1171         log_warning("%s failed to run start-pre executable: %s", unit_id(UNIT(s)), strerror(-r));
1172         service_enter_dead(s, false, true);
1173 }
1174
1175 static void service_enter_restart(Service *s) {
1176         int r;
1177         assert(s);
1178
1179         if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s), JOB_FAIL, false, NULL)) < 0)
1180                 goto fail;
1181
1182         log_debug("%s scheduled restart job.", unit_id(UNIT(s)));
1183         service_enter_dead(s, true, false);
1184         return;
1185
1186 fail:
1187
1188         log_warning("%s failed to schedule restart job: %s", unit_id(UNIT(s)), strerror(-r));
1189         service_enter_dead(s, false, false);
1190 }
1191
1192 static void service_enter_reload(Service *s) {
1193         int r;
1194
1195         assert(s);
1196
1197         if ((s->control_command = s->exec_command[SERVICE_EXEC_RELOAD]))
1198                 if ((r = service_spawn(s,
1199                                        s->control_command,
1200                                        true,
1201                                        false,
1202                                        !s->permissions_start_only,
1203                                        !s->root_directory_start_only,
1204                                        &s->control_pid)) < 0)
1205                         goto fail;
1206
1207         service_set_state(s, SERVICE_RELOAD);
1208
1209         if (!s->control_command)
1210                 service_set_state(s, SERVICE_RUNNING);
1211
1212         return;
1213
1214 fail:
1215         log_warning("%s failed to run reload executable: %s", unit_id(UNIT(s)), strerror(-r));
1216         service_enter_stop(s, false);
1217 }
1218
1219 static void service_run_next(Service *s, bool success) {
1220         int r;
1221
1222         assert(s);
1223         assert(s->control_command);
1224         assert(s->control_command->command_next);
1225
1226         if (!success)
1227                 s->failure = true;
1228
1229         s->control_command = s->control_command->command_next;
1230
1231         if ((r = service_spawn(s,
1232                                s->control_command,
1233                                true,
1234                                false,
1235                                !s->permissions_start_only,
1236                                !s->root_directory_start_only,
1237                                &s->control_pid)) < 0)
1238                 goto fail;
1239
1240         return;
1241
1242 fail:
1243         log_warning("%s failed to run spawn next executable: %s", unit_id(UNIT(s)), strerror(-r));
1244
1245         if (s->state == SERVICE_STOP)
1246                 service_enter_stop_post(s, false);
1247         else if (s->state == SERVICE_STOP_POST)
1248                 service_enter_dead(s, false, true);
1249         else
1250                 service_enter_stop(s, false);
1251 }
1252
1253 static int service_start(Unit *u) {
1254         Service *s = SERVICE(u);
1255
1256         assert(s);
1257
1258         /* We cannot fulfill this request right now, try again later
1259          * please! */
1260         if (s->state == SERVICE_STOP ||
1261             s->state == SERVICE_STOP_SIGTERM ||
1262             s->state == SERVICE_STOP_SIGKILL ||
1263             s->state == SERVICE_STOP_POST ||
1264             s->state == SERVICE_FINAL_SIGTERM ||
1265             s->state == SERVICE_FINAL_SIGKILL)
1266                 return -EAGAIN;
1267
1268         /* Already on it! */
1269         if (s->state == SERVICE_START_PRE ||
1270             s->state == SERVICE_START ||
1271             s->state == SERVICE_START_POST)
1272                 return 0;
1273
1274         assert(s->state == SERVICE_DEAD || s->state == SERVICE_MAINTAINANCE || s->state == SERVICE_AUTO_RESTART);
1275
1276         /* Make sure we don't enter a busy loop of some kind. */
1277         if (!ratelimit_test(&s->ratelimit)) {
1278                 log_warning("%s start request repeated too quickly, refusing to start.", unit_id(u));
1279                 return -EAGAIN;
1280         }
1281
1282         s->failure = false;
1283         s->main_pid_known = false;
1284
1285         service_enter_start_pre(s);
1286         return 0;
1287 }
1288
1289 static int service_stop(Unit *u) {
1290         Service *s = SERVICE(u);
1291
1292         assert(s);
1293
1294         if (s->state == SERVICE_START_PRE ||
1295             s->state == SERVICE_START ||
1296             s->state == SERVICE_START_POST ||
1297             s->state == SERVICE_RELOAD)
1298                 return -EAGAIN;
1299
1300         if (s->state == SERVICE_AUTO_RESTART) {
1301                 service_set_state(s, SERVICE_DEAD);
1302                 return 0;
1303         }
1304
1305         assert(s->state == SERVICE_RUNNING);
1306
1307         service_enter_stop(s, true);
1308         return 0;
1309 }
1310
1311 static int service_reload(Unit *u) {
1312         Service *s = SERVICE(u);
1313
1314         assert(s);
1315
1316         assert(s->state == SERVICE_RUNNING);
1317
1318         service_enter_reload(s);
1319         return 0;
1320 }
1321
1322 static bool service_can_reload(Unit *u) {
1323         Service *s = SERVICE(u);
1324
1325         assert(s);
1326
1327         return !!s->exec_command[SERVICE_EXEC_RELOAD];
1328 }
1329
1330 static UnitActiveState service_active_state(Unit *u) {
1331         assert(u);
1332
1333         return state_translation_table[SERVICE(u)->state];
1334 }
1335
1336 static int main_pid_good(Service *s) {
1337         assert(s);
1338
1339         /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1340          * don't know */
1341
1342         /* If we know the pid file, then lets just check if it is
1343          * still valid */
1344         if (s->main_pid_known)
1345                 return s->main_pid > 0;
1346
1347         /* We don't know the pid */
1348         return -EAGAIN;
1349 }
1350
1351 static bool control_pid_good(Service *s) {
1352         assert(s);
1353
1354         return s->control_pid > 0;
1355 }
1356
1357 static int cgroup_good(Service *s) {
1358         assert(s);
1359
1360         if (s->valid_no_process)
1361                 return -EAGAIN;
1362
1363         return cgroup_bonding_is_empty_list(UNIT(s)->meta.cgroup_bondings);
1364 }
1365
1366 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1367         Service *s = SERVICE(u);
1368         bool success;
1369
1370         assert(s);
1371         assert(pid >= 0);
1372
1373         success = code == CLD_EXITED && status == 0;
1374         s->failure = s->failure || !success;
1375
1376         if (s->main_pid == pid) {
1377
1378                 exec_status_fill(&s->main_exec_status, pid, code, status);
1379                 s->main_pid = 0;
1380
1381                 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_FINISH) {
1382                         assert(s->exec_command[SERVICE_EXEC_START]);
1383                         s->exec_command[SERVICE_EXEC_START]->exec_status = s->main_exec_status;
1384                 }
1385
1386                 log_debug("%s: main process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1387
1388                 /* The service exited, so the service is officially
1389                  * gone. */
1390
1391                 switch (s->state) {
1392
1393                 case SERVICE_START_POST:
1394                 case SERVICE_RELOAD:
1395                 case SERVICE_STOP:
1396                         /* Need to wait until the operation is
1397                          * done */
1398                         break;
1399
1400                 case SERVICE_START:
1401                         assert(s->type == SERVICE_FINISH);
1402
1403                         /* This was our main goal, so let's go on */
1404                         if (success)
1405                                 service_enter_start_post(s);
1406                         else
1407                                 service_enter_stop(s, false);
1408                         break;
1409
1410                 case SERVICE_RUNNING:
1411                         service_enter_stop(s, success);
1412                         break;
1413
1414                 case SERVICE_STOP_SIGTERM:
1415                 case SERVICE_STOP_SIGKILL:
1416
1417                         if (!control_pid_good(s))
1418                                 service_enter_stop_post(s, success);
1419
1420                         /* If there is still a control process, wait for that first */
1421                         break;
1422
1423                 default:
1424                         assert_not_reached("Uh, main process died at wrong time.");
1425                 }
1426
1427         } else if (s->control_pid == pid) {
1428                 assert(s->control_command);
1429
1430                 exec_status_fill(&s->control_command->exec_status, pid, code, status);
1431                 s->control_pid = 0;
1432
1433                 log_debug("%s: control process exited, code=%s status=%i", unit_id(u), sigchld_code_to_string(code), status);
1434
1435                 /* If we are shutting things down anyway we
1436                  * don't care about failing commands. */
1437
1438                 if (s->control_command->command_next &&
1439                     (success || (s->state == SERVICE_EXEC_STOP || s->state == SERVICE_EXEC_STOP_POST)))
1440
1441                         /* There is another command to *
1442                          * execute, so let's do that. */
1443
1444                         service_run_next(s, success);
1445
1446                 else {
1447                         /* No further commands for this step, so let's
1448                          * figure out what to do next */
1449
1450                         log_debug("%s got final SIGCHLD for state %s", unit_id(u), service_state_to_string(s->state));
1451
1452                         switch (s->state) {
1453
1454                         case SERVICE_START_PRE:
1455                                 if (success)
1456                                         service_enter_start(s);
1457                                 else
1458                                         service_enter_stop(s, false);
1459                                 break;
1460
1461                         case SERVICE_START:
1462                                 assert(s->type == SERVICE_FORKING);
1463
1464                                 /* Let's try to load the pid
1465                                  * file here if we can. We
1466                                  * ignore the return value,
1467                                  * since the PID file might
1468                                  * actually be created by a
1469                                  * START_POST script */
1470
1471                                 if (success) {
1472                                         if (s->pid_file)
1473                                                 service_load_pid_file(s);
1474
1475                                         service_enter_start_post(s);
1476                                 } else
1477                                         service_enter_stop(s, false);
1478
1479                                 break;
1480
1481                         case SERVICE_START_POST:
1482                                 if (success && s->pid_file && !s->main_pid_known) {
1483                                         int r;
1484
1485                                         /* Hmm, let's see if we can
1486                                          * load the pid now after the
1487                                          * start-post scripts got
1488                                          * executed. */
1489
1490                                         if ((r = service_load_pid_file(s)) < 0)
1491                                                 log_warning("%s: failed to load PID file %s: %s", unit_id(UNIT(s)), s->pid_file, strerror(-r));
1492                                 }
1493
1494                                 /* Fall through */
1495
1496                         case SERVICE_RELOAD:
1497                                 if (success) {
1498                                         if (main_pid_good(s) != 0 && cgroup_good(s) != 0)
1499                                                 service_set_state(s, SERVICE_RUNNING);
1500                                         else
1501                                                 service_enter_stop(s, true);
1502                                 } else
1503                                         service_enter_stop(s, false);
1504
1505                                 break;
1506
1507                         case SERVICE_STOP:
1508                                 if (main_pid_good(s) > 0)
1509                                         /* Still not dead and we know the PID? Let's go hunting. */
1510                                         service_enter_signal(s, SERVICE_STOP_SIGTERM, success);
1511                                 else
1512                                         service_enter_stop_post(s, success);
1513                                 break;
1514
1515                         case SERVICE_STOP_SIGTERM:
1516                         case SERVICE_STOP_SIGKILL:
1517                                 if (main_pid_good(s) <= 0)
1518                                         service_enter_stop_post(s, success);
1519
1520                                 /* If there is still a service
1521                                  * process around, wait until
1522                                  * that one quit, too */
1523                                 break;
1524
1525                         case SERVICE_STOP_POST:
1526                         case SERVICE_FINAL_SIGTERM:
1527                         case SERVICE_FINAL_SIGKILL:
1528                                 service_enter_dead(s, success, true);
1529                                 break;
1530
1531                         default:
1532                                 assert_not_reached("Uh, control process died at wrong time.");
1533                         }
1534                 }
1535         } else
1536                 assert_not_reached("Got SIGCHLD for unkown PID");
1537 }
1538
1539 static void service_timer_event(Unit *u, uint64_t elapsed, Watch* w) {
1540         Service *s = SERVICE(u);
1541
1542         assert(s);
1543         assert(elapsed == 1);
1544
1545         assert(w == &s->timer_watch);
1546
1547         switch (s->state) {
1548
1549         case SERVICE_START_PRE:
1550         case SERVICE_START:
1551         case SERVICE_START_POST:
1552         case SERVICE_RELOAD:
1553                 log_warning("%s operation timed out. Stopping.", unit_id(u));
1554                 service_enter_stop(s, false);
1555                 break;
1556
1557         case SERVICE_STOP:
1558                 log_warning("%s stopping timed out. Terminating.", unit_id(u));
1559                 service_enter_signal(s, SERVICE_STOP_SIGTERM, false);
1560                 break;
1561
1562         case SERVICE_STOP_SIGTERM:
1563                 log_warning("%s stopping timed out. Killing.", unit_id(u));
1564                 service_enter_signal(s, SERVICE_STOP_SIGKILL, false);
1565                 break;
1566
1567         case SERVICE_STOP_SIGKILL:
1568                 /* Uh, wie sent a SIGKILL and it is still not gone?
1569                  * Must be something we cannot kill, so let's just be
1570                  * weirded out and continue */
1571
1572                 log_warning("%s still around after SIGKILL. Ignoring.", unit_id(u));
1573                 service_enter_stop_post(s, false);
1574                 break;
1575
1576         case SERVICE_STOP_POST:
1577                 log_warning("%s stopping timed out (2). Terminating.", unit_id(u));
1578                 service_enter_signal(s, SERVICE_FINAL_SIGTERM, false);
1579                 break;
1580
1581         case SERVICE_FINAL_SIGTERM:
1582                 log_warning("%s stopping timed out (2). Killing.", unit_id(u));
1583                 service_enter_signal(s, SERVICE_FINAL_SIGKILL, false);
1584                 break;
1585
1586         case SERVICE_FINAL_SIGKILL:
1587                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", unit_id(u));
1588                 service_enter_dead(s, false, true);
1589                 break;
1590
1591         case SERVICE_AUTO_RESTART:
1592                 log_debug("%s holdoff time over, scheduling restart.", unit_id(u));
1593                 service_enter_restart(s);
1594                 break;
1595
1596         default:
1597                 assert_not_reached("Timeout at wrong time.");
1598         }
1599 }
1600
1601 static void service_cgroup_notify_event(Unit *u) {
1602         Service *s = SERVICE(u);
1603
1604         assert(u);
1605
1606         log_debug("%s: cgroup is empty", unit_id(u));
1607
1608         switch (s->state) {
1609
1610                 /* Waiting for SIGCHLD is usually more interesting,
1611                  * because it includes return codes/signals. Which is
1612                  * why we ignore the cgroup events for most cases,
1613                  * except when we don't know pid which to expect the
1614                  * SIGCHLD for. */
1615
1616         case SERVICE_RUNNING:
1617
1618                 if (!s->valid_no_process && main_pid_good(s) <= 0)
1619                         service_enter_stop(s, true);
1620
1621                 break;
1622
1623         default:
1624                 ;
1625         }
1626 }
1627
1628 static int service_enumerate(Manager *m) {
1629
1630         static const char * const rcnd[] = {
1631                 "../rc0.d", SPECIAL_RUNLEVEL0_TARGET,
1632                 "../rc1.d", SPECIAL_RUNLEVEL1_TARGET,
1633                 "../rc2.d", SPECIAL_RUNLEVEL2_TARGET,
1634                 "../rc3.d", SPECIAL_RUNLEVEL3_TARGET,
1635                 "../rc4.d", SPECIAL_RUNLEVEL4_TARGET,
1636                 "../rc5.d", SPECIAL_RUNLEVEL5_TARGET,
1637                 "../rc6.d", SPECIAL_RUNLEVEL6_TARGET
1638         };
1639
1640         char **p;
1641         unsigned i;
1642         DIR *d = NULL;
1643         char *path = NULL, *fpath = NULL, *name = NULL;
1644         int r;
1645
1646         assert(m);
1647
1648         STRV_FOREACH(p, m->sysvinit_path)
1649                 for (i = 0; i < ELEMENTSOF(rcnd); i += 2) {
1650                         struct dirent *de;
1651
1652                         free(path);
1653                         path = NULL;
1654                         if (asprintf(&path, "%s/%s", *p, rcnd[i]) < 0) {
1655                                 r = -ENOMEM;
1656                                 goto finish;
1657                         }
1658
1659                         if (d)
1660                                 closedir(d);
1661
1662                         if (!(d = opendir(path))) {
1663                                 if (errno != ENOENT)
1664                                         log_warning("opendir() failed on %s: %s", path, strerror(errno));
1665
1666                                 continue;
1667                         }
1668
1669                         while ((de = readdir(d))) {
1670                                 Unit *runlevel, *service;
1671
1672                                 if (ignore_file(de->d_name))
1673                                         continue;
1674
1675                                 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
1676                                         continue;
1677
1678                                 if (strlen(de->d_name) < 4)
1679                                         continue;
1680
1681                                 free(fpath);
1682                                 fpath = NULL;
1683                                 if (asprintf(&fpath, "%s/%s/%s", *p, rcnd[i], de->d_name) < 0) {
1684                                         r = -ENOMEM;
1685                                         goto finish;
1686                                 }
1687
1688                                 if (access(fpath, X_OK) < 0) {
1689
1690                                         if (errno != ENOENT)
1691                                                 log_warning("access() failed on %s: %s", fpath, strerror(errno));
1692
1693                                         continue;
1694                                 }
1695
1696                                 free(name);
1697                                 name = NULL;
1698                                 if (asprintf(&name, "%s.service", de->d_name+3) < 0) {
1699                                         r = -ENOMEM;
1700                                         goto finish;
1701                                 }
1702
1703                                 if ((r = manager_load_unit(m, name, &service)) < 0)
1704                                         goto finish;
1705
1706                                 if ((r = manager_load_unit(m, rcnd[i+1], &runlevel)) < 0)
1707                                         goto finish;
1708
1709                                 if (de->d_name[0] == 'S') {
1710                                         if ((r = unit_add_dependency(runlevel, UNIT_WANTS, service)) < 0)
1711                                                 goto finish;
1712
1713                                         if ((r = unit_add_dependency(runlevel, UNIT_AFTER, service)) < 0)
1714                                                 goto finish;
1715                                 } else {
1716                                         if ((r = unit_add_dependency(runlevel, UNIT_CONFLICTS, service)) < 0)
1717                                                 goto finish;
1718
1719                                         if ((r = unit_add_dependency(runlevel, UNIT_BEFORE, service)) < 0)
1720                                                 goto finish;
1721                                 }
1722                         }
1723                 }
1724
1725         r = 0;
1726
1727 finish:
1728         free(path);
1729         free(fpath);
1730         free(name);
1731         closedir(d);
1732
1733         return r;
1734 }
1735
1736 static const char* const service_state_table[_SERVICE_STATE_MAX] = {
1737         [SERVICE_DEAD] = "dead",
1738         [SERVICE_START_PRE] = "start-pre",
1739         [SERVICE_START] = "start",
1740         [SERVICE_START_POST] = "start-post",
1741         [SERVICE_RUNNING] = "running",
1742         [SERVICE_RELOAD] = "reload",
1743         [SERVICE_STOP] = "stop",
1744         [SERVICE_STOP_SIGTERM] = "stop-sigterm",
1745         [SERVICE_STOP_SIGKILL] = "stop-sigkill",
1746         [SERVICE_STOP_POST] = "stop-post",
1747         [SERVICE_FINAL_SIGTERM] = "final-sigterm",
1748         [SERVICE_FINAL_SIGKILL] = "final-sigkill",
1749         [SERVICE_MAINTAINANCE] = "maintainance",
1750         [SERVICE_AUTO_RESTART] = "auto-restart",
1751 };
1752
1753 DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
1754
1755 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
1756         [SERVICE_ONCE] = "once",
1757         [SERVICE_RESTART_ON_SUCCESS] = "restart-on-success",
1758         [SERVICE_RESTART_ALWAYS] = "restart-on-failure",
1759 };
1760
1761 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
1762
1763 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
1764         [SERVICE_FORKING] = "forking",
1765         [SERVICE_SIMPLE] = "simple",
1766         [SERVICE_FINISH] = "finish"
1767 };
1768
1769 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
1770
1771 static const char* const service_exec_command_table[_SERVICE_EXEC_MAX] = {
1772         [SERVICE_EXEC_START_PRE] = "ExecStartPre",
1773         [SERVICE_EXEC_START] = "ExecStart",
1774         [SERVICE_EXEC_START_POST] = "ExecStartPost",
1775         [SERVICE_EXEC_RELOAD] = "ExecReload",
1776         [SERVICE_EXEC_STOP] = "ExecStop",
1777         [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
1778 };
1779
1780 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
1781
1782 const UnitVTable service_vtable = {
1783         .suffix = ".service",
1784
1785         .init = service_init,
1786         .done = service_done,
1787
1788         .dump = service_dump,
1789
1790         .start = service_start,
1791         .stop = service_stop,
1792         .reload = service_reload,
1793
1794         .can_reload = service_can_reload,
1795
1796         .active_state = service_active_state,
1797
1798         .sigchld_event = service_sigchld_event,
1799         .timer_event = service_timer_event,
1800
1801         .cgroup_notify_empty = service_cgroup_notify_event,
1802
1803         .enumerate = service_enumerate
1804 };