klishd.c 11 KB

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