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