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