klishd.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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/argv.h>
  23. #include <faux/ini.h>
  24. #include <faux/log.h>
  25. #include <faux/sched.h>
  26. #include <faux/sysdb.h>
  27. #include <faux/net.h>
  28. #include <faux/list.h>
  29. #include <faux/conv.h>
  30. #include <faux/file.h>
  31. #include <faux/eloop.h>
  32. #include <faux/error.h>
  33. #include <klish/ktp.h>
  34. #include <klish/ktp_session.h>
  35. #include <klish/kscheme.h>
  36. #include <klish/ischeme.h>
  37. #include <klish/kcontext.h>
  38. #include <klish/ksession.h>
  39. #include <klish/kdb.h>
  40. #include <klish/kpargv.h>
  41. #include "private.h"
  42. // Local static functions
  43. bool_t daemonize(const char *pidfile);
  44. bool_t kentry_entrys_is_empty(const kentry_t *entry);
  45. static int create_listen_unix_sock(const char *path);
  46. static kscheme_t *load_all_dbs(const char *dbs,
  47. faux_ini_t *global_config, faux_error_t *error);
  48. static bool_t clear_scheme(kscheme_t *scheme, faux_error_t *error);
  49. // Main loop events
  50. static bool_t stop_loop_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  51. void *associated_data, void *user_data);
  52. static bool_t refresh_config_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  53. void *associated_data, void *user_data);
  54. static bool_t listen_socket_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  55. void *associated_data, void *user_data);
  56. static bool_t wait_for_child_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  57. void *associated_data, void *user_data);
  58. static bool_t wait_for_actions_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  59. void *associated_data, void *user_data);
  60. /** @brief Main function
  61. */
  62. int main(int argc, char **argv)
  63. {
  64. int retval = -1;
  65. struct options *opts = NULL;
  66. int pidfd = -1;
  67. int logoptions = 0;
  68. faux_eloop_t *eloop = NULL;
  69. int listen_unix_sock = -1;
  70. ktpd_session_t *ktpd_session = NULL;
  71. kscheme_t *scheme = NULL;
  72. faux_error_t *error = faux_error_new();
  73. faux_ini_t *config = NULL;
  74. int client_fd = -1;
  75. // Parse command line options
  76. opts = opts_init();
  77. if (opts_parse(argc, argv, opts))
  78. goto err;
  79. // Initialize syslog
  80. logoptions = LOG_CONS;
  81. if (opts->foreground)
  82. logoptions |= LOG_PERROR;
  83. openlog(LOG_NAME, logoptions, opts->log_facility);
  84. if (!opts->verbose)
  85. setlogmask(LOG_UPTO(LOG_INFO));
  86. // Parse config file
  87. syslog(LOG_DEBUG, "Parse config file: %s\n", opts->cfgfile);
  88. if (!access(opts->cfgfile, R_OK)) {
  89. if (!(config = config_parse(opts->cfgfile, opts)))
  90. goto err;
  91. } else if (opts->cfgfile_userdefined) {
  92. // User defined config must be found
  93. fprintf(stderr, "Error: Can't find config file %s\n",
  94. opts->cfgfile);
  95. goto err;
  96. }
  97. // DEBUG: Show options
  98. opts_show(opts);
  99. syslog(LOG_INFO, "Start daemon.\n");
  100. // Fork the daemon if needed
  101. if (!opts->foreground && !daemonize(opts->pidfile))
  102. goto err;
  103. // Load scheme
  104. if (!(scheme = load_all_dbs(opts->dbs, config, error))) {
  105. fprintf(stderr, "Scheme errors:\n");
  106. goto err;
  107. }
  108. // Listen socket
  109. syslog(LOG_DEBUG, "Create listen UNIX socket: %s\n", opts->unix_socket_path);
  110. listen_unix_sock = create_listen_unix_sock(opts->unix_socket_path);
  111. if (listen_unix_sock < 0)
  112. goto err;
  113. syslog(LOG_DEBUG, "Listen socket %d", listen_unix_sock);
  114. // Event loop
  115. eloop = faux_eloop_new(NULL);
  116. // Signals
  117. faux_eloop_add_signal(eloop, SIGINT, stop_loop_ev, NULL);
  118. faux_eloop_add_signal(eloop, SIGTERM, stop_loop_ev, NULL);
  119. faux_eloop_add_signal(eloop, SIGQUIT, stop_loop_ev, NULL);
  120. faux_eloop_add_signal(eloop, SIGHUP, refresh_config_ev, opts);
  121. faux_eloop_add_signal(eloop, SIGCHLD, wait_for_child_ev, NULL);
  122. // Listen socket. Waiting for new connections
  123. faux_eloop_add_fd(eloop, listen_unix_sock, POLLIN,
  124. listen_socket_ev, &client_fd);
  125. // Scheduled events
  126. // faux_eloop_add_sched_once_delayed(eloop, &delayed, 1, sched_once, NULL);
  127. // faux_eloop_add_sched_periodic_delayed(eloop, 2, sched_periodic, NULL, &period, FAUX_SCHED_INFINITE);
  128. // Main loop
  129. faux_eloop_loop(eloop);
  130. faux_eloop_free(eloop);
  131. retval = 0;
  132. err: // For listen daemon
  133. // Print errors
  134. if (faux_error_len(error) > 0)
  135. faux_error_show(error);
  136. faux_error_free(error);
  137. // Close listen socket
  138. if (listen_unix_sock >= 0)
  139. close(listen_unix_sock);
  140. // Finish listen daemon if it's not forked service process.
  141. if (client_fd < 0) {
  142. // Free scheme
  143. clear_scheme(scheme, error);
  144. // Free command line options
  145. opts_free(opts);
  146. faux_ini_free(config);
  147. // Remove pidfile
  148. if (pidfd >= 0) {
  149. if (unlink(opts->pidfile) < 0) {
  150. syslog(LOG_ERR, "Can't remove pid-file %s: %s\n",
  151. opts->pidfile, strerror(errno));
  152. }
  153. }
  154. syslog(LOG_INFO, "Stop daemon.\n");
  155. return retval;
  156. }
  157. // ATTENTION: It's a forked service process
  158. retval = -1; // Pessimism for service process
  159. eloop = NULL;
  160. // Re-Initialize syslog
  161. openlog(LOG_SERVICE_NAME, logoptions, opts->log_facility);
  162. if (!opts->verbose)
  163. setlogmask(LOG_UPTO(LOG_INFO));
  164. // Create event loop
  165. eloop = faux_eloop_new(NULL);
  166. // Create KTP session
  167. // Function ktpd_session_new() will add new events to eloop itself.
  168. ktpd_session = ktpd_session_new(client_fd, scheme, NULL, eloop);
  169. assert(ktpd_session);
  170. if (!ktpd_session) {
  171. syslog(LOG_ERR, "Can't create KTPd session\n");
  172. close(client_fd);
  173. goto err_client;
  174. }
  175. syslog(LOG_DEBUG, "New connection %d\n", client_fd);
  176. // Signals
  177. faux_eloop_add_signal(eloop, SIGINT, stop_loop_ev, NULL);
  178. faux_eloop_add_signal(eloop, SIGTERM, stop_loop_ev, NULL);
  179. faux_eloop_add_signal(eloop, SIGQUIT, stop_loop_ev, NULL);
  180. // Theoretically eloop can use SIGCHLD for different child processes but
  181. // not only for single ktpd_session's ACTIONs so it's not goot to grab
  182. // whole SIGCHLD event handler by ktpd_session object.
  183. faux_eloop_add_signal(eloop, SIGCHLD, wait_for_actions_ev, ktpd_session);
  184. // Main service loop
  185. faux_eloop_loop(eloop);
  186. retval = 0;
  187. err_client:
  188. ktpd_session_free(ktpd_session);
  189. faux_eloop_free(eloop);
  190. // Free scheme
  191. clear_scheme(scheme, error);
  192. // Free command line options
  193. opts_free(opts);
  194. faux_ini_free(config);
  195. return retval;
  196. }
  197. bool_t daemonize(const char *pidfile)
  198. {
  199. int pidfd = -1;
  200. // Daemonize
  201. syslog(LOG_DEBUG, "Daemonize\n");
  202. if (daemon(0, 0) < 0) {
  203. syslog(LOG_ERR, "Can't daemonize\n");
  204. return BOOL_FALSE;
  205. }
  206. // Write pidfile
  207. syslog(LOG_DEBUG, "Write PID file: %s\n", pidfile);
  208. if ((pidfd = open(pidfile,
  209. O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
  210. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
  211. syslog(LOG_WARNING, "Can't open pidfile %s: %s\n",
  212. pidfile, strerror(errno));
  213. } else {
  214. char str[20];
  215. snprintf(str, sizeof(str), "%u\n", getpid());
  216. str[sizeof(str) - 1] = '\0';
  217. if (write(pidfd, str, strlen(str)) < 0)
  218. syslog(LOG_WARNING, "Can't write to %s: %s\n",
  219. pidfile, strerror(errno));
  220. close(pidfd);
  221. }
  222. return BOOL_TRUE;
  223. }
  224. static bool_t load_db(kscheme_t *scheme, const char *db_name,
  225. faux_ini_t *config, faux_error_t *error)
  226. {
  227. kdb_t *db = NULL;
  228. const char *sofile = NULL;
  229. assert(scheme);
  230. if (!scheme)
  231. return BOOL_FALSE;
  232. assert(db_name);
  233. if (!db_name)
  234. return BOOL_FALSE;
  235. // DB.libxml2.so = <so filename>
  236. if (config)
  237. sofile = faux_ini_find(config, "so");
  238. db = kdb_new(db_name, sofile);
  239. assert(db);
  240. if (!db)
  241. return BOOL_FALSE;
  242. kdb_set_ini(db, config);
  243. kdb_set_error(db, error);
  244. // Load DB plugin
  245. if (!kdb_load_plugin(db)) {
  246. faux_error_sprintf(error,
  247. "DB \"%s\": Can't load DB plugin", db_name);
  248. kdb_free(db);
  249. return BOOL_FALSE;
  250. }
  251. // Check plugin API version
  252. if ((kdb_major(db) != KDB_MAJOR) ||
  253. (kdb_minor(db) != KDB_MINOR)) {
  254. faux_error_sprintf(error,
  255. "DB \"%s\": Plugin's API version is %u.%u, need %u.%u",
  256. db_name,
  257. kdb_major(db), kdb_minor(db),
  258. KDB_MAJOR, KDB_MINOR);
  259. kdb_free(db);
  260. return BOOL_FALSE;
  261. }
  262. // Init plugin
  263. if (kdb_has_init_fn(db) && !kdb_init(db)) {
  264. faux_error_sprintf(error,
  265. "DB \"%s\": Can't init DB plugin", db_name);
  266. kdb_free(db);
  267. return BOOL_FALSE;
  268. }
  269. // Load scheme
  270. if (!kdb_has_load_fn(db) || !kdb_load_scheme(db, scheme)) {
  271. faux_error_sprintf(error,
  272. "DB \"%s\": Can't load scheme from DB plugin", db_name);
  273. kdb_fini(db);
  274. kdb_free(db);
  275. return BOOL_FALSE;
  276. }
  277. // Fini plugin
  278. if (kdb_has_fini_fn(db) && !kdb_fini(db)) {
  279. faux_error_sprintf(error,
  280. "DB \"%s\": Can't fini DB plugin", db_name);
  281. kdb_free(db);
  282. return BOOL_FALSE;
  283. }
  284. kdb_free(db);
  285. return BOOL_TRUE;
  286. }
  287. static kscheme_t *load_all_dbs(const char *dbs,
  288. faux_ini_t *global_config, faux_error_t *error)
  289. {
  290. kscheme_t *scheme = NULL;
  291. faux_argv_t *dbs_argv = NULL;
  292. faux_argv_node_t *iter = NULL;
  293. const char *db_name = NULL;
  294. bool_t retcode = BOOL_TRUE;
  295. kcontext_t *context = NULL;
  296. assert(dbs);
  297. if (!dbs)
  298. return NULL;
  299. scheme = kscheme_new();
  300. assert(scheme);
  301. if (!scheme)
  302. return NULL;
  303. dbs_argv = faux_argv_new();
  304. assert(dbs_argv);
  305. if (!dbs_argv) {
  306. kscheme_free(scheme);
  307. return NULL;
  308. }
  309. if (faux_argv_parse(dbs_argv, dbs) <= 0) {
  310. kscheme_free(scheme);
  311. faux_argv_free(dbs_argv);
  312. return NULL;
  313. }
  314. // For each DB
  315. iter = faux_argv_iter(dbs_argv);
  316. while ((db_name = faux_argv_each(&iter))) {
  317. faux_ini_t *config = NULL; // Sub-config for current DB
  318. char *prefix = NULL;
  319. prefix = faux_str_mcat(&prefix, "DB.", db_name, ".", NULL);
  320. if (config)
  321. config = faux_ini_extract_subini(global_config, prefix);
  322. if (!load_db(scheme, db_name, config, error))
  323. retcode = BOOL_FALSE;
  324. faux_ini_free(config);
  325. faux_str_free(prefix);
  326. }
  327. faux_argv_free(dbs_argv);
  328. // Something went wrong while loading DBs
  329. if (!retcode) {
  330. kscheme_free(scheme);
  331. return NULL;
  332. }
  333. // Prepare scheme
  334. context = kcontext_new(KCONTEXT_PLUGIN_INIT);
  335. retcode = kscheme_prepare(scheme, context, error);
  336. kcontext_free(context);
  337. if (!retcode) {
  338. kscheme_free(scheme);
  339. faux_error_sprintf(error, "Scheme preparing errors.\n");
  340. return NULL;
  341. }
  342. /*
  343. // Debug
  344. {
  345. kdb_t *deploy_db = NULL;
  346. // Deploy (for testing purposes)
  347. deploy_db = kdb_new("ischeme", NULL);
  348. kdb_load_plugin(deploy_db);
  349. kdb_init(deploy_db);
  350. kdb_deploy_scheme(deploy_db, scheme);
  351. kdb_fini(deploy_db);
  352. kdb_free(deploy_db);
  353. }
  354. */
  355. return scheme;
  356. }
  357. static bool_t clear_scheme(kscheme_t *scheme, faux_error_t *error)
  358. {
  359. kcontext_t *context = NULL;
  360. if (!scheme)
  361. return BOOL_TRUE; // It's not an error
  362. context = kcontext_new(KCONTEXT_PLUGIN_FINI);
  363. kscheme_fini(scheme, context, error);
  364. kcontext_free(context);
  365. kscheme_free(scheme);
  366. return BOOL_TRUE;
  367. }
  368. /** @brief Create listen socket
  369. *
  370. * Previously removes old socket's file from filesystem. Note daemon must check
  371. * for already working daemon to don't duplicate.
  372. *
  373. * @param [in] path Socket path within filesystem.
  374. * @return Socket descriptor of < 0 on error.
  375. */
  376. static int create_listen_unix_sock(const char *path)
  377. {
  378. int sock = -1;
  379. int opt = 1;
  380. struct sockaddr_un laddr = {};
  381. assert(path);
  382. if (!path)
  383. return -1;
  384. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  385. syslog(LOG_ERR, "Can't create socket: %s\n", strerror(errno));
  386. goto err;
  387. }
  388. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
  389. syslog(LOG_ERR, "Can't set socket options: %s\n", strerror(errno));
  390. goto err;
  391. }
  392. // Remove old (lost) socket's file
  393. unlink(path);
  394. laddr.sun_family = AF_UNIX;
  395. strncpy(laddr.sun_path, path, USOCK_PATH_MAX);
  396. laddr.sun_path[USOCK_PATH_MAX - 1] = '\0';
  397. if (bind(sock, (struct sockaddr *)&laddr, sizeof(laddr))) {
  398. syslog(LOG_ERR, "Can't bind socket %s: %s\n", path, strerror(errno));
  399. goto err;
  400. }
  401. if (listen(sock, 128)) {
  402. unlink(path);
  403. syslog(LOG_ERR, "Can't listen on socket %s: %s\n", path, strerror(errno));
  404. goto err;
  405. }
  406. return sock;
  407. err:
  408. if (sock >= 0)
  409. close(sock);
  410. return -1;
  411. }
  412. /** @brief Stop main event loop.
  413. */
  414. static bool_t stop_loop_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  415. void *associated_data, void *user_data)
  416. {
  417. // Happy compiler
  418. eloop = eloop;
  419. type = type;
  420. associated_data = associated_data;
  421. user_data = user_data;
  422. return BOOL_FALSE; // Stop Event Loop
  423. }
  424. /** @brief Wait for child processes (service processes).
  425. */
  426. static bool_t wait_for_child_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  427. void *associated_data, void *user_data)
  428. {
  429. int wstatus = 0;
  430. pid_t child_pid = -1;
  431. // Wait for any child process. Doesn't block.
  432. while ((child_pid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
  433. if (WIFSIGNALED(wstatus)) {
  434. syslog(LOG_ERR, "Service process %d was terminated "
  435. "by signal: %d",
  436. child_pid, WTERMSIG(wstatus));
  437. } else {
  438. syslog(LOG_ERR, "Service process %d was terminated: %d",
  439. child_pid, WEXITSTATUS(wstatus));
  440. }
  441. }
  442. // Happy compiler
  443. eloop = eloop;
  444. type = type;
  445. associated_data = associated_data;
  446. user_data = user_data;
  447. return BOOL_TRUE;
  448. }
  449. /** @brief Wait for child processes (ACTIONs).
  450. */
  451. static bool_t wait_for_actions_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  452. void *associated_data, void *user_data)
  453. {
  454. int wstatus = 0;
  455. pid_t child_pid = -1;
  456. ktpd_session_t *ktpd_session = (ktpd_session_t *)user_data;
  457. // Wait for any child process. Doesn't block.
  458. while ((child_pid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
  459. if (!ktpd_session)
  460. continue;
  461. ktpd_session_terminated_action(ktpd_session, child_pid, wstatus);
  462. }
  463. // Happy compiler
  464. eloop = eloop;
  465. type = type;
  466. associated_data = associated_data;
  467. return BOOL_TRUE;
  468. }
  469. /** @brief Re-read config file.
  470. *
  471. * This function can refresh klishd options but plugins (dbs for example) are
  472. * already inited and there is no way to re-init them on-the-fly.
  473. */
  474. static bool_t refresh_config_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  475. void *associated_data, void *user_data)
  476. {
  477. struct options *opts = (struct options *)user_data;
  478. faux_ini_t *ini = NULL;
  479. if (access(opts->cfgfile, R_OK) == 0) {
  480. syslog(LOG_DEBUG, "Re-reading config file \"%s\"\n", opts->cfgfile);
  481. if (!(ini = config_parse(opts->cfgfile, opts)))
  482. syslog(LOG_ERR, "Error while config file parsing.\n");
  483. } else if (opts->cfgfile_userdefined) {
  484. syslog(LOG_ERR, "Can't find config file \"%s\"\n", opts->cfgfile);
  485. }
  486. faux_ini_free(ini); // No way to use it later
  487. // Happy compiler
  488. eloop = eloop;
  489. type = type;
  490. associated_data = associated_data;
  491. return BOOL_TRUE;
  492. }
  493. /** @brief Event on listen socket. New remote client.
  494. */
  495. static bool_t listen_socket_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  496. void *associated_data, void *user_data)
  497. {
  498. int new_conn = -1;
  499. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  500. pid_t child_pid = -1;
  501. assert(user_data);
  502. new_conn = accept(info->fd, NULL, NULL);
  503. if (new_conn < 0) {
  504. syslog(LOG_ERR, "Can't accept() new connection");
  505. return BOOL_TRUE;
  506. }
  507. // Fork new instance for newly connected client
  508. child_pid = fork();
  509. if (child_pid < 0) {
  510. close(new_conn);
  511. syslog(LOG_ERR, "Can't fork service process for client");
  512. return BOOL_TRUE;
  513. }
  514. // Parent
  515. if (child_pid > 0) {
  516. close(new_conn); // It's needed by child but not for parent
  517. syslog(LOG_ERR, "Service process for client was forked: %d",
  518. child_pid);
  519. return BOOL_TRUE;
  520. }
  521. // Child (forked service process)
  522. // Pass new ktpd_session to main programm
  523. *((int *)user_data) = new_conn;
  524. type = type; // Happy compiler
  525. eloop = eloop;
  526. // Return BOOL_FALSE to break listen parent loop. Child will create its
  527. // own loop then.
  528. return BOOL_FALSE;
  529. }