klishd.c 14 KB

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