kexec.c 14 KB

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