ktpd_session.c 37 KB

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