Merge branch '2743_search_unicode'
[midnight-commander.git] / src / subshell.c
blob81c9f7147c11ff37e0dc23c07f1327de3b148a3a
1 /*
2 Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994-2014
5 Free Software Foundation, Inc.
7 Written by:
8 Slava Zanko <slavazanko@gmail.com>, 2013
10 This file is part of the Midnight Commander.
12 The Midnight Commander is free software: you can redistribute it
13 and/or modify it under the terms of the GNU General Public License as
14 published by the Free Software Foundation, either version 3 of the License,
15 or (at your option) any later version.
17 The Midnight Commander is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 /** \file subshell.c
27 * \brief Source: concurrent shell support
30 #include <config.h>
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>
50 #ifdef HAVE_STROPTS_H
51 #include <stropts.h> /* For I_PUSH */
52 #endif /* HAVE_STROPTS_H */
54 #include "lib/global.h"
56 #include "lib/unixcompat.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 "setup.h"
69 #include "subshell.h"
71 /*** global variables ****************************************************************************/
73 /* State of the subshell:
74 * INACTIVE: the default state; awaiting a command
75 * ACTIVE: remain in the shell until the user hits 'subshell_switch_key'
76 * RUNNING_COMMAND: return to MC when the current command finishes */
77 enum subshell_state_enum subshell_state;
79 /* Holds the latest prompt captured from the subshell */
80 GString *subshell_prompt = NULL;
82 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
83 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
84 gboolean update_subshell_prompt = FALSE;
86 /*** file scope macro definitions ****************************************************************/
88 #ifndef WEXITSTATUS
89 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
90 #endif
92 #ifndef WIFEXITED
93 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
94 #endif
96 /* Initial length of the buffer for the subshell's prompt */
97 #define INITIAL_PROMPT_SIZE 10
99 /* Used by the child process to indicate failure to start the subshell */
100 #define FORK_FAILURE 69 /* Arbitrary */
102 /* Length of the buffer for all I/O with the subshell */
103 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
105 /*** file scope type declarations ****************************************************************/
107 /* For pipes */
108 enum
110 READ = 0,
111 WRITE = 1
114 /* Subshell type (gleaned from the SHELL environment variable, if available) */
115 static enum
117 BASH,
118 TCSH,
119 ZSH,
120 FISH
121 } subshell_type;
123 /*** file scope variables ************************************************************************/
125 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
126 static char tcsh_fifo[128];
128 static int subshell_pty_slave = -1;
130 /* The key for switching back to MC from the subshell */
131 /* *INDENT-OFF* */
132 static const char subshell_switch_key = XCTRL ('o') & 255;
133 /* *INDENT-ON* */
135 /* For reading/writing on the subshell's pty */
136 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
138 /* To pass CWD info from the subshell to MC */
139 static int subshell_pipe[2];
141 /* The subshell's process ID */
142 static pid_t subshell_pid = 1;
144 /* One extra char for final '\n' */
145 static char subshell_cwd[MC_MAXPATHLEN + 1];
147 /* Flag to indicate whether the subshell is ready for next command */
148 static int subshell_ready;
150 /* The following two flags can be changed by the SIGCHLD handler. This is */
151 /* OK, because the 'int' type is updated atomically on all known machines */
152 static volatile int subshell_alive, subshell_stopped;
154 /* We store the terminal's initial mode here so that we can configure
155 the pty similarly, and also so we can restore the real terminal to
156 sanity if we have to exit abruptly */
157 static struct termios shell_mode;
159 /* This is a transparent mode for the terminal where MC is running on */
160 /* It is used when the shell is active, so that the control signals */
161 /* are delivered to the shell pty */
162 static struct termios raw_mode;
164 /* --------------------------------------------------------------------------------------------- */
165 /*** file scope functions ************************************************************************/
166 /* --------------------------------------------------------------------------------------------- */
168 * Write all data, even if the write() call is interrupted.
171 static ssize_t
172 write_all (int fd, const void *buf, size_t count)
174 ssize_t written = 0;
176 while (count > 0)
178 ssize_t ret;
180 ret = write (fd, (const unsigned char *) buf + written, count);
181 if (ret < 0)
183 if (errno == EINTR)
185 if (mc_global.tty.winch_flag != 0)
186 tty_change_screen_size ();
188 continue;
191 return written > 0 ? written : ret;
193 count -= ret;
194 written += ret;
196 return written;
199 /* --------------------------------------------------------------------------------------------- */
201 * Prepare child process to running the shell and run it.
203 * Modifies the global variables (in the child process only):
204 * shell_mode
206 * Returns: never.
209 static void
210 init_subshell_child (const char *pty_name)
212 char *init_file = NULL;
213 pid_t mc_sid;
215 (void) pty_name;
216 setsid (); /* Get a fresh terminal session */
218 /* Make sure that it has become our controlling terminal */
220 /* Redundant on Linux and probably most systems, but just in case: */
222 #ifdef TIOCSCTTY
223 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
224 #endif
226 /* Configure its terminal modes and window size */
228 /* Set up the pty with the same termios flags as our own tty */
229 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
231 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
232 my_exit (FORK_FAILURE);
235 /* Set the pty's size (80x25 by default on Linux) according to the */
236 /* size of the real terminal as calculated by ncurses, if possible */
237 tty_resize (subshell_pty_slave);
239 /* Set up the subshell's environment and init file name */
241 /* It simplifies things to change to our home directory here, */
242 /* and the user's startup file may do a 'cd' command anyway */
244 int ret;
245 ret = chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
246 (void) ret;
249 /* Set MC_SID to prevent running one mc from another */
250 mc_sid = getsid (0);
251 if (mc_sid != -1)
253 char sid_str[BUF_SMALL];
254 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
255 putenv (g_strdup (sid_str));
258 switch (subshell_type)
260 case BASH:
261 init_file = mc_config_get_full_path ("bashrc");
263 if (access (init_file, R_OK) == -1)
265 g_free (init_file);
266 init_file = g_strdup (".bashrc");
269 /* Make MC's special commands not show up in bash's history */
270 putenv ((char *) "HISTCONTROL=ignorespace");
272 /* Allow alternative readline settings for MC */
274 char *input_file = mc_config_get_full_path ("inputrc");
275 if (access (input_file, R_OK) == 0)
277 char *putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
278 putenv (putenv_str);
279 g_free (putenv_str);
281 g_free (input_file);
284 break;
286 /* TODO: Find a way to pass initfile to TCSH and ZSH */
287 case TCSH:
288 case ZSH:
289 case FISH:
290 break;
292 default:
293 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
294 my_exit (FORK_FAILURE);
297 /* Attach all our standard file descriptors to the pty */
299 /* This is done just before the fork, because stderr must still */
300 /* be connected to the real tty during the above error messages; */
301 /* otherwise the user will never see them. */
303 dup2 (subshell_pty_slave, STDIN_FILENO);
304 dup2 (subshell_pty_slave, STDOUT_FILENO);
305 dup2 (subshell_pty_slave, STDERR_FILENO);
307 close (subshell_pipe[READ]);
308 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
309 /* Close master side of pty. This is important; apart from */
310 /* freeing up the descriptor for use in the subshell, it also */
311 /* means that when MC exits, the subshell will get a SIGHUP and */
312 /* exit too, because there will be no more descriptors pointing */
313 /* at the master side of the pty and so it will disappear. */
314 close (mc_global.tty.subshell_pty);
316 /* Execute the subshell at last */
318 switch (subshell_type)
320 case BASH:
321 execl (mc_global.tty.shell, "bash", "-rcfile", init_file, (char *) NULL);
322 break;
324 case TCSH:
325 execl (mc_global.tty.shell, "tcsh", (char *) NULL);
326 break;
328 case ZSH:
329 /* Use -g to exclude cmds beginning with space from history
330 * and -Z to use the line editor on non-interactive term */
331 execl (mc_global.tty.shell, "zsh", "-Z", "-g", (char *) NULL);
333 break;
335 case FISH:
336 execl (mc_global.tty.shell, "fish", (char *) NULL);
337 break;
340 /* If we get this far, everything failed miserably */
341 g_free (init_file);
342 my_exit (FORK_FAILURE);
346 /* --------------------------------------------------------------------------------------------- */
348 * Check MC_SID to prevent running one mc from another.
349 * Return:
350 * 0 if no parent mc in our session was found,
351 * 1 if parent mc was found and the user wants to continue,
352 * 2 if parent mc was found and the user wants to quit mc.
355 static int
356 check_sid (void)
358 pid_t my_sid, old_sid;
359 const char *sid_str;
360 int r;
362 sid_str = getenv ("MC_SID");
363 if (!sid_str)
364 return 0;
366 old_sid = (pid_t) strtol (sid_str, NULL, 0);
367 if (!old_sid)
368 return 0;
370 my_sid = getsid (0);
371 if (my_sid == -1)
372 return 0;
374 /* The parent mc is in a different session, it's OK */
375 if (old_sid != my_sid)
376 return 0;
378 r = query_dialog (_("Warning"),
379 _("GNU Midnight Commander is already\n"
380 "running on this terminal.\n"
381 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
382 if (r != 0)
384 return 2;
387 return 1;
390 /* --------------------------------------------------------------------------------------------- */
392 static void
393 init_raw_mode ()
395 static int initialized = 0;
397 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
398 /* original settings. However, here we need to make this tty very raw, */
399 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
400 /* pty. So, instead of changing the code for execute(), pre_exec(), */
401 /* etc, we just set up the modes we need here, before each command. */
403 if (initialized == 0) /* First time: initialise 'raw_mode' */
405 tcgetattr (STDOUT_FILENO, &raw_mode);
406 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
407 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
408 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
409 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
410 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
411 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
412 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
413 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
414 initialized = 1;
418 /* --------------------------------------------------------------------------------------------- */
420 * Wait until the subshell dies or stops. If it stops, make it resume.
421 * Possibly modifies the globals 'subshell_alive' and 'subshell_stopped'
424 static void
425 synchronize (void)
427 sigset_t sigchld_mask, old_mask;
429 sigemptyset (&sigchld_mask);
430 sigaddset (&sigchld_mask, SIGCHLD);
431 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
434 * SIGCHLD should not be blocked, but we unblock it just in case.
435 * This is known to be useful for cygwin 1.3.12 and older.
437 sigdelset (&old_mask, SIGCHLD);
439 /* Wait until the subshell has stopped */
440 while (subshell_alive && !subshell_stopped)
441 sigsuspend (&old_mask);
443 if (subshell_state != ACTIVE)
445 /* Discard all remaining data from stdin to the subshell */
446 tcflush (subshell_pty_slave, TCIFLUSH);
449 subshell_stopped = FALSE;
450 kill (subshell_pid, SIGCONT);
452 sigprocmask (SIG_SETMASK, &old_mask, NULL);
453 /* We can't do any better without modifying the shell(s) */
456 /* --------------------------------------------------------------------------------------------- */
457 /** Feed the subshell our keyboard input until it says it's finished */
459 static gboolean
460 feed_subshell (int how, int fail_on_error)
462 fd_set read_set; /* For 'select' */
463 int bytes; /* For the return value from 'read' */
464 int i; /* Loop counter */
466 struct timeval wtime; /* Maximum time we wait for the subshell */
467 struct timeval *wptr;
469 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
470 wtime.tv_sec = 10;
471 wtime.tv_usec = 0;
472 wptr = fail_on_error ? &wtime : NULL;
474 while (TRUE)
476 int maxfdp;
478 if (!subshell_alive)
479 return FALSE;
481 /* Prepare the file-descriptor set and call 'select' */
483 FD_ZERO (&read_set);
484 FD_SET (mc_global.tty.subshell_pty, &read_set);
485 FD_SET (subshell_pipe[READ], &read_set);
486 maxfdp = max (mc_global.tty.subshell_pty, subshell_pipe[READ]);
487 if (how == VISIBLY)
489 FD_SET (STDIN_FILENO, &read_set);
490 maxfdp = max (maxfdp, STDIN_FILENO);
493 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
495 /* Despite using SA_RESTART, we still have to check for this */
496 if (errno == EINTR)
498 if (mc_global.tty.winch_flag != 0)
499 tty_change_screen_size ();
501 continue; /* try all over again */
503 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
504 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
505 unix_error_string (errno));
506 exit (EXIT_FAILURE);
509 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
510 /* Read from the subshell, write to stdout */
512 /* This loop improves performance by reducing context switches
513 by a factor of 20 or so... unfortunately, it also hangs MC
514 randomly, because of an apparent Linux bug. Investigate. */
515 /* for (i=0; i<5; ++i) * FIXME -- experimental */
517 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
519 /* The subshell has died */
520 if (bytes == -1 && errno == EIO && !subshell_alive)
521 return FALSE;
523 if (bytes <= 0)
525 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
526 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
527 exit (EXIT_FAILURE);
530 if (how == VISIBLY)
531 write_all (STDOUT_FILENO, pty_buffer, bytes);
534 else if (FD_ISSET (subshell_pipe[READ], &read_set))
535 /* Read the subshell's CWD and capture its prompt */
537 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
538 if (bytes <= 0)
540 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
541 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
542 unix_error_string (errno));
543 exit (EXIT_FAILURE);
546 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
548 synchronize ();
550 subshell_ready = TRUE;
551 if (subshell_state == RUNNING_COMMAND)
553 subshell_state = INACTIVE;
554 return TRUE;
558 else if (FD_ISSET (STDIN_FILENO, &read_set))
559 /* Read from stdin, write to the subshell */
561 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
562 if (bytes <= 0)
564 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
565 fprintf (stderr,
566 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
567 exit (EXIT_FAILURE);
570 for (i = 0; i < bytes; ++i)
571 if (pty_buffer[i] == subshell_switch_key)
573 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
574 if (subshell_ready)
575 subshell_state = INACTIVE;
576 return TRUE;
579 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
581 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
582 subshell_ready = FALSE;
584 else
585 return FALSE;
589 /* --------------------------------------------------------------------------------------------- */
590 /* pty opening functions */
592 #ifdef HAVE_GRANTPT
594 /* System V version of pty_open_master */
596 static int
597 pty_open_master (char *pty_name)
599 char *slave_name;
600 int pty_master;
602 #ifdef HAVE_POSIX_OPENPT
603 pty_master = posix_openpt (O_RDWR);
604 #elif HAVE_GETPT
605 /* getpt () is a GNU extension (glibc 2.1.x) */
606 pty_master = getpt ();
607 #elif IS_AIX
608 strcpy (pty_name, "/dev/ptc");
609 pty_master = open (pty_name, O_RDWR);
610 #else
611 strcpy (pty_name, "/dev/ptmx");
612 pty_master = open (pty_name, O_RDWR);
613 #endif
615 if (pty_master == -1)
616 return -1;
618 if (grantpt (pty_master) == -1 /* Grant access to slave */
619 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
620 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
622 close (pty_master);
623 return -1;
625 strcpy (pty_name, slave_name);
626 return pty_master;
629 /* --------------------------------------------------------------------------------------------- */
630 /** System V version of pty_open_slave */
632 static int
633 pty_open_slave (const char *pty_name)
635 int pty_slave = open (pty_name, O_RDWR);
637 if (pty_slave == -1)
639 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
640 return -1;
642 #if !defined(__osf__) && !defined(__linux__)
643 #if defined (I_FIND) && defined (I_PUSH)
644 if (!ioctl (pty_slave, I_FIND, "ptem"))
645 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
647 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
648 pty_slave, unix_error_string (errno));
649 close (pty_slave);
650 return -1;
653 if (!ioctl (pty_slave, I_FIND, "ldterm"))
654 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
656 fprintf (stderr,
657 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
658 pty_slave, unix_error_string (errno));
659 close (pty_slave);
660 return -1;
662 #if !defined(sgi) && !defined(__sgi)
663 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
664 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
666 fprintf (stderr,
667 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
668 pty_slave, unix_error_string (errno));
669 close (pty_slave);
670 return -1;
672 #endif /* sgi || __sgi */
673 #endif /* I_FIND && I_PUSH */
674 #endif /* __osf__ || __linux__ */
676 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
677 return pty_slave;
680 #else /* !HAVE_GRANTPT */
682 /* --------------------------------------------------------------------------------------------- */
683 /** BSD version of pty_open_master */
684 static int
685 pty_open_master (char *pty_name)
687 int pty_master;
688 const char *ptr1, *ptr2;
690 strcpy (pty_name, "/dev/ptyXX");
691 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
693 pty_name[8] = *ptr1;
694 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
696 pty_name[9] = *ptr2;
698 /* Try to open master */
699 pty_master = open (pty_name, O_RDWR);
700 if (pty_master == -1)
702 if (errno == ENOENT) /* Different from EIO */
703 return -1; /* Out of pty devices */
704 continue; /* Try next pty device */
706 pty_name[5] = 't'; /* Change "pty" to "tty" */
707 if (access (pty_name, 6) != 0)
709 close (pty_master);
710 pty_name[5] = 'p';
711 continue;
713 return pty_master;
716 return -1; /* Ran out of pty devices */
719 /* --------------------------------------------------------------------------------------------- */
720 /** BSD version of pty_open_slave */
722 static int
723 pty_open_slave (const char *pty_name)
725 int pty_slave;
726 struct group *group_info = getgrnam ("tty");
728 if (group_info != NULL)
730 /* The following two calls will only succeed if we are root */
731 /* [Commented out while permissions problem is investigated] */
732 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
733 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
735 pty_slave = open (pty_name, O_RDWR);
736 if (pty_slave == -1)
737 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
738 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
739 return pty_slave;
741 #endif /* !HAVE_GRANTPT */
743 /* --------------------------------------------------------------------------------------------- */
744 /*** public functions ****************************************************************************/
745 /* --------------------------------------------------------------------------------------------- */
747 /* --------------------------------------------------------------------------------------------- */
749 * Fork the subshell, and set up many, many things.
751 * Possibly modifies the global variables:
752 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
753 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
754 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
757 void
758 init_subshell (void)
760 /* This must be remembered across calls to init_subshell() */
761 static char pty_name[BUF_SMALL];
762 char precmd[BUF_MEDIUM];
764 switch (check_sid ())
766 case 1:
767 mc_global.tty.use_subshell = FALSE;
768 return;
769 case 2:
770 mc_global.tty.use_subshell = FALSE;
771 mc_global.midnight_shutdown = TRUE;
772 return;
775 /* Take the current (hopefully pristine) tty mode and make */
776 /* a raw mode based on it now, before we do anything else with it */
777 init_raw_mode ();
779 if (mc_global.tty.subshell_pty == 0)
780 { /* First time through */
781 /* Find out what type of shell we have */
783 if (strstr (mc_global.tty.shell, "/zsh") || getenv ("ZSH_VERSION"))
784 subshell_type = ZSH;
785 else if (strstr (mc_global.tty.shell, "/tcsh"))
786 subshell_type = TCSH;
787 else if (strstr (mc_global.tty.shell, "/csh"))
788 subshell_type = TCSH;
789 else if (strstr (mc_global.tty.shell, "/bash") || getenv ("BASH"))
790 subshell_type = BASH;
791 else if (strstr (mc_global.tty.shell, "/fish"))
792 subshell_type = FISH;
793 else
795 mc_global.tty.use_subshell = FALSE;
796 return;
799 /* Open a pty for talking to the subshell */
801 /* FIXME: We may need to open a fresh pty each time on SVR4 */
803 mc_global.tty.subshell_pty = pty_open_master (pty_name);
804 if (mc_global.tty.subshell_pty == -1)
806 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
807 mc_global.tty.use_subshell = FALSE;
808 return;
810 subshell_pty_slave = pty_open_slave (pty_name);
811 if (subshell_pty_slave == -1)
813 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
814 pty_name, unix_error_string (errno));
815 mc_global.tty.use_subshell = FALSE;
816 return;
819 /* Create a pipe for receiving the subshell's CWD */
821 if (subshell_type == TCSH)
823 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
824 mc_tmpdir (), (int) getpid ());
825 if (mkfifo (tcsh_fifo, 0600) == -1)
827 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
828 mc_global.tty.use_subshell = FALSE;
829 return;
832 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
834 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
835 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
837 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
838 perror (__FILE__ ": open");
839 mc_global.tty.use_subshell = FALSE;
840 return;
843 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
845 perror (__FILE__ ": couldn't create pipe");
846 mc_global.tty.use_subshell = FALSE;
847 return;
851 /* Fork the subshell */
853 subshell_alive = TRUE;
854 subshell_stopped = FALSE;
855 subshell_pid = fork ();
857 if (subshell_pid == -1)
859 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
860 /* We exit here because, if the process table is full, the */
861 /* other method of running user commands won't work either */
862 exit (EXIT_FAILURE);
865 if (subshell_pid == 0)
867 /* We are in the child process */
868 init_subshell_child (pty_name);
871 /* Set up 'precmd' or equivalent for reading the subshell's CWD */
873 switch (subshell_type)
875 case BASH:
876 g_snprintf (precmd, sizeof (precmd),
877 " PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND; }'pwd>&%d;kill -STOP $$'\n",
878 subshell_pipe[WRITE]);
879 break;
881 case ZSH:
882 g_snprintf (precmd, sizeof (precmd),
883 " _mc_precmd(){ pwd>&%d;kill -STOP $$ }; precmd_functions+=(_mc_precmd)\n",
884 subshell_pipe[WRITE]);
885 break;
887 case TCSH:
888 g_snprintf (precmd, sizeof (precmd),
889 "set echo_style=both;"
890 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
891 break;
892 case FISH:
893 /* Use fish_prompt_mc function for prompt, if not present then copy fish_prompt to it. */
894 g_snprintf (precmd, sizeof (precmd),
895 "if not functions -q fish_prompt_mc;"
896 "functions -c fish_prompt fish_prompt_mc; end;"
897 "function fish_prompt; echo $PWD>&%d; fish_prompt_mc; kill -STOP %%self; end\n",
898 subshell_pipe[WRITE]);
899 break;
902 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
904 /* Wait until the subshell has started up and processed the command */
906 subshell_state = RUNNING_COMMAND;
907 tty_enable_interrupt_key ();
908 if (!feed_subshell (QUIETLY, TRUE))
910 mc_global.tty.use_subshell = FALSE;
912 tty_disable_interrupt_key ();
913 if (!subshell_alive)
914 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
917 /* --------------------------------------------------------------------------------------------- */
920 invoke_subshell (const char *command, int how, vfs_path_t ** new_dir_vpath)
922 /* 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);
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);
953 if (new_dir_vpath != NULL && subshell_alive)
955 const char *pcwd;
957 pcwd = vfs_translate_path (vfs_path_as_str (current_panel->cwd_vpath));
958 if (strcmp (subshell_cwd, pcwd) != 0)
959 *new_dir_vpath = vfs_path_from_str (subshell_cwd); /* Make MC change to the subshell's CWD */
962 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
963 while (!subshell_alive && quit == 0 && mc_global.tty.use_subshell)
964 init_subshell ();
966 return quit;
970 /* --------------------------------------------------------------------------------------------- */
972 gboolean
973 read_subshell_prompt (void)
975 int rc = 0;
976 ssize_t bytes = 0;
977 struct timeval timeleft = { 0, 0 };
978 GString *p;
979 gboolean prompt_was_reset = FALSE;
981 fd_set tmp;
982 FD_ZERO (&tmp);
983 FD_SET (mc_global.tty.subshell_pty, &tmp);
985 /* First time through */
986 if (subshell_prompt == NULL)
987 subshell_prompt = g_string_sized_new (INITIAL_PROMPT_SIZE);
989 p = g_string_sized_new (INITIAL_PROMPT_SIZE);
991 while (subshell_alive
992 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)) != 0)
994 ssize_t i;
996 /* Check for 'select' errors */
997 if (rc == -1)
999 if (errno == EINTR)
1001 if (mc_global.tty.winch_flag != 0)
1002 tty_change_screen_size ();
1004 continue;
1007 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1008 exit (EXIT_FAILURE);
1011 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1013 /* 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 g_string_set_size (p, 0);
1018 prompt_was_reset = TRUE;
1020 else if (pty_buffer[i] != '\0')
1021 g_string_append_c (p, pty_buffer[i]);
1024 if (p->len != 0 || prompt_was_reset)
1025 g_string_assign (subshell_prompt, p->str);
1027 g_string_free (p, TRUE);
1029 return (rc != 0 || bytes != 0);
1032 /* --------------------------------------------------------------------------------------------- */
1034 void
1035 do_update_prompt (void)
1037 if (update_subshell_prompt)
1039 printf ("\r\n%s", subshell_prompt->str);
1040 fflush (stdout);
1041 update_subshell_prompt = FALSE;
1045 /* --------------------------------------------------------------------------------------------- */
1047 gboolean
1048 exit_subshell (void)
1050 gboolean subshell_quit = TRUE;
1052 if (subshell_state != INACTIVE && subshell_alive)
1053 subshell_quit =
1054 query_dialog (_("Warning"),
1055 _("The shell is still active. Quit anyway?"),
1056 D_NORMAL, 2, _("&Yes"), _("&No")) == 0;
1058 if (subshell_quit)
1060 if (subshell_type == TCSH)
1062 if (unlink (tcsh_fifo) == -1)
1063 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1064 tcsh_fifo, unix_error_string (errno));
1067 g_string_free (subshell_prompt, TRUE);
1068 subshell_prompt = NULL;
1069 pty_buffer[0] = '\0';
1072 return subshell_quit;
1075 /* --------------------------------------------------------------------------------------------- */
1077 * Carefully quote directory name to allow entering any directory safely,
1078 * no matter what weird characters it may contain in its name.
1079 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1080 * executing any commands in the shell. Escape all control characters.
1081 * Use following technique:
1083 * printf(1) with format string containing a single conversion specifier,
1084 * "b", and an argument which contains a copy of the string passed to
1085 * subshell_name_quote() with all characters, except digits and letters,
1086 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1087 * numeric value of the character converted to octal number.
1089 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1093 static GString *
1094 subshell_name_quote (const char *s)
1096 GString *ret;
1097 const char *su, *n;
1098 const char *quote_cmd_start, *quote_cmd_end;
1100 if (subshell_type == FISH)
1102 quote_cmd_start = "(printf \"%b\" '";
1103 quote_cmd_end = "')";
1105 else
1107 quote_cmd_start = "\"`printf \"%b\" '";
1108 quote_cmd_end = "'`\"";
1111 ret = g_string_sized_new (64);
1113 /* Prevent interpreting leading '-' as a switch for 'cd' */
1114 if (s[0] == '-')
1115 g_string_append (ret, "./");
1117 /* Copy the beginning of the command to the buffer */
1118 g_string_append (ret, quote_cmd_start);
1121 * Print every character except digits and letters as a backslash-escape
1122 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1123 * character converted to octal number.
1125 for (su = s; su[0] != '\0'; su = n)
1127 n = str_cget_next_char_safe (su);
1129 if (str_isalnum (su))
1130 g_string_append_len (ret, su, n - su);
1131 else
1133 int c;
1135 for (c = 0; c < n - su; c++)
1136 g_string_append_printf (ret, "\\0%03o", (unsigned char) su[c]);
1140 g_string_append (ret, quote_cmd_end);
1142 return ret;
1146 /* --------------------------------------------------------------------------------------------- */
1148 /** If it actually changed the directory it returns true */
1149 void
1150 do_subshell_chdir (const vfs_path_t * vpath, gboolean update_prompt)
1152 char *pcwd;
1154 pcwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_RECODE);
1156 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1158 /* We have to repaint the subshell prompt if we read it from
1159 * the main program. Please note that in the code after this
1160 * if, the cd command that is sent will make the subshell
1161 * repaint the prompt, so we don't have to paint it. */
1162 if (update_prompt)
1163 do_update_prompt ();
1164 g_free (pcwd);
1165 return;
1168 /* The initial space keeps this out of the command history (in bash
1169 because we set "HISTCONTROL=ignorespace") */
1170 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1172 if (vpath != NULL)
1174 const char *translate;
1176 translate = vfs_translate_path (vfs_path_as_str (vpath));
1177 if (translate != NULL)
1179 GString *temp;
1181 temp = subshell_name_quote (translate);
1182 write_all (mc_global.tty.subshell_pty, temp->str, temp->len);
1183 g_string_free (temp, TRUE);
1185 else
1187 write_all (mc_global.tty.subshell_pty, ".", 1);
1190 else
1192 write_all (mc_global.tty.subshell_pty, "/", 1);
1194 write_all (mc_global.tty.subshell_pty, "\n", 1);
1196 subshell_state = RUNNING_COMMAND;
1197 feed_subshell (QUIETLY, FALSE);
1199 if (subshell_alive)
1201 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1203 if (bPathNotEq && subshell_type == TCSH)
1205 char rp_subshell_cwd[PATH_MAX];
1206 char rp_current_panel_cwd[PATH_MAX];
1208 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1209 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1211 if (p_subshell_cwd == NULL)
1212 p_subshell_cwd = subshell_cwd;
1213 if (p_current_panel_cwd == NULL)
1214 p_current_panel_cwd = pcwd;
1215 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1218 if (bPathNotEq && !DIR_IS_DOT (pcwd))
1220 char *cwd;
1222 cwd = vfs_path_to_str_flags (current_panel->cwd_vpath, 0, VPF_STRIP_PASSWORD);
1223 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd);
1224 g_free (cwd);
1228 /* Really escape Zsh history */
1229 if (subshell_type == ZSH)
1231 /* Per Zsh documentation last command prefixed with space lingers in the internal history
1232 * until the next command is entered before it vanishes. To make it vanish right away,
1233 * type a space and press return. */
1234 write_all (mc_global.tty.subshell_pty, " \n", 2);
1235 subshell_state = RUNNING_COMMAND;
1236 feed_subshell (QUIETLY, FALSE);
1239 update_subshell_prompt = FALSE;
1241 g_free (pcwd);
1242 /* Make sure that MC never stores the CWD in a silly format */
1243 /* like /usr////lib/../bin, or the strcmp() above will fail */
1246 /* --------------------------------------------------------------------------------------------- */
1248 void
1249 subshell_get_console_attributes (void)
1251 /* Get our current terminal modes */
1253 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1255 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1256 mc_global.tty.use_subshell = FALSE;
1260 /* --------------------------------------------------------------------------------------------- */
1262 * Figure out whether the subshell has stopped, exited or been killed
1263 * Possibly modifies: 'subshell_alive', 'subshell_stopped' and 'quit' */
1265 void
1266 sigchld_handler (int sig)
1268 int status;
1269 pid_t pid;
1271 (void) sig;
1273 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1275 if (pid == subshell_pid)
1277 /* Figure out what has happened to the subshell */
1279 if (WIFSTOPPED (status))
1281 if (WSTOPSIG (status) == SIGSTOP)
1283 /* The subshell has received a SIGSTOP signal */
1284 subshell_stopped = TRUE;
1286 else
1288 /* The user has suspended the subshell. Revive it */
1289 kill (subshell_pid, SIGCONT);
1292 else
1294 /* The subshell has either exited normally or been killed */
1295 subshell_alive = FALSE;
1296 delete_select_channel (mc_global.tty.subshell_pty);
1297 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1298 quit |= SUBSHELL_EXIT; /* Exited normally */
1301 #ifdef __linux__
1302 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1304 if (pid == cons_saver_pid)
1307 if (WIFSTOPPED (status))
1308 /* Someone has stopped cons.saver - restart it */
1309 kill (pid, SIGCONT);
1310 else
1312 /* cons.saver has died - disable confole saving */
1313 handle_console (CONSOLE_DONE);
1314 mc_global.tty.console_flag = '\0';
1318 #endif /* __linux__ */
1320 /* If we got here, some other child exited; ignore it */
1323 /* --------------------------------------------------------------------------------------------- */