klishd.c 10 KB

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