klishd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. #include "sch.c"
  43. // Local static functions
  44. static int create_listen_unix_sock(const char *path);
  45. static bool_t load_all_dbs(kscheme_t *scheme, const char *dbs,
  46. faux_ini_t *global_config, faux_error_t *error);
  47. // Main loop events
  48. static bool_t stop_loop_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  49. void *associated_data, void *user_data);
  50. static bool_t refresh_config_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  51. void *associated_data, void *user_data);
  52. static bool_t client_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 sched_once(faux_eloop_t *eloop, faux_eloop_type_e type,
  57. void *associated_data, void *user_data);
  58. static bool_t sched_periodic(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_clients_t *clients = NULL;
  71. kscheme_t *scheme = NULL;
  72. ksession_t *session = NULL;
  73. faux_error_t *error = faux_error_new();
  74. faux_ini_t *config = NULL;
  75. struct timespec delayed = { .tv_sec = 10, .tv_nsec = 0 };
  76. struct timespec period = { .tv_sec = 3, .tv_nsec = 0 };
  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
  103. if (!opts->foreground) {
  104. // Daemonize
  105. syslog(LOG_DEBUG, "Daemonize\n");
  106. if (daemon(0, 0) < 0) {
  107. syslog(LOG_ERR, "Can't daemonize\n");
  108. goto err;
  109. }
  110. // Write pidfile
  111. syslog(LOG_DEBUG, "Write PID file: %s\n", opts->pidfile);
  112. if ((pidfd = open(opts->pidfile,
  113. O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
  114. S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
  115. syslog(LOG_WARNING, "Can't open pidfile %s: %s\n",
  116. opts->pidfile, strerror(errno));
  117. } else {
  118. char str[20];
  119. snprintf(str, sizeof(str), "%u\n", getpid());
  120. str[sizeof(str) - 1] = '\0';
  121. if (write(pidfd, str, strlen(str)) < 0)
  122. syslog(LOG_WARNING, "Can't write to %s: %s\n",
  123. opts->pidfile, strerror(errno));
  124. close(pidfd);
  125. }
  126. }
  127. // Scheme
  128. scheme = kscheme_new();
  129. {
  130. kcontext_t *context = NULL;
  131. bool_t prepare_retcode = BOOL_FALSE;
  132. kdb_t *deploy_db = NULL;
  133. // Load scheme
  134. if (!load_all_dbs(scheme, opts->dbs, config, error)) {
  135. fprintf(stderr, "Scheme errors:\n");
  136. goto err;
  137. }
  138. // Prepare scheme
  139. context = kcontext_new(KCONTEXT_PLUGIN_INIT);
  140. prepare_retcode = kscheme_prepare(scheme, context, error);
  141. kcontext_free(context);
  142. if (!prepare_retcode) {
  143. fprintf(stderr, "Scheme preparing errors:\n");
  144. goto err;
  145. }
  146. // Deploy (for testing purposes)
  147. deploy_db = kdb_new("ischeme", NULL);
  148. kdb_load_plugin(deploy_db);
  149. kdb_init(deploy_db);
  150. // kdb_deploy_scheme(deploy_db, scheme);
  151. kdb_fini(deploy_db);
  152. kdb_free(deploy_db);
  153. }
  154. // Parsing
  155. {
  156. char *s = NULL;
  157. const char *line = "cmd o1 m7 o2 e1";
  158. kpargv_t *pargv = NULL;
  159. kpargv_pargs_node_t *p_iter = NULL;
  160. session = ksession_new(scheme, "/lowview");
  161. kpath_push(ksession_path(session), klevel_new(kscheme_find_entry_by_path(scheme, "/main")));
  162. pargv = ksession_parse_line(session, line);
  163. if (pargv) {
  164. switch (kpargv_status(pargv)) {
  165. case KPARSE_NONE:
  166. s = "None";
  167. break;
  168. case KPARSE_OK:
  169. s = "Ok";
  170. break;
  171. case KPARSE_INPROGRESS:
  172. s = "In progress";
  173. break;
  174. case KPARSE_NOTFOUND:
  175. s = "Not found";
  176. break;
  177. case KPARSE_INCOMPLETED:
  178. s = "Incompleted";
  179. break;
  180. case KPARSE_ILLEGAL:
  181. s = "Illegal";
  182. break;
  183. case KPARSE_ERROR:
  184. s = "Error";
  185. break;
  186. }
  187. printf("Level: %lu, Command: %s, Line '%s': %s\n",
  188. kpargv_level(pargv), kentry_name(kpargv_command(pargv)),
  189. line, s);
  190. kparg_t *parg = NULL;
  191. p_iter = kpargv_pargs_iter(pargv);
  192. while ((parg = kpargv_pargs_each(&p_iter))) {
  193. printf("%s(%s) ", kparg_value(parg), kentry_name(kparg_entry(parg)));
  194. }
  195. printf("\n");
  196. }
  197. kpargv_free(pargv);
  198. ksession_free(session);
  199. }
  200. goto err; // Test purposes
  201. // Listen socket
  202. syslog(LOG_DEBUG, "Create listen UNIX socket: %s\n", opts->unix_socket_path);
  203. listen_unix_sock = create_listen_unix_sock(opts->unix_socket_path);
  204. if (listen_unix_sock < 0)
  205. goto err;
  206. syslog(LOG_DEBUG, "Listen socket %d", listen_unix_sock);
  207. // Clients sessions DB
  208. clients = ktpd_clients_new();
  209. assert(clients);
  210. if (!clients)
  211. goto err;
  212. // Event loop
  213. eloop = faux_eloop_new(NULL);
  214. // Signals
  215. faux_eloop_add_signal(eloop, SIGINT, stop_loop_ev, NULL);
  216. faux_eloop_add_signal(eloop, SIGTERM, stop_loop_ev, NULL);
  217. faux_eloop_add_signal(eloop, SIGQUIT, stop_loop_ev, NULL);
  218. faux_eloop_add_signal(eloop, SIGHUP, refresh_config_ev, opts);
  219. // Listen socket. Waiting for new connections
  220. faux_eloop_add_fd(eloop, listen_unix_sock, POLLIN, listen_socket_ev, clients);
  221. // Scheduled events
  222. faux_eloop_add_sched_once_delayed(eloop, &delayed, 1, sched_once, NULL);
  223. faux_eloop_add_sched_periodic_delayed(eloop, 2, sched_periodic, NULL, &period, FAUX_SCHED_INFINITE);
  224. // Main loop
  225. faux_eloop_loop(eloop);
  226. faux_eloop_free(eloop);
  227. /*
  228. // Non-blocking wait for all children
  229. while ((pid = waitpid(-1, NULL, WNOHANG)) > 0) {
  230. syslog(LOG_DEBUG, "Exit child process %d\n", pid);
  231. }
  232. */
  233. retval = 0;
  234. err:
  235. syslog(LOG_DEBUG, "Cleanup.\n");
  236. ktpd_clients_free(clients);
  237. // Close listen socket
  238. if (listen_unix_sock >= 0)
  239. close(listen_unix_sock);
  240. // Remove pidfile
  241. if (pidfd >= 0) {
  242. if (unlink(opts->pidfile) < 0) {
  243. syslog(LOG_ERR, "Can't remove pid-file %s: %s\n",
  244. opts->pidfile, strerror(errno));
  245. }
  246. }
  247. // Free scheme
  248. if (scheme) {
  249. kcontext_t *context = kcontext_new(KCONTEXT_PLUGIN_FINI);
  250. kscheme_fini(scheme, context, error);
  251. kcontext_free(context);
  252. kscheme_free(scheme);
  253. }
  254. // Free command line options
  255. opts_free(opts);
  256. faux_ini_free(config);
  257. syslog(LOG_INFO, "Stop daemon.\n");
  258. if (faux_error_len(error) > 0)
  259. faux_error_show(error);
  260. faux_error_free(error);
  261. return retval;
  262. }
  263. static bool_t load_db(kscheme_t *scheme, const char *db_name,
  264. faux_ini_t *config, faux_error_t *error)
  265. {
  266. kdb_t *db = NULL;
  267. const char *sofile = NULL;
  268. assert(scheme);
  269. if (!scheme)
  270. return BOOL_FALSE;
  271. assert(db_name);
  272. if (!db_name)
  273. return BOOL_FALSE;
  274. // DB.libxml2.so = <so filename>
  275. if (config)
  276. sofile = faux_ini_find(config, "so");
  277. db = kdb_new(db_name, sofile);
  278. assert(db);
  279. if (!db)
  280. return BOOL_FALSE;
  281. kdb_set_ini(db, config);
  282. kdb_set_error(db, error);
  283. // Load DB plugin
  284. if (!kdb_load_plugin(db)) {
  285. faux_error_sprintf(error,
  286. "DB \"%s\": Can't load DB plugin", db_name);
  287. kdb_free(db);
  288. return BOOL_FALSE;
  289. }
  290. // Check plugin API version
  291. if ((kdb_major(db) != KDB_MAJOR) ||
  292. (kdb_minor(db) != KDB_MINOR)) {
  293. faux_error_sprintf(error,
  294. "DB \"%s\": Plugin's API version is %u.%u, need %u.%u",
  295. db_name,
  296. kdb_major(db), kdb_minor(db),
  297. KDB_MAJOR, KDB_MINOR);
  298. kdb_free(db);
  299. return BOOL_FALSE;
  300. }
  301. // Init plugin
  302. if (kdb_has_init_fn(db) && !kdb_init(db)) {
  303. faux_error_sprintf(error,
  304. "DB \"%s\": Can't init DB plugin", db_name);
  305. kdb_free(db);
  306. return BOOL_FALSE;
  307. }
  308. // Load scheme
  309. if (!kdb_has_load_fn(db) || !kdb_load_scheme(db, scheme)) {
  310. faux_error_sprintf(error,
  311. "DB \"%s\": Can't load scheme from DB plugin", db_name);
  312. kdb_fini(db);
  313. kdb_free(db);
  314. return BOOL_FALSE;
  315. }
  316. // Fini plugin
  317. if (kdb_has_fini_fn(db) && !kdb_fini(db)) {
  318. faux_error_sprintf(error,
  319. "DB \"%s\": Can't fini DB plugin", db_name);
  320. kdb_free(db);
  321. return BOOL_FALSE;
  322. }
  323. kdb_free(db);
  324. return BOOL_TRUE;
  325. }
  326. static bool_t load_all_dbs(kscheme_t *scheme, const char *dbs,
  327. faux_ini_t *global_config, faux_error_t *error)
  328. {
  329. faux_argv_t *dbs_argv = NULL;
  330. faux_argv_node_t *iter = NULL;
  331. const char *db_name = NULL;
  332. bool_t retcode = BOOL_TRUE;
  333. assert(scheme);
  334. if (!scheme)
  335. return BOOL_FALSE;
  336. assert(dbs);
  337. if (!dbs)
  338. return BOOL_FALSE;
  339. dbs_argv = faux_argv_new();
  340. assert(dbs_argv);
  341. if (!dbs_argv)
  342. return BOOL_FALSE;
  343. if (faux_argv_parse(dbs_argv, dbs) <= 0) {
  344. faux_argv_free(dbs_argv);
  345. return BOOL_FALSE;
  346. }
  347. // For each DB
  348. iter = faux_argv_iter(dbs_argv);
  349. while ((db_name = faux_argv_each(&iter))) {
  350. faux_ini_t *config = NULL; // Sub-config for current DB
  351. char *prefix = NULL;
  352. prefix = faux_str_mcat(&prefix, "DB.", db_name, ".", NULL);
  353. if (config)
  354. config = faux_ini_extract_subini(global_config, prefix);
  355. if (!load_db(scheme, db_name, config, error))
  356. retcode = BOOL_FALSE;
  357. faux_ini_free(config);
  358. faux_str_free(prefix);
  359. }
  360. faux_argv_free(dbs_argv);
  361. return retcode;
  362. }
  363. /** @brief Create listen socket
  364. *
  365. * Previously removes old socket's file from filesystem. Note daemon must check
  366. * for already working daemon to don't duplicate.
  367. *
  368. * @param [in] path Socket path within filesystem.
  369. * @return Socket descriptor of < 0 on error.
  370. */
  371. static int create_listen_unix_sock(const char *path)
  372. {
  373. int sock = -1;
  374. int opt = 1;
  375. struct sockaddr_un laddr = {};
  376. assert(path);
  377. if (!path)
  378. return -1;
  379. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  380. syslog(LOG_ERR, "Can't create socket: %s\n", strerror(errno));
  381. goto err;
  382. }
  383. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
  384. syslog(LOG_ERR, "Can't set socket options: %s\n", strerror(errno));
  385. goto err;
  386. }
  387. // Remove old (lost) socket's file
  388. unlink(path);
  389. laddr.sun_family = AF_UNIX;
  390. strncpy(laddr.sun_path, path, USOCK_PATH_MAX);
  391. laddr.sun_path[USOCK_PATH_MAX - 1] = '\0';
  392. if (bind(sock, (struct sockaddr *)&laddr, sizeof(laddr))) {
  393. syslog(LOG_ERR, "Can't bind socket %s: %s\n", path, strerror(errno));
  394. goto err;
  395. }
  396. if (listen(sock, 128)) {
  397. unlink(path);
  398. syslog(LOG_ERR, "Can't listen on socket %s: %s\n", path, strerror(errno));
  399. goto err;
  400. }
  401. return sock;
  402. err:
  403. if (sock >= 0)
  404. close(sock);
  405. return -1;
  406. }
  407. /** @brief Stop main event loop.
  408. */
  409. static bool_t stop_loop_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  410. void *associated_data, void *user_data)
  411. {
  412. // Happy compiler
  413. eloop = eloop;
  414. type = type;
  415. associated_data = associated_data;
  416. user_data = user_data;
  417. return BOOL_FALSE; // Stop Event Loop
  418. }
  419. /** @brief Re-read config file.
  420. *
  421. * This function can refresh klishd options but plugins (dbs for example) are
  422. * already inited and there is no way to re-init them on-the-fly.
  423. */
  424. static bool_t refresh_config_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  425. void *associated_data, void *user_data)
  426. {
  427. struct options *opts = (struct options *)user_data;
  428. faux_ini_t *ini = NULL;
  429. if (access(opts->cfgfile, R_OK) == 0) {
  430. syslog(LOG_DEBUG, "Re-reading config file \"%s\"\n", opts->cfgfile);
  431. if (!(ini = config_parse(opts->cfgfile, opts)))
  432. syslog(LOG_ERR, "Error while config file parsing.\n");
  433. } else if (opts->cfgfile_userdefined) {
  434. syslog(LOG_ERR, "Can't find config file \"%s\"\n", opts->cfgfile);
  435. }
  436. faux_ini_free(ini); // No way to use it later
  437. // Happy compiler
  438. eloop = eloop;
  439. type = type;
  440. associated_data = associated_data;
  441. return BOOL_TRUE;
  442. }
  443. bool_t fd_stall_cb(ktpd_session_t *session, void *user_data)
  444. {
  445. faux_eloop_t *eloop = (faux_eloop_t *)user_data;
  446. assert(session);
  447. assert(eloop);
  448. faux_eloop_include_fd_event(eloop, ktpd_session_fd(session), POLLOUT);
  449. return BOOL_TRUE;
  450. }
  451. /** @brief Event on listen socket. New remote client.
  452. */
  453. static bool_t listen_socket_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  454. void *associated_data, void *user_data)
  455. {
  456. int new_conn = -1;
  457. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  458. ktpd_clients_t *clients = (ktpd_clients_t *)user_data;
  459. ktpd_session_t *session = NULL;
  460. assert(clients);
  461. new_conn = accept(info->fd, NULL, NULL);
  462. if (new_conn < 0) {
  463. syslog(LOG_ERR, "Can't accept() new connection");
  464. return BOOL_TRUE;
  465. }
  466. session = ktpd_clients_add(clients, new_conn);
  467. if (!session) {
  468. syslog(LOG_ERR, "Duplicated client fd");
  469. close(new_conn);
  470. return BOOL_TRUE;
  471. }
  472. ktpd_session_set_stall_cb(session, fd_stall_cb, eloop);
  473. faux_eloop_add_fd(eloop, new_conn, POLLIN, client_ev, clients);
  474. syslog(LOG_DEBUG, "New connection %d", new_conn);
  475. type = type; // Happy compiler
  476. user_data = user_data; // Happy compiler
  477. return BOOL_TRUE;
  478. }
  479. static bool_t client_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  480. void *associated_data, void *user_data)
  481. {
  482. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  483. ktpd_clients_t *clients = (ktpd_clients_t *)user_data;
  484. ktpd_session_t *session = NULL;
  485. assert(clients);
  486. // Find out session
  487. session = ktpd_clients_find(clients, info->fd);
  488. if (!session) { // Some strange case
  489. syslog(LOG_ERR, "Can't find client session for fd %d", info->fd);
  490. faux_eloop_del_fd(eloop, info->fd);
  491. close(info->fd);
  492. return BOOL_TRUE;
  493. }
  494. // Write data
  495. if (info->revents & POLLOUT) {
  496. faux_eloop_exclude_fd_event(eloop, info->fd, POLLOUT);
  497. if (!ktpd_session_async_out(session)) {
  498. // Someting went wrong
  499. faux_eloop_del_fd(eloop, info->fd);
  500. ktpd_clients_del(clients, info->fd);
  501. syslog(LOG_ERR, "Problem with async input");
  502. }
  503. }
  504. // Read data
  505. if (info->revents & POLLIN) {
  506. if (!ktpd_session_async_in(session)) {
  507. // Someting went wrong
  508. faux_eloop_del_fd(eloop, info->fd);
  509. ktpd_clients_del(clients, info->fd);
  510. syslog(LOG_ERR, "Problem with async input");
  511. }
  512. }
  513. // EOF
  514. if (info->revents & POLLHUP) {
  515. faux_eloop_del_fd(eloop, info->fd);
  516. ktpd_clients_del(clients, info->fd);
  517. syslog(LOG_DEBUG, "Close connection %d", info->fd);
  518. }
  519. type = type; // Happy compiler
  520. user_data = user_data; // Happy compiler
  521. return BOOL_TRUE;
  522. }
  523. static bool_t sched_once(faux_eloop_t *eloop, faux_eloop_type_e type,
  524. void *associated_data, void *user_data)
  525. {
  526. faux_eloop_info_sched_t *info = (faux_eloop_info_sched_t *)associated_data;
  527. printf("Once %d\n", info->ev_id);
  528. // Happy compiler
  529. eloop = eloop;
  530. type = type;
  531. associated_data = associated_data;
  532. user_data = user_data;
  533. return BOOL_TRUE;
  534. }
  535. static bool_t sched_periodic(faux_eloop_t *eloop, faux_eloop_type_e type,
  536. void *associated_data, void *user_data)
  537. {
  538. faux_eloop_info_sched_t *info = (faux_eloop_info_sched_t *)associated_data;
  539. printf("Periodic %d\n", info->ev_id);
  540. // Happy compiler
  541. eloop = eloop;
  542. type = type;
  543. associated_data = associated_data;
  544. user_data = user_data;
  545. return BOOL_TRUE;
  546. }