ktpd_session.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. #define _GNU_SOURCE
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <sys/socket.h>
  12. #include <sys/un.h>
  13. #include <syslog.h>
  14. #include <poll.h>
  15. #include <sys/wait.h>
  16. #include <faux/str.h>
  17. #include <faux/conv.h>
  18. #include <faux/async.h>
  19. #include <faux/msg.h>
  20. #include <faux/eloop.h>
  21. #include <faux/sysdb.h>
  22. #include <klish/ksession.h>
  23. #include <klish/ksession_parse.h>
  24. #include <klish/ktp.h>
  25. #include <klish/ktp_session.h>
  26. typedef enum {
  27. KTPD_SESSION_STATE_DISCONNECTED = 'd',
  28. KTPD_SESSION_STATE_UNAUTHORIZED = 'a',
  29. KTPD_SESSION_STATE_IDLE = 'i',
  30. KTPD_SESSION_STATE_WAIT_FOR_PROCESS = 'p',
  31. } ktpd_session_state_e;
  32. struct ktpd_session_s {
  33. ksession_t *session;
  34. ktpd_session_state_e state;
  35. faux_async_t *async; // Object for data exchange with client (KTP)
  36. faux_hdr_t *hdr; // Engine will receive header and then msg
  37. faux_eloop_t *eloop; // External link, dont's free()
  38. kexec_t *exec;
  39. bool_t exit;
  40. bool_t stdin_must_be_closed;
  41. };
  42. // Static declarations
  43. static bool_t ktpd_session_read_cb(faux_async_t *async,
  44. faux_buf_t *buf, size_t len, void *user_data);
  45. static bool_t wait_for_actions_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  46. void *associated_data, void *user_data);
  47. bool_t client_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  48. void *associated_data, void *user_data);
  49. static bool_t ktpd_session_exec(ktpd_session_t *ktpd, const char *line,
  50. int *retcode, faux_error_t *error,
  51. bool_t dry_run, bool_t *view_was_changed);
  52. static bool_t action_stdout_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  53. void *associated_data, void *user_data);
  54. static bool_t action_stderr_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  55. void *associated_data, void *user_data);
  56. static bool_t get_stream(ktpd_session_t *ktpd, int fd, bool_t is_stderr);
  57. ktpd_session_t *ktpd_session_new(int sock, kscheme_t *scheme,
  58. const char *start_entry, faux_eloop_t *eloop)
  59. {
  60. ktpd_session_t *ktpd = NULL;
  61. if (sock < 0)
  62. return NULL;
  63. if (!eloop)
  64. return NULL;
  65. ktpd = faux_zmalloc(sizeof(*ktpd));
  66. assert(ktpd);
  67. if (!ktpd)
  68. return NULL;
  69. // Init
  70. ktpd->state = KTPD_SESSION_STATE_UNAUTHORIZED;
  71. ktpd->eloop = eloop;
  72. ktpd->session = ksession_new(scheme, start_entry);
  73. if (!ktpd->session) {
  74. faux_free(ktpd);
  75. return NULL;
  76. }
  77. ktpd->exec = NULL;
  78. // Client can send command to close stdin but it can't be done
  79. // immediately because stdin buffer can still contain data. So really
  80. // close stdin after all data is written.
  81. ktpd->stdin_must_be_closed = BOOL_FALSE;
  82. // Exit flag. It differs from ksession done flag because KTPD session
  83. // can't exit immediately. It must finish current command processing
  84. // before really stop the event loop. Note: User defined plugin
  85. // function must use ksession done flag. This exit flag is internal
  86. // feature of KTPD session.
  87. ktpd->exit = BOOL_FALSE;
  88. // Async object
  89. ktpd->async = faux_async_new(sock);
  90. assert(ktpd->async);
  91. // Receive message header first
  92. faux_async_set_read_limits(ktpd->async,
  93. sizeof(faux_hdr_t), sizeof(faux_hdr_t));
  94. faux_async_set_read_cb(ktpd->async, ktpd_session_read_cb, ktpd);
  95. ktpd->hdr = NULL;
  96. faux_async_set_stall_cb(ktpd->async, ktp_stall_cb, ktpd->eloop);
  97. // Eloop callbacks
  98. faux_eloop_add_fd(ktpd->eloop, ktpd_session_fd(ktpd), POLLIN,
  99. client_ev, ktpd);
  100. faux_eloop_add_signal(ktpd->eloop, SIGCHLD, wait_for_actions_ev, ktpd);
  101. return ktpd;
  102. }
  103. void ktpd_session_free(ktpd_session_t *ktpd)
  104. {
  105. kcontext_t *context = NULL;
  106. kscheme_t *scheme = NULL;
  107. if (!ktpd)
  108. return;
  109. // fini session for plugins
  110. if (ktpd->state != KTPD_SESSION_STATE_UNAUTHORIZED) {
  111. scheme = ksession_scheme(ktpd->session);
  112. context = kcontext_new(KCONTEXT_TYPE_PLUGIN_FINI);
  113. kcontext_set_session(context, ktpd->session);
  114. kcontext_set_scheme(context, scheme);
  115. kscheme_fini_session_plugins(scheme, context, NULL);
  116. kcontext_free(context);
  117. }
  118. kexec_free(ktpd->exec);
  119. ksession_free(ktpd->session);
  120. faux_free(ktpd->hdr);
  121. close(ktpd_session_fd(ktpd));
  122. faux_async_free(ktpd->async);
  123. faux_free(ktpd);
  124. }
  125. static char *generate_prompt(ktpd_session_t *ktpd)
  126. {
  127. kpath_levels_node_t *iter = NULL;
  128. klevel_t *level = NULL;
  129. char *prompt = NULL;
  130. iter = kpath_iterr(ksession_path(ktpd->session));
  131. while ((level = kpath_eachr(&iter))) {
  132. const kentry_t *view = klevel_entry(level);
  133. kentry_t *prompt_entry = kentry_nested_by_purpose(view,
  134. KENTRY_PURPOSE_PROMPT);
  135. if (!prompt_entry)
  136. continue;
  137. if (kentry_actions_len(prompt_entry) > 0) {
  138. int rc = -1;
  139. bool_t res = BOOL_FALSE;
  140. res = ksession_exec_locally(ktpd->session,
  141. prompt_entry, NULL, &rc, &prompt);
  142. if (!res || (rc < 0) || !prompt) {
  143. if (prompt)
  144. faux_str_free(prompt);
  145. prompt = NULL;
  146. }
  147. }
  148. if (!prompt) {
  149. if (kentry_value(prompt_entry))
  150. prompt = faux_str_dup(kentry_value(prompt_entry));
  151. }
  152. if (prompt)
  153. break;
  154. }
  155. return prompt;
  156. }
  157. // Format: <key>'\0'<cmd>
  158. static bool_t add_hotkey(faux_msg_t *msg, khotkey_t *hotkey)
  159. {
  160. const char *key = NULL;
  161. const char *cmd = NULL;
  162. char *whole_str = NULL;
  163. size_t key_s = 0;
  164. size_t cmd_s = 0;
  165. key = khotkey_key(hotkey);
  166. key_s = strlen(key);
  167. cmd = khotkey_cmd(hotkey);
  168. cmd_s = strlen(cmd);
  169. whole_str = faux_zmalloc(key_s + 1 + cmd_s);
  170. memcpy(whole_str, key, key_s);
  171. memcpy(whole_str + key_s + 1, cmd, cmd_s);
  172. faux_msg_add_param(msg, KTP_PARAM_HOTKEY, whole_str, key_s + 1 + cmd_s);
  173. faux_free(whole_str);
  174. return BOOL_TRUE;
  175. }
  176. static bool_t add_hotkeys_to_msg(ktpd_session_t *ktpd, faux_msg_t *msg)
  177. {
  178. faux_list_t *list = NULL;
  179. kpath_t *path = NULL;
  180. kentry_hotkeys_node_t *l_iter = NULL;
  181. khotkey_t *hotkey = NULL;
  182. assert(ktpd);
  183. assert(msg);
  184. path = ksession_path(ktpd->session);
  185. assert(path);
  186. if (kpath_len(path) == 1) {
  187. // We don't need additional list because there is only one
  188. // VIEW in the path so hotkey's list is only one too. Get it.
  189. list = kentry_hotkeys(klevel_entry(
  190. (klevel_t *)faux_list_data(kpath_iter(path))));
  191. } else {
  192. faux_list_node_t *iterr = NULL;
  193. klevel_t *level = NULL;
  194. // Create temp hotkeys list to add hotkeys from all VIEWs in
  195. // the path and exclude duplications. Don't free elements
  196. // because they are just a references.
  197. list = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_UNIQUE,
  198. kentry_hotkey_compare, NULL, NULL);
  199. // Begin with the end. Because hotkeys from nested VIEWs has
  200. // higher priority.
  201. iterr = kpath_iterr(path);
  202. while ((level = kpath_eachr(&iterr))) {
  203. const kentry_t *entry = klevel_entry(level);
  204. kentry_hotkeys_node_t *hk_iter = kentry_hotkeys_iter(entry);
  205. while ((hotkey = kentry_hotkeys_each(&hk_iter)))
  206. faux_list_add(list, hotkey);
  207. }
  208. }
  209. // Add found hotkeys to msg
  210. l_iter = faux_list_head(list);
  211. while ((hotkey = (khotkey_t *)faux_list_each(&l_iter)))
  212. add_hotkey(msg, hotkey);
  213. if (kpath_len(path) != 1)
  214. faux_list_free(list);
  215. return BOOL_TRUE;
  216. }
  217. // Now it's not really an auth function. Just a hand-shake with client and
  218. // passing prompt to client.
  219. static bool_t ktpd_session_process_auth(ktpd_session_t *ktpd, faux_msg_t *msg)
  220. {
  221. ktp_cmd_e cmd = KTP_AUTH_ACK;
  222. uint32_t status = KTP_STATUS_NONE;
  223. faux_msg_t *ack = NULL;
  224. char *prompt = NULL;
  225. uint8_t retcode8bit = 0;
  226. struct ucred ucred = {};
  227. socklen_t len = sizeof(ucred);
  228. int sock = -1;
  229. char *user = NULL;
  230. kcontext_t *context = NULL;
  231. kscheme_t *scheme = NULL;
  232. uint32_t client_status = KTP_STATUS_NONE;
  233. assert(ktpd);
  234. assert(msg);
  235. // Get UNIX socket peer information
  236. sock = faux_async_fd(ktpd->async);
  237. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) < 0) {
  238. const char *err = "Can't get peer credentials";
  239. syslog(LOG_ERR, "%s for connection %d", err, sock);
  240. ack = ktp_msg_preform(cmd, KTP_STATUS_ERROR | KTP_STATUS_EXIT);
  241. faux_msg_add_param(ack, KTP_PARAM_ERROR, err, strlen(err));
  242. faux_msg_send_async(ack, ktpd->async);
  243. faux_msg_free(ack);
  244. ktpd->exit = BOOL_TRUE;
  245. return BOOL_FALSE;
  246. }
  247. ksession_set_pid(ktpd->session, ucred.pid);
  248. ksession_set_uid(ktpd->session, ucred.uid);
  249. user = faux_sysdb_name_by_uid(ucred.uid);
  250. ksession_set_user(ktpd->session, user);
  251. faux_str_free(user);
  252. // Get tty information from auth message status
  253. client_status = faux_msg_get_status(msg);
  254. ksession_set_isatty_stdin(ktpd->session,
  255. KTP_STATUS_IS_TTY_STDIN(client_status));
  256. ksession_set_isatty_stdout(ktpd->session,
  257. KTP_STATUS_IS_TTY_STDOUT(client_status));
  258. ksession_set_isatty_stderr(ktpd->session,
  259. KTP_STATUS_IS_TTY_STDERR(client_status));
  260. // init session for plugins
  261. scheme = ksession_scheme(ktpd->session);
  262. context = kcontext_new(KCONTEXT_TYPE_PLUGIN_INIT);
  263. kcontext_set_session(context, ktpd->session);
  264. kcontext_set_scheme(context, scheme);
  265. kscheme_init_session_plugins(scheme, context, NULL);
  266. kcontext_free(context);
  267. // Prepare ACK message
  268. ack = ktp_msg_preform(cmd, status);
  269. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  270. // Generate prompt
  271. prompt = generate_prompt(ktpd);
  272. if (prompt) {
  273. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  274. faux_str_free(prompt);
  275. }
  276. add_hotkeys_to_msg(ktpd, ack);
  277. faux_msg_send_async(ack, ktpd->async);
  278. faux_msg_free(ack);
  279. ktpd->state = KTPD_SESSION_STATE_IDLE;
  280. return BOOL_TRUE;
  281. }
  282. static bool_t ktpd_session_process_cmd(ktpd_session_t *ktpd, faux_msg_t *msg)
  283. {
  284. char *line = NULL;
  285. int retcode = -1;
  286. ktp_cmd_e cmd = KTP_CMD_ACK;
  287. faux_error_t *error = NULL;
  288. bool_t rc = BOOL_FALSE;
  289. bool_t dry_run = BOOL_FALSE;
  290. uint32_t status = KTP_STATUS_NONE;
  291. bool_t ret = BOOL_TRUE;
  292. char *prompt = NULL;
  293. bool_t view_was_changed = BOOL_FALSE;
  294. assert(ktpd);
  295. assert(msg);
  296. // Get line from message
  297. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  298. ktp_send_error(ktpd->async, cmd, "The line is not specified");
  299. return BOOL_FALSE;
  300. }
  301. // Get dry-run flag from message
  302. if (KTP_STATUS_IS_DRY_RUN(faux_msg_get_status(msg)))
  303. dry_run = BOOL_TRUE;
  304. error = faux_error_new();
  305. ktpd->exec = NULL;
  306. rc = ktpd_session_exec(ktpd, line, &retcode, error,
  307. dry_run, &view_was_changed);
  308. faux_str_free(line);
  309. // Command is scheduled. Eloop will wait for ACTION completion.
  310. // So inform client about it and about command features like
  311. // interactive/non-interactive.
  312. if (ktpd->exec) {
  313. faux_msg_t *ack = NULL;
  314. ktp_status_e status = KTP_STATUS_INCOMPLETED;
  315. if (kexec_interactive(ktpd->exec))
  316. status |= KTP_STATUS_INTERACTIVE;
  317. if (kexec_need_stdin(ktpd->exec))
  318. status |= KTP_STATUS_NEED_STDIN;
  319. ack = ktp_msg_preform(cmd, status);
  320. faux_msg_send_async(ack, ktpd->async);
  321. faux_msg_free(ack);
  322. faux_error_free(error);
  323. return BOOL_TRUE; // Continue and wait for ACTION
  324. }
  325. // Here we don't need to wait for the action. We have retcode already.
  326. if (ksession_done(ktpd->session)) {
  327. ktpd->exit = BOOL_TRUE;
  328. status |= KTP_STATUS_EXIT;
  329. }
  330. // Prepare ACK message
  331. faux_msg_t *ack = ktp_msg_preform(cmd, status);
  332. if (rc) {
  333. uint8_t retcode8bit = 0;
  334. retcode8bit = (uint8_t)(retcode & 0xff);
  335. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  336. } else {
  337. faux_msg_set_status(ack, KTP_STATUS_ERROR);
  338. char *err = faux_error_cstr(error);
  339. faux_msg_add_param(ack, KTP_PARAM_ERROR, err, strlen(err));
  340. faux_str_free(err);
  341. ret = BOOL_FALSE;
  342. }
  343. // Generate prompt
  344. prompt = generate_prompt(ktpd);
  345. if (prompt) {
  346. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  347. faux_str_free(prompt);
  348. }
  349. // Add hotkeys
  350. if (view_was_changed)
  351. add_hotkeys_to_msg(ktpd, ack);
  352. faux_msg_send_async(ack, ktpd->async);
  353. faux_msg_free(ack);
  354. faux_error_free(error);
  355. return ret;
  356. }
  357. static bool_t ktpd_session_exec(ktpd_session_t *ktpd, const char *line,
  358. int *retcode, faux_error_t *error,
  359. bool_t dry_run, bool_t *view_was_changed_p)
  360. {
  361. kexec_t *exec = NULL;
  362. assert(ktpd);
  363. if (!ktpd)
  364. return BOOL_FALSE;
  365. // Parsing
  366. exec = ksession_parse_for_exec(ktpd->session, line, error);
  367. if (!exec)
  368. return BOOL_FALSE;
  369. // Set dry-run flag
  370. kexec_set_dry_run(exec, dry_run);
  371. // Session status can be changed while parsing
  372. // NOTE: kexec_t is atomic now
  373. // if (ksession_done(ktpd->session)) {
  374. // kexec_free(exec);
  375. // return BOOL_FALSE; // Because action is not completed
  376. // }
  377. // Execute kexec and then wait for completion using global Eloop
  378. if (!kexec_exec(exec)) {
  379. kexec_free(exec);
  380. return BOOL_FALSE; // Something went wrong
  381. }
  382. // If kexec contains only non-exec (for example dry-run) ACTIONs then
  383. // we don't need event loop and can return here.
  384. if (kexec_retcode(exec, retcode)) {
  385. if (view_was_changed_p)
  386. *view_was_changed_p = !kpath_is_equal(
  387. ksession_path(ktpd->session),
  388. kexec_saved_path(exec));
  389. kexec_free(exec);
  390. return BOOL_TRUE;
  391. }
  392. // Save kexec pointer to use later
  393. ktpd->state = KTPD_SESSION_STATE_WAIT_FOR_PROCESS;
  394. ktpd->exec = exec;
  395. // Set stdin, stdout, stderr handlers. It's so complex because stdin,
  396. // stdout and stderr actually can be the same fd
  397. faux_eloop_add_fd(ktpd->eloop, kexec_stdin(exec), 0,
  398. action_stdout_ev, ktpd);
  399. faux_eloop_add_fd(ktpd->eloop, kexec_stdout(exec), 0,
  400. action_stdout_ev, ktpd);
  401. faux_eloop_add_fd(ktpd->eloop, kexec_stderr(exec), 0,
  402. action_stderr_ev, ktpd);
  403. faux_eloop_include_fd_event(ktpd->eloop, kexec_stdout(exec), POLLIN);
  404. faux_eloop_include_fd_event(ktpd->eloop, kexec_stderr(exec), POLLIN);
  405. return BOOL_TRUE;
  406. }
  407. static bool_t wait_for_actions_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  408. void *associated_data, void *user_data)
  409. {
  410. int wstatus = 0;
  411. pid_t child_pid = -1;
  412. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  413. int retcode = -1;
  414. uint8_t retcode8bit = 0;
  415. faux_msg_t *ack = NULL;
  416. ktp_cmd_e cmd = KTP_CMD_ACK;
  417. uint32_t status = KTP_STATUS_NONE;
  418. char *prompt = NULL;
  419. bool_t view_was_changed = BOOL_FALSE;
  420. if (!ktpd)
  421. return BOOL_FALSE;
  422. // Wait for any child process. Doesn't block.
  423. while ((child_pid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
  424. if (ktpd->exec)
  425. kexec_continue_command_execution(ktpd->exec, child_pid,
  426. wstatus);
  427. }
  428. if (!ktpd->exec)
  429. return BOOL_TRUE;
  430. // Check if kexec is done now
  431. if (!kexec_retcode(ktpd->exec, &retcode))
  432. return BOOL_TRUE; // Continue
  433. // Sometimes SIGCHILD signal can appear before all data were really read
  434. // from process stdout buffer. So read the least data before closing
  435. // file descriptors and send it to client.
  436. get_stream(ktpd, kexec_stdout(ktpd->exec), BOOL_FALSE);
  437. get_stream(ktpd, kexec_stderr(ktpd->exec), BOOL_TRUE);
  438. faux_eloop_del_fd(eloop, kexec_stdin(ktpd->exec));
  439. faux_eloop_del_fd(eloop, kexec_stdout(ktpd->exec));
  440. faux_eloop_del_fd(eloop, kexec_stderr(ktpd->exec));
  441. view_was_changed = !kpath_is_equal(
  442. ksession_path(ktpd->session), kexec_saved_path(ktpd->exec));
  443. kexec_free(ktpd->exec);
  444. ktpd->exec = NULL;
  445. ktpd->state = KTPD_SESSION_STATE_IDLE;
  446. // All kexec_t actions are done so can break the loop if needed.
  447. if (ksession_done(ktpd->session)) {
  448. ktpd->exit = BOOL_TRUE;
  449. status |= KTP_STATUS_EXIT; // Notify client about exiting
  450. }
  451. // Send ACK message
  452. ack = ktp_msg_preform(cmd, status);
  453. retcode8bit = (uint8_t)(retcode & 0xff);
  454. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  455. // Generate prompt
  456. prompt = generate_prompt(ktpd);
  457. if (prompt) {
  458. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  459. faux_str_free(prompt);
  460. }
  461. // Add hotkeys
  462. if (view_was_changed)
  463. add_hotkeys_to_msg(ktpd, ack);
  464. faux_msg_send_async(ack, ktpd->async);
  465. faux_msg_free(ack);
  466. type = type; // Happy compiler
  467. associated_data = associated_data; // Happy compiler
  468. if (ktpd->exit)
  469. return BOOL_FALSE;
  470. return BOOL_TRUE;
  471. }
  472. static int compl_compare(const void *first, const void *second)
  473. {
  474. const char *f = (const char *)first;
  475. const char *s = (const char *)second;
  476. return strcmp(f, s);
  477. }
  478. static int compl_kcompare(const void *key, const void *list_item)
  479. {
  480. const char *f = (const char *)key;
  481. const char *s = (const char *)list_item;
  482. return strcmp(f, s);
  483. }
  484. static bool_t ktpd_session_process_completion(ktpd_session_t *ktpd, faux_msg_t *msg)
  485. {
  486. char *line = NULL;
  487. faux_msg_t *ack = NULL;
  488. kpargv_t *pargv = NULL;
  489. ktp_cmd_e cmd = KTP_COMPLETION_ACK;
  490. uint32_t status = KTP_STATUS_NONE;
  491. const char *prefix = NULL;
  492. size_t prefix_len = 0;
  493. assert(ktpd);
  494. assert(msg);
  495. // Get line from message
  496. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  497. ktp_send_error(ktpd->async, cmd, NULL);
  498. return BOOL_FALSE;
  499. }
  500. // Parsing
  501. pargv = ksession_parse_for_completion(ktpd->session, line);
  502. faux_str_free(line);
  503. if (!pargv) {
  504. ktp_send_error(ktpd->async, cmd, NULL);
  505. return BOOL_FALSE;
  506. }
  507. kpargv_debug(pargv);
  508. if (ksession_done(ktpd->session)) {
  509. ktpd->exit = BOOL_TRUE;
  510. status |= KTP_STATUS_EXIT; // Notify client about exiting
  511. }
  512. // Prepare ACK message
  513. ack = ktp_msg_preform(cmd, status);
  514. // Last unfinished word. Common prefix for all completions
  515. prefix = kpargv_last_arg(pargv);
  516. if (!faux_str_is_empty(prefix)) {
  517. prefix_len = strlen(prefix);
  518. faux_msg_add_param(ack, KTP_PARAM_PREFIX, prefix, prefix_len);
  519. }
  520. // Fill msg with possible completions
  521. if (!kpargv_completions_is_empty(pargv)) {
  522. const kentry_t *candidate = NULL;
  523. kpargv_completions_node_t *citer = kpargv_completions_iter(pargv);
  524. faux_list_node_t *compl_iter = NULL;
  525. faux_list_t *completions = NULL;
  526. char *compl_str = NULL;
  527. completions = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  528. compl_compare, compl_kcompare,
  529. (void (*)(void *))faux_str_free);
  530. while ((candidate = kpargv_completions_each(&citer))) {
  531. const kentry_t *completion = NULL;
  532. kparg_t *parg = NULL;
  533. int rc = -1;
  534. char *out = NULL;
  535. bool_t res = BOOL_FALSE;
  536. char *l = NULL; // One line of completion
  537. const char *str = NULL;
  538. // Get completion entry from candidate entry
  539. completion = kentry_nested_by_purpose(candidate,
  540. KENTRY_PURPOSE_COMPLETION);
  541. // If candidate entry doesn't contain completion then try
  542. // to get completion from entry's PTYPE
  543. if (!completion) {
  544. const kentry_t *ptype = NULL;
  545. ptype = kentry_nested_by_purpose(candidate,
  546. KENTRY_PURPOSE_PTYPE);
  547. if (!ptype)
  548. continue;
  549. completion = kentry_nested_by_purpose(ptype,
  550. KENTRY_PURPOSE_COMPLETION);
  551. }
  552. if (!completion)
  553. continue;
  554. parg = kparg_new(candidate, prefix);
  555. kpargv_set_candidate_parg(pargv, parg);
  556. res = ksession_exec_locally(ktpd->session, completion,
  557. pargv, &rc, &out);
  558. kparg_free(parg);
  559. if (!res || (rc < 0) || !out) {
  560. if (out)
  561. faux_str_free(out);
  562. continue;
  563. }
  564. // Get all completions one by one
  565. str = out;
  566. while ((l = faux_str_getline(str, &str))) {
  567. // Compare prefix
  568. if ((prefix_len > 0) &&
  569. (faux_str_cmpn(prefix, l, prefix_len) != 0)) {
  570. faux_str_free(l);
  571. continue;
  572. }
  573. compl_str = l + prefix_len;
  574. faux_list_add(completions, faux_str_dup(compl_str));
  575. faux_str_free(l);
  576. }
  577. faux_str_free(out);
  578. }
  579. // Put completion list to message
  580. compl_iter = faux_list_head(completions);
  581. while ((compl_str = faux_list_each(&compl_iter))) {
  582. faux_msg_add_param(ack, KTP_PARAM_LINE,
  583. compl_str, strlen(compl_str));
  584. }
  585. faux_list_free(completions);
  586. }
  587. faux_msg_send_async(ack, ktpd->async);
  588. faux_msg_free(ack);
  589. kpargv_free(pargv);
  590. return BOOL_TRUE;
  591. }
  592. // The most priority source of help is candidate's help ACTION output. Next
  593. // source is candidate's PTYPE help ACTION output.
  594. // Function generates two lines for one resulting help line. The first
  595. // component is a 'prefix' and the second component is 'text'.
  596. // The 'prefix' can be something like 'ip', 'filter' i.e.
  597. // subcommand or '3..89', '<STRING>' i.e. description of type. The 'text'
  598. // field is description of current parameter. For example 'Interface IP
  599. // address'. So the full help can be:
  600. // AAA.BBB.CCC.DDD Interface IP address
  601. // [ first field ] [ second field ]
  602. //
  603. // If not candidate parameter nor PTYPE contains the help functions the engine
  604. // tries to construct help itself.
  605. //
  606. // It uses the following sources for 'prefix':
  607. // * 'help' field of PTYPE
  608. // * 'value' field of PTYPE
  609. // * 'name' field of PTYPE
  610. // * 'value' field of parameter
  611. // * 'name' field of parameter
  612. //
  613. // Engine uses the following sources for 'text':
  614. // * 'help' field of parameter
  615. // * 'value' field of parameter
  616. // * 'name' field of parameter
  617. static bool_t ktpd_session_process_help(ktpd_session_t *ktpd, faux_msg_t *msg)
  618. {
  619. char *line = NULL;
  620. faux_msg_t *ack = NULL;
  621. kpargv_t *pargv = NULL;
  622. ktp_cmd_e cmd = KTP_HELP_ACK;
  623. uint32_t status = KTP_STATUS_NONE;
  624. const char *prefix = NULL;
  625. assert(ktpd);
  626. assert(msg);
  627. // Get line from message
  628. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  629. ktp_send_error(ktpd->async, cmd, NULL);
  630. return BOOL_FALSE;
  631. }
  632. // Parsing
  633. pargv = ksession_parse_for_completion(ktpd->session, line);
  634. faux_str_free(line);
  635. if (!pargv) {
  636. ktp_send_error(ktpd->async, cmd, NULL);
  637. return BOOL_FALSE;
  638. }
  639. if (ksession_done(ktpd->session)) {
  640. ktpd->exit = BOOL_TRUE;
  641. status |= KTP_STATUS_EXIT; // Notify client about exiting
  642. }
  643. // Prepare ACK message
  644. ack = ktp_msg_preform(cmd, status);
  645. // Last unfinished word. Common prefix for all entries
  646. prefix = kpargv_last_arg(pargv);
  647. // Fill msg with possible help messages
  648. if (!kpargv_completions_is_empty(pargv)) {
  649. const kentry_t *candidate = NULL;
  650. kpargv_completions_node_t *citer = kpargv_completions_iter(pargv);
  651. faux_list_node_t *help_iter = NULL;
  652. faux_list_t *help_list = NULL;
  653. help_t *help_struct = NULL;
  654. help_list = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  655. help_compare, NULL, help_free);
  656. while ((candidate = kpargv_completions_each(&citer))) {
  657. const kentry_t *help = NULL;
  658. const kentry_t *ptype = NULL;
  659. // Get PTYPE of parameter
  660. ptype = kentry_nested_by_purpose(candidate,
  661. KENTRY_PURPOSE_PTYPE);
  662. // Try to get help fn from parameter itself
  663. help = kentry_nested_by_purpose(candidate,
  664. KENTRY_PURPOSE_HELP);
  665. if (!help && ptype)
  666. help = kentry_nested_by_purpose(ptype,
  667. KENTRY_PURPOSE_HELP);
  668. // Generate help with found ACTION
  669. if (help) {
  670. char *out = NULL;
  671. kparg_t *parg = NULL;
  672. int rc = -1;
  673. parg = kparg_new(candidate, prefix);
  674. kpargv_set_candidate_parg(pargv, parg);
  675. ksession_exec_locally(ktpd->session,
  676. help, pargv, &rc, &out);
  677. kparg_free(parg);
  678. if (out) {
  679. const char *str = out;
  680. char *prefix_str = NULL;
  681. char *line_str = NULL;
  682. do {
  683. prefix_str = faux_str_getline(str, &str);
  684. if (!prefix_str)
  685. break;
  686. line_str = faux_str_getline(str, &str);
  687. if (!line_str) {
  688. faux_str_free(prefix_str);
  689. break;
  690. }
  691. help_struct = help_new(prefix_str, line_str);
  692. if (!faux_list_add(help_list, help_struct))
  693. help_free(help_struct);
  694. } while (line_str);
  695. faux_str_free(out);
  696. }
  697. // Generate help with available information
  698. } else {
  699. const char *prefix_str = NULL;
  700. const char *line_str = NULL;
  701. // Prefix_str
  702. if (ptype) {
  703. prefix_str = kentry_help(ptype);
  704. if (!prefix_str)
  705. prefix_str = kentry_value(ptype);
  706. if (!prefix_str)
  707. prefix_str = kentry_name(ptype);
  708. } else {
  709. prefix_str = kentry_value(candidate);
  710. if (!prefix_str)
  711. prefix_str = kentry_name(candidate);
  712. }
  713. assert(prefix_str);
  714. // Line_str
  715. line_str = kentry_help(candidate);
  716. if (!line_str)
  717. line_str = kentry_value(candidate);
  718. if (!line_str)
  719. line_str = kentry_name(candidate);
  720. assert(line_str);
  721. help_struct = help_new(
  722. faux_str_dup(prefix_str),
  723. faux_str_dup(line_str));
  724. if (!faux_list_add(help_list, help_struct))
  725. help_free(help_struct);
  726. }
  727. }
  728. // Put help list to message
  729. help_iter = faux_list_head(help_list);
  730. while ((help_struct = (help_t *)faux_list_each(&help_iter))) {
  731. faux_msg_add_param(ack, KTP_PARAM_PREFIX,
  732. help_struct->prefix, strlen(help_struct->prefix));
  733. faux_msg_add_param(ack, KTP_PARAM_LINE,
  734. help_struct->line, strlen(help_struct->line));
  735. }
  736. faux_list_free(help_list);
  737. }
  738. faux_msg_send_async(ack, ktpd->async);
  739. faux_msg_free(ack);
  740. kpargv_free(pargv);
  741. return BOOL_TRUE;
  742. }
  743. static ssize_t stdin_out(int fd, faux_buf_t *buf)
  744. {
  745. ssize_t total_written = 0;
  746. assert(buf);
  747. if (!buf)
  748. return -1;
  749. assert(fd >= 0);
  750. while (faux_buf_len(buf) > 0) {
  751. ssize_t data_to_write = 0;
  752. ssize_t bytes_written = 0;
  753. void *data = NULL;
  754. data_to_write = faux_buf_dread_lock_easy(buf, &data);
  755. if (data_to_write <= 0)
  756. return -1;
  757. bytes_written = write(fd, data, data_to_write);
  758. if (bytes_written > 0) {
  759. total_written += bytes_written;
  760. faux_buf_dread_unlock_easy(buf, bytes_written);
  761. } else {
  762. faux_buf_dread_unlock_easy(buf, 0);
  763. }
  764. if (bytes_written < 0) {
  765. if ( // Something went wrong
  766. (errno != EINTR) &&
  767. (errno != EAGAIN) &&
  768. (errno != EWOULDBLOCK)
  769. )
  770. return -1;
  771. // Not whole data block was written
  772. } else if (bytes_written != data_to_write) {
  773. break;
  774. }
  775. }
  776. return total_written;
  777. }
  778. static bool_t push_stdin(ktpd_session_t *ktpd)
  779. {
  780. faux_buf_t *bufin = NULL;
  781. int fd = -1;
  782. if (!ktpd)
  783. return BOOL_TRUE;
  784. if (!ktpd->exec)
  785. return BOOL_TRUE;
  786. fd = kexec_stdin(ktpd->exec);
  787. if (fd < 0) // May be fd is already closed
  788. return BOOL_FALSE;
  789. bufin = kexec_bufin(ktpd->exec);
  790. assert(bufin);
  791. stdin_out(fd, bufin); // Non-blocking write
  792. if (faux_buf_len(bufin) != 0) // Try later
  793. return BOOL_TRUE;
  794. // All data is written
  795. faux_eloop_exclude_fd_event(ktpd->eloop, fd, POLLOUT);
  796. if (ktpd->stdin_must_be_closed) {
  797. close(fd);
  798. // kexec_set_stdin(ktpd->exec, -1);
  799. }
  800. return BOOL_TRUE;
  801. }
  802. static bool_t ktpd_session_process_stdin(ktpd_session_t *ktpd, faux_msg_t *msg)
  803. {
  804. char *line = NULL;
  805. unsigned int len = 0;
  806. faux_buf_t *bufin = NULL;
  807. int fd = -1;
  808. bool_t interrupt = BOOL_FALSE;
  809. const kaction_t *action = NULL;
  810. assert(ktpd);
  811. assert(msg);
  812. if (!ktpd->exec)
  813. return BOOL_FALSE;
  814. fd = kexec_stdin(ktpd->exec);
  815. if (fd < 0)
  816. return BOOL_FALSE;
  817. if (!faux_msg_get_param_by_type(msg, KTP_PARAM_LINE, (void **)&line, &len))
  818. return BOOL_TRUE; // It's strange but not a bug
  819. if (len == 0)
  820. return BOOL_TRUE;
  821. bufin = kexec_bufin(ktpd->exec);
  822. assert(bufin);
  823. action = kexec_current_action(ktpd->exec);
  824. if (action)
  825. interrupt = kaction_interrupt(action);
  826. // If current action is non-interruptible and action's stdin is terminal
  827. // then remove ^C (0x03) symbol from stdin stream to don't deliver
  828. // SIGINT to process
  829. if (isatty(fd) && !interrupt) {
  830. // 0x03 is a ^C
  831. const char chars_to_search[] = {0x03, 0};
  832. const char *start = line;
  833. const char *pos = NULL;
  834. size_t cur_len = len;
  835. while ((pos = faux_str_charsn(start, chars_to_search, cur_len))) {
  836. size_t written = pos - start;
  837. faux_buf_write(bufin, start, written);
  838. start = pos + 1;
  839. cur_len = cur_len - written - 1;
  840. }
  841. if (cur_len > 0)
  842. faux_buf_write(bufin, start, cur_len);
  843. } else {
  844. faux_buf_write(bufin, line, len);
  845. }
  846. stdin_out(fd, bufin); // Non-blocking write
  847. if (faux_buf_len(bufin) == 0)
  848. return BOOL_TRUE;
  849. // Non-blocking write can't write all data so plan to write later
  850. faux_eloop_include_fd_event(ktpd->eloop, fd, POLLOUT);
  851. return BOOL_TRUE;
  852. }
  853. static bool_t ktpd_session_process_winch(ktpd_session_t *ktpd, faux_msg_t *msg)
  854. {
  855. char *line = NULL;
  856. char *p = NULL;
  857. unsigned short width = 0;
  858. unsigned short height = 0;
  859. assert(ktpd);
  860. assert(msg);
  861. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_WINCH)))
  862. return BOOL_TRUE;
  863. p = strchr(line, ' ');
  864. if (!p || (p == line)) {
  865. faux_str_free(line);
  866. return BOOL_FALSE;
  867. }
  868. if (!faux_conv_atous(line, &width, 0)) {
  869. faux_str_free(line);
  870. return BOOL_FALSE;
  871. }
  872. if (!faux_conv_atous(p + 1, &height, 0)) {
  873. faux_str_free(line);
  874. return BOOL_FALSE;
  875. }
  876. ksession_set_term_width(ktpd->session, width);
  877. ksession_set_term_height(ktpd->session, height);
  878. faux_str_free(line);
  879. if (!ktpd->exec)
  880. return BOOL_TRUE;
  881. // Set pseudo terminal window size
  882. kexec_set_winsize(ktpd->exec);
  883. return BOOL_TRUE;
  884. }
  885. static bool_t ktpd_session_process_notification(ktpd_session_t *ktpd, faux_msg_t *msg)
  886. {
  887. assert(ktpd);
  888. assert(msg);
  889. ktpd_session_process_winch(ktpd, msg);
  890. return BOOL_TRUE;
  891. }
  892. static bool_t ktpd_session_process_stdin_close(ktpd_session_t *ktpd,
  893. faux_msg_t *msg)
  894. {
  895. int fd = -1;
  896. assert(ktpd);
  897. assert(msg);
  898. if (!ktpd->exec)
  899. return BOOL_FALSE;
  900. fd = kexec_stdin(ktpd->exec);
  901. if (fd < 0)
  902. return BOOL_FALSE;
  903. // Schedule to close stdin
  904. ktpd->stdin_must_be_closed = BOOL_TRUE;
  905. push_stdin(ktpd);
  906. return BOOL_TRUE;
  907. }
  908. static bool_t ktpd_session_process_stdout_close(ktpd_session_t *ktpd,
  909. faux_msg_t *msg)
  910. {
  911. int fd = -1;
  912. assert(ktpd);
  913. assert(msg);
  914. if (!ktpd->exec)
  915. return BOOL_FALSE;
  916. fd = kexec_stdout(ktpd->exec);
  917. if (fd < 0)
  918. return BOOL_FALSE;
  919. close(fd);
  920. // Remove already generated data from out buffer. This data is not
  921. // needed now
  922. faux_buf_empty(kexec_bufout(ktpd->exec));
  923. return BOOL_TRUE;
  924. }
  925. static bool_t ktpd_session_process_stderr_close(ktpd_session_t *ktpd,
  926. faux_msg_t *msg)
  927. {
  928. int fd = -1;
  929. assert(ktpd);
  930. assert(msg);
  931. if (!ktpd->exec)
  932. return BOOL_FALSE;
  933. fd = kexec_stderr(ktpd->exec);
  934. if (fd < 0)
  935. return BOOL_FALSE;
  936. close(fd);
  937. // Remove already generated data from err buffer. This data is not
  938. // needed any more
  939. faux_buf_empty(kexec_buferr(ktpd->exec));
  940. return BOOL_TRUE;
  941. }
  942. static bool_t ktpd_session_dispatch(ktpd_session_t *ktpd, faux_msg_t *msg)
  943. {
  944. uint16_t cmd = 0;
  945. const char *err = NULL;
  946. ktp_cmd_e ecmd = KTP_NOTIFICATION; // Answer command if error
  947. assert(ktpd);
  948. if (!ktpd)
  949. return BOOL_FALSE;
  950. assert(msg);
  951. if (!msg)
  952. return BOOL_FALSE;
  953. cmd = faux_msg_get_cmd(msg);
  954. switch (cmd) {
  955. case KTP_AUTH:
  956. if ((ktpd->state != KTPD_SESSION_STATE_UNAUTHORIZED) &&
  957. (ktpd->state != KTPD_SESSION_STATE_IDLE)) {
  958. ecmd = KTP_AUTH_ACK;
  959. err = "Server illegal state for authorization";
  960. break;
  961. }
  962. ktpd_session_process_auth(ktpd, msg);
  963. break;
  964. case KTP_CMD:
  965. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  966. ecmd = KTP_CMD_ACK;
  967. err = "Server illegal state for command execution";
  968. break;
  969. }
  970. ktpd_session_process_cmd(ktpd, msg);
  971. break;
  972. case KTP_COMPLETION:
  973. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  974. ecmd = KTP_COMPLETION_ACK;
  975. err = "Server illegal state for completion";
  976. break;
  977. }
  978. ktpd_session_process_completion(ktpd, msg);
  979. break;
  980. case KTP_HELP:
  981. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  982. ecmd = KTP_HELP_ACK;
  983. err = "Server illegal state for help";
  984. break;
  985. }
  986. ktpd_session_process_help(ktpd, msg);
  987. break;
  988. case KTP_STDIN:
  989. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  990. err = "Nobody is waiting for stdin";
  991. break;
  992. }
  993. ktpd_session_process_stdin(ktpd, msg);
  994. break;
  995. case KTP_NOTIFICATION:
  996. ktpd_session_process_notification(ktpd, msg);
  997. break;
  998. case KTP_STDIN_CLOSE:
  999. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1000. err = "No active command is running";
  1001. break;
  1002. }
  1003. ktpd_session_process_stdin_close(ktpd, msg);
  1004. break;
  1005. case KTP_STDOUT_CLOSE:
  1006. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1007. err = "No active command is running";
  1008. break;
  1009. }
  1010. ktpd_session_process_stdout_close(ktpd, msg);
  1011. break;
  1012. case KTP_STDERR_CLOSE:
  1013. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1014. err = "No active command is running";
  1015. break;
  1016. }
  1017. ktpd_session_process_stderr_close(ktpd, msg);
  1018. break;
  1019. default:
  1020. syslog(LOG_WARNING, "Unsupported command: 0x%04u", cmd);
  1021. err = "Unsupported command";
  1022. break;
  1023. }
  1024. // On error
  1025. if (err)
  1026. ktp_send_error(ktpd->async, ecmd, err);
  1027. return BOOL_TRUE;
  1028. }
  1029. /** @brief Low-level function to receive KTP message.
  1030. *
  1031. * Firstly function gets the header of message. Then it checks and parses
  1032. * header and find out the length of whole message. Then it receives the rest
  1033. * of message.
  1034. */
  1035. static bool_t ktpd_session_read_cb(faux_async_t *async,
  1036. faux_buf_t *buf, size_t len, void *user_data)
  1037. {
  1038. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1039. faux_msg_t *completed_msg = NULL;
  1040. char *data = NULL;
  1041. assert(async);
  1042. assert(buf);
  1043. assert(ktpd);
  1044. // Linearize buffer
  1045. data = malloc(len);
  1046. faux_buf_read(buf, data, len);
  1047. // Receive header
  1048. if (!ktpd->hdr) {
  1049. size_t whole_len = 0;
  1050. size_t msg_wo_hdr = 0;
  1051. ktpd->hdr = (faux_hdr_t *)data;
  1052. // Check for broken header
  1053. if (!ktp_check_header(ktpd->hdr)) {
  1054. faux_free(ktpd->hdr);
  1055. ktpd->hdr = NULL;
  1056. return BOOL_FALSE;
  1057. }
  1058. whole_len = faux_hdr_len(ktpd->hdr);
  1059. // msg_wo_hdr >= 0 because ktp_check_header() validates whole_len
  1060. msg_wo_hdr = whole_len - sizeof(faux_hdr_t);
  1061. // Plan to receive message body
  1062. if (msg_wo_hdr > 0) {
  1063. faux_async_set_read_limits(async,
  1064. msg_wo_hdr, msg_wo_hdr);
  1065. return BOOL_TRUE;
  1066. }
  1067. // Here message is completed (msg body has zero length)
  1068. completed_msg = faux_msg_deserialize_parts(ktpd->hdr, NULL, 0);
  1069. // Receive message body
  1070. } else {
  1071. completed_msg = faux_msg_deserialize_parts(ktpd->hdr, data, len);
  1072. faux_free(data);
  1073. }
  1074. // Plan to receive msg header
  1075. faux_async_set_read_limits(ktpd->async,
  1076. sizeof(faux_hdr_t), sizeof(faux_hdr_t));
  1077. faux_free(ktpd->hdr);
  1078. ktpd->hdr = NULL; // Ready to recv new header
  1079. // Here message is completed
  1080. ktpd_session_dispatch(ktpd, completed_msg);
  1081. faux_msg_free(completed_msg);
  1082. return BOOL_TRUE;
  1083. }
  1084. bool_t ktpd_session_connected(ktpd_session_t *ktpd)
  1085. {
  1086. assert(ktpd);
  1087. if (!ktpd)
  1088. return BOOL_FALSE;
  1089. if (KTPD_SESSION_STATE_DISCONNECTED == ktpd->state)
  1090. return BOOL_FALSE;
  1091. return BOOL_TRUE;
  1092. }
  1093. int ktpd_session_fd(const ktpd_session_t *ktpd)
  1094. {
  1095. assert(ktpd);
  1096. if (!ktpd)
  1097. return BOOL_FALSE;
  1098. return faux_async_fd(ktpd->async);
  1099. }
  1100. static bool_t get_stream(ktpd_session_t *ktpd, int fd, bool_t is_stderr)
  1101. {
  1102. ssize_t r = -1;
  1103. faux_buf_t *faux_buf = NULL;
  1104. char *buf = NULL;
  1105. ssize_t len = 0;
  1106. faux_msg_t *ack = NULL;
  1107. if (!ktpd)
  1108. return BOOL_TRUE;
  1109. if (!ktpd->exec)
  1110. return BOOL_TRUE;
  1111. if (is_stderr)
  1112. faux_buf = kexec_buferr(ktpd->exec);
  1113. else
  1114. faux_buf = kexec_bufout(ktpd->exec);
  1115. assert(faux_buf);
  1116. do {
  1117. void *linear_buf = NULL;
  1118. ssize_t really_readed = 0;
  1119. ssize_t linear_len =
  1120. faux_buf_dwrite_lock_easy(faux_buf, &linear_buf);
  1121. // Non-blocked read. The fd became non-blocked while
  1122. // kexec_prepare().
  1123. r = read(fd, linear_buf, linear_len);
  1124. if (r > 0)
  1125. really_readed = r;
  1126. faux_buf_dwrite_unlock_easy(faux_buf, really_readed);
  1127. } while (r > 0);
  1128. len = faux_buf_len(faux_buf);
  1129. if (0 == len)
  1130. return BOOL_TRUE;
  1131. buf = malloc(len);
  1132. faux_buf_read(faux_buf, buf, len);
  1133. // Create KTP_STDOUT/KTP_STDERR message to send to client
  1134. ack = ktp_msg_preform(is_stderr ? KTP_STDERR : KTP_STDOUT, KTP_STATUS_NONE);
  1135. faux_msg_add_param(ack, KTP_PARAM_LINE, buf, len);
  1136. faux_msg_send_async(ack, ktpd->async);
  1137. faux_msg_free(ack);
  1138. free(buf);
  1139. return BOOL_TRUE;
  1140. }
  1141. static bool_t action_stdout_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1142. void *associated_data, void *user_data)
  1143. {
  1144. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1145. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1146. // Interactive command use these function as callback not only for
  1147. // getting stdout but for writing stdin too. Because pseudo-terminal
  1148. // uses the same fd for in and out.
  1149. if (info->revents & POLLOUT)
  1150. push_stdin(ktpd);
  1151. if (info->revents & POLLIN)
  1152. get_stream(ktpd, info->fd, BOOL_FALSE);
  1153. // Some errors or fd is closed so remove it from polling
  1154. // EOF || POLERR || POLLNVAL
  1155. if (info->revents & (POLLHUP | POLLERR | POLLNVAL))
  1156. faux_eloop_del_fd(eloop, info->fd);
  1157. type = type; // Happy compiler
  1158. return BOOL_TRUE;
  1159. }
  1160. static bool_t action_stderr_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1161. void *associated_data, void *user_data)
  1162. {
  1163. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1164. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1165. if (info->revents & POLLIN)
  1166. get_stream(ktpd, info->fd, BOOL_TRUE);
  1167. // Some errors or fd is closed so remove it from polling
  1168. // EOF || POLERR || POLLNVAL
  1169. if (info->revents & (POLLHUP | POLLERR | POLLNVAL))
  1170. faux_eloop_del_fd(eloop, info->fd);
  1171. type = type; // Happy compiler
  1172. return BOOL_TRUE;
  1173. }
  1174. bool_t client_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1175. void *associated_data, void *user_data)
  1176. {
  1177. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1178. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1179. faux_async_t *async = ktpd->async;
  1180. assert(async);
  1181. // Write data
  1182. if (info->revents & POLLOUT) {
  1183. faux_eloop_exclude_fd_event(eloop, info->fd, POLLOUT);
  1184. if (faux_async_out(async) < 0) {
  1185. // Someting went wrong
  1186. faux_eloop_del_fd(eloop, info->fd);
  1187. syslog(LOG_ERR, "Can't send data to client");
  1188. return BOOL_FALSE; // Stop event loop
  1189. }
  1190. }
  1191. // Read data
  1192. if (info->revents & POLLIN) {
  1193. if (faux_async_in(async) < 0) {
  1194. // Someting went wrong
  1195. faux_eloop_del_fd(eloop, info->fd);
  1196. syslog(LOG_ERR, "Can't get data from client");
  1197. return BOOL_FALSE; // Stop event loop
  1198. }
  1199. }
  1200. // EOF
  1201. if (info->revents & POLLHUP) {
  1202. faux_eloop_del_fd(eloop, info->fd);
  1203. syslog(LOG_DEBUG, "Connection %d is closed by client", info->fd);
  1204. return BOOL_FALSE; // Stop event loop
  1205. }
  1206. // POLLERR
  1207. if (info->revents & POLLERR) {
  1208. faux_eloop_del_fd(eloop, info->fd);
  1209. syslog(LOG_DEBUG, "POLLERR received %d", info->fd);
  1210. return BOOL_FALSE; // Stop event loop
  1211. }
  1212. // POLLNVAL
  1213. if (info->revents & POLLNVAL) {
  1214. faux_eloop_del_fd(eloop, info->fd);
  1215. syslog(LOG_DEBUG, "POLLNVAL received %d", info->fd);
  1216. return BOOL_FALSE; // Stop event loop
  1217. }
  1218. type = type; // Happy compiler
  1219. // Session can be really finished here. Note KTPD session can't be
  1220. // stopped immediately so it's only two places within code to really
  1221. // break the loop. This one and within wait_for_action_ev().
  1222. if (ktpd->exit)
  1223. return BOOL_FALSE;
  1224. return BOOL_TRUE;
  1225. }
  1226. #if 0
  1227. static void ktpd_session_bad_socket(ktpd_session_t *ktpd)
  1228. {
  1229. assert(ktpd);
  1230. if (!ktpd)
  1231. return;
  1232. ktpd->state = KTPD_SESSION_STATE_DISCONNECTED;
  1233. }
  1234. #endif