Rename various classes/functions for consistency.
[oweals/dinit.git] / src / shutdown.cc
1 #include <cstddef>
2 #include <cstdio>
3 #include <csignal>
4 #include <unistd.h>
5 #include <cstring>
6 #include <string>
7 #include <iostream>
8
9 #include <sys/reboot.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/un.h>
13 #include <sys/wait.h>
14 #include <sys/stat.h>
15 #include <fcntl.h>
16
17 #include "cpbuffer.h"
18 #include "control-cmds.h"
19 #include "service-constants.h"
20
21 // shutdown:  shut down the system
22 // This utility communicates with the dinit daemon via a unix socket (/dev/initctl).
23
24 void do_system_shutdown(shutdown_type_t shutdown_type);
25 static void unmount_disks();
26 static void swap_off();
27 static void wait_for_reply(cpbuffer<1024> &rbuffer, int fd);
28
29
30 class ReadCPException
31 {
32     public:
33     int errcode;
34     ReadCPException(int err) : errcode(err) { }
35 };
36
37
38 int main(int argc, char **argv)
39 {
40     using namespace std;
41     
42     bool show_help = false;
43     bool sys_shutdown = false;
44     bool use_passed_cfd = false;
45     
46     auto shutdown_type = shutdown_type_t::POWEROFF;
47         
48     for (int i = 1; i < argc; i++) {
49         if (argv[i][0] == '-') {
50             if (strcmp(argv[i], "--help") == 0) {
51                 show_help = true;
52                 break;
53             }
54             
55             if (strcmp(argv[i], "--system") == 0) {
56                 sys_shutdown = true;
57             }
58             else if (strcmp(argv[i], "-r") == 0) {
59                 shutdown_type = shutdown_type_t::REBOOT;
60             }
61             else if (strcmp(argv[i], "-h") == 0) {
62                 shutdown_type = shutdown_type_t::HALT;
63             }
64             else if (strcmp(argv[i], "-p") == 0) {
65                 shutdown_type = shutdown_type_t::POWEROFF;
66             }
67             else if (strcmp(argv[i], "--use-passed-cfd") == 0) {
68                 use_passed_cfd = true;
69             }
70             else {
71                 cerr << "Unrecognized command-line parameter: " << argv[i] << endl;
72                 return 1;
73             }
74         }
75         else {
76             // time argument? TODO
77             show_help = true;
78         }
79     }
80
81     if (show_help) {
82         cout << "dinit-shutdown :   shutdown the system" << endl;
83         cout << "  --help           : show this help" << endl;
84         cout << "  -r               : reboot" << endl;
85         cout << "  -h               : halt system" << endl;
86         cout << "  -p               : power down (default)" << endl;
87         cout << "  --use-passed-cfd : use the socket file descriptor identified by the DINIT_CS_FD" << endl;
88         cout << "                     environment variable to communicate with the init daemon." << endl;
89         cout << "  --system         : perform shutdown immediately, instead of issuing shutdown" << endl;
90         cout << "                     command to the init program. Not recommended for use" << endl;
91         cout << "                     by users." << endl;
92         return 1;
93     }
94     
95     if (sys_shutdown) {
96         do_system_shutdown(shutdown_type);
97         return 0;
98     }
99
100     signal(SIGPIPE, SIG_IGN);
101     
102     int socknum = 0;
103     
104     if (use_passed_cfd) {
105         char * dinit_cs_fd_env = getenv("DINIT_CS_FD");
106         if (dinit_cs_fd_env != nullptr) {
107             char * endptr;
108             long int cfdnum = strtol(dinit_cs_fd_env, &endptr, 10);
109             if (endptr != dinit_cs_fd_env) {
110                 socknum = (int) cfdnum;
111             }
112             else {
113                 use_passed_cfd = false;
114             }
115         }
116         else {
117             use_passed_cfd = false;
118         }
119     }
120     
121     if (! use_passed_cfd) {
122         socknum = socket(AF_UNIX, SOCK_STREAM, 0);
123         if (socknum == -1) {
124             perror("socket");
125             return 1;
126         }
127         
128         const char *naddr = "/dev/dinitctl";
129         
130         struct sockaddr_un name;
131         name.sun_family = AF_UNIX;
132         strcpy(name.sun_path, naddr);
133         int sunlen = offsetof(struct sockaddr_un, sun_path) + strlen(naddr) + 1; // family, (string), nul
134         
135         int connr = connect(socknum, (struct sockaddr *) &name, sunlen);
136         if (connr == -1) {
137             perror("connect");
138             return 1;
139         }
140     }
141
142     // Build buffer;
143     constexpr int bufsize = 2;
144     char buf[bufsize];
145     
146     buf[0] = DINIT_CP_SHUTDOWN;
147     buf[1] = static_cast<char>(shutdown_type);
148     
149     cout << "Issuing shutdown command..." << endl;
150     
151     // TODO make sure to write the whole buffer
152     int r = write(socknum, buf, bufsize);
153     if (r == -1) {
154         perror("write");
155         return 1;
156     }
157     
158     // Wait for ACK/NACK
159     // r = read(socknum, buf, 1);
160     //if (r > 0) {
161     //    cout << "Received acknowledgement. System should now shut down." << endl;
162     //}
163     
164     cpbuffer<1024> rbuffer;
165     try {
166         wait_for_reply(rbuffer, socknum);
167         
168         if (rbuffer[0] != DINIT_RP_ACK) {
169             cerr << "shutdown: control socket protocol error" << endl;
170             return 1;
171         }
172     }
173     catch (ReadCPException &exc)
174     {
175         cerr << "shutdown: control socket read failure or protocol error" << endl;    
176         return 1;
177     }
178     
179     while (true) {
180         pause();
181     }
182     
183     return 0;
184 }
185
186 // Fill a circular buffer from a file descriptor, reading at least _rlength_ bytes.
187 // Throws ReadException if the requested number of bytes cannot be read, with:
188 //     errcode = 0   if end of stream (remote end closed)
189 //     errcode = errno   if another error occurred
190 // Note that EINTR is ignored (i.e. the read will be re-tried).
191 static void fillBufferTo(cpbuffer<1024> *buf, int fd, int rlength)
192 {
193     do {
194         int r = buf->fill_to(fd, rlength);
195         if (r == -1) {
196             if (errno != EINTR) {
197                 throw ReadCPException(errno);
198             }
199         }
200         else if (r == 0) {
201             throw ReadCPException(0);
202         }
203         else {
204             return;
205         }
206     }
207     while (true);
208 }
209
210 // Wait for a reply packet, skipping over any information packets
211 // that are received in the meantime.
212 static void wait_for_reply(cpbuffer<1024> &rbuffer, int fd)
213 {
214     fillBufferTo(&rbuffer, fd, 1);
215     
216     while (rbuffer[0] >= 100) {
217         // Information packet; discard.
218         fillBufferTo(&rbuffer, fd, 1);
219         int pktlen = (unsigned char) rbuffer[1];
220         
221         rbuffer.consume(1);  // Consume one byte so we'll read one byte of the next packet
222         fillBufferTo(&rbuffer, fd, pktlen);
223         rbuffer.consume(pktlen - 1);
224     }
225 }
226
227 // Actually shut down the system.
228 void do_system_shutdown(shutdown_type_t shutdown_type)
229 {
230     using namespace std;
231     
232     // Mask all signals to prevent death of our parent etc from terminating us
233     sigset_t allsigs;
234     sigfillset(&allsigs);
235     sigprocmask(SIG_SETMASK, &allsigs, nullptr);
236     
237     int reboot_type = 0;
238     if (shutdown_type == shutdown_type_t::REBOOT) reboot_type = RB_AUTOBOOT;
239     else if (shutdown_type == shutdown_type_t::POWEROFF) reboot_type = RB_POWER_OFF;
240     else reboot_type = RB_HALT_SYSTEM;
241     
242     // Write to console rather than any terminal, since we lose the terminal it seems:
243     close(STDOUT_FILENO);
244     int consfd = open("/dev/console", O_WRONLY);
245     if (consfd != STDOUT_FILENO) {
246         dup2(consfd, STDOUT_FILENO);
247     }
248     
249     cout << "Sending TERM/KILL to all processes..." << endl; // DAV
250     
251     // Send TERM/KILL to all (remaining) processes
252     kill(-1, SIGTERM);
253     sleep(1);
254     kill(-1, SIGKILL);
255     
256     // perform shutdown
257     cout << "Turning off swap..." << endl;
258     swap_off();
259     cout << "Unmounting disks..." << endl;
260     unmount_disks();
261     sync();
262     
263     cout << "Issuing shutdown via kernel..." << endl;
264     reboot(reboot_type);
265 }
266
267 static void unmount_disks()
268 {
269     pid_t chpid = fork();
270     if (chpid == 0) {
271         // umount -a -r
272         //  -a : all filesystems (except proc)
273         //  -r : mount readonly if can't unmount
274         execl("/bin/umount", "/bin/umount", "-a", "-r", nullptr);
275     }
276     else if (chpid > 0) {
277         int status;
278         waitpid(chpid, &status, 0);
279     }
280 }
281
282 static void swap_off()
283 {
284     pid_t chpid = fork();
285     if (chpid == 0) {
286         // swapoff -a
287         execl("/sbin/swapoff", "/sbin/swapoff", "-a", nullptr);
288     }
289     else if (chpid > 0) {
290         int status;
291         waitpid(chpid, &status, 0);
292     }
293 }