kexec.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /** @file kexec.c
  2. */
  3. #define _XOPEN_SOURCE
  4. #define _XOPEN_SOURCE_EXTENDED
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <assert.h>
  8. #include <string.h>
  9. #include <sys/types.h>
  10. #include <unistd.h>
  11. #include <fcntl.h>
  12. #include <syslog.h>
  13. #include <faux/list.h>
  14. #include <faux/buf.h>
  15. #include <faux/eloop.h>
  16. #include <klish/khelper.h>
  17. #include <klish/kcontext.h>
  18. #include <klish/kpath.h>
  19. #include <klish/kexec.h>
  20. #define PTMX_PATH "/dev/ptmx"
  21. // Declaration of grabber. Implementation is in the grabber.c
  22. void grabber(int fds[][2]);
  23. struct kexec_s {
  24. faux_list_t *contexts;
  25. bool_t dry_run;
  26. int stdin;
  27. int stdout;
  28. int stderr;
  29. faux_buf_t *bufin;
  30. faux_buf_t *bufout;
  31. faux_buf_t *buferr;
  32. kpath_t *saved_path;
  33. };
  34. // Dry-run
  35. KGET_BOOL(exec, dry_run);
  36. KSET_BOOL(exec, dry_run);
  37. // STDIN
  38. KGET(exec, int, stdin);
  39. KSET(exec, int, stdin);
  40. // STDOUT
  41. KGET(exec, int, stdout);
  42. KSET(exec, int, stdout);
  43. // STDERR
  44. KGET(exec, int, stderr);
  45. KSET(exec, int, stderr);
  46. // BufIN
  47. KGET(exec, faux_buf_t *, bufin);
  48. KSET(exec, faux_buf_t *, bufin);
  49. // BufOUT
  50. KGET(exec, faux_buf_t *, bufout);
  51. KSET(exec, faux_buf_t *, bufout);
  52. // BufERR
  53. KGET(exec, faux_buf_t *, buferr);
  54. KSET(exec, faux_buf_t *, buferr);
  55. // Saved path
  56. KGET(exec, kpath_t *, saved_path);
  57. // CONTEXT list
  58. KADD_NESTED(exec, kcontext_t *, contexts);
  59. KNESTED_LEN(exec, contexts);
  60. KNESTED_IS_EMPTY(exec, contexts);
  61. KNESTED_ITER(exec, contexts);
  62. KNESTED_EACH(exec, kcontext_t *, contexts);
  63. kexec_t *kexec_new()
  64. {
  65. kexec_t *exec = NULL;
  66. exec = faux_zmalloc(sizeof(*exec));
  67. assert(exec);
  68. if (!exec)
  69. return NULL;
  70. exec->dry_run = BOOL_FALSE;
  71. exec->saved_path = NULL;
  72. // List of execute contexts
  73. exec->contexts = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_NONUNIQUE,
  74. NULL, NULL, (void (*)(void *))kcontext_free);
  75. assert(exec->contexts);
  76. // I/O
  77. exec->stdin = -1;
  78. exec->stdout = -1;
  79. exec->stderr = -1;
  80. exec->bufin = faux_buf_new(0);
  81. exec->bufout = faux_buf_new(0);
  82. exec->buferr = faux_buf_new(0);
  83. return exec;
  84. }
  85. void kexec_free(kexec_t *exec)
  86. {
  87. if (!exec)
  88. return;
  89. faux_list_free(exec->contexts);
  90. if (exec->stdin != -1)
  91. close(exec->stdin);
  92. if (exec->stdout != -1)
  93. close(exec->stdout);
  94. if (exec->stderr != -1)
  95. close(exec->stderr);
  96. faux_buf_free(exec->bufin);
  97. faux_buf_free(exec->bufout);
  98. faux_buf_free(exec->buferr);
  99. kpath_free(exec->saved_path);
  100. free(exec);
  101. }
  102. size_t kexec_len(const kexec_t *exec)
  103. {
  104. assert(exec);
  105. if (!exec)
  106. return 0;
  107. return faux_list_len(exec->contexts);
  108. }
  109. size_t kexec_is_empty(const kexec_t *exec)
  110. {
  111. assert(exec);
  112. if (!exec)
  113. return 0;
  114. return faux_list_is_empty(exec->contexts);
  115. }
  116. // kexec is done when all the kexec's contexts are done
  117. bool_t kexec_done(const kexec_t *exec)
  118. {
  119. faux_list_node_t *iter = NULL;
  120. kcontext_t *context = NULL;
  121. assert(exec);
  122. if (!exec)
  123. return BOOL_FALSE;
  124. iter = kexec_contexts_iter(exec);
  125. while ((context = kexec_contexts_each(&iter))) {
  126. if (!kcontext_done(context))
  127. return BOOL_FALSE;
  128. }
  129. return BOOL_TRUE;
  130. }
  131. // Retcode of kexec is a retcode of its first context execution because
  132. // next contexts just a filters. Retcode valid if kexec is done. Else current
  133. // retcode is non-valid and will not be returned at all.
  134. bool_t kexec_retcode(const kexec_t *exec, int *status)
  135. {
  136. assert(exec);
  137. if (!exec)
  138. return BOOL_FALSE;
  139. if (kexec_is_empty(exec))
  140. return BOOL_FALSE;
  141. if (!kexec_done(exec)) // Unfinished execution
  142. return BOOL_FALSE;
  143. if (status)
  144. *status = kcontext_retcode(
  145. (kcontext_t *)faux_list_data(faux_list_head(exec->contexts)));
  146. return BOOL_TRUE;
  147. }
  148. bool_t kexec_path_is_changed(const kexec_t *exec)
  149. {
  150. kpath_t *path = NULL;
  151. kcontext_t *context = NULL;
  152. assert(exec);
  153. if (!exec)
  154. return BOOL_FALSE;
  155. context = (kcontext_t *)faux_list_data(faux_list_head(exec->contexts));
  156. path = ksession_path(kcontext_session(context));
  157. if (kpath_is_equal(exec->saved_path, path))
  158. return BOOL_FALSE;
  159. return BOOL_TRUE;
  160. }
  161. bool_t kexec_add(kexec_t *exec, kcontext_t *context)
  162. {
  163. assert(exec);
  164. assert(context);
  165. if (!exec)
  166. return BOOL_FALSE;
  167. if (!context)
  168. return BOOL_FALSE;
  169. if (!faux_list_add(exec->contexts, context))
  170. return BOOL_FALSE;
  171. return BOOL_TRUE;
  172. }
  173. static bool_t kexec_prepare(kexec_t *exec)
  174. {
  175. int pipefd[2] = {};
  176. faux_list_node_t *iter = NULL;
  177. int global_stderr = -1;
  178. int fflags = 0;
  179. assert(exec);
  180. if (!exec)
  181. return BOOL_FALSE;
  182. // Nothing to prepare for empty list
  183. if (kexec_contexts_is_empty(exec))
  184. return BOOL_FALSE;
  185. // If command is interactive then prepare pseudoterminal. Note
  186. // interactive commands can't have filters
  187. if (kexec_interactive(exec)) {
  188. int ptm = -1;
  189. char *pts_name = NULL;
  190. int pts = -1;
  191. kcontext_t *context = (kcontext_t *)faux_list_data(
  192. faux_list_head(exec->contexts));
  193. ptm = open(PTMX_PATH, O_RDWR, O_NOCTTY);
  194. // ptm = open(PTMX_PATH, O_RDWR, 0);
  195. if (ptm < 0)
  196. return BOOL_FALSE;
  197. // Set O_NONBLOCK flag here. Because this flag is ignored while
  198. // open() ptmx. I don't know why. fcntl() is working fine.
  199. fflags = fcntl(ptm, F_GETFL);
  200. fcntl(ptm, F_SETFL, fflags | O_NONBLOCK);
  201. grantpt(ptm);
  202. unlockpt(ptm);
  203. pts_name = ptsname(ptm);
  204. pts = open(pts_name, O_RDWR, O_NOCTTY);
  205. // pts = open(pts_name, O_RDWR, 0);
  206. if (pts < 0) {
  207. close(ptm);
  208. return BOOL_FALSE;
  209. }
  210. kexec_set_stdin(exec, ptm);
  211. kexec_set_stdout(exec, ptm);
  212. kexec_set_stderr(exec, ptm);
  213. kcontext_set_stdin(context, pts);
  214. kcontext_set_stdout(context, pts);
  215. kcontext_set_stderr(context, pts);
  216. return BOOL_TRUE;
  217. }
  218. // Create "global" stdin, stdout, stderr for the whole job execution.
  219. // Now function creates only the simple pipes but somedays it will be
  220. // able to create pseudo-terminal for interactive sessions.
  221. // STDIN
  222. if (pipe(pipefd) < 0)
  223. return BOOL_FALSE;
  224. kcontext_set_stdin(faux_list_data(faux_list_head(exec->contexts)),
  225. pipefd[0]); // Read end
  226. kexec_set_stdin(exec, pipefd[1]); // Write end
  227. // STDOUT
  228. if (pipe(pipefd) < 0)
  229. return BOOL_FALSE;
  230. // Read end of 'stdout' pipe must be non-blocked
  231. fflags = fcntl(pipefd[0], F_GETFL);
  232. fcntl(pipefd[0], F_SETFL, fflags | O_NONBLOCK);
  233. kexec_set_stdout(exec, pipefd[0]); // Read end
  234. kcontext_set_stdout(faux_list_data(faux_list_tail(exec->contexts)),
  235. pipefd[1]); // Write end
  236. // STDERR
  237. if (pipe(pipefd) < 0)
  238. return BOOL_FALSE;
  239. // Read end of 'stderr' pipe must be non-blocked
  240. fflags = fcntl(pipefd[0], F_GETFL);
  241. fcntl(pipefd[0], F_SETFL, fflags | O_NONBLOCK);
  242. kexec_set_stderr(exec, pipefd[0]); // Read end
  243. // STDERR write end will be set to all list members as stderr
  244. global_stderr = pipefd[1]; // Write end
  245. // Iterate all context_t elements to fill all stdin, stdout, stderr
  246. for (iter = faux_list_head(exec->contexts); iter;
  247. iter = faux_list_next_node(iter)) {
  248. faux_list_node_t *next = faux_list_next_node(iter);
  249. kcontext_t *context = (kcontext_t *)faux_list_data(iter);
  250. // The first context is a context of main command. The other
  251. // contexts are contexts of filters. So save current path from
  252. // first context.
  253. if (iter == faux_list_head(exec->contexts)) {
  254. ksession_t *session = kcontext_session(context);
  255. if (session && ksession_path(session))
  256. exec->saved_path = kpath_clone(
  257. ksession_path(session));
  258. }
  259. // Set the same STDERR to all contexts
  260. kcontext_set_stderr(context, global_stderr);
  261. // Create pipes beetween processes
  262. if (next) {
  263. kcontext_t *next_context = (kcontext_t *)faux_list_data(next);
  264. if (pipe(pipefd) < 0)
  265. return BOOL_FALSE;
  266. kcontext_set_stdout(context, pipefd[1]); // Write end
  267. kcontext_set_stdin(next_context, pipefd[0]); // Read end
  268. }
  269. }
  270. return BOOL_TRUE;
  271. }
  272. // === SYNC symbol execution
  273. // The function will be executed right here. It's necessary for
  274. // navigation implementation for example. To grab function output the
  275. // service process will be forked. It gets output and stores it to the
  276. // internal buffer. After sym function return grabber will write
  277. // buffered data back. So grabber will simulate async sym execution.
  278. static bool_t exec_action_sync(kcontext_t *context, const kaction_t *action,
  279. pid_t *pid, int *retcode)
  280. {
  281. ksym_fn fn = NULL;
  282. int exitcode = 0;
  283. pid_t child_pid = -1;
  284. int pipe_stdout[2] = {};
  285. int pipe_stderr[2] = {};
  286. // Create pipes beetween sym function and grabber
  287. if (pipe(pipe_stdout) < 0)
  288. return BOOL_FALSE;
  289. if (pipe(pipe_stderr) < 0) {
  290. close(pipe_stdout[0]);
  291. close(pipe_stdout[1]);
  292. return BOOL_FALSE;
  293. }
  294. fn = ksym_function(kaction_sym(action));
  295. // Prepare streams before fork
  296. fflush(stdout);
  297. fflush(stderr);
  298. // Fork the grabber
  299. child_pid = fork();
  300. if (child_pid == -1) {
  301. close(pipe_stdout[0]);
  302. close(pipe_stdout[1]);
  303. close(pipe_stderr[0]);
  304. close(pipe_stderr[1]);
  305. return BOOL_FALSE;
  306. }
  307. // Parent
  308. if (child_pid != 0) {
  309. int saved_stdout = -1;
  310. int saved_stderr = -1;
  311. // Save pid of grabber
  312. if (pid)
  313. *pid = child_pid;
  314. // Temporarily replace orig output streams by pipe
  315. // stdout
  316. saved_stdout = dup(STDOUT_FILENO);
  317. dup2(pipe_stdout[1], STDOUT_FILENO);
  318. close(pipe_stdout[0]);
  319. close(pipe_stdout[1]);
  320. // stderr
  321. saved_stderr = dup(STDERR_FILENO);
  322. dup2(pipe_stderr[1], STDERR_FILENO);
  323. close(pipe_stderr[0]);
  324. close(pipe_stderr[1]);
  325. // Execute sym function right here
  326. exitcode = fn(context);
  327. if (retcode)
  328. *retcode = exitcode;
  329. // Restore orig output streams
  330. // stdout
  331. fflush(stdout);
  332. dup2(saved_stdout, STDOUT_FILENO);
  333. close(saved_stdout);
  334. // stderr
  335. fflush(stderr);
  336. dup2(saved_stderr, STDERR_FILENO);
  337. close(saved_stderr);
  338. return BOOL_TRUE;
  339. }
  340. // Child (Output grabber)
  341. close(pipe_stdout[1]);
  342. close(pipe_stderr[1]);
  343. {
  344. int fds[][2] = {
  345. {pipe_stdout[0], kcontext_stdout(context)},
  346. {pipe_stderr[0], kcontext_stderr(context)},
  347. {-1, -1},
  348. };
  349. grabber(fds);
  350. }
  351. close(pipe_stdout[0]);
  352. close(pipe_stderr[0]);
  353. _exit(0);
  354. return BOOL_TRUE;
  355. }
  356. // === ASYNC symbol execution
  357. // The process will be forked and sym will be executed there.
  358. // The parent will save forked process's pid and immediately return
  359. // control to event loop which will get forked process stdout and
  360. // wait for process termination.
  361. static bool_t exec_action_async(kcontext_t *context, const kaction_t *action,
  362. pid_t *pid)
  363. {
  364. ksym_fn fn = NULL;
  365. int exitcode = 0;
  366. pid_t child_pid = -1;
  367. fn = ksym_function(kaction_sym(action));
  368. // Oh, it's amazing world of stdio!
  369. // Flush buffers before fork() because buffer content will be inherited
  370. // by child. Moreover dup2() can replace old stdout file descriptor by
  371. // the new one but buffer linked with stdout stream will remain the same.
  372. // It must be empty.
  373. fflush(stdout);
  374. fflush(stderr);
  375. child_pid = fork();
  376. if (child_pid == -1)
  377. return BOOL_FALSE;
  378. // Parent
  379. // Save the child pid and return control. Later event loop will wait
  380. // for saved pid.
  381. if (child_pid != 0) {
  382. if (pid)
  383. *pid = child_pid;
  384. return BOOL_TRUE;
  385. }
  386. // Child
  387. dup2(kcontext_stdin(context), STDIN_FILENO);
  388. dup2(kcontext_stdout(context), STDOUT_FILENO);
  389. dup2(kcontext_stderr(context), STDERR_FILENO);
  390. exitcode = fn(context);
  391. // We will use _exit() later so stdio streams will remain unflushed.
  392. // Some output data can be lost. Flush necessary streams here.
  393. fflush(stdout);
  394. fflush(stderr);
  395. // Use _exit() but not exit() to don't flush all the stdio streams. It
  396. // can be dangerous because parent can have a lot of streams inhereted
  397. // by child process.
  398. _exit(exitcode);
  399. return BOOL_TRUE;
  400. }
  401. static bool_t exec_action(kcontext_t *context, const kaction_t *action,
  402. pid_t *pid, int *retcode)
  403. {
  404. assert(context);
  405. if (!context)
  406. return BOOL_FALSE;
  407. assert(action);
  408. if (!action)
  409. return BOOL_FALSE;
  410. if (kaction_is_sync(action))
  411. return exec_action_sync(context, action, pid, retcode);
  412. return exec_action_async(context, action, pid);
  413. }
  414. static bool_t exec_action_sequence(const kexec_t *exec, kcontext_t *context,
  415. pid_t pid, int wstatus)
  416. {
  417. faux_list_node_t *iter = NULL;
  418. int exitstatus = WEXITSTATUS(wstatus);
  419. pid_t new_pid = -1; // PID of newly forked ACTION process
  420. assert(context);
  421. if (!context)
  422. return BOOL_FALSE;
  423. // There is two reasons to don't start any real actions.
  424. // - The ACTION sequence is already done;
  425. // - Passed PID (PID of completed process) is not owned by this context.
  426. // Returns false that indicates this PID is not mine.
  427. if (kcontext_done(context) || (kcontext_pid(context) != pid))
  428. return BOOL_FALSE;
  429. // Here we know that given PID is our PID
  430. iter = kcontext_action_iter(context); // Get saved current ACTION
  431. // ASYNC: Compute new value for retcode.
  432. // Here iter is a pointer to previous action but not new.
  433. // It's for async actions only. Sync actions will change global
  434. // retcode after the exec_action() invocation.
  435. if (iter) {
  436. const kaction_t *terminated_action = faux_list_data(iter);
  437. assert(terminated_action);
  438. if (!kaction_is_sync(terminated_action) &&
  439. kaction_update_retcode(terminated_action))
  440. kcontext_set_retcode(context, exitstatus);
  441. }
  442. // Loop is needed because some ACTIONs will be skipped due to specified
  443. // execution conditions. So try next actions.
  444. do {
  445. const kaction_t *action = NULL;
  446. bool_t is_sync = BOOL_FALSE;
  447. // Get next ACTION from sequence
  448. if (!iter) { // Is it the first ACTION within list
  449. faux_list_t *actions =
  450. kentry_actions(kpargv_command(kcontext_pargv(context)));
  451. assert(actions);
  452. iter = faux_list_head(actions);
  453. } else {
  454. iter = faux_list_next_node(iter);
  455. }
  456. kcontext_set_action_iter(context, iter);
  457. // Is it end of ACTION sequence?
  458. if (!iter) {
  459. kcontext_set_done(context, BOOL_TRUE);
  460. return BOOL_TRUE;
  461. }
  462. // Get new ACTION to execute
  463. action = (const kaction_t *)faux_list_data(iter);
  464. assert(action);
  465. // Check for previous retcode to find out if next command must
  466. // be executed or skipped.
  467. if (!kaction_meet_exec_conditions(action, kcontext_retcode(context)))
  468. continue; // Skip action, try next one
  469. // Check for dry-run flag and 'permanent' feature of ACTION.
  470. if (kexec_dry_run(exec) && !kaction_is_permanent(action)) {
  471. is_sync = BOOL_TRUE; // Simulate sync action
  472. exitstatus = 0; // Exit status while dry-run is always 0
  473. } else { // Normal execution
  474. is_sync = kaction_is_sync(action);
  475. exec_action(context, action, &new_pid, &exitstatus);
  476. }
  477. // SYNC: Compute new value for retcode.
  478. // Sync actions return retcode immediatelly. Their forked
  479. // processes are for output handling only.
  480. if (is_sync && kaction_update_retcode(action))
  481. kcontext_set_retcode(context, exitstatus);
  482. } while (-1 == new_pid); // PID is not -1 when new process was forked
  483. // Save PID of newly created process
  484. kcontext_set_pid(context, new_pid);
  485. return BOOL_TRUE;
  486. }
  487. bool_t kexec_continue_command_execution(kexec_t *exec, pid_t pid, int wstatus)
  488. {
  489. faux_list_node_t *iter = NULL;
  490. kcontext_t *context = NULL;
  491. assert(exec);
  492. if (!exec)
  493. return BOOL_FALSE;
  494. iter = kexec_contexts_iter(exec);
  495. while ((context = kexec_contexts_each(&iter))) {
  496. bool_t found = BOOL_FALSE;
  497. found = exec_action_sequence(exec, context, pid, wstatus);
  498. if (found && (pid != -1))
  499. break;
  500. }
  501. return BOOL_TRUE;
  502. }
  503. bool_t kexec_exec(kexec_t *exec)
  504. {
  505. kcontext_t *context = NULL;
  506. const kpargv_t *pargv = NULL;
  507. const kentry_t *entry = NULL;
  508. bool_t restore = BOOL_FALSE;
  509. assert(exec);
  510. if (!exec)
  511. return BOOL_FALSE;
  512. // Firsly prepare kexec object for execution. The file streams must
  513. // be created for stdin, stdout, stderr of processes.
  514. if (!kexec_prepare(exec))
  515. return BOOL_FALSE;
  516. // Pre-change VIEW if command has "restore" flag. Only first command in
  517. // line (if many commands are piped) matters. Filters can't change the
  518. // VIEW.
  519. context = (kcontext_t *)faux_list_data(faux_list_head(exec->contexts));
  520. pargv = kcontext_pargv(context);
  521. entry = kpargv_command(pargv);
  522. if (entry)
  523. restore = kentry_restore(entry);
  524. if (restore) {
  525. size_t level = kpargv_level(pargv);
  526. kpath_t *path = ksession_path(kcontext_session(context));
  527. while(kpath_len(path) > (level + 1))
  528. kpath_pop(path);
  529. }
  530. // Here no ACTIONs are executing, so pass -1 as pid of terminated
  531. // ACTION's process.
  532. kexec_continue_command_execution(exec, -1, 0);
  533. return BOOL_TRUE;
  534. }
  535. bool_t kexec_interactive(const kexec_t *exec)
  536. {
  537. faux_list_node_t *node = NULL;
  538. kcontext_t *context = NULL;
  539. const kentry_t *entry = NULL;
  540. assert(exec);
  541. if (!exec)
  542. return BOOL_FALSE;
  543. // Only the ACTION of first context can be interactive
  544. node = faux_list_head(exec->contexts);
  545. if (!node)
  546. return BOOL_FALSE;
  547. context = (kcontext_t *)faux_list_data(node);
  548. if (!context)
  549. return BOOL_FALSE;
  550. entry = kcontext_command(context);
  551. if (!entry)
  552. return BOOL_FALSE;
  553. return kentry_interactive(entry);
  554. }