1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2003, 2004
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. */
48 char *getenv (), *getwd ();
52 #define VERSION "unspecified"
55 /* Name used to invoke this program. */
58 /* The first argument to main. */
61 /* The second argument to main. */
64 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
67 /* Nonzero means args are expressions to be evaluated. --eval. */
70 /* Nonzero means open a new graphical frame. */
71 int window_system
= 0;
73 /* The display on which Emacs should work. --display. */
76 /* Nonzero means open a new Emacs frame on the current terminal. */
79 /* If non-NULL, the name of an editor to fallback to if the server
80 is not running. --alternate-editor. */
81 const char * alternate_editor
= NULL
;
83 /* If non-NULL, the filename of the UNIX socket. */
84 char *socket_name
= NULL
;
86 void print_help_and_exit ();
88 struct option longopts
[] =
90 { "no-wait", no_argument
, NULL
, 'n' },
91 { "eval", no_argument
, NULL
, 'e' },
92 { "help", no_argument
, NULL
, 'H' },
93 { "version", no_argument
, NULL
, 'V' },
94 { "tty", no_argument
, NULL
, 't' },
95 { "current-frame", no_argument
, NULL
, 'c' },
96 { "alternate-editor", required_argument
, NULL
, 'a' },
97 { "socket-name", required_argument
, NULL
, 's' },
98 { "display", required_argument
, NULL
, 'd' },
102 /* Decode the options from argv and argc.
103 The global variable `optind' will say how many arguments we used up. */
106 decode_options (argc
, argv
)
110 alternate_editor
= getenv ("ALTERNATE_EDITOR");
111 display
= getenv ("DISPLAY");
112 if (display
&& strlen (display
) == 0)
122 int opt
= getopt_long (argc
, argv
,
123 "VHnea:s:d:tc", longopts
, 0);
131 /* If getopt returns 0, then it has already processed a
132 long-named option. We should do nothing. */
136 alternate_editor
= optarg
;
140 socket_name
= optarg
;
156 printf ("emacsclient %s\n", VERSION
);
171 print_help_and_exit ();
175 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
188 print_help_and_exit ()
191 "Usage: %s [OPTIONS] FILE...\n\
192 Tell the Emacs server to visit the specified files.\n\
193 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
195 The following OPTIONS are accepted:\n\
196 -V, --version Just print a version info and return\n\
197 -H, --help Print this usage information message\n\
198 -t, --tty Open a new Emacs frame on the current terminal\n\
199 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
200 -n, --no-wait Don't wait for the server to return\n\
201 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
202 -d, --display=DISPLAY Visit the file in the given display\n\
203 -s, --socket-name=FILENAME\n\
204 Set the filename of the UNIX socket for communication\n\
205 -a, --alternate-editor=EDITOR\n\
206 Editor to fallback to if the server is not running\n\
208 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
212 /* Like malloc but get fatal error if memory is exhausted. */
218 long *result
= (long *) malloc (size
);
227 /* Like strdup but get a fatal error if memory is exhausted. */
230 xstrdup (const char *s
)
232 char *result
= strdup (s
);
241 /* In STR, 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.
245 Does not change the string. Outputs the result to STREAM. */
248 quote_argument (str
, stream
)
252 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
273 if (*p
== '&' || (*p
== '-' && p
== str
))
280 fprintf (stream
, "%s", copy
);
286 /* The inverse of quote_argument. Removes quoting in string STR by
287 modifying the string in place. Returns STR. */
290 unquote_argument (str
)
322 Try to run a different command, or --if no alternate editor is
323 defined-- exit with an errorcode.
328 if (alternate_editor
)
331 execvp (alternate_editor
, main_argv
+ i
);
340 /* The process id of Emacs. */
343 /* File handles for communicating with Emacs. */
346 /* A signal handler that passes the signal to the Emacs process.
347 Useful for SIGWINCH. */
350 pass_signal_to_emacs (int signalnum
)
352 int old_errno
= errno
;
355 kill (emacs_pid
, signalnum
);
357 signal (signalnum
, pass_signal_to_emacs
);
361 /* Signal handler for SIGCONT; notify the Emacs process that it can
362 now resume our tty frame. */
365 handle_sigcont (int signalnum
)
367 int old_errno
= errno
;
369 if (tcgetpgrp (1) == getpgrp ())
371 /* We are in the foreground. */
372 fprintf (out
, "-resume \n");
374 fsync (fileno (out
));
378 /* We are in the background; cancel the continue. */
379 kill (getpid (), SIGSTOP
);
384 /* Signal handler for SIGTSTP; notify the Emacs process that we are
385 going to sleep. Normally the suspend is initiated by Emacs via
386 server-handle-suspend-tty, but if the server gets out of sync with
387 reality, we may get a SIGTSTP on C-z. Handling this signal and
388 notifying Emacs about it should get things under control again. */
391 handle_sigtstp (int signalnum
)
393 int old_errno
= errno
;
398 fprintf (out
, "-suspend \n");
400 fsync (fileno (out
));
403 /* Unblock this signal and call the default handler by temprarily
404 changing the handler and resignalling. */
405 sigprocmask (SIG_BLOCK
, NULL
, &set
);
406 sigdelset (&set
, signalnum
);
407 signal (signalnum
, SIG_DFL
);
408 kill (getpid (), signalnum
);
409 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
410 signal (signalnum
, handle_sigtstp
);
415 /* Set up signal handlers before opening a frame on the current tty. */
420 /* Set up signal handlers. */
421 signal (SIGWINCH
, pass_signal_to_emacs
);
423 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
424 deciding which terminal the signal came from. C-g is now a
425 normal input event on secondary terminals. */
427 signal (SIGINT
, pass_signal_to_emacs
);
428 signal (SIGQUIT
, pass_signal_to_emacs
);
431 signal (SIGCONT
, handle_sigcont
);
432 signal (SIGTSTP
, handle_sigtstp
);
433 signal (SIGTTOU
, handle_sigtstp
);
437 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
444 fprintf (stderr
, "%s: Sorry, the Emacs server is supported only\n",
446 fprintf (stderr
, "on systems with Berkeley sockets.\n");
451 #else /* HAVE_SOCKETS */
453 #include <sys/types.h>
454 #include <sys/socket.h>
456 #include <sys/stat.h>
459 extern char *strerror ();
462 /* Three possibilities:
463 2 - can't be `stat'ed (sets errno)
464 1 - isn't owned by us
465 0 - success: none of the above */
468 socket_status (socket_name
)
473 if (stat (socket_name
, &statbfr
) == -1)
476 if (statbfr
.st_uid
!= geteuid ())
482 /* Returns 1 if PREFIX is a prefix of STRING. */
484 strprefix (char *prefix
, char *string
)
493 for (i
= 0; prefix
[i
]; i
++)
494 if (!string
[i
] || string
[i
] != prefix
[i
])
504 int s
, i
, needlf
= 0;
505 struct sockaddr_un server
;
513 /* Process options. */
514 decode_options (argc
, argv
);
516 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
518 fprintf (stderr
, "%s: file name or argument required\n", progname
);
519 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
524 * Open up an AF_UNIX socket in this person's home directory
527 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
529 fprintf (stderr
, "%s: ", argv
[0]);
534 server
.sun_family
= AF_UNIX
;
538 int default_sock
= !socket_name
;
541 char *server_name
= "server";
543 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
544 { /* socket_name is a file name component. */
545 server_name
= socket_name
;
547 default_sock
= 1; /* Try both UIDs. */
552 socket_name
= alloca (100 + strlen (server_name
));
553 sprintf (socket_name
, "/tmp/emacs%d/%s",
554 (int) geteuid (), server_name
);
557 if (strlen (socket_name
) < sizeof (server
.sun_path
))
558 strcpy (server
.sun_path
, socket_name
);
561 fprintf (stderr
, "%s: socket-name %s too long",
562 argv
[0], socket_name
);
566 /* See if the socket exists, and if it's owned by us. */
567 sock_status
= socket_status (server
.sun_path
);
569 if (sock_status
&& default_sock
)
571 /* Failing that, see if LOGNAME or USER exist and differ from
572 our euid. If so, look for a socket based on the UID
573 associated with the name. This is reminiscent of the logic
574 that init_editfns uses to set the global Vuser_full_name. */
576 char *user_name
= (char *) getenv ("LOGNAME");
579 user_name
= (char *) getenv ("USER");
583 struct passwd
*pw
= getpwnam (user_name
);
585 if (pw
&& (pw
->pw_uid
!= geteuid ()))
587 /* We're running under su, apparently. */
588 socket_name
= alloca (100 + strlen (server_name
));
589 sprintf (socket_name
, "/tmp/emacs%d/%s",
590 (int) pw
->pw_uid
, server_name
);
592 if (strlen (socket_name
) < sizeof (server
.sun_path
))
593 strcpy (server
.sun_path
, socket_name
);
596 fprintf (stderr
, "%s: socket-name %s too long",
597 argv
[0], socket_name
);
601 sock_status
= socket_status (server
.sun_path
);
612 /* There's a socket, but it isn't owned by us. This is OK if
616 fprintf (stderr
, "%s: Invalid socket owner\n", argv
[0]);
623 if (saved_errno
== ENOENT
)
625 "%s: can't find socket; have you started the server?\n\
626 To start the server in Emacs, type \"M-x server-start\".\n",
629 fprintf (stderr
, "%s: can't stat %s: %s\n",
630 argv
[0], server
.sun_path
, strerror (saved_errno
));
636 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
639 fprintf (stderr
, "%s: ", argv
[0]);
644 /* We use the stream OUT to send our commands to the server. */
645 if ((out
= fdopen (s
, "r+")) == NULL
)
647 fprintf (stderr
, "%s: ", argv
[0]);
652 /* We use the stream IN to read the responses.
653 We used to use just one stream for both output and input
654 on the socket, but reversing direction works nonportably:
655 on some systems, the output appears as the first input;
656 on other systems it does not. */
657 if ((in
= fdopen (s
, "r+")) == NULL
)
659 fprintf (stderr
, "%s: ", argv
[0]);
665 cwd
= getcwd (string
, sizeof string
);
667 cwd
= getwd (string
);
671 /* getwd puts message in STRING if it fails. */
674 fprintf (stderr
, "%s: %s (%s)\n", argv
[0],
675 "cannot get current working directory", strerror (errno
));
677 fprintf (stderr
, "%s: %s (%s)\n", argv
[0], string
, strerror (errno
));
682 /* First of all, send our version number for verification. */
683 fprintf (out
, "-version %s ", VERSION
);
685 /* Send over our environment. */
687 extern char **environ
;
689 for (i
= 0; environ
[i
]; i
++)
691 char *name
= xstrdup (environ
[i
]);
692 char *value
= strchr (name
, '=');
693 if (value
&& strlen (value
) > 1)
696 fprintf (out
, "-env ");
697 quote_argument (name
, out
);
699 quote_argument (value
, out
);
708 fprintf (out
, "-nowait ");
712 fprintf (out
, "-display ");
713 quote_argument (display
, out
);
719 char *tty_name
= ttyname (fileno (stdin
));
720 char *type
= getenv ("TERM");
724 fprintf (stderr
, "%s: could not get terminal name\n", progname
);
730 fprintf (stderr
, "%s: please set the TERM variable to your terminal type\n",
735 if (! strcmp (type
, "eterm"))
737 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
738 fprintf (stderr
, "%s: opening a frame in an Emacs term buffer"
739 " is not supported\n", progname
);
745 fprintf (out
, "-tty ");
746 quote_argument (tty_name
, out
);
748 quote_argument (type
, out
);
753 fprintf (out
, "-window-system ");
755 if ((argc
- optind
> 0))
757 for (i
= optind
; i
< argc
; i
++)
763 /* Don't prepend any cwd or anything like that. */
764 fprintf (out
, "-eval ");
765 quote_argument (argv
[i
], out
);
772 char *p
= argv
[i
] + 1;
773 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
776 fprintf (out
, "-position ");
777 quote_argument (argv
[i
], out
);
784 else if (*argv
[i
] != '/')
787 fprintf (out
, "-file ");
790 quote_argument (cwd
, out
);
793 quote_argument (argv
[i
], out
);
799 if (!tty
&& !window_system
)
801 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
804 fprintf (out
, "-eval ");
806 fprintf (out
, "-file ");
807 quote_argument (str
, out
);
815 fsync (fileno (out
));
817 /* Wait for an answer. */
818 if (!eval
&& !tty
&& !nowait
)
820 printf ("Waiting for Emacs...");
826 /* Now, wait for an answer and print any messages. */
827 while ((str
= fgets (string
, BUFSIZ
, in
)))
829 char *p
= str
+ strlen (str
) - 1;
830 while (p
> str
&& *p
== '\n')
833 if (strprefix ("-good-version ", str
))
835 /* OK, we got the green light. */
837 else if (strprefix ("-emacs-pid ", str
))
839 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
841 else if (strprefix ("-print ", str
))
843 str
= unquote_argument (str
+ strlen ("-print "));
847 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
849 else if (strprefix ("-error ", str
))
851 str
= unquote_argument (str
+ strlen ("-error "));
854 printf ("*ERROR*: %s", str
);
855 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
857 else if (strprefix ("-suspend ", str
))
868 printf ("*ERROR*: Unknown message: %s", str
);
869 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
881 #endif /* HAVE_SOCKETS */
883 #ifndef HAVE_STRERROR
888 extern char *sys_errlist
[];
891 if (errnum
>= 0 && errnum
< sys_nerr
)
892 return sys_errlist
[errnum
];
893 return (char *) "Unknown error";
896 #endif /* ! HAVE_STRERROR */
898 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
899 (do not change this comment) */
901 /* emacsclient.c ends here */