xref: /netbsd-src/external/bsd/tmux/dist/client.c (revision 901e7e84758515fbf39dfc064cb0b45ab146d8b0)
1 /* $OpenBSD$ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
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.
9  *
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.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/uio.h>
22 #include <sys/un.h>
23 #include <sys/wait.h>
24 #include <sys/file.h>
25 
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 
33 #include "tmux.h"
34 
35 static struct tmuxproc	*client_proc;
36 static struct tmuxpeer	*client_peer;
37 static uint64_t		 client_flags;
38 static int		 client_suspended;
39 static enum {
40 	CLIENT_EXIT_NONE,
41 	CLIENT_EXIT_DETACHED,
42 	CLIENT_EXIT_DETACHED_HUP,
43 	CLIENT_EXIT_LOST_TTY,
44 	CLIENT_EXIT_TERMINATED,
45 	CLIENT_EXIT_LOST_SERVER,
46 	CLIENT_EXIT_EXITED,
47 	CLIENT_EXIT_SERVER_EXITED,
48 	CLIENT_EXIT_MESSAGE_PROVIDED
49 } client_exitreason = CLIENT_EXIT_NONE;
50 static int		 client_exitflag;
51 static int		 client_exitval;
52 static enum msgtype	 client_exittype;
53 static const char	*client_exitsession;
54 static char		*client_exitmessage;
55 static const char	*client_execshell;
56 static const char	*client_execcmd;
57 static int		 client_attached;
58 static struct client_files client_files = RB_INITIALIZER(&client_files);
59 
60 static __dead void	 client_exec(const char *,const char *);
61 static int		 client_get_lock(char *);
62 static int		 client_connect(struct event_base *, const char *,
63 			     uint64_t);
64 static void		 client_send_identify(const char *, const char *,
65 			     char **, u_int, const char *, int);
66 static void		 client_signal(int);
67 static void		 client_dispatch(struct imsg *, void *);
68 static void		 client_dispatch_attached(struct imsg *);
69 static void		 client_dispatch_wait(struct imsg *);
70 static const char	*client_exit_message(void);
71 
72 /*
73  * Get server create lock. If already held then server start is happening in
74  * another client, so block until the lock is released and return -2 to
75  * retry. Return -1 on failure to continue and start the server anyway.
76  */
77 static int
78 client_get_lock(char *lockfile)
79 {
80 	int lockfd;
81 
82 	log_debug("lock file is %s", lockfile);
83 
84 	if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
85 		log_debug("open failed: %s", strerror(errno));
86 		return (-1);
87 	}
88 
89 	if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
90 		log_debug("flock failed: %s", strerror(errno));
91 		if (errno != EAGAIN)
92 			return (lockfd);
93 		while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
94 			/* nothing */;
95 		close(lockfd);
96 		return (-2);
97 	}
98 	log_debug("flock succeeded");
99 
100 	return (lockfd);
101 }
102 
103 /* Connect client to server. */
104 static int
105 client_connect(struct event_base *base, const char *path, uint64_t flags)
106 {
107 	struct sockaddr_un	sa;
108 	size_t			size;
109 	int			fd, lockfd = -1, locked = 0;
110 	char		       *lockfile = NULL;
111 
112 	memset(&sa, 0, sizeof sa);
113 	sa.sun_family = AF_UNIX;
114 	size = strlcpy(sa.sun_path, path, sizeof sa.sun_path);
115 	if (size >= sizeof sa.sun_path) {
116 		errno = ENAMETOOLONG;
117 		return (-1);
118 	}
119 	log_debug("socket is %s", path);
120 
121 retry:
122 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
123 		return (-1);
124 
125 	log_debug("trying connect");
126 	if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == -1) {
127 		log_debug("connect failed: %s", strerror(errno));
128 		if (errno != ECONNREFUSED && errno != ENOENT)
129 			goto failed;
130 		if (flags & CLIENT_NOSTARTSERVER)
131 			goto failed;
132 		if (~flags & CLIENT_STARTSERVER)
133 			goto failed;
134 		close(fd);
135 
136 		if (!locked) {
137 			xasprintf(&lockfile, "%s.lock", path);
138 			if ((lockfd = client_get_lock(lockfile)) < 0) {
139 				log_debug("didn't get lock (%d)", lockfd);
140 
141 				free(lockfile);
142 				lockfile = NULL;
143 
144 				if (lockfd == -2)
145 					goto retry;
146 			}
147 			log_debug("got lock (%d)", lockfd);
148 
149 			/*
150 			 * Always retry at least once, even if we got the lock,
151 			 * because another client could have taken the lock,
152 			 * started the server and released the lock between our
153 			 * connect() and flock().
154 			 */
155 			locked = 1;
156 			goto retry;
157 		}
158 
159 		if (lockfd >= 0 && unlink(path) != 0 && errno != ENOENT) {
160 			free(lockfile);
161 			close(lockfd);
162 			return (-1);
163 		}
164 		fd = server_start(client_proc, flags, base, lockfd, lockfile);
165 	}
166 
167 	if (locked && lockfd >= 0) {
168 		free(lockfile);
169 		close(lockfd);
170 	}
171 	setblocking(fd, 0);
172 	return (fd);
173 
174 failed:
175 	if (locked) {
176 		free(lockfile);
177 		close(lockfd);
178 	}
179 	close(fd);
180 	return (-1);
181 }
182 
183 /* Get exit string from reason number. */
184 const char *
185 client_exit_message(void)
186 {
187 	static char msg[256];
188 
189 	switch (client_exitreason) {
190 	case CLIENT_EXIT_NONE:
191 		break;
192 	case CLIENT_EXIT_DETACHED:
193 		if (client_exitsession != NULL) {
194 			xsnprintf(msg, sizeof msg, "detached "
195 			    "(from session %s)", client_exitsession);
196 			return (msg);
197 		}
198 		return ("detached");
199 	case CLIENT_EXIT_DETACHED_HUP:
200 		if (client_exitsession != NULL) {
201 			xsnprintf(msg, sizeof msg, "detached and SIGHUP "
202 			    "(from session %s)", client_exitsession);
203 			return (msg);
204 		}
205 		return ("detached and SIGHUP");
206 	case CLIENT_EXIT_LOST_TTY:
207 		return ("lost tty");
208 	case CLIENT_EXIT_TERMINATED:
209 		return ("terminated");
210 	case CLIENT_EXIT_LOST_SERVER:
211 		return ("server exited unexpectedly");
212 	case CLIENT_EXIT_EXITED:
213 		return ("exited");
214 	case CLIENT_EXIT_SERVER_EXITED:
215 		return ("server exited");
216 	case CLIENT_EXIT_MESSAGE_PROVIDED:
217 		return (client_exitmessage);
218 	}
219 	return ("unknown reason");
220 }
221 
222 /* Exit if all streams flushed. */
223 static void
224 client_exit(void)
225 {
226 	if (!file_write_left(&client_files))
227 		proc_exit(client_proc);
228 }
229 
230 /* Client main loop. */
231 int
232 client_main(struct event_base *base, int argc, char **argv, uint64_t flags,
233     int feat)
234 {
235 	struct cmd_parse_result	*pr;
236 	struct msg_command	*data;
237 	int			 fd, i;
238 	const char		*ttynam, *termname, *cwd;
239 	pid_t			 ppid;
240 	enum msgtype		 msg;
241 	struct termios		 tio, saved_tio;
242 	size_t			 size, linesize = 0;
243 	ssize_t			 linelen;
244 	char			*line = NULL, **caps = NULL, *cause;
245 	u_int			 ncaps = 0;
246 	struct args_value	*values;
247 
248 	/* Ignore SIGCHLD now or daemon() in the server will leave a zombie. */
249 	signal(SIGCHLD, SIG_IGN);
250 
251 	/* Set up the initial command. */
252 	if (shell_command != NULL) {
253 		msg = MSG_SHELL;
254 		flags |= CLIENT_STARTSERVER;
255 	} else if (argc == 0) {
256 		msg = MSG_COMMAND;
257 		flags |= CLIENT_STARTSERVER;
258 	} else {
259 		msg = MSG_COMMAND;
260 
261 		/*
262 		 * It's annoying parsing the command string twice (in client
263 		 * and later in server) but it is necessary to get the start
264 		 * server flag.
265 		 */
266 		values = args_from_vector(argc, argv);
267 		pr = cmd_parse_from_arguments(values, argc, NULL);
268 		if (pr->status == CMD_PARSE_SUCCESS) {
269 			if (cmd_list_any_have(pr->cmdlist, CMD_STARTSERVER))
270 				flags |= CLIENT_STARTSERVER;
271 			cmd_list_free(pr->cmdlist);
272 		} else
273 			free(pr->error);
274 		args_free_values(values, argc);
275 		free(values);
276 	}
277 
278 	/* Create client process structure (starts logging). */
279 	client_proc = proc_start("client");
280 	proc_set_signals(client_proc, client_signal);
281 
282 	/* Save the flags. */
283 	client_flags = flags;
284 	log_debug("flags are %#llx", (unsigned long long)client_flags);
285 
286 	/* Initialize the client socket and start the server. */
287 	fd = client_connect(base, socket_path, client_flags);
288 	if (fd == -1) {
289 		if (errno == ECONNREFUSED) {
290 			fprintf(stderr, "no server running on %s\n",
291 			    socket_path);
292 		} else {
293 			fprintf(stderr, "error connecting to %s (%s)\n",
294 			    socket_path, strerror(errno));
295 		}
296 		return (1);
297 	}
298 	client_peer = proc_add_peer(client_proc, fd, client_dispatch, NULL);
299 
300 	/* Save these before pledge(). */
301 	if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL)
302 		cwd = "/";
303 	if ((ttynam = ttyname(STDIN_FILENO)) == NULL)
304 		ttynam = "";
305 	if ((termname = getenv("TERM")) == NULL)
306 		termname = "";
307 
308 	/*
309 	 * Drop privileges for client. "proc exec" is needed for -c and for
310 	 * locking (which uses system(3)).
311 	 *
312 	 * "tty" is needed to restore termios(4) and also for some reason -CC
313 	 * does not work properly without it (input is not recognised).
314 	 *
315 	 * "sendfd" is dropped later in client_dispatch_wait().
316 	 */
317 	if (pledge(
318 	    "stdio rpath wpath cpath unix sendfd proc exec tty",
319 	    NULL) != 0)
320 		fatal("pledge failed");
321 
322 	/* Load terminfo entry if any. */
323 	if (isatty(STDIN_FILENO) &&
324 	    *termname != '\0' &&
325 	    tty_term_read_list(termname, STDIN_FILENO, &caps, &ncaps,
326 	    &cause) != 0) {
327 		fprintf(stderr, "%s\n", cause);
328 		free(cause);
329 		return (1);
330 	}
331 
332 	/* Free stuff that is not used in the client. */
333 	if (ptm_fd != -1)
334 		close(ptm_fd);
335 	options_free(global_options);
336 	options_free(global_s_options);
337 	options_free(global_w_options);
338 	environ_free(global_environ);
339 
340 	/* Set up control mode. */
341 	if (client_flags & CLIENT_CONTROLCONTROL) {
342 		if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
343 			fprintf(stderr, "tcgetattr failed: %s\n",
344 			    strerror(errno));
345 			return (1);
346 		}
347 		cfmakeraw(&tio);
348 		tio.c_iflag = ICRNL|IXANY;
349 		tio.c_oflag = OPOST|ONLCR;
350 #ifdef NOKERNINFO
351 		tio.c_lflag = NOKERNINFO;
352 #endif
353 		tio.c_cflag = CREAD|CS8|HUPCL;
354 		tio.c_cc[VMIN] = 1;
355 		tio.c_cc[VTIME] = 0;
356 		cfsetispeed(&tio, cfgetispeed(&saved_tio));
357 		cfsetospeed(&tio, cfgetospeed(&saved_tio));
358 		tcsetattr(STDIN_FILENO, TCSANOW, &tio);
359 	}
360 
361 	/* Send identify messages. */
362 	client_send_identify(ttynam, termname, caps, ncaps, cwd, feat);
363 	tty_term_free_list(caps, ncaps);
364 	proc_flush_peer(client_peer);
365 
366 	/* Send first command. */
367 	if (msg == MSG_COMMAND) {
368 		/* How big is the command? */
369 		size = 0;
370 		for (i = 0; i < argc; i++)
371 			size += strlen(argv[i]) + 1;
372 		if (size > MAX_IMSGSIZE - (sizeof *data)) {
373 			fprintf(stderr, "command too long\n");
374 			return (1);
375 		}
376 		data = xmalloc((sizeof *data) + size);
377 
378 		/* Prepare command for server. */
379 		data->argc = argc;
380 		if (cmd_pack_argv(argc, argv, (char *)(data + 1), size) != 0) {
381 			fprintf(stderr, "command too long\n");
382 			free(data);
383 			return (1);
384 		}
385 		size += sizeof *data;
386 
387 		/* Send the command. */
388 		if (proc_send(client_peer, msg, -1, data, size) != 0) {
389 			fprintf(stderr, "failed to send command\n");
390 			free(data);
391 			return (1);
392 		}
393 		free(data);
394 	} else if (msg == MSG_SHELL)
395 		proc_send(client_peer, msg, -1, NULL, 0);
396 
397 	/* Start main loop. */
398 	proc_loop(client_proc, NULL);
399 
400 	/* Run command if user requested exec, instead of exiting. */
401 	if (client_exittype == MSG_EXEC) {
402 		if (client_flags & CLIENT_CONTROLCONTROL)
403 			tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
404 		client_exec(client_execshell, client_execcmd);
405 	}
406 
407 	/* Restore streams to blocking. */
408 	setblocking(STDIN_FILENO, 1);
409 	setblocking(STDOUT_FILENO, 1);
410 	setblocking(STDERR_FILENO, 1);
411 
412 	/* Print the exit message, if any, and exit. */
413 	if (client_attached) {
414 		if (client_exitreason != CLIENT_EXIT_NONE)
415 			printf("[%s]\n", client_exit_message());
416 
417 		ppid = getppid();
418 		if (client_exittype == MSG_DETACHKILL && ppid > 1)
419 			kill(ppid, SIGHUP);
420 	} else if (client_flags & CLIENT_CONTROL) {
421 		if (client_exitreason != CLIENT_EXIT_NONE)
422 			printf("%%exit %s\n", client_exit_message());
423 		else
424 			printf("%%exit\n");
425 		fflush(stdout);
426 		if (client_flags & CLIENT_CONTROL_WAITEXIT) {
427 			setvbuf(stdin, NULL, _IOLBF, 0);
428 			for (;;) {
429 				linelen = getline(&line, &linesize, stdin);
430 				if (linelen <= 1)
431 					break;
432 			}
433 			free(line);
434 		}
435 		if (client_flags & CLIENT_CONTROLCONTROL) {
436 			printf("\033\\");
437 			fflush(stdout);
438 			tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
439 		}
440 	} else if (client_exitreason != CLIENT_EXIT_NONE)
441 		fprintf(stderr, "%s\n", client_exit_message());
442 	return (client_exitval);
443 }
444 
445 /* Send identify messages to server. */
446 static void
447 client_send_identify(const char *ttynam, const char *termname, char **caps,
448     u_int ncaps, const char *cwd, int feat)
449 {
450 	char	**ss;
451 	size_t	  sslen;
452 	int	  fd, flags = client_flags;
453 	pid_t	  pid;
454 	u_int	  i;
455 
456 	proc_send(client_peer, MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
457 	proc_send(client_peer, MSG_IDENTIFY_LONGFLAGS, -1, &client_flags,
458 	    sizeof client_flags);
459 
460 	proc_send(client_peer, MSG_IDENTIFY_TERM, -1, termname,
461 	    strlen(termname) + 1);
462 	proc_send(client_peer, MSG_IDENTIFY_FEATURES, -1, &feat, sizeof feat);
463 
464 	proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
465 	    strlen(ttynam) + 1);
466 	proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
467 
468 	for (i = 0; i < ncaps; i++) {
469 		proc_send(client_peer, MSG_IDENTIFY_TERMINFO, -1,
470 		    caps[i], strlen(caps[i]) + 1);
471 	}
472 
473 	if ((fd = dup(STDIN_FILENO)) == -1)
474 		fatal("dup failed");
475 	proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
476 	if ((fd = dup(STDOUT_FILENO)) == -1)
477 		fatal("dup failed");
478 	proc_send(client_peer, MSG_IDENTIFY_STDOUT, fd, NULL, 0);
479 
480 	pid = getpid();
481 	proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
482 
483 	for (ss = environ; *ss != NULL; ss++) {
484 		sslen = strlen(*ss) + 1;
485 		if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
486 			continue;
487 		proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
488 	}
489 
490 	proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
491 }
492 
493 /* Run command in shell; used for -c. */
494 static __dead void
495 client_exec(const char *shell, const char *shellcmd)
496 {
497 	const char	*name, *ptr;
498 	char		*argv0;
499 
500 	log_debug("shell %s, command %s", shell, shellcmd);
501 
502 	ptr = strrchr(shell, '/');
503 	if (ptr != NULL && *(ptr + 1) != '\0')
504 		name = ptr + 1;
505 	else
506 		name = shell;
507 	if (client_flags & CLIENT_LOGIN)
508 		xasprintf(&argv0, "-%s", name);
509 	else
510 		xasprintf(&argv0, "%s", name);
511 	setenv("SHELL", shell, 1);
512 
513 	proc_clear_signals(client_proc, 1);
514 
515 	setblocking(STDIN_FILENO, 1);
516 	setblocking(STDOUT_FILENO, 1);
517 	setblocking(STDERR_FILENO, 1);
518 	closefrom(STDERR_FILENO + 1);
519 
520 	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
521 	fatal("execl failed");
522 }
523 
524 /* Callback to handle signals in the client. */
525 static void
526 client_signal(int sig)
527 {
528 	struct sigaction sigact;
529 	int		 status;
530 
531 	log_debug("%s: %s", __func__, strsignal(sig));
532 	if (sig == SIGCHLD)
533 		waitpid(WAIT_ANY, &status, WNOHANG);
534 	else if (!client_attached) {
535 		if (sig == SIGTERM || sig == SIGHUP)
536 			proc_exit(client_proc);
537 	} else {
538 		switch (sig) {
539 		case SIGHUP:
540 			client_exitreason = CLIENT_EXIT_LOST_TTY;
541 			client_exitval = 1;
542 			proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
543 			break;
544 		case SIGTERM:
545 			if (!client_suspended)
546 				client_exitreason = CLIENT_EXIT_TERMINATED;
547 			client_exitval = 1;
548 			proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
549 			break;
550 		case SIGWINCH:
551 			proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
552 			break;
553 		case SIGCONT:
554 			memset(&sigact, 0, sizeof sigact);
555 			sigemptyset(&sigact.sa_mask);
556 			sigact.sa_flags = SA_RESTART;
557 			sigact.sa_handler = SIG_IGN;
558 			if (sigaction(SIGTSTP, &sigact, NULL) != 0)
559 				fatal("sigaction failed");
560 			proc_send(client_peer, MSG_WAKEUP, -1, NULL, 0);
561 			client_suspended = 0;
562 			break;
563 		}
564 	}
565 }
566 
567 /* Callback for file write error or close. */
568 static void
569 client_file_check_cb(__unused struct client *c, __unused const char *path,
570     __unused int error, __unused int closed, __unused struct evbuffer *buffer,
571     __unused void *data)
572 {
573 	if (client_exitflag)
574 		client_exit();
575 }
576 
577 /* Callback for client read events. */
578 static void
579 client_dispatch(struct imsg *imsg, __unused void *arg)
580 {
581 	if (imsg == NULL) {
582 		if (!client_exitflag) {
583 			client_exitreason = CLIENT_EXIT_LOST_SERVER;
584 			client_exitval = 1;
585 		}
586 		proc_exit(client_proc);
587 		return;
588 	}
589 
590 	if (client_attached)
591 		client_dispatch_attached(imsg);
592 	else
593 		client_dispatch_wait(imsg);
594 }
595 
596 /* Process an exit message. */
597 static void
598 client_dispatch_exit_message(char *data, size_t datalen)
599 {
600 	int	retval;
601 
602 	if (datalen < sizeof retval && datalen != 0)
603 		fatalx("bad MSG_EXIT size");
604 
605 	if (datalen >= sizeof retval) {
606 		memcpy(&retval, data, sizeof retval);
607 		client_exitval = retval;
608 	}
609 
610 	if (datalen > sizeof retval) {
611 		datalen -= sizeof retval;
612 		data += sizeof retval;
613 
614 		client_exitmessage = xmalloc(datalen);
615 		memcpy(client_exitmessage, data, datalen);
616 		client_exitmessage[datalen - 1] = '\0';
617 
618 		client_exitreason = CLIENT_EXIT_MESSAGE_PROVIDED;
619 	}
620 }
621 
622 /* Dispatch imsgs when in wait state (before MSG_READY). */
623 static void
624 client_dispatch_wait(struct imsg *imsg)
625 {
626 	char		*data;
627 	ssize_t		 datalen;
628 	static int	 pledge_applied;
629 
630 	/*
631 	 * "sendfd" is no longer required once all of the identify messages
632 	 * have been sent. We know the server won't send us anything until that
633 	 * point (because we don't ask it to), so we can drop "sendfd" once we
634 	 * get the first message from the server.
635 	 */
636 	if (!pledge_applied) {
637 		if (pledge(
638 		    "stdio rpath wpath cpath unix proc exec tty",
639 		    NULL) != 0)
640 			fatal("pledge failed");
641 		pledge_applied = 1;
642 	}
643 
644 	data = imsg->data;
645 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
646 
647 	switch (imsg->hdr.type) {
648 	case MSG_EXIT:
649 	case MSG_SHUTDOWN:
650 		client_dispatch_exit_message(data, datalen);
651 		client_exitflag = 1;
652 		client_exit();
653 		break;
654 	case MSG_READY:
655 		if (datalen != 0)
656 			fatalx("bad MSG_READY size");
657 
658 		client_attached = 1;
659 		proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
660 		break;
661 	case MSG_VERSION:
662 		if (datalen != 0)
663 			fatalx("bad MSG_VERSION size");
664 
665 		fprintf(stderr, "protocol version mismatch "
666 		    "(client %d, server %u)\n", PROTOCOL_VERSION,
667 		    imsg->hdr.peerid & 0xff);
668 		client_exitval = 1;
669 		proc_exit(client_proc);
670 		break;
671 	case MSG_FLAGS:
672 		if (datalen != sizeof client_flags)
673 			fatalx("bad MSG_FLAGS string");
674 
675 		memcpy(&client_flags, data, sizeof client_flags);
676 		log_debug("new flags are %#llx",
677 		    (unsigned long long)client_flags);
678 		break;
679 	case MSG_SHELL:
680 		if (datalen == 0 || data[datalen - 1] != '\0')
681 			fatalx("bad MSG_SHELL string");
682 
683 		client_exec(data, shell_command);
684 		/* NOTREACHED */
685 	case MSG_DETACH:
686 	case MSG_DETACHKILL:
687 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
688 		break;
689 	case MSG_EXITED:
690 		proc_exit(client_proc);
691 		break;
692 	case MSG_READ_OPEN:
693 		file_read_open(&client_files, client_peer, imsg, 1,
694 		    !(client_flags & CLIENT_CONTROL), client_file_check_cb,
695 		    NULL);
696 		break;
697 	case MSG_WRITE_OPEN:
698 		file_write_open(&client_files, client_peer, imsg, 1,
699 		    !(client_flags & CLIENT_CONTROL), client_file_check_cb,
700 		    NULL);
701 		break;
702 	case MSG_WRITE:
703 		file_write_data(&client_files, imsg);
704 		break;
705 	case MSG_WRITE_CLOSE:
706 		file_write_close(&client_files, imsg);
707 		break;
708 	case MSG_OLDSTDERR:
709 	case MSG_OLDSTDIN:
710 	case MSG_OLDSTDOUT:
711 		fprintf(stderr, "server version is too old for client\n");
712 		proc_exit(client_proc);
713 		break;
714 	}
715 }
716 
717 /* Dispatch imsgs in attached state (after MSG_READY). */
718 static void
719 client_dispatch_attached(struct imsg *imsg)
720 {
721 	struct sigaction	 sigact;
722 	char			*data;
723 	ssize_t			 datalen;
724 
725 	data = imsg->data;
726 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
727 
728 	switch (imsg->hdr.type) {
729 	case MSG_FLAGS:
730 		if (datalen != sizeof client_flags)
731 			fatalx("bad MSG_FLAGS string");
732 
733 		memcpy(&client_flags, data, sizeof client_flags);
734 		log_debug("new flags are %#llx",
735 		    (unsigned long long)client_flags);
736 		break;
737 	case MSG_DETACH:
738 	case MSG_DETACHKILL:
739 		if (datalen == 0 || data[datalen - 1] != '\0')
740 			fatalx("bad MSG_DETACH string");
741 
742 		client_exitsession = xstrdup(data);
743 		client_exittype = imsg->hdr.type;
744 		if (imsg->hdr.type == MSG_DETACHKILL)
745 			client_exitreason = CLIENT_EXIT_DETACHED_HUP;
746 		else
747 			client_exitreason = CLIENT_EXIT_DETACHED;
748 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
749 		break;
750 	case MSG_EXEC:
751 		if (datalen == 0 || data[datalen - 1] != '\0' ||
752 		    strlen(data) + 1 == (size_t)datalen)
753 			fatalx("bad MSG_EXEC string");
754 		client_execcmd = xstrdup(data);
755 		client_execshell = xstrdup(data + strlen(data) + 1);
756 
757 		client_exittype = imsg->hdr.type;
758 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
759 		break;
760 	case MSG_EXIT:
761 		client_dispatch_exit_message(data, datalen);
762 		if (client_exitreason == CLIENT_EXIT_NONE)
763 			client_exitreason = CLIENT_EXIT_EXITED;
764 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
765 		break;
766 	case MSG_EXITED:
767 		if (datalen != 0)
768 			fatalx("bad MSG_EXITED size");
769 
770 		proc_exit(client_proc);
771 		break;
772 	case MSG_SHUTDOWN:
773 		if (datalen != 0)
774 			fatalx("bad MSG_SHUTDOWN size");
775 
776 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
777 		client_exitreason = CLIENT_EXIT_SERVER_EXITED;
778 		client_exitval = 1;
779 		break;
780 	case MSG_SUSPEND:
781 		if (datalen != 0)
782 			fatalx("bad MSG_SUSPEND size");
783 
784 		memset(&sigact, 0, sizeof sigact);
785 		sigemptyset(&sigact.sa_mask);
786 		sigact.sa_flags = SA_RESTART;
787 		sigact.sa_handler = SIG_DFL;
788 		if (sigaction(SIGTSTP, &sigact, NULL) != 0)
789 			fatal("sigaction failed");
790 		client_suspended = 1;
791 		kill(getpid(), SIGTSTP);
792 		break;
793 	case MSG_LOCK:
794 		if (datalen == 0 || data[datalen - 1] != '\0')
795 			fatalx("bad MSG_LOCK string");
796 
797 		system(data);
798 		proc_send(client_peer, MSG_UNLOCK, -1, NULL, 0);
799 		break;
800 	}
801 }
802