ktpd_session.c 39 KB

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