Merge branch '2031_solaris_FISH_fix'
[midnight-commander.git] / src / subshell.c
blob7efe891b4e99e1f9a4cf64c3fa884496051815f4
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/mc-vfs/vfs.h"
55 #include "lib/strutil.h"
56 #include "lib/fileloc.h"
57 #include "lib/util.h"
58 #include "lib/widget.h"
60 #include "filemanager/midnight.h" /* current_panel */
62 #include "main.h" /* home_dir */
63 #include "consaver/cons.saver.h" /* handle_console() */
64 #include "subshell.h"
66 /*** global variables ****************************************************************************/
68 /* If using a subshell for evaluating commands this is true */
69 int use_subshell =
70 #ifdef SUBSHELL_OPTIONAL
71 FALSE;
72 #else
73 TRUE;
74 #endif
76 /* File descriptors of the pseudoterminal used by the subshell */
77 int subshell_pty = 0;
79 /* State of the subshell:
80 * INACTIVE: the default state; awaiting a command
81 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
82 * RUNNING_COMMAND: return to MC when the current command finishes */
83 enum subshell_state_enum subshell_state;
85 /* Holds the latest prompt captured from the subshell */
86 char *subshell_prompt = NULL;
88 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
89 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
90 gboolean update_subshell_prompt = FALSE;
92 /*** file scope macro definitions ****************************************************************/
94 #ifndef WEXITSTATUS
95 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
96 #endif
98 #ifndef WIFEXITED
99 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
100 #endif
102 #ifndef STDIN_FILENO
103 #define STDIN_FILENO 0
104 #endif
106 #ifndef STDOUT_FILENO
107 #define STDOUT_FILENO 1
108 #endif
110 #ifndef STDERR_FILENO
111 #define STDERR_FILENO 2
112 #endif
114 /* Initial length of the buffer for the subshell's prompt */
115 #define INITIAL_PROMPT_SIZE 10
117 /* Used by the child process to indicate failure to start the subshell */
118 #define FORK_FAILURE 69 /* Arbitrary */
120 /* Length of the buffer for all I/O with the subshell */
121 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
123 /*** file scope type declarations ****************************************************************/
125 /* For pipes */
126 enum
128 READ = 0,
129 WRITE = 1
132 /* Subshell type (gleaned from the SHELL environment variable, if available) */
133 static enum
135 BASH,
136 TCSH,
137 ZSH,
138 FISH
139 } subshell_type;
141 /*** file scope variables ************************************************************************/
143 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
144 static char tcsh_fifo[128];
146 static int subshell_pty_slave = -1;
148 /* The key for switching back to MC from the subshell */
149 /* *INDENT-OFF* */
150 static const char subshell_switch_key = XCTRL ('o') & 255;
151 /* *INDENT-ON* */
153 /* For reading/writing on the subshell's pty */
154 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
156 /* To pass CWD info from the subshell to MC */
157 static int subshell_pipe[2];
159 /* The subshell's process ID */
160 static pid_t subshell_pid = 1;
162 /* One extra char for final '\n' */
163 static char subshell_cwd[MC_MAXPATHLEN + 1];
165 /* Flag to indicate whether the subshell is ready for next command */
166 static int subshell_ready;
168 /* The following two flags can be changed by the SIGCHLD handler. This is */
169 /* OK, because the `int' type is updated atomically on all known machines */
170 static volatile int subshell_alive, subshell_stopped;
172 /* We store the terminal's initial mode here so that we can configure
173 the pty similarly, and also so we can restore the real terminal to
174 sanity if we have to exit abruptly */
175 static struct termios shell_mode;
177 /* This is a transparent mode for the terminal where MC is running on */
178 /* It is used when the shell is active, so that the control signals */
179 /* are delivered to the shell pty */
180 static struct termios raw_mode;
182 /* This counter indicates how many characters of prompt we have read */
183 /* FIXME: try to figure out why this had to become global */
184 static int prompt_pos;
187 /*** file scope functions ************************************************************************/
188 /* --------------------------------------------------------------------------------------------- */
190 static void init_raw_mode (void);
191 static gboolean feed_subshell (int how, int fail_on_error);
192 static void synchronize (void);
193 static int pty_open_master (char *pty_name);
194 static int pty_open_slave (const char *pty_name);
195 static int resize_tty (int fd);
197 /* --------------------------------------------------------------------------------------------- */
199 * Write all data, even if the write() call is interrupted.
202 static ssize_t
203 write_all (int fd, const void *buf, size_t count)
205 ssize_t ret;
206 ssize_t written = 0;
207 while (count > 0)
209 ret = write (fd, (const unsigned char *) buf + written, count);
210 if (ret < 0)
212 if (errno == EINTR)
214 continue;
216 else
218 return written > 0 ? written : ret;
221 count -= ret;
222 written += ret;
224 return written;
227 /* --------------------------------------------------------------------------------------------- */
229 * Prepare child process to running the shell and run it.
231 * Modifies the global variables (in the child process only):
232 * shell_mode
234 * Returns: never.
237 static void
238 init_subshell_child (const char *pty_name)
240 const char *init_file = NULL;
241 pid_t mc_sid;
243 (void) pty_name;
244 setsid (); /* Get a fresh terminal session */
246 /* Make sure that it has become our controlling terminal */
248 /* Redundant on Linux and probably most systems, but just in case: */
250 #ifdef TIOCSCTTY
251 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
252 #endif
254 /* Configure its terminal modes and window size */
256 /* Set up the pty with the same termios flags as our own tty */
257 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
259 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
260 _exit (FORK_FAILURE);
263 /* Set the pty's size (80x25 by default on Linux) according to the */
264 /* size of the real terminal as calculated by ncurses, if possible */
265 resize_tty (subshell_pty_slave);
267 /* Set up the subshell's environment and init file name */
269 /* It simplifies things to change to our home directory here, */
270 /* and the user's startup file may do a `cd' command anyway */
272 int ret;
273 ret = chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
276 /* Set MC_SID to prevent running one mc from another */
277 mc_sid = getsid (0);
278 if (mc_sid != -1)
280 char sid_str[BUF_SMALL];
281 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
282 putenv (g_strdup (sid_str));
285 switch (subshell_type)
287 case BASH:
288 init_file = MC_USERCONF_DIR PATH_SEP_STR "bashrc";
289 if (access (init_file, R_OK) == -1)
290 init_file = ".bashrc";
292 /* Make MC's special commands not show up in bash's history */
293 putenv ((char *) "HISTCONTROL=ignorespace");
295 /* Allow alternative readline settings for MC */
296 if (access (MC_USERCONF_DIR PATH_SEP_STR "inputrc", R_OK) == 0)
297 putenv ((char *) "INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR "/inputrc");
299 break;
301 /* TODO: Find a way to pass initfile to TCSH and ZSH */
302 case TCSH:
303 case ZSH:
304 case FISH:
305 break;
307 default:
308 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
309 _exit (FORK_FAILURE);
312 /* Attach all our standard file descriptors to the pty */
314 /* This is done just before the fork, because stderr must still */
315 /* be connected to the real tty during the above error messages; */
316 /* otherwise the user will never see them. */
318 dup2 (subshell_pty_slave, STDIN_FILENO);
319 dup2 (subshell_pty_slave, STDOUT_FILENO);
320 dup2 (subshell_pty_slave, STDERR_FILENO);
322 close (subshell_pipe[READ]);
323 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
324 /* Close master side of pty. This is important; apart from */
325 /* freeing up the descriptor for use in the subshell, it also */
326 /* means that when MC exits, the subshell will get a SIGHUP and */
327 /* exit too, because there will be no more descriptors pointing */
328 /* at the master side of the pty and so it will disappear. */
329 close (subshell_pty);
331 /* Execute the subshell at last */
333 switch (subshell_type)
335 case BASH:
336 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
337 break;
339 case TCSH:
340 execl (shell, "tcsh", (char *) NULL);
341 break;
343 case ZSH:
344 /* Use -g to exclude cmds beginning with space from history
345 * and -Z to use the line editor on non-interactive term */
346 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
348 break;
350 case FISH:
351 execl (shell, "fish", (char *) NULL);
352 break;
355 /* If we get this far, everything failed miserably */
356 _exit (FORK_FAILURE);
360 /* --------------------------------------------------------------------------------------------- */
362 * Check MC_SID to prevent running one mc from another.
363 * Return:
364 * 0 if no parent mc in our session was found,
365 * 1 if parent mc was found and the user wants to continue,
366 * 2 if parent mc was found and the user wants to quit mc.
369 static int
370 check_sid (void)
372 pid_t my_sid, old_sid;
373 const char *sid_str;
374 int r;
376 sid_str = getenv ("MC_SID");
377 if (!sid_str)
378 return 0;
380 old_sid = (pid_t) strtol (sid_str, NULL, 0);
381 if (!old_sid)
382 return 0;
384 my_sid = getsid (0);
385 if (my_sid == -1)
386 return 0;
388 /* The parent mc is in a different session, it's OK */
389 if (old_sid != my_sid)
390 return 0;
392 r = query_dialog (_("Warning"),
393 _("GNU Midnight Commander is already\n"
394 "running on this terminal.\n"
395 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
396 if (r != 0)
398 return 2;
401 return 1;
404 /* --------------------------------------------------------------------------------------------- */
406 static void
407 init_raw_mode ()
409 static int initialized = 0;
411 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
412 /* original settings. However, here we need to make this tty very raw, */
413 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
414 /* pty. So, instead of changing the code for execute(), pre_exec(), */
415 /* etc, we just set up the modes we need here, before each command. */
417 if (initialized == 0) /* First time: initialise `raw_mode' */
419 tcgetattr (STDOUT_FILENO, &raw_mode);
420 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
421 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
422 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
423 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
424 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
425 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
426 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
427 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
428 initialized = 1;
432 /* --------------------------------------------------------------------------------------------- */
433 /** Feed the subshell our keyboard input until it says it's finished */
435 static gboolean
436 feed_subshell (int how, int fail_on_error)
438 fd_set read_set; /* For `select' */
439 int maxfdp;
440 int bytes; /* For the return value from `read' */
441 int i; /* Loop counter */
443 struct timeval wtime; /* Maximum time we wait for the subshell */
444 struct timeval *wptr;
446 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
447 wtime.tv_sec = 10;
448 wtime.tv_usec = 0;
449 wptr = fail_on_error ? &wtime : NULL;
451 while (TRUE)
453 if (!subshell_alive)
454 return FALSE;
456 /* Prepare the file-descriptor set and call `select' */
458 FD_ZERO (&read_set);
459 FD_SET (subshell_pty, &read_set);
460 FD_SET (subshell_pipe[READ], &read_set);
461 maxfdp = max (subshell_pty, subshell_pipe[READ]);
462 if (how == VISIBLY)
464 FD_SET (STDIN_FILENO, &read_set);
465 maxfdp = max (maxfdp, STDIN_FILENO);
468 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
471 /* Despite using SA_RESTART, we still have to check for this */
472 if (errno == EINTR)
473 continue; /* try all over again */
474 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
475 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
476 unix_error_string (errno));
477 exit (EXIT_FAILURE);
480 if (FD_ISSET (subshell_pty, &read_set))
481 /* Read from the subshell, write to stdout */
483 /* This loop improves performance by reducing context switches
484 by a factor of 20 or so... unfortunately, it also hangs MC
485 randomly, because of an apparent Linux bug. Investigate. */
486 /* for (i=0; i<5; ++i) * FIXME -- experimental */
488 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
490 /* The subshell has died */
491 if (bytes == -1 && errno == EIO && !subshell_alive)
492 return FALSE;
494 if (bytes <= 0)
496 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
497 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
498 exit (EXIT_FAILURE);
501 if (how == VISIBLY)
502 write_all (STDOUT_FILENO, pty_buffer, bytes);
505 else if (FD_ISSET (subshell_pipe[READ], &read_set))
506 /* Read the subshell's CWD and capture its prompt */
508 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
509 if (bytes <= 0)
511 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
512 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
513 unix_error_string (errno));
514 exit (EXIT_FAILURE);
517 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
519 synchronize ();
521 subshell_ready = TRUE;
522 if (subshell_state == RUNNING_COMMAND)
524 subshell_state = INACTIVE;
525 return TRUE;
529 else if (FD_ISSET (STDIN_FILENO, &read_set))
530 /* Read from stdin, write to the subshell */
532 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
533 if (bytes <= 0)
535 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
536 fprintf (stderr,
537 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
538 exit (EXIT_FAILURE);
541 for (i = 0; i < bytes; ++i)
542 if (pty_buffer[i] == subshell_switch_key)
544 write_all (subshell_pty, pty_buffer, i);
545 if (subshell_ready)
546 subshell_state = INACTIVE;
547 return TRUE;
550 write_all (subshell_pty, pty_buffer, bytes);
552 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
553 subshell_ready = FALSE;
555 else
556 return FALSE;
560 /* --------------------------------------------------------------------------------------------- */
562 * Wait until the subshell dies or stops. If it stops, make it resume.
563 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
566 static void
567 synchronize (void)
569 sigset_t sigchld_mask, old_mask;
571 sigemptyset (&sigchld_mask);
572 sigaddset (&sigchld_mask, SIGCHLD);
573 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
576 * SIGCHLD should not be blocked, but we unblock it just in case.
577 * This is known to be useful for cygwin 1.3.12 and older.
579 sigdelset (&old_mask, SIGCHLD);
581 /* Wait until the subshell has stopped */
582 while (subshell_alive && !subshell_stopped)
583 sigsuspend (&old_mask);
585 if (subshell_state != ACTIVE)
587 /* Discard all remaining data from stdin to the subshell */
588 tcflush (subshell_pty_slave, TCIFLUSH);
591 subshell_stopped = FALSE;
592 kill (subshell_pid, SIGCONT);
594 sigprocmask (SIG_SETMASK, &old_mask, NULL);
595 /* We can't do any better without modifying the shell(s) */
598 /* pty opening functions */
600 #ifdef HAVE_GRANTPT
602 /* System V version of pty_open_master */
604 static int
605 pty_open_master (char *pty_name)
607 char *slave_name;
608 int pty_master;
610 #ifdef HAVE_POSIX_OPENPT
611 pty_master = posix_openpt (O_RDWR);
612 #elif HAVE_GETPT
613 /* getpt () is a GNU extension (glibc 2.1.x) */
614 pty_master = getpt ();
615 #elif IS_AIX
616 strcpy (pty_name, "/dev/ptc");
617 pty_master = open (pty_name, O_RDWR);
618 #else
619 strcpy (pty_name, "/dev/ptmx");
620 pty_master = open (pty_name, O_RDWR);
621 #endif
623 if (pty_master == -1)
624 return -1;
626 if (grantpt (pty_master) == -1 /* Grant access to slave */
627 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
628 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
630 close (pty_master);
631 return -1;
633 strcpy (pty_name, slave_name);
634 return pty_master;
637 /* --------------------------------------------------------------------------------------------- */
638 /** System V version of pty_open_slave */
640 static int
641 pty_open_slave (const char *pty_name)
643 int pty_slave = open (pty_name, O_RDWR);
645 if (pty_slave == -1)
647 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
648 return -1;
650 #if !defined(__osf__) && !defined(__linux__)
651 #if defined (I_FIND) && defined (I_PUSH)
652 if (!ioctl (pty_slave, I_FIND, "ptem"))
653 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
655 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
656 pty_slave, unix_error_string (errno));
657 close (pty_slave);
658 return -1;
661 if (!ioctl (pty_slave, I_FIND, "ldterm"))
662 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
664 fprintf (stderr,
665 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
666 pty_slave, unix_error_string (errno));
667 close (pty_slave);
668 return -1;
670 #if !defined(sgi) && !defined(__sgi)
671 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
672 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
674 fprintf (stderr,
675 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
676 pty_slave, unix_error_string (errno));
677 close (pty_slave);
678 return -1;
680 #endif /* sgi || __sgi */
681 #endif /* I_FIND && I_PUSH */
682 #endif /* __osf__ || __linux__ */
684 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
685 return pty_slave;
688 #else /* !HAVE_GRANTPT */
690 /* --------------------------------------------------------------------------------------------- */
691 /** BSD version of pty_open_master */
692 static int
693 pty_open_master (char *pty_name)
695 int pty_master;
696 const char *ptr1, *ptr2;
698 strcpy (pty_name, "/dev/ptyXX");
699 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
701 pty_name[8] = *ptr1;
702 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
704 pty_name[9] = *ptr2;
706 /* Try to open master */
707 pty_master = open (pty_name, O_RDWR);
708 if (pty_master == -1)
710 if (errno == ENOENT) /* Different from EIO */
711 return -1; /* Out of pty devices */
712 continue; /* Try next pty device */
714 pty_name[5] = 't'; /* Change "pty" to "tty" */
715 if (access (pty_name, 6) != 0)
717 close (pty_master);
718 pty_name[5] = 'p';
719 continue;
721 return pty_master;
724 return -1; /* Ran out of pty devices */
727 /* --------------------------------------------------------------------------------------------- */
728 /** BSD version of pty_open_slave */
730 static int
731 pty_open_slave (const char *pty_name)
733 int pty_slave;
734 struct group *group_info = getgrnam ("tty");
736 if (group_info != NULL)
738 /* The following two calls will only succeed if we are root */
739 /* [Commented out while permissions problem is investigated] */
740 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
741 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
743 pty_slave = open (pty_name, O_RDWR);
744 if (pty_slave == -1)
745 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
746 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
747 return pty_slave;
749 #endif /* !HAVE_GRANTPT */
750 /* --------------------------------------------------------------------------------------------- */
751 /*** public functions ****************************************************************************/
752 /* --------------------------------------------------------------------------------------------- */
754 /* --------------------------------------------------------------------------------------------- */
756 * Fork the subshell, and set up many, many things.
758 * Possibly modifies the global variables:
759 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
760 * use_subshell - Is set to FALSE if we can't run the subshell
761 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
764 void
765 init_subshell (void)
767 /* This must be remembered across calls to init_subshell() */
768 static char pty_name[BUF_SMALL];
769 char precmd[BUF_SMALL];
771 switch (check_sid ())
773 case 1:
774 use_subshell = FALSE;
775 return;
776 case 2:
777 use_subshell = FALSE;
778 midnight_shutdown = 1;
779 return;
782 /* Take the current (hopefully pristine) tty mode and make */
783 /* a raw mode based on it now, before we do anything else with it */
784 init_raw_mode ();
786 if (subshell_pty == 0)
787 { /* First time through */
788 /* Find out what type of shell we have */
790 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
791 subshell_type = ZSH;
792 else if (strstr (shell, "/tcsh"))
793 subshell_type = TCSH;
794 else if (strstr (shell, "/csh"))
795 subshell_type = TCSH;
796 else if (strstr (shell, "/bash") || getenv ("BASH"))
797 subshell_type = BASH;
798 else if (strstr (shell, "/fish"))
799 subshell_type = FISH;
800 else
802 use_subshell = FALSE;
803 return;
806 /* Open a pty for talking to the subshell */
808 /* FIXME: We may need to open a fresh pty each time on SVR4 */
810 subshell_pty = pty_open_master (pty_name);
811 if (subshell_pty == -1)
813 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
814 use_subshell = FALSE;
815 return;
817 subshell_pty_slave = pty_open_slave (pty_name);
818 if (subshell_pty_slave == -1)
820 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
821 pty_name, unix_error_string (errno));
822 use_subshell = FALSE;
823 return;
826 /* Create a pipe for receiving the subshell's CWD */
828 if (subshell_type == TCSH)
830 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
831 mc_tmpdir (), (int) getpid ());
832 if (mkfifo (tcsh_fifo, 0600) == -1)
834 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
835 use_subshell = FALSE;
836 return;
839 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
841 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
842 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
844 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
845 perror (__FILE__ ": open");
846 use_subshell = FALSE;
847 return;
850 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
852 perror (__FILE__ ": couldn't create pipe");
853 use_subshell = FALSE;
854 return;
858 /* Fork the subshell */
860 subshell_alive = TRUE;
861 subshell_stopped = FALSE;
862 subshell_pid = fork ();
864 if (subshell_pid == -1)
866 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
867 /* We exit here because, if the process table is full, the */
868 /* other method of running user commands won't work either */
869 exit (EXIT_FAILURE);
872 if (subshell_pid == 0)
874 /* We are in the child process */
875 init_subshell_child (pty_name);
878 /* Set up `precmd' or equivalent for reading the subshell's CWD */
880 switch (subshell_type)
882 case BASH:
883 g_snprintf (precmd, sizeof (precmd),
884 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
885 break;
887 case ZSH:
888 g_snprintf (precmd, sizeof (precmd),
889 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
890 break;
892 case TCSH:
893 g_snprintf (precmd, sizeof (precmd),
894 "set echo_style=both;"
895 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
896 break;
897 case FISH:
898 g_snprintf (precmd, sizeof (precmd),
899 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
900 subshell_pipe[WRITE]);
901 break;
904 write_all (subshell_pty, precmd, strlen (precmd));
906 /* Wait until the subshell has started up and processed the command */
908 subshell_state = RUNNING_COMMAND;
909 tty_enable_interrupt_key ();
910 if (!feed_subshell (QUIETLY, TRUE))
912 use_subshell = FALSE;
914 tty_disable_interrupt_key ();
915 if (!subshell_alive)
916 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
919 /* --------------------------------------------------------------------------------------------- */
922 invoke_subshell (const char *command, int how, char **new_dir)
924 char *pcwd;
926 /* Make the MC terminal transparent */
927 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
929 /* Make the subshell change to MC's working directory */
930 if (new_dir != NULL)
931 do_subshell_chdir (current_panel->cwd, TRUE, TRUE);
933 if (command == NULL) /* The user has done "C-o" from MC */
935 if (subshell_state == INACTIVE)
937 subshell_state = ACTIVE;
938 /* FIXME: possibly take out this hack; the user can
939 re-play it by hitting C-hyphen a few times! */
940 if (subshell_ready)
941 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
944 else /* MC has passed us a user command */
946 if (how == QUIETLY)
947 write_all (subshell_pty, " ", 1);
948 /* FIXME: if command is long (>8KB ?) we go comma */
949 write_all (subshell_pty, command, strlen (command));
950 write_all (subshell_pty, "\n", 1);
951 subshell_state = RUNNING_COMMAND;
952 subshell_ready = FALSE;
955 feed_subshell (how, FALSE);
957 pcwd = vfs_translate_path_n (current_panel->cwd);
958 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
959 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
960 g_free (pcwd);
962 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
963 while (!subshell_alive && quit == 0 && use_subshell)
964 init_subshell ();
966 prompt_pos = 0;
968 return quit;
972 /* --------------------------------------------------------------------------------------------- */
975 read_subshell_prompt (void)
977 static int prompt_size = INITIAL_PROMPT_SIZE;
978 int bytes = 0, i, rc = 0;
979 struct timeval timeleft = { 0, 0 };
981 fd_set tmp;
982 FD_ZERO (&tmp);
983 FD_SET (subshell_pty, &tmp);
985 if (subshell_prompt == NULL)
986 { /* First time through */
987 subshell_prompt = g_malloc (prompt_size);
988 *subshell_prompt = '\0';
989 prompt_pos = 0;
992 while (subshell_alive && (rc = select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft)))
994 /* Check for `select' errors */
995 if (rc == -1)
997 if (errno == EINTR)
998 continue;
999 else
1001 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1002 exit (EXIT_FAILURE);
1006 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
1008 /* Extract the prompt from the shell output */
1010 for (i = 0; i < bytes; ++i)
1011 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1013 prompt_pos = 0;
1015 else
1017 if (!pty_buffer[i])
1018 continue;
1020 subshell_prompt[prompt_pos++] = pty_buffer[i];
1021 if (prompt_pos == prompt_size)
1022 subshell_prompt = g_realloc (subshell_prompt, prompt_size *= 2);
1025 subshell_prompt[prompt_pos] = '\0';
1027 if (rc == 0 && bytes == 0)
1028 return FALSE;
1029 return TRUE;
1032 /* --------------------------------------------------------------------------------------------- */
1034 void
1035 do_update_prompt (void)
1037 if (update_subshell_prompt)
1039 printf ("\r\n%s", subshell_prompt);
1040 fflush (stdout);
1041 update_subshell_prompt = FALSE;
1045 /* --------------------------------------------------------------------------------------------- */
1047 /** Resize given terminal using TIOCSWINSZ, return ioctl() result */
1048 static int
1049 resize_tty (int fd)
1051 #if defined TIOCSWINSZ
1052 struct winsize tty_size;
1054 tty_size.ws_row = LINES;
1055 tty_size.ws_col = COLS;
1056 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
1058 return ioctl (fd, TIOCSWINSZ, &tty_size);
1059 #else
1060 return 0;
1061 #endif
1064 /* --------------------------------------------------------------------------------------------- */
1065 /** Resize subshell_pty */
1067 void
1068 resize_subshell (void)
1070 if (use_subshell == 0)
1071 return;
1073 resize_tty (subshell_pty);
1076 /* --------------------------------------------------------------------------------------------- */
1079 exit_subshell (void)
1081 int subshell_quit = TRUE;
1083 if (subshell_state != INACTIVE && subshell_alive)
1084 subshell_quit =
1085 !query_dialog (_("Warning"),
1086 _("The shell is still active. Quit anyway?"),
1087 D_NORMAL, 2, _("&Yes"), _("&No"));
1089 if (subshell_quit)
1091 if (subshell_type == TCSH)
1093 if (unlink (tcsh_fifo) == -1)
1094 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1095 tcsh_fifo, unix_error_string (errno));
1098 g_free (subshell_prompt);
1099 subshell_prompt = NULL;
1100 pty_buffer[0] = '\0';
1103 return subshell_quit;
1107 /* --------------------------------------------------------------------------------------------- */
1109 * Carefully quote directory name to allow entering any directory safely,
1110 * no matter what weird characters it may contain in its name.
1111 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1112 * executing any commands in the shell. Escape all control characters.
1113 * Use following technique:
1115 * printf(1) with format string containing a single conversion specifier,
1116 * "b", and an argument which contains a copy of the string passed to
1117 * subshell_name_quote() with all characters, except digits and letters,
1118 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1119 * numeric value of the character converted to octal number.
1121 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1125 static char *
1126 subshell_name_quote (const char *s)
1128 char *ret, *d;
1129 const char *su, *n;
1130 const char *quote_cmd_start, *quote_cmd_end;
1131 int c;
1133 if (subshell_type == FISH)
1135 quote_cmd_start = "(printf \"%b\" '";
1136 quote_cmd_end = "')";
1138 else
1140 quote_cmd_start = "\"`printf \"%b\" '";
1141 quote_cmd_end = "'`\"";
1144 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1145 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
1146 + (strlen (quote_cmd_end)));
1147 if (d == NULL)
1148 return NULL;
1150 /* Prevent interpreting leading `-' as a switch for `cd' */
1151 if (*s == '-')
1153 *d++ = '.';
1154 *d++ = '/';
1157 /* Copy the beginning of the command to the buffer */
1158 strcpy (d, quote_cmd_start);
1159 d += strlen (quote_cmd_start);
1162 * Print every character except digits and letters as a backslash-escape
1163 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1164 * character converted to octal number.
1166 su = s;
1167 for (; su[0] != '\0';)
1169 n = str_cget_next_char_safe (su);
1170 if (str_isalnum (su))
1172 memcpy (d, su, n - su);
1173 d += n - su;
1175 else
1177 for (c = 0; c < n - su; c++)
1179 sprintf (d, "\\0%03o", (unsigned char) su[c]);
1180 d += 5;
1183 su = n;
1186 strcpy (d, quote_cmd_end);
1188 return ret;
1192 /* --------------------------------------------------------------------------------------------- */
1194 /** If it actually changed the directory it returns true */
1195 void
1196 do_subshell_chdir (const char *directory, gboolean update_prompt, gboolean reset_prompt)
1198 char *pcwd;
1199 char *temp;
1200 char *translate;
1202 pcwd = vfs_translate_path_n (current_panel->cwd);
1204 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1206 /* We have to repaint the subshell prompt if we read it from
1207 * the main program. Please note that in the code after this
1208 * if, the cd command that is sent will make the subshell
1209 * repaint the prompt, so we don't have to paint it. */
1210 if (update_prompt)
1211 do_update_prompt ();
1212 g_free (pcwd);
1213 return;
1216 /* The initial space keeps this out of the command history (in bash
1217 because we set "HISTCONTROL=ignorespace") */
1218 write_all (subshell_pty, " cd ", 4);
1219 if (*directory)
1221 translate = vfs_translate_path_n (directory);
1222 if (translate)
1224 temp = subshell_name_quote (translate);
1225 if (temp)
1227 write_all (subshell_pty, temp, strlen (temp));
1228 g_free (temp);
1230 else
1232 /* Should not happen unless the directory name is so long
1233 that we don't have memory to quote it. */
1234 write_all (subshell_pty, ".", 1);
1236 g_free (translate);
1238 else
1240 write_all (subshell_pty, ".", 1);
1243 else
1245 write_all (subshell_pty, "/", 1);
1247 write_all (subshell_pty, "\n", 1);
1249 subshell_state = RUNNING_COMMAND;
1250 feed_subshell (QUIETLY, FALSE);
1252 if (subshell_alive)
1254 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1256 if (bPathNotEq && subshell_type == TCSH)
1258 char rp_subshell_cwd[PATH_MAX];
1259 char rp_current_panel_cwd[PATH_MAX];
1261 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1262 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1264 if (p_subshell_cwd == NULL)
1265 p_subshell_cwd = subshell_cwd;
1266 if (p_current_panel_cwd == NULL)
1267 p_current_panel_cwd = pcwd;
1268 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1271 if (bPathNotEq && strcmp (pcwd, "."))
1273 char *cwd = strip_password (g_strdup (pcwd), 1);
1274 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
1275 g_free (cwd);
1279 if (reset_prompt)
1280 prompt_pos = 0;
1281 update_subshell_prompt = FALSE;
1283 g_free (pcwd);
1284 /* Make sure that MC never stores the CWD in a silly format */
1285 /* like /usr////lib/../bin, or the strcmp() above will fail */
1288 /* --------------------------------------------------------------------------------------------- */
1290 void
1291 subshell_get_console_attributes (void)
1293 /* Get our current terminal modes */
1295 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1297 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1298 use_subshell = FALSE;
1299 return;
1303 /* --------------------------------------------------------------------------------------------- */
1305 * Figure out whether the subshell has stopped, exited or been killed
1306 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1308 void
1309 sigchld_handler (int sig)
1311 int status;
1312 pid_t pid;
1314 (void) sig;
1316 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1318 if (pid == subshell_pid)
1320 /* Figure out what has happened to the subshell */
1322 if (WIFSTOPPED (status))
1324 if (WSTOPSIG (status) == SIGSTOP)
1326 /* The subshell has received a SIGSTOP signal */
1327 subshell_stopped = TRUE;
1329 else
1331 /* The user has suspended the subshell. Revive it */
1332 kill (subshell_pid, SIGCONT);
1335 else
1337 /* The subshell has either exited normally or been killed */
1338 subshell_alive = FALSE;
1339 delete_select_channel (subshell_pty);
1340 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1341 quit |= SUBSHELL_EXIT; /* Exited normally */
1344 #ifdef __linux__
1345 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1347 if (pid == cons_saver_pid)
1350 if (WIFSTOPPED (status))
1351 /* Someone has stopped cons.saver - restart it */
1352 kill (pid, SIGCONT);
1353 else
1355 /* cons.saver has died - disable confole saving */
1356 handle_console (CONSOLE_DONE);
1357 console_flag = 0;
1361 #endif /* __linux__ */
1363 /* If we got here, some other child exited; ignore it */
1366 /* --------------------------------------------------------------------------------------------- */
1368 #endif /* HAVE_SUBSHELL_SUPPORT */