klishd.c 15 KB

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