ktpd_session.c 38 KB

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