klishd.c 14 KB

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