ktpd_session.c 40 KB

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