klishd.c 14 KB

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