ktpd_session.c 40 KB

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