b557ded5b26afd71d05adae69d7beea655ce88a0
[midnight-commander.git] / src / subshell.c
blobb557ded5b26afd71d05adae69d7beea655ce88a0
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 char *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 continue;
199 else
201 return written > 0 ? written : ret;
204 count -= ret;
205 written += ret;
207 return written;
210 /* --------------------------------------------------------------------------------------------- */
212 * Prepare child process to running the shell and run it.
214 * Modifies the global variables (in the child process only):
215 * shell_mode
217 * Returns: never.
220 static void
221 init_subshell_child (const char *pty_name)
223 char *init_file = NULL;
224 pid_t mc_sid;
226 (void) pty_name;
227 setsid (); /* Get a fresh terminal session */
229 /* Make sure that it has become our controlling terminal */
231 /* Redundant on Linux and probably most systems, but just in case: */
233 #ifdef TIOCSCTTY
234 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
235 #endif
237 /* Configure its terminal modes and window size */
239 /* Set up the pty with the same termios flags as our own tty */
240 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
242 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
243 _exit (FORK_FAILURE);
246 /* Set the pty's size (80x25 by default on Linux) according to the */
247 /* size of the real terminal as calculated by ncurses, if possible */
248 tty_resize (subshell_pty_slave);
250 /* Set up the subshell's environment and init file name */
252 /* It simplifies things to change to our home directory here, */
253 /* and the user's startup file may do a `cd' command anyway */
255 int ret;
256 ret = chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
259 /* Set MC_SID to prevent running one mc from another */
260 mc_sid = getsid (0);
261 if (mc_sid != -1)
263 char sid_str[BUF_SMALL];
264 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
265 putenv (g_strdup (sid_str));
268 switch (subshell_type)
270 case BASH:
271 init_file = mc_config_get_full_path ("bashrc");
273 if (access (init_file, R_OK) == -1)
275 g_free (init_file);
276 init_file = g_strdup (".bashrc");
279 /* Make MC's special commands not show up in bash's history */
280 putenv ((char *) "HISTCONTROL=ignorespace");
282 /* Allow alternative readline settings for MC */
284 char *input_file = mc_config_get_full_path ("inputrc");
285 if (access (input_file, R_OK) == 0)
287 char *putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
288 putenv (putenv_str);
289 g_free (putenv_str);
291 g_free (input_file);
294 break;
296 /* TODO: Find a way to pass initfile to TCSH and ZSH */
297 case TCSH:
298 case ZSH:
299 case FISH:
300 break;
302 default:
303 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
304 _exit (FORK_FAILURE);
307 /* Attach all our standard file descriptors to the pty */
309 /* This is done just before the fork, because stderr must still */
310 /* be connected to the real tty during the above error messages; */
311 /* otherwise the user will never see them. */
313 dup2 (subshell_pty_slave, STDIN_FILENO);
314 dup2 (subshell_pty_slave, STDOUT_FILENO);
315 dup2 (subshell_pty_slave, STDERR_FILENO);
317 close (subshell_pipe[READ]);
318 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
319 /* Close master side of pty. This is important; apart from */
320 /* freeing up the descriptor for use in the subshell, it also */
321 /* means that when MC exits, the subshell will get a SIGHUP and */
322 /* exit too, because there will be no more descriptors pointing */
323 /* at the master side of the pty and so it will disappear. */
324 close (mc_global.tty.subshell_pty);
326 /* Execute the subshell at last */
328 switch (subshell_type)
330 case BASH:
331 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
332 break;
334 case TCSH:
335 execl (shell, "tcsh", (char *) NULL);
336 break;
338 case ZSH:
339 /* Use -g to exclude cmds beginning with space from history
340 * and -Z to use the line editor on non-interactive term */
341 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
343 break;
345 case FISH:
346 execl (shell, "fish", (char *) NULL);
347 break;
350 /* If we get this far, everything failed miserably */
351 g_free (init_file);
352 _exit (FORK_FAILURE);
356 /* --------------------------------------------------------------------------------------------- */
358 * Check MC_SID to prevent running one mc from another.
359 * Return:
360 * 0 if no parent mc in our session was found,
361 * 1 if parent mc was found and the user wants to continue,
362 * 2 if parent mc was found and the user wants to quit mc.
365 static int
366 check_sid (void)
368 pid_t my_sid, old_sid;
369 const char *sid_str;
370 int r;
372 sid_str = getenv ("MC_SID");
373 if (!sid_str)
374 return 0;
376 old_sid = (pid_t) strtol (sid_str, NULL, 0);
377 if (!old_sid)
378 return 0;
380 my_sid = getsid (0);
381 if (my_sid == -1)
382 return 0;
384 /* The parent mc is in a different session, it's OK */
385 if (old_sid != my_sid)
386 return 0;
388 r = query_dialog (_("Warning"),
389 _("GNU Midnight Commander is already\n"
390 "running on this terminal.\n"
391 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
392 if (r != 0)
394 return 2;
397 return 1;
400 /* --------------------------------------------------------------------------------------------- */
402 static void
403 init_raw_mode ()
405 static int initialized = 0;
407 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
408 /* original settings. However, here we need to make this tty very raw, */
409 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
410 /* pty. So, instead of changing the code for execute(), pre_exec(), */
411 /* etc, we just set up the modes we need here, before each command. */
413 if (initialized == 0) /* First time: initialise `raw_mode' */
415 tcgetattr (STDOUT_FILENO, &raw_mode);
416 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
417 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
418 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
419 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
420 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
421 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
422 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
423 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
424 initialized = 1;
428 /* --------------------------------------------------------------------------------------------- */
430 * Wait until the subshell dies or stops. If it stops, make it resume.
431 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
434 static void
435 synchronize (void)
437 sigset_t sigchld_mask, old_mask;
439 sigemptyset (&sigchld_mask);
440 sigaddset (&sigchld_mask, SIGCHLD);
441 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
444 * SIGCHLD should not be blocked, but we unblock it just in case.
445 * This is known to be useful for cygwin 1.3.12 and older.
447 sigdelset (&old_mask, SIGCHLD);
449 /* Wait until the subshell has stopped */
450 while (subshell_alive && !subshell_stopped)
451 sigsuspend (&old_mask);
453 if (subshell_state != ACTIVE)
455 /* Discard all remaining data from stdin to the subshell */
456 tcflush (subshell_pty_slave, TCIFLUSH);
459 subshell_stopped = FALSE;
460 kill (subshell_pid, SIGCONT);
462 sigprocmask (SIG_SETMASK, &old_mask, NULL);
463 /* We can't do any better without modifying the shell(s) */
466 /* --------------------------------------------------------------------------------------------- */
467 /** Feed the subshell our keyboard input until it says it's finished */
469 static gboolean
470 feed_subshell (int how, int fail_on_error)
472 fd_set read_set; /* For `select' */
473 int maxfdp;
474 int bytes; /* For the return value from `read' */
475 int i; /* Loop counter */
477 struct timeval wtime; /* Maximum time we wait for the subshell */
478 struct timeval *wptr;
480 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
481 wtime.tv_sec = 10;
482 wtime.tv_usec = 0;
483 wptr = fail_on_error ? &wtime : NULL;
485 while (TRUE)
487 if (!subshell_alive)
488 return FALSE;
490 /* Prepare the file-descriptor set and call `select' */
492 FD_ZERO (&read_set);
493 FD_SET (mc_global.tty.subshell_pty, &read_set);
494 FD_SET (subshell_pipe[READ], &read_set);
495 maxfdp = max (mc_global.tty.subshell_pty, subshell_pipe[READ]);
496 if (how == VISIBLY)
498 FD_SET (STDIN_FILENO, &read_set);
499 maxfdp = max (maxfdp, STDIN_FILENO);
502 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)
507 continue; /* try all over again */
508 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
509 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
510 unix_error_string (errno));
511 exit (EXIT_FAILURE);
514 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
515 /* Read from the subshell, write to stdout */
517 /* This loop improves performance by reducing context switches
518 by a factor of 20 or so... unfortunately, it also hangs MC
519 randomly, because of an apparent Linux bug. Investigate. */
520 /* for (i=0; i<5; ++i) * FIXME -- experimental */
522 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
524 /* The subshell has died */
525 if (bytes == -1 && errno == EIO && !subshell_alive)
526 return FALSE;
528 if (bytes <= 0)
530 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
531 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
532 exit (EXIT_FAILURE);
535 if (how == VISIBLY)
536 write_all (STDOUT_FILENO, pty_buffer, bytes);
539 else if (FD_ISSET (subshell_pipe[READ], &read_set))
540 /* Read the subshell's CWD and capture its prompt */
542 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
543 if (bytes <= 0)
545 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
546 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
547 unix_error_string (errno));
548 exit (EXIT_FAILURE);
551 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
553 synchronize ();
555 subshell_ready = TRUE;
556 if (subshell_state == RUNNING_COMMAND)
558 subshell_state = INACTIVE;
559 return TRUE;
563 else if (FD_ISSET (STDIN_FILENO, &read_set))
564 /* Read from stdin, write to the subshell */
566 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
567 if (bytes <= 0)
569 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
570 fprintf (stderr,
571 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
572 exit (EXIT_FAILURE);
575 for (i = 0; i < bytes; ++i)
576 if (pty_buffer[i] == subshell_switch_key)
578 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
579 if (subshell_ready)
580 subshell_state = INACTIVE;
581 return TRUE;
584 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
586 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
587 subshell_ready = FALSE;
589 else
590 return FALSE;
594 /* --------------------------------------------------------------------------------------------- */
595 /* pty opening functions */
597 #ifdef HAVE_GRANTPT
599 /* System V version of pty_open_master */
601 static int
602 pty_open_master (char *pty_name)
604 char *slave_name;
605 int pty_master;
607 #ifdef HAVE_POSIX_OPENPT
608 pty_master = posix_openpt (O_RDWR);
609 #elif HAVE_GETPT
610 /* getpt () is a GNU extension (glibc 2.1.x) */
611 pty_master = getpt ();
612 #elif IS_AIX
613 strcpy (pty_name, "/dev/ptc");
614 pty_master = open (pty_name, O_RDWR);
615 #else
616 strcpy (pty_name, "/dev/ptmx");
617 pty_master = open (pty_name, O_RDWR);
618 #endif
620 if (pty_master == -1)
621 return -1;
623 if (grantpt (pty_master) == -1 /* Grant access to slave */
624 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
625 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
627 close (pty_master);
628 return -1;
630 strcpy (pty_name, slave_name);
631 return pty_master;
634 /* --------------------------------------------------------------------------------------------- */
635 /** System V version of pty_open_slave */
637 static int
638 pty_open_slave (const char *pty_name)
640 int pty_slave = open (pty_name, O_RDWR);
642 if (pty_slave == -1)
644 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
645 return -1;
647 #if !defined(__osf__) && !defined(__linux__)
648 #if defined (I_FIND) && defined (I_PUSH)
649 if (!ioctl (pty_slave, I_FIND, "ptem"))
650 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
652 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
653 pty_slave, unix_error_string (errno));
654 close (pty_slave);
655 return -1;
658 if (!ioctl (pty_slave, I_FIND, "ldterm"))
659 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
661 fprintf (stderr,
662 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
663 pty_slave, unix_error_string (errno));
664 close (pty_slave);
665 return -1;
667 #if !defined(sgi) && !defined(__sgi)
668 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
669 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
671 fprintf (stderr,
672 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
673 pty_slave, unix_error_string (errno));
674 close (pty_slave);
675 return -1;
677 #endif /* sgi || __sgi */
678 #endif /* I_FIND && I_PUSH */
679 #endif /* __osf__ || __linux__ */
681 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
682 return pty_slave;
685 #else /* !HAVE_GRANTPT */
687 /* --------------------------------------------------------------------------------------------- */
688 /** BSD version of pty_open_master */
689 static int
690 pty_open_master (char *pty_name)
692 int pty_master;
693 const char *ptr1, *ptr2;
695 strcpy (pty_name, "/dev/ptyXX");
696 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
698 pty_name[8] = *ptr1;
699 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
701 pty_name[9] = *ptr2;
703 /* Try to open master */
704 pty_master = open (pty_name, O_RDWR);
705 if (pty_master == -1)
707 if (errno == ENOENT) /* Different from EIO */
708 return -1; /* Out of pty devices */
709 continue; /* Try next pty device */
711 pty_name[5] = 't'; /* Change "pty" to "tty" */
712 if (access (pty_name, 6) != 0)
714 close (pty_master);
715 pty_name[5] = 'p';
716 continue;
718 return pty_master;
721 return -1; /* Ran out of pty devices */
724 /* --------------------------------------------------------------------------------------------- */
725 /** BSD version of pty_open_slave */
727 static int
728 pty_open_slave (const char *pty_name)
730 int pty_slave;
731 struct group *group_info = getgrnam ("tty");
733 if (group_info != NULL)
735 /* The following two calls will only succeed if we are root */
736 /* [Commented out while permissions problem is investigated] */
737 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
738 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
740 pty_slave = open (pty_name, O_RDWR);
741 if (pty_slave == -1)
742 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
743 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
744 return pty_slave;
746 #endif /* !HAVE_GRANTPT */
748 /* --------------------------------------------------------------------------------------------- */
749 /*** public functions ****************************************************************************/
750 /* --------------------------------------------------------------------------------------------- */
752 /* --------------------------------------------------------------------------------------------- */
754 * Fork the subshell, and set up many, many things.
756 * Possibly modifies the global variables:
757 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
758 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
759 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
762 void
763 init_subshell (void)
765 /* This must be remembered across calls to init_subshell() */
766 static char pty_name[BUF_SMALL];
767 char precmd[BUF_SMALL];
769 switch (check_sid ())
771 case 1:
772 mc_global.tty.use_subshell = FALSE;
773 return;
774 case 2:
775 mc_global.tty.use_subshell = FALSE;
776 mc_global.midnight_shutdown = TRUE;
777 return;
780 /* Take the current (hopefully pristine) tty mode and make */
781 /* a raw mode based on it now, before we do anything else with it */
782 init_raw_mode ();
784 if (mc_global.tty.subshell_pty == 0)
785 { /* First time through */
786 /* Find out what type of shell we have */
788 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
789 subshell_type = ZSH;
790 else if (strstr (shell, "/tcsh"))
791 subshell_type = TCSH;
792 else if (strstr (shell, "/csh"))
793 subshell_type = TCSH;
794 else if (strstr (shell, "/bash") || getenv ("BASH"))
795 subshell_type = BASH;
796 else if (strstr (shell, "/fish"))
797 subshell_type = FISH;
798 else
800 mc_global.tty.use_subshell = FALSE;
801 return;
804 /* Open a pty for talking to the subshell */
806 /* FIXME: We may need to open a fresh pty each time on SVR4 */
808 mc_global.tty.subshell_pty = pty_open_master (pty_name);
809 if (mc_global.tty.subshell_pty == -1)
811 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
812 mc_global.tty.use_subshell = FALSE;
813 return;
815 subshell_pty_slave = pty_open_slave (pty_name);
816 if (subshell_pty_slave == -1)
818 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
819 pty_name, unix_error_string (errno));
820 mc_global.tty.use_subshell = FALSE;
821 return;
824 /* Create a pipe for receiving the subshell's CWD */
826 if (subshell_type == TCSH)
828 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
829 mc_tmpdir (), (int) getpid ());
830 if (mkfifo (tcsh_fifo, 0600) == -1)
832 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
833 mc_global.tty.use_subshell = FALSE;
834 return;
837 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
839 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
840 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
842 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
843 perror (__FILE__ ": open");
844 mc_global.tty.use_subshell = FALSE;
845 return;
848 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
850 perror (__FILE__ ": couldn't create pipe");
851 mc_global.tty.use_subshell = FALSE;
852 return;
856 /* Fork the subshell */
858 subshell_alive = TRUE;
859 subshell_stopped = FALSE;
860 subshell_pid = fork ();
862 if (subshell_pid == -1)
864 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
865 /* We exit here because, if the process table is full, the */
866 /* other method of running user commands won't work either */
867 exit (EXIT_FAILURE);
870 if (subshell_pid == 0)
872 /* We are in the child process */
873 init_subshell_child (pty_name);
876 /* Set up `precmd' or equivalent for reading the subshell's CWD */
878 switch (subshell_type)
880 case BASH:
881 g_snprintf (precmd, sizeof (precmd),
882 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
883 break;
885 case ZSH:
886 g_snprintf (precmd, sizeof (precmd),
887 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
888 break;
890 case TCSH:
891 g_snprintf (precmd, sizeof (precmd),
892 "set echo_style=both;"
893 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
894 break;
895 case FISH:
896 g_snprintf (precmd, sizeof (precmd),
897 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
898 subshell_pipe[WRITE]);
899 break;
902 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
904 /* Wait until the subshell has started up and processed the command */
906 subshell_state = RUNNING_COMMAND;
907 tty_enable_interrupt_key ();
908 if (!feed_subshell (QUIETLY, TRUE))
910 mc_global.tty.use_subshell = FALSE;
912 tty_disable_interrupt_key ();
913 if (!subshell_alive)
914 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
917 /* --------------------------------------------------------------------------------------------- */
920 invoke_subshell (const char *command, int how, vfs_path_t ** new_dir_vpath)
922 char *pcwd;
924 /* Make the MC terminal transparent */
925 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
927 /* Make the subshell change to MC's working directory */
928 if (new_dir_vpath != NULL)
929 do_subshell_chdir (current_panel->cwd_vpath, TRUE, TRUE);
931 if (command == NULL) /* The user has done "C-o" from MC */
933 if (subshell_state == INACTIVE)
935 subshell_state = ACTIVE;
936 /* FIXME: possibly take out this hack; the user can
937 re-play it by hitting C-hyphen a few times! */
938 if (subshell_ready)
939 write_all (mc_global.tty.subshell_pty, " \b", 2); /* Hack to make prompt reappear */
942 else /* MC has passed us a user command */
944 if (how == QUIETLY)
945 write_all (mc_global.tty.subshell_pty, " ", 1);
946 /* FIXME: if command is long (>8KB ?) we go comma */
947 write_all (mc_global.tty.subshell_pty, command, strlen (command));
948 write_all (mc_global.tty.subshell_pty, "\n", 1);
949 subshell_state = RUNNING_COMMAND;
950 subshell_ready = FALSE;
953 feed_subshell (how, FALSE);
956 char *cwd_str;
958 cwd_str = vfs_path_to_str (current_panel->cwd_vpath);
959 pcwd = vfs_translate_path_n (cwd_str);
960 g_free (cwd_str);
963 if (new_dir_vpath != NULL && subshell_alive && strcmp (subshell_cwd, pcwd))
964 *new_dir_vpath = vfs_path_from_str (subshell_cwd); /* Make MC change to the subshell's CWD */
965 g_free (pcwd);
967 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
968 while (!subshell_alive && quit == 0 && mc_global.tty.use_subshell)
969 init_subshell ();
971 prompt_pos = 0;
973 return quit;
977 /* --------------------------------------------------------------------------------------------- */
980 read_subshell_prompt (void)
982 static int prompt_size = INITIAL_PROMPT_SIZE;
983 int bytes = 0, i, rc = 0;
984 struct timeval timeleft = { 0, 0 };
986 fd_set tmp;
987 FD_ZERO (&tmp);
988 FD_SET (mc_global.tty.subshell_pty, &tmp);
990 if (subshell_prompt == NULL)
991 { /* First time through */
992 subshell_prompt = g_malloc (prompt_size);
993 *subshell_prompt = '\0';
994 prompt_pos = 0;
997 while (subshell_alive
998 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)))
1000 /* Check for `select' errors */
1001 if (rc == -1)
1003 if (errno == EINTR)
1004 continue;
1005 else
1007 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1008 exit (EXIT_FAILURE);
1012 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1014 /* Extract the prompt from the shell output */
1016 for (i = 0; i < bytes; ++i)
1017 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1019 prompt_pos = 0;
1021 else
1023 if (!pty_buffer[i])
1024 continue;
1026 subshell_prompt[prompt_pos++] = pty_buffer[i];
1027 if (prompt_pos == prompt_size)
1028 subshell_prompt = g_realloc (subshell_prompt, prompt_size *= 2);
1031 subshell_prompt[prompt_pos] = '\0';
1033 if (rc == 0 && bytes == 0)
1034 return FALSE;
1035 return TRUE;
1038 /* --------------------------------------------------------------------------------------------- */
1040 void
1041 do_update_prompt (void)
1043 if (update_subshell_prompt)
1045 printf ("\r\n%s", subshell_prompt);
1046 fflush (stdout);
1047 update_subshell_prompt = FALSE;
1051 /* --------------------------------------------------------------------------------------------- */
1054 exit_subshell (void)
1056 int subshell_quit = TRUE;
1058 if (subshell_state != INACTIVE && subshell_alive)
1059 subshell_quit =
1060 !query_dialog (_("Warning"),
1061 _("The shell is still active. Quit anyway?"),
1062 D_NORMAL, 2, _("&Yes"), _("&No"));
1064 if (subshell_quit)
1066 if (subshell_type == TCSH)
1068 if (unlink (tcsh_fifo) == -1)
1069 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1070 tcsh_fifo, unix_error_string (errno));
1073 g_free (subshell_prompt);
1074 subshell_prompt = NULL;
1075 pty_buffer[0] = '\0';
1078 return subshell_quit;
1081 /* --------------------------------------------------------------------------------------------- */
1083 * Carefully quote directory name to allow entering any directory safely,
1084 * no matter what weird characters it may contain in its name.
1085 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1086 * executing any commands in the shell. Escape all control characters.
1087 * Use following technique:
1089 * printf(1) with format string containing a single conversion specifier,
1090 * "b", and an argument which contains a copy of the string passed to
1091 * subshell_name_quote() with all characters, except digits and letters,
1092 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1093 * numeric value of the character converted to octal number.
1095 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1099 static char *
1100 subshell_name_quote (const char *s)
1102 char *ret, *d;
1103 const char *su, *n;
1104 const char *quote_cmd_start, *quote_cmd_end;
1105 int c;
1107 if (subshell_type == FISH)
1109 quote_cmd_start = "(printf \"%b\" '";
1110 quote_cmd_end = "')";
1112 else
1114 quote_cmd_start = "\"`printf \"%b\" '";
1115 quote_cmd_end = "'`\"";
1118 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1119 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
1120 + (strlen (quote_cmd_end)));
1121 if (d == NULL)
1122 return NULL;
1124 /* Prevent interpreting leading `-' as a switch for `cd' */
1125 if (*s == '-')
1127 *d++ = '.';
1128 *d++ = '/';
1131 /* Copy the beginning of the command to the buffer */
1132 strcpy (d, quote_cmd_start);
1133 d += strlen (quote_cmd_start);
1136 * Print every character except digits and letters as a backslash-escape
1137 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1138 * character converted to octal number.
1140 su = s;
1141 for (; su[0] != '\0';)
1143 n = str_cget_next_char_safe (su);
1144 if (str_isalnum (su))
1146 memcpy (d, su, n - su);
1147 d += n - su;
1149 else
1151 for (c = 0; c < n - su; c++)
1153 sprintf (d, "\\0%03o", (unsigned char) su[c]);
1154 d += 5;
1157 su = n;
1160 strcpy (d, quote_cmd_end);
1162 return ret;
1166 /* --------------------------------------------------------------------------------------------- */
1168 /** If it actually changed the directory it returns true */
1169 void
1170 do_subshell_chdir (const vfs_path_t * vpath, gboolean update_prompt, gboolean reset_prompt)
1172 char *pcwd;
1173 char *temp;
1174 char *directory;
1176 pcwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_RECODE);
1178 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1180 /* We have to repaint the subshell prompt if we read it from
1181 * the main program. Please note that in the code after this
1182 * if, the cd command that is sent will make the subshell
1183 * repaint the prompt, so we don't have to paint it. */
1184 if (update_prompt)
1185 do_update_prompt ();
1186 g_free (pcwd);
1187 return;
1190 /* The initial space keeps this out of the command history (in bash
1191 because we set "HISTCONTROL=ignorespace") */
1192 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1194 directory = vfs_path_to_str (vpath);
1195 if (directory != '\0')
1197 char *translate;
1199 translate = vfs_translate_path_n (directory);
1200 if (translate != NULL)
1202 temp = subshell_name_quote (translate);
1203 if (temp)
1205 write_all (mc_global.tty.subshell_pty, temp, strlen (temp));
1206 g_free (temp);
1208 else
1210 /* Should not happen unless the directory name is so long
1211 that we don't have memory to quote it. */
1212 write_all (mc_global.tty.subshell_pty, ".", 1);
1214 g_free (translate);
1216 else
1218 write_all (mc_global.tty.subshell_pty, ".", 1);
1221 else
1223 write_all (mc_global.tty.subshell_pty, "/", 1);
1225 g_free (directory);
1226 write_all (mc_global.tty.subshell_pty, "\n", 1);
1228 subshell_state = RUNNING_COMMAND;
1229 feed_subshell (QUIETLY, FALSE);
1231 if (subshell_alive)
1233 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1235 if (bPathNotEq && subshell_type == TCSH)
1237 char rp_subshell_cwd[PATH_MAX];
1238 char rp_current_panel_cwd[PATH_MAX];
1240 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1241 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1243 if (p_subshell_cwd == NULL)
1244 p_subshell_cwd = subshell_cwd;
1245 if (p_current_panel_cwd == NULL)
1246 p_current_panel_cwd = pcwd;
1247 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1250 if (bPathNotEq && strcmp (pcwd, ".") != 0)
1252 char *cwd;
1254 cwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_STRIP_PASSWORD);
1255 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd);
1256 g_free (cwd);
1260 if (reset_prompt)
1261 prompt_pos = 0;
1262 update_subshell_prompt = FALSE;
1264 g_free (pcwd);
1265 /* Make sure that MC never stores the CWD in a silly format */
1266 /* like /usr////lib/../bin, or the strcmp() above will fail */
1269 /* --------------------------------------------------------------------------------------------- */
1271 void
1272 subshell_get_console_attributes (void)
1274 /* Get our current terminal modes */
1276 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1278 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1279 mc_global.tty.use_subshell = FALSE;
1283 /* --------------------------------------------------------------------------------------------- */
1285 * Figure out whether the subshell has stopped, exited or been killed
1286 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1288 void
1289 sigchld_handler (int sig)
1291 int status;
1292 pid_t pid;
1294 (void) sig;
1296 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1298 if (pid == subshell_pid)
1300 /* Figure out what has happened to the subshell */
1302 if (WIFSTOPPED (status))
1304 if (WSTOPSIG (status) == SIGSTOP)
1306 /* The subshell has received a SIGSTOP signal */
1307 subshell_stopped = TRUE;
1309 else
1311 /* The user has suspended the subshell. Revive it */
1312 kill (subshell_pid, SIGCONT);
1315 else
1317 /* The subshell has either exited normally or been killed */
1318 subshell_alive = FALSE;
1319 delete_select_channel (mc_global.tty.subshell_pty);
1320 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1321 quit |= SUBSHELL_EXIT; /* Exited normally */
1324 #ifdef __linux__
1325 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1327 if (pid == cons_saver_pid)
1330 if (WIFSTOPPED (status))
1331 /* Someone has stopped cons.saver - restart it */
1332 kill (pid, SIGCONT);
1333 else
1335 /* cons.saver has died - disable confole saving */
1336 handle_console (CONSOLE_DONE);
1337 mc_global.tty.console_flag = '\0';
1341 #endif /* __linux__ */
1343 /* If we got here, some other child exited; ignore it */
1346 /* --------------------------------------------------------------------------------------------- */