2 Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
6 The Free Software Foundation, Inc.
8 This file is part of the Midnight Commander.
10 The Midnight Commander is free software: you can redistribute it
11 and/or modify it under the terms of the GNU General Public License as
12 published by the Free Software Foundation, either version 3 of the License,
13 or (at your option) any later version.
15 The Midnight Commander is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 * \brief Source: concurrent shell support
30 #ifdef HAVE_SUBSHELL_SUPPORT
43 #include <sys/types.h>
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
52 #include <stropts.h> /* For I_PUSH */
53 #endif /* HAVE_STROPTS_H */
55 #include "lib/global.h"
57 #include "lib/tty/tty.h" /* LINES */
58 #include "lib/tty/key.h" /* XCTRL */
59 #include "lib/vfs/vfs.h"
60 #include "lib/strutil.h"
61 #include "lib/mcconfig.h"
63 #include "lib/widget.h"
65 #include "filemanager/midnight.h" /* current_panel */
67 #include "consaver/cons.saver.h" /* handle_console() */
71 /*** global variables ****************************************************************************/
73 /* State of the subshell:
74 * INACTIVE: the default state; awaiting a command
75 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
76 * RUNNING_COMMAND: return to MC when the current command finishes */
77 enum subshell_state_enum subshell_state
;
79 /* Holds the latest prompt captured from the subshell */
80 char *subshell_prompt
= NULL
;
82 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
83 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
84 gboolean update_subshell_prompt
= FALSE
;
86 /*** file scope macro definitions ****************************************************************/
89 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
93 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
97 #define STDIN_FILENO 0
100 #ifndef STDOUT_FILENO
101 #define STDOUT_FILENO 1
104 #ifndef STDERR_FILENO
105 #define STDERR_FILENO 2
108 /* Initial length of the buffer for the subshell's prompt */
109 #define INITIAL_PROMPT_SIZE 10
111 /* Used by the child process to indicate failure to start the subshell */
112 #define FORK_FAILURE 69 /* Arbitrary */
114 /* Length of the buffer for all I/O with the subshell */
115 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
117 /*** file scope type declarations ****************************************************************/
126 /* Subshell type (gleaned from the SHELL environment variable, if available) */
135 /*** file scope variables ************************************************************************/
137 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
138 static char tcsh_fifo
[128];
140 static int subshell_pty_slave
= -1;
142 /* The key for switching back to MC from the subshell */
144 static const char subshell_switch_key
= XCTRL ('o') & 255;
147 /* For reading/writing on the subshell's pty */
148 static char pty_buffer
[PTY_BUFFER_SIZE
] = "\0";
150 /* To pass CWD info from the subshell to MC */
151 static int subshell_pipe
[2];
153 /* The subshell's process ID */
154 static pid_t subshell_pid
= 1;
156 /* One extra char for final '\n' */
157 static char subshell_cwd
[MC_MAXPATHLEN
+ 1];
159 /* Flag to indicate whether the subshell is ready for next command */
160 static int subshell_ready
;
162 /* The following two flags can be changed by the SIGCHLD handler. This is */
163 /* OK, because the `int' type is updated atomically on all known machines */
164 static volatile int subshell_alive
, subshell_stopped
;
166 /* We store the terminal's initial mode here so that we can configure
167 the pty similarly, and also so we can restore the real terminal to
168 sanity if we have to exit abruptly */
169 static struct termios shell_mode
;
171 /* This is a transparent mode for the terminal where MC is running on */
172 /* It is used when the shell is active, so that the control signals */
173 /* are delivered to the shell pty */
174 static struct termios raw_mode
;
176 /* This counter indicates how many characters of prompt we have read */
177 /* FIXME: try to figure out why this had to become global */
178 static int prompt_pos
;
181 /*** file scope functions ************************************************************************/
182 /* --------------------------------------------------------------------------------------------- */
184 * Write all data, even if the write() call is interrupted.
188 write_all (int fd
, const void *buf
, size_t count
)
194 ret
= write (fd
, (const unsigned char *) buf
+ written
, count
);
203 return written
> 0 ? written
: ret
;
212 /* --------------------------------------------------------------------------------------------- */
214 * Prepare child process to running the shell and run it.
216 * Modifies the global variables (in the child process only):
223 init_subshell_child (const char *pty_name
)
225 char *init_file
= NULL
;
229 setsid (); /* Get a fresh terminal session */
231 /* Make sure that it has become our controlling terminal */
233 /* Redundant on Linux and probably most systems, but just in case: */
236 ioctl (subshell_pty_slave
, TIOCSCTTY
, 0);
239 /* Configure its terminal modes and window size */
241 /* Set up the pty with the same termios flags as our own tty */
242 if (tcsetattr (subshell_pty_slave
, TCSANOW
, &shell_mode
))
244 fprintf (stderr
, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno
));
245 _exit (FORK_FAILURE
);
248 /* Set the pty's size (80x25 by default on Linux) according to the */
249 /* size of the real terminal as calculated by ncurses, if possible */
250 tty_resize (subshell_pty_slave
);
252 /* Set up the subshell's environment and init file name */
254 /* It simplifies things to change to our home directory here, */
255 /* and the user's startup file may do a `cd' command anyway */
258 ret
= chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
261 /* Set MC_SID to prevent running one mc from another */
265 char sid_str
[BUF_SMALL
];
266 g_snprintf (sid_str
, sizeof (sid_str
), "MC_SID=%ld", (long) mc_sid
);
267 putenv (g_strdup (sid_str
));
270 switch (subshell_type
)
273 init_file
= mc_config_get_full_path ("bashrc");
275 if (access (init_file
, R_OK
) == -1)
278 init_file
= g_strdup (".bashrc");
281 /* Make MC's special commands not show up in bash's history */
282 putenv ((char *) "HISTCONTROL=ignorespace");
284 /* Allow alternative readline settings for MC */
286 char *input_file
= mc_config_get_full_path ("inputrc");
287 if (access (input_file
, R_OK
) == 0)
289 char *putenv_str
= g_strconcat ("INPUTRC=", input_file
, NULL
);
298 /* TODO: Find a way to pass initfile to TCSH and ZSH */
305 fprintf (stderr
, __FILE__
": unimplemented subshell type %d\r\n", subshell_type
);
306 _exit (FORK_FAILURE
);
309 /* Attach all our standard file descriptors to the pty */
311 /* This is done just before the fork, because stderr must still */
312 /* be connected to the real tty during the above error messages; */
313 /* otherwise the user will never see them. */
315 dup2 (subshell_pty_slave
, STDIN_FILENO
);
316 dup2 (subshell_pty_slave
, STDOUT_FILENO
);
317 dup2 (subshell_pty_slave
, STDERR_FILENO
);
319 close (subshell_pipe
[READ
]);
320 close (subshell_pty_slave
); /* These may be FD_CLOEXEC, but just in case... */
321 /* Close master side of pty. This is important; apart from */
322 /* freeing up the descriptor for use in the subshell, it also */
323 /* means that when MC exits, the subshell will get a SIGHUP and */
324 /* exit too, because there will be no more descriptors pointing */
325 /* at the master side of the pty and so it will disappear. */
326 close (mc_global
.tty
.subshell_pty
);
328 /* Execute the subshell at last */
330 switch (subshell_type
)
333 execl (shell
, "bash", "-rcfile", init_file
, (char *) NULL
);
337 execl (shell
, "tcsh", (char *) NULL
);
341 /* Use -g to exclude cmds beginning with space from history
342 * and -Z to use the line editor on non-interactive term */
343 execl (shell
, "zsh", "-Z", "-g", (char *) NULL
);
348 execl (shell
, "fish", (char *) NULL
);
352 /* If we get this far, everything failed miserably */
354 _exit (FORK_FAILURE
);
358 /* --------------------------------------------------------------------------------------------- */
360 * Check MC_SID to prevent running one mc from another.
362 * 0 if no parent mc in our session was found,
363 * 1 if parent mc was found and the user wants to continue,
364 * 2 if parent mc was found and the user wants to quit mc.
370 pid_t my_sid
, old_sid
;
374 sid_str
= getenv ("MC_SID");
378 old_sid
= (pid_t
) strtol (sid_str
, NULL
, 0);
386 /* The parent mc is in a different session, it's OK */
387 if (old_sid
!= my_sid
)
390 r
= query_dialog (_("Warning"),
391 _("GNU Midnight Commander is already\n"
392 "running on this terminal.\n"
393 "Subshell support will be disabled."), D_ERROR
, 2, _("&OK"), _("&Quit"));
402 /* --------------------------------------------------------------------------------------------- */
407 static int initialized
= 0;
409 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
410 /* original settings. However, here we need to make this tty very raw, */
411 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
412 /* pty. So, instead of changing the code for execute(), pre_exec(), */
413 /* etc, we just set up the modes we need here, before each command. */
415 if (initialized
== 0) /* First time: initialise `raw_mode' */
417 tcgetattr (STDOUT_FILENO
, &raw_mode
);
418 raw_mode
.c_lflag
&= ~ICANON
; /* Disable line-editing chars, etc. */
419 raw_mode
.c_lflag
&= ~ISIG
; /* Disable intr, quit & suspend chars */
420 raw_mode
.c_lflag
&= ~ECHO
; /* Disable input echoing */
421 raw_mode
.c_iflag
&= ~IXON
; /* Pass ^S/^Q to subshell undisturbed */
422 raw_mode
.c_iflag
&= ~ICRNL
; /* Don't translate CRs into LFs */
423 raw_mode
.c_oflag
&= ~OPOST
; /* Don't postprocess output */
424 raw_mode
.c_cc
[VTIME
] = 0; /* IE: wait forever, and return as */
425 raw_mode
.c_cc
[VMIN
] = 1; /* soon as a character is available */
430 /* --------------------------------------------------------------------------------------------- */
432 * Wait until the subshell dies or stops. If it stops, make it resume.
433 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
439 sigset_t sigchld_mask
, old_mask
;
441 sigemptyset (&sigchld_mask
);
442 sigaddset (&sigchld_mask
, SIGCHLD
);
443 sigprocmask (SIG_BLOCK
, &sigchld_mask
, &old_mask
);
446 * SIGCHLD should not be blocked, but we unblock it just in case.
447 * This is known to be useful for cygwin 1.3.12 and older.
449 sigdelset (&old_mask
, SIGCHLD
);
451 /* Wait until the subshell has stopped */
452 while (subshell_alive
&& !subshell_stopped
)
453 sigsuspend (&old_mask
);
455 if (subshell_state
!= ACTIVE
)
457 /* Discard all remaining data from stdin to the subshell */
458 tcflush (subshell_pty_slave
, TCIFLUSH
);
461 subshell_stopped
= FALSE
;
462 kill (subshell_pid
, SIGCONT
);
464 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
465 /* We can't do any better without modifying the shell(s) */
468 /* --------------------------------------------------------------------------------------------- */
469 /** Feed the subshell our keyboard input until it says it's finished */
472 feed_subshell (int how
, int fail_on_error
)
474 fd_set read_set
; /* For `select' */
476 int bytes
; /* For the return value from `read' */
477 int i
; /* Loop counter */
479 struct timeval wtime
; /* Maximum time we wait for the subshell */
480 struct timeval
*wptr
;
482 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
485 wptr
= fail_on_error
? &wtime
: NULL
;
492 /* Prepare the file-descriptor set and call `select' */
495 FD_SET (mc_global
.tty
.subshell_pty
, &read_set
);
496 FD_SET (subshell_pipe
[READ
], &read_set
);
497 maxfdp
= max (mc_global
.tty
.subshell_pty
, subshell_pipe
[READ
]);
500 FD_SET (STDIN_FILENO
, &read_set
);
501 maxfdp
= max (maxfdp
, STDIN_FILENO
);
504 if (select (maxfdp
+ 1, &read_set
, NULL
, NULL
, wptr
) == -1)
507 /* Despite using SA_RESTART, we still have to check for this */
509 continue; /* try all over again */
510 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
511 fprintf (stderr
, "select (FD_SETSIZE, &read_set...): %s\r\n",
512 unix_error_string (errno
));
516 if (FD_ISSET (mc_global
.tty
.subshell_pty
, &read_set
))
517 /* Read from the subshell, write to stdout */
519 /* This loop improves performance by reducing context switches
520 by a factor of 20 or so... unfortunately, it also hangs MC
521 randomly, because of an apparent Linux bug. Investigate. */
522 /* for (i=0; i<5; ++i) * FIXME -- experimental */
524 bytes
= read (mc_global
.tty
.subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
526 /* The subshell has died */
527 if (bytes
== -1 && errno
== EIO
&& !subshell_alive
)
532 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
533 fprintf (stderr
, "read (subshell_pty...): %s\r\n", unix_error_string (errno
));
538 write_all (STDOUT_FILENO
, pty_buffer
, bytes
);
541 else if (FD_ISSET (subshell_pipe
[READ
], &read_set
))
542 /* Read the subshell's CWD and capture its prompt */
544 bytes
= read (subshell_pipe
[READ
], subshell_cwd
, MC_MAXPATHLEN
+ 1);
547 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
548 fprintf (stderr
, "read (subshell_pipe[READ]...): %s\r\n",
549 unix_error_string (errno
));
553 subshell_cwd
[bytes
- 1] = 0; /* Squash the final '\n' */
557 subshell_ready
= TRUE
;
558 if (subshell_state
== RUNNING_COMMAND
)
560 subshell_state
= INACTIVE
;
565 else if (FD_ISSET (STDIN_FILENO
, &read_set
))
566 /* Read from stdin, write to the subshell */
568 bytes
= read (STDIN_FILENO
, pty_buffer
, sizeof (pty_buffer
));
571 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
573 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno
));
577 for (i
= 0; i
< bytes
; ++i
)
578 if (pty_buffer
[i
] == subshell_switch_key
)
580 write_all (mc_global
.tty
.subshell_pty
, pty_buffer
, i
);
582 subshell_state
= INACTIVE
;
586 write_all (mc_global
.tty
.subshell_pty
, pty_buffer
, bytes
);
588 if (pty_buffer
[bytes
- 1] == '\n' || pty_buffer
[bytes
- 1] == '\r')
589 subshell_ready
= FALSE
;
596 /* --------------------------------------------------------------------------------------------- */
597 /* pty opening functions */
601 /* System V version of pty_open_master */
604 pty_open_master (char *pty_name
)
609 #ifdef HAVE_POSIX_OPENPT
610 pty_master
= posix_openpt (O_RDWR
);
612 /* getpt () is a GNU extension (glibc 2.1.x) */
613 pty_master
= getpt ();
615 strcpy (pty_name
, "/dev/ptc");
616 pty_master
= open (pty_name
, O_RDWR
);
618 strcpy (pty_name
, "/dev/ptmx");
619 pty_master
= open (pty_name
, O_RDWR
);
622 if (pty_master
== -1)
625 if (grantpt (pty_master
) == -1 /* Grant access to slave */
626 || unlockpt (pty_master
) == -1 /* Clear slave's lock flag */
627 || !(slave_name
= ptsname (pty_master
))) /* Get slave's name */
632 strcpy (pty_name
, slave_name
);
636 /* --------------------------------------------------------------------------------------------- */
637 /** System V version of pty_open_slave */
640 pty_open_slave (const char *pty_name
)
642 int pty_slave
= open (pty_name
, O_RDWR
);
646 fprintf (stderr
, "open (%s, O_RDWR): %s\r\n", pty_name
, unix_error_string (errno
));
649 #if !defined(__osf__) && !defined(__linux__)
650 #if defined (I_FIND) && defined (I_PUSH)
651 if (!ioctl (pty_slave
, I_FIND
, "ptem"))
652 if (ioctl (pty_slave
, I_PUSH
, "ptem") == -1)
654 fprintf (stderr
, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
655 pty_slave
, unix_error_string (errno
));
660 if (!ioctl (pty_slave
, I_FIND
, "ldterm"))
661 if (ioctl (pty_slave
, I_PUSH
, "ldterm") == -1)
664 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
665 pty_slave
, unix_error_string (errno
));
669 #if !defined(sgi) && !defined(__sgi)
670 if (!ioctl (pty_slave
, I_FIND
, "ttcompat"))
671 if (ioctl (pty_slave
, I_PUSH
, "ttcompat") == -1)
674 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
675 pty_slave
, unix_error_string (errno
));
679 #endif /* sgi || __sgi */
680 #endif /* I_FIND && I_PUSH */
681 #endif /* __osf__ || __linux__ */
683 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
687 #else /* !HAVE_GRANTPT */
689 /* --------------------------------------------------------------------------------------------- */
690 /** BSD version of pty_open_master */
692 pty_open_master (char *pty_name
)
695 const char *ptr1
, *ptr2
;
697 strcpy (pty_name
, "/dev/ptyXX");
698 for (ptr1
= "pqrstuvwxyzPQRST"; *ptr1
; ++ptr1
)
701 for (ptr2
= "0123456789abcdef"; *ptr2
!= '\0'; ++ptr2
)
705 /* Try to open master */
706 pty_master
= open (pty_name
, O_RDWR
);
707 if (pty_master
== -1)
709 if (errno
== ENOENT
) /* Different from EIO */
710 return -1; /* Out of pty devices */
711 continue; /* Try next pty device */
713 pty_name
[5] = 't'; /* Change "pty" to "tty" */
714 if (access (pty_name
, 6) != 0)
723 return -1; /* Ran out of pty devices */
726 /* --------------------------------------------------------------------------------------------- */
727 /** BSD version of pty_open_slave */
730 pty_open_slave (const char *pty_name
)
733 struct group
*group_info
= getgrnam ("tty");
735 if (group_info
!= NULL
)
737 /* The following two calls will only succeed if we are root */
738 /* [Commented out while permissions problem is investigated] */
739 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
740 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
742 pty_slave
= open (pty_name
, O_RDWR
);
744 fprintf (stderr
, "open (pty_name, O_RDWR): %s\r\n", pty_name
);
745 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
748 #endif /* !HAVE_GRANTPT */
750 /* --------------------------------------------------------------------------------------------- */
751 /*** public functions ****************************************************************************/
752 /* --------------------------------------------------------------------------------------------- */
754 /* --------------------------------------------------------------------------------------------- */
756 * Fork the subshell, and set up many, many things.
758 * Possibly modifies the global variables:
759 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
760 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
761 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
767 /* This must be remembered across calls to init_subshell() */
768 static char pty_name
[BUF_SMALL
];
769 char precmd
[BUF_SMALL
];
771 switch (check_sid ())
774 mc_global
.tty
.use_subshell
= FALSE
;
777 mc_global
.tty
.use_subshell
= FALSE
;
778 mc_global
.midnight_shutdown
= TRUE
;
782 /* Take the current (hopefully pristine) tty mode and make */
783 /* a raw mode based on it now, before we do anything else with it */
786 if (mc_global
.tty
.subshell_pty
== 0)
787 { /* First time through */
788 /* Find out what type of shell we have */
790 if (strstr (shell
, "/zsh") || getenv ("ZSH_VERSION"))
792 else if (strstr (shell
, "/tcsh"))
793 subshell_type
= TCSH
;
794 else if (strstr (shell
, "/csh"))
795 subshell_type
= TCSH
;
796 else if (strstr (shell
, "/bash") || getenv ("BASH"))
797 subshell_type
= BASH
;
798 else if (strstr (shell
, "/fish"))
799 subshell_type
= FISH
;
802 mc_global
.tty
.use_subshell
= FALSE
;
806 /* Open a pty for talking to the subshell */
808 /* FIXME: We may need to open a fresh pty each time on SVR4 */
810 mc_global
.tty
.subshell_pty
= pty_open_master (pty_name
);
811 if (mc_global
.tty
.subshell_pty
== -1)
813 fprintf (stderr
, "Cannot open master side of pty: %s\r\n", unix_error_string (errno
));
814 mc_global
.tty
.use_subshell
= FALSE
;
817 subshell_pty_slave
= pty_open_slave (pty_name
);
818 if (subshell_pty_slave
== -1)
820 fprintf (stderr
, "Cannot open slave side of pty %s: %s\r\n",
821 pty_name
, unix_error_string (errno
));
822 mc_global
.tty
.use_subshell
= FALSE
;
826 /* Create a pipe for receiving the subshell's CWD */
828 if (subshell_type
== TCSH
)
830 g_snprintf (tcsh_fifo
, sizeof (tcsh_fifo
), "%s/mc.pipe.%d",
831 mc_tmpdir (), (int) getpid ());
832 if (mkfifo (tcsh_fifo
, 0600) == -1)
834 fprintf (stderr
, "mkfifo(%s) failed: %s\r\n", tcsh_fifo
, unix_error_string (errno
));
835 mc_global
.tty
.use_subshell
= FALSE
;
839 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
841 if ((subshell_pipe
[READ
] = open (tcsh_fifo
, O_RDWR
)) == -1
842 || (subshell_pipe
[WRITE
] = open (tcsh_fifo
, O_RDWR
)) == -1)
844 fprintf (stderr
, _("Cannot open named pipe %s\n"), tcsh_fifo
);
845 perror (__FILE__
": open");
846 mc_global
.tty
.use_subshell
= FALSE
;
850 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe
))
852 perror (__FILE__
": couldn't create pipe");
853 mc_global
.tty
.use_subshell
= FALSE
;
858 /* Fork the subshell */
860 subshell_alive
= TRUE
;
861 subshell_stopped
= FALSE
;
862 subshell_pid
= fork ();
864 if (subshell_pid
== -1)
866 fprintf (stderr
, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno
));
867 /* We exit here because, if the process table is full, the */
868 /* other method of running user commands won't work either */
872 if (subshell_pid
== 0)
874 /* We are in the child process */
875 init_subshell_child (pty_name
);
878 /* Set up `precmd' or equivalent for reading the subshell's CWD */
880 switch (subshell_type
)
883 g_snprintf (precmd
, sizeof (precmd
),
884 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe
[WRITE
]);
888 g_snprintf (precmd
, sizeof (precmd
),
889 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe
[WRITE
]);
893 g_snprintf (precmd
, sizeof (precmd
),
894 "set echo_style=both;"
895 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo
);
898 g_snprintf (precmd
, sizeof (precmd
),
899 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
900 subshell_pipe
[WRITE
]);
904 write_all (mc_global
.tty
.subshell_pty
, precmd
, strlen (precmd
));
906 /* Wait until the subshell has started up and processed the command */
908 subshell_state
= RUNNING_COMMAND
;
909 tty_enable_interrupt_key ();
910 if (!feed_subshell (QUIETLY
, TRUE
))
912 mc_global
.tty
.use_subshell
= FALSE
;
914 tty_disable_interrupt_key ();
916 mc_global
.tty
.use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
919 /* --------------------------------------------------------------------------------------------- */
922 invoke_subshell (const char *command
, int how
, vfs_path_t
** new_dir_vpath
)
926 /* Make the MC terminal transparent */
927 tcsetattr (STDOUT_FILENO
, TCSANOW
, &raw_mode
);
929 /* Make the subshell change to MC's working directory */
930 if (new_dir_vpath
!= NULL
)
931 do_subshell_chdir (current_panel
->cwd_vpath
, TRUE
, TRUE
);
933 if (command
== NULL
) /* The user has done "C-o" from MC */
935 if (subshell_state
== INACTIVE
)
937 subshell_state
= ACTIVE
;
938 /* FIXME: possibly take out this hack; the user can
939 re-play it by hitting C-hyphen a few times! */
941 write_all (mc_global
.tty
.subshell_pty
, " \b", 2); /* Hack to make prompt reappear */
944 else /* MC has passed us a user command */
947 write_all (mc_global
.tty
.subshell_pty
, " ", 1);
948 /* FIXME: if command is long (>8KB ?) we go comma */
949 write_all (mc_global
.tty
.subshell_pty
, command
, strlen (command
));
950 write_all (mc_global
.tty
.subshell_pty
, "\n", 1);
951 subshell_state
= RUNNING_COMMAND
;
952 subshell_ready
= FALSE
;
955 feed_subshell (how
, FALSE
);
960 cwd_str
= vfs_path_to_str (current_panel
->cwd_vpath
);
961 pcwd
= vfs_translate_path_n (cwd_str
);
965 if (new_dir_vpath
!= NULL
&& subshell_alive
&& strcmp (subshell_cwd
, pcwd
))
966 *new_dir_vpath
= vfs_path_from_str (subshell_cwd
); /* Make MC change to the subshell's CWD */
969 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
970 while (!subshell_alive
&& quit
== 0 && mc_global
.tty
.use_subshell
)
979 /* --------------------------------------------------------------------------------------------- */
982 read_subshell_prompt (void)
984 static int prompt_size
= INITIAL_PROMPT_SIZE
;
985 int bytes
= 0, i
, rc
= 0;
986 struct timeval timeleft
= { 0, 0 };
990 FD_SET (mc_global
.tty
.subshell_pty
, &tmp
);
992 if (subshell_prompt
== NULL
)
993 { /* First time through */
994 subshell_prompt
= g_malloc (prompt_size
);
995 *subshell_prompt
= '\0';
999 while (subshell_alive
1000 && (rc
= select (mc_global
.tty
.subshell_pty
+ 1, &tmp
, NULL
, NULL
, &timeleft
)))
1002 /* Check for `select' errors */
1009 fprintf (stderr
, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno
));
1010 exit (EXIT_FAILURE
);
1014 bytes
= read (mc_global
.tty
.subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
1016 /* Extract the prompt from the shell output */
1018 for (i
= 0; i
< bytes
; ++i
)
1019 if (pty_buffer
[i
] == '\n' || pty_buffer
[i
] == '\r')
1028 subshell_prompt
[prompt_pos
++] = pty_buffer
[i
];
1029 if (prompt_pos
== prompt_size
)
1030 subshell_prompt
= g_realloc (subshell_prompt
, prompt_size
*= 2);
1033 subshell_prompt
[prompt_pos
] = '\0';
1035 if (rc
== 0 && bytes
== 0)
1040 /* --------------------------------------------------------------------------------------------- */
1043 do_update_prompt (void)
1045 if (update_subshell_prompt
)
1047 printf ("\r\n%s", subshell_prompt
);
1049 update_subshell_prompt
= FALSE
;
1053 /* --------------------------------------------------------------------------------------------- */
1056 exit_subshell (void)
1058 int subshell_quit
= TRUE
;
1060 if (subshell_state
!= INACTIVE
&& subshell_alive
)
1062 !query_dialog (_("Warning"),
1063 _("The shell is still active. Quit anyway?"),
1064 D_NORMAL
, 2, _("&Yes"), _("&No"));
1068 if (subshell_type
== TCSH
)
1070 if (unlink (tcsh_fifo
) == -1)
1071 fprintf (stderr
, "Cannot remove named pipe %s: %s\r\n",
1072 tcsh_fifo
, unix_error_string (errno
));
1075 g_free (subshell_prompt
);
1076 subshell_prompt
= NULL
;
1077 pty_buffer
[0] = '\0';
1080 return subshell_quit
;
1083 /* --------------------------------------------------------------------------------------------- */
1085 * Carefully quote directory name to allow entering any directory safely,
1086 * no matter what weird characters it may contain in its name.
1087 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1088 * executing any commands in the shell. Escape all control characters.
1089 * Use following technique:
1091 * printf(1) with format string containing a single conversion specifier,
1092 * "b", and an argument which contains a copy of the string passed to
1093 * subshell_name_quote() with all characters, except digits and letters,
1094 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1095 * numeric value of the character converted to octal number.
1097 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1102 subshell_name_quote (const char *s
)
1106 const char *quote_cmd_start
, *quote_cmd_end
;
1109 if (subshell_type
== FISH
)
1111 quote_cmd_start
= "(printf \"%b\" '";
1112 quote_cmd_end
= "')";
1116 quote_cmd_start
= "\"`printf \"%b\" '";
1117 quote_cmd_end
= "'`\"";
1120 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1121 d
= ret
= g_try_malloc (1 + (5 * strlen (s
)) + (strlen (quote_cmd_start
))
1122 + (strlen (quote_cmd_end
)));
1126 /* Prevent interpreting leading `-' as a switch for `cd' */
1133 /* Copy the beginning of the command to the buffer */
1134 strcpy (d
, quote_cmd_start
);
1135 d
+= strlen (quote_cmd_start
);
1138 * Print every character except digits and letters as a backslash-escape
1139 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1140 * character converted to octal number.
1143 for (; su
[0] != '\0';)
1145 n
= str_cget_next_char_safe (su
);
1146 if (str_isalnum (su
))
1148 memcpy (d
, su
, n
- su
);
1153 for (c
= 0; c
< n
- su
; c
++)
1155 sprintf (d
, "\\0%03o", (unsigned char) su
[c
]);
1162 strcpy (d
, quote_cmd_end
);
1168 /* --------------------------------------------------------------------------------------------- */
1170 /** If it actually changed the directory it returns true */
1172 do_subshell_chdir (const vfs_path_t
* vpath
, gboolean update_prompt
, gboolean reset_prompt
)
1178 pcwd
= vfs_path_to_str_flags (current_panel
->cwd_vpath
, 0, VPF_RECODE
);
1180 if (!(subshell_state
== INACTIVE
&& strcmp (subshell_cwd
, pcwd
) != 0))
1182 /* We have to repaint the subshell prompt if we read it from
1183 * the main program. Please note that in the code after this
1184 * if, the cd command that is sent will make the subshell
1185 * repaint the prompt, so we don't have to paint it. */
1187 do_update_prompt ();
1192 /* The initial space keeps this out of the command history (in bash
1193 because we set "HISTCONTROL=ignorespace") */
1194 write_all (mc_global
.tty
.subshell_pty
, " cd ", 4);
1196 directory
= vfs_path_to_str (vpath
);
1197 if (directory
!= '\0')
1201 translate
= vfs_translate_path_n (directory
);
1202 if (translate
!= NULL
)
1204 temp
= subshell_name_quote (translate
);
1207 write_all (mc_global
.tty
.subshell_pty
, temp
, strlen (temp
));
1212 /* Should not happen unless the directory name is so long
1213 that we don't have memory to quote it. */
1214 write_all (mc_global
.tty
.subshell_pty
, ".", 1);
1220 write_all (mc_global
.tty
.subshell_pty
, ".", 1);
1225 write_all (mc_global
.tty
.subshell_pty
, "/", 1);
1228 write_all (mc_global
.tty
.subshell_pty
, "\n", 1);
1230 subshell_state
= RUNNING_COMMAND
;
1231 feed_subshell (QUIETLY
, FALSE
);
1235 int bPathNotEq
= strcmp (subshell_cwd
, pcwd
);
1237 if (bPathNotEq
&& subshell_type
== TCSH
)
1239 char rp_subshell_cwd
[PATH_MAX
];
1240 char rp_current_panel_cwd
[PATH_MAX
];
1242 char *p_subshell_cwd
= mc_realpath (subshell_cwd
, rp_subshell_cwd
);
1243 char *p_current_panel_cwd
= mc_realpath (pcwd
, rp_current_panel_cwd
);
1245 if (p_subshell_cwd
== NULL
)
1246 p_subshell_cwd
= subshell_cwd
;
1247 if (p_current_panel_cwd
== NULL
)
1248 p_current_panel_cwd
= pcwd
;
1249 bPathNotEq
= strcmp (p_subshell_cwd
, p_current_panel_cwd
);
1252 if (bPathNotEq
&& strcmp (pcwd
, ".") != 0)
1256 cwd
= vfs_path_to_str_flags (current_panel
->cwd_vpath
, 0, VPF_STRIP_PASSWORD
);
1257 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd
);
1264 update_subshell_prompt
= FALSE
;
1267 /* Make sure that MC never stores the CWD in a silly format */
1268 /* like /usr////lib/../bin, or the strcmp() above will fail */
1271 /* --------------------------------------------------------------------------------------------- */
1274 subshell_get_console_attributes (void)
1276 /* Get our current terminal modes */
1278 if (tcgetattr (STDOUT_FILENO
, &shell_mode
))
1280 fprintf (stderr
, "Cannot get terminal settings: %s\r\n", unix_error_string (errno
));
1281 mc_global
.tty
.use_subshell
= FALSE
;
1285 /* --------------------------------------------------------------------------------------------- */
1287 * Figure out whether the subshell has stopped, exited or been killed
1288 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1291 sigchld_handler (int sig
)
1298 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
1300 if (pid
== subshell_pid
)
1302 /* Figure out what has happened to the subshell */
1304 if (WIFSTOPPED (status
))
1306 if (WSTOPSIG (status
) == SIGSTOP
)
1308 /* The subshell has received a SIGSTOP signal */
1309 subshell_stopped
= TRUE
;
1313 /* The user has suspended the subshell. Revive it */
1314 kill (subshell_pid
, SIGCONT
);
1319 /* The subshell has either exited normally or been killed */
1320 subshell_alive
= FALSE
;
1321 delete_select_channel (mc_global
.tty
.subshell_pty
);
1322 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
1323 quit
|= SUBSHELL_EXIT
; /* Exited normally */
1327 pid
= waitpid (cons_saver_pid
, &status
, WUNTRACED
| WNOHANG
);
1329 if (pid
== cons_saver_pid
)
1332 if (WIFSTOPPED (status
))
1333 /* Someone has stopped cons.saver - restart it */
1334 kill (pid
, SIGCONT
);
1337 /* cons.saver has died - disable confole saving */
1338 handle_console (CONSOLE_DONE
);
1339 mc_global
.tty
.console_flag
= '\0';
1343 #endif /* __linux__ */
1345 /* If we got here, some other child exited; ignore it */
1348 /* --------------------------------------------------------------------------------------------- */
1350 #endif /* HAVE_SUBSHELL_SUPPORT */