1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006 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., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
31 /* config.h defines these, which disables sockets altogether! */
39 # define NO_SOCKETS_IN_FILE_SYSTEM
41 # define HSOCKET SOCKET
42 # define CLOSE_SOCKET closesocket
43 # define INITIALIZE() (initialize_sockets ())
45 #else /* !WINDOWSNT */
47 # include <sys/types.h>
49 # ifdef HAVE_INET_SOCKETS
50 # include <netinet/in.h>
53 # define INVALID_SOCKET -1
55 # define CLOSE_SOCKET close
58 #endif /* !WINDOWSNT */
75 #else /* not WINDOWSNT */
77 #endif /* not WINDOWSNT */
80 char *getenv (), *getwd ();
84 #define VERSION "unspecified"
87 #define SEND_STRING(data) (send_to_emacs (s, (data)))
88 #define SEND_QUOTED(data) (quote_file_name (s, (data)))
91 #define EXIT_SUCCESS 0
95 #define EXIT_FAILURE 1
110 /* Name used to invoke this program. */
113 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
116 /* Nonzero means args are expressions to be evaluated. --eval. */
119 /* The display on which Emacs should work. --display. */
120 char *display
= NULL
;
122 /* If non-NULL, the name of an editor to fallback to if the server
123 is not running. --alternate-editor. */
124 const char *alternate_editor
= NULL
;
126 /* If non-NULL, the filename of the UNIX socket. */
127 char *socket_name
= NULL
;
129 /* If non-NULL, the filename of the authentication file. */
130 char *server_file
= NULL
;
132 void print_help_and_exit () NO_RETURN
;
134 struct option longopts
[] =
136 { "no-wait", no_argument
, NULL
, 'n' },
137 { "eval", no_argument
, NULL
, 'e' },
138 { "help", no_argument
, NULL
, 'H' },
139 { "version", no_argument
, NULL
, 'V' },
140 { "alternate-editor", required_argument
, NULL
, 'a' },
141 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
142 { "socket-name", required_argument
, NULL
, 's' },
144 { "server-file", required_argument
, NULL
, 'f' },
145 { "display", required_argument
, NULL
, 'd' },
149 /* Message functions. */
152 /* I first tried to check for STDOUT. The check did not work,
153 I get a valid handle also in nonconsole apps.
154 Instead I test for console title, which seems to work. */
158 static int window_app
= -1;
159 char szTitle
[MAX_PATH
];
162 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
169 message (int is_error
, char *message
, ...)
175 va_start (args
, message
);
179 sprintf (buf
, "%s: ", progname
);
180 msg
= strchr (buf
, '\0');
183 vsprintf (msg
, message
, args
);
187 if (w32_window_app ())
190 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
192 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
196 fprintf (is_error
? stderr
: stdout
, msg
);
199 /* Decode the options from argv and argc.
200 The global variable `optind' will say how many arguments we used up. */
203 decode_options (argc
, argv
)
207 alternate_editor
= getenv ("ALTERNATE_EDITOR");
211 int opt
= getopt_long (argc
, argv
,
212 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
225 /* If getopt returns 0, then it has already processed a
226 long-named option. We should do nothing. */
230 alternate_editor
= optarg
;
233 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
235 socket_name
= optarg
;
240 server_file
= optarg
;
256 message (FALSE
, "emacsclient %s\n", VERSION
);
261 print_help_and_exit ();
265 message (TRUE
, "Try `%s --help' for more information\n", progname
);
273 print_help_and_exit ()
276 "Usage: %s [OPTIONS] FILE...\n\
277 Tell the Emacs server to visit the specified files.\n\
278 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
280 The following OPTIONS are accepted:\n\
281 -V, --version Just print a version info and return\n\
282 -H, --help Print this usage information message\n\
283 -n, --no-wait Don't wait for the server to return\n\
284 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
285 -d, --display=DISPLAY Visit the file in the given display\n"
286 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
287 "-s, --socket-name=FILENAME\n\
288 Set the filename of the UNIX socket for communication\n"
290 "-f, --server-file=FILENAME\n\
291 Set the filename of the TCP configuration file\n\
292 -a, --alternate-editor=EDITOR\n\
293 Editor to fallback to if the server is not running\n\
295 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
301 Try to run a different command, or --if no alternate editor is
302 defined-- exit with an errorcode.
309 if (alternate_editor
)
313 argv
[i
] = (char *)alternate_editor
;
315 execvp (alternate_editor
, argv
+ i
);
316 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
317 progname
, alternate_editor
);
323 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
330 message (TRUE
, "%s: Sorry, the Emacs server is supported only\non systems with Berkely sockets.\n",
336 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
339 # include <winsock2.h>
341 # include <sys/types.h>
342 # include <sys/socket.h>
344 # include <sys/stat.h>
348 #define AUTH_KEY_LENGTH 64
349 #define SEND_BUFFER_SIZE 4096
351 extern char *strerror ();
354 /* Buffer to accumulate data to send in TCP connections. */
355 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
356 int sblen
= 0; /* Fill pointer for the send buffer. */
358 /* Let's send the data to Emacs when either
359 - the data ends in "\n", or
360 - the buffer is full (but this shouldn't happen)
361 Otherwise, we just accumulate it. */
363 send_to_emacs (s
, data
)
369 int dlen
= strlen (data
);
370 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
372 int part
= SEND_BUFFER_SIZE
- sblen
;
373 strncpy (&send_buffer
[sblen
], data
, part
);
375 sblen
= SEND_BUFFER_SIZE
;
379 strcpy (&send_buffer
[sblen
], data
);
386 if (sblen
== SEND_BUFFER_SIZE
387 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
389 int sent
= send (s
, send_buffer
, sblen
, 0);
391 strcpy (send_buffer
, &send_buffer
[sent
]);
397 /* In NAME, insert a & before each &, each space, each newline, and
398 any initial -. Change spaces to underscores, too, so that the
399 return value never contains a space. */
401 quote_file_name (s
, name
)
405 char *copy
= (char *) malloc (strlen (name
) * 2 + 1);
426 if (*p
== '&' || (*p
== '-' && p
== name
))
439 file_name_absolute_p (filename
)
440 const unsigned char *filename
;
442 /* Sanity check, it shouldn't happen. */
443 if (! filename
) return FALSE
;
445 /* /xxx is always an absolute path. */
446 if (filename
[0] == '/') return TRUE
;
448 /* Empty filenames (which shouldn't happen) are relative. */
449 if (filename
[0] == '\0') return FALSE
;
452 /* X:\xxx is always absolute; X:xxx is an error and will fail. */
453 if (islower (tolower (filename
[0]))
454 && filename
[1] == ':' && filename
[2] == '\\')
457 /* Both \xxx and \\xxx\yyy are absolute. */
458 if (filename
[0] == '\\') return TRUE
;
465 /* Wrapper to make WSACleanup a cdecl, as required by atexit(). */
467 __cdecl
close_winsock ()
472 /* Initialize the WinSock2 library. */
474 initialize_sockets ()
478 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
480 message (TRUE
, "%s: error initializing WinSock2", progname
);
484 atexit (close_winsock
);
486 #endif /* WINDOWSNT */
489 * Read the information needed to set up a TCP comm channel with
490 * the Emacs server: host, port, pid and authentication string.
493 get_server_config (server
, authentication
)
494 struct sockaddr_in
*server
;
495 char *authentication
;
502 if (file_name_absolute_p (server_file
))
503 config
= fopen (server_file
, "rb");
506 char *home
= getenv ("HOME");
510 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
511 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
512 config
= fopen (path
, "rb");
515 if (!config
&& (home
= getenv ("APPDATA")))
517 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
518 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
519 config
= fopen (path
, "rb");
527 if (fgets (dotted
, sizeof dotted
, config
)
528 && (port
= strchr (dotted
, ':'))
529 && (pid
= strchr (port
, ' ')))
536 message (TRUE
, "%s: invalid configuration info", progname
);
540 server
->sin_family
= AF_INET
;
541 server
->sin_addr
.s_addr
= inet_addr (dotted
);
542 server
->sin_port
= htons (atoi (port
));
544 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
546 message (TRUE
, "%s: cannot read authentication info", progname
);
554 Modern Windows restrict which processes can set the foreground window.
555 So, for emacsclient to be able to force Emacs into the foreground, we
556 have to call AllowSetForegroundWindow(). Unfortunately, older Windows
557 (W95, W98 and NT) don't have this function, so we have to check first.
559 We're doing this here because it has to be done before sending info
560 to Emacs, and otherwise we'll need a global variable just to pass around
561 the pid, which is also inelegant.
566 if (hUser32
= LoadLibrary ("user32.dll"))
569 if (set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
571 FreeLibrary (hUser32
);
583 struct sockaddr_in server
;
584 struct linger l_arg
= {1, 1};
585 char auth_string
[AUTH_KEY_LENGTH
+ 1];
587 if (! get_server_config (&server
, auth_string
))
588 return INVALID_SOCKET
;
590 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
591 message (TRUE
, "%s: connected to remote socket at %s\n",
592 progname
, inet_ntoa (server
.sin_addr
));
595 * Open up an AF_INET socket
597 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
599 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
600 return INVALID_SOCKET
;
606 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
608 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
609 return INVALID_SOCKET
;
612 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
615 * Send the authentication
617 auth_string
[AUTH_KEY_LENGTH
] = '\0';
619 SEND_STRING ("-auth ");
620 SEND_STRING (auth_string
);
626 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
628 /* Three possibilities:
629 2 - can't be `stat'ed (sets errno)
630 1 - isn't owned by us
631 0 - success: none of the above */
634 socket_status (socket_name
)
639 if (stat (socket_name
, &statbfr
) == -1)
642 if (statbfr
.st_uid
!= geteuid ())
652 struct sockaddr_un server
;
655 * Open up an AF_UNIX socket in this person's home directory
658 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
660 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
661 return INVALID_SOCKET
;
664 server
.sun_family
= AF_UNIX
;
668 int default_sock
= !socket_name
;
670 char *server_name
= "server";
672 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
673 { /* socket_name is a file name component. */
674 server_name
= socket_name
;
676 default_sock
= 1; /* Try both UIDs. */
681 socket_name
= alloca (100 + strlen (server_name
));
682 sprintf (socket_name
, "/tmp/emacs%d/%s",
683 (int) geteuid (), server_name
);
686 if (strlen (socket_name
) < sizeof (server
.sun_path
))
687 strcpy (server
.sun_path
, socket_name
);
690 message (TRUE
, "%s: socket-name %s too long",
691 progname
, socket_name
);
695 /* See if the socket exists, and if it's owned by us. */
696 sock_status
= socket_status (server
.sun_path
);
698 if (sock_status
&& default_sock
)
700 /* Failing that, see if LOGNAME or USER exist and differ from
701 our euid. If so, look for a socket based on the UID
702 associated with the name. This is reminiscent of the logic
703 that init_editfns uses to set the global Vuser_full_name. */
705 char *user_name
= (char *) getenv ("LOGNAME");
708 user_name
= (char *) getenv ("USER");
712 struct passwd
*pw
= getpwnam (user_name
);
714 if (pw
&& (pw
->pw_uid
!= geteuid ()))
716 /* We're running under su, apparently. */
717 socket_name
= alloca (100 + strlen (server_name
));
718 sprintf (socket_name
, "/tmp/emacs%d/%s",
719 (int) pw
->pw_uid
, server_name
);
721 if (strlen (socket_name
) < sizeof (server
.sun_path
))
722 strcpy (server
.sun_path
, socket_name
);
725 message (TRUE
, "%s: socket-name %s too long",
726 progname
, socket_name
);
730 sock_status
= socket_status (server
.sun_path
);
741 /* There's a socket, but it isn't owned by us. This is OK if
745 message (TRUE
, "%s: Invalid socket owner\n", progname
);
746 return INVALID_SOCKET
;
752 if (saved_errno
== ENOENT
)
754 "%s: can't find socket; have you started the server?\n\
755 To start the server in Emacs, type \"M-x server-start\".\n",
758 message (TRUE
, "%s: can't stat %s: %s\n",
759 progname
, server
.sun_path
, strerror (saved_errno
));
760 return INVALID_SOCKET
;
764 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
767 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
768 return INVALID_SOCKET
;
773 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
782 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
783 /* Explicit --socket-name argument. */
786 s
= set_local_socket ();
787 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
790 message (TRUE
, "%s: error accessing socket \"%s\"",
791 progname
, socket_name
);
796 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
798 server_file
= getenv ("EMACS_SERVER_FILE");
802 s
= set_tcp_socket ();
803 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
806 message (TRUE
, "%s: error accessing server file \"%s\"",
807 progname
, server_file
);
811 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
812 /* Implicit local socket. */
813 s
= set_local_socket ();
814 if (s
!= INVALID_SOCKET
)
818 /* Implicit server file. */
819 server_file
= "server";
820 s
= set_tcp_socket ();
821 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
824 /* No implicit or explicit socket, and no alternate editor. */
825 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
826 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
829 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
830 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
841 int i
, rl
, needlf
= 0;
843 char string
[BUFSIZ
+1];
847 /* Process options. */
848 decode_options (argc
, argv
);
850 if ((argc
- optind
< 1) && !eval
)
852 message (TRUE
, "%s: file name or argument required\nTry `%s --help' for more information\n",
857 if ((s
= set_socket ()) == INVALID_SOCKET
)
861 cwd
= getcwd (string
, sizeof string
);
863 cwd
= getwd (string
);
867 /* getwd puts message in STRING if it fails. */
869 message (TRUE
, "%s: %s (%s)\n", progname
,
870 "Cannot get current working directory", strerror (errno
));
872 message (TRUE
, "%s: %s (%s)\n", progname
, string
, strerror (errno
));
878 SEND_STRING ("-nowait ");
881 SEND_STRING ("-eval ");
885 SEND_STRING ("-display ");
886 SEND_QUOTED (display
);
890 if ((argc
- optind
> 0))
892 for (i
= optind
; i
< argc
; i
++)
895 ; /* Don't prepend any cwd or anything like that. */
896 else if (*argv
[i
] == '+')
898 char *p
= argv
[i
] + 1;
899 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
906 else if (! file_name_absolute_p (argv
[i
]))
912 SEND_QUOTED (argv
[i
]);
918 while (fgets (string
, BUFSIZ
, stdin
))
920 SEND_QUOTED (string
);
927 /* Maybe wait for an answer. */
932 printf ("Waiting for Emacs...");
937 /* Now, wait for an answer and print any messages. */
938 while ((rl
= recv (s
, string
, BUFSIZ
, 0)) > 0)
943 printf ("%s", string
);
944 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
956 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
958 #ifndef HAVE_STRERROR
963 extern char *sys_errlist
[];
966 if (errnum
>= 0 && errnum
< sys_nerr
)
967 return sys_errlist
[errnum
];
968 return (char *) "Unknown error";
971 #endif /* ! HAVE_STRERROR */
973 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
974 (do not change this comment) */
976 /* emacsclient.c ends here */