2 Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994-2018
5 Free Software Foundation, Inc.
8 Alexander Kriegisch <Alexander@Kriegisch.name>
9 Aliaksey Kandratsenka <alk@tut.by>
10 Andreas Mohr <and@gmx.li>
11 Andrew Borodin <aborodin@vmail.ru>
12 Andrew Borodin <borodin@borodin.zarya>
13 Andrew V. Samoilov <sav@bcs.zp.ua>
14 Chris Owen <chris@candu.co.uk>
15 Claes Nästén <me@pekdon.net>
16 Egmont Koblinger <egmont@gmail.com>
17 Enrico Weigelt, metux IT service <weigelt@metux.de>
18 Igor Urazov <z0rc3r@gmail.com>
19 Ilia Maslakov <il.smind@gmail.com>
20 Leonard den Ottolander <leonard@den.ottolander.nl>
21 Miguel de Icaza <miguel@novell.com>
22 Mikhail S. Pobolovets <styx.mp@gmail.com>
23 Norbert Warmuth <nwarmuth@privat.circular.de>
24 Patrick Winnertz <winnie@debian.org>
25 Pavel Machek <pavel@suse.cz>
26 Pavel Roskin <proski@gnu.org>
27 Pavel Tsekov <ptsekov@gmx.net>
28 Roland Illig <roland.illig@gmx.de>
29 Sergei Trofimovich <slyfox@inbox.ru>
30 Slava Zanko <slavazanko@gmail.com>, 2013,2015.
31 Timur Bakeyev <mc@bat.ru>
32 Vit Rosin <vit_r@list.ru>
34 This file is part of the Midnight Commander.
36 The Midnight Commander is free software: you can redistribute it
37 and/or modify it under the terms of the GNU General Public License as
38 published by the Free Software Foundation, either version 3 of the License,
39 or (at your option) any later version.
41 The Midnight Commander is distributed in the hope that it will be useful,
42 but WITHOUT ANY WARRANTY; without even the implied warranty of
43 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 GNU General Public License for more details.
46 You should have received a copy of the GNU General Public License
47 along with this program. If not, see <http://www.gnu.org/licenses/>.
51 * \brief Source: concurrent shell support
66 #include <sys/types.h>
68 #ifdef HAVE_SYS_IOCTL_H
69 #include <sys/ioctl.h>
74 #include <stropts.h> /* For I_PUSH */
75 #endif /* HAVE_STROPTS_H */
78 /* includes for openpty() */
85 /* <sys/types.h> is a prerequisite of <libutil.h> on FreeBSD 8.0. */
89 #endif /* HAVE_OPENPTY */
91 #include "lib/global.h"
93 #include "lib/unixcompat.h"
94 #include "lib/tty/tty.h" /* LINES */
95 #include "lib/tty/key.h" /* XCTRL */
96 #include "lib/vfs/vfs.h"
97 #include "lib/strutil.h"
98 #include "lib/mcconfig.h"
100 #include "lib/widget.h"
102 #include "subshell.h"
103 #include "internal.h"
105 /*** global variables ****************************************************************************/
107 /* State of the subshell:
108 * INACTIVE: the default state; awaiting a command
109 * ACTIVE: remain in the shell until the user hits 'subshell_switch_key'
110 * RUNNING_COMMAND: return to MC when the current command finishes */
111 enum subshell_state_enum subshell_state
;
113 /* Holds the latest prompt captured from the subshell */
114 GString
*subshell_prompt
= NULL
;
116 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
117 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
118 gboolean update_subshell_prompt
= FALSE
;
120 /*** file scope macro definitions ****************************************************************/
123 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
127 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
130 /* Initial length of the buffer for the subshell's prompt */
131 #define INITIAL_PROMPT_SIZE 10
133 /* Used by the child process to indicate failure to start the subshell */
134 #define FORK_FAILURE 69 /* Arbitrary */
136 /* Length of the buffer for all I/O with the subshell */
137 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
139 /*** file scope type declarations ****************************************************************/
148 /*** file scope variables ************************************************************************/
150 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
151 static char tcsh_fifo
[128];
153 static int subshell_pty_slave
= -1;
155 /* The key for switching back to MC from the subshell */
157 static const char subshell_switch_key
= XCTRL ('o') & 255;
160 /* For reading/writing on the subshell's pty */
161 static char pty_buffer
[PTY_BUFFER_SIZE
] = "\0";
163 /* To pass CWD info from the subshell to MC */
164 static int subshell_pipe
[2];
166 /* The subshell's process ID */
167 static pid_t subshell_pid
= 1;
169 /* One extra char for final '\n' */
170 static char subshell_cwd
[MC_MAXPATHLEN
+ 1];
172 /* Flag to indicate whether the subshell is ready for next command */
173 static int subshell_ready
;
175 /* The following two flags can be changed by the SIGCHLD handler. This is */
176 /* OK, because the 'int' type is updated atomically on all known machines */
177 static volatile int subshell_alive
, subshell_stopped
;
179 /* We store the terminal's initial mode here so that we can configure
180 the pty similarly, and also so we can restore the real terminal to
181 sanity if we have to exit abruptly */
182 static struct termios shell_mode
;
184 /* This is a transparent mode for the terminal where MC is running on */
185 /* It is used when the shell is active, so that the control signals */
186 /* are delivered to the shell pty */
187 static struct termios raw_mode
;
189 /* --------------------------------------------------------------------------------------------- */
190 /*** file scope functions ************************************************************************/
191 /* --------------------------------------------------------------------------------------------- */
193 * Write all data, even if the write() call is interrupted.
197 write_all (int fd
, const void *buf
, size_t count
)
205 ret
= write (fd
, (const unsigned char *) buf
+ written
, count
);
210 if (mc_global
.tty
.winch_flag
!= 0)
211 tty_change_screen_size ();
216 return written
> 0 ? written
: ret
;
224 /* --------------------------------------------------------------------------------------------- */
226 * Prepare child process to running the shell and run it.
228 * Modifies the global variables (in the child process only):
235 init_subshell_child (const char *pty_name
)
237 char *init_file
= NULL
;
238 char *putenv_str
= NULL
;
242 setsid (); /* Get a fresh terminal session */
244 /* Make sure that it has become our controlling terminal */
246 /* Redundant on Linux and probably most systems, but just in case: */
249 ioctl (subshell_pty_slave
, TIOCSCTTY
, 0);
252 /* Configure its terminal modes and window size */
254 /* Set up the pty with the same termios flags as our own tty */
255 if (tcsetattr (subshell_pty_slave
, TCSANOW
, &shell_mode
))
257 fprintf (stderr
, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno
));
258 my_exit (FORK_FAILURE
);
261 /* Set the pty's size (80x25 by default on Linux) according to the */
262 /* size of the real terminal as calculated by ncurses, if possible */
263 tty_resize (subshell_pty_slave
);
265 /* Set up the subshell's environment and init file name */
267 /* It simplifies things to change to our home directory here, */
268 /* and the user's startup file may do a 'cd' command anyway */
272 ret
= chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
276 /* Set MC_SID to prevent running one mc from another */
280 char sid_str
[BUF_SMALL
];
282 g_snprintf (sid_str
, sizeof (sid_str
), "MC_SID=%ld", (long) mc_sid
);
283 putenv (g_strdup (sid_str
));
286 switch (mc_global
.shell
->type
)
289 /* Do we have a custom init file ~/.local/share/mc/bashrc? */
290 init_file
= mc_config_get_full_path ("bashrc");
292 /* Otherwise use ~/.bashrc */
293 if (!exist_file (init_file
))
296 init_file
= g_strdup (".bashrc");
299 /* Make MC's special commands not show up in bash's history and also suppress
300 * consecutive identical commands*/
301 putenv ((char *) "HISTCONTROL=ignoreboth");
303 /* Allow alternative readline settings for MC */
307 input_file
= mc_config_get_full_path ("inputrc");
308 if (exist_file (input_file
))
310 putenv_str
= g_strconcat ("INPUTRC=", input_file
, (char *) NULL
);
318 case SHELL_ASH_BUSYBOX
:
320 /* Do we have a custom init file ~/.local/share/mc/ashrc? */
321 init_file
= mc_config_get_full_path ("ashrc");
323 /* Otherwise use ~/.profile */
324 if (!exist_file (init_file
))
327 init_file
= g_strdup (".profile");
330 /* Put init file to ENV variable used by ash */
331 putenv_str
= g_strconcat ("ENV=", init_file
, (char *) NULL
);
333 /* Do not use "g_free (putenv_str)" here, otherwise ENV will be undefined! */
337 /* TODO: Find a way to pass initfile to TCSH, ZSH and FISH */
344 fprintf (stderr
, __FILE__
": unimplemented subshell type %u\r\n", mc_global
.shell
->type
);
345 my_exit (FORK_FAILURE
);
348 /* Attach all our standard file descriptors to the pty */
350 /* This is done just before the fork, because stderr must still */
351 /* be connected to the real tty during the above error messages; */
352 /* otherwise the user will never see them. */
354 dup2 (subshell_pty_slave
, STDIN_FILENO
);
355 dup2 (subshell_pty_slave
, STDOUT_FILENO
);
356 dup2 (subshell_pty_slave
, STDERR_FILENO
);
358 close (subshell_pipe
[READ
]);
359 close (subshell_pty_slave
); /* These may be FD_CLOEXEC, but just in case... */
360 /* Close master side of pty. This is important; apart from */
361 /* freeing up the descriptor for use in the subshell, it also */
362 /* means that when MC exits, the subshell will get a SIGHUP and */
363 /* exit too, because there will be no more descriptors pointing */
364 /* at the master side of the pty and so it will disappear. */
365 close (mc_global
.tty
.subshell_pty
);
367 /* Execute the subshell at last */
369 switch (mc_global
.shell
->type
)
372 execl (mc_global
.shell
->path
, "bash", "-rcfile", init_file
, (char *) NULL
);
376 /* Use -g to exclude cmds beginning with space from history
377 * and -Z to use the line editor on non-interactive term */
378 execl (mc_global
.shell
->path
, "zsh", "-Z", "-g", (char *) NULL
);
382 case SHELL_ASH_BUSYBOX
:
386 execl (mc_global
.shell
->path
, mc_global
.shell
->path
, (char *) NULL
);
393 /* If we get this far, everything failed miserably */
396 my_exit (FORK_FAILURE
);
400 /* --------------------------------------------------------------------------------------------- */
402 * Check MC_SID to prevent running one mc from another.
404 * 0 if no parent mc in our session was found,
405 * 1 if parent mc was found and the user wants to continue,
406 * 2 if parent mc was found and the user wants to quit mc.
412 pid_t my_sid
, old_sid
;
416 sid_str
= getenv ("MC_SID");
420 old_sid
= (pid_t
) strtol (sid_str
, NULL
, 0);
428 /* The parent mc is in a different session, it's OK */
429 if (old_sid
!= my_sid
)
432 r
= query_dialog (_("Warning"),
433 _("GNU Midnight Commander is already\n"
434 "running on this terminal.\n"
435 "Subshell support will be disabled."), D_ERROR
, 2, _("&OK"), _("&Quit"));
437 return (r
!= 0) ? 2 : 1;
440 /* --------------------------------------------------------------------------------------------- */
445 static gboolean initialized
= FALSE
;
447 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
448 /* original settings. However, here we need to make this tty very raw, */
449 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
450 /* pty. So, instead of changing the code for execute(), pre_exec(), */
451 /* etc, we just set up the modes we need here, before each command. */
453 if (!initialized
) /* First time: initialise 'raw_mode' */
455 tcgetattr (STDOUT_FILENO
, &raw_mode
);
456 raw_mode
.c_lflag
&= ~ICANON
; /* Disable line-editing chars, etc. */
457 raw_mode
.c_lflag
&= ~ISIG
; /* Disable intr, quit & suspend chars */
458 raw_mode
.c_lflag
&= ~ECHO
; /* Disable input echoing */
459 raw_mode
.c_iflag
&= ~IXON
; /* Pass ^S/^Q to subshell undisturbed */
460 raw_mode
.c_iflag
&= ~ICRNL
; /* Don't translate CRs into LFs */
461 raw_mode
.c_oflag
&= ~OPOST
; /* Don't postprocess output */
462 raw_mode
.c_cc
[VTIME
] = 0; /* IE: wait forever, and return as */
463 raw_mode
.c_cc
[VMIN
] = 1; /* soon as a character is available */
468 /* --------------------------------------------------------------------------------------------- */
470 * Wait until the subshell dies or stops. If it stops, make it resume.
471 * Possibly modifies the globals 'subshell_alive' and 'subshell_stopped'
477 sigset_t sigchld_mask
, old_mask
;
479 sigemptyset (&sigchld_mask
);
480 sigaddset (&sigchld_mask
, SIGCHLD
);
481 sigprocmask (SIG_BLOCK
, &sigchld_mask
, &old_mask
);
484 * SIGCHLD should not be blocked, but we unblock it just in case.
485 * This is known to be useful for cygwin 1.3.12 and older.
487 sigdelset (&old_mask
, SIGCHLD
);
489 /* Wait until the subshell has stopped */
490 while (subshell_alive
&& !subshell_stopped
)
491 sigsuspend (&old_mask
);
493 if (subshell_state
!= ACTIVE
)
495 /* Discard all remaining data from stdin to the subshell */
496 tcflush (subshell_pty_slave
, TCIFLUSH
);
499 subshell_stopped
= FALSE
;
500 kill (subshell_pid
, SIGCONT
);
502 sigprocmask (SIG_SETMASK
, &old_mask
, NULL
);
503 /* We can't do any better without modifying the shell(s) */
506 /* --------------------------------------------------------------------------------------------- */
507 /** Feed the subshell our keyboard input until it says it's finished */
510 feed_subshell (int how
, gboolean fail_on_error
)
512 fd_set read_set
; /* For 'select' */
513 int bytes
; /* For the return value from 'read' */
514 int i
; /* Loop counter */
516 struct timeval wtime
; /* Maximum time we wait for the subshell */
517 struct timeval
*wptr
;
519 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
522 wptr
= fail_on_error
? &wtime
: NULL
;
531 /* Prepare the file-descriptor set and call 'select' */
534 FD_SET (mc_global
.tty
.subshell_pty
, &read_set
);
535 FD_SET (subshell_pipe
[READ
], &read_set
);
536 maxfdp
= MAX (mc_global
.tty
.subshell_pty
, subshell_pipe
[READ
]);
539 FD_SET (STDIN_FILENO
, &read_set
);
540 maxfdp
= MAX (maxfdp
, STDIN_FILENO
);
543 if (select (maxfdp
+ 1, &read_set
, NULL
, NULL
, wptr
) == -1)
545 /* Despite using SA_RESTART, we still have to check for this */
548 if (mc_global
.tty
.winch_flag
!= 0)
549 tty_change_screen_size ();
551 continue; /* try all over again */
553 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
554 fprintf (stderr
, "select (FD_SETSIZE, &read_set...): %s\r\n",
555 unix_error_string (errno
));
559 if (FD_ISSET (mc_global
.tty
.subshell_pty
, &read_set
))
560 /* Read from the subshell, write to stdout */
562 /* This loop improves performance by reducing context switches
563 by a factor of 20 or so... unfortunately, it also hangs MC
564 randomly, because of an apparent Linux bug. Investigate. */
565 /* for (i=0; i<5; ++i) * FIXME -- experimental */
567 bytes
= read (mc_global
.tty
.subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
569 /* The subshell has died */
570 if (bytes
== -1 && errno
== EIO
&& !subshell_alive
)
576 /* On IBM i, read(1) can return 0 for a non-closed fd */
579 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
580 fprintf (stderr
, "read (subshell_pty...): %s\r\n", unix_error_string (errno
));
586 write_all (STDOUT_FILENO
, pty_buffer
, bytes
);
589 else if (FD_ISSET (subshell_pipe
[READ
], &read_set
))
590 /* Read the subshell's CWD and capture its prompt */
592 bytes
= read (subshell_pipe
[READ
], subshell_cwd
, sizeof (subshell_cwd
));
595 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
596 fprintf (stderr
, "read (subshell_pipe[READ]...): %s\r\n",
597 unix_error_string (errno
));
601 subshell_cwd
[bytes
- 1] = 0; /* Squash the final '\n' */
605 subshell_ready
= TRUE
;
606 if (subshell_state
== RUNNING_COMMAND
)
608 subshell_state
= INACTIVE
;
613 else if (FD_ISSET (STDIN_FILENO
, &read_set
))
614 /* Read from stdin, write to the subshell */
616 bytes
= read (STDIN_FILENO
, pty_buffer
, sizeof (pty_buffer
));
619 tcsetattr (STDOUT_FILENO
, TCSANOW
, &shell_mode
);
621 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno
));
625 for (i
= 0; i
< bytes
; ++i
)
626 if (pty_buffer
[i
] == subshell_switch_key
)
628 write_all (mc_global
.tty
.subshell_pty
, pty_buffer
, i
);
630 subshell_state
= INACTIVE
;
634 write_all (mc_global
.tty
.subshell_pty
, pty_buffer
, bytes
);
636 if (pty_buffer
[bytes
- 1] == '\n' || pty_buffer
[bytes
- 1] == '\r')
637 subshell_ready
= FALSE
;
644 /* --------------------------------------------------------------------------------------------- */
645 /* pty opening functions */
651 /* System V version of pty_open_master */
654 pty_open_master (char *pty_name
)
659 #ifdef HAVE_POSIX_OPENPT
660 pty_master
= posix_openpt (O_RDWR
);
661 #elif defined HAVE_GETPT
662 /* getpt () is a GNU extension (glibc 2.1.x) */
663 pty_master
= getpt ();
665 strcpy (pty_name
, "/dev/ptc");
666 pty_master
= open (pty_name
, O_RDWR
);
668 strcpy (pty_name
, "/dev/ptmx");
669 pty_master
= open (pty_name
, O_RDWR
);
672 if (pty_master
== -1)
675 if (grantpt (pty_master
) == -1 /* Grant access to slave */
676 || unlockpt (pty_master
) == -1 /* Clear slave's lock flag */
677 || !(slave_name
= ptsname (pty_master
))) /* Get slave's name */
682 strcpy (pty_name
, slave_name
);
686 /* --------------------------------------------------------------------------------------------- */
687 /** System V version of pty_open_slave */
690 pty_open_slave (const char *pty_name
)
694 pty_slave
= open (pty_name
, O_RDWR
);
697 fprintf (stderr
, "open (%s, O_RDWR): %s\r\n", pty_name
, unix_error_string (errno
));
700 #if !defined(__osf__) && !defined(__linux__)
701 #if defined (I_FIND) && defined (I_PUSH)
702 if (ioctl (pty_slave
, I_FIND
, "ptem") == 0)
703 if (ioctl (pty_slave
, I_PUSH
, "ptem") == -1)
705 fprintf (stderr
, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
706 pty_slave
, unix_error_string (errno
));
711 if (ioctl (pty_slave
, I_FIND
, "ldterm") == 0)
712 if (ioctl (pty_slave
, I_PUSH
, "ldterm") == -1)
715 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
716 pty_slave
, unix_error_string (errno
));
720 #if !defined(sgi) && !defined(__sgi)
721 if (ioctl (pty_slave
, I_FIND
, "ttcompat") == 0)
722 if (ioctl (pty_slave
, I_PUSH
, "ttcompat") == -1)
725 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
726 pty_slave
, unix_error_string (errno
));
730 #endif /* sgi || __sgi */
731 #endif /* I_FIND && I_PUSH */
732 #endif /* __osf__ || __linux__ */
734 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
738 #else /* !HAVE_GRANTPT */
740 /* --------------------------------------------------------------------------------------------- */
741 /** BSD version of pty_open_master */
743 pty_open_master (char *pty_name
)
746 const char *ptr1
, *ptr2
;
748 strcpy (pty_name
, "/dev/ptyXX");
749 for (ptr1
= "pqrstuvwxyzPQRST"; *ptr1
; ++ptr1
)
752 for (ptr2
= "0123456789abcdef"; *ptr2
!= '\0'; ++ptr2
)
756 /* Try to open master */
757 pty_master
= open (pty_name
, O_RDWR
);
758 if (pty_master
== -1)
760 if (errno
== ENOENT
) /* Different from EIO */
761 return -1; /* Out of pty devices */
762 continue; /* Try next pty device */
764 pty_name
[5] = 't'; /* Change "pty" to "tty" */
765 if (access (pty_name
, 6) != 0)
774 return -1; /* Ran out of pty devices */
777 /* --------------------------------------------------------------------------------------------- */
778 /** BSD version of pty_open_slave */
781 pty_open_slave (const char *pty_name
)
784 struct group
*group_info
;
786 group_info
= getgrnam ("tty");
787 if (group_info
!= NULL
)
789 /* The following two calls will only succeed if we are root */
790 /* [Commented out while permissions problem is investigated] */
791 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
792 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
794 pty_slave
= open (pty_name
, O_RDWR
);
796 fprintf (stderr
, "open (pty_name, O_RDWR): %s\r\n", pty_name
);
797 fcntl (pty_slave
, F_SETFD
, FD_CLOEXEC
);
800 #endif /* !HAVE_GRANTPT */
802 #endif /* !HAVE_OPENPTY */
804 /* --------------------------------------------------------------------------------------------- */
806 * Set up `precmd' or equivalent for reading the subshell's CWD.
808 * Attention! Never forget that these are *one-liners* even though the concatenated
809 * substrings contain line breaks and indentation for better understanding of the
810 * shell code. It is vital that each one-liner ends with a line feed character ("\n" ).
812 * @return initialized pre-command string
816 init_subshell_precmd (char *precmd
, size_t buff_size
)
818 switch (mc_global
.shell
->type
)
821 g_snprintf (precmd
, buff_size
,
822 " PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND\n}'pwd>&%d;kill -STOP $$'\n"
823 "PS1='\\u@\\h:\\w\\$ '\n", subshell_pipe
[WRITE
]);
826 case SHELL_ASH_BUSYBOX
:
827 /* BusyBox ash needs a somewhat complicated precmd emulation via PS1, and it is vital
828 * that BB be built with active CONFIG_ASH_EXPAND_PRMT, but this is the default anyway.
830 * A: This leads to a stopped subshell (=frozen mc) if user calls "ash" command
831 * "PS1='$(pwd>&%d; kill -STOP $$)\\u@\\h:\\w\\$ '\n",
833 * B: This leads to "sh: precmd: not found" in sub-subshell if user calls "ash" command
834 * "precmd() { pwd>&%d; kill -STOP $$; }; "
835 * "PS1='$(precmd)\\u@\\h:\\w\\$ '\n",
837 * C: This works if user calls "ash" command because in sub-subshell
838 * PRECMD is unfedined, thus evaluated to empty string - no damage done.
839 * Attention: BusyBox must be built with FEATURE_EDITING_FANCY_PROMPT to
840 * permit \u, \w, \h, \$ escape sequences. Unfortunately this cannot be guaranteed,
841 * especially on embedded systems where people try to save space, so let's use
842 * the dash version below. It should work on virtually all systems.
843 * "precmd() { pwd>&%d; kill -STOP $$; }; "
845 * "PS1='$(eval $PRECMD)\\u@\\h:\\w\\$ '\n",
848 /* Debian ash needs a precmd emulation via PS1, similar to BusyBox ash,
849 * but does not support escape sequences for user, host and cwd in prompt.
850 * Attention! Make sure that the buffer for precmd is big enough.
852 * We want to have a fancy dynamic prompt with user@host:cwd just like in the BusyBox
853 * examples above, but because replacing the home directory part of the path by "~" is
854 * complicated, it bloats the precmd to a size > BUF_SMALL (128).
856 * The following example is a little less fancy (home directory not replaced)
857 * and shows the basic workings of our prompt for easier understanding:
860 * "echo \"$USER@$(hostname -s):$PWD\"; "
865 * "PS1='$($PRECMD)$ '\n",
867 g_snprintf (precmd
, buff_size
,
869 "if [ ! \"${PWD##$HOME}\" ]; then "
872 "[ \"${PWD##$HOME/}\" = \"$PWD\" ] && MC_PWD=\"$PWD\" || MC_PWD=\"~/${PWD##$HOME/}\"; "
874 "echo \"$USER@$(hostname -s):$MC_PWD\"; "
877 "}; " "PRECMD=precmd; " "PS1='$($PRECMD)$ '\n", subshell_pipe
[WRITE
]);
881 g_snprintf (precmd
, buff_size
,
882 " _mc_precmd(){ pwd>&%d;kill -STOP $$ }; precmd_functions+=(_mc_precmd)\n"
883 "PS1='%%n@%%m:%%~%%# '\n", subshell_pipe
[WRITE
]);
887 g_snprintf (precmd
, buff_size
,
888 "set echo_style=both; "
889 "set prompt='%%n@%%m:%%~%%# '; "
890 "alias precmd 'echo $cwd:q >>%s; kill -STOP $$'\n", tcsh_fifo
);
894 /* We also want a fancy user@host:cwd prompt here, but fish makes it very easy to also
895 * use colours, which is what we will do. But first here is a simpler, uncoloured version:
896 * "function fish_prompt; "
897 * "echo (whoami)@(hostname -s):(pwd)\\$\\ ; "
898 * "echo \"$PWD\">&%d; "
899 * "kill -STOP %%self; "
902 * TODO: fish prompt is shown when panel is hidden (Ctrl-O), but not when it is visible.
903 * Find out how to fix this.
905 g_snprintf (precmd
, buff_size
,
906 " if not functions -q fish_prompt_mc;"
907 "functions -c fish_prompt fish_prompt_mc; end;"
908 "function fish_prompt;"
909 "echo (whoami)@(hostname -s):(set_color $fish_color_cwd)(pwd)(set_color normal)\\$\\ ; "
910 "echo \"$PWD\">&%d; fish_prompt_mc; kill -STOP %%self; end\n",
911 subshell_pipe
[WRITE
]);
919 /* --------------------------------------------------------------------------------------------- */
921 * Carefully quote directory name to allow entering any directory safely,
922 * no matter what weird characters it may contain in its name.
923 * NOTE: Treat directory name an untrusted data, don't allow it to cause
924 * executing any commands in the shell. Escape all control characters.
925 * Use following technique:
927 * printf(1) with format string containing a single conversion specifier,
928 * "b", and an argument which contains a copy of the string passed to
929 * subshell_name_quote() with all characters, except digits and letters,
930 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
931 * numeric value of the character converted to octal number.
933 * cd "`printf '%b' 'ABC\0nnnDEF\0nnnXYZ'`"
935 * N.B.: Use single quotes for conversion specifier to work around
936 * tcsh 6.20+ parser breakage, see ticket #3852 for the details.
940 subshell_name_quote (const char *s
)
944 const char *quote_cmd_start
, *quote_cmd_end
;
946 if (mc_global
.shell
->type
== SHELL_FISH
)
948 quote_cmd_start
= "(printf '%b' '";
949 quote_cmd_end
= "')";
951 /* TODO: When BusyBox printf is fixed, get rid of this "else if", see
952 http://lists.busybox.net/pipermail/busybox/2012-March/077460.html */
953 /* else if (subshell_type == ASH_BUSYBOX)
955 quote_cmd_start = "\"`echo -en '";
956 quote_cmd_end = "'`\"";
960 quote_cmd_start
= "\"`printf '%b' '";
961 quote_cmd_end
= "'`\"";
964 ret
= g_string_sized_new (64);
966 /* Prevent interpreting leading '-' as a switch for 'cd' */
968 g_string_append (ret
, "./");
970 /* Copy the beginning of the command to the buffer */
971 g_string_append (ret
, quote_cmd_start
);
974 * Print every character except digits and letters as a backslash-escape
975 * sequence of the form \0nnn, where "nnn" is the numeric value of the
976 * character converted to octal number.
978 for (su
= s
; su
[0] != '\0'; su
= n
)
980 n
= str_cget_next_char_safe (su
);
982 if (str_isalnum (su
))
983 g_string_append_len (ret
, su
, n
- su
);
988 for (c
= 0; c
< n
- su
; c
++)
989 g_string_append_printf (ret
, "\\0%03o", (unsigned char) su
[c
]);
993 g_string_append (ret
, quote_cmd_end
);
998 /* --------------------------------------------------------------------------------------------- */
999 /*** public functions ****************************************************************************/
1000 /* --------------------------------------------------------------------------------------------- */
1002 /* --------------------------------------------------------------------------------------------- */
1004 * Fork the subshell, and set up many, many things.
1006 * Possibly modifies the global variables:
1007 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
1008 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
1009 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
1013 init_subshell (void)
1015 /* This must be remembered across calls to init_subshell() */
1016 static char pty_name
[BUF_SMALL
];
1017 /* Must be considerably longer than BUF_SMALL (128) to support fancy shell prompts */
1018 char precmd
[BUF_MEDIUM
];
1020 switch (check_sid ())
1023 mc_global
.tty
.use_subshell
= FALSE
;
1026 mc_global
.tty
.use_subshell
= FALSE
;
1027 mc_global
.midnight_shutdown
= TRUE
;
1033 /* Take the current (hopefully pristine) tty mode and make */
1034 /* a raw mode based on it now, before we do anything else with it */
1037 if (mc_global
.tty
.subshell_pty
== 0)
1038 { /* First time through */
1039 if (mc_global
.shell
->type
== SHELL_NONE
)
1042 /* Open a pty for talking to the subshell */
1044 /* FIXME: We may need to open a fresh pty each time on SVR4 */
1047 if (openpty (&mc_global
.tty
.subshell_pty
, &subshell_pty_slave
, NULL
, NULL
, NULL
))
1049 fprintf (stderr
, "Cannot open master and slave sides of pty: %s\n",
1050 unix_error_string (errno
));
1051 mc_global
.tty
.use_subshell
= FALSE
;
1055 mc_global
.tty
.subshell_pty
= pty_open_master (pty_name
);
1056 if (mc_global
.tty
.subshell_pty
== -1)
1058 fprintf (stderr
, "Cannot open master side of pty: %s\r\n", unix_error_string (errno
));
1059 mc_global
.tty
.use_subshell
= FALSE
;
1062 subshell_pty_slave
= pty_open_slave (pty_name
);
1063 if (subshell_pty_slave
== -1)
1065 fprintf (stderr
, "Cannot open slave side of pty %s: %s\r\n",
1066 pty_name
, unix_error_string (errno
));
1067 mc_global
.tty
.use_subshell
= FALSE
;
1070 #endif /* HAVE_OPENPTY */
1072 /* Create a pipe for receiving the subshell's CWD */
1074 if (mc_global
.shell
->type
== SHELL_TCSH
)
1076 g_snprintf (tcsh_fifo
, sizeof (tcsh_fifo
), "%s/mc.pipe.%d",
1077 mc_tmpdir (), (int) getpid ());
1078 if (mkfifo (tcsh_fifo
, 0600) == -1)
1080 fprintf (stderr
, "mkfifo(%s) failed: %s\r\n", tcsh_fifo
, unix_error_string (errno
));
1081 mc_global
.tty
.use_subshell
= FALSE
;
1085 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
1087 if ((subshell_pipe
[READ
] = open (tcsh_fifo
, O_RDWR
)) == -1
1088 || (subshell_pipe
[WRITE
] = open (tcsh_fifo
, O_RDWR
)) == -1)
1090 fprintf (stderr
, _("Cannot open named pipe %s\n"), tcsh_fifo
);
1091 perror (__FILE__
": open");
1092 mc_global
.tty
.use_subshell
= FALSE
;
1096 else if (pipe (subshell_pipe
)) /* subshell_type is BASH, ASH_BUSYBOX, DASH or ZSH */
1098 perror (__FILE__
": couldn't create pipe");
1099 mc_global
.tty
.use_subshell
= FALSE
;
1104 /* Fork the subshell */
1106 subshell_alive
= TRUE
;
1107 subshell_stopped
= FALSE
;
1108 subshell_pid
= fork ();
1110 if (subshell_pid
== -1)
1112 fprintf (stderr
, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno
));
1113 /* We exit here because, if the process table is full, the */
1114 /* other method of running user commands won't work either */
1115 exit (EXIT_FAILURE
);
1118 if (subshell_pid
== 0)
1120 /* We are in the child process */
1121 init_subshell_child (pty_name
);
1124 init_subshell_precmd (precmd
, BUF_MEDIUM
);
1126 write_all (mc_global
.tty
.subshell_pty
, precmd
, strlen (precmd
));
1128 /* Wait until the subshell has started up and processed the command */
1130 subshell_state
= RUNNING_COMMAND
;
1131 tty_enable_interrupt_key ();
1132 if (!feed_subshell (QUIETLY
, TRUE
))
1134 mc_global
.tty
.use_subshell
= FALSE
;
1136 tty_disable_interrupt_key ();
1137 if (!subshell_alive
)
1138 mc_global
.tty
.use_subshell
= FALSE
; /* Subshell died instantly, so don't use it */
1141 /* --------------------------------------------------------------------------------------------- */
1144 invoke_subshell (const char *command
, int how
, vfs_path_t
** new_dir_vpath
)
1146 /* Make the MC terminal transparent */
1147 tcsetattr (STDOUT_FILENO
, TCSANOW
, &raw_mode
);
1149 /* Make the subshell change to MC's working directory */
1150 if (new_dir_vpath
!= NULL
)
1151 do_subshell_chdir (subshell_get_cwd_from_current_panel (), TRUE
);
1153 if (command
== NULL
) /* The user has done "C-o" from MC */
1155 if (subshell_state
== INACTIVE
)
1157 subshell_state
= ACTIVE
;
1158 /* FIXME: possibly take out this hack; the user can
1159 re-play it by hitting C-hyphen a few times! */
1161 write_all (mc_global
.tty
.subshell_pty
, " \b", 2); /* Hack to make prompt reappear */
1164 else /* MC has passed us a user command */
1167 write_all (mc_global
.tty
.subshell_pty
, " ", 1);
1168 /* FIXME: if command is long (>8KB ?) we go comma */
1169 write_all (mc_global
.tty
.subshell_pty
, command
, strlen (command
));
1170 write_all (mc_global
.tty
.subshell_pty
, "\n", 1);
1171 subshell_state
= RUNNING_COMMAND
;
1172 subshell_ready
= FALSE
;
1175 feed_subshell (how
, FALSE
);
1177 if (new_dir_vpath
!= NULL
&& subshell_alive
)
1181 pcwd
= vfs_translate_path (vfs_path_as_str (subshell_get_cwd_from_current_panel ()));
1182 if (strcmp (subshell_cwd
, pcwd
) != 0)
1183 *new_dir_vpath
= vfs_path_from_str (subshell_cwd
); /* Make MC change to the subshell's CWD */
1186 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
1187 while (!subshell_alive
&& subshell_get_mainloop_quit () == 0 && mc_global
.tty
.use_subshell
)
1190 return subshell_get_mainloop_quit ();
1194 /* --------------------------------------------------------------------------------------------- */
1197 read_subshell_prompt (void)
1201 struct timeval timeleft
= { 0, 0 };
1203 gboolean prompt_was_reset
= FALSE
;
1207 FD_SET (mc_global
.tty
.subshell_pty
, &tmp
);
1209 /* First time through */
1210 if (subshell_prompt
== NULL
)
1211 subshell_prompt
= g_string_sized_new (INITIAL_PROMPT_SIZE
);
1213 p
= g_string_sized_new (INITIAL_PROMPT_SIZE
);
1215 while (subshell_alive
1216 && (rc
= select (mc_global
.tty
.subshell_pty
+ 1, &tmp
, NULL
, NULL
, &timeleft
)) != 0)
1220 /* Check for 'select' errors */
1225 if (mc_global
.tty
.winch_flag
!= 0)
1226 tty_change_screen_size ();
1231 fprintf (stderr
, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno
));
1232 exit (EXIT_FAILURE
);
1235 bytes
= read (mc_global
.tty
.subshell_pty
, pty_buffer
, sizeof (pty_buffer
));
1237 /* Extract the prompt from the shell output */
1238 for (i
= 0; i
< bytes
; i
++)
1239 if (pty_buffer
[i
] == '\n' || pty_buffer
[i
] == '\r')
1241 g_string_set_size (p
, 0);
1242 prompt_was_reset
= TRUE
;
1244 else if (pty_buffer
[i
] != '\0')
1245 g_string_append_c (p
, pty_buffer
[i
]);
1248 if (p
->len
!= 0 || prompt_was_reset
)
1249 g_string_assign (subshell_prompt
, p
->str
);
1251 g_string_free (p
, TRUE
);
1253 return (rc
!= 0 || bytes
!= 0);
1256 /* --------------------------------------------------------------------------------------------- */
1259 do_update_prompt (void)
1261 if (update_subshell_prompt
)
1263 printf ("\r\n%s", subshell_prompt
->str
);
1265 update_subshell_prompt
= FALSE
;
1269 /* --------------------------------------------------------------------------------------------- */
1272 exit_subshell (void)
1274 gboolean subshell_quit
= TRUE
;
1276 if (subshell_state
!= INACTIVE
&& subshell_alive
)
1278 query_dialog (_("Warning"),
1279 _("The shell is still active. Quit anyway?"),
1280 D_NORMAL
, 2, _("&Yes"), _("&No")) == 0;
1284 if (mc_global
.shell
->type
== SHELL_TCSH
)
1286 if (unlink (tcsh_fifo
) == -1)
1287 fprintf (stderr
, "Cannot remove named pipe %s: %s\r\n",
1288 tcsh_fifo
, unix_error_string (errno
));
1291 g_string_free (subshell_prompt
, TRUE
);
1292 subshell_prompt
= NULL
;
1293 pty_buffer
[0] = '\0';
1296 return subshell_quit
;
1299 /* --------------------------------------------------------------------------------------------- */
1301 /** If it actually changed the directory it returns true */
1303 do_subshell_chdir (const vfs_path_t
* vpath
, gboolean update_prompt
)
1307 pcwd
= vfs_path_to_str_flags (subshell_get_cwd_from_current_panel (), 0, VPF_RECODE
);
1309 if (!(subshell_state
== INACTIVE
&& strcmp (subshell_cwd
, pcwd
) != 0))
1311 /* We have to repaint the subshell prompt if we read it from
1312 * the main program. Please note that in the code after this
1313 * if, the cd command that is sent will make the subshell
1314 * repaint the prompt, so we don't have to paint it. */
1316 do_update_prompt ();
1321 /* The initial space keeps this out of the command history (in bash
1322 because we set "HISTCONTROL=ignorespace") */
1323 write_all (mc_global
.tty
.subshell_pty
, " cd ", 4);
1327 const char *translate
;
1329 translate
= vfs_translate_path (vfs_path_as_str (vpath
));
1330 if (translate
!= NULL
)
1334 temp
= subshell_name_quote (translate
);
1335 write_all (mc_global
.tty
.subshell_pty
, temp
->str
, temp
->len
);
1336 g_string_free (temp
, TRUE
);
1340 write_all (mc_global
.tty
.subshell_pty
, ".", 1);
1345 write_all (mc_global
.tty
.subshell_pty
, "/", 1);
1347 write_all (mc_global
.tty
.subshell_pty
, "\n", 1);
1349 subshell_state
= RUNNING_COMMAND
;
1350 feed_subshell (QUIETLY
, FALSE
);
1354 gboolean bPathNotEq
;
1356 bPathNotEq
= strcmp (subshell_cwd
, pcwd
) != 0;
1358 if (bPathNotEq
&& mc_global
.shell
->type
== SHELL_TCSH
)
1360 char rp_subshell_cwd
[PATH_MAX
];
1361 char rp_current_panel_cwd
[PATH_MAX
];
1362 char *p_subshell_cwd
, *p_current_panel_cwd
;
1364 p_subshell_cwd
= mc_realpath (subshell_cwd
, rp_subshell_cwd
);
1365 p_current_panel_cwd
= mc_realpath (pcwd
, rp_current_panel_cwd
);
1367 if (p_subshell_cwd
== NULL
)
1368 p_subshell_cwd
= subshell_cwd
;
1369 if (p_current_panel_cwd
== NULL
)
1370 p_current_panel_cwd
= pcwd
;
1371 bPathNotEq
= strcmp (p_subshell_cwd
, p_current_panel_cwd
) != 0;
1374 if (bPathNotEq
&& !DIR_IS_DOT (pcwd
))
1379 vfs_path_to_str_flags (subshell_get_cwd_from_current_panel (), 0,
1380 VPF_STRIP_PASSWORD
);
1381 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd
);
1386 /* Really escape Zsh history */
1387 if (mc_global
.shell
->type
== SHELL_ZSH
)
1389 /* Per Zsh documentation last command prefixed with space lingers in the internal history
1390 * until the next command is entered before it vanishes. To make it vanish right away,
1391 * type a space and press return. */
1392 write_all (mc_global
.tty
.subshell_pty
, " \n", 2);
1393 subshell_state
= RUNNING_COMMAND
;
1394 feed_subshell (QUIETLY
, FALSE
);
1397 update_subshell_prompt
= FALSE
;
1400 /* Make sure that MC never stores the CWD in a silly format */
1401 /* like /usr////lib/../bin, or the strcmp() above will fail */
1404 /* --------------------------------------------------------------------------------------------- */
1407 subshell_get_console_attributes (void)
1409 /* Get our current terminal modes */
1411 if (tcgetattr (STDOUT_FILENO
, &shell_mode
))
1413 fprintf (stderr
, "Cannot get terminal settings: %s\r\n", unix_error_string (errno
));
1414 mc_global
.tty
.use_subshell
= FALSE
;
1418 /* --------------------------------------------------------------------------------------------- */
1420 * Figure out whether the subshell has stopped, exited or been killed
1421 * Possibly modifies: 'subshell_alive', 'subshell_stopped' and 'quit' */
1424 sigchld_handler (int sig
)
1431 pid
= waitpid (subshell_pid
, &status
, WUNTRACED
| WNOHANG
);
1433 if (pid
== subshell_pid
)
1435 /* Figure out what has happened to the subshell */
1437 if (WIFSTOPPED (status
))
1439 if (WSTOPSIG (status
) == SIGSTOP
)
1441 /* The subshell has received a SIGSTOP signal */
1442 subshell_stopped
= TRUE
;
1446 /* The user has suspended the subshell. Revive it */
1447 kill (subshell_pid
, SIGCONT
);
1452 /* The subshell has either exited normally or been killed */
1453 subshell_alive
= FALSE
;
1454 delete_select_channel (mc_global
.tty
.subshell_pty
);
1455 if (WIFEXITED (status
) && WEXITSTATUS (status
) != FORK_FAILURE
)
1458 subshell_quit
= subshell_get_mainloop_quit () | SUBSHELL_EXIT
; /* Exited normally */
1459 subshell_set_mainloop_quit (subshell_quit
);
1463 subshell_handle_cons_saver ();
1465 /* If we got here, some other child exited; ignore it */
1468 /* --------------------------------------------------------------------------------------------- */