klishd.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. // Block signals to prevent race conditions while loop and ppoll()
  155. // Catch signals while ppoll() only
  156. sigemptyset(&sig_set);
  157. sigaddset(&sig_set, SIGTERM);
  158. sigaddset(&sig_set, SIGINT);
  159. sigaddset(&sig_set, SIGQUIT);
  160. sigaddset(&sig_set, SIGHUP);
  161. sigaddset(&sig_set, SIGCHLD);
  162. sigprocmask(SIG_BLOCK, &sig_set, &orig_sig_set);
  163. // Main loop
  164. while (!sigterm) {
  165. int sn = 0;
  166. struct timespec *timeout = NULL;
  167. struct timespec next_interval = {};
  168. faux_pollfd_iterator_t pollfd_iter;
  169. struct pollfd *pollfd = NULL;
  170. pid_t pid = -1;
  171. // Re-read config file on SIGHUP
  172. if (sighup) {
  173. if (access(opts->cfgfile, R_OK) == 0) {
  174. syslog(LOG_INFO, "Re-reading config file \"%s\"\n", opts->cfgfile);
  175. if (config_parse(opts->cfgfile, opts) < 0)
  176. syslog(LOG_ERR, "Error while config file parsing.\n");
  177. } else if (opts->cfgfile_userdefined) {
  178. syslog(LOG_ERR, "Can't find config file \"%s\"\n", opts->cfgfile);
  179. }
  180. sighup = 0;
  181. }
  182. // Non-blocking wait for all children
  183. while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) {
  184. syslog(LOG_DEBUG, "Exit child process %d\n", pid);
  185. }
  186. sigchld = 0;
  187. // Find out timeout interval
  188. if (faux_sched_next_interval(sched, &next_interval) < 0) {
  189. timeout = NULL;
  190. } else {
  191. timeout = &next_interval;
  192. syslog(LOG_DEBUG, "Next interval: %ld\n", timeout->tv_sec);
  193. }
  194. // Wait for events
  195. sn = ppoll(faux_pollfd_vector(fds), faux_pollfd_len(fds), timeout, &orig_sig_set);
  196. if (sn < 0) {
  197. if ((EAGAIN == errno) || (EINTR == errno))
  198. continue;
  199. syslog(LOG_ERR, "Error while select(): %s\n", strerror(errno));
  200. break;
  201. }
  202. // Timeout (Scheduled event)
  203. if (0 == sn) {
  204. int id = 0; // Event idenftifier
  205. void *data = NULL; // Event data
  206. // Some scheduled events
  207. while(faux_sched_pop(sched, &id, &data) == 0) {
  208. syslog(LOG_DEBUG, "sched: Update event\n");
  209. }
  210. continue;
  211. }
  212. // Get data via socket
  213. faux_pollfd_init_iterator(fds, &pollfd_iter);
  214. while ((pollfd = faux_pollfd_each_active(fds, &pollfd_iter))) {
  215. int fd = pollfd->fd;
  216. // Listen socket
  217. if (fd == listen_unix_sock) {
  218. int new_conn = -1;
  219. new_conn = accept(listen_unix_sock, NULL, NULL);
  220. if (new_conn < 0)
  221. continue;
  222. faux_pollfd_add(fds, new_conn, POLLIN);
  223. syslog(LOG_DEBUG, "New connection %d\n", new_conn);
  224. continue;
  225. }
  226. // If it's not a listen socket then we have received
  227. // a message from client.
  228. }
  229. } // Main loop end
  230. retval = 0;
  231. err:
  232. syslog(LOG_DEBUG, "Cleanup.\n");
  233. sigprocmask(SIG_BLOCK, &orig_sig_set, NULL);
  234. faux_pollfd_free(fds);
  235. faux_sched_free(sched);
  236. // Close listen socket
  237. if (listen_unix_sock >= 0)
  238. close(listen_unix_sock);
  239. // Remove pidfile
  240. if (pidfd >= 0) {
  241. if (unlink(opts->pidfile) < 0) {
  242. syslog(LOG_ERR, "Can't remove pid-file %s: %s\n",
  243. opts->pidfile, strerror(errno));
  244. }
  245. }
  246. // Free command line options
  247. opts_free(opts);
  248. syslog(LOG_INFO, "Stop daemon.\n");
  249. return retval;
  250. }
  251. /** @brief Create listen socket
  252. *
  253. * Previously removes old socket's file from filesystem. Note daemon must check
  254. * for already working daemon to don't duplicate.
  255. *
  256. * @param [in] path Socket path within filesystem.
  257. * @return Socket descriptor of < 0 on error.
  258. */
  259. static int create_listen_unix_sock(const char *path)
  260. {
  261. int sock = -1;
  262. int opt = 1;
  263. struct sockaddr_un laddr = {};
  264. assert(path);
  265. if (!path)
  266. return -1;
  267. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  268. syslog(LOG_ERR, "Can't create socket: %s\n", strerror(errno));
  269. goto err;
  270. }
  271. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
  272. syslog(LOG_ERR, "Can't set socket options: %s\n", strerror(errno));
  273. goto err;
  274. }
  275. // Remove old (lost) socket's file
  276. unlink(path);
  277. laddr.sun_family = AF_UNIX;
  278. strncpy(laddr.sun_path, path, USOCK_PATH_MAX);
  279. laddr.sun_path[USOCK_PATH_MAX - 1] = '\0';
  280. if (bind(sock, (struct sockaddr *)&laddr, sizeof(laddr))) {
  281. syslog(LOG_ERR, "Can't bind socket %s: %s\n", path, strerror(errno));
  282. goto err;
  283. }
  284. if (listen(sock, 128)) {
  285. unlink(path);
  286. syslog(LOG_ERR, "Can't listen on socket %s: %s\n", path, strerror(errno));
  287. goto err;
  288. }
  289. return sock;
  290. err:
  291. if (sock >= 0)
  292. close(sock);
  293. return -1;
  294. }
  295. /** @brief Signal handler for temination signals (like SIGTERM, SIGINT, ...)
  296. */
  297. static void sighandler(int signo)
  298. {
  299. sigterm = 1;
  300. signo = signo; // Happy compiler
  301. }
  302. /** @brief Re-read config file on SIGHUP
  303. */
  304. static void sighup_handler(int signo)
  305. {
  306. sighup = 1;
  307. signo = signo; // Happy compiler
  308. }
  309. /** @brief Child was finished
  310. */
  311. static void sigchld_handler(int signo)
  312. {
  313. sigchld = 1;
  314. signo = signo; // Happy compiler
  315. }