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