kexec.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. if (ptm < 0)
  195. return BOOL_FALSE;
  196. // Set O_NONBLOCK flag here. Because this flag is ignored while
  197. // open() ptmx. I don't know why. fcntl() is working fine.
  198. fflags = fcntl(ptm, F_GETFL);
  199. fcntl(ptm, F_SETFL, fflags | O_NONBLOCK);
  200. grantpt(ptm);
  201. unlockpt(ptm);
  202. pts_name = ptsname(ptm);
  203. pts = open(pts_name, O_RDWR, O_NOCTTY);
  204. if (pts < 0) {
  205. close(ptm);
  206. return BOOL_FALSE;
  207. }
  208. kexec_set_stdin(exec, ptm);
  209. kexec_set_stdout(exec, ptm);
  210. kexec_set_stderr(exec, ptm);
  211. kcontext_set_stdin(context, pts);
  212. kcontext_set_stdout(context, pts);
  213. kcontext_set_stderr(context, pts);
  214. return BOOL_TRUE;
  215. }
  216. // Create "global" stdin, stdout, stderr for the whole job execution.
  217. // Now function creates only the simple pipes but somedays it will be
  218. // able to create pseudo-terminal for interactive sessions.
  219. // STDIN
  220. if (pipe(pipefd) < 0)
  221. return BOOL_FALSE;
  222. kcontext_set_stdin(faux_list_data(faux_list_head(exec->contexts)),
  223. pipefd[0]); // Read end
  224. kexec_set_stdin(exec, pipefd[1]); // Write end
  225. // STDOUT
  226. if (pipe(pipefd) < 0)
  227. return BOOL_FALSE;
  228. // Read end of 'stdout' pipe must be non-blocked
  229. fflags = fcntl(pipefd[0], F_GETFL);
  230. fcntl(pipefd[0], F_SETFL, fflags | O_NONBLOCK);
  231. kexec_set_stdout(exec, pipefd[0]); // Read end
  232. kcontext_set_stdout(faux_list_data(faux_list_tail(exec->contexts)),
  233. pipefd[1]); // Write end
  234. // STDERR
  235. if (pipe(pipefd) < 0)
  236. return BOOL_FALSE;
  237. // Read end of 'stderr' pipe must be non-blocked
  238. fflags = fcntl(pipefd[0], F_GETFL);
  239. fcntl(pipefd[0], F_SETFL, fflags | O_NONBLOCK);
  240. kexec_set_stderr(exec, pipefd[0]); // Read end
  241. // STDERR write end will be set to all list members as stderr
  242. global_stderr = pipefd[1]; // Write end
  243. // Iterate all context_t elements to fill all stdin, stdout, stderr
  244. for (iter = faux_list_head(exec->contexts); iter;
  245. iter = faux_list_next_node(iter)) {
  246. faux_list_node_t *next = faux_list_next_node(iter);
  247. kcontext_t *context = (kcontext_t *)faux_list_data(iter);
  248. // The first context is a context of main command. The other
  249. // contexts are contexts of filters. So save current path from
  250. // first context.
  251. if (iter == faux_list_head(exec->contexts)) {
  252. ksession_t *session = kcontext_session(context);
  253. if (session && ksession_path(session))
  254. exec->saved_path = kpath_clone(
  255. ksession_path(session));
  256. }
  257. // Set the same STDERR to all contexts
  258. kcontext_set_stderr(context, global_stderr);
  259. // Create pipes beetween processes
  260. if (next) {
  261. kcontext_t *next_context = (kcontext_t *)faux_list_data(next);
  262. if (pipe(pipefd) < 0)
  263. return BOOL_FALSE;
  264. kcontext_set_stdout(context, pipefd[1]); // Write end
  265. kcontext_set_stdin(next_context, pipefd[0]); // Read end
  266. }
  267. }
  268. return BOOL_TRUE;
  269. }
  270. // === SYNC symbol execution
  271. // The function will be executed right here. It's necessary for
  272. // navigation implementation for example. To grab function output the
  273. // service process will be forked. It gets output and stores it to the
  274. // internal buffer. After sym function return grabber will write
  275. // buffered data back. So grabber will simulate async sym execution.
  276. static bool_t exec_action_sync(kcontext_t *context, const kaction_t *action,
  277. pid_t *pid, int *retcode)
  278. {
  279. ksym_fn fn = NULL;
  280. int exitcode = 0;
  281. pid_t child_pid = -1;
  282. int pipe_stdout[2] = {};
  283. int pipe_stderr[2] = {};
  284. // Create pipes beetween sym function and grabber
  285. if (pipe(pipe_stdout) < 0)
  286. return BOOL_FALSE;
  287. if (pipe(pipe_stderr) < 0) {
  288. close(pipe_stdout[0]);
  289. close(pipe_stdout[1]);
  290. return BOOL_FALSE;
  291. }
  292. fn = ksym_function(kaction_sym(action));
  293. // Prepare streams before fork
  294. fflush(stdout);
  295. fflush(stderr);
  296. // Fork the grabber
  297. child_pid = fork();
  298. if (child_pid == -1) {
  299. close(pipe_stdout[0]);
  300. close(pipe_stdout[1]);
  301. close(pipe_stderr[0]);
  302. close(pipe_stderr[1]);
  303. return BOOL_FALSE;
  304. }
  305. // Parent
  306. if (child_pid != 0) {
  307. int saved_stdout = -1;
  308. int saved_stderr = -1;
  309. // Save pid of grabber
  310. if (pid)
  311. *pid = child_pid;
  312. // Temporarily replace orig output streams by pipe
  313. // stdout
  314. saved_stdout = dup(STDOUT_FILENO);
  315. dup2(pipe_stdout[1], STDOUT_FILENO);
  316. close(pipe_stdout[0]);
  317. close(pipe_stdout[1]);
  318. // stderr
  319. saved_stderr = dup(STDERR_FILENO);
  320. dup2(pipe_stderr[1], STDERR_FILENO);
  321. close(pipe_stderr[0]);
  322. close(pipe_stderr[1]);
  323. // Execute sym function right here
  324. exitcode = fn(context);
  325. if (retcode)
  326. *retcode = exitcode;
  327. // Restore orig output streams
  328. // stdout
  329. fflush(stdout);
  330. dup2(saved_stdout, STDOUT_FILENO);
  331. close(saved_stdout);
  332. // stderr
  333. fflush(stderr);
  334. dup2(saved_stderr, STDERR_FILENO);
  335. close(saved_stderr);
  336. return BOOL_TRUE;
  337. }
  338. // Child (Output grabber)
  339. close(pipe_stdout[1]);
  340. close(pipe_stderr[1]);
  341. {
  342. int fds[][2] = {
  343. {pipe_stdout[0], kcontext_stdout(context)},
  344. {pipe_stderr[0], kcontext_stderr(context)},
  345. {-1, -1},
  346. };
  347. grabber(fds);
  348. }
  349. close(pipe_stdout[0]);
  350. close(pipe_stderr[0]);
  351. _exit(0);
  352. return BOOL_TRUE;
  353. }
  354. // === ASYNC symbol execution
  355. // The process will be forked and sym will be executed there.
  356. // The parent will save forked process's pid and immediately return
  357. // control to event loop which will get forked process stdout and
  358. // wait for process termination.
  359. static bool_t exec_action_async(kcontext_t *context, const kaction_t *action,
  360. pid_t *pid)
  361. {
  362. ksym_fn fn = NULL;
  363. int exitcode = 0;
  364. pid_t child_pid = -1;
  365. fn = ksym_function(kaction_sym(action));
  366. // Oh, it's amazing world of stdio!
  367. // Flush buffers before fork() because buffer content will be inherited
  368. // by child. Moreover dup2() can replace old stdout file descriptor by
  369. // the new one but buffer linked with stdout stream will remain the same.
  370. // It must be empty.
  371. fflush(stdout);
  372. fflush(stderr);
  373. child_pid = fork();
  374. if (child_pid == -1)
  375. return BOOL_FALSE;
  376. // Parent
  377. // Save the child pid and return control. Later event loop will wait
  378. // for saved pid.
  379. if (child_pid != 0) {
  380. if (pid)
  381. *pid = child_pid;
  382. return BOOL_TRUE;
  383. }
  384. // Child
  385. dup2(kcontext_stdin(context), STDIN_FILENO);
  386. dup2(kcontext_stdout(context), STDOUT_FILENO);
  387. dup2(kcontext_stderr(context), STDERR_FILENO);
  388. exitcode = fn(context);
  389. // We will use _exit() later so stdio streams will remain unflushed.
  390. // Some output data can be lost. Flush necessary streams here.
  391. fflush(stdout);
  392. fflush(stderr);
  393. // Use _exit() but not exit() to don't flush all the stdio streams. It
  394. // can be dangerous because parent can have a lot of streams inhereted
  395. // by child process.
  396. _exit(exitcode);
  397. return BOOL_TRUE;
  398. }
  399. static bool_t exec_action(kcontext_t *context, const kaction_t *action,
  400. pid_t *pid, int *retcode)
  401. {
  402. assert(context);
  403. if (!context)
  404. return BOOL_FALSE;
  405. assert(action);
  406. if (!action)
  407. return BOOL_FALSE;
  408. if (kaction_is_sync(action))
  409. return exec_action_sync(context, action, pid, retcode);
  410. return exec_action_async(context, action, pid);
  411. }
  412. static bool_t exec_action_sequence(const kexec_t *exec, kcontext_t *context,
  413. pid_t pid, int wstatus)
  414. {
  415. faux_list_node_t *iter = NULL;
  416. int exitstatus = WEXITSTATUS(wstatus);
  417. pid_t new_pid = -1; // PID of newly forked ACTION process
  418. assert(context);
  419. if (!context)
  420. return BOOL_FALSE;
  421. // There is two reasons to don't start any real actions.
  422. // - The ACTION sequence is already done;
  423. // - Passed PID (PID of completed process) is not owned by this context.
  424. // Returns false that indicates this PID is not mine.
  425. if (kcontext_done(context) || (kcontext_pid(context) != pid))
  426. return BOOL_FALSE;
  427. // Here we know that given PID is our PID
  428. iter = kcontext_action_iter(context); // Get saved current ACTION
  429. // ASYNC: Compute new value for retcode.
  430. // Here iter is a pointer to previous action but not new.
  431. // It's for async actions only. Sync actions will change global
  432. // retcode after the exec_action() invocation.
  433. if (iter) {
  434. const kaction_t *terminated_action = faux_list_data(iter);
  435. assert(terminated_action);
  436. if (!kaction_is_sync(terminated_action) &&
  437. kaction_update_retcode(terminated_action))
  438. kcontext_set_retcode(context, exitstatus);
  439. }
  440. // Loop is needed because some ACTIONs will be skipped due to specified
  441. // execution conditions. So try next actions.
  442. do {
  443. const kaction_t *action = NULL;
  444. bool_t is_sync = BOOL_FALSE;
  445. // Get next ACTION from sequence
  446. if (!iter) { // Is it the first ACTION within list
  447. faux_list_t *actions =
  448. kentry_actions(kpargv_command(kcontext_pargv(context)));
  449. assert(actions);
  450. iter = faux_list_head(actions);
  451. } else {
  452. iter = faux_list_next_node(iter);
  453. }
  454. kcontext_set_action_iter(context, iter);
  455. // Is it end of ACTION sequence?
  456. if (!iter) {
  457. kcontext_set_done(context, BOOL_TRUE);
  458. return BOOL_TRUE;
  459. }
  460. // Get new ACTION to execute
  461. action = (const kaction_t *)faux_list_data(iter);
  462. assert(action);
  463. // Check for previous retcode to find out if next command must
  464. // be executed or skipped.
  465. if (!kaction_meet_exec_conditions(action, kcontext_retcode(context)))
  466. continue; // Skip action, try next one
  467. // Check for dry-run flag and 'permanent' feature of ACTION.
  468. if (kexec_dry_run(exec) && !kaction_is_permanent(action)) {
  469. is_sync = BOOL_TRUE; // Simulate sync action
  470. exitstatus = 0; // Exit status while dry-run is always 0
  471. } else { // Normal execution
  472. is_sync = kaction_is_sync(action);
  473. exec_action(context, action, &new_pid, &exitstatus);
  474. }
  475. // SYNC: Compute new value for retcode.
  476. // Sync actions return retcode immediatelly. Their forked
  477. // processes are for output handling only.
  478. if (is_sync && kaction_update_retcode(action))
  479. kcontext_set_retcode(context, exitstatus);
  480. } while (-1 == new_pid); // PID is not -1 when new process was forked
  481. // Save PID of newly created process
  482. kcontext_set_pid(context, new_pid);
  483. return BOOL_TRUE;
  484. }
  485. bool_t kexec_continue_command_execution(kexec_t *exec, pid_t pid, int wstatus)
  486. {
  487. faux_list_node_t *iter = NULL;
  488. kcontext_t *context = NULL;
  489. assert(exec);
  490. if (!exec)
  491. return BOOL_FALSE;
  492. iter = kexec_contexts_iter(exec);
  493. while ((context = kexec_contexts_each(&iter))) {
  494. bool_t found = BOOL_FALSE;
  495. found = exec_action_sequence(exec, context, pid, wstatus);
  496. if (found && (pid != -1))
  497. break;
  498. }
  499. return BOOL_TRUE;
  500. }
  501. bool_t kexec_exec(kexec_t *exec)
  502. {
  503. kcontext_t *context = NULL;
  504. const kpargv_t *pargv = NULL;
  505. const kentry_t *entry = NULL;
  506. bool_t restore = BOOL_FALSE;
  507. assert(exec);
  508. if (!exec)
  509. return BOOL_FALSE;
  510. // Firsly prepare kexec object for execution. The file streams must
  511. // be created for stdin, stdout, stderr of processes.
  512. if (!kexec_prepare(exec))
  513. return BOOL_FALSE;
  514. // Pre-change VIEW if command has "restore" flag. Only first command in
  515. // line (if many commands are piped) matters. Filters can't change the
  516. // VIEW.
  517. context = (kcontext_t *)faux_list_data(faux_list_head(exec->contexts));
  518. pargv = kcontext_pargv(context);
  519. entry = kpargv_command(pargv);
  520. if (entry)
  521. restore = kentry_restore(entry);
  522. if (restore) {
  523. size_t level = kpargv_level(pargv);
  524. kpath_t *path = ksession_path(kcontext_session(context));
  525. while(kpath_len(path) > (level + 1))
  526. kpath_pop(path);
  527. }
  528. // Here no ACTIONs are executing, so pass -1 as pid of terminated
  529. // ACTION's process.
  530. kexec_continue_command_execution(exec, -1, 0);
  531. return BOOL_TRUE;
  532. }
  533. bool_t kexec_interactive(const kexec_t *exec)
  534. {
  535. faux_list_node_t *node = NULL;
  536. kcontext_t *context = NULL;
  537. const kentry_t *entry = NULL;
  538. assert(exec);
  539. if (!exec)
  540. return BOOL_FALSE;
  541. // Only the ACTION of first context can be interactive
  542. node = faux_list_head(exec->contexts);
  543. if (!node)
  544. return BOOL_FALSE;
  545. context = (kcontext_t *)faux_list_data(node);
  546. if (!context)
  547. return BOOL_FALSE;
  548. entry = kcontext_command(context);
  549. if (!entry)
  550. return BOOL_FALSE;
  551. return kentry_interactive(entry);
  552. }