2 Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
5 2005, 2006, 2007, 2011, 2013
6 The Free Software Foundation, Inc.
9 Slava Zanko <slavazanko@gmail.com>, 2013
11 This file is part of the Midnight Commander.
13 The Midnight Commander is free software: you can redistribute it
14 and/or modify it under the terms of the GNU General Public License as
15 published by the Free Software Foundation, either version 3 of the License,
16 or (at your option) any later version.
18 The Midnight Commander is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program. If not, see <http://www.gnu.org/licenses/>.
28 * \brief Source: concurrent shell support
44 #include <sys/types.h>
46 #ifdef HAVE_SYS_IOCTL_H
47 #include <sys/ioctl.h>
53 #include <stropts.h> /* For I_PUSH */
54 #endif /* HAVE_STROPTS_H */
56 #include "lib/global.h"
58 #include "lib/tty/tty.h" /* LINES */
59 #include "lib/tty/key.h" /* XCTRL */
60 #include "lib/vfs/vfs.h"
61 #include "lib/strutil.h"
62 #include "lib/mcconfig.h"
64 #include "lib/widget.h"
66 #include "filemanager/midnight.h" /* current_panel */
68 #include "consaver/cons.saver.h" /* handle_console() */
72 /*** global variables ****************************************************************************/
74 /* State of the subshell:
75 * INACTIVE: the default state; awaiting a command
76 * ACTIVE: remain in the shell until the user hits 'subshell_switch_key'
77 * RUNNING_COMMAND: return to MC when the current command finishes */
78 enum subshell_state_enum subshell_state
;
80 /* Holds the latest prompt captured from the subshell */
81 GString
*subshell_prompt
= NULL
;
83 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
84 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
85 gboolean update_subshell_prompt
= FALSE
;
87 /*** file scope macro definitions ****************************************************************/
90 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
94 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
98 #define STDIN_FILENO 0
101 #ifndef STDOUT_FILENO
102 #define STDOUT_FILENO 1
105 #ifndef STDERR_FILENO
106 #define STDERR_FILENO 2
109 /* Initial length of the buffer for the subshell's prompt */
110 #define INITIAL_PROMPT_SIZE 10
112 /* Used by the child process to indicate failure to start the subshell */
113 #define FORK_FAILURE 69 /* Arbitrary */
115 /* Length of the buffer for all I/O with the subshell */
116 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
118 /*** file scope type declarations ****************************************************************/
127 /* Subshell type (gleaned from the SHELL environment variable, if available) */
136 /*** file scope variables ************************************************************************/
138 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
139 static char tcsh_fifo
[128];
141 static int subshell_pty_slave
= -1;
143 /* The key for switching back to MC from the subshell */
145 static const char subshell_switch_key
= XCTRL ('o') & 255;
148 /* For reading/writing on the subshell's pty */
149 static char pty_buffer
[PTY_BUFFER_SIZE
] = "\0";
151 /* To pass CWD info from the subshell to MC */
152 static int subshell_pipe
[2];
154 /* The subshell's process ID */
155 static pid_t subshell_pid
= 1;
157 /* One extra char for final '\n' */
158 static char subshell_cwd
[MC_MAXPATHLEN
+ 1];
160 /* Flag to indicate whether the subshell is ready for next command */
161 static int subshell_ready
;
163 /* The following two flags can be changed by the SIGCHLD handler. This is */
164 /* OK, because the 'int' type is updated atomically on all known machines */
165 static volatile int subshell_alive
, subshell_stopped
;
167 /* We store the terminal's initial mode here so that we can configure
168 the pty similarly, and also so we can restore the real terminal to
169 sanity if we have to exit abruptly */
170 static struct termios shell_mode
;
172 /* This is a transparent mode for the terminal where MC is running on */
173 /* It is used when the shell is active, so that the control signals */
174 /* are delivered to the shell pty */
175 static struct termios raw_mode
;
177 /* This counter indicates how many characters of prompt we have read */
178 /* FIXME: try to figure out why this had to become global */
179 static int prompt_pos
;
182 /*** file scope functions ************************************************************************/
183 /* --------------------------------------------------------------------------------------------- */
185 * Write all data, even if the write() call is interrupted.
189 write_all (int fd
, const void *buf
, size_t count
)
195 ret
= write (fd
, (const unsigned char *) buf
+ written
, count
);
200 if (mc_global
.tty
.winch_flag
!= 0)
201 tty_change_screen_size ();
206 return written
> 0 ? written
: ret
;
214 /* --------------------------------------------------------------------------------------------- */
216 * Prepare child process to running the shell and run it.
218 * Modifies the global variables (in the child process only):
225 init_subshell_child (const char *pty_name
)
227 char *init_file
= NULL
;
231 setsid (); /* Get a fresh terminal session */
233 /* Make sure that it has become our controlling terminal */
235 /* Redundant on Linux and probably most systems, but just in case: */
238 ioctl (subshell_pty_slave
, TIOCSCTTY
, 0);
241 /* Configure its terminal modes and window size */
243 /* Set up the pty with the same termios flags as our own tty */
244 if (tcsetattr (subshell_pty_slave
, TCSANOW
, &shell_mode
))
246 fprintf (stderr
, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno
));
247 my_exit (FORK_FAILURE
);
250 /* Set the pty's size (80x25 by default on Linux) according to the */
251 /* size of the real terminal as calculated by ncurses, if possible */
252 tty_resize (subshell_pty_slave
);
254 /* Set up the subshell's environment and init file name */
256 /* It simplifies things to change to our home directory here, */
257 /* and the user's startup file may do a 'cd' command anyway */
260 ret
= chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
264 /* Set MC_SID to prevent running one mc from another */
268 char sid_str
[BUF_SMALL
];
269 g_snprintf (sid_str
, sizeof (sid_str
), "MC_SID=%ld", (long) mc_sid
);
270 putenv (g_strdup (sid_str
));
273 switch (subshell_type
)
276 init_file
= mc_config_get_full_path ("bashrc");
278 if (access (init_file
, R_OK
) == -1)
281 init_file
= g_strdup (".bashrc");
284 /* Make MC's special commands not show up in bash's history */
285 putenv ((char *) "HISTCONTROL=ignorespace");
287 /* Allow alternative readline settings for MC */
289 char *input_file
= mc_config_get_full_path ("inputrc");
290 if (access (input_file
, R_OK
) == 0)
292 char *putenv_str
= g_strconcat ("INPUTRC=", input_file
, NULL
);
301 /* TODO: Find a way to pass initfile to TCSH and ZSH */
308 fprintf (stderr
, __FILE__
": unimplemented subshell type %d\r\n", subshell_type
);
309 my_exit (FORK_FAILURE
);
312 /* Attach all our standard file descriptors to the pty */
314 /* This is done just before the fork, because stderr must still */
315 /* be connected to the real tty during the above error messages; */
316 /* otherwise the user will never see them. */
318 dup2 (subshell_pty_slave
, STDIN_FILENO
);
319 dup2 (subshell_pty_slave
, STDOUT_FILENO
);
320 dup2 (subshell_pty_slave
, STDERR_FILENO
);
322 close (subshell_pipe
[READ
]);
323 close (subshell_pty_slave
); /* These may be FD_CLOEXEC, but just in case... */
324 /* Close master side of pty. This is important; apart from */
325 /* freeing up the descriptor for use in the subshell, it also */
326 /* means that when MC exits, the subshell will get a SIGHUP and */
327 /* exit too, because there will be no more descriptors pointing */
328 /* at the master side of the pty and so it will disappear. */
329 close (mc_global
.tty
.subshell_pty
);
331 /* Execute the subshell at last */
333 switch (subshell_type
)
336 execl (mc_global
.tty
.shell
, "bash", "-rcfile", init_file
, (char *) NULL
);
340 execl (mc_global
.tty
.shell
, "tcsh", (char *) NULL
);
344 /* Use -g to exclude cmds beginning with space from history
345 * and -Z to use the line editor on non-interactive term */
346 execl (mc_global
.tty
.shell
, "zsh", "-Z", "-g", (char *) NULL
);
351 execl (mc_global
.tty
.shell
, "fish", (char *) NULL
);
355 /* If we get this far, everything failed miserably */
357 my_exit (FORK_FAILURE
);
361 /* --------------------------------------------------------------------------------------------- */
363 * Check MC_SID to prevent running one mc from another.
365 * 0 if no parent mc in our session was found,
366 * 1 if parent mc was found and the user wants to continue,
367 * 2 if parent mc was found and the user wants to quit mc.
373 pid_t my_sid
, old_sid
;
377 sid_str
= getenv ("MC_SID");
381 old_sid
= (pid_t
) strtol (sid_str
, NULL
, 0);
389 /* The parent mc is in a different session, it's OK */
390 if (old_sid
!= my_sid
)
393 r
= query_dialog (_("Warning"),
394 _("GNU Midnight Commander is already\n"
395 "running on this terminal.\n"
396 "Subshell support will be disabled."), D_ERROR
, 2, _("&OK"), _("&Quit"));
405 /* --------------------------------------------------------------------------------------------- */
410 static int initialized
= 0;
412 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
413 /* original settings. However, here we need to make this tty very raw, */
414 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
415 /* pty. So, instead of changing the code for execute(), pre_exec(), */
416 /* etc, we just set up the modes we need here, before each command. */
418 if (initialized
== 0) /* First time: initialise 'raw_mode' */
420 tcgetattr (STDOUT_FILENO
, &raw_mode
);
421 raw_mode
.c_lflag
&= ~ICANON
; /* Disable line-editing chars, etc. */
422 raw_mode
.c_lflag
&= ~ISIG
; /* Disable intr, quit & suspend chars */
423 raw_mode
.c_lflag
&= ~ECHO
; /* Disable input echoing */
424 raw_mode
.c_iflag
&= ~IXON
; /* Pass ^S/^Q to subshell undisturbed */
425 raw_mode
.c_iflag
&= ~ICRNL
; /* Don't translate CRs into LFs */
426 raw_mode
.c_oflag
&= ~OPOST
; /* Don't postprocess output */
427 raw_mode
.c_cc
[VTIME
] = 0; /* IE: wait forever, and return as */
428 raw_mode
.c_cc
[VMIN
] = 1; /* soon as a character is available */
433 /* --------------------------------------------------------------------------------------------- */
435 * Wait until the subshell dies or stops. If it stops, make it resume.
436 * Possibly modifies the globals 'subshell_alive' and 'subshell_stopped'
442 sigset_t sigchld_mask
, old_mask
;
444 sigemptyset (&sigchld_mask
);
445 sigaddset (&sigchld_mask
, SIGCHLD
);
446 sigprocmask (SIG_BLOCK
, &sigchld_mask
, &old_mask
);
449 * SIGCHLD should not be blocked, but we unblock it just in case.
450 * This is known to be useful for cygwin 1.3.12 and older.
452 sigdelset (&old_mask
, SIGCHLD
);
454 /* Wait until the subshell has stopped */
455 while (subshell_alive
&& !subshell_stopped
)
456 sigsuspend (&old_mask
);
458 if (subshell_state
!= ACTIVE
)
460 /* Discard all remaining data from stdin to the subshell */
461 tcflush (subshell_pty_slave
, TCIFLUSH
);
464 subshell_stopped
= FALSE
;
465 kill (subshell_pid
, SIGCONT
);
467 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
468 /* We can't do any better without modifying the shell(s) */
471 /* --------------------------------------------------------------------------------------------- */
472 /** Feed the subshell our keyboard input until it says it's finished */
475 feed_subshell (int how
, int fail_on_error
)
477 fd_set read_set
; /* For 'select' */
479 int bytes
; /* For the return value from 'read' */
480 int i
; /* Loop counter */
482 struct timeval wtime
; /* Maximum time we wait for the subshell */
483 struct timeval
*wptr
;
485 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
488 wptr
= fail_on_error
? &wtime
: NULL
;
495 /* Prepare the file-descriptor set and call 'select' */
498 FD_SET (mc_global
.tty
.subshell_pty
, &read_set
);
499 FD_SET (subshell_pipe
[READ
], &read_set
);
500 maxfdp
= max (mc_global
.tty
.subshell_pty
, subshell_pipe
[READ
]);
503 FD_SET (STDIN_FILENO
, &read_set
);
504 maxfdp
= max (maxfdp
, STDIN_FILENO
);
507 if (select (maxfdp
+ 1, &read_set
, NULL
, NULL
, wptr
) == -1)
509 /* Despite using SA_RESTART, we still have to check for this */
512 if (mc_global
.tty
.winch_flag
!= 0)
513 tty_change_screen_size ();
515 continue; /* try all over again */
517 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
518 fprintf (stderr
, "select (FD_SETSIZE, &read_set...): %s\r\n",
519 unix_error_string (errno
));
523 if (FD_ISSET (mc_global
.tty
.subshell_pty
, &read_set
))
524 /* Read from the subshell, write to stdout */
526 /* This loop improves performance by reducing context switches
527 by a factor of 20 or so... unfortunately, it also hangs MC
528 randomly, because of an apparent Linux bug. Investigate. */
529 /* for (i=0; i<5; ++i) * FIXME -- experimental */
531 bytes
= read (mc_global
.tty
.subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
533 /* The subshell has died */
534 if (bytes
== -1 && errno
== EIO
&& !subshell_alive
)
539 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
540 fprintf (stderr
, "read (subshell_pty...): %s\r\n", unix_error_string (errno
));
545 write_all (STDOUT_FILENO
, pty_buffer
, bytes
);
548 else if (FD_ISSET (subshell_pipe
[READ
], &read_set
))
549 /* Read the subshell's CWD and capture its prompt */
551 bytes
= read (subshell_pipe
[READ
], subshell_cwd
, MC_MAXPATHLEN
+ 1);
554 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
555 fprintf (stderr
, "read (subshell_pipe[READ]...): %s\r\n",
556 unix_error_string (errno
));
560 subshell_cwd
[bytes
- 1] = 0; /* Squash the final '\n' */
564 subshell_ready
= TRUE
;
565 if (subshell_state
== RUNNING_COMMAND
)
567 subshell_state
= INACTIVE
;
572 else if (FD_ISSET (STDIN_FILENO
, &read_set
))
573 /* Read from stdin, write to the subshell */
575 bytes
= read (STDIN_FILENO
, pty_buffer
, sizeof (pty_buffer
));
578 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
580 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno
));
584 for (i
= 0; i
< bytes
; ++i
)
585 if (pty_buffer
[i
] == subshell_switch_key
)
587 write_all (mc_global
.tty
.subshell_pty
, pty_buffer
, i
);
589 subshell_state
= INACTIVE
;
593 write_all (mc_global
.tty
.subshell_pty
, pty_buffer
, bytes
);
595 if (pty_buffer
[bytes
- 1] == '\n' || pty_buffer
[bytes
- 1] == '\r')
596 subshell_ready
= FALSE
;
603 /* --------------------------------------------------------------------------------------------- */
604 /* pty opening functions */
608 /* System V version of pty_open_master */
611 pty_open_master (char *pty_name
)
616 #ifdef HAVE_POSIX_OPENPT
617 pty_master
= posix_openpt (O_RDWR
);
619 /* getpt () is a GNU extension (glibc 2.1.x) */
620 pty_master
= getpt ();
622 strcpy (pty_name
, "/dev/ptc");
623 pty_master
= open (pty_name
, O_RDWR
);
625 strcpy (pty_name
, "/dev/ptmx");
626 pty_master
= open (pty_name
, O_RDWR
);
629 if (pty_master
== -1)
632 if (grantpt (pty_master
) == -1 /* Grant access to slave */
633 || unlockpt (pty_master
) == -1 /* Clear slave's lock flag */
634 || !(slave_name
= ptsname (pty_master
))) /* Get slave's name */
639 strcpy (pty_name
, slave_name
);
643 /* --------------------------------------------------------------------------------------------- */
644 /** System V version of pty_open_slave */
647 pty_open_slave (const char *pty_name
)
649 int pty_slave
= open (pty_name
, O_RDWR
);
653 fprintf (stderr
, "open (%s, O_RDWR): %s\r\n", pty_name
, unix_error_string (errno
));
656 #if !defined(__osf__) && !defined(__linux__)
657 #if defined (I_FIND) && defined (I_PUSH)
658 if (!ioctl (pty_slave
, I_FIND
, "ptem"))
659 if (ioctl (pty_slave
, I_PUSH
, "ptem") == -1)
661 fprintf (stderr
, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
662 pty_slave
, unix_error_string (errno
));
667 if (!ioctl (pty_slave
, I_FIND
, "ldterm"))
668 if (ioctl (pty_slave
, I_PUSH
, "ldterm") == -1)
671 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
672 pty_slave
, unix_error_string (errno
));
676 #if !defined(sgi) && !defined(__sgi)
677 if (!ioctl (pty_slave
, I_FIND
, "ttcompat"))
678 if (ioctl (pty_slave
, I_PUSH
, "ttcompat") == -1)
681 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
682 pty_slave
, unix_error_string (errno
));
686 #endif /* sgi || __sgi */
687 #endif /* I_FIND && I_PUSH */
688 #endif /* __osf__ || __linux__ */
690 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
694 #else /* !HAVE_GRANTPT */
696 /* --------------------------------------------------------------------------------------------- */
697 /** BSD version of pty_open_master */
699 pty_open_master (char *pty_name
)
702 const char *ptr1
, *ptr2
;
704 strcpy (pty_name
, "/dev/ptyXX");
705 for (ptr1
= "pqrstuvwxyzPQRST"; *ptr1
; ++ptr1
)
708 for (ptr2
= "0123456789abcdef"; *ptr2
!= '\0'; ++ptr2
)
712 /* Try to open master */
713 pty_master
= open (pty_name
, O_RDWR
);
714 if (pty_master
== -1)
716 if (errno
== ENOENT
) /* Different from EIO */
717 return -1; /* Out of pty devices */
718 continue; /* Try next pty device */
720 pty_name
[5] = 't'; /* Change "pty" to "tty" */
721 if (access (pty_name
, 6) != 0)
730 return -1; /* Ran out of pty devices */
733 /* --------------------------------------------------------------------------------------------- */
734 /** BSD version of pty_open_slave */
737 pty_open_slave (const char *pty_name
)
740 struct group
*group_info
= getgrnam ("tty");
742 if (group_info
!= NULL
)
744 /* The following two calls will only succeed if we are root */
745 /* [Commented out while permissions problem is investigated] */
746 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
747 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
749 pty_slave
= open (pty_name
, O_RDWR
);
751 fprintf (stderr
, "open (pty_name, O_RDWR): %s\r\n", pty_name
);
752 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
755 #endif /* !HAVE_GRANTPT */
757 /* --------------------------------------------------------------------------------------------- */
758 /*** public functions ****************************************************************************/
759 /* --------------------------------------------------------------------------------------------- */
761 /* --------------------------------------------------------------------------------------------- */
763 * Fork the subshell, and set up many, many things.
765 * Possibly modifies the global variables:
766 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
767 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
768 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
774 /* This must be remembered across calls to init_subshell() */
775 static char pty_name
[BUF_SMALL
];
776 char precmd
[BUF_SMALL
];
778 switch (check_sid ())
781 mc_global
.tty
.use_subshell
= FALSE
;
784 mc_global
.tty
.use_subshell
= FALSE
;
785 mc_global
.midnight_shutdown
= TRUE
;
789 /* Take the current (hopefully pristine) tty mode and make */
790 /* a raw mode based on it now, before we do anything else with it */
793 if (mc_global
.tty
.subshell_pty
== 0)
794 { /* First time through */
795 /* Find out what type of shell we have */
797 if (strstr (mc_global
.tty
.shell
, "/zsh") || getenv ("ZSH_VERSION"))
799 else if (strstr (mc_global
.tty
.shell
, "/tcsh"))
800 subshell_type
= TCSH
;
801 else if (strstr (mc_global
.tty
.shell
, "/csh"))
802 subshell_type
= TCSH
;
803 else if (strstr (mc_global
.tty
.shell
, "/bash") || getenv ("BASH"))
804 subshell_type
= BASH
;
805 else if (strstr (mc_global
.tty
.shell
, "/fish"))
806 subshell_type
= FISH
;
809 mc_global
.tty
.use_subshell
= FALSE
;
813 /* Open a pty for talking to the subshell */
815 /* FIXME: We may need to open a fresh pty each time on SVR4 */
817 mc_global
.tty
.subshell_pty
= pty_open_master (pty_name
);
818 if (mc_global
.tty
.subshell_pty
== -1)
820 fprintf (stderr
, "Cannot open master side of pty: %s\r\n", unix_error_string (errno
));
821 mc_global
.tty
.use_subshell
= FALSE
;
824 subshell_pty_slave
= pty_open_slave (pty_name
);
825 if (subshell_pty_slave
== -1)
827 fprintf (stderr
, "Cannot open slave side of pty %s: %s\r\n",
828 pty_name
, unix_error_string (errno
));
829 mc_global
.tty
.use_subshell
= FALSE
;
833 /* Create a pipe for receiving the subshell's CWD */
835 if (subshell_type
== TCSH
)
837 g_snprintf (tcsh_fifo
, sizeof (tcsh_fifo
), "%s/mc.pipe.%d",
838 mc_tmpdir (), (int) getpid ());
839 if (mkfifo (tcsh_fifo
, 0600) == -1)
841 fprintf (stderr
, "mkfifo(%s) failed: %s\r\n", tcsh_fifo
, unix_error_string (errno
));
842 mc_global
.tty
.use_subshell
= FALSE
;
846 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
848 if ((subshell_pipe
[READ
] = open (tcsh_fifo
, O_RDWR
)) == -1
849 || (subshell_pipe
[WRITE
] = open (tcsh_fifo
, O_RDWR
)) == -1)
851 fprintf (stderr
, _("Cannot open named pipe %s\n"), tcsh_fifo
);
852 perror (__FILE__
": open");
853 mc_global
.tty
.use_subshell
= FALSE
;
857 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe
))
859 perror (__FILE__
": couldn't create pipe");
860 mc_global
.tty
.use_subshell
= FALSE
;
865 /* Fork the subshell */
867 subshell_alive
= TRUE
;
868 subshell_stopped
= FALSE
;
869 subshell_pid
= fork ();
871 if (subshell_pid
== -1)
873 fprintf (stderr
, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno
));
874 /* We exit here because, if the process table is full, the */
875 /* other method of running user commands won't work either */
879 if (subshell_pid
== 0)
881 /* We are in the child process */
882 init_subshell_child (pty_name
);
885 /* Set up 'precmd' or equivalent for reading the subshell's CWD */
887 switch (subshell_type
)
890 g_snprintf (precmd
, sizeof (precmd
),
891 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe
[WRITE
]);
895 g_snprintf (precmd
, sizeof (precmd
),
896 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe
[WRITE
]);
900 g_snprintf (precmd
, sizeof (precmd
),
901 "set echo_style=both;"
902 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo
);
905 g_snprintf (precmd
, sizeof (precmd
),
906 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
907 subshell_pipe
[WRITE
]);
911 write_all (mc_global
.tty
.subshell_pty
, precmd
, strlen (precmd
));
913 /* Wait until the subshell has started up and processed the command */
915 subshell_state
= RUNNING_COMMAND
;
916 tty_enable_interrupt_key ();
917 if (!feed_subshell (QUIETLY
, TRUE
))
919 mc_global
.tty
.use_subshell
= FALSE
;
921 tty_disable_interrupt_key ();
923 mc_global
.tty
.use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
926 /* --------------------------------------------------------------------------------------------- */
929 invoke_subshell (const char *command
, int how
, vfs_path_t
** new_dir_vpath
)
933 /* Make the MC terminal transparent */
934 tcsetattr (STDOUT_FILENO
, TCSANOW
, &raw_mode
);
936 /* Make the subshell change to MC's working directory */
937 if (new_dir_vpath
!= NULL
)
938 do_subshell_chdir (current_panel
->cwd_vpath
, TRUE
, TRUE
);
940 if (command
== NULL
) /* The user has done "C-o" from MC */
942 if (subshell_state
== INACTIVE
)
944 subshell_state
= ACTIVE
;
945 /* FIXME: possibly take out this hack; the user can
946 re-play it by hitting C-hyphen a few times! */
948 write_all (mc_global
.tty
.subshell_pty
, " \b", 2); /* Hack to make prompt reappear */
951 else /* MC has passed us a user command */
954 write_all (mc_global
.tty
.subshell_pty
, " ", 1);
955 /* FIXME: if command is long (>8KB ?) we go comma */
956 write_all (mc_global
.tty
.subshell_pty
, command
, strlen (command
));
957 write_all (mc_global
.tty
.subshell_pty
, "\n", 1);
958 subshell_state
= RUNNING_COMMAND
;
959 subshell_ready
= FALSE
;
962 feed_subshell (how
, FALSE
);
964 pcwd
= vfs_translate_path_n (vfs_path_as_str (current_panel
->cwd_vpath
));
966 if (new_dir_vpath
!= NULL
&& subshell_alive
&& strcmp (subshell_cwd
, pcwd
))
967 *new_dir_vpath
= vfs_path_from_str (subshell_cwd
); /* Make MC change to the subshell's CWD */
970 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
971 while (!subshell_alive
&& quit
== 0 && mc_global
.tty
.use_subshell
)
980 /* --------------------------------------------------------------------------------------------- */
983 read_subshell_prompt (void)
987 struct timeval timeleft
= { 0, 0 };
989 gboolean prompt_was_reset
= FALSE
;
993 FD_SET (mc_global
.tty
.subshell_pty
, &tmp
);
995 /* First time through */
996 if (subshell_prompt
== NULL
)
997 subshell_prompt
= g_string_sized_new (INITIAL_PROMPT_SIZE
);
999 p
= g_string_sized_new (INITIAL_PROMPT_SIZE
);
1001 while (subshell_alive
1002 && (rc
= select (mc_global
.tty
.subshell_pty
+ 1, &tmp
, NULL
, NULL
, &timeleft
)) != 0)
1006 /* Check for 'select' errors */
1011 if (mc_global
.tty
.winch_flag
!= 0)
1012 tty_change_screen_size ();
1017 fprintf (stderr
, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno
));
1018 exit (EXIT_FAILURE
);
1021 bytes
= read (mc_global
.tty
.subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
1023 /* Extract the prompt from the shell output */
1024 for (i
= 0; i
< bytes
; i
++)
1025 if (pty_buffer
[i
] == '\n' || pty_buffer
[i
] == '\r')
1027 g_string_set_size (p
, 0);
1028 prompt_was_reset
= TRUE
;
1030 else if (pty_buffer
[i
] != '\0')
1031 g_string_append_c (p
, pty_buffer
[i
]);
1034 if (p
->len
!= 0 || prompt_was_reset
)
1035 g_string_assign (subshell_prompt
, p
->str
);
1037 g_string_free (p
, TRUE
);
1039 return (rc
!= 0 || bytes
!= 0);
1042 /* --------------------------------------------------------------------------------------------- */
1045 do_update_prompt (void)
1047 if (update_subshell_prompt
)
1049 printf ("\r\n%s", subshell_prompt
->str
);
1051 update_subshell_prompt
= FALSE
;
1055 /* --------------------------------------------------------------------------------------------- */
1058 exit_subshell (void)
1060 gboolean subshell_quit
= TRUE
;
1062 if (subshell_state
!= INACTIVE
&& subshell_alive
)
1064 query_dialog (_("Warning"),
1065 _("The shell is still active. Quit anyway?"),
1066 D_NORMAL
, 2, _("&Yes"), _("&No")) == 0;
1070 if (subshell_type
== TCSH
)
1072 if (unlink (tcsh_fifo
) == -1)
1073 fprintf (stderr
, "Cannot remove named pipe %s: %s\r\n",
1074 tcsh_fifo
, unix_error_string (errno
));
1077 g_string_free (subshell_prompt
, TRUE
);
1078 subshell_prompt
= NULL
;
1079 pty_buffer
[0] = '\0';
1082 return subshell_quit
;
1085 /* --------------------------------------------------------------------------------------------- */
1087 * Carefully quote directory name to allow entering any directory safely,
1088 * no matter what weird characters it may contain in its name.
1089 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1090 * executing any commands in the shell. Escape all control characters.
1091 * Use following technique:
1093 * printf(1) with format string containing a single conversion specifier,
1094 * "b", and an argument which contains a copy of the string passed to
1095 * subshell_name_quote() with all characters, except digits and letters,
1096 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1097 * numeric value of the character converted to octal number.
1099 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1104 subshell_name_quote (const char *s
)
1108 const char *quote_cmd_start
, *quote_cmd_end
;
1110 if (subshell_type
== FISH
)
1112 quote_cmd_start
= "(printf \"%b\" '";
1113 quote_cmd_end
= "')";
1117 quote_cmd_start
= "\"`printf \"%b\" '";
1118 quote_cmd_end
= "'`\"";
1121 ret
= g_string_sized_new (64);
1123 /* Prevent interpreting leading '-' as a switch for 'cd' */
1125 g_string_append (ret
, "./");
1127 /* Copy the beginning of the command to the buffer */
1128 g_string_append (ret
, quote_cmd_start
);
1131 * Print every character except digits and letters as a backslash-escape
1132 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1133 * character converted to octal number.
1135 for (su
= s
; su
[0] != '\0'; su
= n
)
1137 n
= str_cget_next_char_safe (su
);
1139 if (str_isalnum (su
))
1140 g_string_append_len (ret
, su
, n
- su
);
1145 for (c
= 0; c
< n
- su
; c
++)
1146 g_string_append_printf (ret
, "\\0%03o", (unsigned char) su
[c
]);
1150 g_string_append (ret
, quote_cmd_end
);
1156 /* --------------------------------------------------------------------------------------------- */
1158 /** If it actually changed the directory it returns true */
1160 do_subshell_chdir (const vfs_path_t
* vpath
, gboolean update_prompt
, gboolean reset_prompt
)
1164 pcwd
= vfs_path_to_str_flags (current_panel
->cwd_vpath
, 0, VPF_RECODE
);
1166 if (!(subshell_state
== INACTIVE
&& strcmp (subshell_cwd
, pcwd
) != 0))
1168 /* We have to repaint the subshell prompt if we read it from
1169 * the main program. Please note that in the code after this
1170 * if, the cd command that is sent will make the subshell
1171 * repaint the prompt, so we don't have to paint it. */
1173 do_update_prompt ();
1178 /* The initial space keeps this out of the command history (in bash
1179 because we set "HISTCONTROL=ignorespace") */
1180 write_all (mc_global
.tty
.subshell_pty
, " cd ", 4);
1186 translate
= vfs_translate_path_n (vfs_path_as_str (vpath
));
1187 if (translate
!= NULL
)
1191 temp
= subshell_name_quote (translate
);
1192 write_all (mc_global
.tty
.subshell_pty
, temp
->str
, temp
->len
);
1193 g_string_free (temp
, TRUE
);
1199 write_all (mc_global
.tty
.subshell_pty
, ".", 1);
1204 write_all (mc_global
.tty
.subshell_pty
, "/", 1);
1206 write_all (mc_global
.tty
.subshell_pty
, "\n", 1);
1208 subshell_state
= RUNNING_COMMAND
;
1209 feed_subshell (QUIETLY
, FALSE
);
1213 int bPathNotEq
= strcmp (subshell_cwd
, pcwd
);
1215 if (bPathNotEq
&& subshell_type
== TCSH
)
1217 char rp_subshell_cwd
[PATH_MAX
];
1218 char rp_current_panel_cwd
[PATH_MAX
];
1220 char *p_subshell_cwd
= mc_realpath (subshell_cwd
, rp_subshell_cwd
);
1221 char *p_current_panel_cwd
= mc_realpath (pcwd
, rp_current_panel_cwd
);
1223 if (p_subshell_cwd
== NULL
)
1224 p_subshell_cwd
= subshell_cwd
;
1225 if (p_current_panel_cwd
== NULL
)
1226 p_current_panel_cwd
= pcwd
;
1227 bPathNotEq
= strcmp (p_subshell_cwd
, p_current_panel_cwd
);
1230 if (bPathNotEq
&& strcmp (pcwd
, ".") != 0)
1234 cwd
= vfs_path_to_str_flags (current_panel
->cwd_vpath
, 0, VPF_STRIP_PASSWORD
);
1235 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd
);
1242 update_subshell_prompt
= FALSE
;
1245 /* Make sure that MC never stores the CWD in a silly format */
1246 /* like /usr////lib/../bin, or the strcmp() above will fail */
1249 /* --------------------------------------------------------------------------------------------- */
1252 subshell_get_console_attributes (void)
1254 /* Get our current terminal modes */
1256 if (tcgetattr (STDOUT_FILENO
, &shell_mode
))
1258 fprintf (stderr
, "Cannot get terminal settings: %s\r\n", unix_error_string (errno
));
1259 mc_global
.tty
.use_subshell
= FALSE
;
1263 /* --------------------------------------------------------------------------------------------- */
1265 * Figure out whether the subshell has stopped, exited or been killed
1266 * Possibly modifies: 'subshell_alive', 'subshell_stopped' and 'quit' */
1269 sigchld_handler (int sig
)
1276 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
1278 if (pid
== subshell_pid
)
1280 /* Figure out what has happened to the subshell */
1282 if (WIFSTOPPED (status
))
1284 if (WSTOPSIG (status
) == SIGSTOP
)
1286 /* The subshell has received a SIGSTOP signal */
1287 subshell_stopped
= TRUE
;
1291 /* The user has suspended the subshell. Revive it */
1292 kill (subshell_pid
, SIGCONT
);
1297 /* The subshell has either exited normally or been killed */
1298 subshell_alive
= FALSE
;
1299 delete_select_channel (mc_global
.tty
.subshell_pty
);
1300 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
1301 quit
|= SUBSHELL_EXIT
; /* Exited normally */
1305 pid
= waitpid (cons_saver_pid
, &status
, WUNTRACED
| WNOHANG
);
1307 if (pid
== cons_saver_pid
)
1310 if (WIFSTOPPED (status
))
1311 /* Someone has stopped cons.saver - restart it */
1312 kill (pid
, SIGCONT
);
1315 /* cons.saver has died - disable confole saving */
1316 handle_console (CONSOLE_DONE
);
1317 mc_global
.tty
.console_flag
= '\0';
1321 #endif /* __linux__ */
1323 /* If we got here, some other child exited; ignore it */
1326 /* --------------------------------------------------------------------------------------------- */