1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2003
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
45 /****************************************/
50 #ifndef INCLUDED_FCNTL
51 #define INCLUDED_FCNTL
60 #endif /* not HAVE_TERMIOS */
62 #ifdef __GNU_LIBRARY__
63 #include <sys/ioctl.h>
67 #if (defined (POSIX) || defined (NEED_UNISTD_H)) && defined (HAVE_UNISTD_H)
73 /* Try to establish the correct character to disable terminal functions
74 in a system-independent manner. Note that USG (at least) define
75 _POSIX_VDISABLE as 0! */
77 #ifdef _POSIX_VDISABLE
78 #define CDISABLE _POSIX_VDISABLE
79 #else /* not _POSIX_VDISABLE */
86 #endif /* not _POSIX_VDISABLE */
90 /****************************************/
92 char *getenv (), *getwd ();
95 /* This is defined with -D from the compilation command,
96 which extracts it from ../lisp/version.el. */
99 #define VERSION "unspecified"
102 /* Name used to invoke this program. */
105 /* The first argument to main. */
108 /* The second argument to main. */
111 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
114 /* Nonzero means args are expressions to be evaluated. --eval. */
117 /* The display on which Emacs should work. --display. */
118 char *display
= NULL
;
120 /* Nonzero means open a new Emacs frame on the current terminal. */
123 /* If non-NULL, the name of an editor to fallback to if the server
124 is not running. --alternate-editor. */
125 const char * alternate_editor
= NULL
;
127 /* If non-NULL, the filename of the UNIX socket. */
128 char *socket_name
= NULL
;
130 void print_help_and_exit ();
132 struct option longopts
[] =
134 { "no-wait", no_argument
, NULL
, 'n' },
135 { "eval", no_argument
, NULL
, 'e' },
136 { "help", no_argument
, NULL
, 'H' },
137 { "version", no_argument
, NULL
, 'V' },
138 { "frame", no_argument
, NULL
, 'f' },
139 { "alternate-editor", required_argument
, NULL
, 'a' },
140 { "socket-name", required_argument
, NULL
, 's' },
141 { "display", required_argument
, NULL
, 'd' },
145 /* Decode the options from argv and argc.
146 The global variable `optind' will say how many arguments we used up. */
149 decode_options (argc
, argv
)
155 int opt
= getopt_long (argc
, argv
,
156 "VHnea:s:d:t", longopts
, 0);
161 alternate_editor
= getenv ("ALTERNATE_EDITOR");
166 /* If getopt returns 0, then it has already processed a
167 long-named option. We should do nothing. */
171 alternate_editor
= optarg
;
175 socket_name
= optarg
;
191 printf ("emacsclient %s\n", VERSION
);
200 print_help_and_exit ();
204 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
218 print_help_and_exit ()
221 "Usage: %s [OPTIONS] FILE...\n\
222 Tell the Emacs server to visit the specified files.\n\
223 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
225 The following OPTIONS are accepted:\n\
226 -V, --version Just print a version info and return\n\
227 -H, --help Print this usage information message\n\
228 -t, --tty Open a new Emacs frame on the current terminal\n\
229 -n, --no-wait Don't wait for the server to return\n\
230 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
231 -d, --display=DISPLAY Visit the file in the given display\n\
232 -s, --socket-name=FILENAME\n\
233 Set the filename of the UNIX socket for communication\n\
234 -a, --alternate-editor=EDITOR\n\
235 Editor to fallback to if the server is not running\n\
237 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
241 /* In NAME, insert a & before each &, each space, each newline, and
242 any initial -. Change spaces to underscores, too, so that the
243 return value never contains a space. */
246 quote_file_name (name
, stream
)
250 char *copy
= (char *) malloc (strlen (name
) * 2 + 1);
271 if (*p
== '&' || (*p
== '-' && p
== name
))
278 fprintf (stream
, copy
);
283 /* Like malloc but get fatal error if memory is exhausted. */
289 long *result
= (long *) malloc (size
);
299 Try to run a different command, or --if no alternate editor is
300 defined-- exit with an errorcode.
305 if (alternate_editor
)
308 execvp (alternate_editor
, main_argv
+ i
);
320 /* Adapted from emacs_get_tty() in sysdep.c. */
322 ec_get_tty (int fd
, struct termios
*settings
)
324 bzero (settings
, sizeof (struct termios
));
325 if (tcgetattr (fd
, settings
) < 0)
330 /* Adapted from emacs_set_tty() in sysdep.c. */
332 ec_set_tty (int fd
, struct termios
*settings
, int flushp
)
334 /* Set the primary parameters - baud rate, character size, etcetera. */
337 /* We have those nifty POSIX tcmumbleattr functions.
338 William J. Smith <wjs@wiis.wang.com> writes:
339 "POSIX 1003.1 defines tcsetattr to return success if it was
340 able to perform any of the requested actions, even if some
341 of the requested actions could not be performed.
342 We must read settings back to ensure tty setup properly.
343 AIX requires this to keep tty from hanging occasionally." */
344 /* This make sure that we don't loop indefinitely in here. */
345 for (i
= 0 ; i
< 10 ; i
++)
346 if (tcsetattr (fd
, flushp
? TCSAFLUSH
: TCSADRAIN
, settings
) < 0)
357 bzero (&new, sizeof (new));
358 /* Get the current settings, and see if they're what we asked for. */
359 tcgetattr (fd
, &new);
360 /* We cannot use memcmp on the whole structure here because under
361 * aix386 the termios structure has some reserved field that may
364 if ( new.c_iflag
== settings
->c_iflag
365 && new.c_oflag
== settings
->c_oflag
366 && new.c_cflag
== settings
->c_cflag
367 && new.c_lflag
== settings
->c_lflag
368 && memcmp (new.c_cc
, settings
->c_cc
, NCCS
) == 0)
379 struct termios old_tty
;
384 int quit_char
= 'g' & 037;
385 int flow_control
= 0;
390 /* Adapted from init_sys_modes() in sysdep.c. */
396 fprintf (stderr
, "%s: Input is not a terminal", "init_tty");
400 ec_get_tty (0, &old_tty
);
404 tty_erase_char
= old_tty
.c_cc
[VERASE
];
406 tty
.c_iflag
|= (IGNBRK
); /* Ignore break condition */
407 tty
.c_iflag
&= ~ICRNL
; /* Disable map of CR to NL on input */
409 tty
.c_iflag
&= ~INLCR
; /* Disable map of NL to CR on input */
412 tty
.c_iflag
&= ~ISTRIP
; /* don't strip 8th bit on input */
414 tty
.c_lflag
&= ~ECHO
; /* Disable echo */
415 tty
.c_lflag
&= ~ICANON
; /* Disable erase/kill processing */
417 tty
.c_lflag
&= ~IEXTEN
; /* Disable other editing characters. */
419 tty
.c_lflag
|= ISIG
; /* Enable signals */
422 tty
.c_iflag
|= IXON
; /* Enable start/stop output control */
424 tty
.c_iflag
&= ~IXANY
;
428 tty
.c_iflag
&= ~IXON
; /* Disable start/stop output control */
429 tty
.c_oflag
&= ~ONLCR
; /* Disable map of NL to CR-NL
431 tty
.c_oflag
&= ~TAB3
; /* Disable tab expansion */
435 tty
.c_cflag
|= CS8
; /* allow 8th bit on input */
436 tty
.c_cflag
&= ~PARENB
; /* Don't check parity */
439 tty
.c_cc
[VINTR
] = quit_char
; /* C-g (usually) gives SIGINT */
440 /* Set up C-g for both SIGQUIT and SIGINT.
441 We don't know which we will get, but we handle both alike
442 so which one it really gives us does not matter. */
443 tty
.c_cc
[VQUIT
] = quit_char
;
444 tty
.c_cc
[VMIN
] = 1; /* Input should wait for at least 1 char */
445 tty
.c_cc
[VTIME
] = 0; /* no matter how long that takes. */
447 tty
.c_cc
[VSWTCH
] = CDISABLE
; /* Turn off shell layering use of C-z */
451 tty
.c_cc
[VSUSP
] = CDISABLE
; /* Turn off mips handling of C-z. */
454 tty
.c_cc
[V_DSUSP
] = CDISABLE
; /* Turn off mips handling of C-y. */
456 #ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP. */
457 tty
.c_cc
[VDSUSP
] = CDISABLE
;
460 tty
.c_cc
[VLNEXT
] = CDISABLE
;
463 tty
.c_cc
[VREPRINT
] = CDISABLE
;
464 #endif /* VREPRINT */
466 tty
.c_cc
[VWERASE
] = CDISABLE
;
469 tty
.c_cc
[VDISCARD
] = CDISABLE
;
470 #endif /* VDISCARD */
475 tty
.c_cc
[VSTART
] = '\021';
478 tty
.c_cc
[VSTOP
] = '\023';
484 tty
.c_cc
[VSTART
] = CDISABLE
;
487 tty
.c_cc
[VSTOP
] = CDISABLE
;
491 #ifdef SET_LINE_DISCIPLINE
492 /* Need to explicitly request TERMIODISC line discipline or
493 Ultrix's termios does not work correctly. */
494 tty
.c_line
= SET_LINE_DISCIPLINE
;
499 /* AIX enhanced edit loses NULs, so disable it. */
501 tty
.c_iflag
&= ~ASCEDIT
;
503 tty
.c_cc
[VSTRT
] = 255;
504 tty
.c_cc
[VSTOP
] = 255;
505 tty
.c_cc
[VSUSP
] = 255;
506 tty
.c_cc
[VDSUSP
] = 255;
507 #endif /* IBMR2AIX */
511 tty
.c_cc
[VSTART
] = '\021';
514 tty
.c_cc
[VSTOP
] = '\023';
517 /* Also, PTY overloads NUL and BREAK.
518 don't ignore break, but don't signal either, so it looks like NUL.
519 This really serves a purpose only if running in an XTERM window
520 or via TELNET or the like, but does no harm elsewhere. */
521 tty
.c_iflag
&= ~IGNBRK
;
522 tty
.c_iflag
&= ~BRKINT
;
525 ec_set_tty (0, &tty
, 0);
527 /* This code added to insure that, if flow-control is not to be used,
528 we have an unlocked terminal at the start. */
531 if (!flow_control
) ioctl (0, TCXONC
, 1);
535 if (!flow_control
) ioctl (0, TIOCSTART
, 0);
539 #if defined (HAVE_TERMIOS) || defined (HPUX9)
541 if (!flow_control
) tcflow (0, TCOON
);
546 /* This symbol is defined on recent USG systems.
547 Someone says without this call USG won't really buffer the file
548 even with a call to setbuf. */
549 setvbuf (stdout
, (char *) _sobuf
, _IOFBF
, sizeof _sobuf
);
551 setbuf (stdout
, (char *) _sobuf
);
560 int width
= 0, height
= 0;
567 if (ioctl (0, TIOCGWINSZ
, &size
) == -1)
572 height
= size
.ws_row
;
581 if (ioctl (0, TIOCGSIZE
, &size
) == -1)
585 width
= size
.ts_cols
;
586 height
= size
.ts_lines
;
589 #endif /* not SunOS-style */
590 #endif /* not BSD-style */
596 size
.ws_row
= height
;
599 ioctl (master
, TIOCSWINSZ
, &size
);
606 size
.ts_lines
= height
;
607 size
.ts_cols
= width
;
609 ioctl (master
, TIOCGSIZE
, &size
);
611 #endif /* not SunOS-style */
612 #endif /* not BSD-style */
614 if (emacs_pid
&& width
&& height
)
615 kill (emacs_pid
, SIGWINCH
);
618 int in_conversation
= 0;
619 int quit_conversation
= 0;
622 hang_up_signal (int signalnum
)
624 int old_errno
= errno
;
626 if (! in_conversation
)
629 quit_conversation
= 1;
635 window_change_signal (int signalnum
)
637 int old_errno
= errno
;
639 if (! in_conversation
)
645 signal (SIGWINCH
, window_change_signal
);
650 interrupt_signal (int signalnum
)
652 int old_errno
= errno
;
654 /* Forward it to Emacs. */
656 kill (emacs_pid
, SIGINT
);
664 /* Set up signal handlers. */
665 signal (SIGWINCH
, window_change_signal
);
666 signal (SIGHUP
, hang_up_signal
);
667 signal (SIGINT
, interrupt_signal
);
673 /* Adapted from reset_sys_modes in sysdep.c. */
680 /* Avoid possible loss of output when changing terminal modes. */
681 fsync (fileno (stdout
));
687 fcntl (0, F_SETFL
, fcntl (0, F_GETFL
, 0) & ~O_NDELAY
);
692 while (ec_set_tty (0, &old_tty
, 0) < 0 && errno
== EINTR
)
706 if (grantpt (master
) < 0 || unlockpt (master
) < 0)
708 pty_name
= strdup (ptsname (master
));
712 /* Propagate window size. */
723 copy_from_to (int in
, int out
, int sigio
)
725 static char buf
[BUFSIZ
];
726 int nread
= read (in
, &buf
, BUFSIZ
);
729 else if (nread
< 0 && errno
!= EAGAIN
)
737 r
= write (out
, &buf
, nread
);
738 } while ((r
< 0 && errno
== EINTR
)
739 || (r
> 0 && (written
+= r
) && written
!= nread
));
744 if (sigio
&& emacs_pid
)
745 kill (emacs_pid
, SIGIO
);
751 pty_conversation (FILE *in
)
759 FD_SET (master
, &set
);
761 FD_SET (fileno (in
), &set
);
765 while (! quit_conversation
) {
767 res
= select (FD_SETSIZE
, &rset
, NULL
, NULL
, NULL
);
768 if (res
< 0 && errno
!= EINTR
)
771 fprintf (stderr
, "%s: ", progname
);
773 return 0; /* Error */
777 if (FD_ISSET (master
, &rset
))
779 /* Copy Emacs output to stdout. */
780 if (! copy_from_to (master
, 0, 0))
782 FD_CLR (master
, &set
);
785 if (FD_ISSET (1, &rset
))
787 /* Forward user input to Emacs. */
788 if (! copy_from_to (1, master
, 1))
790 FD_CLR (master
, &set
);
793 if (FD_ISSET (fileno (in
), &rset
))
796 res
= read (fileno (in
), string
, BUFSIZ
-1);
797 } while (res
== EINTR
);
801 fprintf (stderr
, "%s: ", progname
);
811 if (string
[res
-1] == '\n')
816 /* Get the pid of the Emacs process.
817 XXX Is there some nifty libc/kernel feature for doing this?
822 fprintf (stderr
, "%s: could not get Emacs process id\n"
823 "Maybe this Emacs does not support multiple terminals.\n", progname
);
826 emacs_pid
= strtol (string
, NULL
, 10);
829 if (! emacs_pid
) /* emacs_pid should be set above */
832 fprintf (stderr
, "%s: %s\n", progname
, string
);
841 #endif /* HAVE_TERMIOS */
844 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
851 fprintf (stderr
, "%s: Sorry, the Emacs server is supported only\n",
853 fprintf (stderr
, "on systems with Berkeley sockets.\n");
858 #else /* HAVE_SOCKETS */
860 #include <sys/types.h>
861 #include <sys/socket.h>
863 #include <sys/stat.h>
866 extern char *strerror ();
869 /* Three possibilities:
870 2 - can't be `stat'ed (sets errno)
871 1 - isn't owned by us
872 0 - success: none of the above */
875 socket_status (socket_name
)
880 if (stat (socket_name
, &statbfr
) == -1)
883 if (statbfr
.st_uid
!= geteuid ())
895 int system_name_length
;
896 int s
, i
, needlf
= 0;
898 struct sockaddr_un server
;
906 /* Process options. */
907 decode_options (argc
, argv
);
909 if ((argc
- optind
< 1) && !eval
&& !frame
)
911 fprintf (stderr
, "%s: file name or argument required\n", progname
);
912 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
917 * Open up an AF_UNIX socket in this person's home directory
920 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
922 fprintf (stderr
, "%s: ", argv
[0]);
927 server
.sun_family
= AF_UNIX
;
931 system_name_length
= 32;
935 system_name
= (char *) xmalloc (system_name_length
+ 1);
937 /* system_name must be null-terminated string. */
938 system_name
[system_name_length
] = '\0';
940 if (gethostname (system_name
, system_name_length
) == 0)
944 system_name_length
*= 2;
947 /* We always use the non-dotted host name, for simplicity. */
948 dot
= index (system_name
, '.');
959 socket_name
= alloca (system_name_length
+ 100);
960 sprintf (socket_name
, "/tmp/emacs%d-%s/server",
961 (int) geteuid (), system_name
);
964 if (strlen (socket_name
) < sizeof (server
.sun_path
))
965 strcpy (server
.sun_path
, socket_name
);
968 fprintf (stderr
, "%s: socket-name %s too long",
969 argv
[0], socket_name
);
973 /* See if the socket exists, and if it's owned by us. */
974 sock_status
= socket_status (server
.sun_path
);
978 /* Failing that, see if LOGNAME or USER exist and differ from
979 our euid. If so, look for a socket based on the UID
980 associated with the name. This is reminiscent of the logic
981 that init_editfns uses to set the global Vuser_full_name. */
983 char *user_name
= (char *) getenv ("LOGNAME");
985 user_name
= (char *) getenv ("USER");
989 struct passwd
*pw
= getpwnam (user_name
);
990 if (pw
&& (pw
->pw_uid
!= geteuid ()))
992 /* We're running under su, apparently. */
993 sprintf (server
.sun_path
, "/tmp/esrv%d-%s",
994 (int) pw
->pw_uid
, system_name
);
995 sock_status
= socket_status (server
.sun_path
);
1001 switch (sock_status
)
1004 /* There's a socket, but it isn't owned by us. This is OK if
1006 if (0 != geteuid ())
1008 fprintf (stderr
, "%s: Invalid socket owner\n", argv
[0]);
1015 if (errno
== ENOENT
)
1017 "%s: Can't find socket; have you started the server?\n\
1018 To start the server in Emacs, type \"M-x server-start\".\n",
1021 fprintf (stderr
, "%s: Can't stat %s: %s\n",
1022 argv
[0], server
.sun_path
, strerror (oerrno
));
1028 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1031 fprintf (stderr
, "%s: ", argv
[0]);
1036 /* We use the stream OUT to send our command to the server. */
1037 if ((out
= fdopen (s
, "r+")) == NULL
)
1039 fprintf (stderr
, "%s: ", argv
[0]);
1044 /* We use the stream IN to read the response.
1045 We used to use just one stream for both output and input
1046 on the socket, but reversing direction works nonportably:
1047 on some systems, the output appears as the first input;
1048 on other systems it does not. */
1049 if ((in
= fdopen (s
, "r+")) == NULL
)
1051 fprintf (stderr
, "%s: ", argv
[0]);
1057 cwd
= getcwd (string
, sizeof string
);
1059 cwd
= getwd (string
);
1063 /* getwd puts message in STRING if it fails. */
1066 fprintf (stderr
, "%s: %s (%s)\n", argv
[0],
1067 "Cannot get current working directory", strerror (errno
));
1069 fprintf (stderr
, "%s: %s (%s)\n", argv
[0], string
, strerror (errno
));
1075 fprintf (out
, "-nowait ");
1078 fprintf (out
, "-eval ");
1082 fprintf (out
, "-display ");
1083 quote_file_name (display
, out
);
1089 if (! init_signals ())
1091 fprintf (stderr
, "%s: ", argv
[0]);
1099 fprintf (stderr
, "%s: ", argv
[0]);
1107 fprintf (stderr
, "%s: ", argv
[0]);
1112 fprintf (out
, "-tty ");
1113 quote_file_name (pty_name
, out
);
1115 quote_file_name (getenv("TERM"), out
);
1119 if ((argc
- optind
> 0))
1121 for (i
= optind
; i
< argc
; i
++)
1124 ; /* Don't prepend any cwd or anything like that. */
1125 else if (*argv
[i
] == '+')
1127 char *p
= argv
[i
] + 1;
1128 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1131 quote_file_name (cwd
, out
);
1135 else if (*argv
[i
] != '/')
1137 quote_file_name (cwd
, out
);
1141 quote_file_name (argv
[i
], out
);
1149 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1151 quote_file_name (str
, out
);
1157 fprintf (out
, "\n");
1160 /* Maybe wait for an answer. */
1169 if (! pty_conversation (out
))
1180 printf ("Waiting for Emacs...");
1185 /* Now, wait for an answer and print any messages. */
1186 while ((str
= fgets (string
, BUFSIZ
, in
)))
1191 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1202 #endif /* HAVE_SOCKETS */
1204 #ifndef HAVE_STRERROR
1209 extern char *sys_errlist
[];
1210 extern int sys_nerr
;
1212 if (errnum
>= 0 && errnum
< sys_nerr
)
1213 return sys_errlist
[errnum
];
1214 return (char *) "Unknown error";
1217 #endif /* ! HAVE_STRERROR */
1219 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1220 (do not change this comment) */