2
0

shutdown.cc 20 KB

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