Changes into src directory:
[midnight-commander.git] / src / subshell.c
blob862175bc3719688d8e99d76ddc7e16c47d2a7bb5
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 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 /* 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 {READ=0, WRITE=1};
130 static char pty_buffer[PTY_BUFFER_SIZE] = "\0"; /* For reading/writing on the subshell's pty */
131 static int subshell_pipe[2]; /* To pass CWD info from the subshell to MC */
132 static pid_t subshell_pid = 1; /* The subshell's process ID */
133 static char subshell_cwd[MC_MAXPATHLEN+1]; /* One extra char for final '\n' */
135 /* Subshell type (gleaned from the SHELL environment variable, if available) */
136 static enum {
137 BASH,
138 TCSH,
139 ZSH,
140 FISH
141 } subshell_type;
143 /* Flag to indicate whether the subshell is ready for next command */
144 static int subshell_ready;
146 /* The following two flags can be changed by the SIGCHLD handler. This is */
147 /* OK, because the `int' type is updated atomically on all known machines */
148 static volatile int subshell_alive, subshell_stopped;
150 /* We store the terminal's initial mode here so that we can configure
151 the pty similarly, and also so we can restore the real terminal to
152 sanity if we have to exit abruptly */
153 static struct termios shell_mode;
155 /* This is a transparent mode for the terminal where MC is running on */
156 /* It is used when the shell is active, so that the control signals */
157 /* are delivered to the shell pty */
158 static struct termios raw_mode;
160 /* This counter indicates how many characters of prompt we have read */
161 /* FIXME: try to figure out why this had to become global */
162 static int prompt_pos;
166 * Write all data, even if the write() call is interrupted.
168 static ssize_t
169 write_all (int fd, const void *buf, size_t count)
171 ssize_t ret;
172 ssize_t written = 0;
173 while (count > 0) {
174 ret = write (fd, (const unsigned char *) buf + written, count);
175 if (ret < 0) {
176 if (errno == EINTR) {
177 continue;
178 } else {
179 return written > 0 ? written : ret;
182 count -= ret;
183 written += ret;
185 return written;
189 * Prepare child process to running the shell and run it.
191 * Modifies the global variables (in the child process only):
192 * shell_mode
194 * Returns: never.
196 static void
197 init_subshell_child (const char *pty_name)
199 const char *init_file = NULL;
200 pid_t mc_sid;
202 (void) pty_name;
203 setsid (); /* Get a fresh terminal session */
205 /* Make sure that it has become our controlling terminal */
207 /* Redundant on Linux and probably most systems, but just in case: */
209 #ifdef TIOCSCTTY
210 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
211 #endif
213 /* Configure its terminal modes and window size */
215 /* Set up the pty with the same termios flags as our own tty */
216 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode)) {
217 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n",
218 unix_error_string (errno));
219 _exit (FORK_FAILURE);
222 /* Set the pty's size (80x25 by default on Linux) according to the */
223 /* size of the real terminal as calculated by ncurses, if possible */
224 resize_tty (subshell_pty_slave);
226 /* Set up the subshell's environment and init file name */
228 /* It simplifies things to change to our home directory here, */
229 /* and the user's startup file may do a `cd' command anyway */
231 int ret;
232 ret = chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
235 /* Set MC_SID to prevent running one mc from another */
236 mc_sid = getsid (0);
237 if (mc_sid != -1) {
238 char sid_str[BUF_SMALL];
239 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld",
240 (long) mc_sid);
241 putenv (g_strdup (sid_str));
244 switch (subshell_type) {
245 case BASH:
246 init_file = MC_USERCONF_DIR PATH_SEP_STR "bashrc";
247 if (access (init_file, R_OK) == -1)
248 init_file = ".bashrc";
250 /* Make MC's special commands not show up in bash's history */
251 putenv ((char*)"HISTCONTROL=ignorespace");
253 /* Allow alternative readline settings for MC */
254 if (access (MC_USERCONF_DIR PATH_SEP_STR "inputrc", R_OK) == 0)
255 putenv ((char*)"INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR "/inputrc");
257 break;
259 /* TODO: Find a way to pass initfile to TCSH and ZSH */
260 case TCSH:
261 case ZSH:
262 case FISH:
263 break;
265 default:
266 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n",
267 subshell_type);
268 _exit (FORK_FAILURE);
271 /* Attach all our standard file descriptors to the pty */
273 /* This is done just before the fork, because stderr must still */
274 /* be connected to the real tty during the above error messages; */
275 /* otherwise the user will never see them. */
277 dup2 (subshell_pty_slave, STDIN_FILENO);
278 dup2 (subshell_pty_slave, STDOUT_FILENO);
279 dup2 (subshell_pty_slave, STDERR_FILENO);
281 close (subshell_pipe[READ]);
282 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
283 /* Close master side of pty. This is important; apart from */
284 /* freeing up the descriptor for use in the subshell, it also */
285 /* means that when MC exits, the subshell will get a SIGHUP and */
286 /* exit too, because there will be no more descriptors pointing */
287 /* at the master side of the pty and so it will disappear. */
288 close (subshell_pty);
290 /* Execute the subshell at last */
292 switch (subshell_type) {
293 case BASH:
294 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
295 break;
297 case TCSH:
298 execl (shell, "tcsh", (char *) NULL);
299 break;
301 case ZSH:
302 /* Use -g to exclude cmds beginning with space from history
303 * and -Z to use the line editor on non-interactive term */
304 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
306 break;
308 case FISH:
309 execl (shell, "fish", (char *) NULL);
310 break;
313 /* If we get this far, everything failed miserably */
314 _exit (FORK_FAILURE);
319 * Check MC_SID to prevent running one mc from another.
320 * Return:
321 * 0 if no parent mc in our session was found,
322 * 1 if parent mc was found and the user wants to continue,
323 * 2 if parent mc was found and the user wants to quit mc.
325 static int
326 check_sid (void)
328 pid_t my_sid, old_sid;
329 const char *sid_str;
330 int r;
332 sid_str = getenv ("MC_SID");
333 if (!sid_str)
334 return 0;
336 old_sid = (pid_t) strtol (sid_str, NULL, 0);
337 if (!old_sid)
338 return 0;
340 my_sid = getsid (0);
341 if (my_sid == -1)
342 return 0;
344 /* The parent mc is in a different session, it's OK */
345 if (old_sid != my_sid)
346 return 0;
348 r = query_dialog (_("Warning"),
349 _("GNU Midnight Commander is already\n"
350 "running on this terminal.\n"
351 "Subshell support will be disabled."), D_ERROR, 2,
352 _("&OK"), _("&Quit"));
353 if (r != 0) {
354 return 2;
357 return 1;
362 * Fork the subshell, and set up many, many things.
364 * Possibly modifies the global variables:
365 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
366 * use_subshell - Is set to FALSE if we can't run the subshell
367 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
370 void
371 init_subshell (void)
373 /* This must be remembered across calls to init_subshell() */
374 static char pty_name[BUF_SMALL];
375 char precmd[BUF_SMALL];
377 switch (check_sid ()) {
378 case 1:
379 use_subshell = FALSE;
380 return;
381 case 2:
382 use_subshell = FALSE;
383 midnight_shutdown = 1;
384 return;
387 /* Take the current (hopefully pristine) tty mode and make */
388 /* a raw mode based on it now, before we do anything else with it */
389 init_raw_mode ();
391 if (subshell_pty == 0) { /* First time through */
392 /* Find out what type of shell we have */
394 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
395 subshell_type = ZSH;
396 else if (strstr (shell, "/tcsh"))
397 subshell_type = TCSH;
398 else if (strstr (shell, "/csh"))
399 subshell_type = TCSH;
400 else if (strstr (shell, "/bash") || getenv ("BASH"))
401 subshell_type = BASH;
402 else if (strstr (shell, "/fish"))
403 subshell_type = FISH;
404 else {
405 use_subshell = FALSE;
406 return;
409 /* Open a pty for talking to the subshell */
411 /* FIXME: We may need to open a fresh pty each time on SVR4 */
413 subshell_pty = pty_open_master (pty_name);
414 if (subshell_pty == -1) {
415 fprintf (stderr, "Cannot open master side of pty: %s\r\n",
416 unix_error_string (errno));
417 use_subshell = FALSE;
418 return;
420 subshell_pty_slave = pty_open_slave (pty_name);
421 if (subshell_pty_slave == -1) {
422 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
423 pty_name, unix_error_string (errno));
424 use_subshell = FALSE;
425 return;
428 /* Create a pipe for receiving the subshell's CWD */
430 if (subshell_type == TCSH) {
431 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
432 mc_tmpdir (), (int) getpid ());
433 if (mkfifo (tcsh_fifo, 0600) == -1) {
434 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo,
435 unix_error_string (errno));
436 use_subshell = FALSE;
437 return;
440 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
442 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
443 || (subshell_pipe[WRITE] =
444 open (tcsh_fifo, O_RDWR)) == -1) {
445 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
446 perror (__FILE__": open");
447 use_subshell = FALSE;
448 return;
450 } else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe)) {
451 perror (__FILE__": couldn't create pipe");
452 use_subshell = FALSE;
453 return;
457 /* Fork the subshell */
459 subshell_alive = TRUE;
460 subshell_stopped = FALSE;
461 subshell_pid = fork ();
463 if (subshell_pid == -1) {
464 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n",
465 unix_error_string (errno));
466 /* We exit here because, if the process table is full, the */
467 /* other method of running user commands won't work either */
468 exit (1);
471 if (subshell_pid == 0) { /* We are in the child process */
472 init_subshell_child (pty_name);
475 /* Set up `precmd' or equivalent for reading the subshell's CWD */
477 switch (subshell_type) {
478 case BASH:
479 g_snprintf (precmd, sizeof (precmd),
480 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
481 subshell_pipe[WRITE]);
482 break;
484 case ZSH:
485 g_snprintf (precmd, sizeof (precmd),
486 " precmd(){ pwd>&%d;kill -STOP $$ }\n",
487 subshell_pipe[WRITE]);
488 break;
490 case TCSH:
491 g_snprintf (precmd, sizeof (precmd),
492 "set echo_style=both;"
493 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n",
494 tcsh_fifo);
495 break;
496 case FISH:
497 g_snprintf (precmd, sizeof (precmd),
498 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
499 subshell_pipe[WRITE]);
500 break;
503 write_all (subshell_pty, precmd, strlen (precmd));
505 /* Wait until the subshell has started up and processed the command */
507 subshell_state = RUNNING_COMMAND;
508 tty_enable_interrupt_key ();
509 if (!feed_subshell (QUIETLY, TRUE)) {
510 use_subshell = FALSE;
512 tty_disable_interrupt_key ();
513 if (!subshell_alive)
514 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
518 static void init_raw_mode ()
520 static int initialized = 0;
522 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
523 /* original settings. However, here we need to make this tty very raw, */
524 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
525 /* pty. So, instead of changing the code for execute(), pre_exec(), */
526 /* etc, we just set up the modes we need here, before each command. */
528 if (initialized == 0) /* First time: initialise `raw_mode' */
530 tcgetattr (STDOUT_FILENO, &raw_mode);
531 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
532 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
533 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
534 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
535 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
536 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
537 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
538 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
539 initialized = 1;
544 int invoke_subshell (const char *command, int how, char **new_dir)
546 char *pcwd;
548 /* Make the MC terminal transparent */
549 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
551 /* Make the subshell change to MC's working directory */
552 if (new_dir)
553 do_subshell_chdir (current_panel->cwd, TRUE, 1);
555 if (command == NULL) /* The user has done "C-o" from MC */
557 if (subshell_state == INACTIVE)
559 subshell_state = ACTIVE;
560 /* FIXME: possibly take out this hack; the user can
561 re-play it by hitting C-hyphen a few times! */
562 if (subshell_ready)
563 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
566 else /* MC has passed us a user command */
568 if (how == QUIETLY)
569 write_all (subshell_pty, " ", 1);
570 /* FIXME: if command is long (>8KB ?) we go comma */
571 write_all (subshell_pty, command, strlen (command));
572 write_all (subshell_pty, "\n", 1);
573 subshell_state = RUNNING_COMMAND;
574 subshell_ready = FALSE;
577 feed_subshell (how, FALSE);
579 pcwd = vfs_translate_path_n (current_panel->cwd);
580 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
581 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
582 g_free (pcwd);
584 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
585 while (!subshell_alive && !quit && use_subshell)
586 init_subshell ();
588 prompt_pos = 0;
590 return quit;
595 read_subshell_prompt (void)
597 static int prompt_size = INITIAL_PROMPT_SIZE;
598 int bytes = 0, i, rc = 0;
599 struct timeval timeleft = { 0, 0 };
601 fd_set tmp;
602 FD_ZERO (&tmp);
603 FD_SET (subshell_pty, &tmp);
605 if (subshell_prompt == NULL) { /* First time through */
606 subshell_prompt = g_malloc (prompt_size);
607 *subshell_prompt = '\0';
608 prompt_pos = 0;
611 while (subshell_alive
612 && (rc =
613 select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft))) {
614 /* Check for `select' errors */
615 if (rc == -1) {
616 if (errno == EINTR)
617 continue;
618 else {
619 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n",
620 unix_error_string (errno));
621 exit (1);
625 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
627 /* Extract the prompt from the shell output */
629 for (i = 0; i < bytes; ++i)
630 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r') {
631 prompt_pos = 0;
632 } else {
633 if (!pty_buffer[i])
634 continue;
636 subshell_prompt[prompt_pos++] = pty_buffer[i];
637 if (prompt_pos == prompt_size)
638 subshell_prompt =
639 g_realloc (subshell_prompt, prompt_size *= 2);
642 subshell_prompt[prompt_pos] = '\0';
644 if (rc == 0 && bytes == 0)
645 return FALSE;
646 return TRUE;
649 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
650 static int resize_tty (int fd)
652 #if defined TIOCSWINSZ
653 struct winsize tty_size;
655 tty_size.ws_row = LINES;
656 tty_size.ws_col = COLS;
657 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
659 return ioctl (fd, TIOCSWINSZ, &tty_size);
660 #else
661 return 0;
662 #endif
665 /* Resize subshell_pty */
666 void resize_subshell (void)
668 if (use_subshell == 0)
669 return;
671 resize_tty (subshell_pty);
675 exit_subshell (void)
677 int subshell_quit = TRUE;
679 if (subshell_state != INACTIVE && subshell_alive)
680 subshell_quit =
681 !query_dialog (_("Warning"),
682 _(" The shell is still active. Quit anyway? "),
683 D_NORMAL, 2, _("&Yes"), _("&No"));
685 if (subshell_quit) {
686 if (subshell_type == TCSH) {
687 if (unlink (tcsh_fifo) == -1)
688 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
689 tcsh_fifo, unix_error_string (errno));
692 g_free (subshell_prompt);
693 subshell_prompt = NULL;
694 pty_buffer[0] = '\0';
697 return subshell_quit;
702 * Carefully quote directory name to allow entering any directory safely,
703 * no matter what weird characters it may contain in its name.
704 * NOTE: Treat directory name an untrusted data, don't allow it to cause
705 * executing any commands in the shell. Escape all control characters.
706 * Use following technique:
708 * printf(1) with format string containing a single conversion specifier,
709 * "b", and an argument which contains a copy of the string passed to
710 * subshell_name_quote() with all characters, except digits and letters,
711 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
712 * numeric value of the character converted to octal number.
714 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
717 static char *
718 subshell_name_quote (const char *s)
720 char *ret, *d;
721 const char *su, *n;
722 const char *quote_cmd_start, *quote_cmd_end;
723 int c;
725 if (subshell_type == FISH) {
726 quote_cmd_start = "(printf \"%b\" '";
727 quote_cmd_end = "')";
728 } else {
729 quote_cmd_start = "\"`printf \"%b\" '";
730 quote_cmd_end = "'`\"";
733 /* Factor 5 because we need \, 0 and 3 other digits per character. */
734 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen(quote_cmd_start))
735 + (strlen(quote_cmd_end)));
736 if (d == NULL)
737 return NULL;
739 /* Prevent interpreting leading `-' as a switch for `cd' */
740 if (*s == '-') {
741 *d++ = '.';
742 *d++ = '/';
745 /* Copy the beginning of the command to the buffer */
746 strcpy (d, quote_cmd_start);
747 d += strlen(quote_cmd_start);
750 * Print every character except digits and letters as a backslash-escape
751 * sequence of the form \0nnn, where "nnn" is the numeric value of the
752 * character converted to octal number.
754 su = s;
755 for (; su[0] != '\0'; ) {
756 n = str_cget_next_char_safe (su);
757 if (str_isalnum (su)) {
758 memcpy (d, su, n - su);
759 d+= n - su;
760 } else {
761 for (c = 0; c < n - su; c++) {
762 sprintf (d, "\\0%03o", (unsigned char) su[c]);
763 d += 5;
766 su = n;
769 strcpy (d, quote_cmd_end);
771 return ret;
775 /* If it actually changed the directory it returns true */
776 void
777 do_subshell_chdir (const char *directory, int do_update, int reset_prompt)
779 char *pcwd;
780 char *temp;
781 char *translate;
783 pcwd = vfs_translate_path_n (current_panel->cwd);
785 if (!
786 (subshell_state == INACTIVE
787 && strcmp (subshell_cwd, pcwd))) {
788 /* We have to repaint the subshell prompt if we read it from
789 * the main program. Please note that in the code after this
790 * if, the cd command that is sent will make the subshell
791 * repaint the prompt, so we don't have to paint it. */
792 if (do_update)
793 do_update_prompt ();
794 g_free (pcwd);
795 return;
798 /* The initial space keeps this out of the command history (in bash
799 because we set "HISTCONTROL=ignorespace") */
800 write_all (subshell_pty, " cd ", 4);
801 if (*directory) {
802 translate = vfs_translate_path_n (directory);
803 if (translate) {
804 temp = subshell_name_quote (translate);
805 if (temp) {
806 write_all (subshell_pty, temp, strlen (temp));
807 g_free (temp);
808 } else {
809 /* Should not happen unless the directory name is so long
810 that we don't have memory to quote it. */
811 write_all (subshell_pty, ".", 1);
813 g_free (translate);
814 } else {
815 write_all (subshell_pty, ".", 1);
817 } else {
818 write_all (subshell_pty, "/", 1);
820 write_all (subshell_pty, "\n", 1);
822 subshell_state = RUNNING_COMMAND;
823 feed_subshell (QUIETLY, FALSE);
825 if (subshell_alive) {
826 int bPathNotEq = strcmp (subshell_cwd, pcwd);
828 if (bPathNotEq && subshell_type == TCSH) {
829 char rp_subshell_cwd[PATH_MAX];
830 char rp_current_panel_cwd[PATH_MAX];
832 char *p_subshell_cwd =
833 mc_realpath (subshell_cwd, rp_subshell_cwd);
834 char *p_current_panel_cwd =
835 mc_realpath (pcwd, rp_current_panel_cwd);
837 if (p_subshell_cwd == NULL)
838 p_subshell_cwd = subshell_cwd;
839 if (p_current_panel_cwd == NULL)
840 p_current_panel_cwd = pcwd;
841 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
844 if (bPathNotEq && strcmp (pcwd, ".")) {
845 char *cwd = strip_password (g_strdup (pcwd), 1);
846 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
847 g_free (cwd);
851 if (reset_prompt)
852 prompt_pos = 0;
853 update_prompt = FALSE;
855 g_free (pcwd);
856 /* Make sure that MC never stores the CWD in a silly format */
857 /* like /usr////lib/../bin, or the strcmp() above will fail */
861 void
862 subshell_get_console_attributes (void)
864 /* Get our current terminal modes */
866 if (tcgetattr (STDOUT_FILENO, &shell_mode)) {
867 fprintf (stderr, "Cannot get terminal settings: %s\r\n",
868 unix_error_string (errno));
869 use_subshell = FALSE;
870 return;
875 /* Figure out whether the subshell has stopped, exited or been killed */
876 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
877 void
878 sigchld_handler (int sig)
880 int status;
881 pid_t pid;
883 (void) sig;
885 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
887 if (pid == subshell_pid) {
888 /* Figure out what has happened to the subshell */
890 if (WIFSTOPPED (status)) {
891 if (WSTOPSIG (status) == SIGSTOP) {
892 /* The subshell has received a SIGSTOP signal */
893 subshell_stopped = TRUE;
894 } else {
895 /* The user has suspended the subshell. Revive it */
896 kill (subshell_pid, SIGCONT);
898 } else {
899 /* The subshell has either exited normally or been killed */
900 subshell_alive = FALSE;
901 delete_select_channel (subshell_pty);
902 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
903 quit |= SUBSHELL_EXIT; /* Exited normally */
906 #ifdef __linux__
907 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
909 if (pid == cons_saver_pid) {
911 if (WIFSTOPPED (status))
912 /* Someone has stopped cons.saver - restart it */
913 kill (pid, SIGCONT);
914 else {
915 /* cons.saver has died - disable confole saving */
916 handle_console (CONSOLE_DONE);
917 console_flag = 0;
921 #endif /* __linux__ */
923 /* If we got here, some other child exited; ignore it */
927 /* Feed the subshell our keyboard input until it says it's finished */
928 static int
929 feed_subshell (int how, int fail_on_error)
931 fd_set read_set; /* For `select' */
932 int maxfdp;
933 int bytes; /* For the return value from `read' */
934 int i; /* Loop counter */
936 struct timeval wtime; /* Maximum time we wait for the subshell */
937 struct timeval *wptr;
939 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
940 wtime.tv_sec = 10;
941 wtime.tv_usec = 0;
942 wptr = fail_on_error ? &wtime : NULL;
944 while (1) {
945 if (!subshell_alive)
946 return FALSE;
948 /* Prepare the file-descriptor set and call `select' */
950 FD_ZERO (&read_set);
951 FD_SET (subshell_pty, &read_set);
952 FD_SET (subshell_pipe[READ], &read_set);
953 maxfdp = max (subshell_pty, subshell_pipe[READ]);
954 if (how == VISIBLY) {
955 FD_SET (STDIN_FILENO, &read_set);
956 maxfdp = max (maxfdp, STDIN_FILENO);
959 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1) {
961 /* Despite using SA_RESTART, we still have to check for this */
962 if (errno == EINTR)
963 continue; /* try all over again */
964 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
965 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
966 unix_error_string (errno));
967 exit (1);
970 if (FD_ISSET (subshell_pty, &read_set))
971 /* Read from the subshell, write to stdout */
973 /* This loop improves performance by reducing context switches
974 by a factor of 20 or so... unfortunately, it also hangs MC
975 randomly, because of an apparent Linux bug. Investigate. */
976 /* for (i=0; i<5; ++i) * FIXME -- experimental */
978 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
980 /* The subshell has died */
981 if (bytes == -1 && errno == EIO && !subshell_alive)
982 return FALSE;
984 if (bytes <= 0) {
985 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
986 fprintf (stderr, "read (subshell_pty...): %s\r\n",
987 unix_error_string (errno));
988 exit (1);
991 if (how == VISIBLY)
992 write_all (STDOUT_FILENO, pty_buffer, bytes);
995 else if (FD_ISSET (subshell_pipe[READ], &read_set))
996 /* Read the subshell's CWD and capture its prompt */
999 bytes =
1000 read (subshell_pipe[READ], subshell_cwd,
1001 MC_MAXPATHLEN + 1);
1002 if (bytes <= 0) {
1003 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1004 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
1005 unix_error_string (errno));
1006 exit (1);
1009 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
1011 synchronize ();
1013 subshell_ready = TRUE;
1014 if (subshell_state == RUNNING_COMMAND) {
1015 subshell_state = INACTIVE;
1016 return 1;
1020 else if (FD_ISSET (STDIN_FILENO, &read_set))
1021 /* Read from stdin, write to the subshell */
1023 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
1024 if (bytes <= 0) {
1025 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1026 fprintf (stderr,
1027 "read (STDIN_FILENO, pty_buffer...): %s\r\n",
1028 unix_error_string (errno));
1029 exit (1);
1032 for (i = 0; i < bytes; ++i)
1033 if (pty_buffer[i] == subshell_switch_key) {
1034 write_all (subshell_pty, pty_buffer, i);
1035 if (subshell_ready)
1036 subshell_state = INACTIVE;
1037 return TRUE;
1040 write_all (subshell_pty, pty_buffer, bytes);
1042 if (pty_buffer[bytes-1] == '\n' || pty_buffer[bytes-1] == '\r')
1043 subshell_ready = FALSE;
1044 } else {
1045 return FALSE;
1051 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1052 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1053 static void synchronize (void)
1055 sigset_t sigchld_mask, old_mask;
1057 sigemptyset (&sigchld_mask);
1058 sigaddset (&sigchld_mask, SIGCHLD);
1059 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
1062 * SIGCHLD should not be blocked, but we unblock it just in case.
1063 * This is known to be useful for cygwin 1.3.12 and older.
1065 sigdelset (&old_mask, SIGCHLD);
1067 /* Wait until the subshell has stopped */
1068 while (subshell_alive && !subshell_stopped)
1069 sigsuspend (&old_mask);
1071 if (subshell_state != ACTIVE) {
1072 /* Discard all remaining data from stdin to the subshell */
1073 tcflush (subshell_pty_slave, TCIFLUSH);
1076 subshell_stopped = FALSE;
1077 kill (subshell_pid, SIGCONT);
1079 sigprocmask (SIG_SETMASK, &old_mask, NULL);
1080 /* We can't do any better without modifying the shell(s) */
1083 /* pty opening functions */
1085 #ifdef HAVE_GRANTPT
1087 /* System V version of pty_open_master */
1089 static int pty_open_master (char *pty_name)
1091 char *slave_name;
1092 int pty_master;
1094 #ifdef HAVE_POSIX_OPENPT
1095 pty_master = posix_openpt(O_RDWR);
1096 #elif HAVE_GETPT
1097 /* getpt () is a GNU extension (glibc 2.1.x) */
1098 pty_master = getpt ();
1099 #elif IS_AIX
1100 strcpy (pty_name, "/dev/ptc");
1101 pty_master = open (pty_name, O_RDWR);
1102 #else
1103 strcpy (pty_name, "/dev/ptmx");
1104 pty_master = open (pty_name, O_RDWR);
1105 #endif
1107 if (pty_master == -1)
1108 return -1;
1110 if (grantpt (pty_master) == -1 /* Grant access to slave */
1111 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
1112 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
1114 close (pty_master);
1115 return -1;
1117 strcpy (pty_name, slave_name);
1118 return pty_master;
1121 /* System V version of pty_open_slave */
1122 static int
1123 pty_open_slave (const char *pty_name)
1125 int pty_slave = open (pty_name, O_RDWR);
1127 if (pty_slave == -1) {
1128 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name,
1129 unix_error_string (errno));
1130 return -1;
1132 #if !defined(__osf__) && !defined(__linux__)
1133 #if defined (I_FIND) && defined (I_PUSH)
1134 if (!ioctl (pty_slave, I_FIND, "ptem"))
1135 if (ioctl (pty_slave, I_PUSH, "ptem") == -1) {
1136 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1137 pty_slave, unix_error_string (errno));
1138 close (pty_slave);
1139 return -1;
1142 if (!ioctl (pty_slave, I_FIND, "ldterm"))
1143 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1) {
1144 fprintf (stderr,
1145 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1146 pty_slave, unix_error_string (errno));
1147 close (pty_slave);
1148 return -1;
1150 #if !defined(sgi) && !defined(__sgi)
1151 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
1152 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1) {
1153 fprintf (stderr,
1154 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1155 pty_slave, unix_error_string (errno));
1156 close (pty_slave);
1157 return -1;
1159 #endif /* sgi || __sgi */
1160 #endif /* I_FIND && I_PUSH */
1161 #endif /* __osf__ || __linux__ */
1163 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1164 return pty_slave;
1167 #else /* !HAVE_GRANTPT */
1169 /* BSD version of pty_open_master */
1170 static int pty_open_master (char *pty_name)
1172 int pty_master;
1173 const char *ptr1, *ptr2;
1175 strcpy (pty_name, "/dev/ptyXX");
1176 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
1178 pty_name [8] = *ptr1;
1179 for (ptr2 = "0123456789abcdef"; *ptr2; ++ptr2)
1181 pty_name [9] = *ptr2;
1183 /* Try to open master */
1184 if ((pty_master = open (pty_name, O_RDWR)) == -1) {
1185 if (errno == ENOENT) /* Different from EIO */
1186 return -1; /* Out of pty devices */
1187 else
1188 continue; /* Try next pty device */
1190 pty_name [5] = 't'; /* Change "pty" to "tty" */
1191 if (access (pty_name, 6)){
1192 close (pty_master);
1193 pty_name [5] = 'p';
1194 continue;
1196 return pty_master;
1199 return -1; /* Ran out of pty devices */
1202 /* BSD version of pty_open_slave */
1203 static int
1204 pty_open_slave (const char *pty_name)
1206 int pty_slave;
1207 struct group *group_info = getgrnam ("tty");
1209 if (group_info != NULL) {
1210 /* The following two calls will only succeed if we are root */
1211 /* [Commented out while permissions problem is investigated] */
1212 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1213 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1215 if ((pty_slave = open (pty_name, O_RDWR)) == -1)
1216 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
1217 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1218 return pty_slave;
1221 #endif /* !HAVE_GRANTPT */
1222 #endif /* HAVE_SUBSHELL_SUPPORT */