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