shutdown.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. #include <cstddef>
  2. #include <cstdio>
  3. #include <csignal>
  4. #include <cstring>
  5. #include <string>
  6. #include <iostream>
  7. #include <exception>
  8. #include <sys/reboot.h>
  9. #include <sys/types.h>
  10. #include <sys/socket.h>
  11. #include <sys/un.h>
  12. #include <sys/wait.h>
  13. #include <sys/stat.h>
  14. #include <unistd.h>
  15. #include <fcntl.h>
  16. #include "cpbuffer.h"
  17. #include "control-cmds.h"
  18. #include "service-constants.h"
  19. #include "dinit-client.h"
  20. #include "dinit-util.h"
  21. #include "mconfig.h"
  22. #include "control-datatypes.h"
  23. #include "dasynq.h"
  24. // shutdown: shut down the system
  25. // This utility communicates with the dinit daemon via a unix socket (specified in SYSCONTROLSOCKET).
  26. static constexpr uint16_t min_cp_version = 1;
  27. static constexpr uint16_t max_cp_version = 1;
  28. using loop_t = dasynq::event_loop_n;
  29. using rearm = dasynq::rearm;
  30. using clock_type = dasynq::clock_type;
  31. class subproc_buffer;
  32. void do_system_shutdown(shutdown_type_t shutdown_type);
  33. static void unmount_disks(loop_t &loop, subproc_buffer &sub_buf);
  34. static void swap_off(loop_t &loop, subproc_buffer &sub_buf);
  35. static int run_process(const char * prog_args[], loop_t &loop, subproc_buffer &sub_buf);
  36. constexpr static int subproc_bufsize = 4096;
  37. constexpr static char output_lost_msg[] = "[Some output has not been shown due to buffer overflow]\n";
  38. // A buffer which maintains a series of overflow markers, used for capturing and echoing
  39. // subprocess output.
  40. class subproc_buffer : private cpbuffer<subproc_bufsize>
  41. {
  42. using base = cpbuffer<subproc_bufsize>;
  43. int overflow_marker = -1;
  44. int last_overflow = -1; // last marker in the series
  45. const char *overflow_msg_ptr = nullptr; // current position in overflow message
  46. dasynq::event_loop_n &loop;
  47. dasynq::event_loop_n::fd_watcher * out_watch;
  48. public:
  49. enum class fill_status
  50. {
  51. OK,
  52. ENDFILE,
  53. FULL
  54. };
  55. subproc_buffer(dasynq::event_loop_n &loop_p, int out_fd) : loop(loop_p)
  56. {
  57. using loop_t = dasynq::event_loop_n;
  58. using rearm = dasynq::rearm;
  59. out_watch = loop_t::fd_watcher::add_watch(loop, out_fd, dasynq::OUT_EVENTS,
  60. [&](loop_t &eloop, int fd, int flags) -> rearm {
  61. auto fstatus = flush(STDOUT_FILENO);
  62. if (fstatus == subproc_buffer::fill_status::ENDFILE) {
  63. return rearm::DISARM;
  64. }
  65. return rearm::REARM;
  66. });
  67. }
  68. ~subproc_buffer()
  69. {
  70. out_watch->deregister(loop);
  71. }
  72. // Fill buffer by reading from file descriptor. Note caller must set overflow marker
  73. // if the buffer becomes full and more data is available.
  74. fill_status fill(int fd)
  75. {
  76. int rem = get_free();
  77. if (rem == 0) {
  78. return fill_status::FULL;
  79. }
  80. int read = base::fill(fd, rem);
  81. if (read <= 0) {
  82. if (read == -1 && errno == EAGAIN) {
  83. return fill_status::OK;
  84. }
  85. return fill_status::ENDFILE;
  86. }
  87. out_watch->set_enabled(loop, true);
  88. return fill_status::OK;
  89. }
  90. // Append a message. If the message will not fit in the buffer, discard it and mark overflow.
  91. void append(const char *msg)
  92. {
  93. out_watch->set_enabled(loop, true);
  94. unsigned len = strlen(msg);
  95. if (subproc_bufsize - get_length() >= len) {
  96. base::append(msg, len);
  97. }
  98. else {
  99. mark_overflow();
  100. }
  101. }
  102. // Append the given buffer, which must fit in the remaining space in this buffer.
  103. void append(const char *buf, int len)
  104. {
  105. out_watch->set_enabled(loop, true);
  106. base::append(buf, len);
  107. }
  108. int get_free()
  109. {
  110. return base::get_free();
  111. }
  112. // Write buffer contents out to file descriptor. The descriptor is assumed to be non-blocking.
  113. // returns ENDFILE if there is no more content to flush (buffer is now empty) or OK otherwise.
  114. fill_status flush(int fd)
  115. {
  116. int to_write = get_contiguous_length(get_ptr(0));
  117. if (overflow_marker != -1) {
  118. if (overflow_marker == 0) {
  119. // output (remainder of) overflow message
  120. int l = std::strlen(overflow_msg_ptr);
  121. int r = write(fd, overflow_msg_ptr, l);
  122. if (r == l) {
  123. // entire message has been written; next marker is in buffer
  124. int16_t overflow_marker16;
  125. extract(reinterpret_cast<char *>(&overflow_marker16), 0, sizeof(overflow_marker16));
  126. overflow_marker = overflow_marker16;
  127. consume(sizeof(overflow_marker16));
  128. // no more overflow markers?
  129. if (overflow_marker == -1) {
  130. last_overflow = -1;
  131. }
  132. return get_length() == 0 ? fill_status::ENDFILE : fill_status::OK;
  133. }
  134. if (r > 0) {
  135. overflow_msg_ptr += r;
  136. }
  137. return fill_status::OK;
  138. }
  139. to_write = std::min(to_write, overflow_marker);
  140. }
  141. int r = write(fd, get_ptr(0), to_write);
  142. if (r > 0) {
  143. consume(r);
  144. if (overflow_marker != -1) {
  145. overflow_marker -= r;
  146. last_overflow -= r;
  147. if (overflow_marker == 0) {
  148. overflow_msg_ptr = output_lost_msg;
  149. }
  150. }
  151. }
  152. return get_length() == 0 ? fill_status::ENDFILE : fill_status::OK;
  153. }
  154. // Mark overflow occurred. Call this only when the buffer is full.
  155. // The marker is put after the most recent newline in the buffer, if possible, so that whole
  156. // lines are retained in the buffer. In some cases marking overflow will not add a new overflow
  157. // marker but simply trim the buffer to an existing marker.
  158. void mark_overflow()
  159. {
  160. // Try to find the last newline in the buffer
  161. int begin = 0;
  162. if (last_overflow != -1) {
  163. begin = last_overflow + sizeof(int16_t);
  164. }
  165. int end = get_length() - 1 - sizeof(int16_t); // -1, then -2 for storage of marker
  166. int i;
  167. for (i = end; i >= begin; i--) {
  168. if ((*this)[i] == '\n') break;
  169. }
  170. if (last_overflow != -1 && i < begin) {
  171. // No new line after existing marker: trim all beyond that marker, don't
  172. // create a new marker:
  173. trim_to(last_overflow + sizeof(uint16_t));
  174. return;
  175. }
  176. if (i < begin) {
  177. // No newline in the whole buffer... we'll put the overflow marker at the end,
  178. // on the assumption that it is better to output a partial line than it is to
  179. // discard the entire buffer:
  180. last_overflow = get_length() - sizeof(int16_t);
  181. overflow_marker = last_overflow;
  182. int16_t overflow16 = -1;
  183. char * overflow16_ptr = reinterpret_cast<char *>(&overflow16);
  184. *get_ptr(last_overflow + 0) = overflow16_ptr[0];
  185. *get_ptr(last_overflow + 1) = overflow16_ptr[1];
  186. return;
  187. }
  188. // We found a newline, put the overflow marker just after it:
  189. int new_overflow = i + 1;
  190. if (last_overflow != -1) {
  191. int16_t new_overflow16 = new_overflow;
  192. char * new_overflow16_ptr = reinterpret_cast<char *>(&new_overflow16);
  193. *get_ptr(last_overflow + 0) = new_overflow16_ptr[0];
  194. *get_ptr(last_overflow + 1) = new_overflow16_ptr[1];
  195. }
  196. last_overflow = new_overflow;
  197. if (overflow_marker == -1) {
  198. overflow_marker = last_overflow;
  199. }
  200. int16_t overflow16 = -1;
  201. char * overflow16_ptr = reinterpret_cast<char *>(&overflow16);
  202. *get_ptr(last_overflow + 0) = overflow16_ptr[0];
  203. *get_ptr(last_overflow + 0) = overflow16_ptr[1];
  204. trim_to(last_overflow + sizeof(int16_t));
  205. }
  206. };
  207. int main(int argc, char **argv)
  208. {
  209. using namespace std;
  210. bool show_help = false;
  211. bool sys_shutdown = false;
  212. bool use_passed_cfd = false;
  213. auto shutdown_type = shutdown_type_t::POWEROFF;
  214. const char *execname = base_name(argv[0]);
  215. if (strcmp(execname, "reboot") == 0) {
  216. shutdown_type = shutdown_type_t::REBOOT;
  217. }
  218. for (int i = 1; i < argc; i++) {
  219. if (argv[i][0] == '-') {
  220. if (strcmp(argv[i], "--help") == 0) {
  221. show_help = true;
  222. break;
  223. }
  224. if (strcmp(argv[i], "--system") == 0) {
  225. sys_shutdown = true;
  226. }
  227. else if (strcmp(argv[i], "-r") == 0) {
  228. shutdown_type = shutdown_type_t::REBOOT;
  229. }
  230. else if (strcmp(argv[i], "-h") == 0) {
  231. shutdown_type = shutdown_type_t::HALT;
  232. }
  233. else if (strcmp(argv[i], "-p") == 0) {
  234. shutdown_type = shutdown_type_t::POWEROFF;
  235. }
  236. else if (strcmp(argv[i], "--use-passed-cfd") == 0) {
  237. use_passed_cfd = true;
  238. }
  239. else {
  240. cerr << "Unrecognized command-line parameter: " << argv[i] << endl;
  241. return 1;
  242. }
  243. }
  244. else {
  245. // time argument? TODO
  246. show_help = true;
  247. }
  248. }
  249. if (show_help) {
  250. cout << execname << " : shutdown the system\n"
  251. " --help : show this help\n"
  252. " -r : reboot\n"
  253. " -h : halt system\n"
  254. " -p : power down (default)\n"
  255. " --use-passed-cfd : use the socket file descriptor identified by the DINIT_CS_FD\n"
  256. " environment variable to communicate with the init daemon.\n"
  257. " --system : perform shutdown immediately, instead of issuing shutdown\n"
  258. " command to the init program. Not recommended for use\n"
  259. " by users.\n";
  260. return 1;
  261. }
  262. if (sys_shutdown) {
  263. do_system_shutdown(shutdown_type);
  264. return 0;
  265. }
  266. signal(SIGPIPE, SIG_IGN);
  267. int socknum = -1;
  268. if (use_passed_cfd) {
  269. socknum = get_passed_cfd();
  270. if (socknum == -1) {
  271. use_passed_cfd = false;
  272. }
  273. }
  274. if (!use_passed_cfd) {
  275. socknum = socket(AF_UNIX, SOCK_STREAM, 0);
  276. if (socknum == -1) {
  277. perror("socket");
  278. return 1;
  279. }
  280. const char *naddr = SYSCONTROLSOCKET;
  281. struct sockaddr_un name;
  282. name.sun_family = AF_UNIX;
  283. strcpy(name.sun_path, naddr);
  284. int sunlen = offsetof(struct sockaddr_un, sun_path) + strlen(naddr) + 1; // family, (string), nul
  285. int connr = connect(socknum, (struct sockaddr *) &name, sunlen);
  286. if (connr == -1) {
  287. perror("connect");
  288. return 1;
  289. }
  290. }
  291. try {
  292. cpbuffer_t rbuffer;
  293. check_protocol_version(min_cp_version, max_cp_version, rbuffer, socknum);
  294. // Build buffer;
  295. constexpr int bufsize = 2;
  296. char buf[bufsize];
  297. buf[0] = (dinit_cptypes::cp_cmd_t)cp_cmd::SHUTDOWN;
  298. buf[1] = static_cast<char>(shutdown_type);
  299. cout << "Issuing shutdown command..." << endl;
  300. write_all_x(socknum, buf, bufsize);
  301. // Wait for ACK/NACK
  302. wait_for_reply(rbuffer, socknum);
  303. if (rbuffer[0] != (dinit_cptypes::cp_rply_t)cp_rply::ACK) {
  304. cerr << "shutdown: control socket protocol error" << endl;
  305. return 1;
  306. }
  307. }
  308. catch (cp_old_client_exception &e) {
  309. std::cerr << "shutdown: too old (server reports newer protocol version)" << std::endl;
  310. return 1;
  311. }
  312. catch (cp_old_server_exception &e) {
  313. std::cerr << "shutdown: server too old or protocol error" << std::endl;
  314. return 1;
  315. }
  316. catch (cp_read_exception &e) {
  317. cerr << "shutdown: control socket read failure or protocol error" << endl;
  318. return 1;
  319. }
  320. catch (cp_write_exception &e) {
  321. cerr << "shutdown: control socket write error: " << std::strerror(e.errcode) << endl;
  322. return 1;
  323. }
  324. while (true) {
  325. pause();
  326. }
  327. return 0;
  328. }
  329. // Actually shut down the system.
  330. void do_system_shutdown(shutdown_type_t shutdown_type)
  331. {
  332. using namespace std;
  333. // Mask all signals to prevent death of our parent etc from terminating us
  334. sigset_t allsigs;
  335. sigfillset(&allsigs);
  336. sigprocmask(SIG_SETMASK, &allsigs, nullptr);
  337. int reboot_type = RB_AUTOBOOT; // reboot
  338. #if defined(RB_POWER_OFF)
  339. if (shutdown_type == shutdown_type_t::POWEROFF) reboot_type = RB_POWER_OFF;
  340. #endif
  341. #if defined(RB_HALT_SYSTEM)
  342. if (shutdown_type == shutdown_type_t::HALT) reboot_type = RB_HALT_SYSTEM;
  343. #elif defined(RB_HALT)
  344. if (shutdown_type == shutdown_type_t::HALT) reboot_type = RB_HALT;
  345. #endif
  346. // Write to console rather than any terminal, since we lose the terminal it seems:
  347. int consfd = open("/dev/console", O_WRONLY);
  348. if (consfd != STDOUT_FILENO && consfd != -1) {
  349. dup2(consfd, STDOUT_FILENO);
  350. }
  351. loop_t loop;
  352. subproc_buffer sub_buf {loop, STDOUT_FILENO};
  353. sub_buf.append("Sending TERM/KILL to all processes...\n");
  354. // Send TERM/KILL to all (remaining) processes
  355. kill(-1, SIGTERM);
  356. // 1 second delay (while outputting from sub_buf):
  357. bool timeout_reached = false;
  358. dasynq::time_val timeout {1, 0};
  359. dasynq::time_val interval {0,0};
  360. loop_t::timer::add_timer(loop, clock_type::MONOTONIC, true /* relative */,
  361. timeout.get_timespec(), interval.get_timespec(),
  362. [&](loop_t &eloop, int expiry_count) -> rearm {
  363. timeout_reached = true;
  364. return rearm::REMOVE;
  365. });
  366. do {
  367. loop.run();
  368. } while (! timeout_reached);
  369. kill(-1, SIGKILL);
  370. // Attempt to execute shutdown hook at three possible locations:
  371. const char * const hook_paths[] = {
  372. "/etc/dinit/shutdown-hook",
  373. "/lib/dinit/shutdown-hook"
  374. };
  375. bool do_unmount_ourself = true;
  376. const int execmask = S_IXOTH | S_IXGRP | S_IXUSR;
  377. struct stat statbuf;
  378. for (size_t i = 0; i < sizeof(hook_paths) / sizeof(hook_paths[0]); ++i) {
  379. int stat_r = lstat(hook_paths[i], &statbuf);
  380. if (stat_r == 0 && (statbuf.st_mode & execmask) != 0) {
  381. sub_buf.append("Executing shutdown hook...\n");
  382. const char *prog_args[] = { hook_paths[i], nullptr };
  383. try {
  384. int r = run_process(prog_args, loop, sub_buf);
  385. if (r == 0) {
  386. do_unmount_ourself = false;
  387. }
  388. }
  389. catch (std::exception &e) {
  390. sub_buf.append("Couldn't fork for shutdown-hook: ");
  391. sub_buf.append(e.what());
  392. sub_buf.append("\n");
  393. }
  394. break;
  395. }
  396. }
  397. // perform shutdown
  398. if (do_unmount_ourself) {
  399. sub_buf.append("Turning off swap...\n");
  400. swap_off(loop, sub_buf);
  401. sub_buf.append("Unmounting disks...\n");
  402. unmount_disks(loop, sub_buf);
  403. }
  404. sync();
  405. sub_buf.append("Issuing shutdown via kernel...\n");
  406. loop.poll(); // give message a chance to get to console
  407. reboot(reboot_type);
  408. }
  409. // Watcher for subprocess output.
  410. class subproc_out_watch : public loop_t::fd_watcher_impl<subproc_out_watch>
  411. {
  412. subproc_buffer &sub_buf;
  413. bool in_overflow = false;
  414. rearm read_overflow(int fd)
  415. {
  416. char buf[128];
  417. int r = read(fd, buf, 128);
  418. if (r == 0 || (r == -1 && errno != EAGAIN)) {
  419. return rearm::NOOP; // leave disarmed
  420. }
  421. if (r == -1) {
  422. return rearm::REARM;
  423. }
  424. // How much space is available?
  425. int fr = sub_buf.get_free();
  426. for (int b = r - std::min(r, fr); b < r; b++) {
  427. if (buf[b] == '\n') {
  428. // Copy the (partial) line into sub_buf and leave overflow mode
  429. sub_buf.append(buf + b, r - b);
  430. in_overflow = false;
  431. }
  432. }
  433. return rearm::REARM;
  434. }
  435. public:
  436. subproc_out_watch(subproc_buffer &sub_buf_p) : sub_buf(sub_buf_p) {}
  437. rearm fd_event(loop_t &, int fd, int flags)
  438. {
  439. // if current status is reading overflow, read and discard until newline
  440. if (in_overflow) {
  441. return read_overflow(fd);
  442. }
  443. auto r = sub_buf.fill(fd);
  444. if (r == subproc_buffer::fill_status::FULL) {
  445. sub_buf.mark_overflow();
  446. in_overflow = true;
  447. return read_overflow(fd);
  448. }
  449. else if (r == subproc_buffer::fill_status::ENDFILE) {
  450. return rearm::NOOP;
  451. }
  452. return rearm::REARM; // re-enable watcher
  453. }
  454. };
  455. // Run process, put its output through the subprocess buffer
  456. // may throw: std::system_error, std::bad_alloc
  457. static int run_process(const char * prog_args[], loop_t &loop, subproc_buffer &sub_buf)
  458. {
  459. class sp_watcher_t : public loop_t::child_proc_watcher_impl<sp_watcher_t>
  460. {
  461. public:
  462. bool terminated = false;
  463. int exit_status;
  464. rearm status_change(loop_t &, pid_t child, int status)
  465. {
  466. terminated = true;
  467. exit_status = status;
  468. return rearm::REMOVE;
  469. }
  470. };
  471. sp_watcher_t sp_watcher;
  472. // Create output pipe
  473. bool have_pipe = true;
  474. int pipefds[2];
  475. if (dasynq::pipe2(pipefds, O_NONBLOCK) == -1) {
  476. sub_buf.append("Warning: ");
  477. sub_buf.append(prog_args[0]);
  478. sub_buf.append(": could not create pipe for subprocess output\n");
  479. have_pipe = false;
  480. // Note, we proceed and let the sub-process run with our stdout/stderr.
  481. }
  482. subproc_out_watch owatch {sub_buf};
  483. if (have_pipe) {
  484. try {
  485. owatch.add_watch(loop, pipefds[0], dasynq::IN_EVENTS);
  486. }
  487. catch (...) {
  488. // failed to create the watcher for the subprocess output; again, let it run with
  489. // our stdout/stderr
  490. sub_buf.append("Warning: could not create output watch for subprocess\n");
  491. close(pipefds[0]);
  492. close(pipefds[1]);
  493. have_pipe = false;
  494. }
  495. }
  496. // If we've buffered any messages/output, give them a chance to go out now:
  497. loop.poll();
  498. pid_t ch_pid = sp_watcher.fork(loop);
  499. if (ch_pid == 0) {
  500. // child
  501. // Dup output pipe to stdout, stderr
  502. if (have_pipe) {
  503. dup2(pipefds[1], STDOUT_FILENO);
  504. dup2(pipefds[1], STDERR_FILENO);
  505. close(pipefds[0]);
  506. close(pipefds[1]);
  507. }
  508. execv(prog_args[0], const_cast<char **>(prog_args));
  509. puts("Failed to execute subprocess: ");
  510. perror(prog_args[0]);
  511. _exit(1);
  512. }
  513. if (have_pipe) {
  514. close(pipefds[1]);
  515. }
  516. do {
  517. loop.run();
  518. } while (!sp_watcher.terminated);
  519. if (have_pipe) {
  520. owatch.deregister(loop);
  521. close(pipefds[0]);
  522. }
  523. return sp_watcher.exit_status;
  524. }
  525. static void unmount_disks(loop_t &loop, subproc_buffer &sub_buf)
  526. {
  527. try {
  528. const char * unmount_args[] = { "/bin/umount", "-a", "-r", nullptr };
  529. run_process(unmount_args, loop, sub_buf);
  530. }
  531. catch (std::exception &e) {
  532. sub_buf.append("Couldn't fork for umount: ");
  533. sub_buf.append(e.what());
  534. sub_buf.append("\n");
  535. }
  536. }
  537. static void swap_off(loop_t &loop, subproc_buffer &sub_buf)
  538. {
  539. try {
  540. const char * swapoff_args[] = { "/sbin/swapoff", "-a", nullptr };
  541. run_process(swapoff_args, loop, sub_buf);
  542. }
  543. catch (std::exception &e) {
  544. sub_buf.append("Couldn't fork for swapoff: ");
  545. sub_buf.append(e.what());
  546. sub_buf.append("\n");
  547. }
  548. }