ktpd_session.c 38 KB

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