(init_subshell_child): use exist_file().
[midnight-commander.git] / src / subshell / common.c
blobc5eb4f6a62446cde9d461f0cb78c59167b7c07d1
1 /*
2 Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994-2015
5 Free Software Foundation, Inc.
7 Written by:
8 Alexander Kriegisch <Alexander@Kriegisch.name>
9 Aliaksey Kandratsenka <alk@tut.by>
10 Andreas Mohr <and@gmx.li>
11 Andrew Borodin <aborodin@vmail.ru>
12 Andrew Borodin <borodin@borodin.zarya>
13 Andrew V. Samoilov <sav@bcs.zp.ua>
14 Chris Owen <chris@candu.co.uk>
15 Claes Nästén <me@pekdon.net>
16 Egmont Koblinger <egmont@gmail.com>
17 Enrico Weigelt, metux IT service <weigelt@metux.de>
18 Igor Urazov <z0rc3r@gmail.com>
19 Ilia Maslakov <il.smind@gmail.com>
20 Leonard den Ottolander <leonard@den.ottolander.nl>
21 Miguel de Icaza <miguel@novell.com>
22 Mikhail S. Pobolovets <styx.mp@gmail.com>
23 Norbert Warmuth <nwarmuth@privat.circular.de>
24 Patrick Winnertz <winnie@debian.org>
25 Pavel Machek <pavel@suse.cz>
26 Pavel Roskin <proski@gnu.org>
27 Pavel Tsekov <ptsekov@gmx.net>
28 Roland Illig <roland.illig@gmx.de>
29 Sergei Trofimovich <slyfox@inbox.ru>
30 Slava Zanko <slavazanko@gmail.com>, 2013,2015.
31 Timur Bakeyev <mc@bat.ru>
32 Vit Rosin <vit_r@list.ru>
34 This file is part of the Midnight Commander.
36 The Midnight Commander is free software: you can redistribute it
37 and/or modify it under the terms of the GNU General Public License as
38 published by the Free Software Foundation, either version 3 of the License,
39 or (at your option) any later version.
41 The Midnight Commander is distributed in the hope that it will be useful,
42 but WITHOUT ANY WARRANTY; without even the implied warranty of
43 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 GNU General Public License for more details.
46 You should have received a copy of the GNU General Public License
47 along with this program. If not, see <http://www.gnu.org/licenses/>.
50 /** \file subshell.c
51 * \brief Source: concurrent shell support
54 #include <config.h>
56 #ifndef _GNU_SOURCE
57 #define _GNU_SOURCE 1
58 #endif
60 #include <ctype.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <errno.h>
64 #include <string.h>
65 #include <signal.h>
66 #include <sys/types.h>
67 #include <sys/wait.h>
68 #ifdef HAVE_SYS_IOCTL_H
69 #include <sys/ioctl.h>
70 #endif
71 #include <termios.h>
73 #ifdef HAVE_STROPTS_H
74 #include <stropts.h> /* For I_PUSH */
75 #endif /* HAVE_STROPTS_H */
77 #include "lib/global.h"
79 #include "lib/unixcompat.h"
80 #include "lib/tty/tty.h" /* LINES */
81 #include "lib/tty/key.h" /* XCTRL */
82 #include "lib/vfs/vfs.h"
83 #include "lib/strutil.h"
84 #include "lib/mcconfig.h"
85 #include "lib/util.h"
86 #include "lib/widget.h"
88 #include "subshell.h"
89 #include "internal.h"
91 /*** global variables ****************************************************************************/
93 /* State of the subshell:
94 * INACTIVE: the default state; awaiting a command
95 * ACTIVE: remain in the shell until the user hits 'subshell_switch_key'
96 * RUNNING_COMMAND: return to MC when the current command finishes */
97 enum subshell_state_enum subshell_state;
99 /* Holds the latest prompt captured from the subshell */
100 GString *subshell_prompt = NULL;
102 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
103 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
104 gboolean update_subshell_prompt = FALSE;
106 /*** file scope macro definitions ****************************************************************/
108 #ifndef WEXITSTATUS
109 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
110 #endif
112 #ifndef WIFEXITED
113 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
114 #endif
116 /* Initial length of the buffer for the subshell's prompt */
117 #define INITIAL_PROMPT_SIZE 10
119 /* Used by the child process to indicate failure to start the subshell */
120 #define FORK_FAILURE 69 /* Arbitrary */
122 /* Length of the buffer for all I/O with the subshell */
123 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
125 /*** file scope type declarations ****************************************************************/
127 /* For pipes */
128 enum
130 READ = 0,
131 WRITE = 1
134 /* Subshell type (gleaned from the SHELL environment variable, if available) */
135 static enum
137 BASH,
138 ASH_BUSYBOX, /* BusyBox default shell (ash) */
139 DASH, /* Debian variant of ash */
140 TCSH,
141 ZSH,
142 FISH
143 } subshell_type;
145 /*** file scope variables ************************************************************************/
147 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
148 static char tcsh_fifo[128];
150 static int subshell_pty_slave = -1;
152 /* The key for switching back to MC from the subshell */
153 /* *INDENT-OFF* */
154 static const char subshell_switch_key = XCTRL ('o') & 255;
155 /* *INDENT-ON* */
157 /* For reading/writing on the subshell's pty */
158 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
160 /* To pass CWD info from the subshell to MC */
161 static int subshell_pipe[2];
163 /* The subshell's process ID */
164 static pid_t subshell_pid = 1;
166 /* One extra char for final '\n' */
167 static char subshell_cwd[MC_MAXPATHLEN + 1];
169 /* Flag to indicate whether the subshell is ready for next command */
170 static int subshell_ready;
172 /* The following two flags can be changed by the SIGCHLD handler. This is */
173 /* OK, because the 'int' type is updated atomically on all known machines */
174 static volatile int subshell_alive, subshell_stopped;
176 /* We store the terminal's initial mode here so that we can configure
177 the pty similarly, and also so we can restore the real terminal to
178 sanity if we have to exit abruptly */
179 static struct termios shell_mode;
181 /* This is a transparent mode for the terminal where MC is running on */
182 /* It is used when the shell is active, so that the control signals */
183 /* are delivered to the shell pty */
184 static struct termios raw_mode;
186 /* --------------------------------------------------------------------------------------------- */
187 /*** file scope functions ************************************************************************/
188 /* --------------------------------------------------------------------------------------------- */
190 * Write all data, even if the write() call is interrupted.
193 static ssize_t
194 write_all (int fd, const void *buf, size_t count)
196 ssize_t written = 0;
198 while (count > 0)
200 ssize_t ret;
202 ret = write (fd, (const unsigned char *) buf + written, count);
203 if (ret < 0)
205 if (errno == EINTR)
207 if (mc_global.tty.winch_flag != 0)
208 tty_change_screen_size ();
210 continue;
213 return written > 0 ? written : ret;
215 count -= ret;
216 written += ret;
218 return written;
221 /* --------------------------------------------------------------------------------------------- */
223 * Prepare child process to running the shell and run it.
225 * Modifies the global variables (in the child process only):
226 * shell_mode
228 * Returns: never.
231 static void
232 init_subshell_child (const char *pty_name)
234 char *init_file = NULL;
235 char *putenv_str = NULL;
236 pid_t mc_sid;
238 (void) pty_name;
239 setsid (); /* Get a fresh terminal session */
241 /* Make sure that it has become our controlling terminal */
243 /* Redundant on Linux and probably most systems, but just in case: */
245 #ifdef TIOCSCTTY
246 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
247 #endif
249 /* Configure its terminal modes and window size */
251 /* Set up the pty with the same termios flags as our own tty */
252 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
254 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
255 my_exit (FORK_FAILURE);
258 /* Set the pty's size (80x25 by default on Linux) according to the */
259 /* size of the real terminal as calculated by ncurses, if possible */
260 tty_resize (subshell_pty_slave);
262 /* Set up the subshell's environment and init file name */
264 /* It simplifies things to change to our home directory here, */
265 /* and the user's startup file may do a 'cd' command anyway */
267 int ret;
269 ret = chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
270 (void) ret;
273 /* Set MC_SID to prevent running one mc from another */
274 mc_sid = getsid (0);
275 if (mc_sid != -1)
277 char sid_str[BUF_SMALL];
279 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
280 putenv (g_strdup (sid_str));
283 switch (subshell_type)
285 case BASH:
286 /* Do we have a custom init file ~/.local/share/mc/bashrc? */
287 init_file = mc_config_get_full_path ("bashrc");
289 /* Otherwise use ~/.bashrc */
290 if (!exist_file (init_file))
292 g_free (init_file);
293 init_file = g_strdup (".bashrc");
296 /* Make MC's special commands not show up in bash's history and also suppress
297 * consecutive identical commands*/
298 putenv ((char *) "HISTCONTROL=ignoreboth");
300 /* Allow alternative readline settings for MC */
302 char *input_file;
304 input_file = mc_config_get_full_path ("inputrc");
305 if (exist_file (input_file))
307 putenv_str = g_strconcat ("INPUTRC=", input_file, NULL);
308 putenv (putenv_str);
310 g_free (input_file);
313 break;
315 case ASH_BUSYBOX:
316 case DASH:
317 /* Do we have a custom init file ~/.local/share/mc/ashrc? */
318 init_file = mc_config_get_full_path ("ashrc");
320 /* Otherwise use ~/.profile */
321 if (!exist_file (init_file))
323 g_free (init_file);
324 init_file = g_strdup (".profile");
327 /* Put init file to ENV variable used by ash */
328 putenv_str = g_strconcat ("ENV=", init_file, NULL);
329 putenv (putenv_str);
330 /* Do not use "g_free (putenv_str)" here, otherwise ENV will be undefined! */
332 break;
334 /* TODO: Find a way to pass initfile to TCSH, ZSH and FISH */
335 case TCSH:
336 case ZSH:
337 case FISH:
338 break;
340 default:
341 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
342 my_exit (FORK_FAILURE);
345 /* Attach all our standard file descriptors to the pty */
347 /* This is done just before the fork, because stderr must still */
348 /* be connected to the real tty during the above error messages; */
349 /* otherwise the user will never see them. */
351 dup2 (subshell_pty_slave, STDIN_FILENO);
352 dup2 (subshell_pty_slave, STDOUT_FILENO);
353 dup2 (subshell_pty_slave, STDERR_FILENO);
355 close (subshell_pipe[READ]);
356 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
357 /* Close master side of pty. This is important; apart from */
358 /* freeing up the descriptor for use in the subshell, it also */
359 /* means that when MC exits, the subshell will get a SIGHUP and */
360 /* exit too, because there will be no more descriptors pointing */
361 /* at the master side of the pty and so it will disappear. */
362 close (mc_global.tty.subshell_pty);
364 /* Execute the subshell at last */
366 switch (subshell_type)
368 case BASH:
369 execl (mc_global.tty.shell, "bash", "-rcfile", init_file, (char *) NULL);
370 break;
372 case ZSH:
373 /* Use -g to exclude cmds beginning with space from history
374 * and -Z to use the line editor on non-interactive term */
375 execl (mc_global.tty.shell, "zsh", "-Z", "-g", (char *) NULL);
377 break;
379 case ASH_BUSYBOX:
380 case DASH:
381 case TCSH:
382 case FISH:
383 execl (mc_global.tty.shell, mc_global.tty.shell, (char *) NULL);
384 break;
386 default:
387 break;
390 /* If we get this far, everything failed miserably */
391 g_free (init_file);
392 g_free (putenv_str);
393 my_exit (FORK_FAILURE);
397 /* --------------------------------------------------------------------------------------------- */
399 * Check MC_SID to prevent running one mc from another.
400 * Return:
401 * 0 if no parent mc in our session was found,
402 * 1 if parent mc was found and the user wants to continue,
403 * 2 if parent mc was found and the user wants to quit mc.
406 static int
407 check_sid (void)
409 pid_t my_sid, old_sid;
410 const char *sid_str;
411 int r;
413 sid_str = getenv ("MC_SID");
414 if (sid_str == NULL)
415 return 0;
417 old_sid = (pid_t) strtol (sid_str, NULL, 0);
418 if (old_sid == 0)
419 return 0;
421 my_sid = getsid (0);
422 if (my_sid == -1)
423 return 0;
425 /* The parent mc is in a different session, it's OK */
426 if (old_sid != my_sid)
427 return 0;
429 r = query_dialog (_("Warning"),
430 _("GNU Midnight Commander is already\n"
431 "running on this terminal.\n"
432 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
434 return (r != 0) ? 2 : 1;
437 /* --------------------------------------------------------------------------------------------- */
439 static void
440 init_raw_mode (void)
442 static gboolean initialized = FALSE;
444 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
445 /* original settings. However, here we need to make this tty very raw, */
446 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
447 /* pty. So, instead of changing the code for execute(), pre_exec(), */
448 /* etc, we just set up the modes we need here, before each command. */
450 if (!initialized) /* First time: initialise 'raw_mode' */
452 tcgetattr (STDOUT_FILENO, &raw_mode);
453 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
454 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
455 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
456 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
457 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
458 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
459 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
460 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
461 initialized = TRUE;
465 /* --------------------------------------------------------------------------------------------- */
467 * Wait until the subshell dies or stops. If it stops, make it resume.
468 * Possibly modifies the globals 'subshell_alive' and 'subshell_stopped'
471 static void
472 synchronize (void)
474 sigset_t sigchld_mask, old_mask;
476 sigemptyset (&sigchld_mask);
477 sigaddset (&sigchld_mask, SIGCHLD);
478 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
481 * SIGCHLD should not be blocked, but we unblock it just in case.
482 * This is known to be useful for cygwin 1.3.12 and older.
484 sigdelset (&old_mask, SIGCHLD);
486 /* Wait until the subshell has stopped */
487 while (subshell_alive && !subshell_stopped)
488 sigsuspend (&old_mask);
490 if (subshell_state != ACTIVE)
492 /* Discard all remaining data from stdin to the subshell */
493 tcflush (subshell_pty_slave, TCIFLUSH);
496 subshell_stopped = FALSE;
497 kill (subshell_pid, SIGCONT);
499 sigprocmask (SIG_SETMASK, &old_mask, NULL);
500 /* We can't do any better without modifying the shell(s) */
503 /* --------------------------------------------------------------------------------------------- */
504 /** Feed the subshell our keyboard input until it says it's finished */
506 static gboolean
507 feed_subshell (int how, int fail_on_error)
509 fd_set read_set; /* For 'select' */
510 int bytes; /* For the return value from 'read' */
511 int i; /* Loop counter */
513 struct timeval wtime; /* Maximum time we wait for the subshell */
514 struct timeval *wptr;
516 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
517 wtime.tv_sec = 10;
518 wtime.tv_usec = 0;
519 wptr = fail_on_error ? &wtime : NULL;
521 while (TRUE)
523 int maxfdp;
525 if (!subshell_alive)
526 return FALSE;
528 /* Prepare the file-descriptor set and call 'select' */
530 FD_ZERO (&read_set);
531 FD_SET (mc_global.tty.subshell_pty, &read_set);
532 FD_SET (subshell_pipe[READ], &read_set);
533 maxfdp = max (mc_global.tty.subshell_pty, subshell_pipe[READ]);
534 if (how == VISIBLY)
536 FD_SET (STDIN_FILENO, &read_set);
537 maxfdp = max (maxfdp, STDIN_FILENO);
540 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
542 /* Despite using SA_RESTART, we still have to check for this */
543 if (errno == EINTR)
545 if (mc_global.tty.winch_flag != 0)
546 tty_change_screen_size ();
548 continue; /* try all over again */
550 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
551 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
552 unix_error_string (errno));
553 exit (EXIT_FAILURE);
556 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
557 /* Read from the subshell, write to stdout */
559 /* This loop improves performance by reducing context switches
560 by a factor of 20 or so... unfortunately, it also hangs MC
561 randomly, because of an apparent Linux bug. Investigate. */
562 /* for (i=0; i<5; ++i) * FIXME -- experimental */
564 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
566 /* The subshell has died */
567 if (bytes == -1 && errno == EIO && !subshell_alive)
568 return FALSE;
570 if (bytes <= 0)
572 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
573 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
574 exit (EXIT_FAILURE);
577 if (how == VISIBLY)
578 write_all (STDOUT_FILENO, pty_buffer, bytes);
581 else if (FD_ISSET (subshell_pipe[READ], &read_set))
582 /* Read the subshell's CWD and capture its prompt */
584 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
585 if (bytes <= 0)
587 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
588 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
589 unix_error_string (errno));
590 exit (EXIT_FAILURE);
593 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
595 synchronize ();
597 subshell_ready = TRUE;
598 if (subshell_state == RUNNING_COMMAND)
600 subshell_state = INACTIVE;
601 return TRUE;
605 else if (FD_ISSET (STDIN_FILENO, &read_set))
606 /* Read from stdin, write to the subshell */
608 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
609 if (bytes <= 0)
611 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
612 fprintf (stderr,
613 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
614 exit (EXIT_FAILURE);
617 for (i = 0; i < bytes; ++i)
618 if (pty_buffer[i] == subshell_switch_key)
620 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
621 if (subshell_ready)
622 subshell_state = INACTIVE;
623 return TRUE;
626 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
628 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
629 subshell_ready = FALSE;
631 else
632 return FALSE;
636 /* --------------------------------------------------------------------------------------------- */
637 /* pty opening functions */
639 #ifdef HAVE_GRANTPT
641 /* System V version of pty_open_master */
643 static int
644 pty_open_master (char *pty_name)
646 char *slave_name;
647 int pty_master;
649 #ifdef HAVE_POSIX_OPENPT
650 pty_master = posix_openpt (O_RDWR);
651 #elif defined HAVE_GETPT
652 /* getpt () is a GNU extension (glibc 2.1.x) */
653 pty_master = getpt ();
654 #elif defined IS_AIX
655 strcpy (pty_name, "/dev/ptc");
656 pty_master = open (pty_name, O_RDWR);
657 #else
658 strcpy (pty_name, "/dev/ptmx");
659 pty_master = open (pty_name, O_RDWR);
660 #endif
662 if (pty_master == -1)
663 return -1;
665 if (grantpt (pty_master) == -1 /* Grant access to slave */
666 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
667 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
669 close (pty_master);
670 return -1;
672 strcpy (pty_name, slave_name);
673 return pty_master;
676 /* --------------------------------------------------------------------------------------------- */
677 /** System V version of pty_open_slave */
679 static int
680 pty_open_slave (const char *pty_name)
682 int pty_slave;
684 pty_slave = open (pty_name, O_RDWR);
685 if (pty_slave == -1)
687 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
688 return -1;
690 #if !defined(__osf__) && !defined(__linux__)
691 #if defined (I_FIND) && defined (I_PUSH)
692 if (ioctl (pty_slave, I_FIND, "ptem") == 0)
693 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
695 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
696 pty_slave, unix_error_string (errno));
697 close (pty_slave);
698 return -1;
701 if (ioctl (pty_slave, I_FIND, "ldterm") == 0)
702 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
704 fprintf (stderr,
705 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
706 pty_slave, unix_error_string (errno));
707 close (pty_slave);
708 return -1;
710 #if !defined(sgi) && !defined(__sgi)
711 if (ioctl (pty_slave, I_FIND, "ttcompat") == 0)
712 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
714 fprintf (stderr,
715 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
716 pty_slave, unix_error_string (errno));
717 close (pty_slave);
718 return -1;
720 #endif /* sgi || __sgi */
721 #endif /* I_FIND && I_PUSH */
722 #endif /* __osf__ || __linux__ */
724 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
725 return pty_slave;
728 #else /* !HAVE_GRANTPT */
730 /* --------------------------------------------------------------------------------------------- */
731 /** BSD version of pty_open_master */
732 static int
733 pty_open_master (char *pty_name)
735 int pty_master;
736 const char *ptr1, *ptr2;
738 strcpy (pty_name, "/dev/ptyXX");
739 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
741 pty_name[8] = *ptr1;
742 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
744 pty_name[9] = *ptr2;
746 /* Try to open master */
747 pty_master = open (pty_name, O_RDWR);
748 if (pty_master == -1)
750 if (errno == ENOENT) /* Different from EIO */
751 return -1; /* Out of pty devices */
752 continue; /* Try next pty device */
754 pty_name[5] = 't'; /* Change "pty" to "tty" */
755 if (access (pty_name, 6) != 0)
757 close (pty_master);
758 pty_name[5] = 'p';
759 continue;
761 return pty_master;
764 return -1; /* Ran out of pty devices */
767 /* --------------------------------------------------------------------------------------------- */
768 /** BSD version of pty_open_slave */
770 static int
771 pty_open_slave (const char *pty_name)
773 int pty_slave;
774 struct group *group_info;
776 group_info = getgrnam ("tty");
777 if (group_info != NULL)
779 /* The following two calls will only succeed if we are root */
780 /* [Commented out while permissions problem is investigated] */
781 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
782 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
784 pty_slave = open (pty_name, O_RDWR);
785 if (pty_slave == -1)
786 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
787 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
788 return pty_slave;
790 #endif /* !HAVE_GRANTPT */
793 /* --------------------------------------------------------------------------------------------- */
795 * Get a subshell type and store in subshell_type variable
797 * @return TRUE if subtype was gotten, FALSE otherwise
800 static gboolean
801 init_subshell_type (void)
803 gboolean result = TRUE;
805 /* Find out what type of shell we have. Also consider real paths (resolved symlinks)
806 * because e.g. csh might point to tcsh, ash to dash or busybox, sh to anything. */
808 if (strstr (mc_global.tty.shell, "/zsh") != NULL
809 || strstr (mc_global.tty.shell_realpath, "/zsh") != NULL || getenv ("ZSH_VERSION") != NULL)
810 /* Also detects ksh symlinked to zsh */
811 subshell_type = ZSH;
812 else if (strstr (mc_global.tty.shell, "/tcsh") != NULL
813 || strstr (mc_global.tty.shell_realpath, "/tcsh") != NULL)
814 /* Also detects csh symlinked to tcsh */
815 subshell_type = TCSH;
816 else if (strstr (mc_global.tty.shell, "/fish") != NULL
817 || strstr (mc_global.tty.shell_realpath, "/fish") != NULL)
818 subshell_type = FISH;
819 else if (strstr (mc_global.tty.shell, "/dash") != NULL
820 || strstr (mc_global.tty.shell_realpath, "/dash") != NULL)
821 /* Debian ash (also found if symlinked to by ash/sh) */
822 subshell_type = DASH;
823 else if (strstr (mc_global.tty.shell_realpath, "/busybox") != NULL)
825 /* If shell is symlinked to busybox, assume it is an ash, even though theoretically
826 * it could also be a hush (a mini shell for non-MMU systems deactivated by default).
827 * For simplicity's sake we assume that busybox always contains an ash, not a hush.
828 * On embedded platforms or on server systems, /bin/sh often points to busybox.
829 * Sometimes even bash is symlinked to busybox (CONFIG_FEATURE_BASH_IS_ASH option),
830 * so we need to check busybox symlinks *before* checking for the name "bash"
831 * in order to avoid that case. */
832 subshell_type = ASH_BUSYBOX;
834 else if (strstr (mc_global.tty.shell, "/bash") != NULL || getenv ("BASH") != NULL)
835 /* If bash is not symlinked to busybox, it is safe to assume it is a real bash */
836 subshell_type = BASH;
837 else
839 mc_global.tty.use_subshell = FALSE;
840 result = FALSE;
842 return result;
845 /* --------------------------------------------------------------------------------------------- */
847 * Set up `precmd' or equivalent for reading the subshell's CWD.
849 * Attention! Never forget that these are *one-liners* even though the concatenated
850 * substrings contain line breaks and indentation for better understanding of the
851 * shell code. It is vital that each one-liner ends with a line feed character ("\n" ).
853 * @return initialized pre-command string
856 static void
857 init_subshell_precmd (char *precmd, size_t buff_size)
859 switch (subshell_type)
861 case BASH:
862 g_snprintf (precmd, buff_size,
863 " PROMPT_COMMAND='pwd>&%d; kill -STOP $$';\n", subshell_pipe[WRITE]);
864 break;
866 case ASH_BUSYBOX:
867 /* BusyBox ash needs a somewhat complicated precmd emulation via PS1, and it is vital
868 * that BB be built with active CONFIG_ASH_EXPAND_PRMT, but this is the default anyway.
870 * A: This leads to a stopped subshell (=frozen mc) if user calls "ash" command
871 * "PS1='$(pwd>&%d; kill -STOP $$)\\u@\\h:\\w\\$ '\n",
873 * B: This leads to "sh: precmd: not found" in sub-subshell if user calls "ash" command
874 * "precmd() { pwd>&%d; kill -STOP $$; }; "
875 * "PS1='$(precmd)\\u@\\h:\\w\\$ '\n",
877 * C: This works if user calls "ash" command because in sub-subshell
878 * PRECMD is unfedined, thus evaluated to empty string - no damage done.
879 * Attention: BusyBox must be built with FEATURE_EDITING_FANCY_PROMPT to
880 * permit \u, \w, \h, \$ escape sequences. Unfortunately this cannot be guaranteed,
881 * especially on embedded systems where people try to save space, so let's use
882 * the dash version below. It should work on virtually all systems.
883 * "precmd() { pwd>&%d; kill -STOP $$; }; "
884 * "PRECMD=precmd; "
885 * "PS1='$(eval $PRECMD)\\u@\\h:\\w\\$ '\n",
887 case DASH:
888 /* Debian ash needs a precmd emulation via PS1, similar to BusyBox ash,
889 * but does not support escape sequences for user, host and cwd in prompt.
890 * Attention! Make sure that the buffer for precmd is big enough.
892 * We want to have a fancy dynamic prompt with user@host:cwd just like in the BusyBox
893 * examples above, but because replacing the home directory part of the path by "~" is
894 * complicated, it bloats the precmd to a size > BUF_SMALL (128).
896 * The following example is a little less fancy (home directory not replaced)
897 * and shows the basic workings of our prompt for easier understanding:
899 * "precmd() { "
900 * "echo \"$USER@$(hostname -s):$PWD\"; "
901 * "pwd>&%d; "
902 * "kill -STOP $$; "
903 * "}; "
904 * "PRECMD=precmd; "
905 * "PS1='$($PRECMD)$ '\n",
907 g_snprintf (precmd, buff_size,
908 "precmd() { "
909 "if [ ! \"${PWD##$HOME}\" ]; then "
910 "MC_PWD=\"~\"; "
911 "else "
912 "[ \"${PWD##$HOME/}\" = \"$PWD\" ] && MC_PWD=\"$PWD\" || MC_PWD=\"~/${PWD##$HOME/}\"; "
913 "fi; "
914 "echo \"$USER@$(hostname -s):$MC_PWD\"; "
915 "pwd>&%d; "
916 "kill -STOP $$; "
917 "}; " "PRECMD=precmd; " "PS1='$($PRECMD)$ '\n", subshell_pipe[WRITE]);
918 break;
920 case ZSH:
921 g_snprintf (precmd, buff_size,
922 " precmd() { pwd>&%d; kill -STOP $$; }; "
923 "PS1='%%n@%%m:%%~%%# '\n", subshell_pipe[WRITE]);
924 break;
926 case TCSH:
927 g_snprintf (precmd, buff_size,
928 "set echo_style=both; "
929 "set prompt='%%n@%%m:%%~%%# '; "
930 "alias precmd 'echo $cwd:q >>%s; kill -STOP $$'\n", tcsh_fifo);
931 break;
933 case FISH:
934 /* We also want a fancy user@host:cwd prompt here, but fish makes it very easy to also
935 * use colours, which is what we will do. But first here is a simpler, uncoloured version:
936 * "function fish_prompt; "
937 * "echo (whoami)@(hostname -s):(pwd)\\$\\ ; "
938 * "echo \"$PWD\">&%d; "
939 * "kill -STOP %%self; "
940 * "end\n",
942 * TODO: fish prompt is shown when panel is hidden (Ctrl-O), but not when it is visible.
943 * Find out how to fix this.
945 g_snprintf (precmd, buff_size,
946 "function fish_prompt; "
947 "echo (whoami)@(hostname -s):(set_color $fish_color_cwd)(pwd)(set_color normal)\\$\\ ; "
948 "echo \"$PWD\">&%d; " "kill -STOP %%self; " "end\n", subshell_pipe[WRITE]);
949 break;
951 default:
952 break;
956 /* --------------------------------------------------------------------------------------------- */
958 * Carefully quote directory name to allow entering any directory safely,
959 * no matter what weird characters it may contain in its name.
960 * NOTE: Treat directory name an untrusted data, don't allow it to cause
961 * executing any commands in the shell. Escape all control characters.
962 * Use following technique:
964 * printf(1) with format string containing a single conversion specifier,
965 * "b", and an argument which contains a copy of the string passed to
966 * subshell_name_quote() with all characters, except digits and letters,
967 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
968 * numeric value of the character converted to octal number.
970 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
974 static GString *
975 subshell_name_quote (const char *s)
977 GString *ret;
978 const char *su, *n;
979 const char *quote_cmd_start, *quote_cmd_end;
981 if (subshell_type == FISH)
983 quote_cmd_start = "(printf \"%b\" '";
984 quote_cmd_end = "')";
986 /* TODO: When BusyBox printf is fixed, get rid of this "else if", see
987 http://lists.busybox.net/pipermail/busybox/2012-March/077460.html */
988 /* else if (subshell_type == ASH_BUSYBOX)
990 quote_cmd_start = "\"`echo -en '";
991 quote_cmd_end = "'`\"";
992 } */
993 else
995 quote_cmd_start = "\"`printf \"%b\" '";
996 quote_cmd_end = "'`\"";
999 ret = g_string_sized_new (64);
1001 /* Prevent interpreting leading '-' as a switch for 'cd' */
1002 if (s[0] == '-')
1003 g_string_append (ret, "./");
1005 /* Copy the beginning of the command to the buffer */
1006 g_string_append (ret, quote_cmd_start);
1009 * Print every character except digits and letters as a backslash-escape
1010 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1011 * character converted to octal number.
1013 for (su = s; su[0] != '\0'; su = n)
1015 n = str_cget_next_char_safe (su);
1017 if (str_isalnum (su))
1018 g_string_append_len (ret, su, n - su);
1019 else
1021 int c;
1023 for (c = 0; c < n - su; c++)
1024 g_string_append_printf (ret, "\\0%03o", (unsigned char) su[c]);
1028 g_string_append (ret, quote_cmd_end);
1030 return ret;
1033 /* --------------------------------------------------------------------------------------------- */
1034 /*** public functions ****************************************************************************/
1035 /* --------------------------------------------------------------------------------------------- */
1037 /* --------------------------------------------------------------------------------------------- */
1039 * Fork the subshell, and set up many, many things.
1041 * Possibly modifies the global variables:
1042 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
1043 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
1044 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
1047 void
1048 init_subshell (void)
1050 /* This must be remembered across calls to init_subshell() */
1051 static char pty_name[BUF_SMALL];
1052 /* Must be considerably longer than BUF_SMALL (128) to support fancy shell prompts */
1053 char precmd[BUF_MEDIUM];
1055 switch (check_sid ())
1057 case 1:
1058 mc_global.tty.use_subshell = FALSE;
1059 return;
1060 case 2:
1061 mc_global.tty.use_subshell = FALSE;
1062 mc_global.midnight_shutdown = TRUE;
1063 return;
1064 default:
1065 break;
1068 /* Take the current (hopefully pristine) tty mode and make */
1069 /* a raw mode based on it now, before we do anything else with it */
1070 init_raw_mode ();
1072 if (mc_global.tty.subshell_pty == 0)
1073 { /* First time through */
1074 if (!init_subshell_type ())
1075 return;
1077 /* Open a pty for talking to the subshell */
1079 /* FIXME: We may need to open a fresh pty each time on SVR4 */
1081 mc_global.tty.subshell_pty = pty_open_master (pty_name);
1082 if (mc_global.tty.subshell_pty == -1)
1084 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
1085 mc_global.tty.use_subshell = FALSE;
1086 return;
1088 subshell_pty_slave = pty_open_slave (pty_name);
1089 if (subshell_pty_slave == -1)
1091 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
1092 pty_name, unix_error_string (errno));
1093 mc_global.tty.use_subshell = FALSE;
1094 return;
1097 /* Create a pipe for receiving the subshell's CWD */
1099 if (subshell_type == TCSH)
1101 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
1102 mc_tmpdir (), (int) getpid ());
1103 if (mkfifo (tcsh_fifo, 0600) == -1)
1105 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
1106 mc_global.tty.use_subshell = FALSE;
1107 return;
1110 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
1112 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
1113 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
1115 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
1116 perror (__FILE__ ": open");
1117 mc_global.tty.use_subshell = FALSE;
1118 return;
1121 else if (pipe (subshell_pipe)) /* subshell_type is BASH, ASH_BUSYBOX, DASH or ZSH */
1123 perror (__FILE__ ": couldn't create pipe");
1124 mc_global.tty.use_subshell = FALSE;
1125 return;
1129 /* Fork the subshell */
1131 subshell_alive = TRUE;
1132 subshell_stopped = FALSE;
1133 subshell_pid = fork ();
1135 if (subshell_pid == -1)
1137 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
1138 /* We exit here because, if the process table is full, the */
1139 /* other method of running user commands won't work either */
1140 exit (EXIT_FAILURE);
1143 if (subshell_pid == 0)
1145 /* We are in the child process */
1146 init_subshell_child (pty_name);
1149 init_subshell_precmd (precmd, BUF_MEDIUM);
1151 /* Set up `precmd' or equivalent for reading the subshell's CWD
1153 * Attention! Never forget that these are *one-liners* even though the concatenated
1154 * substrings contain line breaks and indentation for better understanding of the
1155 * shell code. It is vital that each one-liner ends with a line feed character ("\n" ).
1158 switch (subshell_type)
1160 case BASH:
1161 g_snprintf (precmd, sizeof (precmd),
1162 " PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND\n}'pwd>&%d;kill -STOP $$'\n"
1163 "PS1='\\u@\\h:\\w\\$ '\n", subshell_pipe[WRITE]);
1164 break;
1166 case ASH_BUSYBOX:
1167 /* BusyBox ash needs a somewhat complicated precmd emulation via PS1, and it is vital
1168 * that BB be built with active CONFIG_ASH_EXPAND_PRMT, but this is the default anyway.
1170 * A: This leads to a stopped subshell (=frozen mc) if user calls "ash" command
1171 * "PS1='$(pwd>&%d; kill -STOP $$)\\u@\\h:\\w\\$ '\n",
1173 * B: This leads to "sh: precmd: not found" in sub-subshell if user calls "ash" command
1174 * "precmd() { pwd>&%d; kill -STOP $$; }; "
1175 * "PS1='$(precmd)\\u@\\h:\\w\\$ '\n",
1177 * C: This works if user calls "ash" command because in sub-subshell
1178 * PRECMD is unfedined, thus evaluated to empty string - no damage done.
1179 * Attention: BusyBox must be built with FEATURE_EDITING_FANCY_PROMPT to
1180 * permit \u, \w, \h, \$ escape sequences. Unfortunately this cannot be guaranteed,
1181 * especially on embedded systems where people try to save space, so let's use
1182 * the dash version below. It should work on virtually all systems.
1183 * "precmd() { pwd>&%d; kill -STOP $$; }; "
1184 * "PRECMD=precmd; "
1185 * "PS1='$(eval $PRECMD)\\u@\\h:\\w\\$ '\n",
1187 case DASH:
1188 /* Debian ash needs a precmd emulation via PS1, similar to BusyBox ash,
1189 * but does not support escape sequences for user, host and cwd in prompt.
1190 * Attention! Make sure that the buffer for precmd is big enough.
1192 * We want to have a fancy dynamic prompt with user@host:cwd just like in the BusyBox
1193 * examples above, but because replacing the home directory part of the path by "~" is
1194 * complicated, it bloats the precmd to a size > BUF_SMALL (128).
1196 * The following example is a little less fancy (home directory not replaced)
1197 * and shows the basic workings of our prompt for easier understanding:
1199 * "precmd() { "
1200 * "echo \"$USER@$(hostname -s):$PWD\"; "
1201 * "pwd>&%d; "
1202 * "kill -STOP $$; "
1203 * "}; "
1204 * "PRECMD=precmd; "
1205 * "PS1='$($PRECMD)$ '\n",
1207 g_snprintf (precmd, sizeof (precmd),
1208 "precmd() { "
1209 "if [ ! \"${PWD##$HOME}\" ]; then "
1210 "MC_PWD=\"~\"; "
1211 "else "
1212 "[ \"${PWD##$HOME/}\" = \"$PWD\" ] && MC_PWD=\"$PWD\" || MC_PWD=\"~/${PWD##$HOME/}\"; "
1213 "fi; "
1214 "echo \"$USER@$(hostname -s):$MC_PWD\"; "
1215 "pwd>&%d; "
1216 "kill -STOP $$; "
1217 "}; " "PRECMD=precmd; " "PS1='$($PRECMD)$ '\n", subshell_pipe[WRITE]);
1218 break;
1220 case ZSH:
1221 g_snprintf (precmd, sizeof (precmd),
1222 " _mc_precmd(){ pwd>&%d;kill -STOP $$ }; precmd_functions+=(_mc_precmd)\n"
1223 "PS1='%%n@%%m:%%~%%# '\n", subshell_pipe[WRITE]);
1224 break;
1226 case TCSH:
1227 g_snprintf (precmd, sizeof (precmd),
1228 "set echo_style=both; "
1229 "set prompt='%%n@%%m:%%~%%# '; "
1230 "alias precmd 'echo $cwd:q >>%s; kill -STOP $$'\n", tcsh_fifo);
1231 break;
1233 case FISH:
1234 /* Use fish_prompt_mc function for prompt, if not present then copy fish_prompt to it. */
1235 /* We also want a fancy user@host:cwd prompt here, but fish makes it very easy to also
1236 * use colours, which is what we will do. But first here is a simpler, uncoloured version:
1237 * "function fish_prompt; "
1238 * "echo (whoami)@(hostname -s):(pwd)\\$\\ ; "
1239 * "echo \"$PWD\">&%d; "
1240 * "kill -STOP %%self; "
1241 * "end\n",
1243 * TODO: fish prompt is shown when panel is hidden (Ctrl-O), but not when it is visible.
1244 * Find out how to fix this.
1246 g_snprintf (precmd, sizeof (precmd),
1247 "if not functions -q fish_prompt_mc;"
1248 "functions -c fish_prompt fish_prompt_mc; end;"
1249 "function fish_prompt;"
1250 "echo (whoami)@(hostname -s):(set_color $fish_color_cwd)(pwd)(set_color normal)\\$\\ ; "
1251 "echo \"$PWD\">&%d; fish_prompt_mc; kill -STOP %%self; end\n",
1252 subshell_pipe[WRITE]);
1253 break;
1255 default:
1256 break;
1259 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
1261 /* Wait until the subshell has started up and processed the command */
1263 subshell_state = RUNNING_COMMAND;
1264 tty_enable_interrupt_key ();
1265 if (!feed_subshell (QUIETLY, TRUE))
1267 mc_global.tty.use_subshell = FALSE;
1269 tty_disable_interrupt_key ();
1270 if (!subshell_alive)
1271 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
1274 /* --------------------------------------------------------------------------------------------- */
1277 invoke_subshell (const char *command, int how, vfs_path_t ** new_dir_vpath)
1279 /* Make the MC terminal transparent */
1280 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
1282 /* Make the subshell change to MC's working directory */
1283 if (new_dir_vpath != NULL)
1284 do_subshell_chdir (subshell_get_cwd_from_current_panel (), TRUE);
1286 if (command == NULL) /* The user has done "C-o" from MC */
1288 if (subshell_state == INACTIVE)
1290 subshell_state = ACTIVE;
1291 /* FIXME: possibly take out this hack; the user can
1292 re-play it by hitting C-hyphen a few times! */
1293 if (subshell_ready)
1294 write_all (mc_global.tty.subshell_pty, " \b", 2); /* Hack to make prompt reappear */
1297 else /* MC has passed us a user command */
1299 if (how == QUIETLY)
1300 write_all (mc_global.tty.subshell_pty, " ", 1);
1301 /* FIXME: if command is long (>8KB ?) we go comma */
1302 write_all (mc_global.tty.subshell_pty, command, strlen (command));
1303 write_all (mc_global.tty.subshell_pty, "\n", 1);
1304 subshell_state = RUNNING_COMMAND;
1305 subshell_ready = FALSE;
1308 feed_subshell (how, FALSE);
1310 if (new_dir_vpath != NULL && subshell_alive)
1312 const char *pcwd;
1314 pcwd = vfs_translate_path (vfs_path_as_str (subshell_get_cwd_from_current_panel ()));
1315 if (strcmp (subshell_cwd, pcwd) != 0)
1316 *new_dir_vpath = vfs_path_from_str (subshell_cwd); /* Make MC change to the subshell's CWD */
1319 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
1320 while (!subshell_alive && subshell_get_mainloop_quit () == 0 && mc_global.tty.use_subshell)
1321 init_subshell ();
1323 return subshell_get_mainloop_quit ();
1327 /* --------------------------------------------------------------------------------------------- */
1329 gboolean
1330 read_subshell_prompt (void)
1332 int rc = 0;
1333 ssize_t bytes = 0;
1334 struct timeval timeleft = { 0, 0 };
1335 GString *p;
1336 gboolean prompt_was_reset = FALSE;
1338 fd_set tmp;
1339 FD_ZERO (&tmp);
1340 FD_SET (mc_global.tty.subshell_pty, &tmp);
1342 /* First time through */
1343 if (subshell_prompt == NULL)
1344 subshell_prompt = g_string_sized_new (INITIAL_PROMPT_SIZE);
1346 p = g_string_sized_new (INITIAL_PROMPT_SIZE);
1348 while (subshell_alive
1349 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)) != 0)
1351 ssize_t i;
1353 /* Check for 'select' errors */
1354 if (rc == -1)
1356 if (errno == EINTR)
1358 if (mc_global.tty.winch_flag != 0)
1359 tty_change_screen_size ();
1361 continue;
1364 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1365 exit (EXIT_FAILURE);
1368 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1370 /* Extract the prompt from the shell output */
1371 for (i = 0; i < bytes; i++)
1372 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1374 g_string_set_size (p, 0);
1375 prompt_was_reset = TRUE;
1377 else if (pty_buffer[i] != '\0')
1378 g_string_append_c (p, pty_buffer[i]);
1381 if (p->len != 0 || prompt_was_reset)
1382 g_string_assign (subshell_prompt, p->str);
1384 g_string_free (p, TRUE);
1386 return (rc != 0 || bytes != 0);
1389 /* --------------------------------------------------------------------------------------------- */
1391 void
1392 do_update_prompt (void)
1394 if (update_subshell_prompt)
1396 printf ("\r\n%s", subshell_prompt->str);
1397 fflush (stdout);
1398 update_subshell_prompt = FALSE;
1402 /* --------------------------------------------------------------------------------------------- */
1404 gboolean
1405 exit_subshell (void)
1407 gboolean subshell_quit = TRUE;
1409 if (subshell_state != INACTIVE && subshell_alive)
1410 subshell_quit =
1411 query_dialog (_("Warning"),
1412 _("The shell is still active. Quit anyway?"),
1413 D_NORMAL, 2, _("&Yes"), _("&No")) == 0;
1415 if (subshell_quit)
1417 if (subshell_type == TCSH)
1419 if (unlink (tcsh_fifo) == -1)
1420 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1421 tcsh_fifo, unix_error_string (errno));
1424 g_string_free (subshell_prompt, TRUE);
1425 subshell_prompt = NULL;
1426 pty_buffer[0] = '\0';
1429 return subshell_quit;
1432 /* --------------------------------------------------------------------------------------------- */
1434 /** If it actually changed the directory it returns true */
1435 void
1436 do_subshell_chdir (const vfs_path_t * vpath, gboolean update_prompt)
1438 char *pcwd;
1440 pcwd = vfs_path_to_str_flags (subshell_get_cwd_from_current_panel (), 0, VPF_RECODE);
1442 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1444 /* We have to repaint the subshell prompt if we read it from
1445 * the main program. Please note that in the code after this
1446 * if, the cd command that is sent will make the subshell
1447 * repaint the prompt, so we don't have to paint it. */
1448 if (update_prompt)
1449 do_update_prompt ();
1450 g_free (pcwd);
1451 return;
1454 /* The initial space keeps this out of the command history (in bash
1455 because we set "HISTCONTROL=ignorespace") */
1456 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1458 if (vpath != NULL)
1460 const char *translate;
1462 translate = vfs_translate_path (vfs_path_as_str (vpath));
1463 if (translate != NULL)
1465 GString *temp;
1467 temp = subshell_name_quote (translate);
1468 write_all (mc_global.tty.subshell_pty, temp->str, temp->len);
1469 g_string_free (temp, TRUE);
1471 else
1473 write_all (mc_global.tty.subshell_pty, ".", 1);
1476 else
1478 write_all (mc_global.tty.subshell_pty, "/", 1);
1480 write_all (mc_global.tty.subshell_pty, "\n", 1);
1482 subshell_state = RUNNING_COMMAND;
1483 feed_subshell (QUIETLY, FALSE);
1485 if (subshell_alive)
1487 gboolean bPathNotEq;
1489 bPathNotEq = strcmp (subshell_cwd, pcwd) != 0;
1491 if (bPathNotEq && subshell_type == TCSH)
1493 char rp_subshell_cwd[PATH_MAX];
1494 char rp_current_panel_cwd[PATH_MAX];
1495 char *p_subshell_cwd, *p_current_panel_cwd;
1497 p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1498 p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1500 if (p_subshell_cwd == NULL)
1501 p_subshell_cwd = subshell_cwd;
1502 if (p_current_panel_cwd == NULL)
1503 p_current_panel_cwd = pcwd;
1504 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd) != 0;
1507 if (bPathNotEq && !DIR_IS_DOT (pcwd))
1509 char *cwd;
1511 cwd =
1512 vfs_path_to_str_flags (subshell_get_cwd_from_current_panel (), 0,
1513 VPF_STRIP_PASSWORD);
1514 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd);
1515 g_free (cwd);
1519 /* Really escape Zsh history */
1520 if (subshell_type == ZSH)
1522 /* Per Zsh documentation last command prefixed with space lingers in the internal history
1523 * until the next command is entered before it vanishes. To make it vanish right away,
1524 * type a space and press return. */
1525 write_all (mc_global.tty.subshell_pty, " \n", 2);
1526 subshell_state = RUNNING_COMMAND;
1527 feed_subshell (QUIETLY, FALSE);
1530 update_subshell_prompt = FALSE;
1532 g_free (pcwd);
1533 /* Make sure that MC never stores the CWD in a silly format */
1534 /* like /usr////lib/../bin, or the strcmp() above will fail */
1537 /* --------------------------------------------------------------------------------------------- */
1539 void
1540 subshell_get_console_attributes (void)
1542 /* Get our current terminal modes */
1544 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1546 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1547 mc_global.tty.use_subshell = FALSE;
1551 /* --------------------------------------------------------------------------------------------- */
1553 * Figure out whether the subshell has stopped, exited or been killed
1554 * Possibly modifies: 'subshell_alive', 'subshell_stopped' and 'quit' */
1556 void
1557 sigchld_handler (int sig)
1559 int status;
1560 pid_t pid;
1562 (void) sig;
1564 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1566 if (pid == subshell_pid)
1568 /* Figure out what has happened to the subshell */
1570 if (WIFSTOPPED (status))
1572 if (WSTOPSIG (status) == SIGSTOP)
1574 /* The subshell has received a SIGSTOP signal */
1575 subshell_stopped = TRUE;
1577 else
1579 /* The user has suspended the subshell. Revive it */
1580 kill (subshell_pid, SIGCONT);
1583 else
1585 /* The subshell has either exited normally or been killed */
1586 subshell_alive = FALSE;
1587 delete_select_channel (mc_global.tty.subshell_pty);
1588 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1590 int subshell_quit;
1591 subshell_quit = subshell_get_mainloop_quit () | SUBSHELL_EXIT; /* Exited normally */
1592 subshell_set_mainloop_quit (subshell_quit);
1596 subshell_handle_cons_saver ();
1598 /* If we got here, some other child exited; ignore it */
1601 /* --------------------------------------------------------------------------------------------- */