(subshell_prompt): changed to GString.
[midnight-commander.git] / src / subshell.c
blobe5175cec15856d1f05f75ea9713b31f569414a2d
1 /*
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
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/>.
24 /** \file subshell.c
25 * \brief Source: concurrent shell support
28 #include <config.h>
30 #ifndef _GNU_SOURCE
31 #define _GNU_SOURCE 1
32 #endif
34 #include <ctype.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <errno.h>
38 #include <string.h>
39 #include <signal.h>
40 #include <fcntl.h>
41 #include <sys/types.h>
42 #include <sys/wait.h>
43 #ifdef HAVE_SYS_IOCTL_H
44 #include <sys/ioctl.h>
45 #endif
46 #include <termios.h>
47 #include <unistd.h>
49 #ifdef HAVE_STROPTS_H
50 #include <stropts.h> /* For I_PUSH */
51 #endif /* HAVE_STROPTS_H */
53 #include "lib/global.h"
55 #include "lib/tty/tty.h" /* LINES */
56 #include "lib/tty/key.h" /* XCTRL */
57 #include "lib/vfs/vfs.h"
58 #include "lib/strutil.h"
59 #include "lib/mcconfig.h"
60 #include "lib/util.h"
61 #include "lib/widget.h"
63 #include "filemanager/midnight.h" /* current_panel */
65 #include "consaver/cons.saver.h" /* handle_console() */
66 #include "setup.h"
67 #include "subshell.h"
69 /*** global variables ****************************************************************************/
71 /* State of the subshell:
72 * INACTIVE: the default state; awaiting a command
73 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
74 * RUNNING_COMMAND: return to MC when the current command finishes */
75 enum subshell_state_enum subshell_state;
77 /* Holds the latest prompt captured from the subshell */
78 GString *subshell_prompt = NULL;
80 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
81 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
82 gboolean update_subshell_prompt = FALSE;
84 /*** file scope macro definitions ****************************************************************/
86 #ifndef WEXITSTATUS
87 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
88 #endif
90 #ifndef WIFEXITED
91 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
92 #endif
94 #ifndef STDIN_FILENO
95 #define STDIN_FILENO 0
96 #endif
98 #ifndef STDOUT_FILENO
99 #define STDOUT_FILENO 1
100 #endif
102 #ifndef STDERR_FILENO
103 #define STDERR_FILENO 2
104 #endif
106 /* Initial length of the buffer for the subshell's prompt */
107 #define INITIAL_PROMPT_SIZE 10
109 /* Used by the child process to indicate failure to start the subshell */
110 #define FORK_FAILURE 69 /* Arbitrary */
112 /* Length of the buffer for all I/O with the subshell */
113 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
115 /*** file scope type declarations ****************************************************************/
117 /* For pipes */
118 enum
120 READ = 0,
121 WRITE = 1
124 /* Subshell type (gleaned from the SHELL environment variable, if available) */
125 static enum
127 BASH,
128 TCSH,
129 ZSH,
130 FISH
131 } subshell_type;
133 /*** file scope variables ************************************************************************/
135 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
136 static char tcsh_fifo[128];
138 static int subshell_pty_slave = -1;
140 /* The key for switching back to MC from the subshell */
141 /* *INDENT-OFF* */
142 static const char subshell_switch_key = XCTRL ('o') & 255;
143 /* *INDENT-ON* */
145 /* For reading/writing on the subshell's pty */
146 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
148 /* To pass CWD info from the subshell to MC */
149 static int subshell_pipe[2];
151 /* The subshell's process ID */
152 static pid_t subshell_pid = 1;
154 /* One extra char for final '\n' */
155 static char subshell_cwd[MC_MAXPATHLEN + 1];
157 /* Flag to indicate whether the subshell is ready for next command */
158 static int subshell_ready;
160 /* The following two flags can be changed by the SIGCHLD handler. This is */
161 /* OK, because the `int' type is updated atomically on all known machines */
162 static volatile int subshell_alive, subshell_stopped;
164 /* We store the terminal's initial mode here so that we can configure
165 the pty similarly, and also so we can restore the real terminal to
166 sanity if we have to exit abruptly */
167 static struct termios shell_mode;
169 /* This is a transparent mode for the terminal where MC is running on */
170 /* It is used when the shell is active, so that the control signals */
171 /* are delivered to the shell pty */
172 static struct termios raw_mode;
174 /* This counter indicates how many characters of prompt we have read */
175 /* FIXME: try to figure out why this had to become global */
176 static int prompt_pos;
179 /*** file scope functions ************************************************************************/
180 /* --------------------------------------------------------------------------------------------- */
182 * Write all data, even if the write() call is interrupted.
185 static ssize_t
186 write_all (int fd, const void *buf, size_t count)
188 ssize_t ret;
189 ssize_t written = 0;
190 while (count > 0)
192 ret = write (fd, (const unsigned char *) buf + written, count);
193 if (ret < 0)
195 if (errno == EINTR)
197 if (mc_global.tty.winch_flag != 0)
198 tty_change_screen_size ();
200 continue;
203 return written > 0 ? written : ret;
205 count -= ret;
206 written += ret;
208 return written;
211 /* --------------------------------------------------------------------------------------------- */
213 * Prepare child process to running the shell and run it.
215 * Modifies the global variables (in the child process only):
216 * shell_mode
218 * Returns: never.
221 static void
222 init_subshell_child (const char *pty_name)
224 char *init_file = NULL;
225 pid_t mc_sid;
227 (void) pty_name;
228 setsid (); /* Get a fresh terminal session */
230 /* Make sure that it has become our controlling terminal */
232 /* Redundant on Linux and probably most systems, but just in case: */
234 #ifdef TIOCSCTTY
235 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
236 #endif
238 /* Configure its terminal modes and window size */
240 /* Set up the pty with the same termios flags as our own tty */
241 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
243 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
244 _exit (FORK_FAILURE);
247 /* Set the pty's size (80x25 by default on Linux) according to the */
248 /* size of the real terminal as calculated by ncurses, if possible */
249 tty_resize (subshell_pty_slave);
251 /* Set up the subshell's environment and init file name */
253 /* It simplifies things to change to our home directory here, */
254 /* and the user's startup file may do a `cd' command anyway */
256 int ret;
257 ret = chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
260 /* Set MC_SID to prevent running one mc from another */
261 mc_sid = getsid (0);
262 if (mc_sid != -1)
264 char sid_str[BUF_SMALL];
265 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
266 putenv (g_strdup (sid_str));
269 switch (subshell_type)
271 case BASH:
272 init_file = mc_config_get_full_path ("bashrc");
274 if (access (init_file, R_OK) == -1)
276 g_free (init_file);
277 init_file = g_strdup (".bashrc");
280 /* Make MC's special commands not show up in bash's history */
281 putenv ((char *) "HISTCONTROL=ignorespace");
283 /* Allow alternative readline settings for MC */
285 char *input_file = mc_config_get_full_path ("inputrc");
286 if (access (input_file, R_OK) == 0)
288 char *putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
289 putenv (putenv_str);
290 g_free (putenv_str);
292 g_free (input_file);
295 break;
297 /* TODO: Find a way to pass initfile to TCSH and ZSH */
298 case TCSH:
299 case ZSH:
300 case FISH:
301 break;
303 default:
304 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
305 _exit (FORK_FAILURE);
308 /* Attach all our standard file descriptors to the pty */
310 /* This is done just before the fork, because stderr must still */
311 /* be connected to the real tty during the above error messages; */
312 /* otherwise the user will never see them. */
314 dup2 (subshell_pty_slave, STDIN_FILENO);
315 dup2 (subshell_pty_slave, STDOUT_FILENO);
316 dup2 (subshell_pty_slave, STDERR_FILENO);
318 close (subshell_pipe[READ]);
319 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
320 /* Close master side of pty. This is important; apart from */
321 /* freeing up the descriptor for use in the subshell, it also */
322 /* means that when MC exits, the subshell will get a SIGHUP and */
323 /* exit too, because there will be no more descriptors pointing */
324 /* at the master side of the pty and so it will disappear. */
325 close (mc_global.tty.subshell_pty);
327 /* Execute the subshell at last */
329 switch (subshell_type)
331 case BASH:
332 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
333 break;
335 case TCSH:
336 execl (shell, "tcsh", (char *) NULL);
337 break;
339 case ZSH:
340 /* Use -g to exclude cmds beginning with space from history
341 * and -Z to use the line editor on non-interactive term */
342 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
344 break;
346 case FISH:
347 execl (shell, "fish", (char *) NULL);
348 break;
351 /* If we get this far, everything failed miserably */
352 g_free (init_file);
353 _exit (FORK_FAILURE);
357 /* --------------------------------------------------------------------------------------------- */
359 * Check MC_SID to prevent running one mc from another.
360 * Return:
361 * 0 if no parent mc in our session was found,
362 * 1 if parent mc was found and the user wants to continue,
363 * 2 if parent mc was found and the user wants to quit mc.
366 static int
367 check_sid (void)
369 pid_t my_sid, old_sid;
370 const char *sid_str;
371 int r;
373 sid_str = getenv ("MC_SID");
374 if (!sid_str)
375 return 0;
377 old_sid = (pid_t) strtol (sid_str, NULL, 0);
378 if (!old_sid)
379 return 0;
381 my_sid = getsid (0);
382 if (my_sid == -1)
383 return 0;
385 /* The parent mc is in a different session, it's OK */
386 if (old_sid != my_sid)
387 return 0;
389 r = query_dialog (_("Warning"),
390 _("GNU Midnight Commander is already\n"
391 "running on this terminal.\n"
392 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
393 if (r != 0)
395 return 2;
398 return 1;
401 /* --------------------------------------------------------------------------------------------- */
403 static void
404 init_raw_mode ()
406 static int initialized = 0;
408 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
409 /* original settings. However, here we need to make this tty very raw, */
410 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
411 /* pty. So, instead of changing the code for execute(), pre_exec(), */
412 /* etc, we just set up the modes we need here, before each command. */
414 if (initialized == 0) /* First time: initialise `raw_mode' */
416 tcgetattr (STDOUT_FILENO, &raw_mode);
417 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
418 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
419 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
420 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
421 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
422 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
423 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
424 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
425 initialized = 1;
429 /* --------------------------------------------------------------------------------------------- */
431 * Wait until the subshell dies or stops. If it stops, make it resume.
432 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
435 static void
436 synchronize (void)
438 sigset_t sigchld_mask, old_mask;
440 sigemptyset (&sigchld_mask);
441 sigaddset (&sigchld_mask, SIGCHLD);
442 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
445 * SIGCHLD should not be blocked, but we unblock it just in case.
446 * This is known to be useful for cygwin 1.3.12 and older.
448 sigdelset (&old_mask, SIGCHLD);
450 /* Wait until the subshell has stopped */
451 while (subshell_alive && !subshell_stopped)
452 sigsuspend (&old_mask);
454 if (subshell_state != ACTIVE)
456 /* Discard all remaining data from stdin to the subshell */
457 tcflush (subshell_pty_slave, TCIFLUSH);
460 subshell_stopped = FALSE;
461 kill (subshell_pid, SIGCONT);
463 sigprocmask (SIG_SETMASK, &old_mask, NULL);
464 /* We can't do any better without modifying the shell(s) */
467 /* --------------------------------------------------------------------------------------------- */
468 /** Feed the subshell our keyboard input until it says it's finished */
470 static gboolean
471 feed_subshell (int how, int fail_on_error)
473 fd_set read_set; /* For `select' */
474 int maxfdp;
475 int bytes; /* For the return value from `read' */
476 int i; /* Loop counter */
478 struct timeval wtime; /* Maximum time we wait for the subshell */
479 struct timeval *wptr;
481 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
482 wtime.tv_sec = 10;
483 wtime.tv_usec = 0;
484 wptr = fail_on_error ? &wtime : NULL;
486 while (TRUE)
488 if (!subshell_alive)
489 return FALSE;
491 /* Prepare the file-descriptor set and call `select' */
493 FD_ZERO (&read_set);
494 FD_SET (mc_global.tty.subshell_pty, &read_set);
495 FD_SET (subshell_pipe[READ], &read_set);
496 maxfdp = max (mc_global.tty.subshell_pty, subshell_pipe[READ]);
497 if (how == VISIBLY)
499 FD_SET (STDIN_FILENO, &read_set);
500 maxfdp = max (maxfdp, STDIN_FILENO);
503 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
505 /* Despite using SA_RESTART, we still have to check for this */
506 if (errno == EINTR)
508 if (mc_global.tty.winch_flag != 0)
509 tty_change_screen_size ();
511 continue; /* try all over again */
513 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
514 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
515 unix_error_string (errno));
516 exit (EXIT_FAILURE);
519 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
520 /* Read from the subshell, write to stdout */
522 /* This loop improves performance by reducing context switches
523 by a factor of 20 or so... unfortunately, it also hangs MC
524 randomly, because of an apparent Linux bug. Investigate. */
525 /* for (i=0; i<5; ++i) * FIXME -- experimental */
527 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
529 /* The subshell has died */
530 if (bytes == -1 && errno == EIO && !subshell_alive)
531 return FALSE;
533 if (bytes <= 0)
535 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
536 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
537 exit (EXIT_FAILURE);
540 if (how == VISIBLY)
541 write_all (STDOUT_FILENO, pty_buffer, bytes);
544 else if (FD_ISSET (subshell_pipe[READ], &read_set))
545 /* Read the subshell's CWD and capture its prompt */
547 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
548 if (bytes <= 0)
550 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
551 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
552 unix_error_string (errno));
553 exit (EXIT_FAILURE);
556 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
558 synchronize ();
560 subshell_ready = TRUE;
561 if (subshell_state == RUNNING_COMMAND)
563 subshell_state = INACTIVE;
564 return TRUE;
568 else if (FD_ISSET (STDIN_FILENO, &read_set))
569 /* Read from stdin, write to the subshell */
571 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
572 if (bytes <= 0)
574 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
575 fprintf (stderr,
576 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
577 exit (EXIT_FAILURE);
580 for (i = 0; i < bytes; ++i)
581 if (pty_buffer[i] == subshell_switch_key)
583 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
584 if (subshell_ready)
585 subshell_state = INACTIVE;
586 return TRUE;
589 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
591 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
592 subshell_ready = FALSE;
594 else
595 return FALSE;
599 /* --------------------------------------------------------------------------------------------- */
600 /* pty opening functions */
602 #ifdef HAVE_GRANTPT
604 /* System V version of pty_open_master */
606 static int
607 pty_open_master (char *pty_name)
609 char *slave_name;
610 int pty_master;
612 #ifdef HAVE_POSIX_OPENPT
613 pty_master = posix_openpt (O_RDWR);
614 #elif HAVE_GETPT
615 /* getpt () is a GNU extension (glibc 2.1.x) */
616 pty_master = getpt ();
617 #elif IS_AIX
618 strcpy (pty_name, "/dev/ptc");
619 pty_master = open (pty_name, O_RDWR);
620 #else
621 strcpy (pty_name, "/dev/ptmx");
622 pty_master = open (pty_name, O_RDWR);
623 #endif
625 if (pty_master == -1)
626 return -1;
628 if (grantpt (pty_master) == -1 /* Grant access to slave */
629 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
630 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
632 close (pty_master);
633 return -1;
635 strcpy (pty_name, slave_name);
636 return pty_master;
639 /* --------------------------------------------------------------------------------------------- */
640 /** System V version of pty_open_slave */
642 static int
643 pty_open_slave (const char *pty_name)
645 int pty_slave = open (pty_name, O_RDWR);
647 if (pty_slave == -1)
649 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
650 return -1;
652 #if !defined(__osf__) && !defined(__linux__)
653 #if defined (I_FIND) && defined (I_PUSH)
654 if (!ioctl (pty_slave, I_FIND, "ptem"))
655 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
657 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
658 pty_slave, unix_error_string (errno));
659 close (pty_slave);
660 return -1;
663 if (!ioctl (pty_slave, I_FIND, "ldterm"))
664 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
666 fprintf (stderr,
667 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
668 pty_slave, unix_error_string (errno));
669 close (pty_slave);
670 return -1;
672 #if !defined(sgi) && !defined(__sgi)
673 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
674 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
676 fprintf (stderr,
677 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
678 pty_slave, unix_error_string (errno));
679 close (pty_slave);
680 return -1;
682 #endif /* sgi || __sgi */
683 #endif /* I_FIND && I_PUSH */
684 #endif /* __osf__ || __linux__ */
686 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
687 return pty_slave;
690 #else /* !HAVE_GRANTPT */
692 /* --------------------------------------------------------------------------------------------- */
693 /** BSD version of pty_open_master */
694 static int
695 pty_open_master (char *pty_name)
697 int pty_master;
698 const char *ptr1, *ptr2;
700 strcpy (pty_name, "/dev/ptyXX");
701 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
703 pty_name[8] = *ptr1;
704 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
706 pty_name[9] = *ptr2;
708 /* Try to open master */
709 pty_master = open (pty_name, O_RDWR);
710 if (pty_master == -1)
712 if (errno == ENOENT) /* Different from EIO */
713 return -1; /* Out of pty devices */
714 continue; /* Try next pty device */
716 pty_name[5] = 't'; /* Change "pty" to "tty" */
717 if (access (pty_name, 6) != 0)
719 close (pty_master);
720 pty_name[5] = 'p';
721 continue;
723 return pty_master;
726 return -1; /* Ran out of pty devices */
729 /* --------------------------------------------------------------------------------------------- */
730 /** BSD version of pty_open_slave */
732 static int
733 pty_open_slave (const char *pty_name)
735 int pty_slave;
736 struct group *group_info = getgrnam ("tty");
738 if (group_info != NULL)
740 /* The following two calls will only succeed if we are root */
741 /* [Commented out while permissions problem is investigated] */
742 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
743 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
745 pty_slave = open (pty_name, O_RDWR);
746 if (pty_slave == -1)
747 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
748 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
749 return pty_slave;
751 #endif /* !HAVE_GRANTPT */
753 /* --------------------------------------------------------------------------------------------- */
754 /*** public functions ****************************************************************************/
755 /* --------------------------------------------------------------------------------------------- */
757 /* --------------------------------------------------------------------------------------------- */
759 * Fork the subshell, and set up many, many things.
761 * Possibly modifies the global variables:
762 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
763 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
764 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
767 void
768 init_subshell (void)
770 /* This must be remembered across calls to init_subshell() */
771 static char pty_name[BUF_SMALL];
772 char precmd[BUF_SMALL];
774 switch (check_sid ())
776 case 1:
777 mc_global.tty.use_subshell = FALSE;
778 return;
779 case 2:
780 mc_global.tty.use_subshell = FALSE;
781 mc_global.midnight_shutdown = TRUE;
782 return;
785 /* Take the current (hopefully pristine) tty mode and make */
786 /* a raw mode based on it now, before we do anything else with it */
787 init_raw_mode ();
789 if (mc_global.tty.subshell_pty == 0)
790 { /* First time through */
791 /* Find out what type of shell we have */
793 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
794 subshell_type = ZSH;
795 else if (strstr (shell, "/tcsh"))
796 subshell_type = TCSH;
797 else if (strstr (shell, "/csh"))
798 subshell_type = TCSH;
799 else if (strstr (shell, "/bash") || getenv ("BASH"))
800 subshell_type = BASH;
801 else if (strstr (shell, "/fish"))
802 subshell_type = FISH;
803 else
805 mc_global.tty.use_subshell = FALSE;
806 return;
809 /* Open a pty for talking to the subshell */
811 /* FIXME: We may need to open a fresh pty each time on SVR4 */
813 mc_global.tty.subshell_pty = pty_open_master (pty_name);
814 if (mc_global.tty.subshell_pty == -1)
816 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
817 mc_global.tty.use_subshell = FALSE;
818 return;
820 subshell_pty_slave = pty_open_slave (pty_name);
821 if (subshell_pty_slave == -1)
823 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
824 pty_name, unix_error_string (errno));
825 mc_global.tty.use_subshell = FALSE;
826 return;
829 /* Create a pipe for receiving the subshell's CWD */
831 if (subshell_type == TCSH)
833 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
834 mc_tmpdir (), (int) getpid ());
835 if (mkfifo (tcsh_fifo, 0600) == -1)
837 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
838 mc_global.tty.use_subshell = FALSE;
839 return;
842 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
844 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
845 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
847 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
848 perror (__FILE__ ": open");
849 mc_global.tty.use_subshell = FALSE;
850 return;
853 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
855 perror (__FILE__ ": couldn't create pipe");
856 mc_global.tty.use_subshell = FALSE;
857 return;
861 /* Fork the subshell */
863 subshell_alive = TRUE;
864 subshell_stopped = FALSE;
865 subshell_pid = fork ();
867 if (subshell_pid == -1)
869 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
870 /* We exit here because, if the process table is full, the */
871 /* other method of running user commands won't work either */
872 exit (EXIT_FAILURE);
875 if (subshell_pid == 0)
877 /* We are in the child process */
878 init_subshell_child (pty_name);
881 /* Set up `precmd' or equivalent for reading the subshell's CWD */
883 switch (subshell_type)
885 case BASH:
886 g_snprintf (precmd, sizeof (precmd),
887 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
888 break;
890 case ZSH:
891 g_snprintf (precmd, sizeof (precmd),
892 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
893 break;
895 case TCSH:
896 g_snprintf (precmd, sizeof (precmd),
897 "set echo_style=both;"
898 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
899 break;
900 case FISH:
901 g_snprintf (precmd, sizeof (precmd),
902 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
903 subshell_pipe[WRITE]);
904 break;
907 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
909 /* Wait until the subshell has started up and processed the command */
911 subshell_state = RUNNING_COMMAND;
912 tty_enable_interrupt_key ();
913 if (!feed_subshell (QUIETLY, TRUE))
915 mc_global.tty.use_subshell = FALSE;
917 tty_disable_interrupt_key ();
918 if (!subshell_alive)
919 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
922 /* --------------------------------------------------------------------------------------------- */
925 invoke_subshell (const char *command, int how, vfs_path_t ** new_dir_vpath)
927 char *pcwd;
929 /* Make the MC terminal transparent */
930 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
932 /* Make the subshell change to MC's working directory */
933 if (new_dir_vpath != NULL)
934 do_subshell_chdir (current_panel->cwd_vpath, TRUE, TRUE);
936 if (command == NULL) /* The user has done "C-o" from MC */
938 if (subshell_state == INACTIVE)
940 subshell_state = ACTIVE;
941 /* FIXME: possibly take out this hack; the user can
942 re-play it by hitting C-hyphen a few times! */
943 if (subshell_ready)
944 write_all (mc_global.tty.subshell_pty, " \b", 2); /* Hack to make prompt reappear */
947 else /* MC has passed us a user command */
949 if (how == QUIETLY)
950 write_all (mc_global.tty.subshell_pty, " ", 1);
951 /* FIXME: if command is long (>8KB ?) we go comma */
952 write_all (mc_global.tty.subshell_pty, command, strlen (command));
953 write_all (mc_global.tty.subshell_pty, "\n", 1);
954 subshell_state = RUNNING_COMMAND;
955 subshell_ready = FALSE;
958 feed_subshell (how, FALSE);
961 char *cwd_str;
963 cwd_str = vfs_path_to_str (current_panel->cwd_vpath);
964 pcwd = vfs_translate_path_n (cwd_str);
965 g_free (cwd_str);
968 if (new_dir_vpath != NULL && subshell_alive && strcmp (subshell_cwd, pcwd))
969 *new_dir_vpath = vfs_path_from_str (subshell_cwd); /* Make MC change to the subshell's CWD */
970 g_free (pcwd);
972 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
973 while (!subshell_alive && quit == 0 && mc_global.tty.use_subshell)
974 init_subshell ();
976 prompt_pos = 0;
978 return quit;
982 /* --------------------------------------------------------------------------------------------- */
984 gboolean
985 read_subshell_prompt (void)
987 int rc = 0;
988 ssize_t bytes = 0;
989 struct timeval timeleft = { 0, 0 };
991 fd_set tmp;
992 FD_ZERO (&tmp);
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 while (subshell_alive
1000 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)) != 0)
1002 ssize_t i;
1004 /* Check for `select' errors */
1005 if (rc == -1)
1007 if (errno == EINTR)
1009 if (mc_global.tty.winch_flag != 0)
1010 tty_change_screen_size ();
1012 continue;
1015 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1016 exit (EXIT_FAILURE);
1019 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1021 /* Extract the prompt from the shell output */
1022 g_string_set_size (subshell_prompt, 0);
1023 for (i = 0; i < bytes; i++)
1024 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1025 g_string_set_size (subshell_prompt, 0);
1026 else if (pty_buffer[i] != '\0')
1027 g_string_append_c (subshell_prompt, pty_buffer[i]);
1030 return (rc != 0 || bytes != 0);
1033 /* --------------------------------------------------------------------------------------------- */
1035 void
1036 do_update_prompt (void)
1038 if (update_subshell_prompt)
1040 printf ("\r\n%s", subshell_prompt->str);
1041 fflush (stdout);
1042 update_subshell_prompt = FALSE;
1046 /* --------------------------------------------------------------------------------------------- */
1048 gboolean
1049 exit_subshell (void)
1051 gboolean subshell_quit = TRUE;
1053 if (subshell_state != INACTIVE && subshell_alive)
1054 subshell_quit =
1055 query_dialog (_("Warning"),
1056 _("The shell is still active. Quit anyway?"),
1057 D_NORMAL, 2, _("&Yes"), _("&No")) == 0;
1059 if (subshell_quit)
1061 if (subshell_type == TCSH)
1063 if (unlink (tcsh_fifo) == -1)
1064 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1065 tcsh_fifo, unix_error_string (errno));
1068 g_string_free (subshell_prompt, TRUE);
1069 subshell_prompt = NULL;
1070 pty_buffer[0] = '\0';
1073 return subshell_quit;
1076 /* --------------------------------------------------------------------------------------------- */
1078 * Carefully quote directory name to allow entering any directory safely,
1079 * no matter what weird characters it may contain in its name.
1080 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1081 * executing any commands in the shell. Escape all control characters.
1082 * Use following technique:
1084 * printf(1) with format string containing a single conversion specifier,
1085 * "b", and an argument which contains a copy of the string passed to
1086 * subshell_name_quote() with all characters, except digits and letters,
1087 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1088 * numeric value of the character converted to octal number.
1090 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1094 static char *
1095 subshell_name_quote (const char *s)
1097 char *ret, *d;
1098 const char *su, *n;
1099 const char *quote_cmd_start, *quote_cmd_end;
1100 int c;
1102 if (subshell_type == FISH)
1104 quote_cmd_start = "(printf \"%b\" '";
1105 quote_cmd_end = "')";
1107 else
1109 quote_cmd_start = "\"`printf \"%b\" '";
1110 quote_cmd_end = "'`\"";
1113 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1114 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
1115 + (strlen (quote_cmd_end)));
1116 if (d == NULL)
1117 return NULL;
1119 /* Prevent interpreting leading `-' as a switch for `cd' */
1120 if (*s == '-')
1122 *d++ = '.';
1123 *d++ = '/';
1126 /* Copy the beginning of the command to the buffer */
1127 strcpy (d, quote_cmd_start);
1128 d += strlen (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 su = s;
1136 for (; su[0] != '\0';)
1138 n = str_cget_next_char_safe (su);
1139 if (str_isalnum (su))
1141 memcpy (d, su, n - su);
1142 d += n - su;
1144 else
1146 for (c = 0; c < n - su; c++)
1148 sprintf (d, "\\0%03o", (unsigned char) su[c]);
1149 d += 5;
1152 su = n;
1155 strcpy (d, quote_cmd_end);
1157 return ret;
1161 /* --------------------------------------------------------------------------------------------- */
1163 /** If it actually changed the directory it returns true */
1164 void
1165 do_subshell_chdir (const vfs_path_t * vpath, gboolean update_prompt, gboolean reset_prompt)
1167 char *pcwd;
1168 char *temp;
1169 char *directory;
1171 pcwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_RECODE);
1173 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1175 /* We have to repaint the subshell prompt if we read it from
1176 * the main program. Please note that in the code after this
1177 * if, the cd command that is sent will make the subshell
1178 * repaint the prompt, so we don't have to paint it. */
1179 if (update_prompt)
1180 do_update_prompt ();
1181 g_free (pcwd);
1182 return;
1185 /* The initial space keeps this out of the command history (in bash
1186 because we set "HISTCONTROL=ignorespace") */
1187 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1189 directory = vfs_path_to_str (vpath);
1190 if (directory != '\0')
1192 char *translate;
1194 translate = vfs_translate_path_n (directory);
1195 if (translate != NULL)
1197 temp = subshell_name_quote (translate);
1198 if (temp)
1200 write_all (mc_global.tty.subshell_pty, temp, strlen (temp));
1201 g_free (temp);
1203 else
1205 /* Should not happen unless the directory name is so long
1206 that we don't have memory to quote it. */
1207 write_all (mc_global.tty.subshell_pty, ".", 1);
1209 g_free (translate);
1211 else
1213 write_all (mc_global.tty.subshell_pty, ".", 1);
1216 else
1218 write_all (mc_global.tty.subshell_pty, "/", 1);
1220 g_free (directory);
1221 write_all (mc_global.tty.subshell_pty, "\n", 1);
1223 subshell_state = RUNNING_COMMAND;
1224 feed_subshell (QUIETLY, FALSE);
1226 if (subshell_alive)
1228 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1230 if (bPathNotEq && subshell_type == TCSH)
1232 char rp_subshell_cwd[PATH_MAX];
1233 char rp_current_panel_cwd[PATH_MAX];
1235 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1236 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1238 if (p_subshell_cwd == NULL)
1239 p_subshell_cwd = subshell_cwd;
1240 if (p_current_panel_cwd == NULL)
1241 p_current_panel_cwd = pcwd;
1242 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1245 if (bPathNotEq && strcmp (pcwd, ".") != 0)
1247 char *cwd;
1249 cwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_STRIP_PASSWORD);
1250 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd);
1251 g_free (cwd);
1255 if (reset_prompt)
1256 prompt_pos = 0;
1257 update_subshell_prompt = FALSE;
1259 g_free (pcwd);
1260 /* Make sure that MC never stores the CWD in a silly format */
1261 /* like /usr////lib/../bin, or the strcmp() above will fail */
1264 /* --------------------------------------------------------------------------------------------- */
1266 void
1267 subshell_get_console_attributes (void)
1269 /* Get our current terminal modes */
1271 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1273 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1274 mc_global.tty.use_subshell = FALSE;
1278 /* --------------------------------------------------------------------------------------------- */
1280 * Figure out whether the subshell has stopped, exited or been killed
1281 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1283 void
1284 sigchld_handler (int sig)
1286 int status;
1287 pid_t pid;
1289 (void) sig;
1291 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1293 if (pid == subshell_pid)
1295 /* Figure out what has happened to the subshell */
1297 if (WIFSTOPPED (status))
1299 if (WSTOPSIG (status) == SIGSTOP)
1301 /* The subshell has received a SIGSTOP signal */
1302 subshell_stopped = TRUE;
1304 else
1306 /* The user has suspended the subshell. Revive it */
1307 kill (subshell_pid, SIGCONT);
1310 else
1312 /* The subshell has either exited normally or been killed */
1313 subshell_alive = FALSE;
1314 delete_select_channel (mc_global.tty.subshell_pty);
1315 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1316 quit |= SUBSHELL_EXIT; /* Exited normally */
1319 #ifdef __linux__
1320 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1322 if (pid == cons_saver_pid)
1325 if (WIFSTOPPED (status))
1326 /* Someone has stopped cons.saver - restart it */
1327 kill (pid, SIGCONT);
1328 else
1330 /* cons.saver has died - disable confole saving */
1331 handle_console (CONSOLE_DONE);
1332 mc_global.tty.console_flag = '\0';
1336 #endif /* __linux__ */
1338 /* If we got here, some other child exited; ignore it */
1341 /* --------------------------------------------------------------------------------------------- */