shutdown.cc 19 KB

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