Merge branch '2344_fix_line_jump'
[midnight-commander.git] / src / subshell.c
blob35fa942c67964915d2f17fbd6525d285f92109a1
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 #include <termios.h>
44 #include <unistd.h>
46 #ifdef HAVE_STROPTS_H
47 # include <stropts.h> /* For I_PUSH */
48 #endif /* HAVE_STROPTS_H */
50 #include "lib/global.h"
51 #include "lib/tty/tty.h" /* LINES */
52 #include "lib/tty/key.h" /* XCTRL */
53 #include "lib/vfs/mc-vfs/vfs.h"
54 #include "lib/strutil.h"
55 #include "lib/fileloc.h"
57 #include "panel.h" /* current_panel */
58 #include "wtools.h" /* query_dialog() */
59 #include "main.h" /* do_update_prompt() */
60 #include "consaver/cons.saver.h" /* handle_console() */
61 #include "subshell.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 gboolean 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 /* Length of the buffer for all I/O with the subshell */
125 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
127 /* For pipes */
128 enum
130 READ = 0,
131 WRITE = 1
134 static char pty_buffer[PTY_BUFFER_SIZE] = "\0"; /* For reading/writing on the subshell's pty */
135 static int subshell_pipe[2]; /* To pass CWD info from the subshell to MC */
136 static pid_t subshell_pid = 1; /* The subshell's process ID */
137 static char subshell_cwd[MC_MAXPATHLEN + 1]; /* One extra char for final '\n' */
139 /* Subshell type (gleaned from the SHELL environment variable, if available) */
140 static enum
142 BASH,
143 TCSH,
144 ZSH,
145 FISH
146 } subshell_type;
148 /* Flag to indicate whether the subshell is ready for next command */
149 static int subshell_ready;
151 /* The following two flags can be changed by the SIGCHLD handler. This is */
152 /* OK, because the `int' type is updated atomically on all known machines */
153 static volatile int subshell_alive, subshell_stopped;
155 /* We store the terminal's initial mode here so that we can configure
156 the pty similarly, and also so we can restore the real terminal to
157 sanity if we have to exit abruptly */
158 static struct termios shell_mode;
160 /* This is a transparent mode for the terminal where MC is running on */
161 /* It is used when the shell is active, so that the control signals */
162 /* are delivered to the shell pty */
163 static struct termios raw_mode;
165 /* This counter indicates how many characters of prompt we have read */
166 /* FIXME: try to figure out why this had to become global */
167 static int prompt_pos;
171 * Write all data, even if the write() call is interrupted.
173 static ssize_t
174 write_all (int fd, const void *buf, size_t count)
176 ssize_t ret;
177 ssize_t written = 0;
178 while (count > 0)
180 ret = write (fd, (const unsigned char *) buf + written, count);
181 if (ret < 0)
183 if (errno == EINTR)
185 continue;
187 else
189 return written > 0 ? written : ret;
192 count -= ret;
193 written += ret;
195 return written;
199 * Prepare child process to running the shell and run it.
201 * Modifies the global variables (in the child process only):
202 * shell_mode
204 * Returns: never.
206 static void
207 init_subshell_child (const char *pty_name)
209 const char *init_file = NULL;
210 pid_t mc_sid;
212 (void) pty_name;
213 setsid (); /* Get a fresh terminal session */
215 /* Make sure that it has become our controlling terminal */
217 /* Redundant on Linux and probably most systems, but just in case: */
219 #ifdef TIOCSCTTY
220 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
221 #endif
223 /* Configure its terminal modes and window size */
225 /* Set up the pty with the same termios flags as our own tty */
226 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
228 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
229 _exit (FORK_FAILURE);
232 /* Set the pty's size (80x25 by default on Linux) according to the */
233 /* size of the real terminal as calculated by ncurses, if possible */
234 resize_tty (subshell_pty_slave);
236 /* Set up the subshell's environment and init file name */
238 /* It simplifies things to change to our home directory here, */
239 /* and the user's startup file may do a `cd' command anyway */
241 int ret;
242 ret = chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
245 /* Set MC_SID to prevent running one mc from another */
246 mc_sid = getsid (0);
247 if (mc_sid != -1)
249 char sid_str[BUF_SMALL];
250 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
251 putenv (g_strdup (sid_str));
254 switch (subshell_type)
256 case BASH:
257 init_file = MC_USERCONF_DIR PATH_SEP_STR "bashrc";
258 if (access (init_file, R_OK) == -1)
259 init_file = ".bashrc";
261 /* Make MC's special commands not show up in bash's history */
262 putenv ((char *) "HISTCONTROL=ignorespace");
264 /* Allow alternative readline settings for MC */
265 if (access (MC_USERCONF_DIR PATH_SEP_STR "inputrc", R_OK) == 0)
266 putenv ((char *) "INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR "/inputrc");
268 break;
270 /* TODO: Find a way to pass initfile to TCSH and ZSH */
271 case TCSH:
272 case ZSH:
273 case FISH:
274 break;
276 default:
277 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
278 _exit (FORK_FAILURE);
281 /* Attach all our standard file descriptors to the pty */
283 /* This is done just before the fork, because stderr must still */
284 /* be connected to the real tty during the above error messages; */
285 /* otherwise the user will never see them. */
287 dup2 (subshell_pty_slave, STDIN_FILENO);
288 dup2 (subshell_pty_slave, STDOUT_FILENO);
289 dup2 (subshell_pty_slave, STDERR_FILENO);
291 close (subshell_pipe[READ]);
292 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
293 /* Close master side of pty. This is important; apart from */
294 /* freeing up the descriptor for use in the subshell, it also */
295 /* means that when MC exits, the subshell will get a SIGHUP and */
296 /* exit too, because there will be no more descriptors pointing */
297 /* at the master side of the pty and so it will disappear. */
298 close (subshell_pty);
300 /* Execute the subshell at last */
302 switch (subshell_type)
304 case BASH:
305 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
306 break;
308 case TCSH:
309 execl (shell, "tcsh", (char *) NULL);
310 break;
312 case ZSH:
313 /* Use -g to exclude cmds beginning with space from history
314 * and -Z to use the line editor on non-interactive term */
315 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
317 break;
319 case FISH:
320 execl (shell, "fish", (char *) NULL);
321 break;
324 /* If we get this far, everything failed miserably */
325 _exit (FORK_FAILURE);
330 * Check MC_SID to prevent running one mc from another.
331 * Return:
332 * 0 if no parent mc in our session was found,
333 * 1 if parent mc was found and the user wants to continue,
334 * 2 if parent mc was found and the user wants to quit mc.
336 static int
337 check_sid (void)
339 pid_t my_sid, old_sid;
340 const char *sid_str;
341 int r;
343 sid_str = getenv ("MC_SID");
344 if (!sid_str)
345 return 0;
347 old_sid = (pid_t) strtol (sid_str, NULL, 0);
348 if (!old_sid)
349 return 0;
351 my_sid = getsid (0);
352 if (my_sid == -1)
353 return 0;
355 /* The parent mc is in a different session, it's OK */
356 if (old_sid != my_sid)
357 return 0;
359 r = query_dialog (_("Warning"),
360 _("GNU Midnight Commander is already\n"
361 "running on this terminal.\n"
362 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
363 if (r != 0)
365 return 2;
368 return 1;
373 * Fork the subshell, and set up many, many things.
375 * Possibly modifies the global variables:
376 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
377 * use_subshell - Is set to FALSE if we can't run the subshell
378 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
381 void
382 init_subshell (void)
384 /* This must be remembered across calls to init_subshell() */
385 static char pty_name[BUF_SMALL];
386 char precmd[BUF_SMALL];
388 switch (check_sid ())
390 case 1:
391 use_subshell = FALSE;
392 return;
393 case 2:
394 use_subshell = FALSE;
395 midnight_shutdown = 1;
396 return;
399 /* Take the current (hopefully pristine) tty mode and make */
400 /* a raw mode based on it now, before we do anything else with it */
401 init_raw_mode ();
403 if (subshell_pty == 0)
404 { /* First time through */
405 /* Find out what type of shell we have */
407 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
408 subshell_type = ZSH;
409 else if (strstr (shell, "/tcsh"))
410 subshell_type = TCSH;
411 else if (strstr (shell, "/csh"))
412 subshell_type = TCSH;
413 else if (strstr (shell, "/bash") || getenv ("BASH"))
414 subshell_type = BASH;
415 else if (strstr (shell, "/fish"))
416 subshell_type = FISH;
417 else
419 use_subshell = FALSE;
420 return;
423 /* Open a pty for talking to the subshell */
425 /* FIXME: We may need to open a fresh pty each time on SVR4 */
427 subshell_pty = pty_open_master (pty_name);
428 if (subshell_pty == -1)
430 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
431 use_subshell = FALSE;
432 return;
434 subshell_pty_slave = pty_open_slave (pty_name);
435 if (subshell_pty_slave == -1)
437 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
438 pty_name, unix_error_string (errno));
439 use_subshell = FALSE;
440 return;
443 /* Create a pipe for receiving the subshell's CWD */
445 if (subshell_type == TCSH)
447 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
448 mc_tmpdir (), (int) getpid ());
449 if (mkfifo (tcsh_fifo, 0600) == -1)
451 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
452 use_subshell = FALSE;
453 return;
456 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
458 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
459 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
461 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
462 perror (__FILE__ ": open");
463 use_subshell = FALSE;
464 return;
467 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
469 perror (__FILE__ ": couldn't create pipe");
470 use_subshell = FALSE;
471 return;
475 /* Fork the subshell */
477 subshell_alive = TRUE;
478 subshell_stopped = FALSE;
479 subshell_pid = fork ();
481 if (subshell_pid == -1)
483 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
484 /* We exit here because, if the process table is full, the */
485 /* other method of running user commands won't work either */
486 exit (EXIT_FAILURE);
489 if (subshell_pid == 0)
491 /* We are in the child process */
492 init_subshell_child (pty_name);
495 /* Set up `precmd' or equivalent for reading the subshell's CWD */
497 switch (subshell_type)
499 case BASH:
500 g_snprintf (precmd, sizeof (precmd),
501 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
502 break;
504 case ZSH:
505 g_snprintf (precmd, sizeof (precmd),
506 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
507 break;
509 case TCSH:
510 g_snprintf (precmd, sizeof (precmd),
511 "set echo_style=both;"
512 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
513 break;
514 case FISH:
515 g_snprintf (precmd, sizeof (precmd),
516 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
517 subshell_pipe[WRITE]);
518 break;
521 write_all (subshell_pty, precmd, strlen (precmd));
523 /* Wait until the subshell has started up and processed the command */
525 subshell_state = RUNNING_COMMAND;
526 tty_enable_interrupt_key ();
527 if (!feed_subshell (QUIETLY, TRUE))
529 use_subshell = FALSE;
531 tty_disable_interrupt_key ();
532 if (!subshell_alive)
533 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
537 static void
538 init_raw_mode ()
540 static int initialized = 0;
542 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
543 /* original settings. However, here we need to make this tty very raw, */
544 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
545 /* pty. So, instead of changing the code for execute(), pre_exec(), */
546 /* etc, we just set up the modes we need here, before each command. */
548 if (initialized == 0) /* First time: initialise `raw_mode' */
550 tcgetattr (STDOUT_FILENO, &raw_mode);
551 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
552 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
553 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
554 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
555 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
556 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
557 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
558 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
559 initialized = 1;
565 invoke_subshell (const char *command, int how, char **new_dir)
567 char *pcwd;
569 /* Make the MC terminal transparent */
570 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
572 /* Make the subshell change to MC's working directory */
573 if (new_dir)
574 do_subshell_chdir (current_panel->cwd, TRUE, 1);
576 if (command == NULL) /* The user has done "C-o" from MC */
578 if (subshell_state == INACTIVE)
580 subshell_state = ACTIVE;
581 /* FIXME: possibly take out this hack; the user can
582 re-play it by hitting C-hyphen a few times! */
583 if (subshell_ready)
584 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
587 else /* MC has passed us a user command */
589 if (how == QUIETLY)
590 write_all (subshell_pty, " ", 1);
591 /* FIXME: if command is long (>8KB ?) we go comma */
592 write_all (subshell_pty, command, strlen (command));
593 write_all (subshell_pty, "\n", 1);
594 subshell_state = RUNNING_COMMAND;
595 subshell_ready = FALSE;
598 feed_subshell (how, FALSE);
600 pcwd = vfs_translate_path_n (current_panel->cwd);
601 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
602 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
603 g_free (pcwd);
605 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
606 while (!subshell_alive && !quit && use_subshell)
607 init_subshell ();
609 prompt_pos = 0;
611 return quit;
616 read_subshell_prompt (void)
618 static int prompt_size = INITIAL_PROMPT_SIZE;
619 int bytes = 0, i, rc = 0;
620 struct timeval timeleft = { 0, 0 };
622 fd_set tmp;
623 FD_ZERO (&tmp);
624 FD_SET (subshell_pty, &tmp);
626 if (subshell_prompt == NULL)
627 { /* First time through */
628 subshell_prompt = g_malloc (prompt_size);
629 *subshell_prompt = '\0';
630 prompt_pos = 0;
633 while (subshell_alive && (rc = select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft)))
635 /* Check for `select' errors */
636 if (rc == -1)
638 if (errno == EINTR)
639 continue;
640 else
642 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
643 exit (EXIT_FAILURE);
647 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
649 /* Extract the prompt from the shell output */
651 for (i = 0; i < bytes; ++i)
652 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
654 prompt_pos = 0;
656 else
658 if (!pty_buffer[i])
659 continue;
661 subshell_prompt[prompt_pos++] = pty_buffer[i];
662 if (prompt_pos == prompt_size)
663 subshell_prompt = g_realloc (subshell_prompt, prompt_size *= 2);
666 subshell_prompt[prompt_pos] = '\0';
668 if (rc == 0 && bytes == 0)
669 return FALSE;
670 return TRUE;
673 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
674 static int
675 resize_tty (int fd)
677 #if defined TIOCSWINSZ
678 struct winsize tty_size;
680 tty_size.ws_row = LINES;
681 tty_size.ws_col = COLS;
682 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
684 return ioctl (fd, TIOCSWINSZ, &tty_size);
685 #else
686 return 0;
687 #endif
690 /* Resize subshell_pty */
691 void
692 resize_subshell (void)
694 if (use_subshell == 0)
695 return;
697 resize_tty (subshell_pty);
701 exit_subshell (void)
703 int subshell_quit = TRUE;
705 if (subshell_state != INACTIVE && subshell_alive)
706 subshell_quit =
707 !query_dialog (_("Warning"),
708 _("The shell is still active. Quit anyway?"),
709 D_NORMAL, 2, _("&Yes"), _("&No"));
711 if (subshell_quit)
713 if (subshell_type == TCSH)
715 if (unlink (tcsh_fifo) == -1)
716 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
717 tcsh_fifo, unix_error_string (errno));
720 g_free (subshell_prompt);
721 subshell_prompt = NULL;
722 pty_buffer[0] = '\0';
725 return subshell_quit;
730 * Carefully quote directory name to allow entering any directory safely,
731 * no matter what weird characters it may contain in its name.
732 * NOTE: Treat directory name an untrusted data, don't allow it to cause
733 * executing any commands in the shell. Escape all control characters.
734 * Use following technique:
736 * printf(1) with format string containing a single conversion specifier,
737 * "b", and an argument which contains a copy of the string passed to
738 * subshell_name_quote() with all characters, except digits and letters,
739 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
740 * numeric value of the character converted to octal number.
742 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
745 static char *
746 subshell_name_quote (const char *s)
748 char *ret, *d;
749 const char *su, *n;
750 const char *quote_cmd_start, *quote_cmd_end;
751 int c;
753 if (subshell_type == FISH)
755 quote_cmd_start = "(printf \"%b\" '";
756 quote_cmd_end = "')";
758 else
760 quote_cmd_start = "\"`printf \"%b\" '";
761 quote_cmd_end = "'`\"";
764 /* Factor 5 because we need \, 0 and 3 other digits per character. */
765 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
766 + (strlen (quote_cmd_end)));
767 if (d == NULL)
768 return NULL;
770 /* Prevent interpreting leading `-' as a switch for `cd' */
771 if (*s == '-')
773 *d++ = '.';
774 *d++ = '/';
777 /* Copy the beginning of the command to the buffer */
778 strcpy (d, quote_cmd_start);
779 d += strlen (quote_cmd_start);
782 * Print every character except digits and letters as a backslash-escape
783 * sequence of the form \0nnn, where "nnn" is the numeric value of the
784 * character converted to octal number.
786 su = s;
787 for (; su[0] != '\0';)
789 n = str_cget_next_char_safe (su);
790 if (str_isalnum (su))
792 memcpy (d, su, n - su);
793 d += n - su;
795 else
797 for (c = 0; c < n - su; c++)
799 sprintf (d, "\\0%03o", (unsigned char) su[c]);
800 d += 5;
803 su = n;
806 strcpy (d, quote_cmd_end);
808 return ret;
812 /* If it actually changed the directory it returns true */
813 void
814 do_subshell_chdir (const char *directory, int do_update, int reset_prompt)
816 char *pcwd;
817 char *temp;
818 char *translate;
820 pcwd = vfs_translate_path_n (current_panel->cwd);
822 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd)))
824 /* We have to repaint the subshell prompt if we read it from
825 * the main program. Please note that in the code after this
826 * if, the cd command that is sent will make the subshell
827 * repaint the prompt, so we don't have to paint it. */
828 if (do_update)
829 do_update_prompt ();
830 g_free (pcwd);
831 return;
834 /* The initial space keeps this out of the command history (in bash
835 because we set "HISTCONTROL=ignorespace") */
836 write_all (subshell_pty, " cd ", 4);
837 if (*directory)
839 translate = vfs_translate_path_n (directory);
840 if (translate)
842 temp = subshell_name_quote (translate);
843 if (temp)
845 write_all (subshell_pty, temp, strlen (temp));
846 g_free (temp);
848 else
850 /* Should not happen unless the directory name is so long
851 that we don't have memory to quote it. */
852 write_all (subshell_pty, ".", 1);
854 g_free (translate);
856 else
858 write_all (subshell_pty, ".", 1);
861 else
863 write_all (subshell_pty, "/", 1);
865 write_all (subshell_pty, "\n", 1);
867 subshell_state = RUNNING_COMMAND;
868 feed_subshell (QUIETLY, FALSE);
870 if (subshell_alive)
872 int bPathNotEq = strcmp (subshell_cwd, pcwd);
874 if (bPathNotEq && subshell_type == TCSH)
876 char rp_subshell_cwd[PATH_MAX];
877 char rp_current_panel_cwd[PATH_MAX];
879 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
880 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
882 if (p_subshell_cwd == NULL)
883 p_subshell_cwd = subshell_cwd;
884 if (p_current_panel_cwd == NULL)
885 p_current_panel_cwd = pcwd;
886 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
889 if (bPathNotEq && strcmp (pcwd, "."))
891 char *cwd = strip_password (g_strdup (pcwd), 1);
892 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
893 g_free (cwd);
897 if (reset_prompt)
898 prompt_pos = 0;
899 update_prompt = FALSE;
901 g_free (pcwd);
902 /* Make sure that MC never stores the CWD in a silly format */
903 /* like /usr////lib/../bin, or the strcmp() above will fail */
907 void
908 subshell_get_console_attributes (void)
910 /* Get our current terminal modes */
912 if (tcgetattr (STDOUT_FILENO, &shell_mode))
914 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
915 use_subshell = FALSE;
916 return;
921 /* Figure out whether the subshell has stopped, exited or been killed */
922 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
923 void
924 sigchld_handler (int sig)
926 int status;
927 pid_t pid;
929 (void) sig;
931 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
933 if (pid == subshell_pid)
935 /* Figure out what has happened to the subshell */
937 if (WIFSTOPPED (status))
939 if (WSTOPSIG (status) == SIGSTOP)
941 /* The subshell has received a SIGSTOP signal */
942 subshell_stopped = TRUE;
944 else
946 /* The user has suspended the subshell. Revive it */
947 kill (subshell_pid, SIGCONT);
950 else
952 /* The subshell has either exited normally or been killed */
953 subshell_alive = FALSE;
954 delete_select_channel (subshell_pty);
955 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
956 quit |= SUBSHELL_EXIT; /* Exited normally */
959 #ifdef __linux__
960 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
962 if (pid == cons_saver_pid)
965 if (WIFSTOPPED (status))
966 /* Someone has stopped cons.saver - restart it */
967 kill (pid, SIGCONT);
968 else
970 /* cons.saver has died - disable confole saving */
971 handle_console (CONSOLE_DONE);
972 console_flag = 0;
976 #endif /* __linux__ */
978 /* If we got here, some other child exited; ignore it */
982 /* Feed the subshell our keyboard input until it says it's finished */
983 static gboolean
984 feed_subshell (int how, int fail_on_error)
986 fd_set read_set; /* For `select' */
987 int maxfdp;
988 int bytes; /* For the return value from `read' */
989 int i; /* Loop counter */
991 struct timeval wtime; /* Maximum time we wait for the subshell */
992 struct timeval *wptr;
994 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
995 wtime.tv_sec = 10;
996 wtime.tv_usec = 0;
997 wptr = fail_on_error ? &wtime : NULL;
999 while (TRUE)
1001 if (!subshell_alive)
1002 return FALSE;
1004 /* Prepare the file-descriptor set and call `select' */
1006 FD_ZERO (&read_set);
1007 FD_SET (subshell_pty, &read_set);
1008 FD_SET (subshell_pipe[READ], &read_set);
1009 maxfdp = max (subshell_pty, subshell_pipe[READ]);
1010 if (how == VISIBLY)
1012 FD_SET (STDIN_FILENO, &read_set);
1013 maxfdp = max (maxfdp, STDIN_FILENO);
1016 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
1019 /* Despite using SA_RESTART, we still have to check for this */
1020 if (errno == EINTR)
1021 continue; /* try all over again */
1022 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1023 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
1024 unix_error_string (errno));
1025 exit (EXIT_FAILURE);
1028 if (FD_ISSET (subshell_pty, &read_set))
1029 /* Read from the subshell, write to stdout */
1031 /* This loop improves performance by reducing context switches
1032 by a factor of 20 or so... unfortunately, it also hangs MC
1033 randomly, because of an apparent Linux bug. Investigate. */
1034 /* for (i=0; i<5; ++i) * FIXME -- experimental */
1036 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
1038 /* The subshell has died */
1039 if (bytes == -1 && errno == EIO && !subshell_alive)
1040 return FALSE;
1042 if (bytes <= 0)
1044 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1045 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
1046 exit (EXIT_FAILURE);
1049 if (how == VISIBLY)
1050 write_all (STDOUT_FILENO, pty_buffer, bytes);
1053 else if (FD_ISSET (subshell_pipe[READ], &read_set))
1054 /* Read the subshell's CWD and capture its prompt */
1056 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
1057 if (bytes <= 0)
1059 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1060 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
1061 unix_error_string (errno));
1062 exit (EXIT_FAILURE);
1065 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
1067 synchronize ();
1069 subshell_ready = TRUE;
1070 if (subshell_state == RUNNING_COMMAND)
1072 subshell_state = INACTIVE;
1073 return TRUE;
1077 else if (FD_ISSET (STDIN_FILENO, &read_set))
1078 /* Read from stdin, write to the subshell */
1080 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
1081 if (bytes <= 0)
1083 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1084 fprintf (stderr,
1085 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
1086 exit (EXIT_FAILURE);
1089 for (i = 0; i < bytes; ++i)
1090 if (pty_buffer[i] == subshell_switch_key)
1092 write_all (subshell_pty, pty_buffer, i);
1093 if (subshell_ready)
1094 subshell_state = INACTIVE;
1095 return TRUE;
1098 write_all (subshell_pty, pty_buffer, bytes);
1100 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
1101 subshell_ready = FALSE;
1103 else
1104 return FALSE;
1109 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1110 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1111 static void
1112 synchronize (void)
1114 sigset_t sigchld_mask, old_mask;
1116 sigemptyset (&sigchld_mask);
1117 sigaddset (&sigchld_mask, SIGCHLD);
1118 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
1121 * SIGCHLD should not be blocked, but we unblock it just in case.
1122 * This is known to be useful for cygwin 1.3.12 and older.
1124 sigdelset (&old_mask, SIGCHLD);
1126 /* Wait until the subshell has stopped */
1127 while (subshell_alive && !subshell_stopped)
1128 sigsuspend (&old_mask);
1130 if (subshell_state != ACTIVE)
1132 /* Discard all remaining data from stdin to the subshell */
1133 tcflush (subshell_pty_slave, TCIFLUSH);
1136 subshell_stopped = FALSE;
1137 kill (subshell_pid, SIGCONT);
1139 sigprocmask (SIG_SETMASK, &old_mask, NULL);
1140 /* We can't do any better without modifying the shell(s) */
1143 /* pty opening functions */
1145 #ifdef HAVE_GRANTPT
1147 /* System V version of pty_open_master */
1149 static int
1150 pty_open_master (char *pty_name)
1152 char *slave_name;
1153 int pty_master;
1155 #ifdef HAVE_POSIX_OPENPT
1156 pty_master = posix_openpt (O_RDWR);
1157 #elif HAVE_GETPT
1158 /* getpt () is a GNU extension (glibc 2.1.x) */
1159 pty_master = getpt ();
1160 #elif IS_AIX
1161 strcpy (pty_name, "/dev/ptc");
1162 pty_master = open (pty_name, O_RDWR);
1163 #else
1164 strcpy (pty_name, "/dev/ptmx");
1165 pty_master = open (pty_name, O_RDWR);
1166 #endif
1168 if (pty_master == -1)
1169 return -1;
1171 if (grantpt (pty_master) == -1 /* Grant access to slave */
1172 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
1173 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
1175 close (pty_master);
1176 return -1;
1178 strcpy (pty_name, slave_name);
1179 return pty_master;
1182 /* System V version of pty_open_slave */
1183 static int
1184 pty_open_slave (const char *pty_name)
1186 int pty_slave = open (pty_name, O_RDWR);
1188 if (pty_slave == -1)
1190 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
1191 return -1;
1193 #if !defined(__osf__) && !defined(__linux__)
1194 #if defined (I_FIND) && defined (I_PUSH)
1195 if (!ioctl (pty_slave, I_FIND, "ptem"))
1196 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
1198 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1199 pty_slave, unix_error_string (errno));
1200 close (pty_slave);
1201 return -1;
1204 if (!ioctl (pty_slave, I_FIND, "ldterm"))
1205 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
1207 fprintf (stderr,
1208 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1209 pty_slave, unix_error_string (errno));
1210 close (pty_slave);
1211 return -1;
1213 #if !defined(sgi) && !defined(__sgi)
1214 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
1215 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
1217 fprintf (stderr,
1218 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1219 pty_slave, unix_error_string (errno));
1220 close (pty_slave);
1221 return -1;
1223 #endif /* sgi || __sgi */
1224 #endif /* I_FIND && I_PUSH */
1225 #endif /* __osf__ || __linux__ */
1227 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
1228 return pty_slave;
1231 #else /* !HAVE_GRANTPT */
1233 /* BSD version of pty_open_master */
1234 static int
1235 pty_open_master (char *pty_name)
1237 int pty_master;
1238 const char *ptr1, *ptr2;
1240 strcpy (pty_name, "/dev/ptyXX");
1241 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
1243 pty_name[8] = *ptr1;
1244 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
1246 pty_name[9] = *ptr2;
1248 /* Try to open master */
1249 pty_master = open (pty_name, O_RDWR);
1250 if (pty_master == -1)
1252 if (errno == ENOENT) /* Different from EIO */
1253 return -1; /* Out of pty devices */
1254 continue; /* Try next pty device */
1256 pty_name[5] = 't'; /* Change "pty" to "tty" */
1257 if (access (pty_name, 6) != 0)
1259 close (pty_master);
1260 pty_name[5] = 'p';
1261 continue;
1263 return pty_master;
1266 return -1; /* Ran out of pty devices */
1269 /* BSD version of pty_open_slave */
1270 static int
1271 pty_open_slave (const char *pty_name)
1273 int pty_slave;
1274 struct group *group_info = getgrnam ("tty");
1276 if (group_info != NULL)
1278 /* The following two calls will only succeed if we are root */
1279 /* [Commented out while permissions problem is investigated] */
1280 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1281 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1283 pty_slave = open (pty_name, O_RDWR);
1284 if (pty_slave == -1)
1285 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
1286 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
1287 return pty_slave;
1290 #endif /* !HAVE_GRANTPT */
1291 #endif /* HAVE_SUBSHELL_SUPPORT */