kexec.c 15 KB

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