kexec.c 15 KB

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