Merge branch '1618_rpm_spec_fix'
[midnight-commander.git] / src / subshell.c
blobe4883b270208c74d9b63fa528910a38f0eb828b5
1 /* Concurrent shell support for the Midnight Commander
2 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of Version 2 of the GNU General Public
7 License, as published by the Free Software Foundation.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 /** \file subshell.c
20 * \brief Source: concurrent shell support
23 #include <config.h>
25 #ifdef HAVE_SUBSHELL_SUPPORT
27 #ifndef _GNU_SOURCE
28 # define _GNU_SOURCE 1
29 #endif
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_TERMIOS_H
44 #include <termios.h>
45 #endif
46 #include <unistd.h>
48 #ifdef HAVE_STROPTS_H
49 # include <stropts.h> /* For I_PUSH */
50 #endif /* HAVE_STROPTS_H */
52 #include "global.h"
53 #include "../src/tty/tty.h" /* LINES */
54 #include "panel.h" /* current_panel */
55 #include "wtools.h" /* query_dialog() */
56 #include "main.h" /* do_update_prompt() */
57 #include "cons.saver.h" /* handle_console() */
58 #include "../src/tty/key.h" /* XCTRL */
59 #include "subshell.h"
60 #include "strutil.h"
61 #include "fileloc.h"
63 #ifndef WEXITSTATUS
64 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
65 #endif
67 #ifndef WIFEXITED
68 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
69 #endif
71 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
72 static char tcsh_fifo[128];
74 /* Local functions */
75 static void init_raw_mode (void);
76 static int feed_subshell (int how, int fail_on_error);
77 static void synchronize (void);
78 static int pty_open_master (char *pty_name);
79 static int pty_open_slave (const char *pty_name);
80 static int resize_tty (int fd);
82 #ifndef STDIN_FILENO
83 # define STDIN_FILENO 0
84 #endif
86 #ifndef STDOUT_FILENO
87 # define STDOUT_FILENO 1
88 #endif
90 #ifndef STDERR_FILENO
91 # define STDERR_FILENO 2
92 #endif
94 /* If using a subshell for evaluating commands this is true */
95 int use_subshell =
96 #ifdef SUBSHELL_OPTIONAL
97 FALSE;
98 #else
99 TRUE;
100 #endif
102 /* File descriptors of the pseudoterminal used by the subshell */
103 int subshell_pty = 0;
104 static int subshell_pty_slave = -1;
106 /* The key for switching back to MC from the subshell */
107 static const char subshell_switch_key = XCTRL('o') & 255;
109 /* State of the subshell:
110 * INACTIVE: the default state; awaiting a command
111 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
112 * RUNNING_COMMAND: return to MC when the current command finishes */
113 enum subshell_state_enum subshell_state;
115 /* Holds the latest prompt captured from the subshell */
116 char *subshell_prompt = NULL;
118 /* Initial length of the buffer for the subshell's prompt */
119 #define INITIAL_PROMPT_SIZE 10
121 /* Used by the child process to indicate failure to start the subshell */
122 #define FORK_FAILURE 69 /* Arbitrary */
124 /* Initial length of the buffer for all I/O with the subshell */
125 #define INITIAL_PTY_BUFFER_SIZE 100 /* Arbitrary; but keep it >= 80 */
127 /* For pipes */
128 enum {READ=0, WRITE=1};
130 static char *pty_buffer; /* For reading/writing on the subshell's pty */
131 static int pty_buffer_size; /* The buffer grows as needed */
132 static int subshell_pipe[2]; /* To pass CWD info from the subshell to MC */
133 static pid_t subshell_pid = 1; /* The subshell's process ID */
134 static char subshell_cwd[MC_MAXPATHLEN+1]; /* One extra char for final '\n' */
136 /* Subshell type (gleaned from the SHELL environment variable, if available) */
137 static enum {
138 BASH,
139 TCSH,
140 ZSH,
141 FISH
142 } subshell_type;
144 /* Flag to indicate whether the subshell is ready for next command */
145 static int subshell_ready;
147 /* The following two flags can be changed by the SIGCHLD handler. This is */
148 /* OK, because the `int' type is updated atomically on all known machines */
149 static volatile int subshell_alive, subshell_stopped;
151 /* We store the terminal's initial mode here so that we can configure
152 the pty similarly, and also so we can restore the real terminal to
153 sanity if we have to exit abruptly */
154 static struct termios shell_mode;
156 /* This is a transparent mode for the terminal where MC is running on */
157 /* It is used when the shell is active, so that the control signals */
158 /* are delivered to the shell pty */
159 static struct termios raw_mode;
161 /* This counter indicates how many characters of prompt we have read */
162 /* FIXME: try to figure out why this had to become global */
163 static int prompt_pos;
167 * Write all data, even if the write() call is interrupted.
169 static ssize_t
170 write_all (int fd, const void *buf, size_t count)
172 ssize_t ret;
173 ssize_t written = 0;
174 while (count > 0) {
175 ret = write (fd, (const unsigned char *) buf + written, count);
176 if (ret < 0) {
177 if (errno == EINTR) {
178 continue;
179 } else {
180 return written > 0 ? written : ret;
183 count -= ret;
184 written += ret;
186 return written;
190 * Prepare child process to running the shell and run it.
192 * Modifies the global variables (in the child process only):
193 * shell_mode
195 * Returns: never.
197 static void
198 init_subshell_child (const char *pty_name)
200 const char *init_file = NULL;
201 #ifdef HAVE_GETSID
202 pid_t mc_sid;
203 #endif /* HAVE_GETSID */
205 (void) pty_name;
206 setsid (); /* Get a fresh terminal session */
208 /* Make sure that it has become our controlling terminal */
210 /* Redundant on Linux and probably most systems, but just in case: */
212 #ifdef TIOCSCTTY
213 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
214 #endif
216 /* Configure its terminal modes and window size */
218 /* Set up the pty with the same termios flags as our own tty, plus */
219 /* TOSTOP, which keeps background processes from writing to the pty */
221 shell_mode.c_lflag |= TOSTOP; /* So background writers get SIGTTOU */
222 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode)) {
223 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n",
224 unix_error_string (errno));
225 _exit (FORK_FAILURE);
228 /* Set the pty's size (80x25 by default on Linux) according to the */
229 /* size of the real terminal as calculated by ncurses, if possible */
230 resize_tty (subshell_pty_slave);
232 /* Set up the subshell's environment and init file name */
234 /* It simplifies things to change to our home directory here, */
235 /* and the user's startup file may do a `cd' command anyway */
236 chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
238 #ifdef HAVE_GETSID
239 /* Set MC_SID to prevent running one mc from another */
240 mc_sid = getsid (0);
241 if (mc_sid != -1) {
242 char sid_str[BUF_SMALL];
243 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld",
244 (long) mc_sid);
245 putenv (g_strdup (sid_str));
247 #endif /* HAVE_GETSID */
249 switch (subshell_type) {
250 case BASH:
251 init_file = MC_USERCONF_DIR PATH_SEP_STR "bashrc";
252 if (access (init_file, R_OK) == -1)
253 init_file = ".bashrc";
255 /* Make MC's special commands not show up in bash's history */
256 putenv ((char*)"HISTCONTROL=ignorespace");
258 /* Allow alternative readline settings for MC */
259 if (access (MC_USERCONF_DIR PATH_SEP_STR "inputrc", R_OK) == 0)
260 putenv ((char*)"INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR "/inputrc");
262 break;
264 /* TODO: Find a way to pass initfile to TCSH and ZSH */
265 case TCSH:
266 case ZSH:
267 case FISH:
268 break;
270 default:
271 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n",
272 subshell_type);
273 _exit (FORK_FAILURE);
276 /* Attach all our standard file descriptors to the pty */
278 /* This is done just before the fork, because stderr must still */
279 /* be connected to the real tty during the above error messages; */
280 /* otherwise the user will never see them. */
282 dup2 (subshell_pty_slave, STDIN_FILENO);
283 dup2 (subshell_pty_slave, STDOUT_FILENO);
284 dup2 (subshell_pty_slave, STDERR_FILENO);
286 close (subshell_pipe[READ]);
287 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
288 /* Close master side of pty. This is important; apart from */
289 /* freeing up the descriptor for use in the subshell, it also */
290 /* means that when MC exits, the subshell will get a SIGHUP and */
291 /* exit too, because there will be no more descriptors pointing */
292 /* at the master side of the pty and so it will disappear. */
293 close (subshell_pty);
295 /* Execute the subshell at last */
297 switch (subshell_type) {
298 case BASH:
299 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
300 break;
302 case TCSH:
303 execl (shell, "tcsh", (char *) NULL);
304 break;
306 case ZSH:
307 /* Use -g to exclude cmds beginning with space from history
308 * and -Z to use the line editor on non-interactive term */
309 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
311 break;
313 case FISH:
314 execl (shell, "fish", (char *) NULL);
315 break;
318 /* If we get this far, everything failed miserably */
319 _exit (FORK_FAILURE);
323 #ifdef HAVE_GETSID
325 * Check MC_SID to prevent running one mc from another.
326 * Return:
327 * 0 if no parent mc in our session was found,
328 * 1 if parent mc was found and the user wants to continue,
329 * 2 if parent mc was found and the user wants to quit mc.
331 static int
332 check_sid (void)
334 pid_t my_sid, old_sid;
335 const char *sid_str;
336 int r;
338 sid_str = getenv ("MC_SID");
339 if (!sid_str)
340 return 0;
342 old_sid = (pid_t) strtol (sid_str, NULL, 0);
343 if (!old_sid)
344 return 0;
346 my_sid = getsid (0);
347 if (my_sid == -1)
348 return 0;
350 /* The parent mc is in a different session, it's OK */
351 if (old_sid != my_sid)
352 return 0;
354 r = query_dialog (_("Warning"),
355 _("GNU Midnight Commander is already\n"
356 "running on this terminal.\n"
357 "Subshell support will be disabled."), D_ERROR, 2,
358 _("&OK"), _("&Quit"));
359 if (r != 0) {
360 return 2;
363 return 1;
365 #endif /* HAVE_GETSID */
369 * Fork the subshell, and set up many, many things.
371 * Possibly modifies the global variables:
372 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
373 * use_subshell - Is set to FALSE if we can't run the subshell
374 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
377 void
378 init_subshell (void)
380 /* This must be remembered across calls to init_subshell() */
381 static char pty_name[BUF_SMALL];
382 char precmd[BUF_SMALL];
384 #ifdef HAVE_GETSID
385 switch (check_sid ()) {
386 case 1:
387 use_subshell = FALSE;
388 return;
389 case 2:
390 use_subshell = FALSE;
391 midnight_shutdown = 1;
392 return;
394 #endif /* HAVE_GETSID */
396 /* Take the current (hopefully pristine) tty mode and make */
397 /* a raw mode based on it now, before we do anything else with it */
398 init_raw_mode ();
400 if (subshell_pty == 0) { /* First time through */
401 /* Find out what type of shell we have */
403 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
404 subshell_type = ZSH;
405 else if (strstr (shell, "/tcsh"))
406 subshell_type = TCSH;
407 else if (strstr (shell, "/csh"))
408 subshell_type = TCSH;
409 else if (strstr (shell, "/bash") || getenv ("BASH"))
410 subshell_type = BASH;
411 else if (strstr (shell, "/fish"))
412 subshell_type = FISH;
413 else {
414 use_subshell = FALSE;
415 return;
418 /* Open a pty for talking to the subshell */
420 /* FIXME: We may need to open a fresh pty each time on SVR4 */
422 subshell_pty = pty_open_master (pty_name);
423 if (subshell_pty == -1) {
424 fprintf (stderr, "Cannot open master side of pty: %s\r\n",
425 unix_error_string (errno));
426 use_subshell = FALSE;
427 return;
429 subshell_pty_slave = pty_open_slave (pty_name);
430 if (subshell_pty_slave == -1) {
431 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
432 pty_name, unix_error_string (errno));
433 use_subshell = FALSE;
434 return;
437 /* Initialise the pty's I/O buffer */
439 pty_buffer_size = INITIAL_PTY_BUFFER_SIZE;
440 pty_buffer = g_malloc (pty_buffer_size);
442 /* Create a pipe for receiving the subshell's CWD */
444 if (subshell_type == TCSH) {
445 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
446 mc_tmpdir (), (int) getpid ());
447 if (mkfifo (tcsh_fifo, 0600) == -1) {
448 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo,
449 unix_error_string (errno));
450 use_subshell = FALSE;
451 return;
454 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
456 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
457 || (subshell_pipe[WRITE] =
458 open (tcsh_fifo, O_RDWR)) == -1) {
459 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
460 perror (__FILE__": open");
461 use_subshell = FALSE;
462 return;
464 } else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe)) {
465 perror (__FILE__": couldn't create pipe");
466 use_subshell = FALSE;
467 return;
471 /* Fork the subshell */
473 subshell_alive = TRUE;
474 subshell_stopped = FALSE;
475 subshell_pid = fork ();
477 if (subshell_pid == -1) {
478 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n",
479 unix_error_string (errno));
480 /* We exit here because, if the process table is full, the */
481 /* other method of running user commands won't work either */
482 exit (1);
485 if (subshell_pid == 0) { /* We are in the child process */
486 init_subshell_child (pty_name);
489 /* Set up `precmd' or equivalent for reading the subshell's CWD */
491 switch (subshell_type) {
492 case BASH:
493 g_snprintf (precmd, sizeof (precmd),
494 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
495 subshell_pipe[WRITE]);
496 break;
498 case ZSH:
499 g_snprintf (precmd, sizeof (precmd),
500 " precmd(){ pwd>&%d;kill -STOP $$ }\n",
501 subshell_pipe[WRITE]);
502 break;
504 case TCSH:
505 g_snprintf (precmd, sizeof (precmd),
506 "set echo_style=both;"
507 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n",
508 tcsh_fifo);
509 break;
510 case FISH:
511 g_snprintf (precmd, sizeof (precmd),
512 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
513 subshell_pipe[WRITE]);
514 break;
517 write_all (subshell_pty, precmd, strlen (precmd));
519 /* Wait until the subshell has started up and processed the command */
521 subshell_state = RUNNING_COMMAND;
522 tty_enable_interrupt_key ();
523 if (!feed_subshell (QUIETLY, TRUE)) {
524 use_subshell = FALSE;
526 tty_disable_interrupt_key ();
527 if (!subshell_alive)
528 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
532 static void init_raw_mode ()
534 static int initialized = 0;
536 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
537 /* original settings. However, here we need to make this tty very raw, */
538 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
539 /* pty. So, instead of changing the code for execute(), pre_exec(), */
540 /* etc, we just set up the modes we need here, before each command. */
542 if (initialized == 0) /* First time: initialise `raw_mode' */
544 tcgetattr (STDOUT_FILENO, &raw_mode);
545 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
546 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
547 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
548 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
549 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
550 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
551 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
552 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
553 initialized = 1;
558 int invoke_subshell (const char *command, int how, char **new_dir)
560 char *pcwd;
562 /* Make the MC terminal transparent */
563 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
565 /* Make the subshell change to MC's working directory */
566 if (new_dir)
567 do_subshell_chdir (current_panel->cwd, TRUE, 1);
569 if (command == NULL) /* The user has done "C-o" from MC */
571 if (subshell_state == INACTIVE)
573 subshell_state = ACTIVE;
574 /* FIXME: possibly take out this hack; the user can
575 re-play it by hitting C-hyphen a few times! */
576 if (subshell_ready)
577 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
580 else /* MC has passed us a user command */
582 if (how == QUIETLY)
583 write_all (subshell_pty, " ", 1);
584 /* FIXME: if command is long (>8KB ?) we go comma */
585 write_all (subshell_pty, command, strlen (command));
586 write_all (subshell_pty, "\n", 1);
587 subshell_state = RUNNING_COMMAND;
588 subshell_ready = FALSE;
591 feed_subshell (how, FALSE);
593 pcwd = vfs_translate_path_n (current_panel->cwd);
594 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
595 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
596 g_free (pcwd);
598 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
599 while (!subshell_alive && !quit && use_subshell)
600 init_subshell ();
602 prompt_pos = 0;
604 return quit;
609 read_subshell_prompt (void)
611 static int prompt_size = INITIAL_PROMPT_SIZE;
612 int bytes = 0, i, rc = 0;
613 struct timeval timeleft = { 0, 0 };
615 fd_set tmp;
616 FD_ZERO (&tmp);
617 FD_SET (subshell_pty, &tmp);
619 if (subshell_prompt == NULL) { /* First time through */
620 subshell_prompt = g_malloc (prompt_size);
621 *subshell_prompt = '\0';
622 prompt_pos = 0;
625 while (subshell_alive
626 && (rc =
627 select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft))) {
628 /* Check for `select' errors */
629 if (rc == -1) {
630 if (errno == EINTR)
631 continue;
632 else {
633 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n",
634 unix_error_string (errno));
635 exit (1);
639 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
641 /* Extract the prompt from the shell output */
643 for (i = 0; i < bytes; ++i)
644 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r') {
645 prompt_pos = 0;
646 } else {
647 if (!pty_buffer[i])
648 continue;
650 subshell_prompt[prompt_pos++] = pty_buffer[i];
651 if (prompt_pos == prompt_size)
652 subshell_prompt =
653 g_realloc (subshell_prompt, prompt_size *= 2);
656 subshell_prompt[prompt_pos] = '\0';
658 if (rc == 0 && bytes == 0)
659 return FALSE;
660 return TRUE;
663 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
664 static int resize_tty (int fd)
666 #if defined TIOCSWINSZ
667 struct winsize tty_size;
669 tty_size.ws_row = LINES;
670 tty_size.ws_col = COLS;
671 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
673 return ioctl (fd, TIOCSWINSZ, &tty_size);
674 #else
675 return 0;
676 #endif
679 /* Resize subshell_pty */
680 void resize_subshell (void)
682 if (use_subshell == 0)
683 return;
685 resize_tty (subshell_pty);
689 exit_subshell (void)
691 int subshell_quit = TRUE;
693 if (subshell_state != INACTIVE && subshell_alive)
694 subshell_quit =
695 !query_dialog (_("Warning"),
696 _(" The shell is still active. Quit anyway? "),
697 D_NORMAL, 2, _("&Yes"), _("&No"));
699 if (subshell_quit) {
700 if (subshell_type == TCSH) {
701 if (unlink (tcsh_fifo) == -1)
702 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
703 tcsh_fifo, unix_error_string (errno));
706 g_free (subshell_prompt);
707 g_free (pty_buffer);
708 subshell_prompt = NULL;
709 pty_buffer = NULL;
712 return subshell_quit;
717 * Carefully quote directory name to allow entering any directory safely,
718 * no matter what weird characters it may contain in its name.
719 * NOTE: Treat directory name an untrusted data, don't allow it to cause
720 * executing any commands in the shell. Escape all control characters.
721 * Use following technique:
723 * printf(1) with format string containing a single conversion specifier,
724 * "b", and an argument which contains a copy of the string passed to
725 * subshell_name_quote() with all characters, except digits and letters,
726 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
727 * numeric value of the character converted to octal number.
729 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
732 static char *
733 subshell_name_quote (const char *s)
735 char *ret, *d;
736 const char *su, *n;
737 const char *quote_cmd_start, *quote_cmd_end;
738 int c;
740 if (subshell_type == FISH) {
741 quote_cmd_start = "(printf \"%b\" '";
742 quote_cmd_end = "')";
743 } else {
744 quote_cmd_start = "\"`printf \"%b\" '";
745 quote_cmd_end = "'`\"";
748 /* Factor 5 because we need \, 0 and 3 other digits per character. */
749 d = ret = g_malloc (1 + (5 * strlen (s)) + (strlen(quote_cmd_start))
750 + (strlen(quote_cmd_end)));
751 if (!d)
752 return NULL;
754 /* Prevent interpreting leading `-' as a switch for `cd' */
755 if (*s == '-') {
756 *d++ = '.';
757 *d++ = '/';
760 /* Copy the beginning of the command to the buffer */
761 strcpy (d, quote_cmd_start);
762 d += strlen(quote_cmd_start);
765 * Print every character except digits and letters as a backslash-escape
766 * sequence of the form \0nnn, where "nnn" is the numeric value of the
767 * character converted to octal number.
769 su = s;
770 for (; su[0] != '\0'; ) {
771 n = str_cget_next_char_safe (su);
772 if (str_isalnum (su)) {
773 memcpy (d, su, n - su);
774 d+= n - su;
775 } else {
776 for (c = 0; c < n - su; c++) {
777 sprintf (d, "\\0%03o", (unsigned char) su[c]);
778 d += 5;
781 su = n;
784 strcpy (d, quote_cmd_end);
786 return ret;
790 /* If it actually changed the directory it returns true */
791 void
792 do_subshell_chdir (const char *directory, int do_update, int reset_prompt)
794 char *pcwd;
795 char *temp;
796 char *translate;
798 pcwd = vfs_translate_path_n (current_panel->cwd);
800 if (!
801 (subshell_state == INACTIVE
802 && strcmp (subshell_cwd, pcwd))) {
803 /* We have to repaint the subshell prompt if we read it from
804 * the main program. Please note that in the code after this
805 * if, the cd command that is sent will make the subshell
806 * repaint the prompt, so we don't have to paint it. */
807 if (do_update)
808 do_update_prompt ();
809 g_free (pcwd);
810 return;
813 /* The initial space keeps this out of the command history (in bash
814 because we set "HISTCONTROL=ignorespace") */
815 write_all (subshell_pty, " cd ", 4);
816 if (*directory) {
817 translate = vfs_translate_path_n (directory);
818 if (translate) {
819 temp = subshell_name_quote (translate);
820 if (temp) {
821 write_all (subshell_pty, temp, strlen (temp));
822 g_free (temp);
823 } else {
824 /* Should not happen unless the directory name is so long
825 that we don't have memory to quote it. */
826 write_all (subshell_pty, ".", 1);
828 g_free (translate);
829 } else {
830 write_all (subshell_pty, ".", 1);
832 } else {
833 write_all (subshell_pty, "/", 1);
835 write_all (subshell_pty, "\n", 1);
837 subshell_state = RUNNING_COMMAND;
838 feed_subshell (QUIETLY, FALSE);
840 if (subshell_alive) {
841 int bPathNotEq = strcmp (subshell_cwd, pcwd);
843 if (bPathNotEq && subshell_type == TCSH) {
844 char rp_subshell_cwd[PATH_MAX];
845 char rp_current_panel_cwd[PATH_MAX];
847 char *p_subshell_cwd =
848 mc_realpath (subshell_cwd, rp_subshell_cwd);
849 char *p_current_panel_cwd =
850 mc_realpath (pcwd, rp_current_panel_cwd);
852 if (p_subshell_cwd == NULL)
853 p_subshell_cwd = subshell_cwd;
854 if (p_current_panel_cwd == NULL)
855 p_current_panel_cwd = pcwd;
856 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
859 if (bPathNotEq && strcmp (pcwd, ".")) {
860 char *cwd = strip_password (g_strdup (pcwd), 1);
861 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
862 g_free (cwd);
866 if (reset_prompt)
867 prompt_pos = 0;
868 update_prompt = FALSE;
870 g_free (pcwd);
871 /* Make sure that MC never stores the CWD in a silly format */
872 /* like /usr////lib/../bin, or the strcmp() above will fail */
876 void
877 subshell_get_console_attributes (void)
879 /* Get our current terminal modes */
881 if (tcgetattr (STDOUT_FILENO, &shell_mode)) {
882 fprintf (stderr, "Cannot get terminal settings: %s\r\n",
883 unix_error_string (errno));
884 use_subshell = FALSE;
885 return;
890 /* Figure out whether the subshell has stopped, exited or been killed */
891 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
892 void
893 sigchld_handler (int sig)
895 int status;
896 pid_t pid;
898 (void) sig;
900 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
902 if (pid == subshell_pid) {
903 /* Figure out what has happened to the subshell */
905 if (WIFSTOPPED (status)) {
906 if (WSTOPSIG (status) == SIGSTOP) {
907 /* The subshell has received a SIGSTOP signal */
908 subshell_stopped = TRUE;
909 } else {
910 /* The user has suspended the subshell. Revive it */
911 kill (subshell_pid, SIGCONT);
913 } else {
914 /* The subshell has either exited normally or been killed */
915 subshell_alive = FALSE;
916 delete_select_channel (subshell_pty);
917 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
918 quit |= SUBSHELL_EXIT; /* Exited normally */
921 #ifdef __linux__
922 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
924 if (pid == cons_saver_pid) {
926 if (WIFSTOPPED (status))
927 /* Someone has stopped cons.saver - restart it */
928 kill (pid, SIGCONT);
929 else {
930 /* cons.saver has died - disable confole saving */
931 handle_console (CONSOLE_DONE);
932 console_flag = 0;
936 #endif /* __linux__ */
938 /* If we got here, some other child exited; ignore it */
942 /* Feed the subshell our keyboard input until it says it's finished */
943 static int
944 feed_subshell (int how, int fail_on_error)
946 fd_set read_set; /* For `select' */
947 int maxfdp;
948 int bytes; /* For the return value from `read' */
949 int i; /* Loop counter */
951 struct timeval wtime; /* Maximum time we wait for the subshell */
952 struct timeval *wptr;
954 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
955 wtime.tv_sec = 10;
956 wtime.tv_usec = 0;
957 wptr = fail_on_error ? &wtime : NULL;
959 while (1) {
960 if (!subshell_alive)
961 return FALSE;
963 /* Prepare the file-descriptor set and call `select' */
965 FD_ZERO (&read_set);
966 FD_SET (subshell_pty, &read_set);
967 FD_SET (subshell_pipe[READ], &read_set);
968 maxfdp = max (subshell_pty, subshell_pipe[READ]);
969 if (how == VISIBLY) {
970 FD_SET (STDIN_FILENO, &read_set);
971 maxfdp = max (maxfdp, STDIN_FILENO);
974 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1) {
976 /* Despite using SA_RESTART, we still have to check for this */
977 if (errno == EINTR)
978 continue; /* try all over again */
979 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
980 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
981 unix_error_string (errno));
982 exit (1);
985 if (FD_ISSET (subshell_pty, &read_set))
986 /* Read from the subshell, write to stdout */
988 /* This loop improves performance by reducing context switches
989 by a factor of 20 or so... unfortunately, it also hangs MC
990 randomly, because of an apparent Linux bug. Investigate. */
991 /* for (i=0; i<5; ++i) * FIXME -- experimental */
993 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
995 /* The subshell has died */
996 if (bytes == -1 && errno == EIO && !subshell_alive)
997 return FALSE;
999 if (bytes <= 0) {
1000 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1001 fprintf (stderr, "read (subshell_pty...): %s\r\n",
1002 unix_error_string (errno));
1003 exit (1);
1006 if (how == VISIBLY)
1007 write_all (STDOUT_FILENO, pty_buffer, bytes);
1010 else if (FD_ISSET (subshell_pipe[READ], &read_set))
1011 /* Read the subshell's CWD and capture its prompt */
1014 bytes =
1015 read (subshell_pipe[READ], subshell_cwd,
1016 MC_MAXPATHLEN + 1);
1017 if (bytes <= 0) {
1018 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1019 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
1020 unix_error_string (errno));
1021 exit (1);
1024 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
1026 synchronize ();
1028 subshell_ready = TRUE;
1029 if (subshell_state == RUNNING_COMMAND) {
1030 subshell_state = INACTIVE;
1031 return 1;
1035 else if (FD_ISSET (STDIN_FILENO, &read_set))
1036 /* Read from stdin, write to the subshell */
1038 bytes = read (STDIN_FILENO, pty_buffer, pty_buffer_size);
1039 if (bytes <= 0) {
1040 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1041 fprintf (stderr,
1042 "read (STDIN_FILENO, pty_buffer...): %s\r\n",
1043 unix_error_string (errno));
1044 exit (1);
1047 for (i = 0; i < bytes; ++i)
1048 if (pty_buffer[i] == subshell_switch_key) {
1049 write_all (subshell_pty, pty_buffer, i);
1050 if (subshell_ready)
1051 subshell_state = INACTIVE;
1052 return TRUE;
1055 write_all (subshell_pty, pty_buffer, bytes);
1057 if (pty_buffer[bytes-1] == '\n' || pty_buffer[bytes-1] == '\r')
1058 subshell_ready = FALSE;
1059 } else {
1060 return FALSE;
1066 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1067 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1068 static void synchronize (void)
1070 sigset_t sigchld_mask, old_mask;
1072 sigemptyset (&sigchld_mask);
1073 sigaddset (&sigchld_mask, SIGCHLD);
1074 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
1077 * SIGCHLD should not be blocked, but we unblock it just in case.
1078 * This is known to be useful for cygwin 1.3.12 and older.
1080 sigdelset (&old_mask, SIGCHLD);
1082 /* Wait until the subshell has stopped */
1083 while (subshell_alive && !subshell_stopped)
1084 sigsuspend (&old_mask);
1086 if (subshell_state != ACTIVE) {
1087 /* Discard all remaining data from stdin to the subshell */
1088 tcflush (subshell_pty_slave, TCIFLUSH);
1091 subshell_stopped = FALSE;
1092 kill (subshell_pid, SIGCONT);
1094 sigprocmask (SIG_SETMASK, &old_mask, NULL);
1095 /* We can't do any better without modifying the shell(s) */
1098 /* pty opening functions */
1100 #ifdef HAVE_GRANTPT
1102 /* System V version of pty_open_master */
1104 static int pty_open_master (char *pty_name)
1106 char *slave_name;
1107 int pty_master;
1109 #ifdef HAVE_POSIX_OPENPT
1110 pty_master = posix_openpt(O_RDWR);
1111 #elif HAVE_GETPT
1112 /* getpt () is a GNU extension (glibc 2.1.x) */
1113 pty_master = getpt ();
1114 #elif IS_AIX
1115 strcpy (pty_name, "/dev/ptc");
1116 pty_master = open (pty_name, O_RDWR);
1117 #else
1118 strcpy (pty_name, "/dev/ptmx");
1119 pty_master = open (pty_name, O_RDWR);
1120 #endif
1122 if (pty_master == -1)
1123 return -1;
1125 if (grantpt (pty_master) == -1 /* Grant access to slave */
1126 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
1127 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
1129 close (pty_master);
1130 return -1;
1132 strcpy (pty_name, slave_name);
1133 return pty_master;
1136 /* System V version of pty_open_slave */
1137 static int
1138 pty_open_slave (const char *pty_name)
1140 int pty_slave = open (pty_name, O_RDWR);
1142 if (pty_slave == -1) {
1143 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name,
1144 unix_error_string (errno));
1145 return -1;
1147 #if !defined(__osf__) && !defined(__linux__)
1148 #if defined (I_FIND) && defined (I_PUSH)
1149 if (!ioctl (pty_slave, I_FIND, "ptem"))
1150 if (ioctl (pty_slave, I_PUSH, "ptem") == -1) {
1151 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1152 pty_slave, unix_error_string (errno));
1153 close (pty_slave);
1154 return -1;
1157 if (!ioctl (pty_slave, I_FIND, "ldterm"))
1158 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1) {
1159 fprintf (stderr,
1160 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1161 pty_slave, unix_error_string (errno));
1162 close (pty_slave);
1163 return -1;
1165 #if !defined(sgi) && !defined(__sgi)
1166 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
1167 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1) {
1168 fprintf (stderr,
1169 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1170 pty_slave, unix_error_string (errno));
1171 close (pty_slave);
1172 return -1;
1174 #endif /* sgi || __sgi */
1175 #endif /* I_FIND && I_PUSH */
1176 #endif /* __osf__ || __linux__ */
1178 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1179 return pty_slave;
1182 #else /* !HAVE_GRANTPT */
1184 /* BSD version of pty_open_master */
1185 static int pty_open_master (char *pty_name)
1187 int pty_master;
1188 const char *ptr1, *ptr2;
1190 strcpy (pty_name, "/dev/ptyXX");
1191 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
1193 pty_name [8] = *ptr1;
1194 for (ptr2 = "0123456789abcdef"; *ptr2; ++ptr2)
1196 pty_name [9] = *ptr2;
1198 /* Try to open master */
1199 if ((pty_master = open (pty_name, O_RDWR)) == -1) {
1200 if (errno == ENOENT) /* Different from EIO */
1201 return -1; /* Out of pty devices */
1202 else
1203 continue; /* Try next pty device */
1205 pty_name [5] = 't'; /* Change "pty" to "tty" */
1206 if (access (pty_name, 6)){
1207 close (pty_master);
1208 pty_name [5] = 'p';
1209 continue;
1211 return pty_master;
1214 return -1; /* Ran out of pty devices */
1217 /* BSD version of pty_open_slave */
1218 static int
1219 pty_open_slave (const char *pty_name)
1221 int pty_slave;
1222 struct group *group_info = getgrnam ("tty");
1224 if (group_info != NULL) {
1225 /* The following two calls will only succeed if we are root */
1226 /* [Commented out while permissions problem is investigated] */
1227 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1228 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1230 if ((pty_slave = open (pty_name, O_RDWR)) == -1)
1231 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
1232 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1233 return pty_slave;
1236 #endif /* !HAVE_GRANTPT */
1237 #endif /* HAVE_SUBSHELL_SUPPORT */