ktpd_session.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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, 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 line_has_content(const char *line)
  289. {
  290. const char *l = line;
  291. if (faux_str_is_empty(line))
  292. return BOOL_FALSE;
  293. while (*l) {
  294. if (!isspace(*l))
  295. return BOOL_TRUE;
  296. l++;
  297. }
  298. return BOOL_FALSE;
  299. }
  300. static bool_t ktpd_session_process_cmd(ktpd_session_t *ktpd, faux_msg_t *msg)
  301. {
  302. char *line = NULL;
  303. int retcode = -1;
  304. ktp_cmd_e cmd = KTP_CMD_ACK;
  305. faux_error_t *error = NULL;
  306. bool_t rc = BOOL_FALSE;
  307. bool_t dry_run = BOOL_FALSE;
  308. uint32_t status = KTP_STATUS_NONE;
  309. bool_t ret = BOOL_TRUE;
  310. char *prompt = NULL;
  311. bool_t view_was_changed = BOOL_FALSE;
  312. faux_msg_t *ack = NULL;
  313. assert(ktpd);
  314. assert(msg);
  315. // Get line from message
  316. line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE);
  317. if (!line_has_content(line)) {
  318. faux_str_free(line);
  319. // Line is not specified. User sent empty command.
  320. // It's not bug. Send OK to user and regenerate prompt
  321. ack = ktp_msg_preform(cmd, KTP_STATUS_NONE);
  322. // Generate prompt
  323. prompt = generate_prompt(ktpd);
  324. if (prompt) {
  325. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  326. faux_str_free(prompt);
  327. }
  328. faux_msg_send_async(ack, ktpd->async);
  329. faux_msg_free(ack);
  330. return BOOL_TRUE;
  331. }
  332. // Get dry-run flag from message
  333. if (KTP_STATUS_IS_DRY_RUN(faux_msg_get_status(msg)))
  334. dry_run = BOOL_TRUE;
  335. error = faux_error_new();
  336. ktpd->exec = NULL;
  337. rc = ktpd_session_exec(ktpd, line, &retcode, error,
  338. dry_run, &view_was_changed);
  339. faux_str_free(line);
  340. // Command is scheduled. Eloop will wait for ACTION completion.
  341. // So inform client about it and about command features like
  342. // interactive/non-interactive.
  343. if (ktpd->exec) {
  344. faux_msg_t *ack = NULL;
  345. ktp_status_e status = KTP_STATUS_INCOMPLETED;
  346. if (kexec_interactive(ktpd->exec))
  347. status |= KTP_STATUS_INTERACTIVE;
  348. if (kexec_need_stdin(ktpd->exec))
  349. status |= KTP_STATUS_NEED_STDIN;
  350. ack = ktp_msg_preform(cmd, status);
  351. faux_msg_send_async(ack, ktpd->async);
  352. faux_msg_free(ack);
  353. faux_error_free(error);
  354. return BOOL_TRUE; // Continue and wait for ACTION
  355. }
  356. // Here we don't need to wait for the action. We have retcode already.
  357. if (ksession_done(ktpd->session)) {
  358. ktpd->exit = BOOL_TRUE;
  359. status |= KTP_STATUS_EXIT;
  360. }
  361. // Prepare ACK message
  362. ack = ktp_msg_preform(cmd, status);
  363. if (rc) {
  364. uint8_t retcode8bit = 0;
  365. retcode8bit = (uint8_t)(retcode & 0xff);
  366. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  367. } else {
  368. faux_msg_set_status(ack, KTP_STATUS_ERROR);
  369. char *err = faux_error_cstr(error);
  370. faux_msg_add_param(ack, KTP_PARAM_ERROR, err, strlen(err));
  371. faux_str_free(err);
  372. ret = BOOL_FALSE;
  373. }
  374. // Generate prompt
  375. prompt = generate_prompt(ktpd);
  376. if (prompt) {
  377. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  378. faux_str_free(prompt);
  379. }
  380. // Add hotkeys
  381. if (view_was_changed)
  382. add_hotkeys_to_msg(ktpd, ack);
  383. faux_msg_send_async(ack, ktpd->async);
  384. faux_msg_free(ack);
  385. faux_error_free(error);
  386. return ret;
  387. }
  388. static bool_t ktpd_session_exec(ktpd_session_t *ktpd, const char *line,
  389. int *retcode, faux_error_t *error,
  390. bool_t dry_run, bool_t *view_was_changed_p)
  391. {
  392. kexec_t *exec = NULL;
  393. assert(ktpd);
  394. if (!ktpd)
  395. return BOOL_FALSE;
  396. // Parsing
  397. exec = ksession_parse_for_exec(ktpd->session, line, error);
  398. if (!exec)
  399. return BOOL_FALSE;
  400. // Set dry-run flag
  401. kexec_set_dry_run(exec, dry_run);
  402. // Session status can be changed while parsing
  403. // NOTE: kexec_t is atomic now
  404. // if (ksession_done(ktpd->session)) {
  405. // kexec_free(exec);
  406. // return BOOL_FALSE; // Because action is not completed
  407. // }
  408. // Execute kexec and then wait for completion using global Eloop
  409. if (!kexec_exec(exec)) {
  410. kexec_free(exec);
  411. return BOOL_FALSE; // Something went wrong
  412. }
  413. // If kexec contains only non-exec (for example dry-run) ACTIONs then
  414. // we don't need event loop and can return here.
  415. if (kexec_retcode(exec, retcode)) {
  416. if (view_was_changed_p)
  417. *view_was_changed_p = !kpath_is_equal(
  418. ksession_path(ktpd->session),
  419. kexec_saved_path(exec));
  420. ktpd_session_log(ktpd, exec);
  421. kexec_free(exec);
  422. return BOOL_TRUE;
  423. }
  424. // Save kexec pointer to use later
  425. ktpd->state = KTPD_SESSION_STATE_WAIT_FOR_PROCESS;
  426. ktpd->exec = exec;
  427. // Set stdin, stdout, stderr handlers. It's so complex because stdin,
  428. // stdout and stderr actually can be the same fd
  429. faux_eloop_add_fd(ktpd->eloop, kexec_stdin(exec), 0,
  430. action_stdout_ev, ktpd);
  431. faux_eloop_add_fd(ktpd->eloop, kexec_stdout(exec), 0,
  432. action_stdout_ev, ktpd);
  433. faux_eloop_add_fd(ktpd->eloop, kexec_stderr(exec), 0,
  434. action_stderr_ev, ktpd);
  435. faux_eloop_include_fd_event(ktpd->eloop, kexec_stdout(exec), POLLIN);
  436. faux_eloop_include_fd_event(ktpd->eloop, kexec_stderr(exec), POLLIN);
  437. return BOOL_TRUE;
  438. }
  439. static bool_t wait_for_actions_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  440. void *associated_data, void *user_data)
  441. {
  442. int wstatus = 0;
  443. pid_t child_pid = -1;
  444. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  445. int retcode = -1;
  446. uint8_t retcode8bit = 0;
  447. faux_msg_t *ack = NULL;
  448. ktp_cmd_e cmd = KTP_CMD_ACK;
  449. uint32_t status = KTP_STATUS_NONE;
  450. char *prompt = NULL;
  451. bool_t view_was_changed = BOOL_FALSE;
  452. if (!ktpd)
  453. return BOOL_FALSE;
  454. // Wait for any child process. Doesn't block.
  455. while ((child_pid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
  456. if (ktpd->exec)
  457. kexec_continue_command_execution(ktpd->exec, child_pid,
  458. wstatus);
  459. }
  460. if (!ktpd->exec)
  461. return BOOL_TRUE;
  462. // Check if kexec is done now
  463. if (!kexec_retcode(ktpd->exec, &retcode))
  464. return BOOL_TRUE; // Continue
  465. // Sometimes SIGCHILD signal can appear before all data were really read
  466. // from process stdout buffer. So read the least data before closing
  467. // file descriptors and send it to client.
  468. get_stream(ktpd, kexec_stdout(ktpd->exec), BOOL_FALSE, BOOL_TRUE);
  469. get_stream(ktpd, kexec_stderr(ktpd->exec), BOOL_TRUE, BOOL_TRUE);
  470. faux_eloop_del_fd(eloop, kexec_stdin(ktpd->exec));
  471. faux_eloop_del_fd(eloop, kexec_stdout(ktpd->exec));
  472. faux_eloop_del_fd(eloop, kexec_stderr(ktpd->exec));
  473. ktpd_session_log(ktpd, ktpd->exec);
  474. view_was_changed = !kpath_is_equal(
  475. ksession_path(ktpd->session), kexec_saved_path(ktpd->exec));
  476. kexec_free(ktpd->exec);
  477. ktpd->exec = NULL;
  478. ktpd->state = KTPD_SESSION_STATE_IDLE;
  479. // All kexec_t actions are done so can break the loop if needed.
  480. if (ksession_done(ktpd->session)) {
  481. ktpd->exit = BOOL_TRUE;
  482. status |= KTP_STATUS_EXIT; // Notify client about exiting
  483. }
  484. // Send ACK message
  485. ack = ktp_msg_preform(cmd, status);
  486. retcode8bit = (uint8_t)(retcode & 0xff);
  487. faux_msg_add_param(ack, KTP_PARAM_RETCODE, &retcode8bit, 1);
  488. // Generate prompt
  489. prompt = generate_prompt(ktpd);
  490. if (prompt) {
  491. faux_msg_add_param(ack, KTP_PARAM_PROMPT, prompt, strlen(prompt));
  492. faux_str_free(prompt);
  493. }
  494. // Add hotkeys
  495. if (view_was_changed)
  496. add_hotkeys_to_msg(ktpd, ack);
  497. faux_msg_send_async(ack, ktpd->async);
  498. faux_msg_free(ack);
  499. type = type; // Happy compiler
  500. associated_data = associated_data; // Happy compiler
  501. if (ktpd->exit)
  502. return BOOL_FALSE;
  503. return BOOL_TRUE;
  504. }
  505. static bool_t ktpd_session_log(ktpd_session_t *ktpd, const kexec_t *exec)
  506. {
  507. kexec_contexts_node_t *iter = NULL;
  508. kcontext_t *context = NULL;
  509. iter = kexec_contexts_iter(exec);
  510. while ((context = kexec_contexts_each(&iter))) {
  511. const kentry_t *entry = kcontext_command(context);
  512. const kentry_t *log_entry = NULL;
  513. int rc = -1;
  514. if (!entry)
  515. continue;
  516. log_entry = kentry_nested_by_purpose(entry, KENTRY_PURPOSE_LOG);
  517. if (!log_entry)
  518. continue;
  519. if (kentry_actions_len(log_entry) == 0)
  520. continue;
  521. ksession_exec_locally(ktpd->session, log_entry,
  522. kcontext_pargv(context), context, exec, &rc, NULL);
  523. }
  524. return BOOL_TRUE;
  525. }
  526. static int compl_compare(const void *first, const void *second)
  527. {
  528. const char *f = (const char *)first;
  529. const char *s = (const char *)second;
  530. return strcmp(f, s);
  531. }
  532. static int compl_kcompare(const void *key, const void *list_item)
  533. {
  534. const char *f = (const char *)key;
  535. const char *s = (const char *)list_item;
  536. return strcmp(f, s);
  537. }
  538. static bool_t ktpd_session_process_completion(ktpd_session_t *ktpd, faux_msg_t *msg)
  539. {
  540. char *line = NULL;
  541. faux_msg_t *ack = NULL;
  542. kpargv_t *pargv = NULL;
  543. ktp_cmd_e cmd = KTP_COMPLETION_ACK;
  544. uint32_t status = KTP_STATUS_NONE;
  545. const char *prefix = NULL;
  546. size_t prefix_len = 0;
  547. assert(ktpd);
  548. assert(msg);
  549. // Get line from message
  550. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  551. ktp_send_error(ktpd->async, cmd, NULL);
  552. return BOOL_FALSE;
  553. }
  554. // Parsing
  555. pargv = ksession_parse_for_completion(ktpd->session, line);
  556. faux_str_free(line);
  557. if (!pargv) {
  558. ktp_send_error(ktpd->async, cmd, NULL);
  559. return BOOL_FALSE;
  560. }
  561. kpargv_debug(pargv);
  562. if (ksession_done(ktpd->session)) {
  563. ktpd->exit = BOOL_TRUE;
  564. status |= KTP_STATUS_EXIT; // Notify client about exiting
  565. }
  566. // Prepare ACK message
  567. ack = ktp_msg_preform(cmd, status);
  568. // Last unfinished word. Common prefix for all completions
  569. prefix = kpargv_last_arg(pargv);
  570. if (!faux_str_is_empty(prefix)) {
  571. prefix_len = strlen(prefix);
  572. faux_msg_add_param(ack, KTP_PARAM_PREFIX, prefix, prefix_len);
  573. }
  574. // Fill msg with possible completions
  575. if (!kpargv_completions_is_empty(pargv)) {
  576. const kentry_t *candidate = NULL;
  577. kpargv_completions_node_t *citer = kpargv_completions_iter(pargv);
  578. faux_list_node_t *compl_iter = NULL;
  579. faux_list_t *completions = NULL;
  580. char *compl_str = NULL;
  581. completions = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  582. compl_compare, compl_kcompare,
  583. (void (*)(void *))faux_str_free);
  584. while ((candidate = kpargv_completions_each(&citer))) {
  585. const kentry_t *completion = NULL;
  586. kparg_t *parg = NULL;
  587. int rc = -1;
  588. char *out = NULL;
  589. bool_t res = BOOL_FALSE;
  590. char *l = NULL; // One line of completion
  591. const char *str = NULL;
  592. // Get completion entry from candidate entry
  593. completion = kentry_nested_by_purpose(candidate,
  594. KENTRY_PURPOSE_COMPLETION);
  595. // If candidate entry doesn't contain completion then try
  596. // to get completion from entry's PTYPE
  597. if (!completion) {
  598. const kentry_t *ptype = NULL;
  599. ptype = kentry_nested_by_purpose(candidate,
  600. KENTRY_PURPOSE_PTYPE);
  601. if (!ptype)
  602. continue;
  603. completion = kentry_nested_by_purpose(ptype,
  604. KENTRY_PURPOSE_COMPLETION);
  605. }
  606. if (!completion)
  607. continue;
  608. parg = kparg_new(candidate, prefix);
  609. kpargv_set_candidate_parg(pargv, parg);
  610. res = ksession_exec_locally(ktpd->session, completion,
  611. pargv, NULL, NULL, &rc, &out);
  612. kparg_free(parg);
  613. if (!res || (rc < 0) || !out) {
  614. if (out)
  615. faux_str_free(out);
  616. continue;
  617. }
  618. // Get all completions one by one
  619. str = out;
  620. while ((l = faux_str_getline(str, &str))) {
  621. // Compare prefix
  622. if ((prefix_len > 0) &&
  623. (faux_str_cmpn(prefix, l, prefix_len) != 0)) {
  624. faux_str_free(l);
  625. continue;
  626. }
  627. compl_str = l + prefix_len;
  628. faux_list_add(completions, faux_str_dup(compl_str));
  629. faux_str_free(l);
  630. }
  631. faux_str_free(out);
  632. }
  633. // Put completion list to message
  634. compl_iter = faux_list_head(completions);
  635. while ((compl_str = faux_list_each(&compl_iter))) {
  636. faux_msg_add_param(ack, KTP_PARAM_LINE,
  637. compl_str, strlen(compl_str));
  638. }
  639. faux_list_free(completions);
  640. }
  641. faux_msg_send_async(ack, ktpd->async);
  642. faux_msg_free(ack);
  643. kpargv_free(pargv);
  644. return BOOL_TRUE;
  645. }
  646. // The most priority source of help is candidate's help ACTION output. Next
  647. // source is candidate's PTYPE help ACTION output.
  648. // Function generates two lines for one resulting help line. The first
  649. // component is a 'prefix' and the second component is 'text'.
  650. // The 'prefix' can be something like 'ip', 'filter' i.e.
  651. // subcommand or '3..89', '<STRING>' i.e. description of type. The 'text'
  652. // field is description of current parameter. For example 'Interface IP
  653. // address'. So the full help can be:
  654. // AAA.BBB.CCC.DDD Interface IP address
  655. // [ first field ] [ second field ]
  656. //
  657. // If not candidate parameter nor PTYPE contains the help functions the engine
  658. // tries to construct help itself.
  659. //
  660. // It uses the following sources for 'prefix':
  661. // * 'help' field of PTYPE
  662. // * 'value' field of PTYPE
  663. // * 'name' field of PTYPE
  664. // * 'value' field of parameter
  665. // * 'name' field of parameter
  666. //
  667. // Engine uses the following sources for 'text':
  668. // * 'help' field of parameter
  669. // * 'value' field of parameter
  670. // * 'name' field of parameter
  671. static bool_t ktpd_session_process_help(ktpd_session_t *ktpd, faux_msg_t *msg)
  672. {
  673. char *line = NULL;
  674. faux_msg_t *ack = NULL;
  675. kpargv_t *pargv = NULL;
  676. ktp_cmd_e cmd = KTP_HELP_ACK;
  677. uint32_t status = KTP_STATUS_NONE;
  678. const char *prefix = NULL;
  679. assert(ktpd);
  680. assert(msg);
  681. // Get line from message
  682. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_LINE))) {
  683. ktp_send_error(ktpd->async, cmd, NULL);
  684. return BOOL_FALSE;
  685. }
  686. // Parsing
  687. pargv = ksession_parse_for_completion(ktpd->session, line);
  688. faux_str_free(line);
  689. if (!pargv) {
  690. ktp_send_error(ktpd->async, cmd, NULL);
  691. return BOOL_FALSE;
  692. }
  693. if (ksession_done(ktpd->session)) {
  694. ktpd->exit = BOOL_TRUE;
  695. status |= KTP_STATUS_EXIT; // Notify client about exiting
  696. }
  697. // Prepare ACK message
  698. ack = ktp_msg_preform(cmd, status);
  699. // Last unfinished word. Common prefix for all entries
  700. prefix = kpargv_last_arg(pargv);
  701. // Fill msg with possible help messages
  702. if (!kpargv_completions_is_empty(pargv)) {
  703. const kentry_t *candidate = NULL;
  704. kpargv_completions_node_t *citer = kpargv_completions_iter(pargv);
  705. faux_list_node_t *help_iter = NULL;
  706. faux_list_t *help_list = NULL;
  707. help_t *help_struct = NULL;
  708. help_list = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  709. help_compare, NULL, help_free);
  710. while ((candidate = kpargv_completions_each(&citer))) {
  711. const kentry_t *help = NULL;
  712. const kentry_t *ptype = NULL;
  713. // Get PTYPE of parameter
  714. ptype = kentry_nested_by_purpose(candidate,
  715. KENTRY_PURPOSE_PTYPE);
  716. // Try to get help fn from parameter itself
  717. help = kentry_nested_by_purpose(candidate,
  718. KENTRY_PURPOSE_HELP);
  719. if (!help && ptype)
  720. help = kentry_nested_by_purpose(ptype,
  721. KENTRY_PURPOSE_HELP);
  722. // Generate help with found ACTION
  723. if (help) {
  724. char *out = NULL;
  725. kparg_t *parg = NULL;
  726. int rc = -1;
  727. parg = kparg_new(candidate, prefix);
  728. kpargv_set_candidate_parg(pargv, parg);
  729. ksession_exec_locally(ktpd->session,
  730. help, pargv, NULL, NULL, &rc, &out);
  731. kparg_free(parg);
  732. if (out) {
  733. const char *str = out;
  734. char *prefix_str = NULL;
  735. char *line_str = NULL;
  736. do {
  737. prefix_str = faux_str_getline(str, &str);
  738. if (!prefix_str)
  739. break;
  740. line_str = faux_str_getline(str, &str);
  741. if (!line_str) {
  742. faux_str_free(prefix_str);
  743. break;
  744. }
  745. help_struct = help_new(prefix_str, line_str);
  746. if (!faux_list_add(help_list, help_struct))
  747. help_free(help_struct);
  748. } while (line_str);
  749. faux_str_free(out);
  750. }
  751. // Generate help with available information
  752. } else {
  753. const char *prefix_str = NULL;
  754. const char *line_str = NULL;
  755. // Prefix_str
  756. if (ptype) {
  757. prefix_str = kentry_help(ptype);
  758. if (!prefix_str)
  759. prefix_str = kentry_value(ptype);
  760. if (!prefix_str)
  761. prefix_str = kentry_name(ptype);
  762. } else {
  763. prefix_str = kentry_value(candidate);
  764. if (!prefix_str)
  765. prefix_str = kentry_name(candidate);
  766. }
  767. assert(prefix_str);
  768. // Line_str
  769. line_str = kentry_help(candidate);
  770. if (!line_str)
  771. line_str = kentry_value(candidate);
  772. if (!line_str)
  773. line_str = kentry_name(candidate);
  774. assert(line_str);
  775. help_struct = help_new(
  776. faux_str_dup(prefix_str),
  777. faux_str_dup(line_str));
  778. if (!faux_list_add(help_list, help_struct))
  779. help_free(help_struct);
  780. }
  781. }
  782. // Put help list to message
  783. help_iter = faux_list_head(help_list);
  784. while ((help_struct = (help_t *)faux_list_each(&help_iter))) {
  785. faux_msg_add_param(ack, KTP_PARAM_PREFIX,
  786. help_struct->prefix, strlen(help_struct->prefix));
  787. faux_msg_add_param(ack, KTP_PARAM_LINE,
  788. help_struct->line, strlen(help_struct->line));
  789. }
  790. faux_list_free(help_list);
  791. }
  792. faux_msg_send_async(ack, ktpd->async);
  793. faux_msg_free(ack);
  794. kpargv_free(pargv);
  795. return BOOL_TRUE;
  796. }
  797. static ssize_t stdin_out(int fd, faux_buf_t *buf, bool_t process_all_data)
  798. {
  799. ssize_t total_written = 0;
  800. assert(buf);
  801. if (!buf)
  802. return -1;
  803. assert(fd >= 0);
  804. while (faux_buf_len(buf) > 0) {
  805. ssize_t data_to_write = 0;
  806. ssize_t bytes_written = 0;
  807. void *data = NULL;
  808. data_to_write = faux_buf_dread_lock_easy(buf, &data);
  809. if (data_to_write <= 0)
  810. break;
  811. bytes_written = write(fd, data, data_to_write);
  812. if (bytes_written > 0) {
  813. total_written += bytes_written;
  814. faux_buf_dread_unlock_easy(buf, bytes_written);
  815. } else {
  816. faux_buf_dread_unlock_easy(buf, 0);
  817. }
  818. if (bytes_written < 0) {
  819. if ( // Something went wrong
  820. (errno != EINTR) &&
  821. (errno != EAGAIN) &&
  822. (errno != EWOULDBLOCK)
  823. )
  824. return -1;
  825. // Not whole data block was written
  826. } else if (bytes_written != data_to_write) {
  827. break;
  828. }
  829. if (!process_all_data)
  830. break;
  831. }
  832. return total_written;
  833. }
  834. static bool_t push_stdin(ktpd_session_t *ktpd)
  835. {
  836. faux_buf_t *bufin = NULL;
  837. int fd = -1;
  838. if (!ktpd)
  839. return BOOL_TRUE;
  840. if (!ktpd->exec)
  841. return BOOL_TRUE;
  842. fd = kexec_stdin(ktpd->exec);
  843. if (fd < 0) // May be fd is already closed
  844. return BOOL_FALSE;
  845. bufin = kexec_bufin(ktpd->exec);
  846. assert(bufin);
  847. stdin_out(fd, bufin, BOOL_FALSE); // Non-blocking write
  848. // Restore data receiving from client
  849. if (faux_buf_len(bufin) < BUF_LIMIT)
  850. faux_eloop_include_fd_event(ktpd->eloop,
  851. faux_async_fd(ktpd->async), POLLIN);
  852. if (faux_buf_len(bufin) != 0) // Try later
  853. return BOOL_TRUE;
  854. // All data is written
  855. faux_eloop_exclude_fd_event(ktpd->eloop, fd, POLLOUT);
  856. if (ktpd->stdin_must_be_closed) {
  857. close(fd);
  858. // kexec_set_stdin(ktpd->exec, -1);
  859. }
  860. return BOOL_TRUE;
  861. }
  862. static bool_t ktpd_session_process_stdin(ktpd_session_t *ktpd, faux_msg_t *msg)
  863. {
  864. char *line = NULL;
  865. unsigned int len = 0;
  866. faux_buf_t *bufin = NULL;
  867. int fd = -1;
  868. bool_t interrupt = BOOL_FALSE;
  869. const kaction_t *action = NULL;
  870. assert(ktpd);
  871. assert(msg);
  872. if (!ktpd->exec)
  873. return BOOL_FALSE;
  874. fd = kexec_stdin(ktpd->exec);
  875. if (fd < 0)
  876. return BOOL_FALSE;
  877. if (!faux_msg_get_param_by_type(msg, KTP_PARAM_LINE, (void **)&line, &len))
  878. return BOOL_TRUE; // It's strange but not a bug
  879. if (len == 0)
  880. return BOOL_TRUE;
  881. bufin = kexec_bufin(ktpd->exec);
  882. assert(bufin);
  883. action = kexec_current_action(ktpd->exec);
  884. if (action)
  885. interrupt = kaction_interrupt(action);
  886. // If current action is non-interruptible and action's stdin is terminal
  887. // then remove ^C (0x03) symbol from stdin stream to don't deliver
  888. // SIGINT to process
  889. if (isatty(fd) && !interrupt) {
  890. // 0x03 is a ^C
  891. const char chars_to_search[] = {0x03, 0};
  892. const char *start = line;
  893. const char *pos = NULL;
  894. size_t cur_len = len;
  895. while ((pos = faux_str_charsn(start, chars_to_search, cur_len))) {
  896. size_t written = pos - start;
  897. faux_buf_write(bufin, start, written);
  898. start = pos + 1;
  899. cur_len = cur_len - written - 1;
  900. }
  901. if (cur_len > 0)
  902. faux_buf_write(bufin, start, cur_len);
  903. } else {
  904. faux_buf_write(bufin, line, len);
  905. }
  906. stdin_out(fd, bufin, BOOL_FALSE); // Non-blocking write
  907. if (faux_buf_len(bufin) == 0)
  908. return BOOL_TRUE;
  909. // Non-blocking write can't write all data so plan to write later
  910. faux_eloop_include_fd_event(ktpd->eloop, fd, POLLOUT);
  911. // Temporarily stop data receiving from client because buffer is
  912. // full
  913. if (faux_buf_len(bufin) > BUF_LIMIT)
  914. faux_eloop_exclude_fd_event(ktpd->eloop,
  915. faux_async_fd(ktpd->async), POLLIN);
  916. return BOOL_TRUE;
  917. }
  918. static bool_t ktpd_session_process_winch(ktpd_session_t *ktpd, faux_msg_t *msg)
  919. {
  920. char *line = NULL;
  921. char *p = NULL;
  922. unsigned short width = 0;
  923. unsigned short height = 0;
  924. assert(ktpd);
  925. assert(msg);
  926. if (!(line = faux_msg_get_str_param_by_type(msg, KTP_PARAM_WINCH)))
  927. return BOOL_TRUE;
  928. p = strchr(line, ' ');
  929. if (!p || (p == line)) {
  930. faux_str_free(line);
  931. return BOOL_FALSE;
  932. }
  933. if (!faux_conv_atous(line, &width, 0)) {
  934. faux_str_free(line);
  935. return BOOL_FALSE;
  936. }
  937. if (!faux_conv_atous(p + 1, &height, 0)) {
  938. faux_str_free(line);
  939. return BOOL_FALSE;
  940. }
  941. ksession_set_term_width(ktpd->session, width);
  942. ksession_set_term_height(ktpd->session, height);
  943. faux_str_free(line);
  944. if (!ktpd->exec)
  945. return BOOL_TRUE;
  946. // Set pseudo terminal window size
  947. kexec_set_winsize(ktpd->exec);
  948. return BOOL_TRUE;
  949. }
  950. static bool_t ktpd_session_process_notification(ktpd_session_t *ktpd, faux_msg_t *msg)
  951. {
  952. assert(ktpd);
  953. assert(msg);
  954. ktpd_session_process_winch(ktpd, msg);
  955. return BOOL_TRUE;
  956. }
  957. static bool_t ktpd_session_process_stdin_close(ktpd_session_t *ktpd,
  958. faux_msg_t *msg)
  959. {
  960. int fd = -1;
  961. assert(ktpd);
  962. assert(msg);
  963. if (!ktpd->exec)
  964. return BOOL_FALSE;
  965. fd = kexec_stdin(ktpd->exec);
  966. if (fd < 0)
  967. return BOOL_FALSE;
  968. // Schedule to close stdin
  969. ktpd->stdin_must_be_closed = BOOL_TRUE;
  970. push_stdin(ktpd);
  971. return BOOL_TRUE;
  972. }
  973. static bool_t ktpd_session_process_stdout_close(ktpd_session_t *ktpd,
  974. faux_msg_t *msg)
  975. {
  976. int fd = -1;
  977. assert(ktpd);
  978. assert(msg);
  979. if (!ktpd->exec)
  980. return BOOL_FALSE;
  981. fd = kexec_stdout(ktpd->exec);
  982. if (fd < 0)
  983. return BOOL_FALSE;
  984. close(fd);
  985. // Remove already generated data from out buffer. This data is not
  986. // needed now
  987. faux_buf_empty(kexec_bufout(ktpd->exec));
  988. return BOOL_TRUE;
  989. }
  990. static bool_t ktpd_session_process_stderr_close(ktpd_session_t *ktpd,
  991. faux_msg_t *msg)
  992. {
  993. int fd = -1;
  994. assert(ktpd);
  995. assert(msg);
  996. if (!ktpd->exec)
  997. return BOOL_FALSE;
  998. fd = kexec_stderr(ktpd->exec);
  999. if (fd < 0)
  1000. return BOOL_FALSE;
  1001. close(fd);
  1002. // Remove already generated data from err buffer. This data is not
  1003. // needed any more
  1004. faux_buf_empty(kexec_buferr(ktpd->exec));
  1005. return BOOL_TRUE;
  1006. }
  1007. static bool_t ktpd_session_dispatch(ktpd_session_t *ktpd, faux_msg_t *msg)
  1008. {
  1009. uint16_t cmd = 0;
  1010. const char *err = NULL;
  1011. ktp_cmd_e ecmd = KTP_NOTIFICATION; // Answer command if error
  1012. assert(ktpd);
  1013. if (!ktpd)
  1014. return BOOL_FALSE;
  1015. assert(msg);
  1016. if (!msg)
  1017. return BOOL_FALSE;
  1018. cmd = faux_msg_get_cmd(msg);
  1019. switch (cmd) {
  1020. case KTP_AUTH:
  1021. if ((ktpd->state != KTPD_SESSION_STATE_UNAUTHORIZED) &&
  1022. (ktpd->state != KTPD_SESSION_STATE_IDLE)) {
  1023. ecmd = KTP_AUTH_ACK;
  1024. err = "Server illegal state for authorization";
  1025. break;
  1026. }
  1027. ktpd_session_process_auth(ktpd, msg);
  1028. break;
  1029. case KTP_CMD:
  1030. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  1031. ecmd = KTP_CMD_ACK;
  1032. err = "Server illegal state for command execution";
  1033. break;
  1034. }
  1035. ktpd_session_process_cmd(ktpd, msg);
  1036. break;
  1037. case KTP_COMPLETION:
  1038. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  1039. ecmd = KTP_COMPLETION_ACK;
  1040. err = "Server illegal state for completion";
  1041. break;
  1042. }
  1043. ktpd_session_process_completion(ktpd, msg);
  1044. break;
  1045. case KTP_HELP:
  1046. if (ktpd->state != KTPD_SESSION_STATE_IDLE) {
  1047. ecmd = KTP_HELP_ACK;
  1048. err = "Server illegal state for help";
  1049. break;
  1050. }
  1051. ktpd_session_process_help(ktpd, msg);
  1052. break;
  1053. case KTP_STDIN:
  1054. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1055. err = "Nobody is waiting for stdin";
  1056. break;
  1057. }
  1058. ktpd_session_process_stdin(ktpd, msg);
  1059. break;
  1060. case KTP_NOTIFICATION:
  1061. ktpd_session_process_notification(ktpd, msg);
  1062. break;
  1063. case KTP_STDIN_CLOSE:
  1064. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1065. err = "No active command is running";
  1066. break;
  1067. }
  1068. ktpd_session_process_stdin_close(ktpd, msg);
  1069. break;
  1070. case KTP_STDOUT_CLOSE:
  1071. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1072. err = "No active command is running";
  1073. break;
  1074. }
  1075. ktpd_session_process_stdout_close(ktpd, msg);
  1076. break;
  1077. case KTP_STDERR_CLOSE:
  1078. if (ktpd->state != KTPD_SESSION_STATE_WAIT_FOR_PROCESS) {
  1079. err = "No active command is running";
  1080. break;
  1081. }
  1082. ktpd_session_process_stderr_close(ktpd, msg);
  1083. break;
  1084. default:
  1085. syslog(LOG_WARNING, "Unsupported command: 0x%04u", cmd);
  1086. err = "Unsupported command";
  1087. break;
  1088. }
  1089. // On error
  1090. if (err)
  1091. ktp_send_error(ktpd->async, ecmd, err);
  1092. return BOOL_TRUE;
  1093. }
  1094. /** @brief Low-level function to receive KTP message.
  1095. *
  1096. * Firstly function gets the header of message. Then it checks and parses
  1097. * header and find out the length of whole message. Then it receives the rest
  1098. * of message.
  1099. */
  1100. static bool_t ktpd_session_read_cb(faux_async_t *async,
  1101. faux_buf_t *buf, size_t len, void *user_data)
  1102. {
  1103. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1104. faux_msg_t *completed_msg = NULL;
  1105. char *data = NULL;
  1106. assert(async);
  1107. assert(buf);
  1108. assert(ktpd);
  1109. // Linearize buffer
  1110. data = malloc(len);
  1111. faux_buf_read(buf, data, len);
  1112. // Receive header
  1113. if (!ktpd->hdr) {
  1114. size_t whole_len = 0;
  1115. size_t msg_wo_hdr = 0;
  1116. ktpd->hdr = (faux_hdr_t *)data;
  1117. // Check for broken header
  1118. if (!ktp_check_header(ktpd->hdr)) {
  1119. faux_free(ktpd->hdr);
  1120. ktpd->hdr = NULL;
  1121. return BOOL_FALSE;
  1122. }
  1123. whole_len = faux_hdr_len(ktpd->hdr);
  1124. // msg_wo_hdr >= 0 because ktp_check_header() validates whole_len
  1125. msg_wo_hdr = whole_len - sizeof(faux_hdr_t);
  1126. // Plan to receive message body
  1127. if (msg_wo_hdr > 0) {
  1128. faux_async_set_read_limits(async,
  1129. msg_wo_hdr, msg_wo_hdr);
  1130. return BOOL_TRUE;
  1131. }
  1132. // Here message is completed (msg body has zero length)
  1133. completed_msg = faux_msg_deserialize_parts(ktpd->hdr, NULL, 0);
  1134. // Receive message body
  1135. } else {
  1136. completed_msg = faux_msg_deserialize_parts(ktpd->hdr, data, len);
  1137. faux_free(data);
  1138. }
  1139. // Plan to receive msg header
  1140. faux_async_set_read_limits(ktpd->async,
  1141. sizeof(faux_hdr_t), sizeof(faux_hdr_t));
  1142. faux_free(ktpd->hdr);
  1143. ktpd->hdr = NULL; // Ready to recv new header
  1144. // Here message is completed
  1145. ktpd_session_dispatch(ktpd, completed_msg);
  1146. faux_msg_free(completed_msg);
  1147. return BOOL_TRUE;
  1148. }
  1149. bool_t ktpd_session_connected(ktpd_session_t *ktpd)
  1150. {
  1151. assert(ktpd);
  1152. if (!ktpd)
  1153. return BOOL_FALSE;
  1154. if (KTPD_SESSION_STATE_DISCONNECTED == ktpd->state)
  1155. return BOOL_FALSE;
  1156. return BOOL_TRUE;
  1157. }
  1158. int ktpd_session_fd(const ktpd_session_t *ktpd)
  1159. {
  1160. assert(ktpd);
  1161. if (!ktpd)
  1162. return BOOL_FALSE;
  1163. return faux_async_fd(ktpd->async);
  1164. }
  1165. static bool_t get_stream(ktpd_session_t *ktpd, int fd, bool_t is_stderr,
  1166. bool_t process_all_data)
  1167. {
  1168. ssize_t r = -1;
  1169. faux_buf_t *faux_buf = NULL;
  1170. char *buf = NULL;
  1171. ssize_t len = 0;
  1172. faux_msg_t *ack = NULL;
  1173. if (!ktpd)
  1174. return BOOL_TRUE;
  1175. if (!ktpd->exec)
  1176. return BOOL_TRUE;
  1177. if (is_stderr)
  1178. faux_buf = kexec_buferr(ktpd->exec);
  1179. else
  1180. faux_buf = kexec_bufout(ktpd->exec);
  1181. assert(faux_buf);
  1182. do {
  1183. void *linear_buf = NULL;
  1184. ssize_t really_readed = 0;
  1185. ssize_t linear_len =
  1186. faux_buf_dwrite_lock_easy(faux_buf, &linear_buf);
  1187. // Non-blocked read. The fd became non-blocked while
  1188. // kexec_prepare().
  1189. r = read(fd, linear_buf, linear_len);
  1190. if (r > 0)
  1191. really_readed = r;
  1192. faux_buf_dwrite_unlock_easy(faux_buf, really_readed);
  1193. } while ((r > 0) && process_all_data);
  1194. len = faux_buf_len(faux_buf);
  1195. if (0 == len)
  1196. return BOOL_TRUE;
  1197. buf = malloc(len);
  1198. faux_buf_read(faux_buf, buf, len);
  1199. // Create KTP_STDOUT/KTP_STDERR message to send to client
  1200. ack = ktp_msg_preform(is_stderr ? KTP_STDERR : KTP_STDOUT, KTP_STATUS_NONE);
  1201. faux_msg_add_param(ack, KTP_PARAM_LINE, buf, len);
  1202. faux_msg_send_async(ack, ktpd->async);
  1203. faux_msg_free(ack);
  1204. free(buf);
  1205. // Pause stdout/stderr receiving because buffer (to send to client)
  1206. // is full
  1207. if (faux_buf_len(faux_async_obuf(ktpd->async)) > BUF_LIMIT)
  1208. faux_eloop_exclude_fd_event(ktpd->eloop, fd, POLLIN);
  1209. return BOOL_TRUE;
  1210. }
  1211. static bool_t action_stdout_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1212. void *associated_data, void *user_data)
  1213. {
  1214. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1215. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1216. // Interactive command use these function as callback not only for
  1217. // getting stdout but for writing stdin too. Because pseudo-terminal
  1218. // uses the same fd for in and out.
  1219. if (info->revents & POLLOUT)
  1220. push_stdin(ktpd);
  1221. if (info->revents & POLLIN)
  1222. get_stream(ktpd, info->fd, BOOL_FALSE, BOOL_FALSE);
  1223. // Some errors or fd is closed so remove it from polling
  1224. // EOF || POLERR || POLLNVAL
  1225. if (info->revents & (POLLHUP | POLLERR | POLLNVAL))
  1226. faux_eloop_del_fd(eloop, info->fd);
  1227. type = type; // Happy compiler
  1228. return BOOL_TRUE;
  1229. }
  1230. static bool_t action_stderr_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1231. void *associated_data, void *user_data)
  1232. {
  1233. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1234. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1235. if (info->revents & POLLIN)
  1236. get_stream(ktpd, info->fd, BOOL_TRUE, BOOL_FALSE);
  1237. // Some errors or fd is closed so remove it from polling
  1238. // EOF || POLERR || POLLNVAL
  1239. if (info->revents & (POLLHUP | POLLERR | POLLNVAL))
  1240. faux_eloop_del_fd(eloop, info->fd);
  1241. type = type; // Happy compiler
  1242. return BOOL_TRUE;
  1243. }
  1244. bool_t client_ev(faux_eloop_t *eloop, faux_eloop_type_e type,
  1245. void *associated_data, void *user_data)
  1246. {
  1247. faux_eloop_info_fd_t *info = (faux_eloop_info_fd_t *)associated_data;
  1248. ktpd_session_t *ktpd = (ktpd_session_t *)user_data;
  1249. faux_async_t *async = ktpd->async;
  1250. assert(async);
  1251. // Write data
  1252. if (info->revents & POLLOUT) {
  1253. faux_eloop_exclude_fd_event(eloop, info->fd, POLLOUT);
  1254. if (faux_async_out_easy(async) < 0) {
  1255. // Someting went wrong
  1256. faux_eloop_del_fd(eloop, info->fd);
  1257. syslog(LOG_ERR, "Can't send data to client");
  1258. return BOOL_FALSE; // Stop event loop
  1259. }
  1260. // Restore stdout and stderr receiving if out buffer is not
  1261. // full
  1262. if (ktpd->exec &&
  1263. faux_buf_len(faux_async_obuf(async)) < BUF_LIMIT) {
  1264. faux_eloop_include_fd_event(ktpd->eloop,
  1265. kexec_stdout(ktpd->exec), POLLIN);
  1266. faux_eloop_include_fd_event(ktpd->eloop,
  1267. kexec_stderr(ktpd->exec), POLLIN);
  1268. }
  1269. }
  1270. // Read data
  1271. if (info->revents & POLLIN) {
  1272. if (faux_async_in_easy(async) < 0) {
  1273. // Someting went wrong
  1274. faux_eloop_del_fd(eloop, info->fd);
  1275. syslog(LOG_ERR, "Can't get data from client");
  1276. return BOOL_FALSE; // Stop event loop
  1277. }
  1278. }
  1279. // EOF
  1280. if (info->revents & POLLHUP) {
  1281. faux_eloop_del_fd(eloop, info->fd);
  1282. syslog(LOG_DEBUG, "Connection %d is closed by client", info->fd);
  1283. return BOOL_FALSE; // Stop event loop
  1284. }
  1285. // POLLERR
  1286. if (info->revents & POLLERR) {
  1287. faux_eloop_del_fd(eloop, info->fd);
  1288. syslog(LOG_DEBUG, "POLLERR received %d", info->fd);
  1289. return BOOL_FALSE; // Stop event loop
  1290. }
  1291. // POLLNVAL
  1292. if (info->revents & POLLNVAL) {
  1293. faux_eloop_del_fd(eloop, info->fd);
  1294. syslog(LOG_DEBUG, "POLLNVAL received %d", info->fd);
  1295. return BOOL_FALSE; // Stop event loop
  1296. }
  1297. type = type; // Happy compiler
  1298. // Session can be really finished here. Note KTPD session can't be
  1299. // stopped immediately so it's only two places within code to really
  1300. // break the loop. This one and within wait_for_action_ev().
  1301. if (ktpd->exit)
  1302. return BOOL_FALSE;
  1303. return BOOL_TRUE;
  1304. }
  1305. #if 0
  1306. static void ktpd_session_bad_socket(ktpd_session_t *ktpd)
  1307. {
  1308. assert(ktpd);
  1309. if (!ktpd)
  1310. return;
  1311. ktpd->state = KTPD_SESSION_STATE_DISCONNECTED;
  1312. }
  1313. #endif