klishd.c 14 KB

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