ktpd_session.c 40 KB

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