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
;
51 const char *client_exitsession
;
54 int client_get_lock(char *);
55 int client_connect(char *, int);
56 void client_send_identify(int);
57 int client_write_one(enum msgtype
, int, const void *, size_t);
58 int client_write_server(enum msgtype
, const void *, size_t);
59 void client_update_event(void);
60 void client_signal(int, short, void *);
61 void client_stdin_callback(int, short, void *);
62 void client_write(int, const char *, size_t);
63 void client_callback(int, short, void *);
64 int client_dispatch_attached(void);
65 int client_dispatch_wait(void *);
66 const char *client_exit_message(void);
69 * Get server create lock. If already held then server start is happening in
70 * another client, so block until the lock is released and return -1 to
71 * retry. Ignore other errors - just continue and start the server without the
75 client_get_lock(char *lockfile
)
79 if ((lockfd
= open(lockfile
, O_WRONLY
|O_CREAT
, 0600)) == -1)
82 if (lockf(lockfd
, F_TLOCK
, 0) == -1 && errno
== EAGAIN
) {
83 while (lockf(lockfd
, F_LOCK
, 0) == -1 && errno
== EINTR
)
92 /* Connect client to server. */
94 client_connect(char *path
, int start_server
)
96 struct sockaddr_un sa
;
101 memset(&sa
, 0, sizeof sa
);
102 sa
.sun_family
= AF_UNIX
;
103 size
= strlcpy(sa
.sun_path
, path
, sizeof sa
.sun_path
);
104 if (size
>= sizeof sa
.sun_path
) {
105 errno
= ENAMETOOLONG
;
110 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) == -1)
111 fatal("socket failed");
113 if (connect(fd
, (struct sockaddr
*) &sa
, SUN_LEN(&sa
)) == -1) {
114 if (errno
!= ECONNREFUSED
&& errno
!= ENOENT
)
120 xasprintf(&lockfile
, "%s.lock", path
);
121 if ((lockfd
= client_get_lock(lockfile
)) == -1)
123 if (unlink(path
) != 0 && errno
!= ENOENT
)
125 fd
= server_start(lockfd
, lockfile
);
138 /* Get exit string from reason number. */
140 client_exit_message(void)
142 static char msg
[256];
144 switch (client_exitreason
) {
145 case CLIENT_EXIT_NONE
:
147 case CLIENT_EXIT_DETACHED
:
148 if (client_exitsession
!= NULL
) {
149 xsnprintf(msg
, sizeof msg
, "detached "
150 "(from session %s)", client_exitsession
);
154 case CLIENT_EXIT_DETACHED_HUP
:
155 if (client_exitsession
!= NULL
) {
156 xsnprintf(msg
, sizeof msg
, "detached and SIGHUP "
157 "(from session %s)", client_exitsession
);
160 return ("detached and SIGHUP");
161 case CLIENT_EXIT_LOST_TTY
:
163 case CLIENT_EXIT_TERMINATED
:
164 return ("terminated");
165 case CLIENT_EXIT_LOST_SERVER
:
166 return ("lost server");
167 case CLIENT_EXIT_EXITED
:
169 case CLIENT_EXIT_SERVER_EXITED
:
170 return ("server exited");
172 return ("unknown reason");
175 /* Client main loop. */
177 client_main(int argc
, char **argv
, int flags
)
180 struct cmd_list
*cmdlist
;
181 struct msg_command_data
*data
;
186 struct termios tio
, saved_tio
;
189 /* Set up the initial command. */
191 if (shell_cmd
!= NULL
) {
193 cmdflags
= CMD_STARTSERVER
;
194 } else if (argc
== 0) {
196 cmdflags
= CMD_STARTSERVER
|CMD_CANTNEST
;
201 * It sucks parsing the command string twice (in client and
202 * later in server) but it is necessary to get the start server
205 cmdlist
= cmd_list_parse(argc
, argv
, NULL
, 0, &cause
);
206 if (cmdlist
== NULL
) {
207 fprintf(stderr
, "%s\n", cause
);
210 cmdflags
&= ~CMD_STARTSERVER
;
211 TAILQ_FOREACH(cmd
, &cmdlist
->list
, qentry
) {
212 if (cmd
->entry
->flags
& CMD_STARTSERVER
)
213 cmdflags
|= CMD_STARTSERVER
;
214 if (cmd
->entry
->flags
& CMD_CANTNEST
)
215 cmdflags
|= CMD_CANTNEST
;
217 cmd_list_free(cmdlist
);
221 * Check if this could be a nested session, if the command can't nest:
222 * if the socket path matches $TMUX, this is probably the same server.
224 if (shell_cmd
== NULL
&& environ_path
!= NULL
&&
225 (cmdflags
& CMD_CANTNEST
) &&
226 strcmp(socket_path
, environ_path
) == 0) {
227 fprintf(stderr
, "sessions should be nested with care, "
228 "unset $TMUX to force\n");
232 /* Initialise the client socket and start the server. */
233 fd
= client_connect(socket_path
, cmdflags
& CMD_STARTSERVER
);
235 fprintf(stderr
, "failed to connect to server\n");
239 /* Set process title, log and signals now this is the client. */
240 setproctitle("client (%s)", socket_path
);
244 imsg_init(&client_ibuf
, fd
);
245 event_set(&client_event
, fd
, EV_READ
, client_callback
, shell_cmd
);
247 /* Create stdin handler. */
248 setblocking(STDIN_FILENO
, 0);
249 event_set(&client_stdin
, STDIN_FILENO
, EV_READ
|EV_PERSIST
,
250 client_stdin_callback
, NULL
);
251 if (flags
& CLIENT_CONTROLCONTROL
) {
252 if (tcgetattr(STDIN_FILENO
, &saved_tio
) != 0) {
253 fprintf(stderr
, "tcgetattr failed: %s\n",
258 tio
.c_iflag
= ICRNL
|IXANY
;
259 tio
.c_oflag
= OPOST
|ONLCR
;
260 tio
.c_lflag
= NOKERNINFO
;
261 tio
.c_cflag
= CREAD
|CS8
|HUPCL
;
264 cfsetispeed(&tio
, cfgetispeed(&saved_tio
));
265 cfsetospeed(&tio
, cfgetospeed(&saved_tio
));
266 tcsetattr(STDIN_FILENO
, TCSANOW
, &tio
);
269 /* Establish signal handlers. */
270 set_signals(client_signal
);
272 /* Send identify messages. */
273 client_send_identify(flags
);
275 /* Send first command. */
276 if (msg
== MSG_COMMAND
) {
277 /* How big is the command? */
279 for (i
= 0; i
< argc
; i
++)
280 size
+= strlen(argv
[i
]) + 1;
281 data
= xmalloc((sizeof *data
) + size
);
283 /* Fill in command line arguments. */
284 data
->pid
= environ_pid
;
285 data
->session_id
= environ_session_id
;
287 /* Prepare command for server. */
289 if (cmd_pack_argv(argc
, argv
, (char*)(data
+ 1), size
) != 0) {
290 fprintf(stderr
, "command too long\n");
294 size
+= sizeof *data
;
296 /* Send the command. */
297 if (client_write_server(msg
, data
, size
) != 0) {
298 fprintf(stderr
, "failed to send command\n");
303 } else if (msg
== MSG_SHELL
)
304 client_write_server(msg
, NULL
, 0);
306 /* Set the event and dispatch. */
307 client_update_event();
310 /* Print the exit message, if any, and exit. */
311 if (client_attached
) {
312 if (client_exitreason
!= CLIENT_EXIT_NONE
&& !login_shell
)
313 printf("[%s]\n", client_exit_message());
316 if (client_exittype
== MSG_DETACHKILL
&& ppid
> 1)
318 } else if (flags
& CLIENT_CONTROLCONTROL
) {
319 if (client_exitreason
!= CLIENT_EXIT_NONE
)
320 printf("%%exit %s\n", client_exit_message());
324 tcsetattr(STDOUT_FILENO
, TCSAFLUSH
, &saved_tio
);
326 setblocking(STDIN_FILENO
, 1);
327 return (client_exitval
);
330 /* Send identify messages to server. */
332 client_send_identify(int flags
)
338 client_write_one(MSG_IDENTIFY_FLAGS
, -1, &flags
, sizeof flags
);
340 if ((s
= getenv("TERM")) == NULL
)
342 client_write_one(MSG_IDENTIFY_TERM
, -1, s
, strlen(s
) + 1);
344 if ((s
= ttyname(STDIN_FILENO
)) == NULL
)
346 client_write_one(MSG_IDENTIFY_TTYNAME
, -1, s
, strlen(s
) + 1);
348 if ((fd
= open(".", O_RDONLY
)) == -1)
349 fd
= open("/", O_RDONLY
);
350 client_write_one(MSG_IDENTIFY_CWD
, fd
, NULL
, 0);
352 if ((fd
= dup(STDIN_FILENO
)) == -1)
354 client_write_one(MSG_IDENTIFY_STDIN
, fd
, NULL
, 0);
356 for (ss
= environ
; *ss
!= NULL
; ss
++)
357 client_write_one(MSG_IDENTIFY_ENVIRON
, -1, *ss
, strlen(*ss
) + 1);
358 client_write_one(MSG_IDENTIFY_DONE
, -1, NULL
, 0);
360 client_update_event();
363 /* Helper to send one message. */
365 client_write_one(enum msgtype type
, int fd
, const void *buf
, size_t len
)
369 retval
= imsg_compose(&client_ibuf
, type
, PROTOCOL_VERSION
, -1, fd
,
376 /* Write a message to the server without a file descriptor. */
378 client_write_server(enum msgtype type
, const void *buf
, size_t len
)
382 retval
= client_write_one(type
, -1, buf
, len
);
384 client_update_event();
388 /* Update client event based on whether it needs to read or read and write. */
390 client_update_event(void)
394 event_del(&client_event
);
396 if (client_ibuf
.w
.queued
> 0)
399 &client_event
, client_ibuf
.fd
, events
, client_callback
, shell_cmd
);
400 event_add(&client_event
, NULL
);
403 /* Callback to handle signals in the client. */
405 client_signal(int sig
, unused
short events
, unused
void *data
)
407 struct sigaction sigact
;
410 if (!client_attached
) {
413 waitpid(WAIT_ANY
, &status
, WNOHANG
);
416 event_loopexit(NULL
);
422 client_exitreason
= CLIENT_EXIT_LOST_TTY
;
424 client_write_server(MSG_EXITING
, NULL
, 0);
427 client_exitreason
= CLIENT_EXIT_TERMINATED
;
429 client_write_server(MSG_EXITING
, NULL
, 0);
432 client_write_server(MSG_RESIZE
, NULL
, 0);
435 memset(&sigact
, 0, sizeof sigact
);
436 sigemptyset(&sigact
.sa_mask
);
437 sigact
.sa_flags
= SA_RESTART
;
438 sigact
.sa_handler
= SIG_IGN
;
439 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
440 fatal("sigaction failed");
441 client_write_server(MSG_WAKEUP
, NULL
, 0);
446 client_update_event();
449 /* Callback for client imsg read events. */
451 client_callback(unused
int fd
, short events
, void *data
)
456 if (events
& EV_READ
) {
457 if ((n
= imsg_read(&client_ibuf
)) == -1 || n
== 0)
460 retval
= client_dispatch_attached();
462 retval
= client_dispatch_wait(data
);
464 event_loopexit(NULL
);
469 if (events
& EV_WRITE
) {
470 if (msgbuf_write(&client_ibuf
.w
) < 0)
474 client_update_event();
478 client_exitreason
= CLIENT_EXIT_LOST_SERVER
;
480 event_loopexit(NULL
);
483 /* Callback for client stdin read events. */
485 client_stdin_callback(unused
int fd
, unused
short events
, unused
void *data1
)
487 struct msg_stdin_data data
;
489 data
.size
= read(STDIN_FILENO
, data
.data
, sizeof data
.data
);
490 if (data
.size
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
493 client_write_server(MSG_STDIN
, &data
, sizeof data
);
495 event_del(&client_stdin
);
496 client_update_event();
499 /* Force write to file descriptor. */
501 client_write(int fd
, const char *data
, size_t size
)
506 used
= write(fd
, data
, size
);
508 if (errno
== EINTR
|| errno
== EAGAIN
)
517 /* Dispatch imsgs when in wait state (before MSG_READY). */
519 client_dispatch_wait(void *data0
)
524 struct msg_stdout_data stdoutdata
;
525 struct msg_stderr_data stderrdata
;
529 if ((n
= imsg_get(&client_ibuf
, &imsg
)) == -1)
530 fatalx("imsg_get failed");
535 datalen
= imsg
.hdr
.len
- IMSG_HEADER_SIZE
;
537 log_debug("got %d from server", imsg
.hdr
.type
);
538 switch (imsg
.hdr
.type
) {
541 if (datalen
!= sizeof retval
&& datalen
!= 0)
542 fatalx("bad MSG_EXIT size");
543 if (datalen
== sizeof retval
) {
544 memcpy(&retval
, data
, sizeof retval
);
545 client_exitval
= retval
;
551 fatalx("bad MSG_READY size");
553 event_del(&client_stdin
);
555 client_write_server(MSG_RESIZE
, NULL
, 0);
559 fatalx("bad MSG_STDIN size");
561 event_add(&client_stdin
, NULL
);
564 if (datalen
!= sizeof stdoutdata
)
565 fatalx("bad MSG_STDOUT size");
566 memcpy(&stdoutdata
, data
, sizeof stdoutdata
);
568 client_write(STDOUT_FILENO
, stdoutdata
.data
,
572 if (datalen
!= sizeof stderrdata
)
573 fatalx("bad MSG_STDERR size");
574 memcpy(&stderrdata
, data
, sizeof stderrdata
);
576 client_write(STDERR_FILENO
, stderrdata
.data
,
581 fatalx("bad MSG_VERSION size");
583 fprintf(stderr
, "protocol version mismatch "
584 "(client %u, server %u)\n", PROTOCOL_VERSION
,
591 if (datalen
== 0 || data
[datalen
- 1] != '\0')
592 fatalx("bad MSG_SHELL string");
595 shell_exec(data
, data0
);
599 client_write_server(MSG_EXITING
, NULL
, 0);
610 /* Dispatch imsgs in attached state (after MSG_READY). */
612 client_dispatch_attached(void)
615 struct sigaction sigact
;
620 if ((n
= imsg_get(&client_ibuf
, &imsg
)) == -1)
621 fatalx("imsg_get failed");
626 datalen
= imsg
.hdr
.len
- IMSG_HEADER_SIZE
;
628 log_debug("got %d from server", imsg
.hdr
.type
);
629 switch (imsg
.hdr
.type
) {
632 if (datalen
== 0 || data
[datalen
- 1] != '\0')
633 fatalx("bad MSG_DETACH string");
635 client_exitsession
= xstrdup(data
);
636 client_exittype
= imsg
.hdr
.type
;
637 if (imsg
.hdr
.type
== MSG_DETACHKILL
)
638 client_exitreason
= CLIENT_EXIT_DETACHED_HUP
;
640 client_exitreason
= CLIENT_EXIT_DETACHED
;
641 client_write_server(MSG_EXITING
, NULL
, 0);
644 if (datalen
!= 0 && datalen
!= sizeof (int))
645 fatalx("bad MSG_EXIT size");
647 client_write_server(MSG_EXITING
, NULL
, 0);
648 client_exitreason
= CLIENT_EXIT_EXITED
;
652 fatalx("bad MSG_EXITED size");
658 fatalx("bad MSG_SHUTDOWN size");
660 client_write_server(MSG_EXITING
, NULL
, 0);
661 client_exitreason
= CLIENT_EXIT_SERVER_EXITED
;
666 fatalx("bad MSG_SUSPEND size");
668 memset(&sigact
, 0, sizeof sigact
);
669 sigemptyset(&sigact
.sa_mask
);
670 sigact
.sa_flags
= SA_RESTART
;
671 sigact
.sa_handler
= SIG_DFL
;
672 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
673 fatal("sigaction failed");
674 kill(getpid(), SIGTSTP
);
677 if (datalen
== 0 || data
[datalen
- 1] != '\0')
678 fatalx("bad MSG_LOCK string");
681 client_write_server(MSG_UNLOCK
, NULL
, 0);