Added locale setting before calling dpkg to fix "link to" parsing on non-C locales
[midnight-commander.git] / src / subshell.c
blob3ab7f8b9e2249953edcf0196648162f7f73adb70
1 /* Concurrent shell support for the Midnight Commander
2 Copyright (C) 1994, 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of Version 2 of the GNU General Public
7 License, as published by the Free Software Foundation.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 /** \file subshell.c
20 * \brief Source: concurrent shell support
23 #include <config.h>
25 #ifdef HAVE_SUBSHELL_SUPPORT
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE 1
29 #endif
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43 #include <termios.h>
44 #include <unistd.h>
46 #ifdef HAVE_STROPTS_H
47 #include <stropts.h> /* For I_PUSH */
48 #endif /* HAVE_STROPTS_H */
50 #include "lib/global.h"
52 #include "lib/tty/tty.h" /* LINES */
53 #include "lib/tty/key.h" /* XCTRL */
54 #include "lib/vfs/mc-vfs/vfs.h"
55 #include "lib/strutil.h"
56 #include "lib/fileloc.h"
57 #include "lib/util.h"
58 #include "lib/widget.h"
60 #include "filemanager/midnight.h" /* current_panel */
62 #include "main.h" /* home_dir */
63 #include "consaver/cons.saver.h" /* handle_console() */
64 #include "subshell.h"
66 /*** global variables ****************************************************************************/
68 /* If using a subshell for evaluating commands this is true */
69 int use_subshell =
70 #ifdef SUBSHELL_OPTIONAL
71 FALSE;
72 #else
73 TRUE;
74 #endif
76 /* File descriptors of the pseudoterminal used by the subshell */
77 int subshell_pty = 0;
79 /* State of the subshell:
80 * INACTIVE: the default state; awaiting a command
81 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
82 * RUNNING_COMMAND: return to MC when the current command finishes */
83 enum subshell_state_enum subshell_state;
85 /* Holds the latest prompt captured from the subshell */
86 char *subshell_prompt = NULL;
88 /* Subshell: if set, then the prompt was not saved on CONSOLE_SAVE */
89 /* We need to paint it after CONSOLE_RESTORE, see: load_prompt */
90 gboolean update_subshell_prompt = FALSE;
92 /*** file scope macro definitions ****************************************************************/
94 #ifndef WEXITSTATUS
95 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
96 #endif
98 #ifndef WIFEXITED
99 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
100 #endif
102 #ifndef STDIN_FILENO
103 #define STDIN_FILENO 0
104 #endif
106 #ifndef STDOUT_FILENO
107 #define STDOUT_FILENO 1
108 #endif
110 #ifndef STDERR_FILENO
111 #define STDERR_FILENO 2
112 #endif
114 /* Initial length of the buffer for the subshell's prompt */
115 #define INITIAL_PROMPT_SIZE 10
117 /* Used by the child process to indicate failure to start the subshell */
118 #define FORK_FAILURE 69 /* Arbitrary */
120 /* Length of the buffer for all I/O with the subshell */
121 #define PTY_BUFFER_SIZE BUF_SMALL /* Arbitrary; but keep it >= 80 */
123 /*** file scope type declarations ****************************************************************/
125 /* For pipes */
126 enum
128 READ = 0,
129 WRITE = 1
132 /* Subshell type (gleaned from the SHELL environment variable, if available) */
133 static enum
135 BASH,
136 TCSH,
137 ZSH,
138 FISH
139 } subshell_type;
141 /*** file scope variables ************************************************************************/
143 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
144 static char tcsh_fifo[128];
146 static int subshell_pty_slave = -1;
148 /* The key for switching back to MC from the subshell */
149 /* *INDENT-OFF* */
150 static const char subshell_switch_key = XCTRL ('o') & 255;
151 /* *INDENT-ON* */
153 /* For reading/writing on the subshell's pty */
154 static char pty_buffer[PTY_BUFFER_SIZE] = "\0";
156 /* To pass CWD info from the subshell to MC */
157 static int subshell_pipe[2];
159 /* The subshell's process ID */
160 static pid_t subshell_pid = 1;
162 /* One extra char for final '\n' */
163 static char subshell_cwd[MC_MAXPATHLEN + 1];
165 /* Flag to indicate whether the subshell is ready for next command */
166 static int subshell_ready;
168 /* The following two flags can be changed by the SIGCHLD handler. This is */
169 /* OK, because the `int' type is updated atomically on all known machines */
170 static volatile int subshell_alive, subshell_stopped;
172 /* We store the terminal's initial mode here so that we can configure
173 the pty similarly, and also so we can restore the real terminal to
174 sanity if we have to exit abruptly */
175 static struct termios shell_mode;
177 /* This is a transparent mode for the terminal where MC is running on */
178 /* It is used when the shell is active, so that the control signals */
179 /* are delivered to the shell pty */
180 static struct termios raw_mode;
182 /* This counter indicates how many characters of prompt we have read */
183 /* FIXME: try to figure out why this had to become global */
184 static int prompt_pos;
187 /*** file scope functions ************************************************************************/
189 /* --------------------------------------------------------------------------------------------- */
191 * Write all data, even if the write() call is interrupted.
194 static ssize_t
195 write_all (int fd, const void *buf, size_t count)
197 ssize_t ret;
198 ssize_t written = 0;
199 while (count > 0)
201 ret = write (fd, (const unsigned char *) buf + written, count);
202 if (ret < 0)
204 if (errno == EINTR)
206 continue;
208 else
210 return written > 0 ? written : ret;
213 count -= ret;
214 written += ret;
216 return written;
219 /* --------------------------------------------------------------------------------------------- */
221 /** Resize given terminal using TIOCSWINSZ, return ioctl() result */
222 static int
223 resize_tty (int fd)
225 #if defined TIOCSWINSZ
226 struct winsize tty_size;
228 tty_size.ws_row = LINES;
229 tty_size.ws_col = COLS;
230 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
232 return ioctl (fd, TIOCSWINSZ, &tty_size);
233 #else
234 return 0;
235 #endif
238 /* --------------------------------------------------------------------------------------------- */
240 * Prepare child process to running the shell and run it.
242 * Modifies the global variables (in the child process only):
243 * shell_mode
245 * Returns: never.
248 static void
249 init_subshell_child (const char *pty_name)
251 const char *init_file = NULL;
252 pid_t mc_sid;
254 (void) pty_name;
255 setsid (); /* Get a fresh terminal session */
257 /* Make sure that it has become our controlling terminal */
259 /* Redundant on Linux and probably most systems, but just in case: */
261 #ifdef TIOCSCTTY
262 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
263 #endif
265 /* Configure its terminal modes and window size */
267 /* Set up the pty with the same termios flags as our own tty */
268 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode))
270 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n", unix_error_string (errno));
271 _exit (FORK_FAILURE);
274 /* Set the pty's size (80x25 by default on Linux) according to the */
275 /* size of the real terminal as calculated by ncurses, if possible */
276 resize_tty (subshell_pty_slave);
278 /* Set up the subshell's environment and init file name */
280 /* It simplifies things to change to our home directory here, */
281 /* and the user's startup file may do a `cd' command anyway */
283 int ret;
284 ret = chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
287 /* Set MC_SID to prevent running one mc from another */
288 mc_sid = getsid (0);
289 if (mc_sid != -1)
291 char sid_str[BUF_SMALL];
292 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld", (long) mc_sid);
293 putenv (g_strdup (sid_str));
296 switch (subshell_type)
298 case BASH:
299 init_file = MC_USERCONF_DIR PATH_SEP_STR "bashrc";
300 if (access (init_file, R_OK) == -1)
301 init_file = ".bashrc";
303 /* Make MC's special commands not show up in bash's history */
304 putenv ((char *) "HISTCONTROL=ignorespace");
306 /* Allow alternative readline settings for MC */
307 if (access (MC_USERCONF_DIR PATH_SEP_STR "inputrc", R_OK) == 0)
308 putenv ((char *) "INPUTRC=" MC_USERCONF_DIR PATH_SEP_STR "/inputrc");
310 break;
312 /* TODO: Find a way to pass initfile to TCSH and ZSH */
313 case TCSH:
314 case ZSH:
315 case FISH:
316 break;
318 default:
319 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n", subshell_type);
320 _exit (FORK_FAILURE);
323 /* Attach all our standard file descriptors to the pty */
325 /* This is done just before the fork, because stderr must still */
326 /* be connected to the real tty during the above error messages; */
327 /* otherwise the user will never see them. */
329 dup2 (subshell_pty_slave, STDIN_FILENO);
330 dup2 (subshell_pty_slave, STDOUT_FILENO);
331 dup2 (subshell_pty_slave, STDERR_FILENO);
333 close (subshell_pipe[READ]);
334 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
335 /* Close master side of pty. This is important; apart from */
336 /* freeing up the descriptor for use in the subshell, it also */
337 /* means that when MC exits, the subshell will get a SIGHUP and */
338 /* exit too, because there will be no more descriptors pointing */
339 /* at the master side of the pty and so it will disappear. */
340 close (subshell_pty);
342 /* Execute the subshell at last */
344 switch (subshell_type)
346 case BASH:
347 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
348 break;
350 case TCSH:
351 execl (shell, "tcsh", (char *) NULL);
352 break;
354 case ZSH:
355 /* Use -g to exclude cmds beginning with space from history
356 * and -Z to use the line editor on non-interactive term */
357 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
359 break;
361 case FISH:
362 execl (shell, "fish", (char *) NULL);
363 break;
366 /* If we get this far, everything failed miserably */
367 _exit (FORK_FAILURE);
371 /* --------------------------------------------------------------------------------------------- */
373 * Check MC_SID to prevent running one mc from another.
374 * Return:
375 * 0 if no parent mc in our session was found,
376 * 1 if parent mc was found and the user wants to continue,
377 * 2 if parent mc was found and the user wants to quit mc.
380 static int
381 check_sid (void)
383 pid_t my_sid, old_sid;
384 const char *sid_str;
385 int r;
387 sid_str = getenv ("MC_SID");
388 if (!sid_str)
389 return 0;
391 old_sid = (pid_t) strtol (sid_str, NULL, 0);
392 if (!old_sid)
393 return 0;
395 my_sid = getsid (0);
396 if (my_sid == -1)
397 return 0;
399 /* The parent mc is in a different session, it's OK */
400 if (old_sid != my_sid)
401 return 0;
403 r = query_dialog (_("Warning"),
404 _("GNU Midnight Commander is already\n"
405 "running on this terminal.\n"
406 "Subshell support will be disabled."), D_ERROR, 2, _("&OK"), _("&Quit"));
407 if (r != 0)
409 return 2;
412 return 1;
415 /* --------------------------------------------------------------------------------------------- */
417 static void
418 init_raw_mode (void)
420 static int initialized = 0;
422 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
423 /* original settings. However, here we need to make this tty very raw, */
424 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
425 /* pty. So, instead of changing the code for execute(), pre_exec(), */
426 /* etc, we just set up the modes we need here, before each command. */
428 if (initialized == 0) /* First time: initialise `raw_mode' */
430 tcgetattr (STDOUT_FILENO, &raw_mode);
431 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
432 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
433 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
434 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
435 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
436 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
437 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
438 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
439 initialized = 1;
443 /* --------------------------------------------------------------------------------------------- */
445 * Wait until the subshell dies or stops. If it stops, make it resume.
446 * Possibly modifies the globals `subshell_alive' and `subshell_stopped'
449 static void
450 synchronize (void)
452 sigset_t sigchld_mask, old_mask;
454 sigemptyset (&sigchld_mask);
455 sigaddset (&sigchld_mask, SIGCHLD);
456 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
459 * SIGCHLD should not be blocked, but we unblock it just in case.
460 * This is known to be useful for cygwin 1.3.12 and older.
462 sigdelset (&old_mask, SIGCHLD);
464 /* Wait until the subshell has stopped */
465 while (subshell_alive && !subshell_stopped)
466 sigsuspend (&old_mask);
468 if (subshell_state != ACTIVE)
470 /* Discard all remaining data from stdin to the subshell */
471 tcflush (subshell_pty_slave, TCIFLUSH);
474 subshell_stopped = FALSE;
475 kill (subshell_pid, SIGCONT);
477 sigprocmask (SIG_SETMASK, &old_mask, NULL);
478 /* We can't do any better without modifying the shell(s) */
481 /* --------------------------------------------------------------------------------------------- */
482 /** Feed the subshell our keyboard input until it says it's finished */
484 static gboolean
485 feed_subshell (int how, int fail_on_error)
487 fd_set read_set; /* For `select' */
488 int maxfdp;
489 int bytes; /* For the return value from `read' */
490 int i; /* Loop counter */
492 struct timeval wtime; /* Maximum time we wait for the subshell */
493 struct timeval *wptr;
495 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
496 wtime.tv_sec = 10;
497 wtime.tv_usec = 0;
498 wptr = fail_on_error ? &wtime : NULL;
500 while (TRUE)
502 if (!subshell_alive)
503 return FALSE;
505 /* Prepare the file-descriptor set and call `select' */
507 FD_ZERO (&read_set);
508 FD_SET (subshell_pty, &read_set);
509 FD_SET (subshell_pipe[READ], &read_set);
510 maxfdp = max (subshell_pty, subshell_pipe[READ]);
511 if (how == VISIBLY)
513 FD_SET (STDIN_FILENO, &read_set);
514 maxfdp = max (maxfdp, STDIN_FILENO);
517 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1)
520 /* Despite using SA_RESTART, we still have to check for this */
521 if (errno == EINTR)
522 continue; /* try all over again */
523 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
524 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
525 unix_error_string (errno));
526 exit (EXIT_FAILURE);
529 if (FD_ISSET (subshell_pty, &read_set))
530 /* Read from the subshell, write to stdout */
532 /* This loop improves performance by reducing context switches
533 by a factor of 20 or so... unfortunately, it also hangs MC
534 randomly, because of an apparent Linux bug. Investigate. */
535 /* for (i=0; i<5; ++i) * FIXME -- experimental */
537 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
539 /* The subshell has died */
540 if (bytes == -1 && errno == EIO && !subshell_alive)
541 return FALSE;
543 if (bytes <= 0)
545 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
546 fprintf (stderr, "read (subshell_pty...): %s\r\n", unix_error_string (errno));
547 exit (EXIT_FAILURE);
550 if (how == VISIBLY)
551 write_all (STDOUT_FILENO, pty_buffer, bytes);
554 else if (FD_ISSET (subshell_pipe[READ], &read_set))
555 /* Read the subshell's CWD and capture its prompt */
557 bytes = read (subshell_pipe[READ], subshell_cwd, MC_MAXPATHLEN + 1);
558 if (bytes <= 0)
560 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
561 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
562 unix_error_string (errno));
563 exit (EXIT_FAILURE);
566 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
568 synchronize ();
570 subshell_ready = TRUE;
571 if (subshell_state == RUNNING_COMMAND)
573 subshell_state = INACTIVE;
574 return TRUE;
578 else if (FD_ISSET (STDIN_FILENO, &read_set))
579 /* Read from stdin, write to the subshell */
581 bytes = read (STDIN_FILENO, pty_buffer, sizeof (pty_buffer));
582 if (bytes <= 0)
584 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
585 fprintf (stderr,
586 "read (STDIN_FILENO, pty_buffer...): %s\r\n", unix_error_string (errno));
587 exit (EXIT_FAILURE);
590 for (i = 0; i < bytes; ++i)
591 if (pty_buffer[i] == subshell_switch_key)
593 write_all (subshell_pty, pty_buffer, i);
594 if (subshell_ready)
595 subshell_state = INACTIVE;
596 return TRUE;
599 write_all (subshell_pty, pty_buffer, bytes);
601 if (pty_buffer[bytes - 1] == '\n' || pty_buffer[bytes - 1] == '\r')
602 subshell_ready = FALSE;
604 else
605 return FALSE;
609 /* --------------------------------------------------------------------------------------------- */
610 /* pty opening functions */
612 #ifdef HAVE_GRANTPT
614 /* System V version of pty_open_master */
615 static int
616 pty_open_master (char *pty_name)
618 char *slave_name;
619 int pty_master;
621 #ifdef HAVE_POSIX_OPENPT
622 pty_master = posix_openpt (O_RDWR);
623 #elif HAVE_GETPT
624 /* getpt () is a GNU extension (glibc 2.1.x) */
625 pty_master = getpt ();
626 #elif IS_AIX
627 strcpy (pty_name, "/dev/ptc");
628 pty_master = open (pty_name, O_RDWR);
629 #else
630 strcpy (pty_name, "/dev/ptmx");
631 pty_master = open (pty_name, O_RDWR);
632 #endif
634 if (pty_master == -1)
635 return -1;
637 if (grantpt (pty_master) == -1 /* Grant access to slave */
638 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
639 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
641 close (pty_master);
642 return -1;
644 strcpy (pty_name, slave_name);
645 return pty_master;
648 /* --------------------------------------------------------------------------------------------- */
650 /** System V version of pty_open_slave */
651 static int
652 pty_open_slave (const char *pty_name)
654 int pty_slave = open (pty_name, O_RDWR);
656 if (pty_slave == -1)
658 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name, unix_error_string (errno));
659 return -1;
661 #if !defined(__osf__) && !defined(__linux__)
662 #if defined (I_FIND) && defined (I_PUSH)
663 if (!ioctl (pty_slave, I_FIND, "ptem"))
664 if (ioctl (pty_slave, I_PUSH, "ptem") == -1)
666 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
667 pty_slave, unix_error_string (errno));
668 close (pty_slave);
669 return -1;
672 if (!ioctl (pty_slave, I_FIND, "ldterm"))
673 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1)
675 fprintf (stderr,
676 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
677 pty_slave, unix_error_string (errno));
678 close (pty_slave);
679 return -1;
681 #if !defined(sgi) && !defined(__sgi)
682 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
683 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1)
685 fprintf (stderr,
686 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
687 pty_slave, unix_error_string (errno));
688 close (pty_slave);
689 return -1;
691 #endif /* sgi || __sgi */
692 #endif /* I_FIND && I_PUSH */
693 #endif /* __osf__ || __linux__ */
695 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
696 return pty_slave;
699 #else /* !HAVE_GRANTPT */
701 /* --------------------------------------------------------------------------------------------- */
703 /** BSD version of pty_open_master */
704 static int
705 pty_open_master (char *pty_name)
707 int pty_master;
708 const char *ptr1, *ptr2;
710 strcpy (pty_name, "/dev/ptyXX");
711 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
713 pty_name[8] = *ptr1;
714 for (ptr2 = "0123456789abcdef"; *ptr2 != '\0'; ++ptr2)
716 pty_name[9] = *ptr2;
718 /* Try to open master */
719 pty_master = open (pty_name, O_RDWR);
720 if (pty_master == -1)
722 if (errno == ENOENT) /* Different from EIO */
723 return -1; /* Out of pty devices */
724 continue; /* Try next pty device */
726 pty_name[5] = 't'; /* Change "pty" to "tty" */
727 if (access (pty_name, 6) != 0)
729 close (pty_master);
730 pty_name[5] = 'p';
731 continue;
733 return pty_master;
736 return -1; /* Ran out of pty devices */
739 /* --------------------------------------------------------------------------------------------- */
741 /** BSD version of pty_open_slave */
742 static int
743 pty_open_slave (const char *pty_name)
745 int pty_slave;
746 struct group *group_info = getgrnam ("tty");
748 if (group_info != NULL)
750 /* The following two calls will only succeed if we are root */
751 /* [Commented out while permissions problem is investigated] */
752 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
753 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
755 pty_slave = open (pty_name, O_RDWR);
756 if (pty_slave == -1)
757 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
758 fcntl (pty_slave, F_SETFD, FD_CLOEXEC);
759 return pty_slave;
761 #endif /* !HAVE_GRANTPT */
762 /* --------------------------------------------------------------------------------------------- */
763 /*** public functions ****************************************************************************/
764 /* --------------------------------------------------------------------------------------------- */
766 /* --------------------------------------------------------------------------------------------- */
768 * Fork the subshell, and set up many, many things.
770 * Possibly modifies the global variables:
771 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
772 * use_subshell - Is set to FALSE if we can't run the subshell
773 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
776 void
777 init_subshell (void)
779 /* This must be remembered across calls to init_subshell() */
780 static char pty_name[BUF_SMALL];
781 char precmd[BUF_SMALL];
783 switch (check_sid ())
785 case 1:
786 use_subshell = FALSE;
787 return;
788 case 2:
789 use_subshell = FALSE;
790 midnight_shutdown = 1;
791 return;
794 /* Take the current (hopefully pristine) tty mode and make */
795 /* a raw mode based on it now, before we do anything else with it */
796 init_raw_mode ();
798 if (subshell_pty == 0)
799 { /* First time through */
800 /* Find out what type of shell we have */
802 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
803 subshell_type = ZSH;
804 else if (strstr (shell, "/tcsh"))
805 subshell_type = TCSH;
806 else if (strstr (shell, "/csh"))
807 subshell_type = TCSH;
808 else if (strstr (shell, "/bash") || getenv ("BASH"))
809 subshell_type = BASH;
810 else if (strstr (shell, "/fish"))
811 subshell_type = FISH;
812 else
814 use_subshell = FALSE;
815 return;
818 /* Open a pty for talking to the subshell */
820 /* FIXME: We may need to open a fresh pty each time on SVR4 */
822 subshell_pty = pty_open_master (pty_name);
823 if (subshell_pty == -1)
825 fprintf (stderr, "Cannot open master side of pty: %s\r\n", unix_error_string (errno));
826 use_subshell = FALSE;
827 return;
829 subshell_pty_slave = pty_open_slave (pty_name);
830 if (subshell_pty_slave == -1)
832 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
833 pty_name, unix_error_string (errno));
834 use_subshell = FALSE;
835 return;
838 /* Create a pipe for receiving the subshell's CWD */
840 if (subshell_type == TCSH)
842 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
843 mc_tmpdir (), (int) getpid ());
844 if (mkfifo (tcsh_fifo, 0600) == -1)
846 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo, unix_error_string (errno));
847 use_subshell = FALSE;
848 return;
851 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
853 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
854 || (subshell_pipe[WRITE] = open (tcsh_fifo, O_RDWR)) == -1)
856 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
857 perror (__FILE__ ": open");
858 use_subshell = FALSE;
859 return;
862 else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe))
864 perror (__FILE__ ": couldn't create pipe");
865 use_subshell = FALSE;
866 return;
870 /* Fork the subshell */
872 subshell_alive = TRUE;
873 subshell_stopped = FALSE;
874 subshell_pid = fork ();
876 if (subshell_pid == -1)
878 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n", unix_error_string (errno));
879 /* We exit here because, if the process table is full, the */
880 /* other method of running user commands won't work either */
881 exit (EXIT_FAILURE);
884 if (subshell_pid == 0)
886 /* We are in the child process */
887 init_subshell_child (pty_name);
890 /* Set up `precmd' or equivalent for reading the subshell's CWD */
892 switch (subshell_type)
894 case BASH:
895 g_snprintf (precmd, sizeof (precmd),
896 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n", subshell_pipe[WRITE]);
897 break;
899 case ZSH:
900 g_snprintf (precmd, sizeof (precmd),
901 " precmd(){ pwd>&%d;kill -STOP $$ }\n", subshell_pipe[WRITE]);
902 break;
904 case TCSH:
905 g_snprintf (precmd, sizeof (precmd),
906 "set echo_style=both;"
907 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n", tcsh_fifo);
908 break;
909 case FISH:
910 g_snprintf (precmd, sizeof (precmd),
911 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
912 subshell_pipe[WRITE]);
913 break;
916 write_all (subshell_pty, precmd, strlen (precmd));
918 /* Wait until the subshell has started up and processed the command */
920 subshell_state = RUNNING_COMMAND;
921 tty_enable_interrupt_key ();
922 if (!feed_subshell (QUIETLY, TRUE))
924 use_subshell = FALSE;
926 tty_disable_interrupt_key ();
927 if (!subshell_alive)
928 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
931 /* --------------------------------------------------------------------------------------------- */
934 invoke_subshell (const char *command, int how, char **new_dir)
936 char *pcwd;
938 /* Make the MC terminal transparent */
939 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
941 /* Make the subshell change to MC's working directory */
942 if (new_dir != NULL)
943 do_subshell_chdir (current_panel->cwd, TRUE, TRUE);
945 if (command == NULL) /* The user has done "C-o" from MC */
947 if (subshell_state == INACTIVE)
949 subshell_state = ACTIVE;
950 /* FIXME: possibly take out this hack; the user can
951 re-play it by hitting C-hyphen a few times! */
952 if (subshell_ready)
953 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
956 else /* MC has passed us a user command */
958 if (how == QUIETLY)
959 write_all (subshell_pty, " ", 1);
960 /* FIXME: if command is long (>8KB ?) we go comma */
961 write_all (subshell_pty, command, strlen (command));
962 write_all (subshell_pty, "\n", 1);
963 subshell_state = RUNNING_COMMAND;
964 subshell_ready = FALSE;
967 feed_subshell (how, FALSE);
969 pcwd = vfs_translate_path_n (current_panel->cwd);
970 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
971 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
972 g_free (pcwd);
974 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
975 while (!subshell_alive && quit == 0 && use_subshell)
976 init_subshell ();
978 prompt_pos = 0;
980 return quit;
984 /* --------------------------------------------------------------------------------------------- */
987 read_subshell_prompt (void)
989 static int prompt_size = INITIAL_PROMPT_SIZE;
990 int bytes = 0, i, rc = 0;
991 struct timeval timeleft = { 0, 0 };
993 fd_set tmp;
994 FD_ZERO (&tmp);
995 FD_SET (subshell_pty, &tmp);
997 if (subshell_prompt == NULL)
998 { /* First time through */
999 subshell_prompt = g_malloc (prompt_size);
1000 *subshell_prompt = '\0';
1001 prompt_pos = 0;
1004 while (subshell_alive && (rc = select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft)))
1006 /* Check for `select' errors */
1007 if (rc == -1)
1009 if (errno == EINTR)
1010 continue;
1011 else
1013 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n", unix_error_string (errno));
1014 exit (EXIT_FAILURE);
1018 bytes = read (subshell_pty, pty_buffer, sizeof (pty_buffer));
1020 /* Extract the prompt from the shell output */
1022 for (i = 0; i < bytes; ++i)
1023 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r')
1025 prompt_pos = 0;
1027 else
1029 if (!pty_buffer[i])
1030 continue;
1032 subshell_prompt[prompt_pos++] = pty_buffer[i];
1033 if (prompt_pos == prompt_size)
1034 subshell_prompt = g_realloc (subshell_prompt, prompt_size *= 2);
1037 subshell_prompt[prompt_pos] = '\0';
1039 if (rc == 0 && bytes == 0)
1040 return FALSE;
1041 return TRUE;
1044 /* --------------------------------------------------------------------------------------------- */
1046 void
1047 do_update_prompt (void)
1049 if (update_subshell_prompt)
1051 printf ("\r\n%s", subshell_prompt);
1052 fflush (stdout);
1053 update_subshell_prompt = FALSE;
1057 /* --------------------------------------------------------------------------------------------- */
1058 /** Resize subshell_pty */
1060 void
1061 resize_subshell (void)
1063 if (use_subshell != 0)
1064 resize_tty (subshell_pty);
1067 /* --------------------------------------------------------------------------------------------- */
1070 exit_subshell (void)
1072 int subshell_quit = TRUE;
1074 if (subshell_state != INACTIVE && subshell_alive)
1075 subshell_quit =
1076 !query_dialog (_("Warning"),
1077 _("The shell is still active. Quit anyway?"),
1078 D_NORMAL, 2, _("&Yes"), _("&No"));
1080 if (subshell_quit)
1082 if (subshell_type == TCSH)
1084 if (unlink (tcsh_fifo) == -1)
1085 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
1086 tcsh_fifo, unix_error_string (errno));
1089 g_free (subshell_prompt);
1090 subshell_prompt = NULL;
1091 pty_buffer[0] = '\0';
1094 return subshell_quit;
1098 /* --------------------------------------------------------------------------------------------- */
1100 * Carefully quote directory name to allow entering any directory safely,
1101 * no matter what weird characters it may contain in its name.
1102 * NOTE: Treat directory name an untrusted data, don't allow it to cause
1103 * executing any commands in the shell. Escape all control characters.
1104 * Use following technique:
1106 * printf(1) with format string containing a single conversion specifier,
1107 * "b", and an argument which contains a copy of the string passed to
1108 * subshell_name_quote() with all characters, except digits and letters,
1109 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
1110 * numeric value of the character converted to octal number.
1112 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
1116 static char *
1117 subshell_name_quote (const char *s)
1119 char *ret, *d;
1120 const char *su, *n;
1121 const char *quote_cmd_start, *quote_cmd_end;
1122 int c;
1124 if (subshell_type == FISH)
1126 quote_cmd_start = "(printf \"%b\" '";
1127 quote_cmd_end = "')";
1129 else
1131 quote_cmd_start = "\"`printf \"%b\" '";
1132 quote_cmd_end = "'`\"";
1135 /* Factor 5 because we need \, 0 and 3 other digits per character. */
1136 d = ret = g_try_malloc (1 + (5 * strlen (s)) + (strlen (quote_cmd_start))
1137 + (strlen (quote_cmd_end)));
1138 if (d == NULL)
1139 return NULL;
1141 /* Prevent interpreting leading `-' as a switch for `cd' */
1142 if (*s == '-')
1144 *d++ = '.';
1145 *d++ = '/';
1148 /* Copy the beginning of the command to the buffer */
1149 strcpy (d, quote_cmd_start);
1150 d += strlen (quote_cmd_start);
1153 * Print every character except digits and letters as a backslash-escape
1154 * sequence of the form \0nnn, where "nnn" is the numeric value of the
1155 * character converted to octal number.
1157 su = s;
1158 for (; su[0] != '\0';)
1160 n = str_cget_next_char_safe (su);
1161 if (str_isalnum (su))
1163 memcpy (d, su, n - su);
1164 d += n - su;
1166 else
1168 for (c = 0; c < n - su; c++)
1170 sprintf (d, "\\0%03o", (unsigned char) su[c]);
1171 d += 5;
1174 su = n;
1177 strcpy (d, quote_cmd_end);
1179 return ret;
1183 /* --------------------------------------------------------------------------------------------- */
1185 /** If it actually changed the directory it returns true */
1186 void
1187 do_subshell_chdir (const char *directory, gboolean update_prompt, gboolean reset_prompt)
1189 char *pcwd;
1190 char *temp;
1191 char *translate;
1193 pcwd = vfs_translate_path_n (current_panel->cwd);
1195 if (!(subshell_state == INACTIVE && strcmp (subshell_cwd, pcwd) != 0))
1197 /* We have to repaint the subshell prompt if we read it from
1198 * the main program. Please note that in the code after this
1199 * if, the cd command that is sent will make the subshell
1200 * repaint the prompt, so we don't have to paint it. */
1201 if (update_prompt)
1202 do_update_prompt ();
1203 g_free (pcwd);
1204 return;
1207 /* The initial space keeps this out of the command history (in bash
1208 because we set "HISTCONTROL=ignorespace") */
1209 write_all (subshell_pty, " cd ", 4);
1210 if (*directory)
1212 translate = vfs_translate_path_n (directory);
1213 if (translate)
1215 temp = subshell_name_quote (translate);
1216 if (temp)
1218 write_all (subshell_pty, temp, strlen (temp));
1219 g_free (temp);
1221 else
1223 /* Should not happen unless the directory name is so long
1224 that we don't have memory to quote it. */
1225 write_all (subshell_pty, ".", 1);
1227 g_free (translate);
1229 else
1231 write_all (subshell_pty, ".", 1);
1234 else
1236 write_all (subshell_pty, "/", 1);
1238 write_all (subshell_pty, "\n", 1);
1240 subshell_state = RUNNING_COMMAND;
1241 feed_subshell (QUIETLY, FALSE);
1243 if (subshell_alive)
1245 int bPathNotEq = strcmp (subshell_cwd, pcwd);
1247 if (bPathNotEq && subshell_type == TCSH)
1249 char rp_subshell_cwd[PATH_MAX];
1250 char rp_current_panel_cwd[PATH_MAX];
1252 char *p_subshell_cwd = mc_realpath (subshell_cwd, rp_subshell_cwd);
1253 char *p_current_panel_cwd = mc_realpath (pcwd, rp_current_panel_cwd);
1255 if (p_subshell_cwd == NULL)
1256 p_subshell_cwd = subshell_cwd;
1257 if (p_current_panel_cwd == NULL)
1258 p_current_panel_cwd = pcwd;
1259 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
1262 if (bPathNotEq && strcmp (pcwd, "."))
1264 char *cwd = strip_password (g_strdup (pcwd), 1);
1265 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
1266 g_free (cwd);
1270 if (reset_prompt)
1271 prompt_pos = 0;
1272 update_subshell_prompt = FALSE;
1274 g_free (pcwd);
1275 /* Make sure that MC never stores the CWD in a silly format */
1276 /* like /usr////lib/../bin, or the strcmp() above will fail */
1279 /* --------------------------------------------------------------------------------------------- */
1281 void
1282 subshell_get_console_attributes (void)
1284 /* Get our current terminal modes */
1286 if (tcgetattr (STDOUT_FILENO, &shell_mode))
1288 fprintf (stderr, "Cannot get terminal settings: %s\r\n", unix_error_string (errno));
1289 use_subshell = FALSE;
1290 return;
1294 /* --------------------------------------------------------------------------------------------- */
1296 * Figure out whether the subshell has stopped, exited or been killed
1297 * Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
1299 void
1300 sigchld_handler (int sig)
1302 int status;
1303 pid_t pid;
1305 (void) sig;
1307 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
1309 if (pid == subshell_pid)
1311 /* Figure out what has happened to the subshell */
1313 if (WIFSTOPPED (status))
1315 if (WSTOPSIG (status) == SIGSTOP)
1317 /* The subshell has received a SIGSTOP signal */
1318 subshell_stopped = TRUE;
1320 else
1322 /* The user has suspended the subshell. Revive it */
1323 kill (subshell_pid, SIGCONT);
1326 else
1328 /* The subshell has either exited normally or been killed */
1329 subshell_alive = FALSE;
1330 delete_select_channel (subshell_pty);
1331 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
1332 quit |= SUBSHELL_EXIT; /* Exited normally */
1335 #ifdef __linux__
1336 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
1338 if (pid == cons_saver_pid)
1341 if (WIFSTOPPED (status))
1342 /* Someone has stopped cons.saver - restart it */
1343 kill (pid, SIGCONT);
1344 else
1346 /* cons.saver has died - disable confole saving */
1347 handle_console (CONSOLE_DONE);
1348 console_flag = 0;
1352 #endif /* __linux__ */
1354 /* If we got here, some other child exited; ignore it */
1357 /* --------------------------------------------------------------------------------------------- */
1359 #endif /* HAVE_SUBSHELL_SUPPORT */