Ticket #267 (etags incorrect get the line number definition)
[midnight-commander.git] / src / subshell.c
blob120bd99a18e94f86e97649260592db29ae99499f
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 #ifdef HAVE_TERMIOS_H
44 #include <termios.h>
45 #endif
46 #include <unistd.h>
48 #ifdef HAVE_STROPTS_H
49 # include <stropts.h> /* For I_PUSH */
50 #endif /* HAVE_STROPTS_H */
52 #include "global.h"
53 #include "../src/tty/tty.h" /* LINES */
54 #include "panel.h" /* current_panel */
55 #include "wtools.h" /* query_dialog() */
56 #include "main.h" /* do_update_prompt() */
57 #include "cons.saver.h" /* handle_console() */
58 #include "../src/tty/key.h" /* XCTRL */
59 #include "subshell.h"
60 #include "strutil.h"
62 #ifndef WEXITSTATUS
63 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
64 #endif
66 #ifndef WIFEXITED
67 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
68 #endif
70 /* tcsh closes all non-standard file descriptors, so we have to use a pipe */
71 static char tcsh_fifo[128];
73 /* Local functions */
74 static void init_raw_mode (void);
75 static int feed_subshell (int how, int fail_on_error);
76 static void synchronize (void);
77 static int pty_open_master (char *pty_name);
78 static int pty_open_slave (const char *pty_name);
79 static int resize_tty (int fd);
81 #ifndef STDIN_FILENO
82 # define STDIN_FILENO 0
83 #endif
85 #ifndef STDOUT_FILENO
86 # define STDOUT_FILENO 1
87 #endif
89 #ifndef STDERR_FILENO
90 # define STDERR_FILENO 2
91 #endif
93 /* If using a subshell for evaluating commands this is true */
94 int use_subshell =
95 #ifdef SUBSHELL_OPTIONAL
96 FALSE;
97 #else
98 TRUE;
99 #endif
101 /* File descriptors of the pseudoterminal used by the subshell */
102 int subshell_pty = 0;
103 static int subshell_pty_slave = -1;
105 /* The key for switching back to MC from the subshell */
106 static const char subshell_switch_key = XCTRL('o') & 255;
108 /* State of the subshell:
109 * INACTIVE: the default state; awaiting a command
110 * ACTIVE: remain in the shell until the user hits `subshell_switch_key'
111 * RUNNING_COMMAND: return to MC when the current command finishes */
112 enum subshell_state_enum subshell_state;
114 /* Holds the latest prompt captured from the subshell */
115 char *subshell_prompt = NULL;
117 /* Initial length of the buffer for the subshell's prompt */
118 #define INITIAL_PROMPT_SIZE 10
120 /* Used by the child process to indicate failure to start the subshell */
121 #define FORK_FAILURE 69 /* Arbitrary */
123 /* Initial length of the buffer for all I/O with the subshell */
124 #define INITIAL_PTY_BUFFER_SIZE 100 /* Arbitrary; but keep it >= 80 */
126 /* For pipes */
127 enum {READ=0, WRITE=1};
129 static char *pty_buffer; /* For reading/writing on the subshell's pty */
130 static int pty_buffer_size; /* The buffer grows as needed */
131 static int subshell_pipe[2]; /* To pass CWD info from the subshell to MC */
132 static pid_t subshell_pid = 1; /* The subshell's process ID */
133 static char subshell_cwd[MC_MAXPATHLEN+1]; /* One extra char for final '\n' */
135 /* Subshell type (gleaned from the SHELL environment variable, if available) */
136 static enum {
137 BASH,
138 TCSH,
139 ZSH,
140 FISH
141 } subshell_type;
143 /* Flag to indicate whether the subshell is ready for next command */
144 static int subshell_ready;
146 /* The following two flags can be changed by the SIGCHLD handler. This is */
147 /* OK, because the `int' type is updated atomically on all known machines */
148 static volatile int subshell_alive, subshell_stopped;
150 /* We store the terminal's initial mode here so that we can configure
151 the pty similarly, and also so we can restore the real terminal to
152 sanity if we have to exit abruptly */
153 static struct termios shell_mode;
155 /* This is a transparent mode for the terminal where MC is running on */
156 /* It is used when the shell is active, so that the control signals */
157 /* are delivered to the shell pty */
158 static struct termios raw_mode;
160 /* This counter indicates how many characters of prompt we have read */
161 /* FIXME: try to figure out why this had to become global */
162 static int prompt_pos;
166 * Write all data, even if the write() call is interrupted.
168 static ssize_t
169 write_all (int fd, const void *buf, size_t count)
171 ssize_t ret;
172 ssize_t written = 0;
173 while (count > 0) {
174 ret = write (fd, (const unsigned char *) buf + written, count);
175 if (ret < 0) {
176 if (errno == EINTR) {
177 continue;
178 } else {
179 return written > 0 ? written : ret;
182 count -= ret;
183 written += ret;
185 return written;
189 * Prepare child process to running the shell and run it.
191 * Modifies the global variables (in the child process only):
192 * shell_mode
194 * Returns: never.
196 static void
197 init_subshell_child (const char *pty_name)
199 const char *init_file = NULL;
200 #ifdef HAVE_GETSID
201 pid_t mc_sid;
202 #endif /* HAVE_GETSID */
204 (void) pty_name;
205 setsid (); /* Get a fresh terminal session */
207 /* Make sure that it has become our controlling terminal */
209 /* Redundant on Linux and probably most systems, but just in case: */
211 #ifdef TIOCSCTTY
212 ioctl (subshell_pty_slave, TIOCSCTTY, 0);
213 #endif
215 /* Configure its terminal modes and window size */
217 /* Set up the pty with the same termios flags as our own tty, plus */
218 /* TOSTOP, which keeps background processes from writing to the pty */
220 shell_mode.c_lflag |= TOSTOP; /* So background writers get SIGTTOU */
221 if (tcsetattr (subshell_pty_slave, TCSANOW, &shell_mode)) {
222 fprintf (stderr, "Cannot set pty terminal modes: %s\r\n",
223 unix_error_string (errno));
224 _exit (FORK_FAILURE);
227 /* Set the pty's size (80x25 by default on Linux) according to the */
228 /* size of the real terminal as calculated by ncurses, if possible */
229 resize_tty (subshell_pty_slave);
231 /* Set up the subshell's environment and init file name */
233 /* It simplifies things to change to our home directory here, */
234 /* and the user's startup file may do a `cd' command anyway */
235 chdir (home_dir); /* FIXME? What about when we re-run the subshell? */
237 #ifdef HAVE_GETSID
238 /* Set MC_SID to prevent running one mc from another */
239 mc_sid = getsid (0);
240 if (mc_sid != -1) {
241 char sid_str[BUF_SMALL];
242 g_snprintf (sid_str, sizeof (sid_str), "MC_SID=%ld",
243 (long) mc_sid);
244 putenv (g_strdup (sid_str));
246 #endif /* HAVE_GETSID */
248 switch (subshell_type) {
249 case BASH:
250 init_file = ".mc/bashrc";
251 if (access (init_file, R_OK) == -1)
252 init_file = ".bashrc";
254 /* Make MC's special commands not show up in bash's history */
255 putenv ((char*)"HISTCONTROL=ignorespace");
257 /* Allow alternative readline settings for MC */
258 if (access (".mc/inputrc", R_OK) == 0)
259 putenv ((char*)"INPUTRC=.mc/inputrc");
261 break;
263 /* TODO: Find a way to pass initfile to TCSH and ZSH */
264 case TCSH:
265 case ZSH:
266 case FISH:
267 break;
269 default:
270 fprintf (stderr, __FILE__ ": unimplemented subshell type %d\r\n",
271 subshell_type);
272 _exit (FORK_FAILURE);
275 /* Attach all our standard file descriptors to the pty */
277 /* This is done just before the fork, because stderr must still */
278 /* be connected to the real tty during the above error messages; */
279 /* otherwise the user will never see them. */
281 dup2 (subshell_pty_slave, STDIN_FILENO);
282 dup2 (subshell_pty_slave, STDOUT_FILENO);
283 dup2 (subshell_pty_slave, STDERR_FILENO);
285 close (subshell_pipe[READ]);
286 close (subshell_pty_slave); /* These may be FD_CLOEXEC, but just in case... */
287 /* Close master side of pty. This is important; apart from */
288 /* freeing up the descriptor for use in the subshell, it also */
289 /* means that when MC exits, the subshell will get a SIGHUP and */
290 /* exit too, because there will be no more descriptors pointing */
291 /* at the master side of the pty and so it will disappear. */
292 close (subshell_pty);
294 /* Execute the subshell at last */
296 switch (subshell_type) {
297 case BASH:
298 execl (shell, "bash", "-rcfile", init_file, (char *) NULL);
299 break;
301 case TCSH:
302 execl (shell, "tcsh", (char *) NULL);
303 break;
305 case ZSH:
306 /* Use -g to exclude cmds beginning with space from history
307 * and -Z to use the line editor on non-interactive term */
308 execl (shell, "zsh", "-Z", "-g", (char *) NULL);
310 break;
312 case FISH:
313 execl (shell, "fish", (char *) NULL);
314 break;
317 /* If we get this far, everything failed miserably */
318 _exit (FORK_FAILURE);
322 #ifdef HAVE_GETSID
324 * Check MC_SID to prevent running one mc from another.
325 * Return:
326 * 0 if no parent mc in our session was found,
327 * 1 if parent mc was found and the user wants to continue,
328 * 2 if parent mc was found and the user wants to quit mc.
330 static int
331 check_sid (void)
333 pid_t my_sid, old_sid;
334 const char *sid_str;
335 int r;
337 sid_str = getenv ("MC_SID");
338 if (!sid_str)
339 return 0;
341 old_sid = (pid_t) strtol (sid_str, NULL, 0);
342 if (!old_sid)
343 return 0;
345 my_sid = getsid (0);
346 if (my_sid == -1)
347 return 0;
349 /* The parent mc is in a different session, it's OK */
350 if (old_sid != my_sid)
351 return 0;
353 r = query_dialog (_("Warning"),
354 _("GNU Midnight Commander is already\n"
355 "running on this terminal.\n"
356 "Subshell support will be disabled."), D_ERROR, 2,
357 _("&OK"), _("&Quit"));
358 if (r != 0) {
359 return 2;
362 return 1;
364 #endif /* HAVE_GETSID */
368 * Fork the subshell, and set up many, many things.
370 * Possibly modifies the global variables:
371 * subshell_type, subshell_alive, subshell_stopped, subshell_pid
372 * use_subshell - Is set to FALSE if we can't run the subshell
373 * quit - Can be set to SUBSHELL_EXIT by the SIGCHLD handler
376 void
377 init_subshell (void)
379 /* This must be remembered across calls to init_subshell() */
380 static char pty_name[BUF_SMALL];
381 char precmd[BUF_SMALL];
383 #ifdef HAVE_GETSID
384 switch (check_sid ()) {
385 case 1:
386 use_subshell = FALSE;
387 return;
388 case 2:
389 use_subshell = FALSE;
390 midnight_shutdown = 1;
391 return;
393 #endif /* HAVE_GETSID */
395 /* Take the current (hopefully pristine) tty mode and make */
396 /* a raw mode based on it now, before we do anything else with it */
397 init_raw_mode ();
399 if (subshell_pty == 0) { /* First time through */
400 /* Find out what type of shell we have */
402 if (strstr (shell, "/zsh") || getenv ("ZSH_VERSION"))
403 subshell_type = ZSH;
404 else if (strstr (shell, "/tcsh"))
405 subshell_type = TCSH;
406 else if (strstr (shell, "/csh"))
407 subshell_type = TCSH;
408 else if (strstr (shell, "/bash") || getenv ("BASH"))
409 subshell_type = BASH;
410 else if (strstr (shell, "/fish"))
411 subshell_type = FISH;
412 else {
413 use_subshell = FALSE;
414 return;
417 /* Open a pty for talking to the subshell */
419 /* FIXME: We may need to open a fresh pty each time on SVR4 */
421 subshell_pty = pty_open_master (pty_name);
422 if (subshell_pty == -1) {
423 fprintf (stderr, "Cannot open master side of pty: %s\r\n",
424 unix_error_string (errno));
425 use_subshell = FALSE;
426 return;
428 subshell_pty_slave = pty_open_slave (pty_name);
429 if (subshell_pty_slave == -1) {
430 fprintf (stderr, "Cannot open slave side of pty %s: %s\r\n",
431 pty_name, unix_error_string (errno));
432 use_subshell = FALSE;
433 return;
436 /* Initialise the pty's I/O buffer */
438 pty_buffer_size = INITIAL_PTY_BUFFER_SIZE;
439 pty_buffer = g_malloc (pty_buffer_size);
441 /* Create a pipe for receiving the subshell's CWD */
443 if (subshell_type == TCSH) {
444 g_snprintf (tcsh_fifo, sizeof (tcsh_fifo), "%s/mc.pipe.%d",
445 mc_tmpdir (), (int) getpid ());
446 if (mkfifo (tcsh_fifo, 0600) == -1) {
447 fprintf (stderr, "mkfifo(%s) failed: %s\r\n", tcsh_fifo,
448 unix_error_string (errno));
449 use_subshell = FALSE;
450 return;
453 /* Opening the FIFO as O_RDONLY or O_WRONLY causes deadlock */
455 if ((subshell_pipe[READ] = open (tcsh_fifo, O_RDWR)) == -1
456 || (subshell_pipe[WRITE] =
457 open (tcsh_fifo, O_RDWR)) == -1) {
458 fprintf (stderr, _("Cannot open named pipe %s\n"), tcsh_fifo);
459 perror (__FILE__": open");
460 use_subshell = FALSE;
461 return;
463 } else /* subshell_type is BASH or ZSH */ if (pipe (subshell_pipe)) {
464 perror (__FILE__": couldn't create pipe");
465 use_subshell = FALSE;
466 return;
470 /* Fork the subshell */
472 subshell_alive = TRUE;
473 subshell_stopped = FALSE;
474 subshell_pid = fork ();
476 if (subshell_pid == -1) {
477 fprintf (stderr, "Cannot spawn the subshell process: %s\r\n",
478 unix_error_string (errno));
479 /* We exit here because, if the process table is full, the */
480 /* other method of running user commands won't work either */
481 exit (1);
484 if (subshell_pid == 0) { /* We are in the child process */
485 init_subshell_child (pty_name);
488 /* Set up `precmd' or equivalent for reading the subshell's CWD */
490 switch (subshell_type) {
491 case BASH:
492 g_snprintf (precmd, sizeof (precmd),
493 " PROMPT_COMMAND='pwd>&%d;kill -STOP $$'\n",
494 subshell_pipe[WRITE]);
495 break;
497 case ZSH:
498 g_snprintf (precmd, sizeof (precmd),
499 " precmd(){ pwd>&%d;kill -STOP $$ }\n",
500 subshell_pipe[WRITE]);
501 break;
503 case TCSH:
504 g_snprintf (precmd, sizeof (precmd),
505 "set echo_style=both;"
506 "alias precmd 'echo $cwd:q >>%s;kill -STOP $$'\n",
507 tcsh_fifo);
508 break;
509 case FISH:
510 g_snprintf (precmd, sizeof (precmd),
511 "function fish_prompt ; pwd>&%d;kill -STOP %%self; end\n",
512 subshell_pipe[WRITE]);
513 break;
516 write_all (subshell_pty, precmd, strlen (precmd));
518 /* Wait until the subshell has started up and processed the command */
520 subshell_state = RUNNING_COMMAND;
521 tty_enable_interrupt_key ();
522 if (!feed_subshell (QUIETLY, TRUE)) {
523 use_subshell = FALSE;
525 tty_disable_interrupt_key ();
526 if (!subshell_alive)
527 use_subshell = FALSE; /* Subshell died instantly, so don't use it */
531 static void init_raw_mode ()
533 static int initialized = 0;
535 /* MC calls tty_reset_shell_mode() in pre_exec() to set the real tty to its */
536 /* original settings. However, here we need to make this tty very raw, */
537 /* so that all keyboard signals, XON/XOFF, etc. will get through to the */
538 /* pty. So, instead of changing the code for execute(), pre_exec(), */
539 /* etc, we just set up the modes we need here, before each command. */
541 if (initialized == 0) /* First time: initialise `raw_mode' */
543 tcgetattr (STDOUT_FILENO, &raw_mode);
544 raw_mode.c_lflag &= ~ICANON; /* Disable line-editing chars, etc. */
545 raw_mode.c_lflag &= ~ISIG; /* Disable intr, quit & suspend chars */
546 raw_mode.c_lflag &= ~ECHO; /* Disable input echoing */
547 raw_mode.c_iflag &= ~IXON; /* Pass ^S/^Q to subshell undisturbed */
548 raw_mode.c_iflag &= ~ICRNL; /* Don't translate CRs into LFs */
549 raw_mode.c_oflag &= ~OPOST; /* Don't postprocess output */
550 raw_mode.c_cc[VTIME] = 0; /* IE: wait forever, and return as */
551 raw_mode.c_cc[VMIN] = 1; /* soon as a character is available */
552 initialized = 1;
557 int invoke_subshell (const char *command, int how, char **new_dir)
559 char *pcwd;
561 /* Make the MC terminal transparent */
562 tcsetattr (STDOUT_FILENO, TCSANOW, &raw_mode);
564 /* Make the subshell change to MC's working directory */
565 if (new_dir)
566 do_subshell_chdir (current_panel->cwd, TRUE, 1);
568 if (command == NULL) /* The user has done "C-o" from MC */
570 if (subshell_state == INACTIVE)
572 subshell_state = ACTIVE;
573 /* FIXME: possibly take out this hack; the user can
574 re-play it by hitting C-hyphen a few times! */
575 write_all (subshell_pty, " \b", 2); /* Hack to make prompt reappear */
578 else /* MC has passed us a user command */
580 if (how == QUIETLY)
581 write_all (subshell_pty, " ", 1);
582 /* FIXME: if command is long (>8KB ?) we go comma */
583 write_all (subshell_pty, command, strlen (command));
584 write_all (subshell_pty, "\n", 1);
585 subshell_state = RUNNING_COMMAND;
586 subshell_ready = FALSE;
589 feed_subshell (how, FALSE);
591 pcwd = vfs_translate_path_n (current_panel->cwd);
592 if (new_dir && subshell_alive && strcmp (subshell_cwd, pcwd))
593 *new_dir = subshell_cwd; /* Make MC change to the subshell's CWD */
594 g_free (pcwd);
596 /* Restart the subshell if it has died by SIGHUP, SIGQUIT, etc. */
597 while (!subshell_alive && !quit && use_subshell)
598 init_subshell ();
600 prompt_pos = 0;
602 return quit;
607 read_subshell_prompt (void)
609 static int prompt_size = INITIAL_PROMPT_SIZE;
610 int bytes = 0, i, rc = 0;
611 struct timeval timeleft = { 0, 0 };
613 fd_set tmp;
614 FD_ZERO (&tmp);
615 FD_SET (subshell_pty, &tmp);
617 if (subshell_prompt == NULL) { /* First time through */
618 subshell_prompt = g_malloc (prompt_size);
619 *subshell_prompt = '\0';
620 prompt_pos = 0;
623 while (subshell_alive
624 && (rc =
625 select (subshell_pty + 1, &tmp, NULL, NULL, &timeleft))) {
626 /* Check for `select' errors */
627 if (rc == -1) {
628 if (errno == EINTR)
629 continue;
630 else {
631 fprintf (stderr, "select (FD_SETSIZE, &tmp...): %s\r\n",
632 unix_error_string (errno));
633 exit (1);
637 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
639 /* Extract the prompt from the shell output */
641 for (i = 0; i < bytes; ++i)
642 if (pty_buffer[i] == '\n' || pty_buffer[i] == '\r') {
643 prompt_pos = 0;
644 } else {
645 if (!pty_buffer[i])
646 continue;
648 subshell_prompt[prompt_pos++] = pty_buffer[i];
649 if (prompt_pos == prompt_size)
650 subshell_prompt =
651 g_realloc (subshell_prompt, prompt_size *= 2);
654 subshell_prompt[prompt_pos] = '\0';
656 if (rc == 0 && bytes == 0)
657 return FALSE;
658 return TRUE;
661 /* Resize given terminal using TIOCSWINSZ, return ioctl() result */
662 static int resize_tty (int fd)
664 #if defined TIOCSWINSZ
665 struct winsize tty_size;
667 tty_size.ws_row = LINES;
668 tty_size.ws_col = COLS;
669 tty_size.ws_xpixel = tty_size.ws_ypixel = 0;
671 return ioctl (fd, TIOCSWINSZ, &tty_size);
672 #else
673 return 0;
674 #endif
677 /* Resize subshell_pty */
678 void resize_subshell (void)
680 if (use_subshell == 0)
681 return;
683 resize_tty (subshell_pty);
687 exit_subshell (void)
689 int subshell_quit = TRUE;
691 if (subshell_state != INACTIVE && subshell_alive)
692 subshell_quit =
693 !query_dialog (_("Warning"),
694 _(" The shell is still active. Quit anyway? "),
695 D_NORMAL, 2, _("&Yes"), _("&No"));
697 if (subshell_quit) {
698 if (subshell_type == TCSH) {
699 if (unlink (tcsh_fifo) == -1)
700 fprintf (stderr, "Cannot remove named pipe %s: %s\r\n",
701 tcsh_fifo, unix_error_string (errno));
704 g_free (subshell_prompt);
705 g_free (pty_buffer);
706 subshell_prompt = NULL;
707 pty_buffer = NULL;
710 return subshell_quit;
715 * Carefully quote directory name to allow entering any directory safely,
716 * no matter what weird characters it may contain in its name.
717 * NOTE: Treat directory name an untrusted data, don't allow it to cause
718 * executing any commands in the shell. Escape all control characters.
719 * Use following technique:
721 * printf(1) with format string containing a single conversion specifier,
722 * "b", and an argument which contains a copy of the string passed to
723 * subshell_name_quote() with all characters, except digits and letters,
724 * replaced by the backslash-escape sequence \0nnn, where "nnn" is the
725 * numeric value of the character converted to octal number.
727 * cd "`printf "%b" 'ABC\0nnnDEF\0nnnXYZ'`"
730 static char *
731 subshell_name_quote (const char *s)
733 char *ret, *d;
734 const char *su, *n;
735 const char *quote_cmd_start, *quote_cmd_end;
736 int c;
738 if (subshell_type == FISH) {
739 quote_cmd_start = "(printf \"%b\" '";
740 quote_cmd_end = "')";
741 } else {
742 quote_cmd_start = "\"`printf \"%b\" '";
743 quote_cmd_end = "'`\"";
746 /* Factor 5 because we need \, 0 and 3 other digits per character. */
747 d = ret = g_malloc (1 + (5 * strlen (s)) + (strlen(quote_cmd_start))
748 + (strlen(quote_cmd_end)));
749 if (!d)
750 return NULL;
752 /* Prevent interpreting leading `-' as a switch for `cd' */
753 if (*s == '-') {
754 *d++ = '.';
755 *d++ = '/';
758 /* Copy the beginning of the command to the buffer */
759 strcpy (d, quote_cmd_start);
760 d += strlen(quote_cmd_start);
763 * Print every character except digits and letters as a backslash-escape
764 * sequence of the form \0nnn, where "nnn" is the numeric value of the
765 * character converted to octal number.
767 su = s;
768 for (; su[0] != '\0'; ) {
769 n = str_cget_next_char_safe (su);
770 if (str_isalnum (su)) {
771 memcpy (d, su, n - su);
772 d+= n - su;
773 } else {
774 for (c = 0; c < n - su; c++) {
775 sprintf (d, "\\0%03o", (unsigned char) su[c]);
776 d += 5;
779 su = n;
782 strcpy (d, quote_cmd_end);
784 return ret;
788 /* If it actually changed the directory it returns true */
789 void
790 do_subshell_chdir (const char *directory, int do_update, int reset_prompt)
792 char *pcwd;
793 char *temp;
794 char *translate;
796 pcwd = vfs_translate_path_n (current_panel->cwd);
798 if (!
799 (subshell_state == INACTIVE
800 && strcmp (subshell_cwd, pcwd))) {
801 /* We have to repaint the subshell prompt if we read it from
802 * the main program. Please note that in the code after this
803 * if, the cd command that is sent will make the subshell
804 * repaint the prompt, so we don't have to paint it. */
805 if (do_update)
806 do_update_prompt ();
807 g_free (pcwd);
808 return;
811 /* The initial space keeps this out of the command history (in bash
812 because we set "HISTCONTROL=ignorespace") */
813 write_all (subshell_pty, " cd ", 4);
814 if (*directory) {
815 translate = vfs_translate_path_n (directory);
816 if (translate) {
817 temp = subshell_name_quote (translate);
818 if (temp) {
819 write_all (subshell_pty, temp, strlen (temp));
820 g_free (temp);
821 } else {
822 /* Should not happen unless the directory name is so long
823 that we don't have memory to quote it. */
824 write_all (subshell_pty, ".", 1);
826 g_free (translate);
827 } else {
828 write_all (subshell_pty, ".", 1);
830 } else {
831 write_all (subshell_pty, "/", 1);
833 write_all (subshell_pty, "\n", 1);
835 subshell_state = RUNNING_COMMAND;
836 feed_subshell (QUIETLY, FALSE);
838 if (subshell_alive) {
839 int bPathNotEq = strcmp (subshell_cwd, pcwd);
841 if (bPathNotEq && subshell_type == TCSH) {
842 char rp_subshell_cwd[PATH_MAX];
843 char rp_current_panel_cwd[PATH_MAX];
845 char *p_subshell_cwd =
846 mc_realpath (subshell_cwd, rp_subshell_cwd);
847 char *p_current_panel_cwd =
848 mc_realpath (pcwd, rp_current_panel_cwd);
850 if (p_subshell_cwd == NULL)
851 p_subshell_cwd = subshell_cwd;
852 if (p_current_panel_cwd == NULL)
853 p_current_panel_cwd = pcwd;
854 bPathNotEq = strcmp (p_subshell_cwd, p_current_panel_cwd);
857 if (bPathNotEq && strcmp (pcwd, ".")) {
858 char *cwd = strip_password (g_strdup (pcwd), 1);
859 fprintf (stderr, _("Warning: Cannot change to %s.\n"), cwd);
860 g_free (cwd);
864 if (reset_prompt)
865 prompt_pos = 0;
866 update_prompt = FALSE;
868 g_free (pcwd);
869 /* Make sure that MC never stores the CWD in a silly format */
870 /* like /usr////lib/../bin, or the strcmp() above will fail */
874 void
875 subshell_get_console_attributes (void)
877 /* Get our current terminal modes */
879 if (tcgetattr (STDOUT_FILENO, &shell_mode)) {
880 fprintf (stderr, "Cannot get terminal settings: %s\r\n",
881 unix_error_string (errno));
882 use_subshell = FALSE;
883 return;
888 /* Figure out whether the subshell has stopped, exited or been killed */
889 /* Possibly modifies: `subshell_alive', `subshell_stopped' and `quit' */
890 void
891 sigchld_handler (int sig)
893 int status;
894 pid_t pid;
896 (void) sig;
898 pid = waitpid (subshell_pid, &status, WUNTRACED | WNOHANG);
900 if (pid == subshell_pid) {
901 /* Figure out what has happened to the subshell */
903 if (WIFSTOPPED (status)) {
904 if (WSTOPSIG (status) == SIGSTOP) {
905 /* The subshell has received a SIGSTOP signal */
906 subshell_stopped = TRUE;
907 } else {
908 /* The user has suspended the subshell. Revive it */
909 kill (subshell_pid, SIGCONT);
911 } else {
912 /* The subshell has either exited normally or been killed */
913 subshell_alive = FALSE;
914 delete_select_channel (subshell_pty);
915 if (WIFEXITED (status) && WEXITSTATUS (status) != FORK_FAILURE)
916 quit |= SUBSHELL_EXIT; /* Exited normally */
919 #ifdef __linux__
920 pid = waitpid (cons_saver_pid, &status, WUNTRACED | WNOHANG);
922 if (pid == cons_saver_pid) {
924 if (WIFSTOPPED (status))
925 /* Someone has stopped cons.saver - restart it */
926 kill (pid, SIGCONT);
927 else {
928 /* cons.saver has died - disable confole saving */
929 handle_console (CONSOLE_DONE);
930 console_flag = 0;
934 #endif /* __linux__ */
936 /* If we got here, some other child exited; ignore it */
940 /* Feed the subshell our keyboard input until it says it's finished */
941 static int
942 feed_subshell (int how, int fail_on_error)
944 fd_set read_set; /* For `select' */
945 int maxfdp;
946 int bytes; /* For the return value from `read' */
947 int i; /* Loop counter */
949 struct timeval wtime; /* Maximum time we wait for the subshell */
950 struct timeval *wptr;
952 /* we wait up to 10 seconds if fail_on_error, forever otherwise */
953 wtime.tv_sec = 10;
954 wtime.tv_usec = 0;
955 wptr = fail_on_error ? &wtime : NULL;
957 while (1) {
958 if (!subshell_alive)
959 return FALSE;
961 /* Prepare the file-descriptor set and call `select' */
963 FD_ZERO (&read_set);
964 FD_SET (subshell_pty, &read_set);
965 FD_SET (subshell_pipe[READ], &read_set);
966 maxfdp = max (subshell_pty, subshell_pipe[READ]);
967 if (how == VISIBLY) {
968 FD_SET (STDIN_FILENO, &read_set);
969 maxfdp = max (maxfdp, STDIN_FILENO);
972 if (select (maxfdp + 1, &read_set, NULL, NULL, wptr) == -1) {
974 /* Despite using SA_RESTART, we still have to check for this */
975 if (errno == EINTR)
976 continue; /* try all over again */
977 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
978 fprintf (stderr, "select (FD_SETSIZE, &read_set...): %s\r\n",
979 unix_error_string (errno));
980 exit (1);
983 if (FD_ISSET (subshell_pty, &read_set))
984 /* Read from the subshell, write to stdout */
986 /* This loop improves performance by reducing context switches
987 by a factor of 20 or so... unfortunately, it also hangs MC
988 randomly, because of an apparent Linux bug. Investigate. */
989 /* for (i=0; i<5; ++i) * FIXME -- experimental */
991 bytes = read (subshell_pty, pty_buffer, pty_buffer_size);
993 /* The subshell has died */
994 if (bytes == -1 && errno == EIO && !subshell_alive)
995 return FALSE;
997 if (bytes <= 0) {
998 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
999 fprintf (stderr, "read (subshell_pty...): %s\r\n",
1000 unix_error_string (errno));
1001 exit (1);
1004 if (how == VISIBLY)
1005 write_all (STDOUT_FILENO, pty_buffer, bytes);
1008 else if (FD_ISSET (subshell_pipe[READ], &read_set))
1009 /* Read the subshell's CWD and capture its prompt */
1012 bytes =
1013 read (subshell_pipe[READ], subshell_cwd,
1014 MC_MAXPATHLEN + 1);
1015 if (bytes <= 0) {
1016 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1017 fprintf (stderr, "read (subshell_pipe[READ]...): %s\r\n",
1018 unix_error_string (errno));
1019 exit (1);
1022 subshell_cwd[bytes - 1] = 0; /* Squash the final '\n' */
1024 synchronize ();
1026 subshell_ready = TRUE;
1027 if (subshell_state == RUNNING_COMMAND) {
1028 subshell_state = INACTIVE;
1029 return 1;
1033 else if (FD_ISSET (STDIN_FILENO, &read_set))
1034 /* Read from stdin, write to the subshell */
1036 bytes = read (STDIN_FILENO, pty_buffer, pty_buffer_size);
1037 if (bytes <= 0) {
1038 tcsetattr (STDOUT_FILENO, TCSANOW, &shell_mode);
1039 fprintf (stderr,
1040 "read (STDIN_FILENO, pty_buffer...): %s\r\n",
1041 unix_error_string (errno));
1042 exit (1);
1045 for (i = 0; i < bytes; ++i)
1046 if (pty_buffer[i] == subshell_switch_key) {
1047 write_all (subshell_pty, pty_buffer, i);
1048 if (subshell_ready)
1049 subshell_state = INACTIVE;
1050 return TRUE;
1053 write_all (subshell_pty, pty_buffer, bytes);
1054 subshell_ready = FALSE;
1055 } else {
1056 return FALSE;
1062 /* Wait until the subshell dies or stops. If it stops, make it resume. */
1063 /* Possibly modifies the globals `subshell_alive' and `subshell_stopped' */
1064 static void synchronize (void)
1066 sigset_t sigchld_mask, old_mask;
1068 sigemptyset (&sigchld_mask);
1069 sigaddset (&sigchld_mask, SIGCHLD);
1070 sigprocmask (SIG_BLOCK, &sigchld_mask, &old_mask);
1073 * SIGCHLD should not be blocked, but we unblock it just in case.
1074 * This is known to be useful for cygwin 1.3.12 and older.
1076 sigdelset (&old_mask, SIGCHLD);
1078 /* Wait until the subshell has stopped */
1079 while (subshell_alive && !subshell_stopped)
1080 sigsuspend (&old_mask);
1082 if (subshell_state != ACTIVE) {
1083 /* Discard all remaining data from stdin to the subshell */
1084 tcflush (subshell_pty_slave, TCIFLUSH);
1087 subshell_stopped = FALSE;
1088 kill (subshell_pid, SIGCONT);
1090 sigprocmask (SIG_SETMASK, &old_mask, NULL);
1091 /* We can't do any better without modifying the shell(s) */
1094 /* pty opening functions */
1096 #ifdef HAVE_GRANTPT
1098 /* System V version of pty_open_master */
1100 static int pty_open_master (char *pty_name)
1102 char *slave_name;
1103 int pty_master;
1105 #ifdef HAVE_POSIX_OPENPT
1106 pty_master = posix_openpt(O_RDWR);
1107 #elif HAVE_GETPT
1108 /* getpt () is a GNU extension (glibc 2.1.x) */
1109 pty_master = getpt ();
1110 #elif IS_AIX
1111 strcpy (pty_name, "/dev/ptc");
1112 pty_master = open (pty_name, O_RDWR);
1113 #else
1114 strcpy (pty_name, "/dev/ptmx");
1115 pty_master = open (pty_name, O_RDWR);
1116 #endif
1118 if (pty_master == -1)
1119 return -1;
1121 if (grantpt (pty_master) == -1 /* Grant access to slave */
1122 || unlockpt (pty_master) == -1 /* Clear slave's lock flag */
1123 || !(slave_name = ptsname (pty_master))) /* Get slave's name */
1125 close (pty_master);
1126 return -1;
1128 strcpy (pty_name, slave_name);
1129 return pty_master;
1132 /* System V version of pty_open_slave */
1133 static int
1134 pty_open_slave (const char *pty_name)
1136 int pty_slave = open (pty_name, O_RDWR);
1138 if (pty_slave == -1) {
1139 fprintf (stderr, "open (%s, O_RDWR): %s\r\n", pty_name,
1140 unix_error_string (errno));
1141 return -1;
1143 #if !defined(__osf__) && !defined(__linux__)
1144 #if defined (I_FIND) && defined (I_PUSH)
1145 if (!ioctl (pty_slave, I_FIND, "ptem"))
1146 if (ioctl (pty_slave, I_PUSH, "ptem") == -1) {
1147 fprintf (stderr, "ioctl (%d, I_PUSH, \"ptem\") failed: %s\r\n",
1148 pty_slave, unix_error_string (errno));
1149 close (pty_slave);
1150 return -1;
1153 if (!ioctl (pty_slave, I_FIND, "ldterm"))
1154 if (ioctl (pty_slave, I_PUSH, "ldterm") == -1) {
1155 fprintf (stderr,
1156 "ioctl (%d, I_PUSH, \"ldterm\") failed: %s\r\n",
1157 pty_slave, unix_error_string (errno));
1158 close (pty_slave);
1159 return -1;
1161 #if !defined(sgi) && !defined(__sgi)
1162 if (!ioctl (pty_slave, I_FIND, "ttcompat"))
1163 if (ioctl (pty_slave, I_PUSH, "ttcompat") == -1) {
1164 fprintf (stderr,
1165 "ioctl (%d, I_PUSH, \"ttcompat\") failed: %s\r\n",
1166 pty_slave, unix_error_string (errno));
1167 close (pty_slave);
1168 return -1;
1170 #endif /* sgi || __sgi */
1171 #endif /* I_FIND && I_PUSH */
1172 #endif /* __osf__ || __linux__ */
1174 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1175 return pty_slave;
1178 #else /* !HAVE_GRANTPT */
1180 /* BSD version of pty_open_master */
1181 static int pty_open_master (char *pty_name)
1183 int pty_master;
1184 const char *ptr1, *ptr2;
1186 strcpy (pty_name, "/dev/ptyXX");
1187 for (ptr1 = "pqrstuvwxyzPQRST"; *ptr1; ++ptr1)
1189 pty_name [8] = *ptr1;
1190 for (ptr2 = "0123456789abcdef"; *ptr2; ++ptr2)
1192 pty_name [9] = *ptr2;
1194 /* Try to open master */
1195 if ((pty_master = open (pty_name, O_RDWR)) == -1) {
1196 if (errno == ENOENT) /* Different from EIO */
1197 return -1; /* Out of pty devices */
1198 else
1199 continue; /* Try next pty device */
1201 pty_name [5] = 't'; /* Change "pty" to "tty" */
1202 if (access (pty_name, 6)){
1203 close (pty_master);
1204 pty_name [5] = 'p';
1205 continue;
1207 return pty_master;
1210 return -1; /* Ran out of pty devices */
1213 /* BSD version of pty_open_slave */
1214 static int
1215 pty_open_slave (const char *pty_name)
1217 int pty_slave;
1218 struct group *group_info = getgrnam ("tty");
1220 if (group_info != NULL) {
1221 /* The following two calls will only succeed if we are root */
1222 /* [Commented out while permissions problem is investigated] */
1223 /* chown (pty_name, getuid (), group_info->gr_gid); FIXME */
1224 /* chmod (pty_name, S_IRUSR | S_IWUSR | S_IWGRP); FIXME */
1226 if ((pty_slave = open (pty_name, O_RDWR)) == -1)
1227 fprintf (stderr, "open (pty_name, O_RDWR): %s\r\n", pty_name);
1228 fcntl(pty_slave, F_SETFD, FD_CLOEXEC);
1229 return pty_slave;
1232 #endif /* !HAVE_GRANTPT */
1233 #endif /* HAVE_SUBSHELL_SUPPORT */