Release soft dependencies if they stop early.
[oweals/dinit.git] / src / service.cc
1 #include <cstring>
2 #include <cerrno>
3 #include <sstream>
4 #include <iterator>
5 #include <memory>
6 #include <cstddef>
7
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <sys/ioctl.h>
11 #include <sys/un.h>
12 #include <sys/socket.h>
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <termios.h>
16
17 #include "service.h"
18 #include "dinit-log.h"
19
20 /*
21  * service.cc - Service management.
22  * See service.h for details.
23  */
24
25 // from dinit.cc:
26 void open_control_socket(bool report_ro_failure = true) noexcept;
27 void setup_external_log() noexcept;
28 extern EventLoop_t eventLoop;
29
30 // Find the requested service by name
31 static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
32                                     const char *name) noexcept
33 {
34     using std::list;
35     list<ServiceRecord *>::const_iterator i = records.begin();
36     for ( ; i != records.end(); i++ ) {
37         if (strcmp((*i)->getServiceName().c_str(), name) == 0) {
38             return *i;
39         }
40     }
41     return (ServiceRecord *)0;
42 }
43
44 ServiceRecord * ServiceSet::findService(const std::string &name) noexcept
45 {
46     return ::findService(records, name.c_str());
47 }
48
49 void ServiceSet::startService(const char *name)
50 {
51     using namespace std;
52     ServiceRecord *record = loadServiceRecord(name);
53     
54     record->start();
55     processQueues(true);
56 }
57
58 void ServiceSet::stopService(const std::string & name) noexcept
59 {
60     ServiceRecord *record = findService(name);
61     if (record != nullptr) {
62         record->stop();
63         processQueues(false);
64     }
65 }
66
67 // Called when a service has actually stopped.
68 void ServiceRecord::stopped() noexcept
69 {
70     if (service_type != ServiceType::SCRIPTED && service_type != ServiceType::BGPROCESS && onstart_flags.runs_on_console) {
71         tcsetpgrp(0, getpgrp());
72         discard_console_log_buffer();
73         releaseConsole();
74     }
75
76     service_state = ServiceState::STOPPED;
77     force_stop = false;
78     
79     logServiceStopped(service_name);
80     notifyListeners(ServiceEvent::STOPPED);
81     
82     bool will_restart = (desired_state == ServiceState::STARTED) && service_set->get_auto_restart();
83     for (auto dependency : depends_on) {
84         if (! will_restart || ! dependency->can_interrupt_stop()) {
85             dependency->dependentStopped();
86         }
87     }
88     
89     // If we are a soft dependency of another target, break the acquisition from that target now:
90     if (! will_restart) {
91         for (auto dependency : soft_dpts) {
92             if (dependency->holding_acq) {
93                 dependency->holding_acq = false;
94                 release();
95             }
96         }
97     }
98     
99     if (will_restart) {
100         // Desired state is "started".
101         service_set->addToStartQueue(this);
102     }
103     else {
104         desired_state = ServiceState::STOPPED;
105         
106         if (socket_fd != -1) {
107             close(socket_fd);
108             socket_fd = -1;
109         }
110         
111         if (start_explicit) {
112             start_explicit = false;
113             required_by--;
114         }
115         
116         if (required_by == 0) {
117             // Service is now completely inactive.
118             release_dependencies();
119         }
120     }
121 }
122
123 dasynq::rearm ServiceChildWatcher::childStatus(EventLoop_t &loop, pid_t child, int status) noexcept
124 {
125     ServiceRecord *sr = service;
126     
127     sr->pid = -1;
128     sr->exit_status = status;
129     
130     // Ok, for a process service, any process death which we didn't rig
131     // ourselves is a bit... unexpected. Probably, the child died because
132     // we asked it to (sr->service_state == STOPPING). But even if
133     // we didn't, there's not much we can do.
134     
135     if (sr->waiting_for_execstat) {
136         // We still don't have an exec() status from the forked child, wait for that
137         // before doing any further processing.
138         return rearm::REMOVE;
139     }
140     
141     // Must deregister now since handle_exit_status might result in re-launch:
142     deregister(loop, child);
143     
144     sr->handle_exit_status();
145     return rearm::REMOVED;
146 }
147
148 bool ServiceRecord::do_auto_restart() noexcept
149 {
150     if (auto_restart) {
151         return service_set->get_auto_restart();
152     }
153     return false;
154 }
155
156 void ServiceRecord::handle_exit_status() noexcept
157 {
158     bool did_exit = WIFEXITED(exit_status);
159     bool was_signalled = WIFSIGNALED(exit_status);
160
161     if (service_type != ServiceType::SCRIPTED && exit_status != 0 && service_state != ServiceState::STOPPING) {
162         if (did_exit) {
163             log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", WEXITSTATUS(exit_status));
164         }
165         else if (was_signalled) {
166             log(LogLevel::ERROR, "Service ", service_name, " terminated due to signal ", WTERMSIG(exit_status));
167         }
168     }
169
170     if (doing_recovery) {
171         // (BGPROCESS only)
172         doing_recovery = false;
173         bool need_stop = false;
174         if ((did_exit && WEXITSTATUS(exit_status) != 0) || was_signalled) {
175             need_stop = true;
176         }
177         else {
178             // We need to re-read the PID, since it has now changed.
179             if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
180                 if (! read_pid_file()) {
181                     need_stop = true;
182                 }
183             }
184         }
185         
186         if (need_stop) {
187             // Failed startup: no auto-restart.
188             desired_state = ServiceState::STOPPED;
189             forceStop();
190             service_set->processQueues(false);
191         }
192         
193         return;
194     }
195     
196     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
197         if (service_state == ServiceState::STARTING) {
198             // (only applies to BGPROCESS)
199             if (did_exit && WEXITSTATUS(exit_status) == 0) {
200                 started();
201             }
202             else {
203                 failed_to_start();
204             }
205         }
206         else if (service_state == ServiceState::STOPPING) {
207             // We won't log a non-zero exit status or termination due to signal here -
208             // we assume that the process died because we signalled it.
209             stopped();
210         }
211         else if (smooth_recovery && service_state == ServiceState::STARTED && desired_state == ServiceState::STARTED) {
212             // TODO ensure a minimum time between restarts
213             // TODO if we are pinned-started then we should probably check
214             //      that dependencies have started before trying to re-start the
215             //      service process.
216             doing_recovery = (service_type == ServiceType::BGPROCESS);
217             start_ps_process();
218             return;
219         }
220         else {
221             if (! do_auto_restart()) desired_state = ServiceState::STOPPED;
222             forceStop();
223         }
224         service_set->processQueues(false);
225     }
226     else {  // SCRIPTED
227         if (service_state == ServiceState::STOPPING) {
228             if (did_exit && WEXITSTATUS(exit_status) == 0) {
229                 stopped();
230             }
231             else {
232                 // ??? failed to stop! Let's log it as info:
233                 if (did_exit) {
234                     log(LogLevel::INFO, "Service ", service_name, " stop command failed with exit code ", WEXITSTATUS(exit_status));
235                 }
236                 else if (was_signalled) {
237                     log(LogLevel::INFO, "Serivice ", service_name, " stop command terminated due to signal ", WTERMSIG(exit_status));
238                 }
239                 // Just assume that we stopped, so that any dependencies
240                 // can be stopped:
241                 stopped();
242             }
243             service_set->processQueues(false);
244         }
245         else { // STARTING
246             if (exit_status == 0) {
247                 started();
248             }
249             else {
250                 // failed to start
251                 if (did_exit) {
252                     log(LogLevel::ERROR, "Service ", service_name, " command failed with exit code ", WEXITSTATUS(exit_status));
253                 }
254                 else if (was_signalled) {
255                     log(LogLevel::ERROR, "Service ", service_name, " command terminated due to signal ", WTERMSIG(exit_status));
256                 }
257                 failed_to_start();
258             }
259             service_set->processQueues(true);
260         }
261     }
262 }
263
264 rearm ServiceIoWatcher::fdEvent(EventLoop_t &loop, int fd, int flags) noexcept
265 {
266     ServiceRecord *sr = service;
267     sr->waiting_for_execstat = false;
268     
269     int exec_status;
270     int r = read(getWatchedFd(), &exec_status, sizeof(int));
271     deregister(loop);
272     close(getWatchedFd());
273     
274     if (r > 0) {
275         // We read an errno code; exec() failed, and the service startup failed.
276         sr->pid = -1;
277         log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
278         if (sr->service_state == ServiceState::STARTING) {
279             sr->failed_to_start();
280         }
281         else if (sr->service_state == ServiceState::STOPPING) {
282             // Must be a scripted service. We've logged the failure, but it's probably better
283             // not to leave the service in STARTED state:
284             sr->stopped();
285         }
286     }
287     else {
288         // exec() succeeded.
289         if (sr->service_type == ServiceType::PROCESS) {
290             // This could be a smooth recovery (state already STARTED). Even more, the process
291             // might be stopped (and killed via a signal) during smooth recovery.  We don't to
292             // process startup again in either case, so we check for state STARTING:
293             if (sr->service_state == ServiceState::STARTING) {
294                 sr->started();
295             }
296         }
297         
298         if (sr->pid == -1) {
299             // Somehow the process managed to complete before we even saw the status.
300             sr->handle_exit_status();
301         }
302     }
303     
304     sr->service_set->processQueues(true);
305     
306     return rearm::REMOVED;
307 }
308
309 void ServiceRecord::require() noexcept
310 {
311     if (required_by++ == 0) {
312         
313         if (! prop_require) {
314             prop_require = true;
315             prop_release = false;
316             service_set->addToPropQueue(this);
317         }
318         
319         if (service_state == ServiceState::STOPPED) {
320             // (In any other state, the service is already considered active.)
321             service_set->service_active(this);
322         }
323     }
324 }
325
326 void ServiceRecord::release() noexcept
327 {
328     if (--required_by == 0) {
329         desired_state = ServiceState::STOPPED;
330         // Can stop, and release dependencies once we're stopped.
331         if (service_state == ServiceState::STOPPED) {
332             prop_release = true;
333             prop_require = false;
334             service_set->addToPropQueue(this);
335         }
336         else {
337             service_set->addToStopQueue(this);
338         }
339     }
340 }
341
342 void ServiceRecord::release_dependencies() noexcept
343 {
344     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
345         (*i)->release();
346     }
347
348     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
349         ServiceRecord * to = i->getTo();
350         if (i->holding_acq) {
351             to->release();
352             i->holding_acq = false;
353         }
354     }
355     
356     service_set->service_inactive(this);
357 }
358
359 void ServiceRecord::start(bool activate) noexcept
360 {
361     if (activate && ! start_explicit) {
362         require();
363         start_explicit = true;
364     }
365     
366     if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
367     
368     desired_state = ServiceState::STARTED;
369     service_set->addToStartQueue(this);
370 }
371
372 void ServiceRecord::do_propagation() noexcept
373 {
374     if (prop_require) {
375         // Need to require all our dependencies
376         for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
377             (*i)->require();
378         }
379
380         for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
381             ServiceRecord * to = i->getTo();
382             to->require();
383             i->holding_acq = true;
384         }
385         
386         prop_require = false;
387     }
388     
389     if (prop_release) {
390         release_dependencies();
391         prop_release = false;
392     }
393     
394     if (prop_failure) {
395         prop_failure = false;
396         failed_to_start(true);
397     }
398     
399     if (waiting_for_deps) {
400         if (service_state == ServiceState::STARTING) {
401             if (startCheckDependencies(false)) {
402                 allDepsStarted();
403             }
404         }
405         else if (service_state == ServiceState::STOPPING) {
406             if (stopCheckDependents()) {
407                 allDepsStopped();
408             }
409         }
410     }
411 }
412
413 void ServiceRecord::execute_transition() noexcept
414 {
415     bool is_started = (service_state == ServiceState::STARTED)
416             || (service_state == ServiceState::STARTING && can_interrupt_start());
417     bool is_stopped = (service_state == ServiceState::STOPPED)
418             || (service_state == ServiceState::STOPPING && can_interrupt_stop());
419
420     if (is_started && (desired_state == ServiceState::STOPPED || force_stop)) {
421         if (! pinned_started) {
422             do_stop();
423         }
424     }
425     else if (is_stopped && desired_state == ServiceState::STARTED) {
426         if (! pinned_stopped) {
427             do_start();
428         }
429     }
430 }
431
432 void ServiceRecord::do_start() noexcept
433 {
434     if (pinned_stopped) return;
435     
436     if (service_state != ServiceState::STOPPED) {
437         // We're already starting/started, or we are stopping and need to wait for
438         // that the complete.
439         if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
440             return;
441         }
442         // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
443         // but if so they are waiting (for us), so they too can be instantly returned to
444         // STARTING state.
445         notifyListeners(ServiceEvent::STOPCANCELLED);
446     }
447     
448     service_state = ServiceState::STARTING;
449
450     waiting_for_deps = true;
451
452     // Ask dependencies to start, mark them as being waited on.
453     if (! startCheckDependencies(true)) {
454         return;
455     }
456
457     // Actually start this service.
458     allDepsStarted();
459 }
460
461 void ServiceRecord::dependencyStarted() noexcept
462 {
463     if (service_state == ServiceState::STARTING && waiting_for_deps) {
464         service_set->addToPropQueue(this);
465     }
466 }
467
468 bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
469 {
470     bool all_deps_started = true;
471
472     for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
473         if ((*i)->service_state != ServiceState::STARTED) {
474             if (start_deps) {
475                 all_deps_started = false;
476                 (*i)->start(false);
477             }
478             else {
479                 return false;
480             }
481         }
482     }
483
484     for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
485         ServiceRecord * to = i->getTo();
486         if (start_deps) {
487             if (to->service_state != ServiceState::STARTED) {
488                 to->start(false);
489                 i->waiting_on = true;
490                 all_deps_started = false;
491             }
492             else {
493                 i->waiting_on = false;
494             }
495         }
496         else if (i->waiting_on) {
497             if (to->service_state != ServiceState::STARTING) {
498                 // Service has either started or is no longer starting
499                 i->waiting_on = false;
500             }
501             else {
502                 // We are still waiting on this service
503                 return false;
504             }
505         }
506     }
507     
508     return all_deps_started;
509 }
510
511 bool ServiceRecord::open_socket() noexcept
512 {
513     if (socket_path.empty() || socket_fd != -1) {
514         // No socket, or already open
515         return true;
516     }
517     
518     const char * saddrname = socket_path.c_str();
519     uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
520
521     struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
522     if (name == nullptr) {
523         log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
524         return false;
525     }
526     
527     // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
528     unlink(saddrname);
529
530     name->sun_family = AF_UNIX;
531     strcpy(name->sun_path, saddrname);
532
533     int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
534     if (sockfd == -1) {
535         log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
536         free(name);
537         return false;
538     }
539
540     if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
541         log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
542         close(sockfd);
543         free(name);
544         return false;
545     }
546     
547     free(name);
548     
549     // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
550     // use chown and chmod instead.
551     if (chown(saddrname, socket_uid, socket_gid)) {
552         log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
553         close(sockfd);
554         return false;
555     }
556     
557     if (chmod(saddrname, socket_perms) == -1) {
558         log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
559         close(sockfd);
560         return false;
561     }
562
563     if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
564         log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
565         close(sockfd);
566         return false;
567     }
568     
569     socket_fd = sockfd;
570     return true;
571 }
572
573 void ServiceRecord::allDepsStarted(bool has_console) noexcept
574 {
575     if (onstart_flags.runs_on_console && ! has_console) {
576         waiting_for_deps = true;
577         queueForConsole();
578         return;
579     }
580     
581     waiting_for_deps = false;
582
583     if (! open_socket()) {
584         failed_to_start();
585     }
586
587     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS
588             || service_type == ServiceType::SCRIPTED) {
589         bool start_success = start_ps_process();
590         if (! start_success) {
591             failed_to_start();
592         }
593     }
594     else {
595         // "internal" service
596         started();
597     }
598 }
599
600 void ServiceRecord::acquiredConsole() noexcept
601 {
602     if (service_state != ServiceState::STARTING) {
603         // We got the console but no longer want it.
604         releaseConsole();
605     }
606     else if (startCheckDependencies(false)) {
607         allDepsStarted(true);
608     }
609     else {
610         // We got the console but can't use it yet.
611         releaseConsole();
612     }
613 }
614
615 bool ServiceRecord::read_pid_file() noexcept
616 {
617     const char *pid_file_c = pid_file.c_str();
618     int fd = open(pid_file_c, O_CLOEXEC);
619     if (fd != -1) {
620         char pidbuf[21]; // just enought to hold any 64-bit integer
621         int r = read(fd, pidbuf, 20);
622         if (r > 0) {
623             pidbuf[r] = 0; // store nul terminator
624             pid = std::atoi(pidbuf);
625             if (kill(pid, 0) == 0) {                
626                 child_listener.addWatch(eventLoop, pid);
627             }
628             else {
629                 log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
630                 pid = -1;
631                 close(fd);
632                 return false;
633             }
634         }
635         close(fd);
636         return true;
637     }
638     else {
639         log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
640         return false;
641     }
642 }
643
644 void ServiceRecord::started() noexcept
645 {
646     if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
647         tcsetpgrp(0, getpgrp());
648         releaseConsole();
649     }
650     
651     if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
652         if (! read_pid_file()) {
653             failed_to_start();
654             return;
655         }
656     }
657     
658     logServiceStarted(service_name);
659     service_state = ServiceState::STARTED;
660     notifyListeners(ServiceEvent::STARTED);
661
662     if (onstart_flags.rw_ready) {
663         open_control_socket();
664     }
665     if (onstart_flags.log_ready) {
666         setup_external_log();
667     }
668
669     if (force_stop || desired_state == ServiceState::STOPPED) {
670         // We must now stop.
671         service_set->addToStopQueue(this);
672         return;
673     }
674
675     // Notify any dependents whose desired state is STARTED:
676     for (auto i = dependents.begin(); i != dependents.end(); i++) {
677         (*i)->dependencyStarted();
678     }
679     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
680         (*i)->getFrom()->dependencyStarted();
681     }
682 }
683
684 void ServiceRecord::failed_to_start(bool depfailed) noexcept
685 {
686     if (!depfailed && onstart_flags.runs_on_console) {
687         tcsetpgrp(0, getpgrp());
688         releaseConsole();
689     }
690     
691     logServiceFailed(service_name);
692     service_state = ServiceState::STOPPED;
693     if (start_explicit) {
694         start_explicit = false;
695         release();
696     }
697     notifyListeners(ServiceEvent::FAILEDSTART);
698     
699     // Cancel start of dependents:
700     for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
701         if ((*i)->service_state == ServiceState::STARTING) {
702             (*i)->prop_failure = true;
703             service_set->addToPropQueue(*i);
704         }
705     }    
706     for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
707         // We can send 'start', because this is only a soft dependency.
708         // Our startup failure means that they don't have to wait for us.
709         if ((*i)->waiting_on) {
710             (*i)->holding_acq = false;
711             (*i)->waiting_on = false;
712             (*i)->getFrom()->dependencyStarted();
713             release();
714         }
715     }
716 }
717
718 bool ServiceRecord::start_ps_process() noexcept
719 {
720     return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
721 }
722
723 bool ServiceRecord::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
724 {
725     // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
726     // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
727     // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
728     // is written to the pipe, and the parent can read it.
729
730     int pipefd[2];
731     if (pipe2(pipefd, O_CLOEXEC)) {
732         log(LogLevel::ERROR, service_name, ": can't create status check pipe: ", strerror(errno));
733         return false;
734     }
735
736     const char * logfile = this->logfile.c_str();
737     if (*logfile == 0) {
738         logfile = "/dev/null";
739     }
740
741     bool child_status_registered = false;
742     ControlConn *control_conn = nullptr;
743     
744     int control_socket[2] = {-1, -1};
745     if (onstart_flags.pass_cs_fd) {
746         if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, /* protocol */ 0, control_socket)) {
747             log(LogLevel::ERROR, service_name, ": can't create control socket: ", strerror(errno));
748             goto out_p;
749         }
750         
751         // Make the server side socket close-on-exec:
752         int fdflags = fcntl(control_socket[0], F_GETFD);
753         fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
754         
755         try {
756             control_conn = new ControlConn(&eventLoop, service_set, control_socket[0]);
757         }
758         catch (std::exception &exc) {
759             log(LogLevel::ERROR, service_name, ": can't launch process; out of memory");
760             goto out_cs;
761         }
762     }
763     
764     // Set up complete, now fork and exec:
765     
766     pid_t forkpid;
767     
768     try {
769         child_status_listener.addWatch(eventLoop, pipefd[0], IN_EVENTS);
770         child_status_registered = true;
771         
772         forkpid = child_listener.fork(eventLoop);
773     }
774     catch (std::exception &e) {
775         log(LogLevel::ERROR, service_name, ": Could not fork: ", e.what());
776         goto out_cs_h;
777     }
778
779     if (forkpid == 0) {
780         run_child_proc(cmd.data(), logfile, on_console, pipefd[1], control_socket[1]);
781     }
782     else {
783         // Parent process
784         close(pipefd[1]); // close the 'other end' fd
785         if (control_socket[1] != -1) {
786             close(control_socket[1]);
787         }
788         pid = forkpid;
789
790         waiting_for_execstat = true;
791         return true;
792     }
793
794     // Failure exit:
795     
796     out_cs_h:
797     if (child_status_registered) {
798         child_status_listener.deregister(eventLoop);
799     }
800     
801     if (onstart_flags.pass_cs_fd) {
802         delete control_conn;
803     
804         out_cs:
805         close(control_socket[0]);
806         close(control_socket[1]);
807     }
808     
809     out_p:
810     close(pipefd[0]);
811     close(pipefd[1]);
812     
813     return false;
814 }
815
816 void ServiceRecord::run_child_proc(const char * const *args, const char *logfile, bool on_console,
817         int wpipefd, int csfd) noexcept
818 {
819     // Child process. Must not allocate memory (or otherwise risk throwing any exception)
820     // from here until exit().
821
822     // If the console already has a session leader, presumably it is us. On the other hand
823     // if it has no session leader, and we don't create one, then control inputs such as
824     // ^C will have no effect.
825     bool do_set_ctty = (tcgetsid(0) == -1);
826     
827     // Copy signal mask, but unmask signals that we masked on startup. For the moment, we'll
828     // also block all signals, since apparently dup() can be interrupted (!!! really, POSIX??).
829     sigset_t sigwait_set;
830     sigset_t sigall_set;
831     sigfillset(&sigall_set);
832     sigprocmask(SIG_SETMASK, &sigall_set, &sigwait_set);
833     sigdelset(&sigwait_set, SIGCHLD);
834     sigdelset(&sigwait_set, SIGINT);
835     sigdelset(&sigwait_set, SIGTERM);
836     
837     constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t)) / 3 + 2) + 11;
838     // "LISTEN_PID=" - 11 characters; the expression above gives a conservative estimate
839     // on the maxiumum number of bytes required for LISTEN=xxx, including nul terminator,
840     // where xxx is a pid_t in decimal (i.e. one decimal digit is worth just over 3 bits).
841     char nbuf[bufsz];
842     
843     // "DINIT_CS_FD=" - 12 bytes. (we -1 from sizeof(int) in account of sign bit).
844     constexpr int csenvbufsz = ((CHAR_BIT * sizeof(int) - 1) / 3 + 2) + 12;
845     char csenvbuf[csenvbufsz];
846     
847     int minfd = (socket_fd == -1) ? 3 : 4;
848
849     // Move wpipefd/csfd to another fd if necessary
850     if (wpipefd < minfd) {
851         wpipefd = fcntl(wpipefd, F_DUPFD_CLOEXEC, minfd);
852         if (wpipefd == -1) goto failure_out;
853     }
854     
855     if (csfd != -1 && csfd < minfd) {
856         csfd = fcntl(csfd, F_DUPFD, minfd);
857         if (csfd == -1) goto failure_out;
858     }
859     
860     if (socket_fd != -1) {
861         
862         if (dup2(socket_fd, 3) == -1) goto failure_out;
863         if (socket_fd != 3) {
864             close(socket_fd);
865         }
866         
867         if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
868         snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
869         if (putenv(nbuf)) goto failure_out;
870     }
871     
872     if (csfd != -1) {
873         snprintf(csenvbuf, csenvbufsz, "DINIT_CS_FD=%d", csfd);
874         if (putenv(csenvbuf)) goto failure_out;
875     }
876
877     if (! on_console) {
878         // Re-set stdin, stdout, stderr
879         close(0); close(1); close(2);
880
881         if (open("/dev/null", O_RDONLY) == 0) {
882             // stdin = 0. That's what we should have; proceed with opening
883             // stdout and stderr.
884             if (open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR) != 1) {
885                 goto failure_out;
886             }
887             if (dup2(1, 2) != 2) {
888                 goto failure_out;
889             }
890         }
891         else goto failure_out;
892         
893         // We have the option of creating a new process group and/or session. If
894         // we just create a new process group, the child process cannot make itself
895         // a session leader if it wants to do that (eg getty/login will generally
896         // want this). If we do neither, and we are running with a controlling
897         // terminal, a ^C or similar will also affect the child process.
898         setsid();
899     }
900     else {
901         // "run on console" - run as a foreground job on the terminal/console device
902         
903         // if do_set_ctty is false, we are the session leader; we are probably running
904         // as a user process. Don't create a new session leader in that case, and run
905         // as part of the parent session. Otherwise, the new session cannot claim the
906         // terminal as a controlling terminal (it is already claimed), meaning that it
907         // will not see control signals from ^C etc.
908         
909         if (do_set_ctty) {
910             // Disable suspend (^Z) (and on some systems, delayed suspend / ^Y)
911             signal(SIGTSTP, SIG_IGN);
912             
913             // Become session leader
914             setsid();
915             ioctl(0, TIOCSCTTY, 0);
916         }
917         setpgid(0,0);
918         tcsetpgrp(0, getpgrp());
919     }
920     
921     sigprocmask(SIG_SETMASK, &sigwait_set, nullptr);
922     
923     execvp(args[0], const_cast<char **>(args));
924     
925     // If we got here, the exec failed:
926     failure_out:
927     int exec_status = errno;
928     write(wpipefd, &exec_status, sizeof(int));
929     _exit(0);
930 }
931
932 // Mark this and all dependent services as force-stopped.
933 void ServiceRecord::forceStop() noexcept
934 {
935     if (service_state != ServiceState::STOPPED) {
936         force_stop = true;
937         service_set->addToStopQueue(this);
938     }
939 }
940
941 void ServiceRecord::dependentStopped() noexcept
942 {
943     if (service_state == ServiceState::STOPPING && waiting_for_deps) {
944         service_set->addToPropQueue(this);
945     }
946 }
947
948 void ServiceRecord::stop(bool bring_down) noexcept
949 {
950     if (start_explicit) {
951         start_explicit = false;
952         release();
953     }
954     
955     if (bring_down && desired_state != ServiceState::STOPPED) {
956         desired_state = ServiceState::STOPPED;
957         service_set->addToStopQueue(this);
958     }
959 }
960
961 void ServiceRecord::do_stop() noexcept
962 {
963     if (pinned_started) return;
964
965     if (service_state != ServiceState::STARTED) {
966         if (service_state == ServiceState::STARTING) {
967             if (! can_interrupt_start()) {
968                 // Well this is awkward: we're going to have to continue
969                 // starting, but we don't want any dependents to think that
970                 // they are still waiting to start.
971                 // Make sure they remain stopped:
972                 stopDependents();
973                 return;
974             }
975
976             // We must have had desired_state == STARTED.
977             notifyListeners(ServiceEvent::STARTCANCELLED);
978             
979             // Reaching this point, we have can_interrupt_start() == true. So,
980             // we can stop. Dependents might be starting, but they must be
981             // waiting on us, so they should also be immediately stoppable.
982             // Fall through to below,.
983         }
984         else {
985             // If we're starting we need to wait for that to complete.
986             // If we're already stopping/stopped there's nothing to do.
987             return;
988         }
989     }
990     
991     service_state = ServiceState::STOPPING;
992     waiting_for_deps = true;
993     
994     // If we get here, we are in STARTED state; stop all dependents.
995     if (stopDependents()) {
996         allDepsStopped();
997     }
998 }
999
1000 bool ServiceRecord::stopCheckDependents() noexcept
1001 {
1002     bool all_deps_stopped = true;
1003     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1004         if (! (*i)->is_stopped()) {
1005             all_deps_stopped = false;
1006             break;
1007         }
1008     }
1009     
1010     return all_deps_stopped;
1011 }
1012
1013 bool ServiceRecord::stopDependents() noexcept
1014 {
1015     bool all_deps_stopped = true;
1016     for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
1017         if (! (*i)->is_stopped()) {
1018             // Note we check *first* since if the dependent service is not stopped,
1019             // 1. We will issue a stop to it shortly and
1020             // 2. It will notify us when stopped, at which point the stopCheckDependents()
1021             //    check is run anyway.
1022             all_deps_stopped = false;
1023         }
1024         if (force_stop) {
1025             (*i)->forceStop();
1026         }
1027         else {
1028             service_set->addToStopQueue(*i);
1029         }
1030     }
1031     
1032     return all_deps_stopped;
1033 }
1034
1035 // All dependents have stopped; we can stop now, too. Only called when STOPPING.
1036 void ServiceRecord::allDepsStopped()
1037 {
1038     waiting_for_deps = false;
1039     if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
1040         if (pid != -1) {
1041             // The process is still kicking on - must actually kill it.
1042             if (! onstart_flags.no_sigterm) {
1043                 kill(pid, SIGTERM);
1044             }
1045             if (term_signal != -1) {
1046                 kill(pid, term_signal);
1047             }
1048             
1049             // In most cases, the rest is done in process_child_callback.
1050             // If we are a BGPROCESS and the process is not our immediate child, however, that
1051             // won't work - check for this now:
1052             if (service_type == ServiceType::BGPROCESS) {
1053                 int status;
1054                 pid_t r = waitpid(pid, &status, WNOHANG);
1055                 if (r == -1 && errno == ECHILD) {
1056                     // We can't track this child (or it's terminated already)
1057                     stopped();
1058                 }
1059                 else if (r == pid) {
1060                     // TODO, examine status and log anything unusual.
1061                     stopped();
1062                 }
1063             }
1064         }
1065         else {
1066             // The process is already dead.
1067             stopped();
1068         }
1069     }
1070     else if (service_type == ServiceType::SCRIPTED) {
1071         // Scripted service.
1072         if (stop_command.length() == 0) {
1073             stopped();
1074         }
1075         else if (! start_ps_process(stop_arg_parts, false)) {
1076             // Couldn't execute stop script, but there's not much we can do:
1077             stopped();
1078         }
1079     }
1080     else {
1081         stopped();
1082     }
1083 }
1084
1085 void ServiceRecord::unpin() noexcept
1086 {
1087     if (pinned_started) {
1088         pinned_started = false;
1089         if (desired_state == ServiceState::STOPPED) {
1090             do_stop();
1091             service_set->processQueues(false);
1092         }
1093     }
1094     if (pinned_stopped) {
1095         pinned_stopped = false;
1096         if (desired_state == ServiceState::STARTED) {
1097             do_start();
1098             service_set->processQueues(true);
1099         }
1100     }
1101 }
1102
1103 void ServiceRecord::queueForConsole() noexcept
1104 {
1105     service_set->consoleQueueTail(this);
1106 }
1107
1108 void ServiceRecord::releaseConsole() noexcept
1109 {
1110     service_set->pullConsoleQueue();
1111 }
1112
1113 void ServiceSet::service_active(ServiceRecord *sr) noexcept
1114 {
1115     active_services++;
1116 }
1117
1118 void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
1119 {
1120     active_services--;
1121 }