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