Try fix of compile warnings about assigned but unused variables
[midnight-commander.git] / src / subshell.c
blob410a88d1e00feb2f6b1c416774abbd841f010a58
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 #ifdef HAVE_SUBSHELL_SUPPORT
32 #ifndef _GNU_SOURCE
33 #define _GNU_SOURCE 1
34 #endif
36 #include <ctype.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <errno.h>
40 #include <string.h>
41 #include <signal.h>
42 #include <fcntl.h>
43 #include <sys/types.h>
44 #include <sys/wait.h>
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
47 #endif
48 #include <termios.h>
49 #include <unistd.h>
51 #ifdef HAVE_STROPTS_H
52 #include <stropts.h> /* For I_PUSH */
53 #endif /* HAVE_STROPTS_H */
55 #include "lib/global.h"
57 #include "lib/tty/tty.h" /* LINES */
58 #include "lib/tty/key.h" /* XCTRL */
59 #include "lib/vfs/vfs.h"
60 #include "lib/strutil.h"
61 #include "lib/mcconfig.h"
62 #include "lib/util.h"
63 #include "lib/widget.h"
65 #include "filemanager/midnight.h" /* current_panel */
67 #include "consaver/cons.saver.h" /* handle_console() */
68 #include "subshell.h"
70 /*** global variables ****************************************************************************/
72 /* State of the subshell:
73 * INACTIVE: the default state; awaiting a command
74 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
75 * RUNNING_COMMAND: return to MC when the current command finishes */
76 enum subshell_state_enum subshell_state;
78 /* Holds the latest prompt captured from the subshell */
79 char *subshell_prompt = NULL;
81 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
82 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
83 gboolean update_subshell_prompt = FALSE;
85 /*** file scope macro definitions ****************************************************************/
87 #ifndef WEXITSTATUS
88 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
89 #endif
91 #ifndef WIFEXITED
92 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
93 #endif
95 #ifndef STDIN_FILENO
96 #define STDIN_FILENO 0
97 #endif
99 #ifndef STDOUT_FILENO
100 #define STDOUT_FILENO 1
101 #endif
103 #ifndef STDERR_FILENO
104 #define STDERR_FILENO 2
105 #endif
107 /* Initial length of the buffer for the subshell's prompt */
108 #define INITIAL_PROMPT_SIZE 10
110 /* Used by the child process to indicate failure to start the subshell */
111 #define FORK_FAILURE 69 /* Arbitrary */
113 /* Length of the buffer for all I/O with the subshell */
114 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
116 /*** file scope type declarations ****************************************************************/
118 /* For pipes */
119 enum
121 READ = 0,
122 WRITE = 1
125 /* Subshell type (gleaned from the SHELL environment variable, if available) */
126 static enum
128 BASH,
129 TCSH,
130 ZSH,
131 FISH
132 } subshell_type;
134 /*** file scope variables ************************************************************************/
136 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
137 static char tcsh_fifo[128];
139 static int subshell_pty_slave = -1;
141 /* The key for switching back to MC from the subshell */
142 /* *INDENT-OFF* */
143 static const char subshell_switch_key = XCTRL ('o') & 255;
144 /* *INDENT-ON* */
146 /* For reading/writing on the subshell's pty */
147 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
149 /* To pass CWD info from the subshell to MC */
150 static int subshell_pipe[2];
152 /* The subshell's process ID */
153 static pid_t subshell_pid = 1;
155 /* One extra char for final '\n' */
156 static char subshell_cwd[MC_MAXPATHLEN + 1];
158 /* Flag to indicate whether the subshell is ready for next command */
159 static int subshell_ready;
161 /* The following two flags can be changed by the SIGCHLD handler. This is */
162 /* OK, because the `int' type is updated atomically on all known machines */
163 static volatile int subshell_alive, subshell_stopped;
165 /* We store the terminal's initial mode here so that we can configure
166 the pty similarly, and also so we can restore the real terminal to
167 sanity if we have to exit abruptly */
168 static struct termios shell_mode;
170 /* This is a transparent mode for the terminal where MC is running on */
171 /* It is used when the shell is active, so that the control signals */
172 /* are delivered to the shell pty */
173 static struct termios raw_mode;
175 /* This counter indicates how many characters of prompt we have read */
176 /* FIXME: try to figure out why this had to become global */
177 static int prompt_pos;
180 /*** file scope functions ************************************************************************/
181 /* --------------------------------------------------------------------------------------------- */
183 * Write all data, even if the write() call is interrupted.
186 static ssize_t
187 write_all (int fd, const void *buf, size_t count)
189 ssize_t ret;
190 ssize_t written = 0;
191 while (count > 0)
193 ret = write (fd, (const unsigned char *) buf + written, count);
194 if (ret < 0)
196 if (errno == EINTR)
198 continue;
200 else
202 return written > 0 ? written : ret;
205 count -= ret;
206 written += ret;
208 return written;
211 /* --------------------------------------------------------------------------------------------- */
213 * Prepare child process to running the shell and run it.
215 * Modifies the global variables (in the child process only):
216 * shell_mode
218 * Returns: never.
221 static void
222 init_subshell_child (const char *pty_name)
224 char *init_file = NULL;
225 pid_t mc_sid;
227 (void) pty_name;
228 setsid (); /* Get a fresh terminal session */
230 /* Make sure that it has become our controlling terminal */
232 /* Redundant on Linux and probably most systems, but just in case: */
234 #ifdef TIOCSCTTY
235 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
236 #endif
238 /* Configure its terminal modes and window size */
240 /* Set up the pty with the same termios flags as our own tty */
241 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
243 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
244 _exit (FORK_FAILURE);
247 /* Set the pty's size (80x25 by default on Linux) according to the */
248 /* size of the real terminal as calculated by ncurses, if possible */
249 tty_resize (subshell_pty_slave);
251 /* Set up the subshell's environment and init file name */
253 /* It simplifies things to change to our home directory here, */
254 /* and the user's startup file may do a `cd' command anyway */
255 chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
257 /* Set MC_SID to prevent running one mc from another */
258 mc_sid = getsid (0);
259 if (mc_sid != -1)
261 char sid_str[BUF_SMALL];
262 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
263 putenv (g_strdup (sid_str));
266 switch (subshell_type)
268 case BASH:
269 init_file = mc_config_get_full_path ("bashrc");
271 if (access (init_file, R_OK) == -1)
273 g_free (init_file);
274 init_file = g_strdup (".bashrc");
277 /* Make MC's special commands not show up in bash's history */
278 putenv ((char *) "HISTCONTROL=ignorespace");
280 /* Allow alternative readline settings for MC */
282 char *input_file = mc_config_get_full_path ("inputrc");
283 if (access (input_file, R_OK) == 0)
285 char *putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
286 putenv (putenv_str);
287 g_free (putenv_str);
289 g_free (input_file);
292 break;
294 /* TODO: Find a way to pass initfile to TCSH and ZSH */
295 case TCSH:
296 case ZSH:
297 case FISH:
298 break;
300 default:
301 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
302 _exit (FORK_FAILURE);
305 /* Attach all our standard file descriptors to the pty */
307 /* This is done just before the fork, because stderr must still */
308 /* be connected to the real tty during the above error messages; */
309 /* otherwise the user will never see them. */
311 dup2 (subshell_pty_slave, STDIN_FILENO);
312 dup2 (subshell_pty_slave, STDOUT_FILENO);
313 dup2 (subshell_pty_slave, STDERR_FILENO);
315 close (subshell_pipe[READ]);
316 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
317 /* Close master side of pty. This is important; apart from */
318 /* freeing up the descriptor for use in the subshell, it also */
319 /* means that when MC exits, the subshell will get a SIGHUP and */
320 /* exit too, because there will be no more descriptors pointing */
321 /* at the master side of the pty and so it will disappear. */
322 close (mc_global.tty.subshell_pty);
324 /* Execute the subshell at last */
326 switch (subshell_type)
328 case BASH:
329 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
330 break;
332 case TCSH:
333 execl (shell, "tcsh", (char *) NULL);
334 break;
336 case ZSH:
337 /* Use -g to exclude cmds beginning with space from history
338 * and -Z to use the line editor on non-interactive term */
339 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
341 break;
343 case FISH:
344 execl (shell, "fish", (char *) NULL);
345 break;
348 /* If we get this far, everything failed miserably */
349 g_free (init_file);
350 _exit (FORK_FAILURE);
354 /* --------------------------------------------------------------------------------------------- */
356 * Check MC_SID to prevent running one mc from another.
357 * Return:
358 * 0 if no parent mc in our session was found,
359 * 1 if parent mc was found and the user wants to continue,
360 * 2 if parent mc was found and the user wants to quit mc.
363 static int
364 check_sid (void)
366 pid_t my_sid, old_sid;
367 const char *sid_str;
368 int r;
370 sid_str = getenv ("MC_SID");
371 if (!sid_str)
372 return 0;
374 old_sid = (pid_t) strtol (sid_str, NULL, 0);
375 if (!old_sid)
376 return 0;
378 my_sid = getsid (0);
379 if (my_sid == -1)
380 return 0;
382 /* The parent mc is in a different session, it's OK */
383 if (old_sid != my_sid)
384 return 0;
386 r = query_dialog (_("Warning"),
387 _("GNU Midnight Commander is already\n"
388 "running on this terminal.\n"
389 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
390 if (r != 0)
392 return 2;
395 return 1;
398 /* --------------------------------------------------------------------------------------------- */
400 static void
401 init_raw_mode ()
403 static int initialized = 0;
405 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
406 /* original settings. However, here we need to make this tty very raw, */
407 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
408 /* pty. So, instead of changing the code for execute(), pre_exec(), */
409 /* etc, we just set up the modes we need here, before each command. */
411 if (initialized == 0) /* First time: initialise `raw_mode' */
413 tcgetattr (STDOUT_FILENO, &raw_mode);
414 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
415 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
416 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
417 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
418 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
419 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
420 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
421 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
422 initialized = 1;
426 /* --------------------------------------------------------------------------------------------- */
428 * Wait until the subshell dies or stops. If it stops, make it resume.
429 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
432 static void
433 synchronize (void)
435 sigset_t sigchld_mask, old_mask;
437 sigemptyset (&sigchld_mask);
438 sigaddset (&sigchld_mask, SIGCHLD);
439 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
442 * SIGCHLD should not be blocked, but we unblock it just in case.
443 * This is known to be useful for cygwin 1.3.12 and older.
445 sigdelset (&old_mask, SIGCHLD);
447 /* Wait until the subshell has stopped */
448 while (subshell_alive && !subshell_stopped)
449 sigsuspend (&old_mask);
451 if (subshell_state != ACTIVE)
453 /* Discard all remaining data from stdin to the subshell */
454 tcflush (subshell_pty_slave, TCIFLUSH);
457 subshell_stopped = FALSE;
458 kill (subshell_pid, SIGCONT);
460 sigprocmask (SIG_SETMASK, &old_mask, NULL);
461 /* We can't do any better without modifying the shell(s) */
464 /* --------------------------------------------------------------------------------------------- */
465 /** Feed the subshell our keyboard input until it says it's finished */
467 static gboolean
468 feed_subshell (int how, int fail_on_error)
470 fd_set read_set; /* For `select' */
471 int maxfdp;
472 int bytes; /* For the return value from `read' */
473 int i; /* Loop counter */
475 struct timeval wtime; /* Maximum time we wait for the subshell */
476 struct timeval *wptr;
478 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
479 wtime.tv_sec = 10;
480 wtime.tv_usec = 0;
481 wptr = fail_on_error ? &wtime : NULL;
483 while (TRUE)
485 if (!subshell_alive)
486 return FALSE;
488 /* Prepare the file-descriptor set and call `select' */
490 FD_ZERO (&read_set);
491 FD_SET (mc_global.tty.subshell_pty, &read_set);
492 FD_SET (subshell_pipe[READ], &read_set);
493 maxfdp = max (mc_global.tty.subshell_pty, subshell_pipe[READ]);
494 if (how == VISIBLY)
496 FD_SET (STDIN_FILENO, &read_set);
497 maxfdp = max (maxfdp, STDIN_FILENO);
500 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
503 /* Despite using SA_RESTART, we still have to check for this */
504 if (errno == EINTR)
505 continue; /* try all over again */
506 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
507 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
508 unix_error_string (errno));
509 exit (EXIT_FAILURE);
512 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
513 /* Read from the subshell, write to stdout */
515 /* This loop improves performance by reducing context switches
516 by a factor of 20 or so... unfortunately, it also hangs MC
517 randomly, because of an apparent Linux bug. Investigate. */
518 /* for (i=0; i<5; ++i) * FIXME -- experimental */
520 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
522 /* The subshell has died */
523 if (bytes == -1 && errno == EIO && !subshell_alive)
524 return FALSE;
526 if (bytes <= 0)
528 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
529 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
530 exit (EXIT_FAILURE);
533 if (how == VISIBLY)
534 write_all (STDOUT_FILENO, pty_buffer, bytes);
537 else if (FD_ISSET (subshell_pipe[READ], &read_set))
538 /* Read the subshell's CWD and capture its prompt */
540 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
541 if (bytes <= 0)
543 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
544 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
545 unix_error_string (errno));
546 exit (EXIT_FAILURE);
549 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
551 synchronize ();
553 subshell_ready = TRUE;
554 if (subshell_state == RUNNING_COMMAND)
556 subshell_state = INACTIVE;
557 return TRUE;
561 else if (FD_ISSET (STDIN_FILENO, &read_set))
562 /* Read from stdin, write to the subshell */
564 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
565 if (bytes <= 0)
567 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
568 fprintf (stderr,
569 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
570 exit (EXIT_FAILURE);
573 for (i = 0; i < bytes; ++i)
574 if (pty_buffer[i] == subshell_switch_key)
576 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
577 if (subshell_ready)
578 subshell_state = INACTIVE;
579 return TRUE;
582 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
584 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
585 subshell_ready = FALSE;
587 else
588 return FALSE;
592 /* --------------------------------------------------------------------------------------------- */
593 /* pty opening functions */
595 #ifdef HAVE_GRANTPT
597 /* System V version of pty_open_master */
599 static int
600 pty_open_master (char *pty_name)
602 char *slave_name;
603 int pty_master;
605 #ifdef HAVE_POSIX_OPENPT
606 pty_master = posix_openpt (O_RDWR);
607 #elif HAVE_GETPT
608 /* getpt () is a GNU extension (glibc 2.1.x) */
609 pty_master = getpt ();
610 #elif IS_AIX
611 strcpy (pty_name, "/dev/ptc");
612 pty_master = open (pty_name, O_RDWR);
613 #else
614 strcpy (pty_name, "/dev/ptmx");
615 pty_master = open (pty_name, O_RDWR);
616 #endif
618 if (pty_master == -1)
619 return -1;
621 if (grantpt (pty_master) == -1 /* Grant access to slave */
622 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
623 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
625 close (pty_master);
626 return -1;
628 strcpy (pty_name, slave_name);
629 return pty_master;
632 /* --------------------------------------------------------------------------------------------- */
633 /** System V version of pty_open_slave */
635 static int
636 pty_open_slave (const char *pty_name)
638 int pty_slave = open (pty_name, O_RDWR);
640 if (pty_slave == -1)
642 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
643 return -1;
645 #if !defined(__osf__) && !defined(__linux__)
646 #if defined (I_FIND) && defined (I_PUSH)
647 if (!ioctl (pty_slave, I_FIND, "ptem"))
648 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
650 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
651 pty_slave, unix_error_string (errno));
652 close (pty_slave);
653 return -1;
656 if (!ioctl (pty_slave, I_FIND, "ldterm"))
657 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
659 fprintf (stderr,
660 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
661 pty_slave, unix_error_string (errno));
662 close (pty_slave);
663 return -1;
665 #if !defined(sgi) && !defined(__sgi)
666 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
667 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
669 fprintf (stderr,
670 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
671 pty_slave, unix_error_string (errno));
672 close (pty_slave);
673 return -1;
675 #endif /* sgi || __sgi */
676 #endif /* I_FIND && I_PUSH */
677 #endif /* __osf__ || __linux__ */
679 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
680 return pty_slave;
683 #else /* !HAVE_GRANTPT */
685 /* --------------------------------------------------------------------------------------------- */
686 /** BSD version of pty_open_master */
687 static int
688 pty_open_master (char *pty_name)
690 int pty_master;
691 const char *ptr1, *ptr2;
693 strcpy (pty_name, "/dev/ptyXX");
694 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
696 pty_name[8] = *ptr1;
697 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
699 pty_name[9] = *ptr2;
701 /* Try to open master */
702 pty_master = open (pty_name, O_RDWR);
703 if (pty_master == -1)
705 if (errno == ENOENT) /* Different from EIO */
706 return -1; /* Out of pty devices */
707 continue; /* Try next pty device */
709 pty_name[5] = 't'; /* Change "pty" to "tty" */
710 if (access (pty_name, 6) != 0)
712 close (pty_master);
713 pty_name[5] = 'p';
714 continue;
716 return pty_master;
719 return -1; /* Ran out of pty devices */
722 /* --------------------------------------------------------------------------------------------- */
723 /** BSD version of pty_open_slave */
725 static int
726 pty_open_slave (const char *pty_name)
728 int pty_slave;
729 struct group *group_info = getgrnam ("tty");
731 if (group_info != NULL)
733 /* The following two calls will only succeed if we are root */
734 /* [Commented out while permissions problem is investigated] */
735 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
736 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
738 pty_slave = open (pty_name, O_RDWR);
739 if (pty_slave == -1)
740 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
741 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
742 return pty_slave;
744 #endif /* !HAVE_GRANTPT */
746 /* --------------------------------------------------------------------------------------------- */
747 /*** public functions ****************************************************************************/
748 /* --------------------------------------------------------------------------------------------- */
750 /* --------------------------------------------------------------------------------------------- */
752 * Fork the subshell, and set up many, many things.
754 * Possibly modifies the global variables:
755 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
756 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
757 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
760 void
761 init_subshell (void)
763 /* This must be remembered across calls to init_subshell() */
764 static char pty_name[BUF_SMALL];
765 char precmd[BUF_SMALL];
767 switch (check_sid ())
769 case 1:
770 mc_global.tty.use_subshell = FALSE;
771 return;
772 case 2:
773 mc_global.tty.use_subshell = FALSE;
774 mc_global.midnight_shutdown = TRUE;
775 return;
778 /* Take the current (hopefully pristine) tty mode and make */
779 /* a raw mode based on it now, before we do anything else with it */
780 init_raw_mode ();
782 if (mc_global.tty.subshell_pty == 0)
783 { /* First time through */
784 /* Find out what type of shell we have */
786 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
787 subshell_type = ZSH;
788 else if (strstr (shell, "/tcsh"))
789 subshell_type = TCSH;
790 else if (strstr (shell, "/csh"))
791 subshell_type = TCSH;
792 else if (strstr (shell, "/bash") || getenv ("BASH"))
793 subshell_type = BASH;
794 else if (strstr (shell, "/fish"))
795 subshell_type = FISH;
796 else
798 mc_global.tty.use_subshell = FALSE;
799 return;
802 /* Open a pty for talking to the subshell */
804 /* FIXME: We may need to open a fresh pty each time on SVR4 */
806 mc_global.tty.subshell_pty = pty_open_master (pty_name);
807 if (mc_global.tty.subshell_pty == -1)
809 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
810 mc_global.tty.use_subshell = FALSE;
811 return;
813 subshell_pty_slave = pty_open_slave (pty_name);
814 if (subshell_pty_slave == -1)
816 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
817 pty_name, unix_error_string (errno));
818 mc_global.tty.use_subshell = FALSE;
819 return;
822 /* Create a pipe for receiving the subshell's CWD */
824 if (subshell_type == TCSH)
826 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
827 mc_tmpdir (), (int) getpid ());
828 if (mkfifo (tcsh_fifo, 0600) == -1)
830 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
831 mc_global.tty.use_subshell = FALSE;
832 return;
835 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
837 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
838 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
840 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
841 perror (__FILE__ ": open");
842 mc_global.tty.use_subshell = FALSE;
843 return;
846 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
848 perror (__FILE__ ": couldn't create pipe");
849 mc_global.tty.use_subshell = FALSE;
850 return;
854 /* Fork the subshell */
856 subshell_alive = TRUE;
857 subshell_stopped = FALSE;
858 subshell_pid = fork ();
860 if (subshell_pid == -1)
862 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
863 /* We exit here because, if the process table is full, the */
864 /* other method of running user commands won't work either */
865 exit (EXIT_FAILURE);
868 if (subshell_pid == 0)
870 /* We are in the child process */
871 init_subshell_child (pty_name);
874 /* Set up `precmd' or equivalent for reading the subshell's CWD */
876 switch (subshell_type)
878 case BASH:
879 g_snprintf (precmd, sizeof (precmd),
880 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
881 break;
883 case ZSH:
884 g_snprintf (precmd, sizeof (precmd),
885 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
886 break;
888 case TCSH:
889 g_snprintf (precmd, sizeof (precmd),
890 "set echo_style=both;"
891 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
892 break;
893 case FISH:
894 g_snprintf (precmd, sizeof (precmd),
895 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
896 subshell_pipe[WRITE]);
897 break;
900 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
902 /* Wait until the subshell has started up and processed the command */
904 subshell_state = RUNNING_COMMAND;
905 tty_enable_interrupt_key ();
906 if (!feed_subshell (QUIETLY, TRUE))
908 mc_global.tty.use_subshell = FALSE;
910 tty_disable_interrupt_key ();
911 if (!subshell_alive)
912 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
915 /* --------------------------------------------------------------------------------------------- */
918 invoke_subshell (const char *command, int how, vfs_path_t ** new_dir_vpath)
920 char *pcwd;
922 /* Make the MC terminal transparent */
923 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
925 /* Make the subshell change to MC's working directory */
926 if (new_dir_vpath != NULL)
927 do_subshell_chdir (current_panel->cwd_vpath, TRUE, TRUE);
929 if (command == NULL) /* The user has done "C-o" from MC */
931 if (subshell_state == INACTIVE)
933 subshell_state = ACTIVE;
934 /* FIXME: possibly take out this hack; the user can
935 re-play it by hitting C-hyphen a few times! */
936 if (subshell_ready)
937 write_all (mc_global.tty.subshell_pty, " \b", 2); /* Hack to make prompt reappear */
940 else /* MC has passed us a user command */
942 if (how == QUIETLY)
943 write_all (mc_global.tty.subshell_pty, " ", 1);
944 /* FIXME: if command is long (>8KB ?) we go comma */
945 write_all (mc_global.tty.subshell_pty, command, strlen (command));
946 write_all (mc_global.tty.subshell_pty, "\n", 1);
947 subshell_state = RUNNING_COMMAND;
948 subshell_ready = FALSE;
951 feed_subshell (how, FALSE);
954 char *cwd_str;
956 cwd_str = vfs_path_to_str (current_panel->cwd_vpath);
957 pcwd = vfs_translate_path_n (cwd_str);
958 g_free (cwd_str);
961 if (new_dir_vpath != NULL && subshell_alive && strcmp (subshell_cwd, pcwd))
962 *new_dir_vpath = vfs_path_from_str (subshell_cwd); /* Make MC change to the subshell's CWD */
963 g_free (pcwd);
965 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
966 while (!subshell_alive && quit == 0 && mc_global.tty.use_subshell)
967 init_subshell ();
969 prompt_pos = 0;
971 return quit;
975 /* --------------------------------------------------------------------------------------------- */
978 read_subshell_prompt (void)
980 static int prompt_size = INITIAL_PROMPT_SIZE;
981 int bytes = 0, i, rc = 0;
982 struct timeval timeleft = { 0, 0 };
984 fd_set tmp;
985 FD_ZERO (&tmp);
986 FD_SET (mc_global.tty.subshell_pty, &tmp);
988 if (subshell_prompt == NULL)
989 { /* First time through */
990 subshell_prompt = g_malloc (prompt_size);
991 *subshell_prompt = '\0';
992 prompt_pos = 0;
995 while (subshell_alive
996 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)))
998 /* Check for `select' errors */
999 if (rc == -1)
1001 if (errno == EINTR)
1002 continue;
1003 else
1005 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1006 exit (EXIT_FAILURE);
1010 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1012 /* Extract the prompt from the shell output */
1014 for (i = 0; i < bytes; ++i)
1015 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1017 prompt_pos = 0;
1019 else
1021 if (!pty_buffer[i])
1022 continue;
1024 subshell_prompt[prompt_pos++] = pty_buffer[i];
1025 if (prompt_pos == prompt_size)
1026 subshell_prompt = g_realloc (subshell_prompt, prompt_size *= 2);
1029 subshell_prompt[prompt_pos] = '\0';
1031 if (rc == 0 && bytes == 0)
1032 return FALSE;
1033 return TRUE;
1036 /* --------------------------------------------------------------------------------------------- */
1038 void
1039 do_update_prompt (void)
1041 if (update_subshell_prompt)
1043 printf ("\r\n%s", subshell_prompt);
1044 fflush (stdout);
1045 update_subshell_prompt = FALSE;
1049 /* --------------------------------------------------------------------------------------------- */
1052 exit_subshell (void)
1054 int subshell_quit = TRUE;
1056 if (subshell_state != INACTIVE && subshell_alive)
1057 subshell_quit =
1058 !query_dialog (_("Warning"),
1059 _("The shell is still active. Quit anyway?"),
1060 D_NORMAL, 2, _("&Yes"), _("&No"));
1062 if (subshell_quit)
1064 if (subshell_type == TCSH)
1066 if (unlink (tcsh_fifo) == -1)
1067 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1068 tcsh_fifo, unix_error_string (errno));
1071 g_free (subshell_prompt);
1072 subshell_prompt = NULL;
1073 pty_buffer[0] = '\0';
1076 return subshell_quit;
1079 /* --------------------------------------------------------------------------------------------- */
1081 * Carefully quote directory name to allow entering any directory safely,
1082 * no matter what weird characters it may contain in its name.
1083 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1084 * executing any commands in the shell. Escape all control characters.
1085 * Use following technique:
1087 * printf(1) with format string containing a single conversion specifier,
1088 * "b", and an argument which contains a copy of the string passed to
1089 * subshell_name_quote() with all characters, except digits and letters,
1090 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1091 * numeric value of the character converted to octal number.
1093 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1097 static char *
1098 subshell_name_quote (const char *s)
1100 char *ret, *d;
1101 const char *su, *n;
1102 const char *quote_cmd_start, *quote_cmd_end;
1103 int c;
1105 if (subshell_type == FISH)
1107 quote_cmd_start = "(printf \"%b\" '";
1108 quote_cmd_end = "')";
1110 else
1112 quote_cmd_start = "\"`printf \"%b\" '";
1113 quote_cmd_end = "'`\"";
1116 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1117 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
1118 + (strlen (quote_cmd_end)));
1119 if (d == NULL)
1120 return NULL;
1122 /* Prevent interpreting leading `-' as a switch for `cd' */
1123 if (*s == '-')
1125 *d++ = '.';
1126 *d++ = '/';
1129 /* Copy the beginning of the command to the buffer */
1130 strcpy (d, quote_cmd_start);
1131 d += strlen (quote_cmd_start);
1134 * Print every character except digits and letters as a backslash-escape
1135 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1136 * character converted to octal number.
1138 su = s;
1139 for (; su[0] != '\0';)
1141 n = str_cget_next_char_safe (su);
1142 if (str_isalnum (su))
1144 memcpy (d, su, n - su);
1145 d += n - su;
1147 else
1149 for (c = 0; c < n - su; c++)
1151 sprintf (d, "\\0%03o", (unsigned char) su[c]);
1152 d += 5;
1155 su = n;
1158 strcpy (d, quote_cmd_end);
1160 return ret;
1164 /* --------------------------------------------------------------------------------------------- */
1166 /** If it actually changed the directory it returns true */
1167 void
1168 do_subshell_chdir (const vfs_path_t * vpath, gboolean update_prompt, gboolean reset_prompt)
1170 char *pcwd;
1171 char *temp;
1172 char *directory;
1174 pcwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_RECODE);
1176 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1178 /* We have to repaint the subshell prompt if we read it from
1179 * the main program. Please note that in the code after this
1180 * if, the cd command that is sent will make the subshell
1181 * repaint the prompt, so we don't have to paint it. */
1182 if (update_prompt)
1183 do_update_prompt ();
1184 g_free (pcwd);
1185 return;
1188 /* The initial space keeps this out of the command history (in bash
1189 because we set "HISTCONTROL=ignorespace") */
1190 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1192 directory = vfs_path_to_str (vpath);
1193 if (directory != '\0')
1195 char *translate;
1197 translate = vfs_translate_path_n (directory);
1198 if (translate != NULL)
1200 temp = subshell_name_quote (translate);
1201 if (temp)
1203 write_all (mc_global.tty.subshell_pty, temp, strlen (temp));
1204 g_free (temp);
1206 else
1208 /* Should not happen unless the directory name is so long
1209 that we don't have memory to quote it. */
1210 write_all (mc_global.tty.subshell_pty, ".", 1);
1212 g_free (translate);
1214 else
1216 write_all (mc_global.tty.subshell_pty, ".", 1);
1219 else
1221 write_all (mc_global.tty.subshell_pty, "/", 1);
1223 g_free (directory);
1224 write_all (mc_global.tty.subshell_pty, "\n", 1);
1226 subshell_state = RUNNING_COMMAND;
1227 feed_subshell (QUIETLY, FALSE);
1229 if (subshell_alive)
1231 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1233 if (bPathNotEq && subshell_type == TCSH)
1235 char rp_subshell_cwd[PATH_MAX];
1236 char rp_current_panel_cwd[PATH_MAX];
1238 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1239 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1241 if (p_subshell_cwd == NULL)
1242 p_subshell_cwd = subshell_cwd;
1243 if (p_current_panel_cwd == NULL)
1244 p_current_panel_cwd = pcwd;
1245 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1248 if (bPathNotEq && strcmp (pcwd, ".") != 0)
1250 char *cwd;
1252 cwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_STRIP_PASSWORD);
1253 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd);
1254 g_free (cwd);
1258 if (reset_prompt)
1259 prompt_pos = 0;
1260 update_subshell_prompt = FALSE;
1262 g_free (pcwd);
1263 /* Make sure that MC never stores the CWD in a silly format */
1264 /* like /usr////lib/../bin, or the strcmp() above will fail */
1267 /* --------------------------------------------------------------------------------------------- */
1269 void
1270 subshell_get_console_attributes (void)
1272 /* Get our current terminal modes */
1274 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1276 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1277 mc_global.tty.use_subshell = FALSE;
1281 /* --------------------------------------------------------------------------------------------- */
1283 * Figure out whether the subshell has stopped, exited or been killed
1284 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1286 void
1287 sigchld_handler (int sig)
1289 int status;
1290 pid_t pid;
1292 (void) sig;
1294 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1296 if (pid == subshell_pid)
1298 /* Figure out what has happened to the subshell */
1300 if (WIFSTOPPED (status))
1302 if (WSTOPSIG (status) == SIGSTOP)
1304 /* The subshell has received a SIGSTOP signal */
1305 subshell_stopped = TRUE;
1307 else
1309 /* The user has suspended the subshell. Revive it */
1310 kill (subshell_pid, SIGCONT);
1313 else
1315 /* The subshell has either exited normally or been killed */
1316 subshell_alive = FALSE;
1317 delete_select_channel (mc_global.tty.subshell_pty);
1318 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1319 quit |= SUBSHELL_EXIT; /* Exited normally */
1322 #ifdef __linux__
1323 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1325 if (pid == cons_saver_pid)
1328 if (WIFSTOPPED (status))
1329 /* Someone has stopped cons.saver - restart it */
1330 kill (pid, SIGCONT);
1331 else
1333 /* cons.saver has died - disable confole saving */
1334 handle_console (CONSOLE_DONE);
1335 mc_global.tty.console_flag = '\0';
1339 #endif /* __linux__ */
1341 /* If we got here, some other child exited; ignore it */
1344 /* --------------------------------------------------------------------------------------------- */
1346 #endif /* HAVE_SUBSHELL_SUPPORT */