Removed type SHELL_ESCAPED_STR in favour of plain char*
[midnight-commander.git] / src / subshell.c
blobfe2ae6843f352c964f9ca6f7e23e29f04007845a
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 #include <config.h>
21 #ifdef HAVE_SUBSHELL_SUPPORT
23 #ifndef _GNU_SOURCE
24 # define _GNU_SOURCE 1
25 #endif
27 #include <ctype.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <signal.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_IOCTL_H
36 # include <sys/ioctl.h>
37 #endif
38 #ifdef HAVE_TERMIOS_H
39 #include <termios.h>
40 #endif
41 #include <unistd.h>
43 #ifdef HAVE_STROPTS_H
44 # include <stropts.h> /* For I_PUSH */
45 #endif /* HAVE_STROPTS_H */
47 #include <mhl/memory.h>
48 #include <mhl/string.h>
50 #include "global.h"
51 #include "tty.h" /* LINES */
52 #include "panel.h" /* current_panel */
53 #include "wtools.h" /* query_dialog() */
54 #include "main.h" /* do_update_prompt() */
55 #include "cons.saver.h" /* handle_console() */
56 #include "key.h" /* XCTRL */
57 #include "subshell.h"
59 #ifndef WEXITSTATUS
60 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
61 #endif
63 #ifndef WIFEXITED
64 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
65 #endif
67 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
68 static char tcsh_fifo[128];
70 /* Local functions */
71 static void init_raw_mode (void);
72 static int feed_subshell (int how, int fail_on_error);
73 static void synchronize (void);
74 static int pty_open_master (char *pty_name);
75 static int pty_open_slave (const char *pty_name);
76 static int resize_tty (int fd);
78 #ifndef STDIN_FILENO
79 # define STDIN_FILENO 0
80 #endif
82 #ifndef STDOUT_FILENO
83 # define STDOUT_FILENO 1
84 #endif
86 #ifndef STDERR_FILENO
87 # define STDERR_FILENO 2
88 #endif
90 /* If using a subshell for evaluating commands this is true */
91 int use_subshell =
92 #ifdef SUBSHELL_OPTIONAL
93 FALSE;
94 #else
95 TRUE;
96 #endif
98 /* File descriptors of the pseudoterminal used by the subshell */
99 int subshell_pty = 0;
100 static int subshell_pty_slave = -1;
102 /* The key for switching back to MC from the subshell */
103 static const char subshell_switch_key = XCTRL('o') & 255;
105 /* State of the subshell:
106 * INACTIVE: the default state; awaiting a command
107 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
108 * RUNNING_COMMAND: return to MC when the current command finishes */
109 enum subshell_state_enum subshell_state;
111 /* Holds the latest prompt captured from the subshell */
112 char *subshell_prompt = NULL;
114 /* Initial length of the buffer for the subshell's prompt */
115 #define INITIAL_PROMPT_SIZE 10
117 /* Used by the child process to indicate failure to start the subshell */
118 #define FORK_FAILURE 69 /* Arbitrary */
120 /* Initial length of the buffer for all I/O with the subshell */
121 #define INITIAL_PTY_BUFFER_SIZE 100 /* Arbitrary; but keep it >= 80 */
123 /* For pipes */
124 enum {READ=0, WRITE=1};
126 static char *pty_buffer; /* For reading/writing on the subshell's pty */
127 static int pty_buffer_size; /* The buffer grows as needed */
128 static int subshell_pipe[2]; /* To pass CWD info from the subshell to MC */
129 static pid_t subshell_pid = 1; /* The subshell's process ID */
130 static char subshell_cwd[MC_MAXPATHLEN+1]; /* One extra char for final '\n' */
132 /* Subshell type (gleaned from the SHELL environment variable, if available) */
133 static enum {BASH, TCSH, ZSH} subshell_type;
135 /* Flag to indicate whether the subshell is ready for next command */
136 static int subshell_ready;
138 /* The following two flags can be changed by the SIGCHLD handler. This is */
139 /* OK, because the `int' type is updated atomically on all known machines */
140 static volatile int subshell_alive, subshell_stopped;
142 /* We store the terminal's initial mode here so that we can configure
143 the pty similarly, and also so we can restore the real terminal to
144 sanity if we have to exit abruptly */
145 static struct termios shell_mode;
147 /* This is a transparent mode for the terminal where MC is running on */
148 /* It is used when the shell is active, so that the control signals */
149 /* are delivered to the shell pty */
150 static struct termios raw_mode;
152 /* This counter indicates how many characters of prompt we have read */
153 /* FIXME: try to figure out why this had to become global */
154 static int prompt_pos;
158 * Write all data, even if the write() call is interrupted.
160 static ssize_t
161 write_all (int fd, const void *buf, size_t count)
163 ssize_t ret;
164 ssize_t written = 0;
165 while (count > 0) {
166 ret = write (fd, (const unsigned char *) buf + written, count);
167 if (ret < 0) {
168 if (errno == EINTR) {
169 continue;
170 } else {
171 return written > 0 ? written : ret;
174 count -= ret;
175 written += ret;
177 return written;
181 * Prepare child process to running the shell and run it.
183 * Modifies the global variables (in the child process only):
184 * shell_mode
186 * Returns: never.
188 static void
189 init_subshell_child (const char *pty_name)
191 const char *init_file = NULL;
192 #ifdef HAVE_GETSID
193 pid_t mc_sid;
194 #endif /* HAVE_GETSID */
196 setsid (); /* Get a fresh terminal session */
198 /* Make sure that it has become our controlling terminal */
200 /* Redundant on Linux and probably most systems, but just in case: */
202 #ifdef TIOCSCTTY
203 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
204 #endif
206 /* Configure its terminal modes and window size */
208 /* Set up the pty with the same termios flags as our own tty, plus */
209 /* TOSTOP, which keeps background processes from writing to the pty */
211 shell_mode.c_lflag |= TOSTOP; /* So background writers get SIGTTOU */
212 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode)) {
213 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n",
214 unix_error_string (errno));
215 _exit (FORK_FAILURE);
218 /* Set the pty's size (80x25 by default on Linux) according to the */
219 /* size of the real terminal as calculated by ncurses, if possible */
220 resize_tty (subshell_pty_slave);
222 /* Set up the subshell's environment and init file name */
224 /* It simplifies things to change to our home directory here, */
225 /* and the user's startup file may do a `cd' command anyway */
226 chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
228 #ifdef HAVE_GETSID
229 /* Set MC_SID to prevent running one mc from another */
230 mc_sid = getsid (0);
231 if (mc_sid != -1) {
232 char sid_str[BUF_SMALL];
233 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld",
234 (long) mc_sid);
235 putenv (g_strdup (sid_str));
237 #endif /* HAVE_GETSID */
239 switch (subshell_type) {
240 case BASH:
241 init_file = ".mc/bashrc";
242 if (access (init_file, R_OK) == -1)
243 init_file = ".bashrc";
245 /* Make MC's special commands not show up in bash's history */
246 putenv ("HISTCONTROL=ignorespace");
248 /* Allow alternative readline settings for MC */
249 if (access (".mc/inputrc", R_OK) == 0)
250 putenv ("INPUTRC=.mc/inputrc");
252 break;
254 /* TODO: Find a way to pass initfile to TCSH and ZSH */
255 case TCSH:
256 case ZSH:
257 break;
259 default:
260 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n",
261 subshell_type);
262 _exit (FORK_FAILURE);
265 /* Attach all our standard file descriptors to the pty */
267 /* This is done just before the fork, because stderr must still */
268 /* be connected to the real tty during the above error messages; */
269 /* otherwise the user will never see them. */
271 dup2 (subshell_pty_slave, STDIN_FILENO);
272 dup2 (subshell_pty_slave, STDOUT_FILENO);
273 dup2 (subshell_pty_slave, STDERR_FILENO);
275 close (subshell_pipe[READ]);
276 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
277 /* Close master side of pty. This is important; apart from */
278 /* freeing up the descriptor for use in the subshell, it also */
279 /* means that when MC exits, the subshell will get a SIGHUP and */
280 /* exit too, because there will be no more descriptors pointing */
281 /* at the master side of the pty and so it will disappear. */
282 close (subshell_pty);
284 /* Execute the subshell at last */
286 switch (subshell_type) {
287 case BASH:
288 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
289 break;
291 case TCSH:
292 execl (shell, "tcsh", (char *) NULL);
293 break;
295 case ZSH:
296 /* Use -g to exclude cmds beginning with space from history
297 * and -Z to use the line editor on non-interactive term */
298 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
300 break;
303 /* If we get this far, everything failed miserably */
304 _exit (FORK_FAILURE);
308 #ifdef HAVE_GETSID
310 * Check MC_SID to prevent running one mc from another.
311 * Return:
312 * 0 if no parent mc in our session was found,
313 * 1 if parent mc was found and the user wants to continue,
314 * 2 if parent mc was found and the user wants to quit mc.
316 static int
317 check_sid (void)
319 pid_t my_sid, old_sid;
320 const char *sid_str;
321 int r;
323 sid_str = getenv ("MC_SID");
324 if (!sid_str)
325 return 0;
327 old_sid = (pid_t) strtol (sid_str, NULL, 0);
328 if (!old_sid)
329 return 0;
331 my_sid = getsid (0);
332 if (my_sid == -1)
333 return 0;
335 /* The parent mc is in a different session, it's OK */
336 if (old_sid != my_sid)
337 return 0;
339 r = query_dialog (_("Warning"),
340 _("GNU Midnight Commander is already\n"
341 "running on this terminal.\n"
342 "Subshell support will be disabled."), D_ERROR, 2,
343 _("&OK"), _("&Quit"));
344 if (r != 0) {
345 return 2;
348 return 1;
350 #endif /* HAVE_GETSID */
354 * Fork the subshell, and set up many, many things.
356 * Possibly modifies the global variables:
357 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
358 * use_subshell - Is set to FALSE if we can't run the subshell
359 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
362 void
363 init_subshell (void)
365 /* This must be remembered across calls to init_subshell() */
366 static char pty_name[BUF_SMALL];
367 char precmd[BUF_SMALL];
369 #ifdef HAVE_GETSID
370 switch (check_sid ()) {
371 case 1:
372 use_subshell = FALSE;
373 return;
374 case 2:
375 use_subshell = FALSE;
376 midnight_shutdown = 1;
377 return;
379 #endif /* HAVE_GETSID */
381 /* Take the current (hopefully pristine) tty mode and make */
382 /* a raw mode based on it now, before we do anything else with it */
383 init_raw_mode ();
385 if (subshell_pty == 0) { /* First time through */
386 /* Find out what type of shell we have */
388 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
389 subshell_type = ZSH;
390 else if (strstr (shell, "/tcsh"))
391 subshell_type = TCSH;
392 else if (strstr (shell, "/bash") || getenv ("BASH"))
393 subshell_type = BASH;
394 else {
395 use_subshell = FALSE;
396 return;
399 /* Open a pty for talking to the subshell */
401 /* FIXME: We may need to open a fresh pty each time on SVR4 */
403 subshell_pty = pty_open_master (pty_name);
404 if (subshell_pty == -1) {
405 fprintf (stderr, "Cannot open master side of pty: %s\r\n",
406 unix_error_string (errno));
407 use_subshell = FALSE;
408 return;
410 subshell_pty_slave = pty_open_slave (pty_name);
411 if (subshell_pty_slave == -1) {
412 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
413 pty_name, unix_error_string (errno));
414 use_subshell = FALSE;
415 return;
418 /* Initialise the pty's I/O buffer */
420 pty_buffer_size = INITIAL_PTY_BUFFER_SIZE;
421 pty_buffer = g_malloc (pty_buffer_size);
423 /* Create a pipe for receiving the subshell's CWD */
425 if (subshell_type == TCSH) {
426 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
427 mc_tmpdir (), (int) getpid ());
428 if (mkfifo (tcsh_fifo, 0600) == -1) {
429 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo,
430 unix_error_string (errno));
431 use_subshell = FALSE;
432 return;
435 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
437 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
438 || (subshell_pipe[WRITE] =
439 open (tcsh_fifo, O_RDWR)) == -1) {
440 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
441 perror (__FILE__": open");
442 use_subshell = FALSE;
443 return;
445 } else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe)) {
446 perror (__FILE__": couldn't create pipe");
447 use_subshell = FALSE;
448 return;
452 /* Fork the subshell */
454 subshell_alive = TRUE;
455 subshell_stopped = FALSE;
456 subshell_pid = fork ();
458 if (subshell_pid == -1) {
459 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n",
460 unix_error_string (errno));
461 /* We exit here because, if the process table is full, the */
462 /* other method of running user commands won't work either */
463 exit (1);
466 if (subshell_pid == 0) { /* We are in the child process */
467 init_subshell_child (pty_name);
470 /* Set up `precmd' or equivalent for reading the subshell's CWD */
472 switch (subshell_type) {
473 case BASH:
474 g_snprintf (precmd, sizeof (precmd),
475 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
476 subshell_pipe[WRITE]);
477 break;
479 case ZSH:
480 g_snprintf (precmd, sizeof (precmd),
481 " precmd(){ pwd>&%d;kill -STOP $$ }\n",
482 subshell_pipe[WRITE]);
483 break;
485 case TCSH:
486 g_snprintf (precmd, sizeof (precmd),
487 "set echo_style=both;"
488 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n",
489 tcsh_fifo);
490 break;
492 write_all (subshell_pty, precmd, strlen (precmd));
494 /* Wait until the subshell has started up and processed the command */
496 subshell_state = RUNNING_COMMAND;
497 enable_interrupt_key ();
498 if (!feed_subshell (QUIETLY, TRUE)) {
499 use_subshell = FALSE;
501 disable_interrupt_key ();
502 if (!subshell_alive)
503 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
507 static void init_raw_mode ()
509 static int initialized = 0;
511 /* MC calls reset_shell_mode() in pre_exec() to set the real tty to its */
512 /* original settings. However, here we need to make this tty very raw, */
513 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
514 /* pty. So, instead of changing the code for execute(), pre_exec(), */
515 /* etc, we just set up the modes we need here, before each command. */
517 if (initialized == 0) /* First time: initialise `raw_mode' */
519 tcgetattr (STDOUT_FILENO, &raw_mode);
520 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
521 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
522 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
523 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
524 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
525 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
526 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
527 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
528 initialized = 1;
533 int invoke_subshell (const char *command, int how, char **new_dir)
535 /* Make the MC terminal transparent */
536 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
538 /* Make the subshell change to MC's working directory */
539 if (new_dir)
540 do_subshell_chdir (current_panel->cwd, TRUE, 1);
542 if (command == NULL) /* The user has done "C-o" from MC */
544 if (subshell_state == INACTIVE)
546 subshell_state = ACTIVE;
547 /* FIXME: possibly take out this hack; the user can
548 re-play it by hitting C-hyphen a few times! */
549 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
552 else /* MC has passed us a user command */
554 if (how == QUIETLY)
555 write_all (subshell_pty, " ", 1);
556 /* FIXME: if command is long (>8KB ?) we go comma */
557 write_all (subshell_pty, command, strlen (command));
558 write_all (subshell_pty, "\n", 1);
559 subshell_state = RUNNING_COMMAND;
560 subshell_ready = FALSE;
563 feed_subshell (how, FALSE);
565 if (new_dir && subshell_alive && strcmp (subshell_cwd, current_panel->cwd))
566 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
568 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
569 while (!subshell_alive && !quit && use_subshell)
570 init_subshell ();
572 prompt_pos = 0;
574 return quit;
579 read_subshell_prompt (void)
581 static int prompt_size = INITIAL_PROMPT_SIZE;
582 int bytes = 0, i, rc = 0;
583 struct timeval timeleft = { 0, 0 };
585 fd_set tmp;
586 FD_ZERO (&tmp);
587 FD_SET (subshell_pty, &tmp);
589 if (subshell_prompt == NULL) { /* First time through */
590 subshell_prompt = g_malloc (prompt_size);
591 *subshell_prompt = '\0';
592 prompt_pos = 0;
595 while (subshell_alive
596 && (rc =
597 select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft))) {
598 /* Check for `select' errors */
599 if (rc == -1) {
600 if (errno == EINTR)
601 continue;
602 else {
603 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n",
604 unix_error_string (errno));
605 exit (1);
609 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
611 /* Extract the prompt from the shell output */
613 for (i = 0; i < bytes; ++i)
614 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r') {
615 prompt_pos = 0;
616 } else {
617 if (!pty_buffer[i])
618 continue;
620 subshell_prompt[prompt_pos++] = pty_buffer[i];
621 if (prompt_pos == prompt_size)
622 subshell_prompt =
623 g_realloc (subshell_prompt, prompt_size *= 2);
626 subshell_prompt[prompt_pos] = '\0';
628 if (rc == 0 && bytes == 0)
629 return FALSE;
630 return TRUE;
633 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
634 static int resize_tty (int fd)
636 #if defined TIOCSWINSZ
637 struct winsize tty_size;
639 tty_size.ws_row = LINES;
640 tty_size.ws_col = COLS;
641 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
643 return ioctl (fd, TIOCSWINSZ, &tty_size);
644 #else
645 return 0;
646 #endif
649 /* Resize subshell_pty */
650 void resize_subshell (void)
652 if (use_subshell == 0)
653 return;
655 resize_tty (subshell_pty);
659 exit_subshell (void)
661 int subshell_quit = TRUE;
663 if (subshell_state != INACTIVE && subshell_alive)
664 subshell_quit =
665 !query_dialog (_("Warning"),
666 _(" The shell is still active. Quit anyway? "),
667 D_NORMAL, 2, _("&Yes"), _("&No"));
669 if (subshell_quit) {
670 if (subshell_type == TCSH) {
671 if (unlink (tcsh_fifo) == -1)
672 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
673 tcsh_fifo, unix_error_string (errno));
676 g_free (subshell_prompt);
677 g_free (pty_buffer);
678 subshell_prompt = NULL;
679 pty_buffer = NULL;
682 return subshell_quit;
687 * Carefully quote directory name to allow entering any directory safely,
688 * no matter what weird characters it may contain in its name.
689 * NOTE: Treat directory name an untrusted data, don't allow it to cause
690 * executing any commands in the shell. Escape all control characters.
691 * Use following technique:
693 * printf(1) with format string containing a single conversion specifier,
694 * "b", and an argument which contains a copy of the string passed to
695 * subshell_name_quote() with all characters, except digits and letters,
696 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
697 * numeric value of the character converted to octal number.
699 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
702 static char *
703 subshell_name_quote (const char *s)
705 char *ret, *d;
706 const char quote_cmd_start[] = "\"`printf \"%b\" '";
707 const char quote_cmd_end[] = "'`\"";
709 /* Factor 5 because we need \, 0 and 3 other digits per character. */
710 d = ret = g_malloc (1 + (5 * strlen (s)) + (sizeof(quote_cmd_start) - 1)
711 + (sizeof(quote_cmd_end) - 1));
712 if (!d)
713 return NULL;
715 /* Prevent interpreting leading `-' as a switch for `cd' */
716 if (*s == '-') {
717 *d++ = '.';
718 *d++ = '/';
721 /* Copy the beginning of the command to the buffer */
722 strcpy (d, quote_cmd_start);
723 d += sizeof(quote_cmd_start) - 1;
726 * Print every character except digits and letters as a backslash-escape
727 * sequence of the form \0nnn, where "nnn" is the numeric value of the
728 * character converted to octal number.
730 for (; *s; s++) {
731 if (isalnum ((unsigned char) *s)) {
732 *d++ = (unsigned char) *s;
733 } else {
734 sprintf (d, "\\0%03o", (unsigned char) *s);
735 d += 5;
739 strcpy (d, quote_cmd_end);
741 return ret;
745 /* If it actually changed the directory it returns true */
746 void
747 do_subshell_chdir (const char *directory, int do_update, int reset_prompt)
749 if (!
750 (subshell_state == INACTIVE
751 && strcmp (subshell_cwd, current_panel->cwd))) {
752 /* We have to repaint the subshell prompt if we read it from
753 * the main program. Please note that in the code after this
754 * if, the cd command that is sent will make the subshell
755 * repaint the prompt, so we don't have to paint it. */
756 if (do_update)
757 do_update_prompt ();
758 return;
761 /* The initial space keeps this out of the command history (in bash
762 because we set "HISTCONTROL=ignorespace") */
763 write_all (subshell_pty, " cd ", 4);
764 if (*directory) {
765 char *temp = subshell_name_quote (directory);
766 if (temp) {
767 write_all (subshell_pty, temp, strlen (temp));
768 g_free (temp);
769 } else {
770 /* Should not happen unless the directory name is so long
771 that we don't have memory to quote it. */
772 write_all (subshell_pty, ".", 1);
774 } else {
775 write_all (subshell_pty, "/", 1);
777 write_all (subshell_pty, "\n", 1);
779 subshell_state = RUNNING_COMMAND;
780 feed_subshell (QUIETLY, FALSE);
782 if (subshell_alive) {
783 int bPathNotEq = strcmp (subshell_cwd, current_panel->cwd);
785 if (bPathNotEq && subshell_type == TCSH) {
786 char rp_subshell_cwd[PATH_MAX];
787 char rp_current_panel_cwd[PATH_MAX];
789 char *p_subshell_cwd =
790 mc_realpath (subshell_cwd, rp_subshell_cwd);
791 char *p_current_panel_cwd =
792 mc_realpath (current_panel->cwd, rp_current_panel_cwd);
794 if (p_subshell_cwd == NULL)
795 p_subshell_cwd = subshell_cwd;
796 if (p_current_panel_cwd == NULL)
797 p_current_panel_cwd = current_panel->cwd;
798 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
801 if (bPathNotEq && strcmp (current_panel->cwd, ".")) {
802 char *cwd = strip_password (g_strdup (current_panel->cwd), 1);
803 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
804 g_free (cwd);
808 if (reset_prompt)
809 prompt_pos = 0;
810 update_prompt = FALSE;
811 /* Make sure that MC never stores the CWD in a silly format */
812 /* like /usr////lib/../bin, or the strcmp() above will fail */
816 void
817 subshell_get_console_attributes (void)
819 /* Get our current terminal modes */
821 if (tcgetattr (STDOUT_FILENO, &shell_mode)) {
822 fprintf (stderr, "Cannot get terminal settings: %s\r\n",
823 unix_error_string (errno));
824 use_subshell = FALSE;
825 return;
830 /* Figure out whether the subshell has stopped, exited or been killed */
831 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
832 void
833 sigchld_handler (int sig)
835 int status;
836 pid_t pid;
838 (void) sig;
840 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
842 if (pid == subshell_pid) {
843 /* Figure out what has happened to the subshell */
845 if (WIFSTOPPED (status)) {
846 if (WSTOPSIG (status) == SIGSTOP) {
847 /* The subshell has received a SIGSTOP signal */
848 subshell_stopped = TRUE;
849 } else {
850 /* The user has suspended the subshell. Revive it */
851 kill (subshell_pid, SIGCONT);
853 } else {
854 /* The subshell has either exited normally or been killed */
855 subshell_alive = FALSE;
856 delete_select_channel (subshell_pty);
857 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
858 quit |= SUBSHELL_EXIT; /* Exited normally */
861 #ifdef __linux__
862 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
864 if (pid == cons_saver_pid) {
866 if (WIFSTOPPED (status))
867 /* Someone has stopped cons.saver - restart it */
868 kill (pid, SIGCONT);
869 else {
870 /* cons.saver has died - disable confole saving */
871 handle_console (CONSOLE_DONE);
872 console_flag = 0;
876 #endif /* __linux__ */
878 /* If we got here, some other child exited; ignore it */
882 /* Feed the subshell our keyboard input until it says it's finished */
883 static int
884 feed_subshell (int how, int fail_on_error)
886 fd_set read_set; /* For `select' */
887 int maxfdp;
888 int bytes; /* For the return value from `read' */
889 int i; /* Loop counter */
891 struct timeval wtime; /* Maximum time we wait for the subshell */
892 struct timeval *wptr;
894 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
895 wtime.tv_sec = 10;
896 wtime.tv_usec = 0;
897 wptr = fail_on_error ? &wtime : NULL;
899 while (1) {
900 if (!subshell_alive)
901 return FALSE;
903 /* Prepare the file-descriptor set and call `select' */
905 FD_ZERO (&read_set);
906 FD_SET (subshell_pty, &read_set);
907 FD_SET (subshell_pipe[READ], &read_set);
908 maxfdp = max (subshell_pty, subshell_pipe[READ]);
909 if (how == VISIBLY) {
910 FD_SET (STDIN_FILENO, &read_set);
911 maxfdp = max (maxfdp, STDIN_FILENO);
914 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1) {
916 /* Despite using SA_RESTART, we still have to check for this */
917 if (errno == EINTR)
918 continue; /* try all over again */
919 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
920 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
921 unix_error_string (errno));
922 exit (1);
925 if (FD_ISSET (subshell_pty, &read_set))
926 /* Read from the subshell, write to stdout */
928 /* This loop improves performance by reducing context switches
929 by a factor of 20 or so... unfortunately, it also hangs MC
930 randomly, because of an apparent Linux bug. Investigate. */
931 /* for (i=0; i<5; ++i) * FIXME -- experimental */
933 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
935 /* The subshell has died */
936 if (bytes == -1 && errno == EIO && !subshell_alive)
937 return FALSE;
939 if (bytes <= 0) {
940 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
941 fprintf (stderr, "read (subshell_pty...): %s\r\n",
942 unix_error_string (errno));
943 exit (1);
946 if (how == VISIBLY)
947 write_all (STDOUT_FILENO, pty_buffer, bytes);
950 else if (FD_ISSET (subshell_pipe[READ], &read_set))
951 /* Read the subshell's CWD and capture its prompt */
954 bytes =
955 read (subshell_pipe[READ], subshell_cwd,
956 MC_MAXPATHLEN + 1);
957 if (bytes <= 0) {
958 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
959 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
960 unix_error_string (errno));
961 exit (1);
964 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
966 synchronize ();
968 subshell_ready = TRUE;
969 if (subshell_state == RUNNING_COMMAND) {
970 subshell_state = INACTIVE;
971 return 1;
975 else if (FD_ISSET (STDIN_FILENO, &read_set))
976 /* Read from stdin, write to the subshell */
978 bytes = read (STDIN_FILENO, pty_buffer, pty_buffer_size);
979 if (bytes <= 0) {
980 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
981 fprintf (stderr,
982 "read (STDIN_FILENO, pty_buffer...): %s\r\n",
983 unix_error_string (errno));
984 exit (1);
987 for (i = 0; i < bytes; ++i)
988 if (pty_buffer[i] == subshell_switch_key) {
989 write_all (subshell_pty, pty_buffer, i);
990 if (subshell_ready)
991 subshell_state = INACTIVE;
992 return TRUE;
995 write_all (subshell_pty, pty_buffer, bytes);
996 subshell_ready = FALSE;
997 } else {
998 return FALSE;
1004 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1005 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1006 static void synchronize (void)
1008 sigset_t sigchld_mask, old_mask;
1010 sigemptyset (&sigchld_mask);
1011 sigaddset (&sigchld_mask, SIGCHLD);
1012 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
1015 * SIGCHLD should not be blocked, but we unblock it just in case.
1016 * This is known to be useful for cygwin 1.3.12 and older.
1018 sigdelset (&old_mask, SIGCHLD);
1020 /* Wait until the subshell has stopped */
1021 while (subshell_alive && !subshell_stopped)
1022 sigsuspend (&old_mask);
1024 if (subshell_state != ACTIVE) {
1025 /* Discard all remaining data from stdin to the subshell */
1026 tcflush (subshell_pty_slave, TCIFLUSH);
1029 subshell_stopped = FALSE;
1030 kill (subshell_pid, SIGCONT);
1032 sigprocmask (SIG_SETMASK, &old_mask, NULL);
1033 /* We can't do any better without modifying the shell(s) */
1036 /* pty opening functions */
1038 #ifdef HAVE_GRANTPT
1040 /* System V version of pty_open_master */
1042 static int pty_open_master (char *pty_name)
1044 char *slave_name;
1045 int pty_master;
1047 #ifdef HAVE_POSIX_OPENPT
1048 pty_master = posix_openpt(O_RDWR);
1049 #elif HAVE_GETPT
1050 /* getpt () is a GNU extension (glibc 2.1.x) */
1051 pty_master = getpt ();
1052 #elif IS_AIX
1053 strcpy (pty_name, "/dev/ptc");
1054 pty_master = open (pty_name, O_RDWR);
1055 #else
1056 strcpy (pty_name, "/dev/ptmx");
1057 pty_master = open (pty_name, O_RDWR);
1058 #endif
1060 if (pty_master == -1)
1061 return -1;
1063 if (grantpt (pty_master) == -1 /* Grant access to slave */
1064 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
1065 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
1067 close (pty_master);
1068 return -1;
1070 strcpy (pty_name, slave_name);
1071 return pty_master;
1074 /* System V version of pty_open_slave */
1075 static int
1076 pty_open_slave (const char *pty_name)
1078 int pty_slave = open (pty_name, O_RDWR);
1080 if (pty_slave == -1) {
1081 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name,
1082 unix_error_string (errno));
1083 return -1;
1085 #if !defined(__osf__) && !defined(__linux__)
1086 #if defined (I_FIND) && defined (I_PUSH)
1087 if (!ioctl (pty_slave, I_FIND, "ptem"))
1088 if (ioctl (pty_slave, I_PUSH, "ptem") == -1) {
1089 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1090 pty_slave, unix_error_string (errno));
1091 close (pty_slave);
1092 return -1;
1095 if (!ioctl (pty_slave, I_FIND, "ldterm"))
1096 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1) {
1097 fprintf (stderr,
1098 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1099 pty_slave, unix_error_string (errno));
1100 close (pty_slave);
1101 return -1;
1103 #if !defined(sgi) && !defined(__sgi)
1104 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
1105 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1) {
1106 fprintf (stderr,
1107 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1108 pty_slave, unix_error_string (errno));
1109 close (pty_slave);
1110 return -1;
1112 #endif /* sgi || __sgi */
1113 #endif /* I_FIND && I_PUSH */
1114 #endif /* __osf__ || __linux__ */
1116 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1117 return pty_slave;
1120 #else /* !HAVE_GRANTPT */
1122 /* BSD version of pty_open_master */
1123 static int pty_open_master (char *pty_name)
1125 int pty_master;
1126 const char *ptr1, *ptr2;
1128 strcpy (pty_name, "/dev/ptyXX");
1129 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
1131 pty_name [8] = *ptr1;
1132 for (ptr2 = "0123456789abcdef"; *ptr2; ++ptr2)
1134 pty_name [9] = *ptr2;
1136 /* Try to open master */
1137 if ((pty_master = open (pty_name, O_RDWR)) == -1) {
1138 if (errno == ENOENT) /* Different from EIO */
1139 return -1; /* Out of pty devices */
1140 else
1141 continue; /* Try next pty device */
1143 pty_name [5] = 't'; /* Change "pty" to "tty" */
1144 if (access (pty_name, 6)){
1145 close (pty_master);
1146 pty_name [5] = 'p';
1147 continue;
1149 return pty_master;
1152 return -1; /* Ran out of pty devices */
1155 /* BSD version of pty_open_slave */
1156 static int
1157 pty_open_slave (const char *pty_name)
1159 int pty_slave;
1160 struct group *group_info = getgrnam ("tty");
1162 if (group_info != NULL) {
1163 /* The following two calls will only succeed if we are root */
1164 /* [Commented out while permissions problem is investigated] */
1165 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1166 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1168 if ((pty_slave = open (pty_name, O_RDWR)) == -1)
1169 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
1170 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1171 return pty_slave;
1174 #endif /* !HAVE_GRANTPT */
1175 #endif /* HAVE_SUBSHELL_SUPPORT */