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) {
125 if (unlink(path
) != 0 && errno
!= ENOENT
) {
130 fd
= server_start(lockfd
, lockfile
);
143 /* Get exit string from reason number. */
145 client_exit_message(void)
147 static char msg
[256];
149 switch (client_exitreason
) {
150 case CLIENT_EXIT_NONE
:
152 case CLIENT_EXIT_DETACHED
:
153 if (client_exitsession
!= NULL
) {
154 xsnprintf(msg
, sizeof msg
, "detached "
155 "(from session %s)", client_exitsession
);
159 case CLIENT_EXIT_DETACHED_HUP
:
160 if (client_exitsession
!= NULL
) {
161 xsnprintf(msg
, sizeof msg
, "detached and SIGHUP "
162 "(from session %s)", client_exitsession
);
165 return ("detached and SIGHUP");
166 case CLIENT_EXIT_LOST_TTY
:
168 case CLIENT_EXIT_TERMINATED
:
169 return ("terminated");
170 case CLIENT_EXIT_LOST_SERVER
:
171 return ("lost server");
172 case CLIENT_EXIT_EXITED
:
174 case CLIENT_EXIT_SERVER_EXITED
:
175 return ("server exited");
177 return ("unknown reason");
180 /* Client main loop. */
182 client_main(int argc
, char **argv
, int flags
)
185 struct cmd_list
*cmdlist
;
186 struct msg_command_data
*data
;
191 struct termios tio
, saved_tio
;
194 /* Set up the initial command. */
196 if (shell_cmd
!= NULL
) {
198 cmdflags
= CMD_STARTSERVER
;
199 } else if (argc
== 0) {
201 cmdflags
= CMD_STARTSERVER
|CMD_CANTNEST
;
206 * It sucks parsing the command string twice (in client and
207 * later in server) but it is necessary to get the start server
210 cmdlist
= cmd_list_parse(argc
, argv
, NULL
, 0, &cause
);
211 if (cmdlist
== NULL
) {
212 fprintf(stderr
, "%s\n", cause
);
215 cmdflags
&= ~CMD_STARTSERVER
;
216 TAILQ_FOREACH(cmd
, &cmdlist
->list
, qentry
) {
217 if (cmd
->entry
->flags
& CMD_STARTSERVER
)
218 cmdflags
|= CMD_STARTSERVER
;
219 if (cmd
->entry
->flags
& CMD_CANTNEST
)
220 cmdflags
|= CMD_CANTNEST
;
222 cmd_list_free(cmdlist
);
226 * Check if this could be a nested session, if the command can't nest:
227 * if the socket path matches $TMUX, this is probably the same server.
229 if (shell_cmd
== NULL
&& environ_path
!= NULL
&&
230 (cmdflags
& CMD_CANTNEST
) &&
231 strcmp(socket_path
, environ_path
) == 0) {
232 fprintf(stderr
, "sessions should be nested with care, "
233 "unset $TMUX to force\n");
237 /* Initialise the client socket and start the server. */
238 fd
= client_connect(socket_path
, cmdflags
& CMD_STARTSERVER
);
240 fprintf(stderr
, "failed to connect to server: %s\n",
245 /* Set process title, log and signals now this is the client. */
246 #ifdef HAVE_SETPROCTITLE
247 setproctitle("client (%s)", socket_path
);
252 imsg_init(&client_ibuf
, fd
);
253 event_set(&client_event
, fd
, EV_READ
, client_callback
, shell_cmd
);
255 /* Create stdin handler. */
256 setblocking(STDIN_FILENO
, 0);
257 event_set(&client_stdin
, STDIN_FILENO
, EV_READ
|EV_PERSIST
,
258 client_stdin_callback
, NULL
);
259 if (flags
& CLIENT_CONTROLCONTROL
) {
260 if (tcgetattr(STDIN_FILENO
, &saved_tio
) != 0) {
261 fprintf(stderr
, "tcgetattr failed: %s\n",
266 tio
.c_iflag
= ICRNL
|IXANY
;
267 tio
.c_oflag
= OPOST
|ONLCR
;
269 tio
.c_lflag
= NOKERNINFO
;
271 tio
.c_cflag
= CREAD
|CS8
|HUPCL
;
274 cfsetispeed(&tio
, cfgetispeed(&saved_tio
));
275 cfsetospeed(&tio
, cfgetospeed(&saved_tio
));
276 tcsetattr(STDIN_FILENO
, TCSANOW
, &tio
);
279 /* Establish signal handlers. */
280 set_signals(client_signal
);
282 /* Send identify messages. */
283 client_send_identify(flags
);
285 /* Send first command. */
286 if (msg
== MSG_COMMAND
) {
287 /* How big is the command? */
289 for (i
= 0; i
< argc
; i
++)
290 size
+= strlen(argv
[i
]) + 1;
291 data
= xmalloc((sizeof *data
) + size
);
293 /* Prepare command for server. */
295 if (cmd_pack_argv(argc
, argv
, (char*)(data
+ 1), size
) != 0) {
296 fprintf(stderr
, "command too long\n");
300 size
+= sizeof *data
;
302 /* Send the command. */
303 if (client_write_server(msg
, data
, size
) != 0) {
304 fprintf(stderr
, "failed to send command\n");
309 } else if (msg
== MSG_SHELL
)
310 client_write_server(msg
, NULL
, 0);
312 /* Set the event and dispatch. */
313 client_update_event();
316 /* Print the exit message, if any, and exit. */
317 if (client_attached
) {
318 if (client_exitreason
!= CLIENT_EXIT_NONE
&& !login_shell
)
319 printf("[%s]\n", client_exit_message());
322 if (client_exittype
== MSG_DETACHKILL
&& ppid
> 1)
324 } else if (flags
& CLIENT_CONTROLCONTROL
) {
325 if (client_exitreason
!= CLIENT_EXIT_NONE
)
326 printf("%%exit %s\n", client_exit_message());
330 tcsetattr(STDOUT_FILENO
, TCSAFLUSH
, &saved_tio
);
332 setblocking(STDIN_FILENO
, 1);
333 return (client_exitval
);
336 /* Send identify messages to server. */
338 client_send_identify(int flags
)
344 client_write_one(MSG_IDENTIFY_FLAGS
, -1, &flags
, sizeof flags
);
346 if ((s
= getenv("TERM")) == NULL
)
348 client_write_one(MSG_IDENTIFY_TERM
, -1, s
, strlen(s
) + 1);
350 if ((s
= ttyname(STDIN_FILENO
)) == NULL
)
352 client_write_one(MSG_IDENTIFY_TTYNAME
, -1, s
, strlen(s
) + 1);
354 if ((fd
= open(".", O_RDONLY
)) == -1)
355 fd
= open("/", O_RDONLY
);
356 client_write_one(MSG_IDENTIFY_CWD
, fd
, NULL
, 0);
358 if ((fd
= dup(STDIN_FILENO
)) == -1)
360 client_write_one(MSG_IDENTIFY_STDIN
, fd
, NULL
, 0);
362 for (ss
= environ
; *ss
!= NULL
; ss
++)
363 client_write_one(MSG_IDENTIFY_ENVIRON
, -1, *ss
, strlen(*ss
) + 1);
365 client_write_one(MSG_IDENTIFY_DONE
, -1, NULL
, 0);
367 client_update_event();
370 /* Helper to send one message. */
372 client_write_one(enum msgtype type
, int fd
, const void *buf
, size_t len
)
376 retval
= imsg_compose(&client_ibuf
, type
, PROTOCOL_VERSION
, -1, fd
,
377 __UNCONST(buf
), len
);
383 /* Write a message to the server without a file descriptor. */
385 client_write_server(enum msgtype type
, const void *buf
, size_t len
)
389 retval
= client_write_one(type
, -1, buf
, len
);
391 client_update_event();
395 /* Update client event based on whether it needs to read or read and write. */
397 client_update_event(void)
401 event_del(&client_event
);
403 if (client_ibuf
.w
.queued
> 0)
406 &client_event
, client_ibuf
.fd
, events
, client_callback
, shell_cmd
);
407 event_add(&client_event
, NULL
);
410 /* Callback to handle signals in the client. */
412 client_signal(int sig
, unused
short events
, unused
void *data
)
414 struct sigaction sigact
;
417 if (!client_attached
) {
420 waitpid(WAIT_ANY
, &status
, WNOHANG
);
423 event_loopexit(NULL
);
429 client_exitreason
= CLIENT_EXIT_LOST_TTY
;
431 client_write_server(MSG_EXITING
, NULL
, 0);
434 client_exitreason
= CLIENT_EXIT_TERMINATED
;
436 client_write_server(MSG_EXITING
, NULL
, 0);
439 client_write_server(MSG_RESIZE
, NULL
, 0);
442 memset(&sigact
, 0, sizeof sigact
);
443 sigemptyset(&sigact
.sa_mask
);
444 sigact
.sa_flags
= SA_RESTART
;
445 sigact
.sa_handler
= SIG_IGN
;
446 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
447 fatal("sigaction failed");
448 client_write_server(MSG_WAKEUP
, NULL
, 0);
453 client_update_event();
456 /* Callback for client imsg read events. */
458 client_callback(unused
int fd
, short events
, void *data
)
463 if (events
& EV_READ
) {
464 if ((n
= imsg_read(&client_ibuf
)) == -1 || n
== 0)
467 retval
= client_dispatch_attached();
469 retval
= client_dispatch_wait(data
);
471 event_loopexit(NULL
);
476 if (events
& EV_WRITE
) {
477 if (msgbuf_write(&client_ibuf
.w
) < 0 && errno
!= EAGAIN
)
481 client_update_event();
485 client_exitreason
= CLIENT_EXIT_LOST_SERVER
;
487 event_loopexit(NULL
);
490 /* Callback for client stdin read events. */
492 client_stdin_callback(unused
int fd
, unused
short events
, unused
void *data1
)
494 struct msg_stdin_data data
;
496 data
.size
= read(STDIN_FILENO
, data
.data
, sizeof data
.data
);
497 if (data
.size
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
500 client_write_server(MSG_STDIN
, &data
, sizeof data
);
502 event_del(&client_stdin
);
503 client_update_event();
506 /* Force write to file descriptor. */
508 client_write(int fd
, const char *data
, size_t size
)
513 used
= write(fd
, data
, size
);
515 if (errno
== EINTR
|| errno
== EAGAIN
)
524 /* Dispatch imsgs when in wait state (before MSG_READY). */
526 client_dispatch_wait(void *data0
)
531 struct msg_stdout_data stdoutdata
;
532 struct msg_stderr_data stderrdata
;
536 if ((n
= imsg_get(&client_ibuf
, &imsg
)) == -1)
537 fatalx("imsg_get failed");
542 datalen
= imsg
.hdr
.len
- IMSG_HEADER_SIZE
;
544 log_debug("got %d from server", imsg
.hdr
.type
);
545 switch (imsg
.hdr
.type
) {
548 if (datalen
!= sizeof retval
&& datalen
!= 0)
549 fatalx("bad MSG_EXIT size");
550 if (datalen
== sizeof retval
) {
551 memcpy(&retval
, data
, sizeof retval
);
552 client_exitval
= retval
;
558 fatalx("bad MSG_READY size");
560 event_del(&client_stdin
);
562 client_write_server(MSG_RESIZE
, NULL
, 0);
566 fatalx("bad MSG_STDIN size");
568 event_add(&client_stdin
, NULL
);
571 if (datalen
!= sizeof stdoutdata
)
572 fatalx("bad MSG_STDOUT size");
573 memcpy(&stdoutdata
, data
, sizeof stdoutdata
);
575 client_write(STDOUT_FILENO
, stdoutdata
.data
,
579 if (datalen
!= sizeof stderrdata
)
580 fatalx("bad MSG_STDERR size");
581 memcpy(&stderrdata
, data
, sizeof stderrdata
);
583 client_write(STDERR_FILENO
, stderrdata
.data
,
588 fatalx("bad MSG_VERSION size");
590 fprintf(stderr
, "protocol version mismatch "
591 "(client %u, server %u)\n", PROTOCOL_VERSION
,
598 if (datalen
== 0 || data
[datalen
- 1] != '\0')
599 fatalx("bad MSG_SHELL string");
602 shell_exec(data
, data0
);
606 client_write_server(MSG_EXITING
, NULL
, 0);
617 /* Dispatch imsgs in attached state (after MSG_READY). */
619 client_dispatch_attached(void)
622 struct sigaction sigact
;
627 if ((n
= imsg_get(&client_ibuf
, &imsg
)) == -1)
628 fatalx("imsg_get failed");
633 datalen
= imsg
.hdr
.len
- IMSG_HEADER_SIZE
;
635 log_debug("got %d from server", imsg
.hdr
.type
);
636 switch (imsg
.hdr
.type
) {
639 if (datalen
== 0 || data
[datalen
- 1] != '\0')
640 fatalx("bad MSG_DETACH string");
642 client_exitsession
= xstrdup(data
);
643 client_exittype
= imsg
.hdr
.type
;
644 if (imsg
.hdr
.type
== MSG_DETACHKILL
)
645 client_exitreason
= CLIENT_EXIT_DETACHED_HUP
;
647 client_exitreason
= CLIENT_EXIT_DETACHED
;
648 client_write_server(MSG_EXITING
, NULL
, 0);
651 if (datalen
!= 0 && datalen
!= sizeof (int))
652 fatalx("bad MSG_EXIT size");
654 client_write_server(MSG_EXITING
, NULL
, 0);
655 client_exitreason
= CLIENT_EXIT_EXITED
;
659 fatalx("bad MSG_EXITED size");
665 fatalx("bad MSG_SHUTDOWN size");
667 client_write_server(MSG_EXITING
, NULL
, 0);
668 client_exitreason
= CLIENT_EXIT_SERVER_EXITED
;
673 fatalx("bad MSG_SUSPEND size");
675 memset(&sigact
, 0, sizeof sigact
);
676 sigemptyset(&sigact
.sa_mask
);
677 sigact
.sa_flags
= SA_RESTART
;
678 sigact
.sa_handler
= SIG_DFL
;
679 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
680 fatal("sigaction failed");
681 kill(getpid(), SIGTSTP
);
684 if (datalen
== 0 || data
[datalen
- 1] != '\0')
685 fatalx("bad MSG_LOCK string");
688 client_write_server(MSG_UNLOCK
, NULL
, 0);