4 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/types.h>
21 #include <sys/socket.h>
36 struct imsgbuf client_ibuf
;
37 struct event client_event
;
38 struct event client_stdin
;
42 CLIENT_EXIT_DETACHED_HUP
,
44 CLIENT_EXIT_TERMINATED
,
45 CLIENT_EXIT_LOST_SERVER
,
47 CLIENT_EXIT_SERVER_EXITED
,
48 } client_exitreason
= CLIENT_EXIT_NONE
;
50 enum msgtype client_exittype
;
53 int client_get_lock(char *);
54 int client_connect(char *, int);
55 void client_send_identify(int);
56 void client_send_environ(void);
57 void client_write_server(enum msgtype
, void *, size_t);
58 void client_update_event(void);
59 void client_signal(int, short, void *);
60 void client_stdin_callback(int, short, void *);
61 void client_write(int, const char *, size_t);
62 void client_callback(int, short, void *);
63 int client_dispatch_attached(void);
64 int client_dispatch_wait(void *);
65 const char *client_exit_message(void);
68 * Get server create lock. If already held then server start is happening in
69 * another client, so block until the lock is released and return -1 to
70 * retry. Ignore other errors - just continue and start the server without the
74 client_get_lock(char *lockfile
)
78 if ((lockfd
= open(lockfile
, O_WRONLY
|O_CREAT
, 0600)) == -1)
81 if (lockf(lockfd
, F_TLOCK
, 0) == -1 && errno
== EAGAIN
) {
82 while (lockf(lockfd
, F_LOCK
, 0) == -1 && errno
== EINTR
)
91 /* Connect client to server. */
93 client_connect(char *path
, int start_server
)
95 struct sockaddr_un sa
;
100 memset(&sa
, 0, sizeof sa
);
101 sa
.sun_family
= AF_UNIX
;
102 size
= strlcpy(sa
.sun_path
, path
, sizeof sa
.sun_path
);
103 if (size
>= sizeof sa
.sun_path
) {
104 errno
= ENAMETOOLONG
;
109 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) == -1)
110 fatal("socket failed");
112 if (connect(fd
, (struct sockaddr
*) &sa
, SUN_LEN(&sa
)) == -1) {
113 if (errno
!= ECONNREFUSED
&& errno
!= ENOENT
)
119 xasprintf(&lockfile
, "%s.lock", path
);
120 if ((lockfd
= client_get_lock(lockfile
)) == -1)
122 if (unlink(path
) != 0 && errno
!= ENOENT
)
124 fd
= server_start(lockfd
, lockfile
);
137 /* Get exit string from reason number. */
139 client_exit_message(void)
141 switch (client_exitreason
) {
142 case CLIENT_EXIT_NONE
:
144 case CLIENT_EXIT_DETACHED
:
146 case CLIENT_EXIT_DETACHED_HUP
:
147 return ("detached and SIGHUP");
148 case CLIENT_EXIT_LOST_TTY
:
150 case CLIENT_EXIT_TERMINATED
:
151 return ("terminated");
152 case CLIENT_EXIT_LOST_SERVER
:
153 return ("lost server");
154 case CLIENT_EXIT_EXITED
:
156 case CLIENT_EXIT_SERVER_EXITED
:
157 return ("server exited");
159 return ("unknown reason");
162 /* Client main loop. */
164 client_main(int argc
, char **argv
, int flags
)
167 struct cmd_list
*cmdlist
;
168 struct msg_command_data cmddata
;
173 struct termios tio
, saved_tio
;
175 /* Set up the initial command. */
177 if (shell_cmd
!= NULL
) {
179 cmdflags
= CMD_STARTSERVER
;
180 } else if (argc
== 0) {
182 cmdflags
= CMD_STARTSERVER
|CMD_SENDENVIRON
|CMD_CANTNEST
;
187 * It sucks parsing the command string twice (in client and
188 * later in server) but it is necessary to get the start server
191 cmdlist
= cmd_list_parse(argc
, argv
, NULL
, 0, &cause
);
192 if (cmdlist
== NULL
) {
193 fprintf(stderr
, "%s\n", cause
);
196 cmdflags
&= ~CMD_STARTSERVER
;
197 TAILQ_FOREACH(cmd
, &cmdlist
->list
, qentry
) {
198 if (cmd
->entry
->flags
& CMD_STARTSERVER
)
199 cmdflags
|= CMD_STARTSERVER
;
200 if (cmd
->entry
->flags
& CMD_SENDENVIRON
)
201 cmdflags
|= CMD_SENDENVIRON
;
202 if (cmd
->entry
->flags
& CMD_CANTNEST
)
203 cmdflags
|= CMD_CANTNEST
;
205 cmd_list_free(cmdlist
);
209 * Check if this could be a nested session, if the command can't nest:
210 * if the socket path matches $TMUX, this is probably the same server.
212 if (shell_cmd
== NULL
&& environ_path
!= NULL
&&
213 (cmdflags
& CMD_CANTNEST
) &&
214 strcmp(socket_path
, environ_path
) == 0) {
215 fprintf(stderr
, "sessions should be nested with care, "
216 "unset $TMUX to force\n");
220 /* Initialise the client socket and start the server. */
221 fd
= client_connect(socket_path
, cmdflags
& CMD_STARTSERVER
);
223 fprintf(stderr
, "failed to connect to server\n");
227 /* Set process title, log and signals now this is the client. */
228 setproctitle("client (%s)", socket_path
);
232 imsg_init(&client_ibuf
, fd
);
233 event_set(&client_event
, fd
, EV_READ
, client_callback
, shell_cmd
);
235 /* Create stdin handler. */
236 setblocking(STDIN_FILENO
, 0);
237 event_set(&client_stdin
, STDIN_FILENO
, EV_READ
|EV_PERSIST
,
238 client_stdin_callback
, NULL
);
239 if (flags
& IDENTIFY_TERMIOS
) {
240 if (tcgetattr(STDIN_FILENO
, &saved_tio
) != 0) {
241 fprintf(stderr
, "tcgetattr failed: %s\n",
246 tio
.c_iflag
= ICRNL
|IXANY
;
247 tio
.c_oflag
= OPOST
|ONLCR
;
248 tio
.c_lflag
= NOKERNINFO
;
249 tio
.c_cflag
= CREAD
|CS8
|HUPCL
;
252 cfsetispeed(&tio
, cfgetispeed(&saved_tio
));
253 cfsetospeed(&tio
, cfgetospeed(&saved_tio
));
254 tcsetattr(STDIN_FILENO
, TCSANOW
, &tio
);
257 /* Establish signal handlers. */
258 set_signals(client_signal
);
260 /* Send initial environment. */
261 if (cmdflags
& CMD_SENDENVIRON
)
262 client_send_environ();
263 client_send_identify(flags
);
265 /* Send first command. */
266 if (msg
== MSG_COMMAND
) {
267 /* Fill in command line arguments. */
268 cmddata
.pid
= environ_pid
;
269 cmddata
.session_id
= environ_session_id
;
271 /* Prepare command for server. */
274 argc
, argv
, cmddata
.argv
, sizeof cmddata
.argv
) != 0) {
275 fprintf(stderr
, "command too long\n");
279 client_write_server(msg
, &cmddata
, sizeof cmddata
);
280 } else if (msg
== MSG_SHELL
)
281 client_write_server(msg
, NULL
, 0);
283 /* Set the event and dispatch. */
284 client_update_event();
287 /* Print the exit message, if any, and exit. */
288 if (client_attached
) {
289 if (client_exitreason
!= CLIENT_EXIT_NONE
&& !login_shell
)
290 printf("[%s]\n", client_exit_message());
293 if (client_exittype
== MSG_DETACHKILL
&& ppid
> 1)
295 } else if (flags
& IDENTIFY_TERMIOS
) {
296 if (flags
& IDENTIFY_CONTROL
) {
297 if (client_exitreason
!= CLIENT_EXIT_NONE
)
298 printf("%%exit %s\n", client_exit_message());
303 tcsetattr(STDOUT_FILENO
, TCSAFLUSH
, &saved_tio
);
305 setblocking(STDIN_FILENO
, 1);
306 return (client_exitval
);
309 /* Send identify message to server with the file descriptors. */
311 client_send_identify(int flags
)
313 struct msg_identify_data data
;
319 if (getcwd(data
.cwd
, sizeof data
.cwd
) == NULL
)
322 term
= getenv("TERM");
324 strlcpy(data
.term
, term
, sizeof data
.term
) >= sizeof data
.term
)
327 if ((fd
= dup(STDIN_FILENO
)) == -1)
329 imsg_compose(&client_ibuf
,
330 MSG_IDENTIFY
, PROTOCOL_VERSION
, -1, fd
, &data
, sizeof data
);
331 client_update_event();
334 /* Forward entire environment to server. */
336 client_send_environ(void)
338 struct msg_environ_data data
;
341 for (var
= environ
; *var
!= NULL
; var
++) {
342 if (strlcpy(data
.var
, *var
, sizeof data
.var
) >= sizeof data
.var
)
344 client_write_server(MSG_ENVIRON
, &data
, sizeof data
);
348 /* Write a message to the server without a file descriptor. */
350 client_write_server(enum msgtype type
, void *buf
, size_t len
)
352 imsg_compose(&client_ibuf
, type
, PROTOCOL_VERSION
, -1, -1, buf
, len
);
353 client_update_event();
356 /* Update client event based on whether it needs to read or read and write. */
358 client_update_event(void)
362 event_del(&client_event
);
364 if (client_ibuf
.w
.queued
> 0)
367 &client_event
, client_ibuf
.fd
, events
, client_callback
, shell_cmd
);
368 event_add(&client_event
, NULL
);
371 /* Callback to handle signals in the client. */
373 client_signal(int sig
, unused
short events
, unused
void *data
)
375 struct sigaction sigact
;
378 if (!client_attached
) {
381 waitpid(WAIT_ANY
, &status
, WNOHANG
);
384 event_loopexit(NULL
);
390 client_exitreason
= CLIENT_EXIT_LOST_TTY
;
392 client_write_server(MSG_EXITING
, NULL
, 0);
395 client_exitreason
= CLIENT_EXIT_TERMINATED
;
397 client_write_server(MSG_EXITING
, NULL
, 0);
400 client_write_server(MSG_RESIZE
, NULL
, 0);
403 memset(&sigact
, 0, sizeof sigact
);
404 sigemptyset(&sigact
.sa_mask
);
405 sigact
.sa_flags
= SA_RESTART
;
406 sigact
.sa_handler
= SIG_IGN
;
407 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
408 fatal("sigaction failed");
409 client_write_server(MSG_WAKEUP
, NULL
, 0);
414 client_update_event();
417 /* Callback for client imsg read events. */
419 client_callback(unused
int fd
, short events
, void *data
)
424 if (events
& EV_READ
) {
425 if ((n
= imsg_read(&client_ibuf
)) == -1 || n
== 0)
428 retval
= client_dispatch_attached();
430 retval
= client_dispatch_wait(data
);
432 event_loopexit(NULL
);
437 if (events
& EV_WRITE
) {
438 if (msgbuf_write(&client_ibuf
.w
) < 0)
442 client_update_event();
446 client_exitreason
= CLIENT_EXIT_LOST_SERVER
;
448 event_loopexit(NULL
);
451 /* Callback for client stdin read events. */
453 client_stdin_callback(unused
int fd
, unused
short events
, unused
void *data1
)
455 struct msg_stdin_data data
;
457 data
.size
= read(STDIN_FILENO
, data
.data
, sizeof data
.data
);
458 if (data
.size
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
461 client_write_server(MSG_STDIN
, &data
, sizeof data
);
463 event_del(&client_stdin
);
464 client_update_event();
467 /* Force write to file descriptor. */
469 client_write(int fd
, const char *data
, size_t size
)
474 used
= write(fd
, data
, size
);
476 if (errno
== EINTR
|| errno
== EAGAIN
)
485 /* Dispatch imsgs when in wait state (before MSG_READY). */
487 client_dispatch_wait(void *data
)
491 struct msg_shell_data shelldata
;
492 struct msg_exit_data exitdata
;
493 struct msg_stdout_data stdoutdata
;
494 struct msg_stderr_data stderrdata
;
495 const char *shellcmd
= data
;
498 if ((n
= imsg_get(&client_ibuf
, &imsg
)) == -1)
499 fatalx("imsg_get failed");
502 datalen
= imsg
.hdr
.len
- IMSG_HEADER_SIZE
;
504 log_debug("got %d from server", imsg
.hdr
.type
);
505 switch (imsg
.hdr
.type
) {
508 if (datalen
!= sizeof exitdata
) {
510 fatalx("bad MSG_EXIT size");
512 memcpy(&exitdata
, imsg
.data
, sizeof exitdata
);
513 client_exitval
= exitdata
.retcode
;
519 fatalx("bad MSG_READY size");
521 event_del(&client_stdin
);
523 client_write_server(MSG_RESIZE
, NULL
, 0);
527 fatalx("bad MSG_STDIN size");
529 event_add(&client_stdin
, NULL
);
532 if (datalen
!= sizeof stdoutdata
)
533 fatalx("bad MSG_STDOUT");
534 memcpy(&stdoutdata
, imsg
.data
, sizeof stdoutdata
);
536 client_write(STDOUT_FILENO
, stdoutdata
.data
, stdoutdata
.size
);
539 if (datalen
!= sizeof stderrdata
)
540 fatalx("bad MSG_STDERR");
541 memcpy(&stderrdata
, imsg
.data
, sizeof stderrdata
);
543 client_write(STDERR_FILENO
, stderrdata
.data
, stderrdata
.size
);
547 fatalx("bad MSG_VERSION size");
549 fprintf(stderr
, "protocol version mismatch "
550 "(client %u, server %u)\n", PROTOCOL_VERSION
,
557 if (datalen
!= sizeof shelldata
)
558 fatalx("bad MSG_SHELL size");
559 memcpy(&shelldata
, imsg
.data
, sizeof shelldata
);
560 shelldata
.shell
[(sizeof shelldata
.shell
) - 1] = '\0';
564 shell_exec(shelldata
.shell
, shellcmd
);
567 client_write_server(MSG_EXITING
, NULL
, 0);
573 fatalx("unexpected message");
580 /* Dispatch imsgs in attached state (after MSG_READY). */
582 client_dispatch_attached(void)
585 struct msg_lock_data lockdata
;
586 struct sigaction sigact
;
590 if ((n
= imsg_get(&client_ibuf
, &imsg
)) == -1)
591 fatalx("imsg_get failed");
594 datalen
= imsg
.hdr
.len
- IMSG_HEADER_SIZE
;
596 log_debug("got %d from server", imsg
.hdr
.type
);
597 switch (imsg
.hdr
.type
) {
601 fatalx("bad MSG_DETACH size");
603 client_exittype
= imsg
.hdr
.type
;
604 if (imsg
.hdr
.type
== MSG_DETACHKILL
)
605 client_exitreason
= CLIENT_EXIT_DETACHED_HUP
;
607 client_exitreason
= CLIENT_EXIT_DETACHED
;
608 client_write_server(MSG_EXITING
, NULL
, 0);
612 datalen
!= sizeof (struct msg_exit_data
))
613 fatalx("bad MSG_EXIT size");
615 client_write_server(MSG_EXITING
, NULL
, 0);
616 client_exitreason
= CLIENT_EXIT_EXITED
;
620 fatalx("bad MSG_EXITED size");
626 fatalx("bad MSG_SHUTDOWN size");
628 client_write_server(MSG_EXITING
, NULL
, 0);
629 client_exitreason
= CLIENT_EXIT_SERVER_EXITED
;
634 fatalx("bad MSG_SUSPEND size");
636 memset(&sigact
, 0, sizeof sigact
);
637 sigemptyset(&sigact
.sa_mask
);
638 sigact
.sa_flags
= SA_RESTART
;
639 sigact
.sa_handler
= SIG_DFL
;
640 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
641 fatal("sigaction failed");
642 kill(getpid(), SIGTSTP
);
645 if (datalen
!= sizeof lockdata
)
646 fatalx("bad MSG_LOCK size");
647 memcpy(&lockdata
, imsg
.data
, sizeof lockdata
);
649 lockdata
.cmd
[(sizeof lockdata
.cmd
) - 1] = '\0';
650 system(lockdata
.cmd
);
651 client_write_server(MSG_UNLOCK
, NULL
, 0);
654 fatalx("unexpected message");