klishd.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #define _GNU_SOURCE
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <assert.h>
  7. #include <signal.h>
  8. #include <syslog.h>
  9. #include <unistd.h>
  10. #include <errno.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14. #include <sys/socket.h>
  15. #include <sys/un.h>
  16. #include <sys/fsuid.h>
  17. #include <sys/wait.h>
  18. #include <poll.h>
  19. #include <time.h>
  20. #include <faux/faux.h>
  21. #include <faux/str.h>
  22. #include <faux/ini.h>
  23. #include <faux/log.h>
  24. #include <faux/sched.h>
  25. #include <faux/sysdb.h>
  26. #include <faux/net.h>
  27. #include <faux/list.h>
  28. #include <faux/conv.h>
  29. #include <faux/file.h>
  30. #include <klish/ktp.h>
  31. #include <klish/ktp_session.h>
  32. #include "private.h"
  33. // Signal handlers
  34. static volatile int sigterm = 0; // Exit if 1
  35. static void sighandler(int signo);
  36. static volatile int sighup = 0; // Re-read config file
  37. static void sighup_handler(int signo);
  38. static volatile int sigchld = 0; // Child execution is finished
  39. static void sigchld_handler(int signo);
  40. // Network
  41. static int create_listen_unix_sock(const char *path);
  42. /** @brief Main function
  43. */
  44. int main(int argc, char **argv)
  45. {
  46. int retval = -1;
  47. struct options *opts = NULL;
  48. int pidfd = -1;
  49. int logoptions = 0;
  50. // Network
  51. int listen_unix_sock = -1;
  52. faux_pollfd_t *fds = NULL;
  53. // Event scheduler
  54. faux_sched_t *sched = NULL;
  55. // Signal vars
  56. struct sigaction sig_act = {};
  57. sigset_t sig_set = {};
  58. sigset_t orig_sig_set = {}; // Saved signal mask
  59. // Parse command line options
  60. opts = opts_init();
  61. if (opts_parse(argc, argv, opts))
  62. goto err;
  63. // Initialize syslog
  64. logoptions = LOG_CONS;
  65. if (opts->foreground)
  66. logoptions |= LOG_PERROR;
  67. openlog(LOG_NAME, logoptions, opts->log_facility);
  68. if (!opts->verbose)
  69. setlogmask(LOG_UPTO(LOG_INFO));
  70. // Parse config file
  71. syslog(LOG_DEBUG, "Parse config file: %s\n", opts->cfgfile);
  72. if (!access(opts->cfgfile, R_OK)) {
  73. if (config_parse(opts->cfgfile, opts))
  74. goto err;
  75. } else if (opts->cfgfile_userdefined) {
  76. // User defined config must be found
  77. fprintf(stderr, "Error: Can't find config file %s\n",
  78. opts->cfgfile);
  79. goto err;
  80. }
  81. // DEBUG: Show options
  82. opts_show(opts);
  83. syslog(LOG_INFO, "Start daemon.\n");
  84. // Fork the daemon
  85. if (!opts->foreground) {
  86. // Daemonize
  87. syslog(LOG_DEBUG, "Daemonize\n");
  88. if (daemon(0, 0) < 0) {
  89. syslog(LOG_ERR, "Can't daemonize\n");
  90. goto err;
  91. }
  92. // Write pidfile
  93. syslog(LOG_DEBUG, "Write PID file: %s\n", opts->pidfile);
  94. if ((pidfd = open(opts->pidfile,
  95. O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
  96. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
  97. syslog(LOG_WARNING, "Can't open pidfile %s: %s\n",
  98. opts->pidfile, strerror(errno));
  99. } else {
  100. char str[20];
  101. snprintf(str, sizeof(str), "%u\n", getpid());
  102. str[sizeof(str) - 1] = '\0';
  103. if (write(pidfd, str, strlen(str)) < 0)
  104. syslog(LOG_WARNING, "Can't write to %s: %s\n",
  105. opts->pidfile, strerror(errno));
  106. close(pidfd);
  107. }
  108. }
  109. // Network initialization
  110. syslog(LOG_DEBUG, "Create listen UNIX socket: %s\n", opts->unix_socket_path);
  111. listen_unix_sock = create_listen_unix_sock(opts->unix_socket_path);
  112. if (listen_unix_sock < 0)
  113. goto err;
  114. // Set signal handler
  115. syslog(LOG_DEBUG, "Set signal handlers\n");
  116. sigemptyset(&sig_set);
  117. sigaddset(&sig_set, SIGTERM);
  118. sigaddset(&sig_set, SIGINT);
  119. sigaddset(&sig_set, SIGQUIT);
  120. sig_act.sa_flags = 0;
  121. sig_act.sa_mask = sig_set;
  122. sig_act.sa_handler = &sighandler;
  123. sigaction(SIGTERM, &sig_act, NULL);
  124. sigaction(SIGINT, &sig_act, NULL);
  125. sigaction(SIGQUIT, &sig_act, NULL);
  126. // SIGHUP handler
  127. sigemptyset(&sig_set);
  128. sigaddset(&sig_set, SIGHUP);
  129. sig_act.sa_flags = 0;
  130. sig_act.sa_mask = sig_set;
  131. sig_act.sa_handler = &sighup_handler;
  132. sigaction(SIGHUP, &sig_act, NULL);
  133. // SIGCHLD handler
  134. sigemptyset(&sig_set);
  135. sigaddset(&sig_set, SIGCHLD);
  136. sig_act.sa_flags = 0;
  137. sig_act.sa_mask = sig_set;
  138. sig_act.sa_handler = &sigchld_handler;
  139. sigaction(SIGCHLD, &sig_act, NULL);
  140. // Initialize event scheduler
  141. sched = faux_sched_new();
  142. if (!sched) {
  143. syslog(LOG_ERR, "Can't init event scheduler");
  144. goto err;
  145. }
  146. // The struct pollfd vector for ppoll()
  147. fds = faux_pollfd_new();
  148. if (!fds) {
  149. syslog(LOG_ERR, "Can't init pollfd vector");
  150. goto err;
  151. }
  152. // Add listen UNIX socket to pollfds vector
  153. faux_pollfd_add(fds, listen_unix_sock, POLLIN);
  154. syslog(LOG_DEBUG, "Listen socket %d", listen_unix_sock);
  155. // Block signals to prevent race conditions while loop and ppoll()
  156. // Catch signals while ppoll() only
  157. sigemptyset(&sig_set);
  158. sigaddset(&sig_set, SIGTERM);
  159. sigaddset(&sig_set, SIGINT);
  160. sigaddset(&sig_set, SIGQUIT);
  161. sigaddset(&sig_set, SIGHUP);
  162. sigaddset(&sig_set, SIGCHLD);
  163. sigprocmask(SIG_BLOCK, &sig_set, &orig_sig_set);
  164. // Main loop
  165. while (!sigterm) {
  166. int sn = 0;
  167. struct timespec *timeout = NULL;
  168. struct timespec next_interval = {};
  169. faux_pollfd_iterator_t pollfd_iter;
  170. struct pollfd *pollfd = NULL;
  171. pid_t pid = -1;
  172. // Re-read config file on SIGHUP
  173. if (sighup) {
  174. if (access(opts->cfgfile, R_OK) == 0) {
  175. syslog(LOG_INFO, "Re-reading config file \"%s\"\n", opts->cfgfile);
  176. if (config_parse(opts->cfgfile, opts) < 0)
  177. syslog(LOG_ERR, "Error while config file parsing.\n");
  178. } else if (opts->cfgfile_userdefined) {
  179. syslog(LOG_ERR, "Can't find config file \"%s\"\n", opts->cfgfile);
  180. }
  181. sighup = 0;
  182. }
  183. // Non-blocking wait for all children
  184. while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) {
  185. syslog(LOG_DEBUG, "Exit child process %d\n", pid);
  186. }
  187. sigchld = 0;
  188. // Find out timeout interval
  189. if (faux_sched_next_interval(sched, &next_interval) < 0) {
  190. timeout = NULL;
  191. } else {
  192. timeout = &next_interval;
  193. syslog(LOG_DEBUG, "Next interval: %ld\n", timeout->tv_sec);
  194. }
  195. // Wait for events
  196. sn = ppoll(faux_pollfd_vector(fds), faux_pollfd_len(fds), timeout, &orig_sig_set);
  197. if (sn < 0) {
  198. if ((EAGAIN == errno) || (EINTR == errno))
  199. continue;
  200. syslog(LOG_ERR, "Error while select(): %s\n", strerror(errno));
  201. break;
  202. }
  203. // Timeout (Scheduled event)
  204. if (0 == sn) {
  205. int id = 0; // Event idenftifier
  206. void *data = NULL; // Event data
  207. syslog(LOG_DEBUG, "Timeout\n");
  208. // Some scheduled events
  209. while(faux_sched_pop(sched, &id, &data) == 0) {
  210. syslog(LOG_DEBUG, "sched: Update event\n");
  211. }
  212. continue;
  213. }
  214. // Get data via socket
  215. faux_pollfd_init_iterator(fds, &pollfd_iter);
  216. while ((pollfd = faux_pollfd_each_active(fds, &pollfd_iter))) {
  217. int fd = pollfd->fd;
  218. // Listen socket
  219. if (fd == listen_unix_sock) {
  220. int new_conn = -1;
  221. new_conn = accept(listen_unix_sock, NULL, NULL);
  222. if (new_conn < 0)
  223. continue;
  224. faux_pollfd_add(fds, new_conn, POLLIN);
  225. syslog(LOG_DEBUG, "New connection %d\n", new_conn);
  226. continue;
  227. }
  228. // If it's not a listen socket then we have received
  229. // a message from client.
  230. syslog(LOG_DEBUG, "Client %d\n", fd);
  231. // Receive message
  232. // Check for closed connection. Do it after reading from
  233. // socket because buffer of disconnected socket can
  234. // still contain data.
  235. if (pollfd->revents & POLLHUP) {
  236. syslog(LOG_DEBUG, "Close connection %d\n", fd);
  237. ktp_disconnect(fd);
  238. faux_pollfd_del_by_fd(fds, fd);
  239. }
  240. }
  241. } // Main loop end
  242. retval = 0;
  243. err:
  244. syslog(LOG_DEBUG, "Cleanup.\n");
  245. sigprocmask(SIG_BLOCK, &orig_sig_set, NULL);
  246. faux_pollfd_free(fds);
  247. faux_sched_free(sched);
  248. // Close listen socket
  249. if (listen_unix_sock >= 0)
  250. close(listen_unix_sock);
  251. // Remove pidfile
  252. if (pidfd >= 0) {
  253. if (unlink(opts->pidfile) < 0) {
  254. syslog(LOG_ERR, "Can't remove pid-file %s: %s\n",
  255. opts->pidfile, strerror(errno));
  256. }
  257. }
  258. // Free command line options
  259. opts_free(opts);
  260. syslog(LOG_INFO, "Stop daemon.\n");
  261. return retval;
  262. }
  263. /** @brief Create listen socket
  264. *
  265. * Previously removes old socket's file from filesystem. Note daemon must check
  266. * for already working daemon to don't duplicate.
  267. *
  268. * @param [in] path Socket path within filesystem.
  269. * @return Socket descriptor of < 0 on error.
  270. */
  271. static int create_listen_unix_sock(const char *path)
  272. {
  273. int sock = -1;
  274. int opt = 1;
  275. struct sockaddr_un laddr = {};
  276. assert(path);
  277. if (!path)
  278. return -1;
  279. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  280. syslog(LOG_ERR, "Can't create socket: %s\n", strerror(errno));
  281. goto err;
  282. }
  283. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
  284. syslog(LOG_ERR, "Can't set socket options: %s\n", strerror(errno));
  285. goto err;
  286. }
  287. // Remove old (lost) socket's file
  288. unlink(path);
  289. laddr.sun_family = AF_UNIX;
  290. strncpy(laddr.sun_path, path, USOCK_PATH_MAX);
  291. laddr.sun_path[USOCK_PATH_MAX - 1] = '\0';
  292. if (bind(sock, (struct sockaddr *)&laddr, sizeof(laddr))) {
  293. syslog(LOG_ERR, "Can't bind socket %s: %s\n", path, strerror(errno));
  294. goto err;
  295. }
  296. if (listen(sock, 128)) {
  297. unlink(path);
  298. syslog(LOG_ERR, "Can't listen on socket %s: %s\n", path, strerror(errno));
  299. goto err;
  300. }
  301. return sock;
  302. err:
  303. if (sock >= 0)
  304. close(sock);
  305. return -1;
  306. }
  307. /** @brief Signal handler for temination signals (like SIGTERM, SIGINT, ...)
  308. */
  309. static void sighandler(int signo)
  310. {
  311. sigterm = 1;
  312. signo = signo; // Happy compiler
  313. }
  314. /** @brief Re-read config file on SIGHUP
  315. */
  316. static void sighup_handler(int signo)
  317. {
  318. sighup = 1;
  319. signo = signo; // Happy compiler
  320. }
  321. /** @brief Child was finished
  322. */
  323. static void sigchld_handler(int signo)
  324. {
  325. sigchld = 1;
  326. signo = signo; // Happy compiler
  327. }