shell_execute.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. * shell_execute.c
  3. */
  4. #include "private.h"
  5. #include "lub/string.h"
  6. #include "lub/argv.h"
  7. #include <assert.h>
  8. #include <stdio.h>
  9. #include <unistd.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <errno.h>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <sys/file.h>
  16. #include <sys/wait.h>
  17. #include <sys/uio.h>
  18. #include <signal.h>
  19. #include <fcntl.h>
  20. /* Empty signal handler to ignore signal but don't use SIG_IGN. */
  21. static void sig_ignore_handler(int signo)
  22. {
  23. signo = signo; /* Happy compiler */
  24. return;
  25. }
  26. /*-------------------------------------------------------- */
  27. static int clish_shell_lock(const char *lock_path)
  28. {
  29. int i;
  30. int res = -1;
  31. int lock_fd = -1;
  32. struct flock lock;
  33. if (!lock_path)
  34. return -1;
  35. lock_fd = open(lock_path, O_WRONLY | O_CREAT, 00644);
  36. if (-1 == lock_fd) {
  37. fprintf(stderr, "Warning: Can't open lockfile %s.\n", lock_path);
  38. return -1;
  39. }
  40. #ifdef FD_CLOEXEC
  41. fcntl(lock_fd, F_SETFD, fcntl(lock_fd, F_GETFD) | FD_CLOEXEC);
  42. #endif
  43. memset(&lock, 0, sizeof(lock));
  44. lock.l_type = F_WRLCK;
  45. lock.l_whence = SEEK_SET;
  46. for (i = 0; i < CLISH_LOCK_WAIT; i++) {
  47. res = fcntl(lock_fd, F_SETLK, &lock);
  48. if (res != -1)
  49. break;
  50. if (EINTR == errno)
  51. continue;
  52. if ((EAGAIN == errno) || (EACCES == errno)) {
  53. if (0 == i)
  54. fprintf(stderr,
  55. "Warning: Try to get lock. Please wait...\n");
  56. sleep(1);
  57. continue;
  58. }
  59. if (EINVAL == errno)
  60. fprintf(stderr, "Error: Locking isn't supported by OS, consider \"--lockless\".\n");
  61. break;
  62. }
  63. if (res == -1) {
  64. fprintf(stderr, "Error: Can't get lock.\n");
  65. close(lock_fd);
  66. return -1;
  67. }
  68. return lock_fd;
  69. }
  70. /*-------------------------------------------------------- */
  71. static void clish_shell_unlock(int lock_fd)
  72. {
  73. struct flock lock;
  74. if (lock_fd == -1)
  75. return;
  76. memset(&lock, 0, sizeof(lock));
  77. lock.l_type = F_UNLCK;
  78. lock.l_whence = SEEK_SET;
  79. fcntl(lock_fd, F_SETLK, &lock);
  80. close(lock_fd);
  81. }
  82. /*----------------------------------------------------------- */
  83. // Prints return value in a case of machine oriented protocol
  84. void clish_shell_machine_retval(clish_shell_t *shell, int retval)
  85. {
  86. assert(shell);
  87. if (!shell)
  88. return;
  89. if (!clish_shell_is_machine_interface(shell))
  90. return;
  91. printf("\033[%dR\n", retval);
  92. fflush(stdout);
  93. }
  94. /*----------------------------------------------------------- */
  95. int clish_shell_execute(clish_context_t *context, char **out)
  96. {
  97. clish_shell_t *this = clish_context__get_shell(context);
  98. const clish_command_t *cmd = clish_context__get_cmd(context);
  99. int result = 0;
  100. const char *lock_path = clish_shell__get_lockfile(this);
  101. int lock_fd = -1;
  102. clish_view_t *cur_view = clish_shell__get_view(this);
  103. unsigned int saved_wdog_timeout = this->wdog_timeout;
  104. assert(cmd);
  105. /* Pre-change view if the command is from another depth/view */
  106. {
  107. clish_view_restore_e restore = clish_command__get_restore(cmd);
  108. if ((CLISH_RESTORE_VIEW == restore) &&
  109. (clish_command__get_pview(cmd) != cur_view)) {
  110. clish_view_t *view = clish_command__get_pview(cmd);
  111. clish_shell__set_pwd(this, NULL, view, NULL, context);
  112. } else if ((CLISH_RESTORE_DEPTH == restore) &&
  113. (clish_command__get_depth(cmd) < this->depth)) {
  114. this->depth = clish_command__get_depth(cmd);
  115. }
  116. }
  117. /* Lock the lockfile */
  118. if (lock_path && clish_action__get_lock(clish_command__get_action(cmd))) {
  119. lock_fd = clish_shell_lock(lock_path);
  120. if (-1 == lock_fd) {
  121. result = -1;
  122. goto error; /* Can't set lock */
  123. }
  124. }
  125. /* Execute ACTION */
  126. clish_context__set_action(context, clish_command__get_action(cmd));
  127. result = clish_shell_exec_action(context, out);
  128. /* Call config callback */
  129. if (!result)
  130. clish_shell_exec_config(context);
  131. /* Call logging callback */
  132. if (clish_shell__get_log(this) &&
  133. clish_shell_check_hook(context, CLISH_SYM_TYPE_LOG)) {
  134. char *full_line = clish_shell__get_full_line(context);
  135. clish_shell_exec_log(context, full_line, result);
  136. lub_string_free(full_line);
  137. }
  138. if (clish_shell__get_canon_out(this) &&
  139. !clish_command__get_internal(cmd)) {
  140. char *space = NULL;
  141. char *full_line = clish_shell__get_full_line(context);
  142. if (this->depth > 0) {
  143. space = malloc(this->depth + 1);
  144. memset(space, ' ', this->depth);
  145. space[this->depth] = '\0';
  146. }
  147. printf("%s%s\n", space ? space : "", full_line);
  148. lub_string_free(full_line);
  149. if (space)
  150. free(space);
  151. }
  152. // Machine oriented protocol outputs return value
  153. // Note there is some ugly architecture aspect - machine retval
  154. // and logging are executed within clish_shell_tinyrl_key_enter()
  155. // function also. This function is for completed
  156. // commands but ...key_enter() do the same for wrong/incompleted
  157. // commands.
  158. clish_shell_machine_retval(this, result);
  159. /* Unlock the lockfile */
  160. if (lock_fd != -1)
  161. clish_shell_unlock(lock_fd);
  162. /* Move into the new view */
  163. if (!result) {
  164. char *viewname = clish_shell_expand(clish_command__get_viewname(cmd), SHELL_VAR_NONE, context);
  165. if (viewname) {
  166. /* Search for the view */
  167. clish_view_t *view = clish_shell_find_view(this, viewname);
  168. if (!view)
  169. fprintf(stderr, "System error: Can't "
  170. "change view to %s\n", viewname);
  171. lub_string_free(viewname);
  172. /* Save the PWD */
  173. if (view) {
  174. char *line = clish_shell__get_line(context);
  175. clish_shell__set_pwd(this, line, view,
  176. clish_command__get_viewid(cmd), context);
  177. lub_string_free(line);
  178. }
  179. }
  180. }
  181. /* Set appropriate timeout. Workaround: Don't turn on watchdog
  182. on the "set watchdog <timeout>" command itself. */
  183. if (this->wdog_timeout && saved_wdog_timeout) {
  184. tinyrl__set_timeout(this->tinyrl, this->wdog_timeout);
  185. this->wdog_active = BOOL_TRUE;
  186. fprintf(stderr, "Warning: The watchdog is active. Timeout is %u "
  187. "seconds.\nWarning: Press any key to stop watchdog.\n",
  188. this->wdog_timeout);
  189. } else
  190. tinyrl__set_timeout(this->tinyrl, this->idle_timeout);
  191. error:
  192. return result;
  193. }
  194. /*----------------------------------------------------------- */
  195. /* Execute oaction. It suppose the forked process to get
  196. * script's stdout. Then forked process write the output back
  197. * to klish.
  198. */
  199. static int clish_shell_exec_oaction(clish_hook_oaction_fn_t func,
  200. void *context, const char *script, char **out)
  201. {
  202. int result = -1;
  203. int real_stdout; /* Saved stdout handler */
  204. int pipe1[2], pipe2[2];
  205. pid_t cpid = -1;
  206. konf_buf_t *buf;
  207. if (pipe(pipe1))
  208. return -1;
  209. if (pipe(pipe2))
  210. goto stdout_error;
  211. /* Create process to read script's stdout */
  212. cpid = fork();
  213. if (cpid == -1) {
  214. fprintf(stderr, "Error: Can't fork the stdout-grabber process.\n"
  215. "Error: The ACTION will be not executed.\n");
  216. goto stdout_error;
  217. }
  218. /* Child: read action's stdout */
  219. if (cpid == 0) {
  220. lub_list_t *l;
  221. lub_list_node_t *node;
  222. struct iovec *iov;
  223. const int rsize = CLISH_STDOUT_CHUNK; /* Read chunk size */
  224. size_t cur_size = 0;
  225. ssize_t r = 0;
  226. close(pipe1[1]);
  227. close(pipe2[0]);
  228. l = lub_list_new(NULL, NULL);
  229. /* Read the result of script execution */
  230. while (1) {
  231. ssize_t ret;
  232. iov = malloc(sizeof(*iov));
  233. iov->iov_len = rsize;
  234. iov->iov_base = malloc(iov->iov_len);
  235. do {
  236. ret = readv(pipe1[0], iov, 1);
  237. } while ((ret < 0) && (errno == EINTR));
  238. if (ret <= 0) { /* Error or EOF */
  239. free(iov->iov_base);
  240. free(iov);
  241. break;
  242. }
  243. iov->iov_len = ret;
  244. lub_list_add(l, iov);
  245. /* Check the max size of buffer */
  246. cur_size += ret;
  247. if (cur_size >= CLISH_STDOUT_MAXBUF)
  248. break;
  249. }
  250. close(pipe1[0]);
  251. /* Write the result of script back to klish */
  252. while ((node = lub_list__get_head(l))) {
  253. iov = lub_list_node__get_data(node);
  254. lub_list_del(l, node);
  255. lub_list_node_free(node);
  256. r = write(pipe2[1], iov->iov_base, iov->iov_len);
  257. free(iov->iov_base);
  258. free(iov);
  259. }
  260. close(pipe2[1]);
  261. lub_list_free(l);
  262. _exit(r < 0 ? 1 : 0);
  263. }
  264. real_stdout = dup(STDOUT_FILENO);
  265. dup2(pipe1[1], STDOUT_FILENO);
  266. close(pipe1[0]);
  267. close(pipe1[1]);
  268. close(pipe2[1]);
  269. result = func(context, script);
  270. /* Restore real stdout */
  271. dup2(real_stdout, STDOUT_FILENO);
  272. close(real_stdout);
  273. /* Read the result of script execution */
  274. buf = konf_buf_new(pipe2[0]);
  275. while (konf_buf_read(buf) > 0);
  276. *out = konf_buf__dup_line(buf);
  277. konf_buf_delete(buf);
  278. close(pipe2[0]);
  279. /* Wait for the stdout-grabber process */
  280. while (waitpid(cpid, NULL, 0) != cpid);
  281. return result;
  282. stdout_error:
  283. close(pipe1[0]);
  284. close(pipe1[1]);
  285. return -1;
  286. }
  287. /*----------------------------------------------------------- */
  288. int clish_shell_exec_action(clish_context_t *context, char **out)
  289. {
  290. int result = -1;
  291. const clish_sym_t *sym;
  292. const char *rscript;
  293. char *script;
  294. const void *func = NULL; /* We don't know the func API at this time */
  295. const clish_action_t *action = clish_context__get_action(context);
  296. clish_shell_t *shell = clish_context__get_shell(context);
  297. bool_t intr = clish_action__get_interrupt(action);
  298. /* Signal vars */
  299. struct sigaction old_sigint, old_sigquit, old_sighup;
  300. struct sigaction sa;
  301. sigset_t old_sigs;
  302. if (!(sym = clish_action__get_builtin(action)))
  303. return 0;
  304. if (shell->dryrun &&
  305. !clish_sym__get_permanent(sym) &&
  306. !clish_action__get_permanent(action))
  307. return 0;
  308. if (!(func = clish_sym__get_func(sym))) {
  309. fprintf(stderr, "Error: Default ACTION symbol is not specified.\n");
  310. return -1;
  311. }
  312. /* Expand variables, but only if the sym or action want it */
  313. rscript = clish_action__get_script(action);
  314. if(clish_context__get_expand(context))
  315. script = clish_shell_expand(rscript, SHELL_VAR_ACTION, context);
  316. else
  317. script = lub_string_dup(rscript);
  318. /* Ignore and block SIGINT, SIGQUIT, SIGHUP.
  319. * The SIG_IGN is not a case because it will be inherited
  320. * while a fork(). It's necessary to ignore signals because
  321. * the klish itself and ACTION script share the same terminal.
  322. */
  323. sa.sa_flags = 0;
  324. sigemptyset(&sa.sa_mask);
  325. sa.sa_handler = sig_ignore_handler; /* Empty signal handler */
  326. sigaction(SIGINT, &sa, &old_sigint);
  327. sigaction(SIGQUIT, &sa, &old_sigquit);
  328. /* Block signals for children processes. The block state is inherited. */
  329. if (!intr) {
  330. sigset_t sigs;
  331. // Ignore SIGHUP only for non-interruptible commands.
  332. // Because these commands must be atomic. And when terminal
  333. // is closed command must finish its actions. In the same
  334. // time when command is interactive and terminal is closed
  335. // klish must not ignore SIGHUP. Else interactive command
  336. // will be executed continuosly because klish will not stop
  337. // on terminal closing.
  338. sigaction(SIGHUP, &sa, &old_sighup);
  339. sigemptyset(&sigs);
  340. sigaddset(&sigs, SIGINT);
  341. sigaddset(&sigs, SIGQUIT);
  342. sigaddset(&sigs, SIGHUP);
  343. sigprocmask(SIG_BLOCK, &sigs, &old_sigs);
  344. }
  345. /* Find out the function API */
  346. /* CLISH_SYM_API_SIMPLE */
  347. if (clish_sym__get_api(sym) == CLISH_SYM_API_SIMPLE) {
  348. result = ((clish_hook_action_fn_t *)func)(context, script, out);
  349. /* CLISH_SYM_API_STDOUT and output is not needed */
  350. } else if ((clish_sym__get_api(sym) == CLISH_SYM_API_STDOUT) && (!out)) {
  351. result = ((clish_hook_oaction_fn_t *)func)(context, script);
  352. /* CLISH_SYM_API_STDOUT and outpus is needed */
  353. } else if (clish_sym__get_api(sym) == CLISH_SYM_API_STDOUT) {
  354. result = clish_shell_exec_oaction((clish_hook_oaction_fn_t *)func,
  355. context, script, out);
  356. }
  357. /* Restore SIGINT, SIGQUIT, SIGHUP */
  358. if (!intr) {
  359. sigprocmask(SIG_SETMASK, &old_sigs, NULL);
  360. /* Is the signals delivery guaranteed here (before
  361. sigaction restore) for previously blocked and
  362. pending signals? The simple test is working well.
  363. I don't want to use sigtimedwait() function because
  364. it needs a realtime extensions. The sigpending() with
  365. the sleep() is not nice too. Report bug if clish will
  366. get the SIGINT after non-interruptable action.
  367. */
  368. sigaction(SIGHUP, &old_sighup, NULL);
  369. }
  370. // Restore signals
  371. sigaction(SIGINT, &old_sigint, NULL);
  372. sigaction(SIGQUIT, &old_sigquit, NULL);
  373. lub_string_free(script);
  374. return result;
  375. }
  376. /*----------------------------------------------------------- */
  377. const void *clish_shell_check_hook(const clish_context_t *clish_context, int type)
  378. {
  379. clish_sym_t *sym;
  380. clish_shell_t *shell = clish_context__get_shell(clish_context);
  381. const void *func;
  382. if (!(sym = shell->hooks[type]))
  383. return NULL;
  384. if (shell->dryrun && !clish_sym__get_permanent(sym))
  385. return NULL;
  386. if (!(func = clish_sym__get_func(sym)))
  387. return NULL;
  388. return func;
  389. }
  390. /*----------------------------------------------------------- */
  391. CLISH_HOOK_CONFIG(clish_shell_exec_config)
  392. {
  393. clish_hook_config_fn_t *func = NULL;
  394. func = clish_shell_check_hook(clish_context, CLISH_SYM_TYPE_CONFIG);
  395. return func ? func(clish_context) : 0;
  396. }
  397. /*----------------------------------------------------------- */
  398. CLISH_HOOK_LOG(clish_shell_exec_log)
  399. {
  400. clish_hook_log_fn_t *func = NULL;
  401. func = clish_shell_check_hook(clish_context, CLISH_SYM_TYPE_LOG);
  402. return func ? func(clish_context, line, retcode) : 0;
  403. }
  404. /*----------------------------------------------------------- */
  405. char *clish_shell_mkfifo(clish_shell_t * this, char *name, size_t n)
  406. {
  407. int res;
  408. if (n < 1) /* Buffer too small */
  409. return NULL;
  410. do {
  411. strncpy(name, this->fifo_temp, n);
  412. name[n - 1] = '\0';
  413. mktemp(name);
  414. if (name[0] == '\0')
  415. return NULL;
  416. res = mkfifo(name, 0600);
  417. } while ((res < 0) && (EEXIST == errno));
  418. return name;
  419. }
  420. /*----------------------------------------------------------- */
  421. int clish_shell_rmfifo(clish_shell_t * this, const char *name)
  422. {
  423. this = this; // Happy compiler
  424. return unlink(name);
  425. }
  426. CLISH_SET(shell, bool_t, log);
  427. CLISH_GET(shell, bool_t, log);
  428. CLISH_SET(shell, bool_t, dryrun);
  429. CLISH_GET(shell, bool_t, dryrun);
  430. CLISH_SET(shell, bool_t, canon_out);
  431. CLISH_GET(shell, bool_t, canon_out);