klishd.c 14 KB

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