klishd.c 15 KB

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