ktpd_session.c 40 KB

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