Ticket #3890: syntax - add mjs extension to JavaScript pattern
[midnight-commander.git] / src / subshell / common.c
blob772d2c9397db7d7b1df66df23d27d53c4864c630
1 /*
2 Concurrent shell support for the Midnight Commander
4 Copyright (C) 1994-2017
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 /*** 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 /* --------------------------------------------------------------------------------------------- */
176 /*** file scope functions ************************************************************************/
177 /* --------------------------------------------------------------------------------------------- */
179 * Write all data, even if the write() call is interrupted.
182 static ssize_t
183 write_all (int fd, const void *buf, size_t count)
185 ssize_t written = 0;
187 while (count > 0)
189 ssize_t ret;
191 ret = write (fd, (const unsigned char *) buf + written, count);
192 if (ret < 0)
194 if (errno == EINTR)
196 if (mc_global.tty.winch_flag != 0)
197 tty_change_screen_size ();
199 continue;
202 return written > 0 ? written : ret;
204 count -= ret;
205 written += ret;
207 return written;
210 /* --------------------------------------------------------------------------------------------- */
212 * Prepare child process to running the shell and run it.
214 * Modifies the global variables (in the child process only):
215 * shell_mode
217 * Returns: never.
220 static void
221 init_subshell_child (const char *pty_name)
223 char *init_file = NULL;
224 char *putenv_str = 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 my_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 */
256 int ret;
258 ret = chdir (mc_config_get_home_dir ()); /* FIXME? What about when we re-run the subshell? */
259 (void) ret;
262 /* Set MC_SID to prevent running one mc from another */
263 mc_sid = getsid (0);
264 if (mc_sid != -1)
266 char sid_str[BUF_SMALL];
268 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
269 putenv (g_strdup (sid_str));
272 switch (mc_global.shell->type)
274 case SHELL_BASH:
275 /* Do we have a custom init file ~/.local/share/mc/bashrc? */
276 init_file = mc_config_get_full_path ("bashrc");
278 /* Otherwise use ~/.bashrc */
279 if (!exist_file (init_file))
281 g_free (init_file);
282 init_file = g_strdup (".bashrc");
285 /* Make MC's special commands not show up in bash's history and also suppress
286 * consecutive identical commands*/
287 putenv ((char *) "HISTCONTROL=ignoreboth");
289 /* Allow alternative readline settings for MC */
291 char *input_file;
293 input_file = mc_config_get_full_path ("inputrc");
294 if (exist_file (input_file))
296 putenv_str = g_strconcat ("INPUTRC=", input_file, (char *) NULL);
297 putenv (putenv_str);
299 g_free (input_file);
302 break;
304 case SHELL_ASH_BUSYBOX:
305 case SHELL_DASH:
306 /* Do we have a custom init file ~/.local/share/mc/ashrc? */
307 init_file = mc_config_get_full_path ("ashrc");
309 /* Otherwise use ~/.profile */
310 if (!exist_file (init_file))
312 g_free (init_file);
313 init_file = g_strdup (".profile");
316 /* Put init file to ENV variable used by ash */
317 putenv_str = g_strconcat ("ENV=", init_file, (char *) NULL);
318 putenv (putenv_str);
319 /* Do not use "g_free (putenv_str)" here, otherwise ENV will be undefined! */
321 break;
323 /* TODO: Find a way to pass initfile to TCSH, ZSH and FISH */
324 case SHELL_TCSH:
325 case SHELL_ZSH:
326 case SHELL_FISH:
327 break;
329 default:
330 fprintf (stderr, __FILE__ ": unimplemented subshell type %u\r\n", mc_global.shell->type);
331 my_exit (FORK_FAILURE);
334 /* Attach all our standard file descriptors to the pty */
336 /* This is done just before the fork, because stderr must still */
337 /* be connected to the real tty during the above error messages; */
338 /* otherwise the user will never see them. */
340 dup2 (subshell_pty_slave, STDIN_FILENO);
341 dup2 (subshell_pty_slave, STDOUT_FILENO);
342 dup2 (subshell_pty_slave, STDERR_FILENO);
344 close (subshell_pipe[READ]);
345 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
346 /* Close master side of pty. This is important; apart from */
347 /* freeing up the descriptor for use in the subshell, it also */
348 /* means that when MC exits, the subshell will get a SIGHUP and */
349 /* exit too, because there will be no more descriptors pointing */
350 /* at the master side of the pty and so it will disappear. */
351 close (mc_global.tty.subshell_pty);
353 /* Execute the subshell at last */
355 switch (mc_global.shell->type)
357 case SHELL_BASH:
358 execl (mc_global.shell->path, "bash", "-rcfile", init_file, (char *) NULL);
359 break;
361 case SHELL_ZSH:
362 /* Use -g to exclude cmds beginning with space from history
363 * and -Z to use the line editor on non-interactive term */
364 execl (mc_global.shell->path, "zsh", "-Z", "-g", (char *) NULL);
366 break;
368 case SHELL_ASH_BUSYBOX:
369 case SHELL_DASH:
370 case SHELL_TCSH:
371 case SHELL_FISH:
372 execl (mc_global.shell->path, mc_global.shell->path, (char *) NULL);
373 break;
375 default:
376 break;
379 /* If we get this far, everything failed miserably */
380 g_free (init_file);
381 g_free (putenv_str);
382 my_exit (FORK_FAILURE);
386 /* --------------------------------------------------------------------------------------------- */
388 * Check MC_SID to prevent running one mc from another.
389 * Return:
390 * 0 if no parent mc in our session was found,
391 * 1 if parent mc was found and the user wants to continue,
392 * 2 if parent mc was found and the user wants to quit mc.
395 static int
396 check_sid (void)
398 pid_t my_sid, old_sid;
399 const char *sid_str;
400 int r;
402 sid_str = getenv ("MC_SID");
403 if (sid_str == NULL)
404 return 0;
406 old_sid = (pid_t) strtol (sid_str, NULL, 0);
407 if (old_sid == 0)
408 return 0;
410 my_sid = getsid (0);
411 if (my_sid == -1)
412 return 0;
414 /* The parent mc is in a different session, it's OK */
415 if (old_sid != my_sid)
416 return 0;
418 r = query_dialog (_("Warning"),
419 _("GNU Midnight Commander is already\n"
420 "running on this terminal.\n"
421 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
423 return (r != 0) ? 2 : 1;
426 /* --------------------------------------------------------------------------------------------- */
428 static void
429 init_raw_mode (void)
431 static gboolean initialized = FALSE;
433 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
434 /* original settings. However, here we need to make this tty very raw, */
435 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
436 /* pty. So, instead of changing the code for execute(), pre_exec(), */
437 /* etc, we just set up the modes we need here, before each command. */
439 if (!initialized) /* First time: initialise 'raw_mode' */
441 tcgetattr (STDOUT_FILENO, &raw_mode);
442 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
443 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
444 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
445 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
446 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
447 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
448 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
449 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
450 initialized = TRUE;
454 /* --------------------------------------------------------------------------------------------- */
456 * Wait until the subshell dies or stops. If it stops, make it resume.
457 * Possibly modifies the globals 'subshell_alive' and 'subshell_stopped'
460 static void
461 synchronize (void)
463 sigset_t sigchld_mask, old_mask;
465 sigemptyset (&sigchld_mask);
466 sigaddset (&sigchld_mask, SIGCHLD);
467 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
470 * SIGCHLD should not be blocked, but we unblock it just in case.
471 * This is known to be useful for cygwin 1.3.12 and older.
473 sigdelset (&old_mask, SIGCHLD);
475 /* Wait until the subshell has stopped */
476 while (subshell_alive && !subshell_stopped)
477 sigsuspend (&old_mask);
479 if (subshell_state != ACTIVE)
481 /* Discard all remaining data from stdin to the subshell */
482 tcflush (subshell_pty_slave, TCIFLUSH);
485 subshell_stopped = FALSE;
486 kill (subshell_pid, SIGCONT);
488 sigprocmask (SIG_SETMASK, &old_mask, NULL);
489 /* We can't do any better without modifying the shell(s) */
492 /* --------------------------------------------------------------------------------------------- */
493 /** Feed the subshell our keyboard input until it says it's finished */
495 static gboolean
496 feed_subshell (int how, gboolean fail_on_error)
498 fd_set read_set; /* For 'select' */
499 int bytes; /* For the return value from 'read' */
500 int i; /* Loop counter */
502 struct timeval wtime; /* Maximum time we wait for the subshell */
503 struct timeval *wptr;
505 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
506 wtime.tv_sec = 10;
507 wtime.tv_usec = 0;
508 wptr = fail_on_error ? &wtime : NULL;
510 while (TRUE)
512 int maxfdp;
514 if (!subshell_alive)
515 return FALSE;
517 /* Prepare the file-descriptor set and call 'select' */
519 FD_ZERO (&read_set);
520 FD_SET (mc_global.tty.subshell_pty, &read_set);
521 FD_SET (subshell_pipe[READ], &read_set);
522 maxfdp = MAX (mc_global.tty.subshell_pty, subshell_pipe[READ]);
523 if (how == VISIBLY)
525 FD_SET (STDIN_FILENO, &read_set);
526 maxfdp = MAX (maxfdp, STDIN_FILENO);
529 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
531 /* Despite using SA_RESTART, we still have to check for this */
532 if (errno == EINTR)
534 if (mc_global.tty.winch_flag != 0)
535 tty_change_screen_size ();
537 continue; /* try all over again */
539 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
540 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
541 unix_error_string (errno));
542 exit (EXIT_FAILURE);
545 if (FD_ISSET (mc_global.tty.subshell_pty, &read_set))
546 /* Read from the subshell, write to stdout */
548 /* This loop improves performance by reducing context switches
549 by a factor of 20 or so... unfortunately, it also hangs MC
550 randomly, because of an apparent Linux bug. Investigate. */
551 /* for (i=0; i<5; ++i) * FIXME -- experimental */
553 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
555 /* The subshell has died */
556 if (bytes == -1 && errno == EIO && !subshell_alive)
557 return FALSE;
559 if (bytes <= 0)
561 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
562 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
563 exit (EXIT_FAILURE);
566 if (how == VISIBLY)
567 write_all (STDOUT_FILENO, pty_buffer, bytes);
570 else if (FD_ISSET (subshell_pipe[READ], &read_set))
571 /* Read the subshell's CWD and capture its prompt */
573 bytes = read (subshell_pipe[READ], subshell_cwd, sizeof (subshell_cwd));
574 if (bytes <= 0)
576 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
577 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
578 unix_error_string (errno));
579 exit (EXIT_FAILURE);
582 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
584 synchronize ();
586 subshell_ready = TRUE;
587 if (subshell_state == RUNNING_COMMAND)
589 subshell_state = INACTIVE;
590 return TRUE;
594 else if (FD_ISSET (STDIN_FILENO, &read_set))
595 /* Read from stdin, write to the subshell */
597 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
598 if (bytes <= 0)
600 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
601 fprintf (stderr,
602 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
603 exit (EXIT_FAILURE);
606 for (i = 0; i < bytes; ++i)
607 if (pty_buffer[i] == subshell_switch_key)
609 write_all (mc_global.tty.subshell_pty, pty_buffer, i);
610 if (subshell_ready)
611 subshell_state = INACTIVE;
612 return TRUE;
615 write_all (mc_global.tty.subshell_pty, pty_buffer, bytes);
617 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
618 subshell_ready = FALSE;
620 else
621 return FALSE;
625 /* --------------------------------------------------------------------------------------------- */
626 /* pty opening functions */
628 #ifdef HAVE_GRANTPT
630 /* System V version of pty_open_master */
632 static int
633 pty_open_master (char *pty_name)
635 char *slave_name;
636 int pty_master;
638 #ifdef HAVE_POSIX_OPENPT
639 pty_master = posix_openpt (O_RDWR);
640 #elif defined HAVE_GETPT
641 /* getpt () is a GNU extension (glibc 2.1.x) */
642 pty_master = getpt ();
643 #elif defined IS_AIX
644 strcpy (pty_name, "/dev/ptc");
645 pty_master = open (pty_name, O_RDWR);
646 #else
647 strcpy (pty_name, "/dev/ptmx");
648 pty_master = open (pty_name, O_RDWR);
649 #endif
651 if (pty_master == -1)
652 return -1;
654 if (grantpt (pty_master) == -1 /* Grant access to slave */
655 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
656 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
658 close (pty_master);
659 return -1;
661 strcpy (pty_name, slave_name);
662 return pty_master;
665 /* --------------------------------------------------------------------------------------------- */
666 /** System V version of pty_open_slave */
668 static int
669 pty_open_slave (const char *pty_name)
671 int pty_slave;
673 pty_slave = open (pty_name, O_RDWR);
674 if (pty_slave == -1)
676 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
677 return -1;
679 #if !defined(__osf__) && !defined(__linux__)
680 #if defined (I_FIND) && defined (I_PUSH)
681 if (ioctl (pty_slave, I_FIND, "ptem") == 0)
682 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
684 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
685 pty_slave, unix_error_string (errno));
686 close (pty_slave);
687 return -1;
690 if (ioctl (pty_slave, I_FIND, "ldterm") == 0)
691 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
693 fprintf (stderr,
694 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
695 pty_slave, unix_error_string (errno));
696 close (pty_slave);
697 return -1;
699 #if !defined(sgi) && !defined(__sgi)
700 if (ioctl (pty_slave, I_FIND, "ttcompat") == 0)
701 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
703 fprintf (stderr,
704 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
705 pty_slave, unix_error_string (errno));
706 close (pty_slave);
707 return -1;
709 #endif /* sgi || __sgi */
710 #endif /* I_FIND && I_PUSH */
711 #endif /* __osf__ || __linux__ */
713 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
714 return pty_slave;
717 #else /* !HAVE_GRANTPT */
719 /* --------------------------------------------------------------------------------------------- */
720 /** BSD version of pty_open_master */
721 static int
722 pty_open_master (char *pty_name)
724 int pty_master;
725 const char *ptr1, *ptr2;
727 strcpy (pty_name, "/dev/ptyXX");
728 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
730 pty_name[8] = *ptr1;
731 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
733 pty_name[9] = *ptr2;
735 /* Try to open master */
736 pty_master = open (pty_name, O_RDWR);
737 if (pty_master == -1)
739 if (errno == ENOENT) /* Different from EIO */
740 return -1; /* Out of pty devices */
741 continue; /* Try next pty device */
743 pty_name[5] = 't'; /* Change "pty" to "tty" */
744 if (access (pty_name, 6) != 0)
746 close (pty_master);
747 pty_name[5] = 'p';
748 continue;
750 return pty_master;
753 return -1; /* Ran out of pty devices */
756 /* --------------------------------------------------------------------------------------------- */
757 /** BSD version of pty_open_slave */
759 static int
760 pty_open_slave (const char *pty_name)
762 int pty_slave;
763 struct group *group_info;
765 group_info = getgrnam ("tty");
766 if (group_info != NULL)
768 /* The following two calls will only succeed if we are root */
769 /* [Commented out while permissions problem is investigated] */
770 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
771 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
773 pty_slave = open (pty_name, O_RDWR);
774 if (pty_slave == -1)
775 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
776 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
777 return pty_slave;
779 #endif /* !HAVE_GRANTPT */
782 /* --------------------------------------------------------------------------------------------- */
784 * Set up `precmd' or equivalent for reading the subshell's CWD.
786 * Attention! Never forget that these are *one-liners* even though the concatenated
787 * substrings contain line breaks and indentation for better understanding of the
788 * shell code. It is vital that each one-liner ends with a line feed character ("\n" ).
790 * @return initialized pre-command string
793 static void
794 init_subshell_precmd (char *precmd, size_t buff_size)
796 switch (mc_global.shell->type)
798 case SHELL_BASH:
799 g_snprintf (precmd, buff_size,
800 " PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND\n}'pwd>&%d;kill -STOP $$'\n"
801 "PS1='\\u@\\h:\\w\\$ '\n", subshell_pipe[WRITE]);
802 break;
804 case SHELL_ASH_BUSYBOX:
805 /* BusyBox ash needs a somewhat complicated precmd emulation via PS1, and it is vital
806 * that BB be built with active CONFIG_ASH_EXPAND_PRMT, but this is the default anyway.
808 * A: This leads to a stopped subshell (=frozen mc) if user calls "ash" command
809 * "PS1='$(pwd>&%d; kill -STOP $$)\\u@\\h:\\w\\$ '\n",
811 * B: This leads to "sh: precmd: not found" in sub-subshell if user calls "ash" command
812 * "precmd() { pwd>&%d; kill -STOP $$; }; "
813 * "PS1='$(precmd)\\u@\\h:\\w\\$ '\n",
815 * C: This works if user calls "ash" command because in sub-subshell
816 * PRECMD is unfedined, thus evaluated to empty string - no damage done.
817 * Attention: BusyBox must be built with FEATURE_EDITING_FANCY_PROMPT to
818 * permit \u, \w, \h, \$ escape sequences. Unfortunately this cannot be guaranteed,
819 * especially on embedded systems where people try to save space, so let's use
820 * the dash version below. It should work on virtually all systems.
821 * "precmd() { pwd>&%d; kill -STOP $$; }; "
822 * "PRECMD=precmd; "
823 * "PS1='$(eval $PRECMD)\\u@\\h:\\w\\$ '\n",
825 case SHELL_DASH:
826 /* Debian ash needs a precmd emulation via PS1, similar to BusyBox ash,
827 * but does not support escape sequences for user, host and cwd in prompt.
828 * Attention! Make sure that the buffer for precmd is big enough.
830 * We want to have a fancy dynamic prompt with user@host:cwd just like in the BusyBox
831 * examples above, but because replacing the home directory part of the path by "~" is
832 * complicated, it bloats the precmd to a size > BUF_SMALL (128).
834 * The following example is a little less fancy (home directory not replaced)
835 * and shows the basic workings of our prompt for easier understanding:
837 * "precmd() { "
838 * "echo \"$USER@$(hostname -s):$PWD\"; "
839 * "pwd>&%d; "
840 * "kill -STOP $$; "
841 * "}; "
842 * "PRECMD=precmd; "
843 * "PS1='$($PRECMD)$ '\n",
845 g_snprintf (precmd, buff_size,
846 "precmd() { "
847 "if [ ! \"${PWD##$HOME}\" ]; then "
848 "MC_PWD=\"~\"; "
849 "else "
850 "[ \"${PWD##$HOME/}\" = \"$PWD\" ] && MC_PWD=\"$PWD\" || MC_PWD=\"~/${PWD##$HOME/}\"; "
851 "fi; "
852 "echo \"$USER@$(hostname -s):$MC_PWD\"; "
853 "pwd>&%d; "
854 "kill -STOP $$; "
855 "}; " "PRECMD=precmd; " "PS1='$($PRECMD)$ '\n", subshell_pipe[WRITE]);
856 break;
858 case SHELL_ZSH:
859 g_snprintf (precmd, buff_size,
860 " _mc_precmd(){ pwd>&%d;kill -STOP $$ }; precmd_functions+=(_mc_precmd)\n"
861 "PS1='%%n@%%m:%%~%%# '\n", subshell_pipe[WRITE]);
862 break;
864 case SHELL_TCSH:
865 g_snprintf (precmd, buff_size,
866 "set echo_style=both; "
867 "set prompt='%%n@%%m:%%~%%# '; "
868 "alias precmd 'echo $cwd:q >>%s; kill -STOP $$'\n", tcsh_fifo);
869 break;
871 case SHELL_FISH:
872 /* We also want a fancy user@host:cwd prompt here, but fish makes it very easy to also
873 * use colours, which is what we will do. But first here is a simpler, uncoloured version:
874 * "function fish_prompt; "
875 * "echo (whoami)@(hostname -s):(pwd)\\$\\ ; "
876 * "echo \"$PWD\">&%d; "
877 * "kill -STOP %%self; "
878 * "end\n",
880 * TODO: fish prompt is shown when panel is hidden (Ctrl-O), but not when it is visible.
881 * Find out how to fix this.
883 g_snprintf (precmd, buff_size,
884 " if not functions -q fish_prompt_mc;"
885 "functions -c fish_prompt fish_prompt_mc; end;"
886 "function fish_prompt;"
887 "echo (whoami)@(hostname -s):(set_color $fish_color_cwd)(pwd)(set_color normal)\\$\\ ; "
888 "echo \"$PWD\">&%d; fish_prompt_mc; kill -STOP %%self; end\n",
889 subshell_pipe[WRITE]);
890 break;
892 default:
893 break;
897 /* --------------------------------------------------------------------------------------------- */
899 * Carefully quote directory name to allow entering any directory safely,
900 * no matter what weird characters it may contain in its name.
901 * NOTE: Treat directory name an untrusted data, don't allow it to cause
902 * executing any commands in the shell. Escape all control characters.
903 * Use following technique:
905 * printf(1) with format string containing a single conversion specifier,
906 * "b", and an argument which contains a copy of the string passed to
907 * subshell_name_quote() with all characters, except digits and letters,
908 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
909 * numeric value of the character converted to octal number.
911 * cd "`printf '%b' 'ABC\0nnnDEF\0nnnXYZ'`"
913 * N.B.: Use single quotes for conversion specifier to work around
914 * tcsh 6.20+ parser breakage, see ticket #3852 for the details.
917 static GString *
918 subshell_name_quote (const char *s)
920 GString *ret;
921 const char *su, *n;
922 const char *quote_cmd_start, *quote_cmd_end;
924 if (mc_global.shell->type == SHELL_FISH)
926 quote_cmd_start = "(printf '%b' '";
927 quote_cmd_end = "')";
929 /* TODO: When BusyBox printf is fixed, get rid of this "else if", see
930 http://lists.busybox.net/pipermail/busybox/2012-March/077460.html */
931 /* else if (subshell_type == ASH_BUSYBOX)
933 quote_cmd_start = "\"`echo -en '";
934 quote_cmd_end = "'`\"";
935 } */
936 else
938 quote_cmd_start = "\"`printf '%b' '";
939 quote_cmd_end = "'`\"";
942 ret = g_string_sized_new (64);
944 /* Prevent interpreting leading '-' as a switch for 'cd' */
945 if (s[0] == '-')
946 g_string_append (ret, "./");
948 /* Copy the beginning of the command to the buffer */
949 g_string_append (ret, quote_cmd_start);
952 * Print every character except digits and letters as a backslash-escape
953 * sequence of the form \0nnn, where "nnn" is the numeric value of the
954 * character converted to octal number.
956 for (su = s; su[0] != '\0'; su = n)
958 n = str_cget_next_char_safe (su);
960 if (str_isalnum (su))
961 g_string_append_len (ret, su, n - su);
962 else
964 int c;
966 for (c = 0; c < n - su; c++)
967 g_string_append_printf (ret, "\\0%03o", (unsigned char) su[c]);
971 g_string_append (ret, quote_cmd_end);
973 return ret;
976 /* --------------------------------------------------------------------------------------------- */
977 /*** public functions ****************************************************************************/
978 /* --------------------------------------------------------------------------------------------- */
980 /* --------------------------------------------------------------------------------------------- */
982 * Fork the subshell, and set up many, many things.
984 * Possibly modifies the global variables:
985 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
986 * mc_global.tty.use_subshell - Is set to FALSE if we can't run the subshell
987 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
990 void
991 init_subshell (void)
993 /* This must be remembered across calls to init_subshell() */
994 static char pty_name[BUF_SMALL];
995 /* Must be considerably longer than BUF_SMALL (128) to support fancy shell prompts */
996 char precmd[BUF_MEDIUM];
998 switch (check_sid ())
1000 case 1:
1001 mc_global.tty.use_subshell = FALSE;
1002 return;
1003 case 2:
1004 mc_global.tty.use_subshell = FALSE;
1005 mc_global.midnight_shutdown = TRUE;
1006 return;
1007 default:
1008 break;
1011 /* Take the current (hopefully pristine) tty mode and make */
1012 /* a raw mode based on it now, before we do anything else with it */
1013 init_raw_mode ();
1015 if (mc_global.tty.subshell_pty == 0)
1016 { /* First time through */
1017 if (mc_global.shell->type == SHELL_NONE)
1018 return;
1020 /* Open a pty for talking to the subshell */
1022 /* FIXME: We may need to open a fresh pty each time on SVR4 */
1024 mc_global.tty.subshell_pty = pty_open_master (pty_name);
1025 if (mc_global.tty.subshell_pty == -1)
1027 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
1028 mc_global.tty.use_subshell = FALSE;
1029 return;
1031 subshell_pty_slave = pty_open_slave (pty_name);
1032 if (subshell_pty_slave == -1)
1034 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
1035 pty_name, unix_error_string (errno));
1036 mc_global.tty.use_subshell = FALSE;
1037 return;
1040 /* Create a pipe for receiving the subshell's CWD */
1042 if (mc_global.shell->type == SHELL_TCSH)
1044 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
1045 mc_tmpdir (), (int) getpid ());
1046 if (mkfifo (tcsh_fifo, 0600) == -1)
1048 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
1049 mc_global.tty.use_subshell = FALSE;
1050 return;
1053 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
1055 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
1056 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
1058 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
1059 perror (__FILE__ ": open");
1060 mc_global.tty.use_subshell = FALSE;
1061 return;
1064 else if (pipe (subshell_pipe)) /* subshell_type is BASH, ASH_BUSYBOX, DASH or ZSH */
1066 perror (__FILE__ ": couldn't create pipe");
1067 mc_global.tty.use_subshell = FALSE;
1068 return;
1072 /* Fork the subshell */
1074 subshell_alive = TRUE;
1075 subshell_stopped = FALSE;
1076 subshell_pid = fork ();
1078 if (subshell_pid == -1)
1080 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
1081 /* We exit here because, if the process table is full, the */
1082 /* other method of running user commands won't work either */
1083 exit (EXIT_FAILURE);
1086 if (subshell_pid == 0)
1088 /* We are in the child process */
1089 init_subshell_child (pty_name);
1092 init_subshell_precmd (precmd, BUF_MEDIUM);
1094 write_all (mc_global.tty.subshell_pty, precmd, strlen (precmd));
1096 /* Wait until the subshell has started up and processed the command */
1098 subshell_state = RUNNING_COMMAND;
1099 tty_enable_interrupt_key ();
1100 if (!feed_subshell (QUIETLY, TRUE))
1102 mc_global.tty.use_subshell = FALSE;
1104 tty_disable_interrupt_key ();
1105 if (!subshell_alive)
1106 mc_global.tty.use_subshell = FALSE; /* Subshell died instantly, so don't use it */
1109 /* --------------------------------------------------------------------------------------------- */
1112 invoke_subshell (const char *command, int how, vfs_path_t ** new_dir_vpath)
1114 /* Make the MC terminal transparent */
1115 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
1117 /* Make the subshell change to MC's working directory */
1118 if (new_dir_vpath != NULL)
1119 do_subshell_chdir (subshell_get_cwd_from_current_panel (), TRUE);
1121 if (command == NULL) /* The user has done "C-o" from MC */
1123 if (subshell_state == INACTIVE)
1125 subshell_state = ACTIVE;
1126 /* FIXME: possibly take out this hack; the user can
1127 re-play it by hitting C-hyphen a few times! */
1128 if (subshell_ready)
1129 write_all (mc_global.tty.subshell_pty, " \b", 2); /* Hack to make prompt reappear */
1132 else /* MC has passed us a user command */
1134 if (how == QUIETLY)
1135 write_all (mc_global.tty.subshell_pty, " ", 1);
1136 /* FIXME: if command is long (>8KB ?) we go comma */
1137 write_all (mc_global.tty.subshell_pty, command, strlen (command));
1138 write_all (mc_global.tty.subshell_pty, "\n", 1);
1139 subshell_state = RUNNING_COMMAND;
1140 subshell_ready = FALSE;
1143 feed_subshell (how, FALSE);
1145 if (new_dir_vpath != NULL && subshell_alive)
1147 const char *pcwd;
1149 pcwd = vfs_translate_path (vfs_path_as_str (subshell_get_cwd_from_current_panel ()));
1150 if (strcmp (subshell_cwd, pcwd) != 0)
1151 *new_dir_vpath = vfs_path_from_str (subshell_cwd); /* Make MC change to the subshell's CWD */
1154 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
1155 while (!subshell_alive && subshell_get_mainloop_quit () == 0 && mc_global.tty.use_subshell)
1156 init_subshell ();
1158 return subshell_get_mainloop_quit ();
1162 /* --------------------------------------------------------------------------------------------- */
1164 gboolean
1165 read_subshell_prompt (void)
1167 int rc = 0;
1168 ssize_t bytes = 0;
1169 struct timeval timeleft = { 0, 0 };
1170 GString *p;
1171 gboolean prompt_was_reset = FALSE;
1173 fd_set tmp;
1174 FD_ZERO (&tmp);
1175 FD_SET (mc_global.tty.subshell_pty, &tmp);
1177 /* First time through */
1178 if (subshell_prompt == NULL)
1179 subshell_prompt = g_string_sized_new (INITIAL_PROMPT_SIZE);
1181 p = g_string_sized_new (INITIAL_PROMPT_SIZE);
1183 while (subshell_alive
1184 && (rc = select (mc_global.tty.subshell_pty + 1, &tmp, NULL, NULL, &timeleft)) != 0)
1186 ssize_t i;
1188 /* Check for 'select' errors */
1189 if (rc == -1)
1191 if (errno == EINTR)
1193 if (mc_global.tty.winch_flag != 0)
1194 tty_change_screen_size ();
1196 continue;
1199 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1200 exit (EXIT_FAILURE);
1203 bytes = read (mc_global.tty.subshell_pty, pty_buffer, sizeof (pty_buffer));
1205 /* Extract the prompt from the shell output */
1206 for (i = 0; i < bytes; i++)
1207 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1209 g_string_set_size (p, 0);
1210 prompt_was_reset = TRUE;
1212 else if (pty_buffer[i] != '\0')
1213 g_string_append_c (p, pty_buffer[i]);
1216 if (p->len != 0 || prompt_was_reset)
1217 g_string_assign (subshell_prompt, p->str);
1219 g_string_free (p, TRUE);
1221 return (rc != 0 || bytes != 0);
1224 /* --------------------------------------------------------------------------------------------- */
1226 void
1227 do_update_prompt (void)
1229 if (update_subshell_prompt)
1231 printf ("\r\n%s", subshell_prompt->str);
1232 fflush (stdout);
1233 update_subshell_prompt = FALSE;
1237 /* --------------------------------------------------------------------------------------------- */
1239 gboolean
1240 exit_subshell (void)
1242 gboolean subshell_quit = TRUE;
1244 if (subshell_state != INACTIVE && subshell_alive)
1245 subshell_quit =
1246 query_dialog (_("Warning"),
1247 _("The shell is still active. Quit anyway?"),
1248 D_NORMAL, 2, _("&Yes"), _("&No")) == 0;
1250 if (subshell_quit)
1252 if (mc_global.shell->type == SHELL_TCSH)
1254 if (unlink (tcsh_fifo) == -1)
1255 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1256 tcsh_fifo, unix_error_string (errno));
1259 g_string_free (subshell_prompt, TRUE);
1260 subshell_prompt = NULL;
1261 pty_buffer[0] = '\0';
1264 return subshell_quit;
1267 /* --------------------------------------------------------------------------------------------- */
1269 /** If it actually changed the directory it returns true */
1270 void
1271 do_subshell_chdir (const vfs_path_t * vpath, gboolean update_prompt)
1273 char *pcwd;
1275 pcwd = vfs_path_to_str_flags (subshell_get_cwd_from_current_panel (), 0, VPF_RECODE);
1277 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1279 /* We have to repaint the subshell prompt if we read it from
1280 * the main program. Please note that in the code after this
1281 * if, the cd command that is sent will make the subshell
1282 * repaint the prompt, so we don't have to paint it. */
1283 if (update_prompt)
1284 do_update_prompt ();
1285 g_free (pcwd);
1286 return;
1289 /* The initial space keeps this out of the command history (in bash
1290 because we set "HISTCONTROL=ignorespace") */
1291 write_all (mc_global.tty.subshell_pty, " cd ", 4);
1293 if (vpath != NULL)
1295 const char *translate;
1297 translate = vfs_translate_path (vfs_path_as_str (vpath));
1298 if (translate != NULL)
1300 GString *temp;
1302 temp = subshell_name_quote (translate);
1303 write_all (mc_global.tty.subshell_pty, temp->str, temp->len);
1304 g_string_free (temp, TRUE);
1306 else
1308 write_all (mc_global.tty.subshell_pty, ".", 1);
1311 else
1313 write_all (mc_global.tty.subshell_pty, "/", 1);
1315 write_all (mc_global.tty.subshell_pty, "\n", 1);
1317 subshell_state = RUNNING_COMMAND;
1318 feed_subshell (QUIETLY, FALSE);
1320 if (subshell_alive)
1322 gboolean bPathNotEq;
1324 bPathNotEq = strcmp (subshell_cwd, pcwd) != 0;
1326 if (bPathNotEq && mc_global.shell->type == SHELL_TCSH)
1328 char rp_subshell_cwd[PATH_MAX];
1329 char rp_current_panel_cwd[PATH_MAX];
1330 char *p_subshell_cwd, *p_current_panel_cwd;
1332 p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1333 p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1335 if (p_subshell_cwd == NULL)
1336 p_subshell_cwd = subshell_cwd;
1337 if (p_current_panel_cwd == NULL)
1338 p_current_panel_cwd = pcwd;
1339 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd) != 0;
1342 if (bPathNotEq && !DIR_IS_DOT (pcwd))
1344 char *cwd;
1346 cwd =
1347 vfs_path_to_str_flags (subshell_get_cwd_from_current_panel (), 0,
1348 VPF_STRIP_PASSWORD);
1349 vfs_print_message (_("Warning: Cannot change to %s.\n"), cwd);
1350 g_free (cwd);
1354 /* Really escape Zsh history */
1355 if (mc_global.shell->type == SHELL_ZSH)
1357 /* Per Zsh documentation last command prefixed with space lingers in the internal history
1358 * until the next command is entered before it vanishes. To make it vanish right away,
1359 * type a space and press return. */
1360 write_all (mc_global.tty.subshell_pty, " \n", 2);
1361 subshell_state = RUNNING_COMMAND;
1362 feed_subshell (QUIETLY, FALSE);
1365 update_subshell_prompt = FALSE;
1367 g_free (pcwd);
1368 /* Make sure that MC never stores the CWD in a silly format */
1369 /* like /usr////lib/../bin, or the strcmp() above will fail */
1372 /* --------------------------------------------------------------------------------------------- */
1374 void
1375 subshell_get_console_attributes (void)
1377 /* Get our current terminal modes */
1379 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1381 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1382 mc_global.tty.use_subshell = FALSE;
1386 /* --------------------------------------------------------------------------------------------- */
1388 * Figure out whether the subshell has stopped, exited or been killed
1389 * Possibly modifies: 'subshell_alive', 'subshell_stopped' and 'quit' */
1391 void
1392 sigchld_handler (int sig)
1394 int status;
1395 pid_t pid;
1397 (void) sig;
1399 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1401 if (pid == subshell_pid)
1403 /* Figure out what has happened to the subshell */
1405 if (WIFSTOPPED (status))
1407 if (WSTOPSIG (status) == SIGSTOP)
1409 /* The subshell has received a SIGSTOP signal */
1410 subshell_stopped = TRUE;
1412 else
1414 /* The user has suspended the subshell. Revive it */
1415 kill (subshell_pid, SIGCONT);
1418 else
1420 /* The subshell has either exited normally or been killed */
1421 subshell_alive = FALSE;
1422 delete_select_channel (mc_global.tty.subshell_pty);
1423 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1425 int subshell_quit;
1426 subshell_quit = subshell_get_mainloop_quit () | SUBSHELL_EXIT; /* Exited normally */
1427 subshell_set_mainloop_quit (subshell_quit);
1431 subshell_handle_cons_saver ();
1433 /* If we got here, some other child exited; ignore it */
1436 /* --------------------------------------------------------------------------------------------- */