ktpd_session.c 39 KB

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