ktpd_session.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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. assert(ktpd);
  300. assert(msg);
  301. // Get line from message
  302. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  303. ktp_send_error(ktpd->async, cmd, "The line is not specified");
  304. return BOOL_FALSE;
  305. }
  306. // Get dry-run flag from message
  307. if (KTP_STATUS_IS_DRY_RUN(faux_msg_get_status(msg)))
  308. dry_run = BOOL_TRUE;
  309. error = faux_error_new();
  310. ktpd->exec = NULL;
  311. rc = ktpd_session_exec(ktpd, line, &retcode, error,
  312. dry_run, &view_was_changed);
  313. faux_str_free(line);
  314. // Command is scheduled. Eloop will wait for ACTION completion.
  315. // So inform client about it and about command features like
  316. // interactive/non-interactive.
  317. if (ktpd->exec) {
  318. faux_msg_t *ack = NULL;
  319. ktp_status_e status = KTP_STATUS_INCOMPLETED;
  320. if (kexec_interactive(ktpd->exec))
  321. status |= KTP_STATUS_INTERACTIVE;
  322. if (kexec_need_stdin(ktpd->exec))
  323. status |= KTP_STATUS_NEED_STDIN;
  324. ack = ktp_msg_preform(cmd, status);
  325. faux_msg_send_async(ack, ktpd->async);
  326. faux_msg_free(ack);
  327. faux_error_free(error);
  328. return BOOL_TRUE; // Continue and wait for ACTION
  329. }
  330. // Here we don't need to wait for the action. We have retcode already.
  331. if (ksession_done(ktpd->session)) {
  332. ktpd->exit = BOOL_TRUE;
  333. status |= KTP_STATUS_EXIT;
  334. }
  335. // Prepare ACK message
  336. faux_msg_t *ack = ktp_msg_preform(cmd, status);
  337. if (rc) {
  338. uint8_t retcode8bit = 0;
  339. retcode8bit = (uint8_t)(retcode & 0xff);
  340. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  341. } else {
  342. faux_msg_set_status(ack, KTP_STATUS_ERROR);
  343. char *err = faux_error_cstr(error);
  344. faux_msg_add_param(ack, KTP_PARAM_ERROR, err, strlen(err));
  345. faux_str_free(err);
  346. ret = BOOL_FALSE;
  347. }
  348. // Generate prompt
  349. prompt = generate_prompt(ktpd);
  350. if (prompt) {
  351. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  352. faux_str_free(prompt);
  353. }
  354. // Add hotkeys
  355. if (view_was_changed)
  356. add_hotkeys_to_msg(ktpd, ack);
  357. faux_msg_send_async(ack, ktpd->async);
  358. faux_msg_free(ack);
  359. faux_error_free(error);
  360. return ret;
  361. }
  362. static bool_t ktpd_session_exec(ktpd_session_t *ktpd, const char *line,
  363. int *retcode, faux_error_t *error,
  364. bool_t dry_run, bool_t *view_was_changed_p)
  365. {
  366. kexec_t *exec = NULL;
  367. assert(ktpd);
  368. if (!ktpd)
  369. return BOOL_FALSE;
  370. // Parsing
  371. exec = ksession_parse_for_exec(ktpd->session, line, error);
  372. if (!exec)
  373. return BOOL_FALSE;
  374. // Set dry-run flag
  375. kexec_set_dry_run(exec, dry_run);
  376. // Session status can be changed while parsing
  377. // NOTE: kexec_t is atomic now
  378. // if (ksession_done(ktpd->session)) {
  379. // kexec_free(exec);
  380. // return BOOL_FALSE; // Because action is not completed
  381. // }
  382. // Execute kexec and then wait for completion using global Eloop
  383. if (!kexec_exec(exec)) {
  384. kexec_free(exec);
  385. return BOOL_FALSE; // Something went wrong
  386. }
  387. // If kexec contains only non-exec (for example dry-run) ACTIONs then
  388. // we don't need event loop and can return here.
  389. if (kexec_retcode(exec, retcode)) {
  390. if (view_was_changed_p)
  391. *view_was_changed_p = !kpath_is_equal(
  392. ksession_path(ktpd->session),
  393. kexec_saved_path(exec));
  394. ktpd_session_log(ktpd, 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. ktpd_session_log(ktpd, ktpd->exec);
  448. view_was_changed = !kpath_is_equal(
  449. ksession_path(ktpd->session), kexec_saved_path(ktpd->exec));
  450. kexec_free(ktpd->exec);
  451. ktpd->exec = NULL;
  452. ktpd->state = KTPD_SESSION_STATE_IDLE;
  453. // All kexec_t actions are done so can break the loop if needed.
  454. if (ksession_done(ktpd->session)) {
  455. ktpd->exit = BOOL_TRUE;
  456. status |= KTP_STATUS_EXIT; // Notify client about exiting
  457. }
  458. // Send ACK message
  459. ack = ktp_msg_preform(cmd, status);
  460. retcode8bit = (uint8_t)(retcode & 0xff);
  461. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  462. // Generate prompt
  463. prompt = generate_prompt(ktpd);
  464. if (prompt) {
  465. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  466. faux_str_free(prompt);
  467. }
  468. // Add hotkeys
  469. if (view_was_changed)
  470. add_hotkeys_to_msg(ktpd, ack);
  471. faux_msg_send_async(ack, ktpd->async);
  472. faux_msg_free(ack);
  473. type = type; // Happy compiler
  474. associated_data = associated_data; // Happy compiler
  475. if (ktpd->exit)
  476. return BOOL_FALSE;
  477. return BOOL_TRUE;
  478. }
  479. static bool_t ktpd_session_log(ktpd_session_t *ktpd, const kexec_t *exec)
  480. {
  481. kexec_contexts_node_t *iter = NULL;
  482. kcontext_t *context = NULL;
  483. iter = kexec_contexts_iter(exec);
  484. while ((context = kexec_contexts_each(&iter))) {
  485. const kentry_t *entry = kcontext_command(context);
  486. const kentry_t *log_entry = NULL;
  487. int rc = -1;
  488. if (!entry)
  489. continue;
  490. log_entry = kentry_nested_by_purpose(entry, KENTRY_PURPOSE_LOG);
  491. if (!log_entry)
  492. continue;
  493. if (kentry_actions_len(log_entry) == 0)
  494. continue;
  495. ksession_exec_locally(ktpd->session, log_entry,
  496. kcontext_pargv(context), context, exec, &rc, NULL);
  497. }
  498. return BOOL_TRUE;
  499. }
  500. static int compl_compare(const void *first, const void *second)
  501. {
  502. const char *f = (const char *)first;
  503. const char *s = (const char *)second;
  504. return strcmp(f, s);
  505. }
  506. static int compl_kcompare(const void *key, const void *list_item)
  507. {
  508. const char *f = (const char *)key;
  509. const char *s = (const char *)list_item;
  510. return strcmp(f, s);
  511. }
  512. static bool_t ktpd_session_process_completion(ktpd_session_t *ktpd, faux_msg_t *msg)
  513. {
  514. char *line = NULL;
  515. faux_msg_t *ack = NULL;
  516. kpargv_t *pargv = NULL;
  517. ktp_cmd_e cmd = KTP_COMPLETION_ACK;
  518. uint32_t status = KTP_STATUS_NONE;
  519. const char *prefix = NULL;
  520. size_t prefix_len = 0;
  521. assert(ktpd);
  522. assert(msg);
  523. // Get line from message
  524. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  525. ktp_send_error(ktpd->async, cmd, NULL);
  526. return BOOL_FALSE;
  527. }
  528. // Parsing
  529. pargv = ksession_parse_for_completion(ktpd->session, line);
  530. faux_str_free(line);
  531. if (!pargv) {
  532. ktp_send_error(ktpd->async, cmd, NULL);
  533. return BOOL_FALSE;
  534. }
  535. kpargv_debug(pargv);
  536. if (ksession_done(ktpd->session)) {
  537. ktpd->exit = BOOL_TRUE;
  538. status |= KTP_STATUS_EXIT; // Notify client about exiting
  539. }
  540. // Prepare ACK message
  541. ack = ktp_msg_preform(cmd, status);
  542. // Last unfinished word. Common prefix for all completions
  543. prefix = kpargv_last_arg(pargv);
  544. if (!faux_str_is_empty(prefix)) {
  545. prefix_len = strlen(prefix);
  546. faux_msg_add_param(ack, KTP_PARAM_PREFIX, prefix, prefix_len);
  547. }
  548. // Fill msg with possible completions
  549. if (!kpargv_completions_is_empty(pargv)) {
  550. const kentry_t *candidate = NULL;
  551. kpargv_completions_node_t *citer = kpargv_completions_iter(pargv);
  552. faux_list_node_t *compl_iter = NULL;
  553. faux_list_t *completions = NULL;
  554. char *compl_str = NULL;
  555. completions = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  556. compl_compare, compl_kcompare,
  557. (void (*)(void *))faux_str_free);
  558. while ((candidate = kpargv_completions_each(&citer))) {
  559. const kentry_t *completion = NULL;
  560. kparg_t *parg = NULL;
  561. int rc = -1;
  562. char *out = NULL;
  563. bool_t res = BOOL_FALSE;
  564. char *l = NULL; // One line of completion
  565. const char *str = NULL;
  566. // Get completion entry from candidate entry
  567. completion = kentry_nested_by_purpose(candidate,
  568. KENTRY_PURPOSE_COMPLETION);
  569. // If candidate entry doesn't contain completion then try
  570. // to get completion from entry's PTYPE
  571. if (!completion) {
  572. const kentry_t *ptype = NULL;
  573. ptype = kentry_nested_by_purpose(candidate,
  574. KENTRY_PURPOSE_PTYPE);
  575. if (!ptype)
  576. continue;
  577. completion = kentry_nested_by_purpose(ptype,
  578. KENTRY_PURPOSE_COMPLETION);
  579. }
  580. if (!completion)
  581. continue;
  582. parg = kparg_new(candidate, prefix);
  583. kpargv_set_candidate_parg(pargv, parg);
  584. res = ksession_exec_locally(ktpd->session, completion,
  585. pargv, NULL, NULL, &rc, &out);
  586. kparg_free(parg);
  587. if (!res || (rc < 0) || !out) {
  588. if (out)
  589. faux_str_free(out);
  590. continue;
  591. }
  592. // Get all completions one by one
  593. str = out;
  594. while ((l = faux_str_getline(str, &str))) {
  595. // Compare prefix
  596. if ((prefix_len > 0) &&
  597. (faux_str_cmpn(prefix, l, prefix_len) != 0)) {
  598. faux_str_free(l);
  599. continue;
  600. }
  601. compl_str = l + prefix_len;
  602. faux_list_add(completions, faux_str_dup(compl_str));
  603. faux_str_free(l);
  604. }
  605. faux_str_free(out);
  606. }
  607. // Put completion list to message
  608. compl_iter = faux_list_head(completions);
  609. while ((compl_str = faux_list_each(&compl_iter))) {
  610. faux_msg_add_param(ack, KTP_PARAM_LINE,
  611. compl_str, strlen(compl_str));
  612. }
  613. faux_list_free(completions);
  614. }
  615. faux_msg_send_async(ack, ktpd->async);
  616. faux_msg_free(ack);
  617. kpargv_free(pargv);
  618. return BOOL_TRUE;
  619. }
  620. // The most priority source of help is candidate's help ACTION output. Next
  621. // source is candidate's PTYPE help ACTION output.
  622. // Function generates two lines for one resulting help line. The first
  623. // component is a 'prefix' and the second component is 'text'.
  624. // The 'prefix' can be something like 'ip', 'filter' i.e.
  625. // subcommand or '3..89', '<STRING>' i.e. description of type. The 'text'
  626. // field is description of current parameter. For example 'Interface IP
  627. // address'. So the full help can be:
  628. // AAA.BBB.CCC.DDD Interface IP address
  629. // [ first field ] [ second field ]
  630. //
  631. // If not candidate parameter nor PTYPE contains the help functions the engine
  632. // tries to construct help itself.
  633. //
  634. // It uses the following sources for 'prefix':
  635. // * 'help' field of PTYPE
  636. // * 'value' field of PTYPE
  637. // * 'name' field of PTYPE
  638. // * 'value' field of parameter
  639. // * 'name' field of parameter
  640. //
  641. // Engine uses the following sources for 'text':
  642. // * 'help' field of parameter
  643. // * 'value' field of parameter
  644. // * 'name' field of parameter
  645. static bool_t ktpd_session_process_help(ktpd_session_t *ktpd, faux_msg_t *msg)
  646. {
  647. char *line = NULL;
  648. faux_msg_t *ack = NULL;
  649. kpargv_t *pargv = NULL;
  650. ktp_cmd_e cmd = KTP_HELP_ACK;
  651. uint32_t status = KTP_STATUS_NONE;
  652. const char *prefix = NULL;
  653. assert(ktpd);
  654. assert(msg);
  655. // Get line from message
  656. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  657. ktp_send_error(ktpd->async, cmd, NULL);
  658. return BOOL_FALSE;
  659. }
  660. // Parsing
  661. pargv = ksession_parse_for_completion(ktpd->session, line);
  662. faux_str_free(line);
  663. if (!pargv) {
  664. ktp_send_error(ktpd->async, cmd, NULL);
  665. return BOOL_FALSE;
  666. }
  667. if (ksession_done(ktpd->session)) {
  668. ktpd->exit = BOOL_TRUE;
  669. status |= KTP_STATUS_EXIT; // Notify client about exiting
  670. }
  671. // Prepare ACK message
  672. ack = ktp_msg_preform(cmd, status);
  673. // Last unfinished word. Common prefix for all entries
  674. prefix = kpargv_last_arg(pargv);
  675. // Fill msg with possible help messages
  676. if (!kpargv_completions_is_empty(pargv)) {
  677. const kentry_t *candidate = NULL;
  678. kpargv_completions_node_t *citer = kpargv_completions_iter(pargv);
  679. faux_list_node_t *help_iter = NULL;
  680. faux_list_t *help_list = NULL;
  681. help_t *help_struct = NULL;
  682. help_list = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  683. help_compare, NULL, help_free);
  684. while ((candidate = kpargv_completions_each(&citer))) {
  685. const kentry_t *help = NULL;
  686. const kentry_t *ptype = NULL;
  687. // Get PTYPE of parameter
  688. ptype = kentry_nested_by_purpose(candidate,
  689. KENTRY_PURPOSE_PTYPE);
  690. // Try to get help fn from parameter itself
  691. help = kentry_nested_by_purpose(candidate,
  692. KENTRY_PURPOSE_HELP);
  693. if (!help && ptype)
  694. help = kentry_nested_by_purpose(ptype,
  695. KENTRY_PURPOSE_HELP);
  696. // Generate help with found ACTION
  697. if (help) {
  698. char *out = NULL;
  699. kparg_t *parg = NULL;
  700. int rc = -1;
  701. parg = kparg_new(candidate, prefix);
  702. kpargv_set_candidate_parg(pargv, parg);
  703. ksession_exec_locally(ktpd->session,
  704. help, pargv, NULL, NULL, &rc, &out);
  705. kparg_free(parg);
  706. if (out) {
  707. const char *str = out;
  708. char *prefix_str = NULL;
  709. char *line_str = NULL;
  710. do {
  711. prefix_str = faux_str_getline(str, &str);
  712. if (!prefix_str)
  713. break;
  714. line_str = faux_str_getline(str, &str);
  715. if (!line_str) {
  716. faux_str_free(prefix_str);
  717. break;
  718. }
  719. help_struct = help_new(prefix_str, line_str);
  720. if (!faux_list_add(help_list, help_struct))
  721. help_free(help_struct);
  722. } while (line_str);
  723. faux_str_free(out);
  724. }
  725. // Generate help with available information
  726. } else {
  727. const char *prefix_str = NULL;
  728. const char *line_str = NULL;
  729. // Prefix_str
  730. if (ptype) {
  731. prefix_str = kentry_help(ptype);
  732. if (!prefix_str)
  733. prefix_str = kentry_value(ptype);
  734. if (!prefix_str)
  735. prefix_str = kentry_name(ptype);
  736. } else {
  737. prefix_str = kentry_value(candidate);
  738. if (!prefix_str)
  739. prefix_str = kentry_name(candidate);
  740. }
  741. assert(prefix_str);
  742. // Line_str
  743. line_str = kentry_help(candidate);
  744. if (!line_str)
  745. line_str = kentry_value(candidate);
  746. if (!line_str)
  747. line_str = kentry_name(candidate);
  748. assert(line_str);
  749. help_struct = help_new(
  750. faux_str_dup(prefix_str),
  751. faux_str_dup(line_str));
  752. if (!faux_list_add(help_list, help_struct))
  753. help_free(help_struct);
  754. }
  755. }
  756. // Put help list to message
  757. help_iter = faux_list_head(help_list);
  758. while ((help_struct = (help_t *)faux_list_each(&help_iter))) {
  759. faux_msg_add_param(ack, KTP_PARAM_PREFIX,
  760. help_struct->prefix, strlen(help_struct->prefix));
  761. faux_msg_add_param(ack, KTP_PARAM_LINE,
  762. help_struct->line, strlen(help_struct->line));
  763. }
  764. faux_list_free(help_list);
  765. }
  766. faux_msg_send_async(ack, ktpd->async);
  767. faux_msg_free(ack);
  768. kpargv_free(pargv);
  769. return BOOL_TRUE;
  770. }
  771. static ssize_t stdin_out(int fd, faux_buf_t *buf, bool_t process_all_data)
  772. {
  773. ssize_t total_written = 0;
  774. assert(buf);
  775. if (!buf)
  776. return -1;
  777. assert(fd >= 0);
  778. while (faux_buf_len(buf) > 0) {
  779. ssize_t data_to_write = 0;
  780. ssize_t bytes_written = 0;
  781. void *data = NULL;
  782. data_to_write = faux_buf_dread_lock_easy(buf, &data);
  783. if (data_to_write <= 0)
  784. break;
  785. bytes_written = write(fd, data, data_to_write);
  786. if (bytes_written > 0) {
  787. total_written += bytes_written;
  788. faux_buf_dread_unlock_easy(buf, bytes_written);
  789. } else {
  790. faux_buf_dread_unlock_easy(buf, 0);
  791. }
  792. if (bytes_written < 0) {
  793. if ( // Something went wrong
  794. (errno != EINTR) &&
  795. (errno != EAGAIN) &&
  796. (errno != EWOULDBLOCK)
  797. )
  798. return -1;
  799. // Not whole data block was written
  800. } else if (bytes_written != data_to_write) {
  801. break;
  802. }
  803. if (!process_all_data)
  804. break;
  805. }
  806. return total_written;
  807. }
  808. static bool_t push_stdin(ktpd_session_t *ktpd)
  809. {
  810. faux_buf_t *bufin = NULL;
  811. int fd = -1;
  812. if (!ktpd)
  813. return BOOL_TRUE;
  814. if (!ktpd->exec)
  815. return BOOL_TRUE;
  816. fd = kexec_stdin(ktpd->exec);
  817. if (fd < 0) // May be fd is already closed
  818. return BOOL_FALSE;
  819. bufin = kexec_bufin(ktpd->exec);
  820. assert(bufin);
  821. stdin_out(fd, bufin, BOOL_FALSE); // Non-blocking write
  822. // Restore data receiving from client
  823. if (faux_buf_len(bufin) < BUF_LIMIT)
  824. faux_eloop_include_fd_event(ktpd->eloop,
  825. faux_async_fd(ktpd->async), POLLIN);
  826. if (faux_buf_len(bufin) != 0) // Try later
  827. return BOOL_TRUE;
  828. // All data is written
  829. faux_eloop_exclude_fd_event(ktpd->eloop, fd, POLLOUT);
  830. if (ktpd->stdin_must_be_closed) {
  831. close(fd);
  832. // kexec_set_stdin(ktpd->exec, -1);
  833. }
  834. return BOOL_TRUE;
  835. }
  836. static bool_t ktpd_session_process_stdin(ktpd_session_t *ktpd, faux_msg_t *msg)
  837. {
  838. char *line = NULL;
  839. unsigned int len = 0;
  840. faux_buf_t *bufin = NULL;
  841. int fd = -1;
  842. bool_t interrupt = BOOL_FALSE;
  843. const kaction_t *action = NULL;
  844. assert(ktpd);
  845. assert(msg);
  846. if (!ktpd->exec)
  847. return BOOL_FALSE;
  848. fd = kexec_stdin(ktpd->exec);
  849. if (fd < 0)
  850. return BOOL_FALSE;
  851. if (!faux_msg_get_param_by_type(msg, KTP_PARAM_LINE, (void **)&line, &len))
  852. return BOOL_TRUE; // It's strange but not a bug
  853. if (len == 0)
  854. return BOOL_TRUE;
  855. bufin = kexec_bufin(ktpd->exec);
  856. assert(bufin);
  857. action = kexec_current_action(ktpd->exec);
  858. if (action)
  859. interrupt = kaction_interrupt(action);
  860. // If current action is non-interruptible and action's stdin is terminal
  861. // then remove ^C (0x03) symbol from stdin stream to don't deliver
  862. // SIGINT to process
  863. if (isatty(fd) && !interrupt) {
  864. // 0x03 is a ^C
  865. const char chars_to_search[] = {0x03, 0};
  866. const char *start = line;
  867. const char *pos = NULL;
  868. size_t cur_len = len;
  869. while ((pos = faux_str_charsn(start, chars_to_search, cur_len))) {
  870. size_t written = pos - start;
  871. faux_buf_write(bufin, start, written);
  872. start = pos + 1;
  873. cur_len = cur_len - written - 1;
  874. }
  875. if (cur_len > 0)
  876. faux_buf_write(bufin, start, cur_len);
  877. } else {
  878. faux_buf_write(bufin, line, len);
  879. }
  880. stdin_out(fd, bufin, BOOL_FALSE); // Non-blocking write
  881. if (faux_buf_len(bufin) == 0)
  882. return BOOL_TRUE;
  883. // Non-blocking write can't write all data so plan to write later
  884. faux_eloop_include_fd_event(ktpd->eloop, fd, POLLOUT);
  885. // Temporarily stop data receiving from client because buffer is
  886. // full
  887. if (faux_buf_len(bufin) > BUF_LIMIT)
  888. faux_eloop_exclude_fd_event(ktpd->eloop,
  889. faux_async_fd(ktpd->async), POLLIN);
  890. return BOOL_TRUE;
  891. }
  892. static bool_t ktpd_session_process_winch(ktpd_session_t *ktpd, faux_msg_t *msg)
  893. {
  894. char *line = NULL;
  895. char *p = NULL;
  896. unsigned short width = 0;
  897. unsigned short height = 0;
  898. assert(ktpd);
  899. assert(msg);
  900. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_WINCH)))
  901. return BOOL_TRUE;
  902. p = strchr(line, ' ');
  903. if (!p || (p == line)) {
  904. faux_str_free(line);
  905. return BOOL_FALSE;
  906. }
  907. if (!faux_conv_atous(line, &width, 0)) {
  908. faux_str_free(line);
  909. return BOOL_FALSE;
  910. }
  911. if (!faux_conv_atous(p + 1, &height, 0)) {
  912. faux_str_free(line);
  913. return BOOL_FALSE;
  914. }
  915. ksession_set_term_width(ktpd->session, width);
  916. ksession_set_term_height(ktpd->session, height);
  917. faux_str_free(line);
  918. if (!ktpd->exec)
  919. return BOOL_TRUE;
  920. // Set pseudo terminal window size
  921. kexec_set_winsize(ktpd->exec);
  922. return BOOL_TRUE;
  923. }
  924. static bool_t ktpd_session_process_notification(ktpd_session_t *ktpd, faux_msg_t *msg)
  925. {
  926. assert(ktpd);
  927. assert(msg);
  928. ktpd_session_process_winch(ktpd, msg);
  929. return BOOL_TRUE;
  930. }
  931. static bool_t ktpd_session_process_stdin_close(ktpd_session_t *ktpd,
  932. faux_msg_t *msg)
  933. {
  934. int fd = -1;
  935. assert(ktpd);
  936. assert(msg);
  937. if (!ktpd->exec)
  938. return BOOL_FALSE;
  939. fd = kexec_stdin(ktpd->exec);
  940. if (fd < 0)
  941. return BOOL_FALSE;
  942. // Schedule to close stdin
  943. ktpd->stdin_must_be_closed = BOOL_TRUE;
  944. push_stdin(ktpd);
  945. return BOOL_TRUE;
  946. }
  947. static bool_t ktpd_session_process_stdout_close(ktpd_session_t *ktpd,
  948. faux_msg_t *msg)
  949. {
  950. int fd = -1;
  951. assert(ktpd);
  952. assert(msg);
  953. if (!ktpd->exec)
  954. return BOOL_FALSE;
  955. fd = kexec_stdout(ktpd->exec);
  956. if (fd < 0)
  957. return BOOL_FALSE;
  958. close(fd);
  959. // Remove already generated data from out buffer. This data is not
  960. // needed now
  961. faux_buf_empty(kexec_bufout(ktpd->exec));
  962. return BOOL_TRUE;
  963. }
  964. static bool_t ktpd_session_process_stderr_close(ktpd_session_t *ktpd,
  965. faux_msg_t *msg)
  966. {
  967. int fd = -1;
  968. assert(ktpd);
  969. assert(msg);
  970. if (!ktpd->exec)
  971. return BOOL_FALSE;
  972. fd = kexec_stderr(ktpd->exec);
  973. if (fd < 0)
  974. return BOOL_FALSE;
  975. close(fd);
  976. // Remove already generated data from err buffer. This data is not
  977. // needed any more
  978. faux_buf_empty(kexec_buferr(ktpd->exec));
  979. return BOOL_TRUE;
  980. }
  981. static bool_t ktpd_session_dispatch(ktpd_session_t *ktpd, faux_msg_t *msg)
  982. {
  983. uint16_t cmd = 0;
  984. const char *err = NULL;
  985. ktp_cmd_e ecmd = KTP_NOTIFICATION; // Answer command if error
  986. assert(ktpd);
  987. if (!ktpd)
  988. return BOOL_FALSE;
  989. assert(msg);
  990. if (!msg)
  991. return BOOL_FALSE;
  992. cmd = faux_msg_get_cmd(msg);
  993. switch (cmd) {
  994. case KTP_AUTH:
  995. if ((ktpd->state != KTPD_SESSION_STATE_UNAUTHORIZED) &&
  996. (ktpd->state != KTPD_SESSION_STATE_IDLE)) {
  997. ecmd = KTP_AUTH_ACK;
  998. err = "Server illegal state for authorization";
  999. break;
  1000. }
  1001. ktpd_session_process_auth(ktpd, msg);
  1002. break;
  1003. case KTP_CMD:
  1004. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  1005. ecmd = KTP_CMD_ACK;
  1006. err = "Server illegal state for command execution";
  1007. break;
  1008. }
  1009. ktpd_session_process_cmd(ktpd, msg);
  1010. break;
  1011. case KTP_COMPLETION:
  1012. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  1013. ecmd = KTP_COMPLETION_ACK;
  1014. err = "Server illegal state for completion";
  1015. break;
  1016. }
  1017. ktpd_session_process_completion(ktpd, msg);
  1018. break;
  1019. case KTP_HELP:
  1020. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  1021. ecmd = KTP_HELP_ACK;
  1022. err = "Server illegal state for help";
  1023. break;
  1024. }
  1025. ktpd_session_process_help(ktpd, msg);
  1026. break;
  1027. case KTP_STDIN:
  1028. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1029. err = "Nobody is waiting for stdin";
  1030. break;
  1031. }
  1032. ktpd_session_process_stdin(ktpd, msg);
  1033. break;
  1034. case KTP_NOTIFICATION:
  1035. ktpd_session_process_notification(ktpd, msg);
  1036. break;
  1037. case KTP_STDIN_CLOSE:
  1038. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1039. err = "No active command is running";
  1040. break;
  1041. }
  1042. ktpd_session_process_stdin_close(ktpd, msg);
  1043. break;
  1044. case KTP_STDOUT_CLOSE:
  1045. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1046. err = "No active command is running";
  1047. break;
  1048. }
  1049. ktpd_session_process_stdout_close(ktpd, msg);
  1050. break;
  1051. case KTP_STDERR_CLOSE:
  1052. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1053. err = "No active command is running";
  1054. break;
  1055. }
  1056. ktpd_session_process_stderr_close(ktpd, msg);
  1057. break;
  1058. default:
  1059. syslog(LOG_WARNING, "Unsupported command: 0x%04u", cmd);
  1060. err = "Unsupported command";
  1061. break;
  1062. }
  1063. // On error
  1064. if (err)
  1065. ktp_send_error(ktpd->async, ecmd, err);
  1066. return BOOL_TRUE;
  1067. }
  1068. /** @brief Low-level function to receive KTP message.
  1069. *
  1070. * Firstly function gets the header of message. Then it checks and parses
  1071. * header and find out the length of whole message. Then it receives the rest
  1072. * of message.
  1073. */
  1074. static bool_t ktpd_session_read_cb(faux_async_t *async,
  1075. faux_buf_t *buf, size_t len, void *user_data)
  1076. {
  1077. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1078. faux_msg_t *completed_msg = NULL;
  1079. char *data = NULL;
  1080. assert(async);
  1081. assert(buf);
  1082. assert(ktpd);
  1083. // Linearize buffer
  1084. data = malloc(len);
  1085. faux_buf_read(buf, data, len);
  1086. // Receive header
  1087. if (!ktpd->hdr) {
  1088. size_t whole_len = 0;
  1089. size_t msg_wo_hdr = 0;
  1090. ktpd->hdr = (faux_hdr_t *)data;
  1091. // Check for broken header
  1092. if (!ktp_check_header(ktpd->hdr)) {
  1093. faux_free(ktpd->hdr);
  1094. ktpd->hdr = NULL;
  1095. return BOOL_FALSE;
  1096. }
  1097. whole_len = faux_hdr_len(ktpd->hdr);
  1098. // msg_wo_hdr >= 0 because ktp_check_header() validates whole_len
  1099. msg_wo_hdr = whole_len - sizeof(faux_hdr_t);
  1100. // Plan to receive message body
  1101. if (msg_wo_hdr > 0) {
  1102. faux_async_set_read_limits(async,
  1103. msg_wo_hdr, msg_wo_hdr);
  1104. return BOOL_TRUE;
  1105. }
  1106. // Here message is completed (msg body has zero length)
  1107. completed_msg = faux_msg_deserialize_parts(ktpd->hdr, NULL, 0);
  1108. // Receive message body
  1109. } else {
  1110. completed_msg = faux_msg_deserialize_parts(ktpd->hdr, data, len);
  1111. faux_free(data);
  1112. }
  1113. // Plan to receive msg header
  1114. faux_async_set_read_limits(ktpd->async,
  1115. sizeof(faux_hdr_t), sizeof(faux_hdr_t));
  1116. faux_free(ktpd->hdr);
  1117. ktpd->hdr = NULL; // Ready to recv new header
  1118. // Here message is completed
  1119. ktpd_session_dispatch(ktpd, completed_msg);
  1120. faux_msg_free(completed_msg);
  1121. return BOOL_TRUE;
  1122. }
  1123. bool_t ktpd_session_connected(ktpd_session_t *ktpd)
  1124. {
  1125. assert(ktpd);
  1126. if (!ktpd)
  1127. return BOOL_FALSE;
  1128. if (KTPD_SESSION_STATE_DISCONNECTED == ktpd->state)
  1129. return BOOL_FALSE;
  1130. return BOOL_TRUE;
  1131. }
  1132. int ktpd_session_fd(const ktpd_session_t *ktpd)
  1133. {
  1134. assert(ktpd);
  1135. if (!ktpd)
  1136. return BOOL_FALSE;
  1137. return faux_async_fd(ktpd->async);
  1138. }
  1139. static bool_t get_stream(ktpd_session_t *ktpd, int fd, bool_t is_stderr,
  1140. bool_t process_all_data)
  1141. {
  1142. ssize_t r = -1;
  1143. faux_buf_t *faux_buf = NULL;
  1144. char *buf = NULL;
  1145. ssize_t len = 0;
  1146. faux_msg_t *ack = NULL;
  1147. if (!ktpd)
  1148. return BOOL_TRUE;
  1149. if (!ktpd->exec)
  1150. return BOOL_TRUE;
  1151. if (is_stderr)
  1152. faux_buf = kexec_buferr(ktpd->exec);
  1153. else
  1154. faux_buf = kexec_bufout(ktpd->exec);
  1155. assert(faux_buf);
  1156. do {
  1157. void *linear_buf = NULL;
  1158. ssize_t really_readed = 0;
  1159. ssize_t linear_len =
  1160. faux_buf_dwrite_lock_easy(faux_buf, &linear_buf);
  1161. // Non-blocked read. The fd became non-blocked while
  1162. // kexec_prepare().
  1163. r = read(fd, linear_buf, linear_len);
  1164. if (r > 0)
  1165. really_readed = r;
  1166. faux_buf_dwrite_unlock_easy(faux_buf, really_readed);
  1167. } while ((r > 0) && process_all_data);
  1168. len = faux_buf_len(faux_buf);
  1169. if (0 == len)
  1170. return BOOL_TRUE;
  1171. buf = malloc(len);
  1172. faux_buf_read(faux_buf, buf, len);
  1173. // Create KTP_STDOUT/KTP_STDERR message to send to client
  1174. ack = ktp_msg_preform(is_stderr ? KTP_STDERR : KTP_STDOUT, KTP_STATUS_NONE);
  1175. faux_msg_add_param(ack, KTP_PARAM_LINE, buf, len);
  1176. faux_msg_send_async(ack, ktpd->async);
  1177. faux_msg_free(ack);
  1178. free(buf);
  1179. // Pause stdout/stderr receiving because buffer (to send to client)
  1180. // is full
  1181. if (faux_buf_len(faux_async_obuf(ktpd->async)) > BUF_LIMIT)
  1182. faux_eloop_exclude_fd_event(ktpd->eloop, fd, POLLIN);
  1183. return BOOL_TRUE;
  1184. }
  1185. static bool_t action_stdout_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1186. void *associated_data, void *user_data)
  1187. {
  1188. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1189. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1190. // Interactive command use these function as callback not only for
  1191. // getting stdout but for writing stdin too. Because pseudo-terminal
  1192. // uses the same fd for in and out.
  1193. if (info->revents & POLLOUT)
  1194. push_stdin(ktpd);
  1195. if (info->revents & POLLIN)
  1196. get_stream(ktpd, info->fd, BOOL_FALSE, BOOL_FALSE);
  1197. // Some errors or fd is closed so remove it from polling
  1198. // EOF || POLERR || POLLNVAL
  1199. if (info->revents & (POLLHUP | POLLERR | POLLNVAL))
  1200. faux_eloop_del_fd(eloop, info->fd);
  1201. type = type; // Happy compiler
  1202. return BOOL_TRUE;
  1203. }
  1204. static bool_t action_stderr_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1205. void *associated_data, void *user_data)
  1206. {
  1207. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1208. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1209. if (info->revents & POLLIN)
  1210. get_stream(ktpd, info->fd, BOOL_TRUE, BOOL_FALSE);
  1211. // Some errors or fd is closed so remove it from polling
  1212. // EOF || POLERR || POLLNVAL
  1213. if (info->revents & (POLLHUP | POLLERR | POLLNVAL))
  1214. faux_eloop_del_fd(eloop, info->fd);
  1215. type = type; // Happy compiler
  1216. return BOOL_TRUE;
  1217. }
  1218. bool_t client_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1219. void *associated_data, void *user_data)
  1220. {
  1221. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1222. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1223. faux_async_t *async = ktpd->async;
  1224. assert(async);
  1225. // Write data
  1226. if (info->revents & POLLOUT) {
  1227. faux_eloop_exclude_fd_event(eloop, info->fd, POLLOUT);
  1228. if (faux_async_out_easy(async) < 0) {
  1229. // Someting went wrong
  1230. faux_eloop_del_fd(eloop, info->fd);
  1231. syslog(LOG_ERR, "Can't send data to client");
  1232. return BOOL_FALSE; // Stop event loop
  1233. }
  1234. // Restore stdout and stderr receiving if out buffer is not
  1235. // full
  1236. if (ktpd->exec &&
  1237. faux_buf_len(faux_async_obuf(async)) < BUF_LIMIT) {
  1238. faux_eloop_include_fd_event(ktpd->eloop,
  1239. kexec_stdout(ktpd->exec), POLLIN);
  1240. faux_eloop_include_fd_event(ktpd->eloop,
  1241. kexec_stderr(ktpd->exec), POLLIN);
  1242. }
  1243. }
  1244. // Read data
  1245. if (info->revents & POLLIN) {
  1246. if (faux_async_in_easy(async) < 0) {
  1247. // Someting went wrong
  1248. faux_eloop_del_fd(eloop, info->fd);
  1249. syslog(LOG_ERR, "Can't get data from client");
  1250. return BOOL_FALSE; // Stop event loop
  1251. }
  1252. }
  1253. // EOF
  1254. if (info->revents & POLLHUP) {
  1255. faux_eloop_del_fd(eloop, info->fd);
  1256. syslog(LOG_DEBUG, "Connection %d is closed by client", info->fd);
  1257. return BOOL_FALSE; // Stop event loop
  1258. }
  1259. // POLLERR
  1260. if (info->revents & POLLERR) {
  1261. faux_eloop_del_fd(eloop, info->fd);
  1262. syslog(LOG_DEBUG, "POLLERR received %d", info->fd);
  1263. return BOOL_FALSE; // Stop event loop
  1264. }
  1265. // POLLNVAL
  1266. if (info->revents & POLLNVAL) {
  1267. faux_eloop_del_fd(eloop, info->fd);
  1268. syslog(LOG_DEBUG, "POLLNVAL received %d", info->fd);
  1269. return BOOL_FALSE; // Stop event loop
  1270. }
  1271. type = type; // Happy compiler
  1272. // Session can be really finished here. Note KTPD session can't be
  1273. // stopped immediately so it's only two places within code to really
  1274. // break the loop. This one and within wait_for_action_ev().
  1275. if (ktpd->exit)
  1276. return BOOL_FALSE;
  1277. return BOOL_TRUE;
  1278. }
  1279. #if 0
  1280. static void ktpd_session_bad_socket(ktpd_session_t *ktpd)
  1281. {
  1282. assert(ktpd);
  1283. if (!ktpd)
  1284. return;
  1285. ktpd->state = KTPD_SESSION_STATE_DISCONNECTED;
  1286. }
  1287. #endif