klishd.c 12 KB

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