kexec.c 13 KB

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