VFS small optimization
[midnight-commander.git] / src / subshell.c
bloba07deed8bc1bd55708b5217ebc1647597ac846af
1 /* Concurrent shell support for the Midnight Commander
2 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of Version 2 of the GNU General Public
7 License, as published by the Free Software Foundation.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 /** \file subshell.c
20 * \brief Source: concurrent shell support
23 #include <config.h>
25 #ifdef HAVE_SUBSHELL_SUPPORT
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE 1
29 #endif
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43 #include <termios.h>
44 #include <unistd.h>
46 #ifdef HAVE_STROPTS_H
47 #include <stropts.h> /* For I_PUSH */
48 #endif /* HAVE_STROPTS_H */
50 #include "lib/global.h"
52 #include "lib/tty/tty.h" /* LINES */
53 #include "lib/tty/key.h" /* XCTRL */
54 #include "lib/vfs/vfs.h"
55 #include "lib/strutil.h"
56 #include "lib/mcconfig.h"
57 #include "lib/util.h"
58 #include "lib/widget.h"
60 #include "filemanager/midnight.h" /* current_panel */
62 #include "consaver/cons.saver.h" /* handle_console() */
63 #include "subshell.h"
65 /*** global variables ****************************************************************************/
67 /* State of the subshell:
68 * INACTIVE: the default state; awaiting a command
69 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
70 * RUNNING_COMMAND: return to MC when the current command finishes */
71 enum subshell_state_enum subshell_state;
73 /* Holds the latest prompt captured from the subshell */
74 char *subshell_prompt = NULL;
76 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
77 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
78 gboolean update_subshell_prompt = FALSE;
80 /*** file scope macro definitions ****************************************************************/
82 #ifndef WEXITSTATUS
83 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
84 #endif
86 #ifndef WIFEXITED
87 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
88 #endif
90 #ifndef STDIN_FILENO
91 #define STDIN_FILENO 0
92 #endif
94 #ifndef STDOUT_FILENO
95 #define STDOUT_FILENO 1
96 #endif
98 #ifndef STDERR_FILENO
99 #define STDERR_FILENO 2
100 #endif
102 /* Initial length of the buffer for the subshell's prompt */
103 #define INITIAL_PROMPT_SIZE 10
105 /* Used by the child process to indicate failure to start the subshell */
106 #define FORK_FAILURE 69 /* Arbitrary */
108 /* Length of the buffer for all I/O with the subshell */
109 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
111 /*** file scope type declarations ****************************************************************/
113 /* For pipes */
114 enum
116 READ = 0,
117 WRITE = 1
120 /* Subshell type (gleaned from the SHELL environment variable, if available) */
121 static enum
123 BASH,
124 TCSH,
125 ZSH,
126 FISH
127 } subshell_type;
129 /*** file scope variables ************************************************************************/
131 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
132 static char tcsh_fifo[128];
134 static int subshell_pty_slave = -1;
136 /* The key for switching back to MC from the subshell */
137 /* *INDENT-OFF* */
138 static const char subshell_switch_key = XCTRL ('o') & 255;
139 /* *INDENT-ON* */
141 /* For reading/writing on the subshell's pty */
142 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
144 /* To pass CWD info from the subshell to MC */
145 static int subshell_pipe[2];
147 /* The subshell's process ID */
148 static pid_t subshell_pid = 1;
150 /* One extra char for final '\n' */
151 static char subshell_cwd[MC_MAXPATHLEN + 1];
153 /* Flag to indicate whether the subshell is ready for next command */
154 static int subshell_ready;
156 /* The following two flags can be changed by the SIGCHLD handler. This is */
157 /* OK, because the `int' type is updated atomically on all known machines */
158 static volatile int subshell_alive, subshell_stopped;
160 /* We store the terminal's initial mode here so that we can configure
161 the pty similarly, and also so we can restore the real terminal to
162 sanity if we have to exit abruptly */
163 static struct termios shell_mode;
165 /* This is a transparent mode for the terminal where MC is running on */
166 /* It is used when the shell is active, so that the control signals */
167 /* are delivered to the shell pty */
168 static struct termios raw_mode;
170 /* This counter indicates how many characters of prompt we have read */
171 /* FIXME: try to figure out why this had to become global */
172 static int prompt_pos;
175 /*** file scope functions ************************************************************************/
176 /* --------------------------------------------------------------------------------------------- */
178 * Write all data, even if the write() call is interrupted.
181 static ssize_t
182 write_all (int fd, const void *buf, size_t count)
184 ssize_t ret;
185 ssize_t written = 0;
186 while (count > 0)
188 ret = write (fd, (const unsigned char *) buf + written, count);
189 if (ret < 0)
191 if (errno == EINTR)
193 continue;
195 else
197 return written > 0 ? written : ret;
200 count -= ret;
201 written += ret;
203 return written;
206 /* --------------------------------------------------------------------------------------------- */
208 * Prepare child process to running the shell and run it.
210 * Modifies the global variables (in the child process only):
211 * shell_mode
213 * Returns: never.
216 static void
217 init_subshell_child (const char *pty_name)
219 char *init_file = NULL;
220 pid_t mc_sid;
222 (void) pty_name;
223 setsid (); /* Get a fresh terminal session */
225 /* Make sure that it has become our controlling terminal */
227 /* Redundant on Linux and probably most systems, but just in case: */
229 #ifdef TIOCSCTTY
230 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
231 #endif
233 /* Configure its terminal modes and window size */
235 /* Set up the pty with the same termios flags as our own tty */
236 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
238 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
239 _exit (FORK_FAILURE);
242 /* Set the pty's size (80x25 by default on Linux) according to the */
243 /* size of the real terminal as calculated by ncurses, if possible */
244 tty_resize (subshell_pty_slave);
246 /* Set up the subshell's environment and init file name */
248 /* It simplifies things to change to our home directory here, */
249 /* and the user's startup file may do a `cd' command anyway */
251 int ret;
252 ret = chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
255 /* Set MC_SID to prevent running one mc from another */
256 mc_sid = getsid (0);
257 if (mc_sid != -1)
259 char sid_str[BUF_SMALL];
260 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
261 putenv (g_strdup (sid_str));
264 switch (subshell_type)
266 case BASH:
267 init_file = g_build_filename (mc_config_get_path (), "bashrc", NULL);
269 if (access (init_file, R_OK) == -1)
271 g_free (init_file);
272 init_file = g_strdup (".bashrc");
275 /* Make MC's special commands not show up in bash's history */
276 putenv ((char *) "HISTCONTROL=ignorespace");
278 /* Allow alternative readline settings for MC */
280 char *input_file = g_build_filename (mc_config_get_path (), "inputrc", NULL);
281 if (access (input_file, R_OK) == 0)
283 char *putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
284 putenv (putenv_str);
285 g_free (putenv_str);
287 g_free (input_file);
290 break;
292 /* TODO: Find a way to pass initfile to TCSH and ZSH */
293 case TCSH:
294 case ZSH:
295 case FISH:
296 break;
298 default:
299 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
300 _exit (FORK_FAILURE);
303 /* Attach all our standard file descriptors to the pty */
305 /* This is done just before the fork, because stderr must still */
306 /* be connected to the real tty during the above error messages; */
307 /* otherwise the user will never see them. */
309 dup2 (subshell_pty_slave, STDIN_FILENO);
310 dup2 (subshell_pty_slave, STDOUT_FILENO);
311 dup2 (subshell_pty_slave, STDERR_FILENO);
313 close (subshell_pipe[READ]);
314 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
315 /* Close master side of pty. This is important; apart from */
316 /* freeing up the descriptor for use in the subshell, it also */
317 /* means that when MC exits, the subshell will get a SIGHUP and */
318 /* exit too, because there will be no more descriptors pointing */
319 /* at the master side of the pty and so it will disappear. */
320 close (mc_global.tty.subshell_pty);
322 /* Execute the subshell at last */
324 switch (subshell_type)
326 case BASH:
327 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
328 break;
330 case TCSH:
331 execl (shell, "tcsh", (char *) NULL);
332 break;
334 case ZSH:
335 /* Use -g to exclude cmds beginning with space from history
336 * and -Z to use the line editor on non-interactive term */
337 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
339 break;
341 case FISH:
342 execl (shell, "fish", (char *) NULL);
343 break;
346 /* If we get this far, everything failed miserably */
347 g_free (init_file);
348 _exit (FORK_FAILURE);
352 /* --------------------------------------------------------------------------------------------- */
354 * Check MC_SID to prevent running one mc from another.
355 * Return:
356 * 0 if no parent mc in our session was found,
357 * 1 if parent mc was found and the user wants to continue,
358 * 2 if parent mc was found and the user wants to quit mc.
361 static int
362 check_sid (void)
364 pid_t my_sid, old_sid;
365 const char *sid_str;
366 int r;
368 sid_str = getenv ("MC_SID");
369 if (!sid_str)
370 return 0;
372 old_sid = (pid_t) strtol (sid_str, NULL, 0);
373 if (!old_sid)
374 return 0;
376 my_sid = getsid (0);
377 if (my_sid == -1)
378 return 0;
380 /* The parent mc is in a different session, it's OK */
381 if (old_sid != my_sid)
382 return 0;
384 r = query_dialog (_("Warning"),
385 _("GNU Midnight Commander is already\n"
386 "running on this terminal.\n"
387 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
388 if (r != 0)
390 return 2;
393 return 1;
396 /* --------------------------------------------------------------------------------------------- */
398 static void
399 init_raw_mode ()
401 static int initialized = 0;
403 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
404 /* original settings. However, here we need to make this tty very raw, */
405 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
406 /* pty. So, instead of changing the code for execute(), pre_exec(), */
407 /* etc, we just set up the modes we need here, before each command. */
409 if (initialized == 0) /* First time: initialise `raw_mode' */
411 tcgetattr (STDOUT_FILENO, &raw_mode);
412 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
413 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
414 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
415 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
416 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
417 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
418 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
419 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
420 initialized = 1;
424 /* --------------------------------------------------------------------------------------------- */
426 * Wait until the subshell dies or stops. If it stops, make it resume.
427 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
430 static void
431 synchronize (void)
433 sigset_t sigchld_mask, old_mask;
435 sigemptyset (&sigchld_mask);
436 sigaddset (&sigchld_mask, SIGCHLD);
437 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
440 * SIGCHLD should not be blocked, but we unblock it just in case.
441 * This is known to be useful for cygwin 1.3.12 and older.
443 sigdelset (&old_mask, SIGCHLD);
445 /* Wait until the subshell has stopped */
446 while (subshell_alive && !subshell_stopped)
447 sigsuspend (&old_mask);
449 if (subshell_state != ACTIVE)
451 /* Discard all remaining data from stdin to the subshell */
452 tcflush (subshell_pty_slave, TCIFLUSH);
455 subshell_stopped = FALSE;
456 kill (subshell_pid, SIGCONT);
458 sigprocmask (SIG_SETMASK, &old_mask, NULL);
459 /* We can't do any better without modifying the shell(s) */
462 /* --------------------------------------------------------------------------------------------- */
463 /** Feed the subshell our keyboard input until it says it's finished */
465 static gboolean
466 feed_subshell (int how, int fail_on_error)
468 fd_set read_set; /* For `select' */
469 int maxfdp;
470 int bytes; /* For the return value from `read' */
471 int i; /* Loop counter */
473 struct timeval wtime; /* Maximum time we wait for the subshell */
474 struct timeval *wptr;
476 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
477 wtime.tv_sec = 10;
478 wtime.tv_usec = 0;
479 wptr = fail_on_error ? &wtime : NULL;
481 while (TRUE)
483 if (!subshell_alive)
484 return FALSE;
486 /* Prepare the file-descriptor set and call `select' */
488 FD_ZERO (&read_set);
489 FD_SET (mc_global.tty.subshell_pty, &read_set);
490 FD_SET (subshell_pipe[READ], &read_set);
491 maxfdp = max (mc_global.tty.subshell_pty, subshell_pipe[READ]);
492 if (how == VISIBLY)
494 FD_SET (STDIN_FILENO, &read_set);
495 maxfdp = max (maxfdp, STDIN_FILENO);
498 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
501 /* Despite using SA_RESTART, we still have to check for this */
502 if (errno == EINTR)
503 continue; /* try all over again */
504 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
505 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
506 unix_error_string (errno));
507 exit (EXIT_FAILURE);
510 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
511 /* Read from the subshell, write to stdout */
513 /* This loop improves performance by reducing context switches
514 by a factor of 20 or so... unfortunately, it also hangs MC
515 randomly, because of an apparent Linux bug. Investigate. */
516 /* for (i=0; i<5; ++i) * FIXME -- experimental */
518 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
520 /* The subshell has died */
521 if (bytes == -1 && errno == EIO && !subshell_alive)
522 return FALSE;
524 if (bytes <= 0)
526 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
527 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
528 exit (EXIT_FAILURE);
531 if (how == VISIBLY)
532 write_all (STDOUT_FILENO, pty_buffer, bytes);
535 else if (FD_ISSET (subshell_pipe[READ], &read_set))
536 /* Read the subshell's CWD and capture its prompt */
538 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
539 if (bytes <= 0)
541 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
542 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
543 unix_error_string (errno));
544 exit (EXIT_FAILURE);
547 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
549 synchronize ();
551 subshell_ready = TRUE;
552 if (subshell_state == RUNNING_COMMAND)
554 subshell_state = INACTIVE;
555 return TRUE;
559 else if (FD_ISSET (STDIN_FILENO, &read_set))
560 /* Read from stdin, write to the subshell */
562 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
563 if (bytes <= 0)
565 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
566 fprintf (stderr,
567 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
568 exit (EXIT_FAILURE);
571 for (i = 0; i < bytes; ++i)
572 if (pty_buffer[i] == subshell_switch_key)
574 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
575 if (subshell_ready)
576 subshell_state = INACTIVE;
577 return TRUE;
580 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
582 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
583 subshell_ready = FALSE;
585 else
586 return FALSE;
590 /* --------------------------------------------------------------------------------------------- */
591 /* pty opening functions */
593 #ifdef HAVE_GRANTPT
595 /* System V version of pty_open_master */
597 static int
598 pty_open_master (char *pty_name)
600 char *slave_name;
601 int pty_master;
603 #ifdef HAVE_POSIX_OPENPT
604 pty_master = posix_openpt (O_RDWR);
605 #elif HAVE_GETPT
606 /* getpt () is a GNU extension (glibc 2.1.x) */
607 pty_master = getpt ();
608 #elif IS_AIX
609 strcpy (pty_name, "/dev/ptc");
610 pty_master = open (pty_name, O_RDWR);
611 #else
612 strcpy (pty_name, "/dev/ptmx");
613 pty_master = open (pty_name, O_RDWR);
614 #endif
616 if (pty_master == -1)
617 return -1;
619 if (grantpt (pty_master) == -1 /* Grant access to slave */
620 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
621 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
623 close (pty_master);
624 return -1;
626 strcpy (pty_name, slave_name);
627 return pty_master;
630 /* --------------------------------------------------------------------------------------------- */
631 /** System V version of pty_open_slave */
633 static int
634 pty_open_slave (const char *pty_name)
636 int pty_slave = open (pty_name, O_RDWR);
638 if (pty_slave == -1)
640 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
641 return -1;
643 #if !defined(__osf__) && !defined(__linux__)
644 #if defined (I_FIND) && defined (I_PUSH)
645 if (!ioctl (pty_slave, I_FIND, "ptem"))
646 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
648 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
649 pty_slave, unix_error_string (errno));
650 close (pty_slave);
651 return -1;
654 if (!ioctl (pty_slave, I_FIND, "ldterm"))
655 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
657 fprintf (stderr,
658 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
659 pty_slave, unix_error_string (errno));
660 close (pty_slave);
661 return -1;
663 #if !defined(sgi) && !defined(__sgi)
664 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
665 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
667 fprintf (stderr,
668 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
669 pty_slave, unix_error_string (errno));
670 close (pty_slave);
671 return -1;
673 #endif /* sgi || __sgi */
674 #endif /* I_FIND && I_PUSH */
675 #endif /* __osf__ || __linux__ */
677 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
678 return pty_slave;
681 #else /* !HAVE_GRANTPT */
683 /* --------------------------------------------------------------------------------------------- */
684 /** BSD version of pty_open_master */
685 static int
686 pty_open_master (char *pty_name)
688 int pty_master;
689 const char *ptr1, *ptr2;
691 strcpy (pty_name, "/dev/ptyXX");
692 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
694 pty_name[8] = *ptr1;
695 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
697 pty_name[9] = *ptr2;
699 /* Try to open master */
700 pty_master = open (pty_name, O_RDWR);
701 if (pty_master == -1)
703 if (errno == ENOENT) /* Different from EIO */
704 return -1; /* Out of pty devices */
705 continue; /* Try next pty device */
707 pty_name[5] = 't'; /* Change "pty" to "tty" */
708 if (access (pty_name, 6) != 0)
710 close (pty_master);
711 pty_name[5] = 'p';
712 continue;
714 return pty_master;
717 return -1; /* Ran out of pty devices */
720 /* --------------------------------------------------------------------------------------------- */
721 /** BSD version of pty_open_slave */
723 static int
724 pty_open_slave (const char *pty_name)
726 int pty_slave;
727 struct group *group_info = getgrnam ("tty");
729 if (group_info != NULL)
731 /* The following two calls will only succeed if we are root */
732 /* [Commented out while permissions problem is investigated] */
733 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
734 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
736 pty_slave = open (pty_name, O_RDWR);
737 if (pty_slave == -1)
738 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
739 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
740 return pty_slave;
742 #endif /* !HAVE_GRANTPT */
744 /* --------------------------------------------------------------------------------------------- */
745 /*** public functions ****************************************************************************/
746 /* --------------------------------------------------------------------------------------------- */
748 /* --------------------------------------------------------------------------------------------- */
750 * Fork the subshell, and set up many, many things.
752 * Possibly modifies the global variables:
753 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
754 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
755 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
758 void
759 init_subshell (void)
761 /* This must be remembered across calls to init_subshell() */
762 static char pty_name[BUF_SMALL];
763 char precmd[BUF_SMALL];
765 switch (check_sid ())
767 case 1:
768 mc_global.tty.use_subshell = FALSE;
769 return;
770 case 2:
771 mc_global.tty.use_subshell = FALSE;
772 mc_global.widget.midnight_shutdown = TRUE;
773 return;
776 /* Take the current (hopefully pristine) tty mode and make */
777 /* a raw mode based on it now, before we do anything else with it */
778 init_raw_mode ();
780 if (mc_global.tty.subshell_pty == 0)
781 { /* First time through */
782 /* Find out what type of shell we have */
784 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
785 subshell_type = ZSH;
786 else if (strstr (shell, "/tcsh"))
787 subshell_type = TCSH;
788 else if (strstr (shell, "/csh"))
789 subshell_type = TCSH;
790 else if (strstr (shell, "/bash") || getenv ("BASH"))
791 subshell_type = BASH;
792 else if (strstr (shell, "/fish"))
793 subshell_type = FISH;
794 else
796 mc_global.tty.use_subshell = FALSE;
797 return;
800 /* Open a pty for talking to the subshell */
802 /* FIXME: We may need to open a fresh pty each time on SVR4 */
804 mc_global.tty.subshell_pty = pty_open_master (pty_name);
805 if (mc_global.tty.subshell_pty == -1)
807 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
808 mc_global.tty.use_subshell = FALSE;
809 return;
811 subshell_pty_slave = pty_open_slave (pty_name);
812 if (subshell_pty_slave == -1)
814 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
815 pty_name, unix_error_string (errno));
816 mc_global.tty.use_subshell = FALSE;
817 return;
820 /* Create a pipe for receiving the subshell's CWD */
822 if (subshell_type == TCSH)
824 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
825 mc_tmpdir (), (int) getpid ());
826 if (mkfifo (tcsh_fifo, 0600) == -1)
828 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
829 mc_global.tty.use_subshell = FALSE;
830 return;
833 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
835 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
836 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
838 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
839 perror (__FILE__ ": open");
840 mc_global.tty.use_subshell = FALSE;
841 return;
844 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
846 perror (__FILE__ ": couldn't create pipe");
847 mc_global.tty.use_subshell = FALSE;
848 return;
852 /* Fork the subshell */
854 subshell_alive = TRUE;
855 subshell_stopped = FALSE;
856 subshell_pid = fork ();
858 if (subshell_pid == -1)
860 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
861 /* We exit here because, if the process table is full, the */
862 /* other method of running user commands won't work either */
863 exit (EXIT_FAILURE);
866 if (subshell_pid == 0)
868 /* We are in the child process */
869 init_subshell_child (pty_name);
872 /* Set up `precmd' or equivalent for reading the subshell's CWD */
874 switch (subshell_type)
876 case BASH:
877 g_snprintf (precmd, sizeof (precmd),
878 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
879 break;
881 case ZSH:
882 g_snprintf (precmd, sizeof (precmd),
883 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
884 break;
886 case TCSH:
887 g_snprintf (precmd, sizeof (precmd),
888 "set echo_style=both;"
889 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
890 break;
891 case FISH:
892 g_snprintf (precmd, sizeof (precmd),
893 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
894 subshell_pipe[WRITE]);
895 break;
898 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
900 /* Wait until the subshell has started up and processed the command */
902 subshell_state = RUNNING_COMMAND;
903 tty_enable_interrupt_key ();
904 if (!feed_subshell (QUIETLY, TRUE))
906 mc_global.tty.use_subshell = FALSE;
908 tty_disable_interrupt_key ();
909 if (!subshell_alive)
910 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
913 /* --------------------------------------------------------------------------------------------- */
916 invoke_subshell (const char *command, int how, char **new_dir)
918 char *pcwd;
920 /* Make the MC terminal transparent */
921 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
923 /* Make the subshell change to MC's working directory */
924 if (new_dir != NULL)
925 do_subshell_chdir (current_panel->cwd, TRUE, TRUE);
927 if (command == NULL) /* The user has done "C-o" from MC */
929 if (subshell_state == INACTIVE)
931 subshell_state = ACTIVE;
932 /* FIXME: possibly take out this hack; the user can
933 re-play it by hitting C-hyphen a few times! */
934 if (subshell_ready)
935 write_all (mc_global.tty.subshell_pty, " \b", 2); /* Hack to make prompt reappear */
938 else /* MC has passed us a user command */
940 if (how == QUIETLY)
941 write_all (mc_global.tty.subshell_pty, " ", 1);
942 /* FIXME: if command is long (>8KB ?) we go comma */
943 write_all (mc_global.tty.subshell_pty, command, strlen (command));
944 write_all (mc_global.tty.subshell_pty, "\n", 1);
945 subshell_state = RUNNING_COMMAND;
946 subshell_ready = FALSE;
949 feed_subshell (how, FALSE);
951 pcwd = vfs_translate_path_n (current_panel->cwd);
952 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
953 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
954 g_free (pcwd);
956 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
957 while (!subshell_alive && quit == 0 && mc_global.tty.use_subshell)
958 init_subshell ();
960 prompt_pos = 0;
962 return quit;
966 /* --------------------------------------------------------------------------------------------- */
969 read_subshell_prompt (void)
971 static int prompt_size = INITIAL_PROMPT_SIZE;
972 int bytes = 0, i, rc = 0;
973 struct timeval timeleft = { 0, 0 };
975 fd_set tmp;
976 FD_ZERO (&tmp);
977 FD_SET (mc_global.tty.subshell_pty, &tmp);
979 if (subshell_prompt == NULL)
980 { /* First time through */
981 subshell_prompt = g_malloc (prompt_size);
982 *subshell_prompt = '\0';
983 prompt_pos = 0;
986 while (subshell_alive
987 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)))
989 /* Check for `select' errors */
990 if (rc == -1)
992 if (errno == EINTR)
993 continue;
994 else
996 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
997 exit (EXIT_FAILURE);
1001 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1003 /* Extract the prompt from the shell output */
1005 for (i = 0; i < bytes; ++i)
1006 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1008 prompt_pos = 0;
1010 else
1012 if (!pty_buffer[i])
1013 continue;
1015 subshell_prompt[prompt_pos++] = pty_buffer[i];
1016 if (prompt_pos == prompt_size)
1017 subshell_prompt = g_realloc (subshell_prompt, prompt_size *= 2);
1020 subshell_prompt[prompt_pos] = '\0';
1022 if (rc == 0 && bytes == 0)
1023 return FALSE;
1024 return TRUE;
1027 /* --------------------------------------------------------------------------------------------- */
1029 void
1030 do_update_prompt (void)
1032 if (update_subshell_prompt)
1034 printf ("\r\n%s", subshell_prompt);
1035 fflush (stdout);
1036 update_subshell_prompt = FALSE;
1040 /* --------------------------------------------------------------------------------------------- */
1043 exit_subshell (void)
1045 int subshell_quit = TRUE;
1047 if (subshell_state != INACTIVE && subshell_alive)
1048 subshell_quit =
1049 !query_dialog (_("Warning"),
1050 _("The shell is still active. Quit anyway?"),
1051 D_NORMAL, 2, _("&Yes"), _("&No"));
1053 if (subshell_quit)
1055 if (subshell_type == TCSH)
1057 if (unlink (tcsh_fifo) == -1)
1058 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1059 tcsh_fifo, unix_error_string (errno));
1062 g_free (subshell_prompt);
1063 subshell_prompt = NULL;
1064 pty_buffer[0] = '\0';
1067 return subshell_quit;
1070 /* --------------------------------------------------------------------------------------------- */
1072 * Carefully quote directory name to allow entering any directory safely,
1073 * no matter what weird characters it may contain in its name.
1074 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1075 * executing any commands in the shell. Escape all control characters.
1076 * Use following technique:
1078 * printf(1) with format string containing a single conversion specifier,
1079 * "b", and an argument which contains a copy of the string passed to
1080 * subshell_name_quote() with all characters, except digits and letters,
1081 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1082 * numeric value of the character converted to octal number.
1084 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1088 static char *
1089 subshell_name_quote (const char *s)
1091 char *ret, *d;
1092 const char *su, *n;
1093 const char *quote_cmd_start, *quote_cmd_end;
1094 int c;
1096 if (subshell_type == FISH)
1098 quote_cmd_start = "(printf \"%b\" '";
1099 quote_cmd_end = "')";
1101 else
1103 quote_cmd_start = "\"`printf \"%b\" '";
1104 quote_cmd_end = "'`\"";
1107 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1108 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
1109 + (strlen (quote_cmd_end)));
1110 if (d == NULL)
1111 return NULL;
1113 /* Prevent interpreting leading `-' as a switch for `cd' */
1114 if (*s == '-')
1116 *d++ = '.';
1117 *d++ = '/';
1120 /* Copy the beginning of the command to the buffer */
1121 strcpy (d, quote_cmd_start);
1122 d += strlen (quote_cmd_start);
1125 * Print every character except digits and letters as a backslash-escape
1126 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1127 * character converted to octal number.
1129 su = s;
1130 for (; su[0] != '\0';)
1132 n = str_cget_next_char_safe (su);
1133 if (str_isalnum (su))
1135 memcpy (d, su, n - su);
1136 d += n - su;
1138 else
1140 for (c = 0; c < n - su; c++)
1142 sprintf (d, "\\0%03o", (unsigned char) su[c]);
1143 d += 5;
1146 su = n;
1149 strcpy (d, quote_cmd_end);
1151 return ret;
1155 /* --------------------------------------------------------------------------------------------- */
1157 /** If it actually changed the directory it returns true */
1158 void
1159 do_subshell_chdir (const char *directory, gboolean update_prompt, gboolean reset_prompt)
1161 char *pcwd;
1162 char *temp;
1163 char *translate;
1165 pcwd = vfs_translate_path_n (current_panel->cwd);
1167 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1169 /* We have to repaint the subshell prompt if we read it from
1170 * the main program. Please note that in the code after this
1171 * if, the cd command that is sent will make the subshell
1172 * repaint the prompt, so we don't have to paint it. */
1173 if (update_prompt)
1174 do_update_prompt ();
1175 g_free (pcwd);
1176 return;
1179 /* The initial space keeps this out of the command history (in bash
1180 because we set "HISTCONTROL=ignorespace") */
1181 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1182 if (*directory)
1184 translate = vfs_translate_path_n (directory);
1185 if (translate)
1187 temp = subshell_name_quote (translate);
1188 if (temp)
1190 write_all (mc_global.tty.subshell_pty, temp, strlen (temp));
1191 g_free (temp);
1193 else
1195 /* Should not happen unless the directory name is so long
1196 that we don't have memory to quote it. */
1197 write_all (mc_global.tty.subshell_pty, ".", 1);
1199 g_free (translate);
1201 else
1203 write_all (mc_global.tty.subshell_pty, ".", 1);
1206 else
1208 write_all (mc_global.tty.subshell_pty, "/", 1);
1210 write_all (mc_global.tty.subshell_pty, "\n", 1);
1212 subshell_state = RUNNING_COMMAND;
1213 feed_subshell (QUIETLY, FALSE);
1215 if (subshell_alive)
1217 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1219 if (bPathNotEq && subshell_type == TCSH)
1221 char rp_subshell_cwd[PATH_MAX];
1222 char rp_current_panel_cwd[PATH_MAX];
1224 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1225 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1227 if (p_subshell_cwd == NULL)
1228 p_subshell_cwd = subshell_cwd;
1229 if (p_current_panel_cwd == NULL)
1230 p_current_panel_cwd = pcwd;
1231 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1234 if (bPathNotEq && strcmp (pcwd, "."))
1236 char *cwd = strip_password (g_strdup (pcwd), 1);
1237 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
1238 g_free (cwd);
1242 if (reset_prompt)
1243 prompt_pos = 0;
1244 update_subshell_prompt = FALSE;
1246 g_free (pcwd);
1247 /* Make sure that MC never stores the CWD in a silly format */
1248 /* like /usr////lib/../bin, or the strcmp() above will fail */
1251 /* --------------------------------------------------------------------------------------------- */
1253 void
1254 subshell_get_console_attributes (void)
1256 /* Get our current terminal modes */
1258 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1260 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1261 mc_global.tty.use_subshell = FALSE;
1262 return;
1266 /* --------------------------------------------------------------------------------------------- */
1268 * Figure out whether the subshell has stopped, exited or been killed
1269 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1271 void
1272 sigchld_handler (int sig)
1274 int status;
1275 pid_t pid;
1277 (void) sig;
1279 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1281 if (pid == subshell_pid)
1283 /* Figure out what has happened to the subshell */
1285 if (WIFSTOPPED (status))
1287 if (WSTOPSIG (status) == SIGSTOP)
1289 /* The subshell has received a SIGSTOP signal */
1290 subshell_stopped = TRUE;
1292 else
1294 /* The user has suspended the subshell. Revive it */
1295 kill (subshell_pid, SIGCONT);
1298 else
1300 /* The subshell has either exited normally or been killed */
1301 subshell_alive = FALSE;
1302 delete_select_channel (mc_global.tty.subshell_pty);
1303 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1304 quit |= SUBSHELL_EXIT; /* Exited normally */
1307 #ifdef __linux__
1308 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1310 if (pid == cons_saver_pid)
1313 if (WIFSTOPPED (status))
1314 /* Someone has stopped cons.saver - restart it */
1315 kill (pid, SIGCONT);
1316 else
1318 /* cons.saver has died - disable confole saving */
1319 handle_console (CONSOLE_DONE);
1320 mc_global.tty.console_flag = '\0';
1324 #endif /* __linux__ */
1326 /* If we got here, some other child exited; ignore it */
1329 /* --------------------------------------------------------------------------------------------- */
1331 #endif /* HAVE_SUBSHELL_SUPPORT */