ktpd_session.c 38 KB

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