4 * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
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>
20 #include <sys/socket.h>
36 static struct tmuxproc
*client_proc
;
37 static struct tmuxpeer
*client_peer
;
38 static uint64_t client_flags
;
39 static int client_suspended
;
43 CLIENT_EXIT_DETACHED_HUP
,
45 CLIENT_EXIT_TERMINATED
,
46 CLIENT_EXIT_LOST_SERVER
,
48 CLIENT_EXIT_SERVER_EXITED
,
49 CLIENT_EXIT_MESSAGE_PROVIDED
50 } client_exitreason
= CLIENT_EXIT_NONE
;
51 static int client_exitflag
;
52 static int client_exitval
;
53 static enum msgtype client_exittype
;
54 static const char *client_exitsession
;
55 static char *client_exitmessage
;
56 static const char *client_execshell
;
57 static const char *client_execcmd
;
58 static int client_attached
;
59 static struct client_files client_files
= RB_INITIALIZER(&client_files
);
61 static __dead
void client_exec(const char *,const char *);
62 static int client_get_lock(char *);
63 static int client_connect(struct event_base
*, const char *,
65 static void client_send_identify(const char *, const char *,
66 char **, u_int
, const char *, int);
67 static void client_signal(int);
68 static void client_dispatch(struct imsg
*, void *);
69 static void client_dispatch_attached(struct imsg
*);
70 static void client_dispatch_wait(struct imsg
*);
71 static const char *client_exit_message(void);
74 * Get server create lock. If already held then server start is happening in
75 * another client, so block until the lock is released and return -2 to
76 * retry. Return -1 on failure to continue and start the server anyway.
79 client_get_lock(char *lockfile
)
83 log_debug("lock file is %s", lockfile
);
85 if ((lockfd
= open(lockfile
, O_WRONLY
|O_CREAT
, 0600)) == -1) {
86 log_debug("open failed: %s", strerror(errno
));
90 if (flock(lockfd
, LOCK_EX
|LOCK_NB
) == -1) {
91 log_debug("flock failed: %s", strerror(errno
));
94 while (flock(lockfd
, LOCK_EX
) == -1 && errno
== EINTR
)
99 log_debug("flock succeeded");
104 /* Connect client to server. */
106 client_connect(struct event_base
*base
, const char *path
, uint64_t flags
)
108 struct sockaddr_un sa
;
110 int fd
, lockfd
= -1, locked
= 0;
111 char *lockfile
= NULL
;
113 memset(&sa
, 0, sizeof sa
);
114 sa
.sun_family
= AF_UNIX
;
115 size
= strlcpy(sa
.sun_path
, path
, sizeof sa
.sun_path
);
116 if (size
>= sizeof sa
.sun_path
) {
117 errno
= ENAMETOOLONG
;
120 log_debug("socket is %s", path
);
123 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) == -1)
126 log_debug("trying connect");
127 if (connect(fd
, (struct sockaddr
*)&sa
, sizeof sa
) == -1) {
128 log_debug("connect failed: %s", strerror(errno
));
129 if (errno
!= ECONNREFUSED
&& errno
!= ENOENT
)
131 if (flags
& CLIENT_NOSTARTSERVER
)
133 if (~flags
& CLIENT_STARTSERVER
)
138 xasprintf(&lockfile
, "%s.lock", path
);
139 if ((lockfd
= client_get_lock(lockfile
)) < 0) {
140 log_debug("didn't get lock (%d)", lockfd
);
148 log_debug("got lock (%d)", lockfd
);
151 * Always retry at least once, even if we got the lock,
152 * because another client could have taken the lock,
153 * started the server and released the lock between our
154 * connect() and flock().
160 if (lockfd
>= 0 && unlink(path
) != 0 && errno
!= ENOENT
) {
165 fd
= server_start(client_proc
, flags
, base
, lockfd
, lockfile
);
168 if (locked
&& lockfd
>= 0) {
184 /* Get exit string from reason number. */
186 client_exit_message(void)
188 static char msg
[256];
190 switch (client_exitreason
) {
191 case CLIENT_EXIT_NONE
:
193 case CLIENT_EXIT_DETACHED
:
194 if (client_exitsession
!= NULL
) {
195 xsnprintf(msg
, sizeof msg
, "detached "
196 "(from session %s)", client_exitsession
);
200 case CLIENT_EXIT_DETACHED_HUP
:
201 if (client_exitsession
!= NULL
) {
202 xsnprintf(msg
, sizeof msg
, "detached and SIGHUP "
203 "(from session %s)", client_exitsession
);
206 return ("detached and SIGHUP");
207 case CLIENT_EXIT_LOST_TTY
:
209 case CLIENT_EXIT_TERMINATED
:
210 return ("terminated");
211 case CLIENT_EXIT_LOST_SERVER
:
212 return ("server exited unexpectedly");
213 case CLIENT_EXIT_EXITED
:
215 case CLIENT_EXIT_SERVER_EXITED
:
216 return ("server exited");
217 case CLIENT_EXIT_MESSAGE_PROVIDED
:
218 return (client_exitmessage
);
220 return ("unknown reason");
223 /* Exit if all streams flushed. */
227 if (!file_write_left(&client_files
))
228 proc_exit(client_proc
);
231 /* Client main loop. */
233 client_main(struct event_base
*base
, int argc
, char **argv
, uint64_t flags
,
236 struct cmd_parse_result
*pr
;
237 struct msg_command
*data
;
239 const char *ttynam
, *termname
, *cwd
;
242 struct termios tio
, saved_tio
;
243 size_t size
, linesize
= 0;
245 char *line
= NULL
, **caps
= NULL
, *cause
;
247 struct args_value
*values
;
249 /* Set up the initial command. */
250 if (shell_command
!= NULL
) {
252 flags
|= CLIENT_STARTSERVER
;
253 } else if (argc
== 0) {
255 flags
|= CLIENT_STARTSERVER
;
260 * It's annoying parsing the command string twice (in client
261 * and later in server) but it is necessary to get the start
264 values
= args_from_vector(argc
, argv
);
265 pr
= cmd_parse_from_arguments(values
, argc
, NULL
);
266 if (pr
->status
== CMD_PARSE_SUCCESS
) {
267 if (cmd_list_any_have(pr
->cmdlist
, CMD_STARTSERVER
))
268 flags
|= CLIENT_STARTSERVER
;
269 cmd_list_free(pr
->cmdlist
);
272 args_free_values(values
, argc
);
276 /* Create client process structure (starts logging). */
277 client_proc
= proc_start("client");
278 proc_set_signals(client_proc
, client_signal
);
280 /* Save the flags. */
281 client_flags
= flags
;
282 log_debug("flags are %#llx", (unsigned long long)client_flags
);
284 /* Initialize the client socket and start the server. */
285 fd
= client_connect(base
, socket_path
, client_flags
);
287 if (errno
== ECONNREFUSED
) {
288 fprintf(stderr
, "no server running on %s\n",
291 fprintf(stderr
, "error connecting to %s (%s)\n",
292 socket_path
, strerror(errno
));
296 client_peer
= proc_add_peer(client_proc
, fd
, client_dispatch
, NULL
);
298 /* Save these before pledge(). */
299 if ((cwd
= find_cwd()) == NULL
&& (cwd
= find_home()) == NULL
)
301 if ((ttynam
= ttyname(STDIN_FILENO
)) == NULL
)
303 if ((termname
= getenv("TERM")) == NULL
)
307 * Drop privileges for client. "proc exec" is needed for -c and for
308 * locking (which uses system(3)).
310 * "tty" is needed to restore termios(4) and also for some reason -CC
311 * does not work properly without it (input is not recognised).
313 * "sendfd" is dropped later in client_dispatch_wait().
316 "stdio rpath wpath cpath unix sendfd proc exec tty",
318 fatal("pledge failed");
320 /* Load terminfo entry if any. */
321 if (isatty(STDIN_FILENO
) &&
323 tty_term_read_list(termname
, STDIN_FILENO
, &caps
, &ncaps
,
325 fprintf(stderr
, "%s\n", cause
);
330 /* Free stuff that is not used in the client. */
333 options_free(global_options
);
334 options_free(global_s_options
);
335 options_free(global_w_options
);
336 environ_free(global_environ
);
338 /* Set up control mode. */
339 if (client_flags
& CLIENT_CONTROLCONTROL
) {
340 if (tcgetattr(STDIN_FILENO
, &saved_tio
) != 0) {
341 fprintf(stderr
, "tcgetattr failed: %s\n",
346 tio
.c_iflag
= ICRNL
|IXANY
;
347 tio
.c_oflag
= OPOST
|ONLCR
;
348 tio
.c_lflag
= NOKERNINFO
;
349 tio
.c_cflag
= CREAD
|CS8
|HUPCL
;
352 cfsetispeed(&tio
, cfgetispeed(&saved_tio
));
353 cfsetospeed(&tio
, cfgetospeed(&saved_tio
));
354 tcsetattr(STDIN_FILENO
, TCSANOW
, &tio
);
357 /* Send identify messages. */
358 client_send_identify(ttynam
, termname
, caps
, ncaps
, cwd
, feat
);
359 tty_term_free_list(caps
, ncaps
);
360 proc_flush_peer(client_peer
);
362 /* Send first command. */
363 if (msg
== MSG_COMMAND
) {
364 /* How big is the command? */
366 for (i
= 0; i
< argc
; i
++)
367 size
+= strlen(argv
[i
]) + 1;
368 if (size
> MAX_IMSGSIZE
- (sizeof *data
)) {
369 fprintf(stderr
, "command too long\n");
372 data
= xmalloc((sizeof *data
) + size
);
374 /* Prepare command for server. */
376 if (cmd_pack_argv(argc
, argv
, (char *)(data
+ 1), size
) != 0) {
377 fprintf(stderr
, "command too long\n");
381 size
+= sizeof *data
;
383 /* Send the command. */
384 if (proc_send(client_peer
, msg
, -1, data
, size
) != 0) {
385 fprintf(stderr
, "failed to send command\n");
390 } else if (msg
== MSG_SHELL
)
391 proc_send(client_peer
, msg
, -1, NULL
, 0);
393 /* Start main loop. */
394 proc_loop(client_proc
, NULL
);
396 /* Run command if user requested exec, instead of exiting. */
397 if (client_exittype
== MSG_EXEC
) {
398 if (client_flags
& CLIENT_CONTROLCONTROL
)
399 tcsetattr(STDOUT_FILENO
, TCSAFLUSH
, &saved_tio
);
400 client_exec(client_execshell
, client_execcmd
);
403 /* Restore streams to blocking. */
404 setblocking(STDIN_FILENO
, 1);
405 setblocking(STDOUT_FILENO
, 1);
406 setblocking(STDERR_FILENO
, 1);
408 /* Print the exit message, if any, and exit. */
409 if (client_attached
) {
410 if (client_exitreason
!= CLIENT_EXIT_NONE
)
411 printf("[%s]\n", client_exit_message());
414 if (client_exittype
== MSG_DETACHKILL
&& ppid
> 1)
416 } else if (client_flags
& CLIENT_CONTROL
) {
417 if (client_exitreason
!= CLIENT_EXIT_NONE
)
418 printf("%%exit %s\n", client_exit_message());
422 if (client_flags
& CLIENT_CONTROL_WAITEXIT
) {
423 setvbuf(stdin
, NULL
, _IOLBF
, 0);
425 linelen
= getline(&line
, &linesize
, stdin
);
431 if (client_flags
& CLIENT_CONTROLCONTROL
) {
434 tcsetattr(STDOUT_FILENO
, TCSAFLUSH
, &saved_tio
);
436 } else if (client_exitreason
!= CLIENT_EXIT_NONE
)
437 fprintf(stderr
, "%s\n", client_exit_message());
438 return (client_exitval
);
441 /* Send identify messages to server. */
443 client_send_identify(const char *ttynam
, const char *termname
, char **caps
,
444 u_int ncaps
, const char *cwd
, int feat
)
448 int fd
, flags
= client_flags
;
452 proc_send(client_peer
, MSG_IDENTIFY_FLAGS
, -1, &flags
, sizeof flags
);
453 proc_send(client_peer
, MSG_IDENTIFY_LONGFLAGS
, -1, &client_flags
,
454 sizeof client_flags
);
456 proc_send(client_peer
, MSG_IDENTIFY_TERM
, -1, termname
,
457 strlen(termname
) + 1);
458 proc_send(client_peer
, MSG_IDENTIFY_FEATURES
, -1, &feat
, sizeof feat
);
460 proc_send(client_peer
, MSG_IDENTIFY_TTYNAME
, -1, ttynam
,
462 proc_send(client_peer
, MSG_IDENTIFY_CWD
, -1, cwd
, strlen(cwd
) + 1);
464 for (i
= 0; i
< ncaps
; i
++) {
465 proc_send(client_peer
, MSG_IDENTIFY_TERMINFO
, -1,
466 caps
[i
], strlen(caps
[i
]) + 1);
469 if ((fd
= dup(STDIN_FILENO
)) == -1)
471 proc_send(client_peer
, MSG_IDENTIFY_STDIN
, fd
, NULL
, 0);
472 if ((fd
= dup(STDOUT_FILENO
)) == -1)
474 proc_send(client_peer
, MSG_IDENTIFY_STDOUT
, fd
, NULL
, 0);
477 proc_send(client_peer
, MSG_IDENTIFY_CLIENTPID
, -1, &pid
, sizeof pid
);
479 for (ss
= environ
; *ss
!= NULL
; ss
++) {
480 sslen
= strlen(*ss
) + 1;
481 if (sslen
> MAX_IMSGSIZE
- IMSG_HEADER_SIZE
)
483 proc_send(client_peer
, MSG_IDENTIFY_ENVIRON
, -1, *ss
, sslen
);
486 proc_send(client_peer
, MSG_IDENTIFY_DONE
, -1, NULL
, 0);
489 /* Run command in shell; used for -c. */
491 client_exec(const char *shell
, const char *shellcmd
)
493 const char *name
, *ptr
;
496 log_debug("shell %s, command %s", shell
, shellcmd
);
498 ptr
= strrchr(shell
, '/');
499 if (ptr
!= NULL
&& *(ptr
+ 1) != '\0')
503 if (client_flags
& CLIENT_LOGIN
)
504 xasprintf(&argv0
, "-%s", name
);
506 xasprintf(&argv0
, "%s", name
);
507 setenv("SHELL", shell
, 1);
509 proc_clear_signals(client_proc
, 1);
511 setblocking(STDIN_FILENO
, 1);
512 setblocking(STDOUT_FILENO
, 1);
513 setblocking(STDERR_FILENO
, 1);
514 closefrom(STDERR_FILENO
+ 1);
516 execl(shell
, argv0
, "-c", shellcmd
, (char *) NULL
);
517 fatal("execl failed");
520 /* Callback to handle signals in the client. */
522 client_signal(int sig
)
524 struct sigaction sigact
;
528 log_debug("%s: %s", __func__
, strsignal(sig
));
529 if (sig
== SIGCHLD
) {
531 pid
= waitpid(WAIT_ANY
, &status
, WNOHANG
);
537 log_debug("waitpid failed: %s",
541 } else if (!client_attached
) {
542 if (sig
== SIGTERM
|| sig
== SIGHUP
)
543 proc_exit(client_proc
);
547 client_exitreason
= CLIENT_EXIT_LOST_TTY
;
549 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
552 if (!client_suspended
)
553 client_exitreason
= CLIENT_EXIT_TERMINATED
;
555 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
558 proc_send(client_peer
, MSG_RESIZE
, -1, NULL
, 0);
561 memset(&sigact
, 0, sizeof sigact
);
562 sigemptyset(&sigact
.sa_mask
);
563 sigact
.sa_flags
= SA_RESTART
;
564 sigact
.sa_handler
= SIG_IGN
;
565 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
566 fatal("sigaction failed");
567 proc_send(client_peer
, MSG_WAKEUP
, -1, NULL
, 0);
568 client_suspended
= 0;
574 /* Callback for file write error or close. */
576 client_file_check_cb(__unused
struct client
*c
, __unused
const char *path
,
577 __unused
int error
, __unused
int closed
, __unused
struct evbuffer
*buffer
,
584 /* Callback for client read events. */
586 client_dispatch(struct imsg
*imsg
, __unused
void *arg
)
589 if (!client_exitflag
) {
590 client_exitreason
= CLIENT_EXIT_LOST_SERVER
;
593 proc_exit(client_proc
);
598 client_dispatch_attached(imsg
);
600 client_dispatch_wait(imsg
);
603 /* Process an exit message. */
605 client_dispatch_exit_message(char *data
, size_t datalen
)
609 if (datalen
< sizeof retval
&& datalen
!= 0)
610 fatalx("bad MSG_EXIT size");
612 if (datalen
>= sizeof retval
) {
613 memcpy(&retval
, data
, sizeof retval
);
614 client_exitval
= retval
;
617 if (datalen
> sizeof retval
) {
618 datalen
-= sizeof retval
;
619 data
+= sizeof retval
;
621 client_exitmessage
= xmalloc(datalen
);
622 memcpy(client_exitmessage
, data
, datalen
);
623 client_exitmessage
[datalen
- 1] = '\0';
625 client_exitreason
= CLIENT_EXIT_MESSAGE_PROVIDED
;
629 /* Dispatch imsgs when in wait state (before MSG_READY). */
631 client_dispatch_wait(struct imsg
*imsg
)
635 static int pledge_applied
;
638 * "sendfd" is no longer required once all of the identify messages
639 * have been sent. We know the server won't send us anything until that
640 * point (because we don't ask it to), so we can drop "sendfd" once we
641 * get the first message from the server.
643 if (!pledge_applied
) {
645 "stdio rpath wpath cpath unix proc exec tty",
647 fatal("pledge failed");
652 datalen
= imsg
->hdr
.len
- IMSG_HEADER_SIZE
;
654 switch (imsg
->hdr
.type
) {
657 client_dispatch_exit_message(data
, datalen
);
663 fatalx("bad MSG_READY size");
666 proc_send(client_peer
, MSG_RESIZE
, -1, NULL
, 0);
670 fatalx("bad MSG_VERSION size");
672 fprintf(stderr
, "protocol version mismatch "
673 "(client %d, server %u)\n", PROTOCOL_VERSION
,
674 imsg
->hdr
.peerid
& 0xff);
676 proc_exit(client_proc
);
679 if (datalen
!= sizeof client_flags
)
680 fatalx("bad MSG_FLAGS string");
682 memcpy(&client_flags
, data
, sizeof client_flags
);
683 log_debug("new flags are %#llx",
684 (unsigned long long)client_flags
);
687 if (datalen
== 0 || data
[datalen
- 1] != '\0')
688 fatalx("bad MSG_SHELL string");
690 client_exec(data
, shell_command
);
694 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
697 proc_exit(client_proc
);
700 file_read_open(&client_files
, client_peer
, imsg
, 1,
701 !(client_flags
& CLIENT_CONTROL
), client_file_check_cb
,
704 case MSG_READ_CANCEL
:
705 file_read_cancel(&client_files
, imsg
);
708 file_write_open(&client_files
, client_peer
, imsg
, 1,
709 !(client_flags
& CLIENT_CONTROL
), client_file_check_cb
,
713 file_write_data(&client_files
, imsg
);
715 case MSG_WRITE_CLOSE
:
716 file_write_close(&client_files
, imsg
);
721 fprintf(stderr
, "server version is too old for client\n");
722 proc_exit(client_proc
);
727 /* Dispatch imsgs in attached state (after MSG_READY). */
729 client_dispatch_attached(struct imsg
*imsg
)
731 struct sigaction sigact
;
736 datalen
= imsg
->hdr
.len
- IMSG_HEADER_SIZE
;
738 switch (imsg
->hdr
.type
) {
740 if (datalen
!= sizeof client_flags
)
741 fatalx("bad MSG_FLAGS string");
743 memcpy(&client_flags
, data
, sizeof client_flags
);
744 log_debug("new flags are %#llx",
745 (unsigned long long)client_flags
);
749 if (datalen
== 0 || data
[datalen
- 1] != '\0')
750 fatalx("bad MSG_DETACH string");
752 client_exitsession
= xstrdup(data
);
753 client_exittype
= imsg
->hdr
.type
;
754 if (imsg
->hdr
.type
== MSG_DETACHKILL
)
755 client_exitreason
= CLIENT_EXIT_DETACHED_HUP
;
757 client_exitreason
= CLIENT_EXIT_DETACHED
;
758 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
761 if (datalen
== 0 || data
[datalen
- 1] != '\0' ||
762 strlen(data
) + 1 == (size_t)datalen
)
763 fatalx("bad MSG_EXEC string");
764 client_execcmd
= xstrdup(data
);
765 client_execshell
= xstrdup(data
+ strlen(data
) + 1);
767 client_exittype
= imsg
->hdr
.type
;
768 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
771 client_dispatch_exit_message(data
, datalen
);
772 if (client_exitreason
== CLIENT_EXIT_NONE
)
773 client_exitreason
= CLIENT_EXIT_EXITED
;
774 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
778 fatalx("bad MSG_EXITED size");
780 proc_exit(client_proc
);
784 fatalx("bad MSG_SHUTDOWN size");
786 proc_send(client_peer
, MSG_EXITING
, -1, NULL
, 0);
787 client_exitreason
= CLIENT_EXIT_SERVER_EXITED
;
792 fatalx("bad MSG_SUSPEND size");
794 memset(&sigact
, 0, sizeof sigact
);
795 sigemptyset(&sigact
.sa_mask
);
796 sigact
.sa_flags
= SA_RESTART
;
797 sigact
.sa_handler
= SIG_DFL
;
798 if (sigaction(SIGTSTP
, &sigact
, NULL
) != 0)
799 fatal("sigaction failed");
800 client_suspended
= 1;
801 kill(getpid(), SIGTSTP
);
804 if (datalen
== 0 || data
[datalen
- 1] != '\0')
805 fatalx("bad MSG_LOCK string");
808 proc_send(client_peer
, MSG_UNLOCK
, -1, NULL
, 0);