xref: /openbsd/usr.bin/tmux/client.c (revision e5dd7070)
1 /* $OpenBSD: client.c,v 1.148 2020/06/18 08:34:22 nicm Exp $ */
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 
25 #include <errno.h>
26 #include <event.h>
27 #include <fcntl.h>
28 #include <imsg.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 
34 #include "tmux.h"
35 
36 static struct tmuxproc	*client_proc;
37 static struct tmuxpeer	*client_peer;
38 static uint64_t		 client_flags;
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 *, int);
63 static void		 client_send_identify(const char *, const char *, int);
64 static void		 client_signal(int);
65 static void		 client_dispatch(struct imsg *, void *);
66 static void		 client_dispatch_attached(struct imsg *);
67 static void		 client_dispatch_wait(struct imsg *);
68 static const char	*client_exit_message(void);
69 
70 /*
71  * Get server create lock. If already held then server start is happening in
72  * another client, so block until the lock is released and return -2 to
73  * retry. Return -1 on failure to continue and start the server anyway.
74  */
75 static int
76 client_get_lock(char *lockfile)
77 {
78 	int lockfd;
79 
80 	log_debug("lock file is %s", lockfile);
81 
82 	if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
83 		log_debug("open failed: %s", strerror(errno));
84 		return (-1);
85 	}
86 
87 	if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
88 		log_debug("flock failed: %s", strerror(errno));
89 		if (errno != EAGAIN)
90 			return (lockfd);
91 		while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
92 			/* nothing */;
93 		close(lockfd);
94 		return (-2);
95 	}
96 	log_debug("flock succeeded");
97 
98 	return (lockfd);
99 }
100 
101 /* Connect client to server. */
102 static int
103 client_connect(struct event_base *base, const char *path, int flags)
104 {
105 	struct sockaddr_un	sa;
106 	size_t			size;
107 	int			fd, lockfd = -1, locked = 0;
108 	char		       *lockfile = NULL;
109 
110 	memset(&sa, 0, sizeof sa);
111 	sa.sun_family = AF_UNIX;
112 	size = strlcpy(sa.sun_path, path, sizeof sa.sun_path);
113 	if (size >= sizeof sa.sun_path) {
114 		errno = ENAMETOOLONG;
115 		return (-1);
116 	}
117 	log_debug("socket is %s", path);
118 
119 retry:
120 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
121 		return (-1);
122 
123 	log_debug("trying connect");
124 	if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == -1) {
125 		log_debug("connect failed: %s", strerror(errno));
126 		if (errno != ECONNREFUSED && errno != ENOENT)
127 			goto failed;
128 		if (~flags & CLIENT_STARTSERVER)
129 			goto failed;
130 		close(fd);
131 
132 		if (!locked) {
133 			xasprintf(&lockfile, "%s.lock", path);
134 			if ((lockfd = client_get_lock(lockfile)) < 0) {
135 				log_debug("didn't get lock (%d)", lockfd);
136 
137 				free(lockfile);
138 				lockfile = NULL;
139 
140 				if (lockfd == -2)
141 					goto retry;
142 			}
143 			log_debug("got lock (%d)", lockfd);
144 
145 			/*
146 			 * Always retry at least once, even if we got the lock,
147 			 * because another client could have taken the lock,
148 			 * started the server and released the lock between our
149 			 * connect() and flock().
150 			 */
151 			locked = 1;
152 			goto retry;
153 		}
154 
155 		if (lockfd >= 0 && unlink(path) != 0 && errno != ENOENT) {
156 			free(lockfile);
157 			close(lockfd);
158 			return (-1);
159 		}
160 		fd = server_start(client_proc, flags, base, lockfd, lockfile);
161 	}
162 
163 	if (locked && lockfd >= 0) {
164 		free(lockfile);
165 		close(lockfd);
166 	}
167 	setblocking(fd, 0);
168 	return (fd);
169 
170 failed:
171 	if (locked) {
172 		free(lockfile);
173 		close(lockfd);
174 	}
175 	close(fd);
176 	return (-1);
177 }
178 
179 /* Get exit string from reason number. */
180 const char *
181 client_exit_message(void)
182 {
183 	static char msg[256];
184 
185 	switch (client_exitreason) {
186 	case CLIENT_EXIT_NONE:
187 		break;
188 	case CLIENT_EXIT_DETACHED:
189 		if (client_exitsession != NULL) {
190 			xsnprintf(msg, sizeof msg, "detached "
191 			    "(from session %s)", client_exitsession);
192 			return (msg);
193 		}
194 		return ("detached");
195 	case CLIENT_EXIT_DETACHED_HUP:
196 		if (client_exitsession != NULL) {
197 			xsnprintf(msg, sizeof msg, "detached and SIGHUP "
198 			    "(from session %s)", client_exitsession);
199 			return (msg);
200 		}
201 		return ("detached and SIGHUP");
202 	case CLIENT_EXIT_LOST_TTY:
203 		return ("lost tty");
204 	case CLIENT_EXIT_TERMINATED:
205 		return ("terminated");
206 	case CLIENT_EXIT_LOST_SERVER:
207 		return ("server exited unexpectedly");
208 	case CLIENT_EXIT_EXITED:
209 		return ("exited");
210 	case CLIENT_EXIT_SERVER_EXITED:
211 		return ("server exited");
212 	case CLIENT_EXIT_MESSAGE_PROVIDED:
213 		return (client_exitmessage);
214 	}
215 	return ("unknown reason");
216 }
217 
218 /* Exit if all streams flushed. */
219 static void
220 client_exit(void)
221 {
222 	struct client_file	*cf;
223 	size_t 			 left;
224 	int			 waiting = 0;
225 
226 	RB_FOREACH (cf, client_files, &client_files) {
227 		if (cf->event == NULL)
228 			continue;
229 		left = EVBUFFER_LENGTH(cf->event->output);
230 		if (left != 0) {
231 			waiting++;
232 			log_debug("file %u %zu bytes left", cf->stream, left);
233 		}
234 	}
235 	if (waiting == 0)
236 		proc_exit(client_proc);
237 }
238 
239 /* Client main loop. */
240 int
241 client_main(struct event_base *base, int argc, char **argv, int flags, int feat)
242 {
243 	struct cmd_parse_result	*pr;
244 	struct msg_command	*data;
245 	int			 fd, i;
246 	const char		*ttynam, *cwd;
247 	pid_t			 ppid;
248 	enum msgtype		 msg;
249 	struct termios		 tio, saved_tio;
250 	size_t			 size, linesize = 0;
251 	ssize_t			 linelen;
252 	char			*line = NULL;
253 
254 	/* Ignore SIGCHLD now or daemon() in the server will leave a zombie. */
255 	signal(SIGCHLD, SIG_IGN);
256 
257 	/* Set up the initial command. */
258 	if (shell_command != NULL) {
259 		msg = MSG_SHELL;
260 		flags |= CLIENT_STARTSERVER;
261 	} else if (argc == 0) {
262 		msg = MSG_COMMAND;
263 		flags |= CLIENT_STARTSERVER;
264 	} else {
265 		msg = MSG_COMMAND;
266 
267 		/*
268 		 * It sucks parsing the command string twice (in client and
269 		 * later in server) but it is necessary to get the start server
270 		 * flag.
271 		 */
272 		pr = cmd_parse_from_arguments(argc, argv, NULL);
273 		if (pr->status == CMD_PARSE_SUCCESS) {
274 			if (cmd_list_any_have(pr->cmdlist, CMD_STARTSERVER))
275 				flags |= CLIENT_STARTSERVER;
276 			cmd_list_free(pr->cmdlist);
277 		} else
278 			free(pr->error);
279 	}
280 
281 	/* Create client process structure (starts logging). */
282 	client_proc = proc_start("client");
283 	proc_set_signals(client_proc, client_signal);
284 
285 	/* Save the flags. */
286 	client_flags = flags;
287 	log_debug("flags are %#llx", client_flags);
288 
289 	/* Initialize the client socket and start the server. */
290 	fd = client_connect(base, socket_path, client_flags);
291 	if (fd == -1) {
292 		if (errno == ECONNREFUSED) {
293 			fprintf(stderr, "no server running on %s\n",
294 			    socket_path);
295 		} else {
296 			fprintf(stderr, "error connecting to %s (%s)\n",
297 			    socket_path, strerror(errno));
298 		}
299 		return (1);
300 	}
301 	client_peer = proc_add_peer(client_proc, fd, client_dispatch, NULL);
302 
303 	/* Save these before pledge(). */
304 	if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL)
305 		cwd = "/";
306 	if ((ttynam = ttyname(STDIN_FILENO)) == NULL)
307 		ttynam = "";
308 
309 	/*
310 	 * Drop privileges for client. "proc exec" is needed for -c and for
311 	 * locking (which uses system(3)).
312 	 *
313 	 * "tty" is needed to restore termios(4) and also for some reason -CC
314 	 * does not work properly without it (input is not recognised).
315 	 *
316 	 * "sendfd" is dropped later in client_dispatch_wait().
317 	 */
318 	if (pledge(
319 	    "stdio rpath wpath cpath unix sendfd proc exec tty",
320 	    NULL) != 0)
321 		fatal("pledge failed");
322 
323 	/* Free stuff that is not used in the client. */
324 	if (ptm_fd != -1)
325 		close(ptm_fd);
326 	options_free(global_options);
327 	options_free(global_s_options);
328 	options_free(global_w_options);
329 	environ_free(global_environ);
330 
331 	/* Set up control mode. */
332 	if (client_flags & CLIENT_CONTROLCONTROL) {
333 		if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
334 			fprintf(stderr, "tcgetattr failed: %s\n",
335 			    strerror(errno));
336 			return (1);
337 		}
338 		cfmakeraw(&tio);
339 		tio.c_iflag = ICRNL|IXANY;
340 		tio.c_oflag = OPOST|ONLCR;
341 		tio.c_lflag = NOKERNINFO;
342 		tio.c_cflag = CREAD|CS8|HUPCL;
343 		tio.c_cc[VMIN] = 1;
344 		tio.c_cc[VTIME] = 0;
345 		cfsetispeed(&tio, cfgetispeed(&saved_tio));
346 		cfsetospeed(&tio, cfgetospeed(&saved_tio));
347 		tcsetattr(STDIN_FILENO, TCSANOW, &tio);
348 	}
349 
350 	/* Send identify messages. */
351 	client_send_identify(ttynam, cwd, feat);
352 
353 	/* Send first command. */
354 	if (msg == MSG_COMMAND) {
355 		/* How big is the command? */
356 		size = 0;
357 		for (i = 0; i < argc; i++)
358 			size += strlen(argv[i]) + 1;
359 		if (size > MAX_IMSGSIZE - (sizeof *data)) {
360 			fprintf(stderr, "command too long\n");
361 			return (1);
362 		}
363 		data = xmalloc((sizeof *data) + size);
364 
365 		/* Prepare command for server. */
366 		data->argc = argc;
367 		if (cmd_pack_argv(argc, argv, (char *)(data + 1), size) != 0) {
368 			fprintf(stderr, "command too long\n");
369 			free(data);
370 			return (1);
371 		}
372 		size += sizeof *data;
373 
374 		/* Send the command. */
375 		if (proc_send(client_peer, msg, -1, data, size) != 0) {
376 			fprintf(stderr, "failed to send command\n");
377 			free(data);
378 			return (1);
379 		}
380 		free(data);
381 	} else if (msg == MSG_SHELL)
382 		proc_send(client_peer, msg, -1, NULL, 0);
383 
384 	/* Start main loop. */
385 	proc_loop(client_proc, NULL);
386 
387 	/* Run command if user requested exec, instead of exiting. */
388 	if (client_exittype == MSG_EXEC) {
389 		if (client_flags & CLIENT_CONTROLCONTROL)
390 			tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
391 		client_exec(client_execshell, client_execcmd);
392 	}
393 
394 	/* Restore streams to blocking. */
395 	setblocking(STDIN_FILENO, 1);
396 	setblocking(STDOUT_FILENO, 1);
397 	setblocking(STDERR_FILENO, 1);
398 
399 	/* Print the exit message, if any, and exit. */
400 	if (client_attached) {
401 		if (client_exitreason != CLIENT_EXIT_NONE)
402 			printf("[%s]\n", client_exit_message());
403 
404 		ppid = getppid();
405 		if (client_exittype == MSG_DETACHKILL && ppid > 1)
406 			kill(ppid, SIGHUP);
407 	} else if (client_flags & CLIENT_CONTROL) {
408 		if (client_exitreason != CLIENT_EXIT_NONE)
409 			printf("%%exit %s\n", client_exit_message());
410 		else
411 			printf("%%exit\n");
412 		fflush(stdout);
413 		if (client_flags & CLIENT_CONTROL_WAITEXIT) {
414 			setvbuf(stdin, NULL, _IOLBF, 0);
415 			for (;;) {
416 				linelen = getline(&line, &linesize, stdin);
417 				if (linelen <= 1)
418 					break;
419 			}
420 			free(line);
421 		}
422 		if (client_flags & CLIENT_CONTROLCONTROL) {
423 			printf("\033\\");
424 			fflush(stdout);
425 			tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
426 		}
427 	} else if (client_exitreason != CLIENT_EXIT_NONE)
428 		fprintf(stderr, "%s\n", client_exit_message());
429 	return (client_exitval);
430 }
431 
432 /* Send identify messages to server. */
433 static void
434 client_send_identify(const char *ttynam, const char *cwd, int feat)
435 {
436 	const char	 *s;
437 	char		**ss;
438 	size_t		  sslen;
439 	int		  fd, flags = client_flags;
440 	pid_t		  pid;
441 
442 	proc_send(client_peer, MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
443 
444 	if ((s = getenv("TERM")) == NULL)
445 		s = "";
446 	proc_send(client_peer, MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1);
447 	proc_send(client_peer, MSG_IDENTIFY_FEATURES, -1, &feat, sizeof feat);
448 
449 	proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
450 	    strlen(ttynam) + 1);
451 	proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
452 
453 	if ((fd = dup(STDIN_FILENO)) == -1)
454 		fatal("dup failed");
455 	proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
456 	if ((fd = dup(STDOUT_FILENO)) == -1)
457 		fatal("dup failed");
458 	proc_send(client_peer, MSG_IDENTIFY_STDOUT, fd, NULL, 0);
459 
460 	pid = getpid();
461 	proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
462 
463 	for (ss = environ; *ss != NULL; ss++) {
464 		sslen = strlen(*ss) + 1;
465 		if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
466 			continue;
467 		proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
468 	}
469 
470 	proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
471 }
472 
473 /* File write error callback. */
474 static void
475 client_write_error_callback(__unused struct bufferevent *bev,
476     __unused short what, void *arg)
477 {
478 	struct client_file	*cf = arg;
479 
480 	log_debug("write error file %d", cf->stream);
481 
482 	bufferevent_free(cf->event);
483 	cf->event = NULL;
484 
485 	close(cf->fd);
486 	cf->fd = -1;
487 
488 	if (client_exitflag)
489 		client_exit();
490 }
491 
492 /* File write callback. */
493 static void
494 client_write_callback(__unused struct bufferevent *bev, void *arg)
495 {
496 	struct client_file	*cf = arg;
497 
498 	if (cf->closed && EVBUFFER_LENGTH(cf->event->output) == 0) {
499 		bufferevent_free(cf->event);
500 		close(cf->fd);
501 		RB_REMOVE(client_files, &client_files, cf);
502 		file_free(cf);
503 	}
504 
505 	if (client_exitflag)
506 		client_exit();
507 }
508 
509 /* Open write file. */
510 static void
511 client_write_open(void *data, size_t datalen)
512 {
513 	struct msg_write_open	*msg = data;
514 	const char		*path;
515 	struct msg_write_ready	 reply;
516 	struct client_file	 find, *cf;
517 	const int		 flags = O_NONBLOCK|O_WRONLY|O_CREAT;
518 	int			 error = 0;
519 
520 	if (datalen < sizeof *msg)
521 		fatalx("bad MSG_WRITE_OPEN size");
522 	if (datalen == sizeof *msg)
523 		path = "-";
524 	else
525 		path = (const char *)(msg + 1);
526 	log_debug("open write file %d %s", msg->stream, path);
527 
528 	find.stream = msg->stream;
529 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
530 		cf = file_create(NULL, msg->stream, NULL, NULL);
531 		RB_INSERT(client_files, &client_files, cf);
532 	} else {
533 		error = EBADF;
534 		goto reply;
535 	}
536 	if (cf->closed) {
537 		error = EBADF;
538 		goto reply;
539 	}
540 
541 	cf->fd = -1;
542 	if (msg->fd == -1)
543 		cf->fd = open(path, msg->flags|flags, 0644);
544 	else {
545 		if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)
546 			errno = EBADF;
547 		else {
548 			cf->fd = dup(msg->fd);
549 			if (~client_flags & CLIENT_CONTROL)
550 				close(msg->fd); /* can only be used once */
551 		}
552 	}
553 	if (cf->fd == -1) {
554 		error = errno;
555 		goto reply;
556 	}
557 
558 	cf->event = bufferevent_new(cf->fd, NULL, client_write_callback,
559 	    client_write_error_callback, cf);
560 	bufferevent_enable(cf->event, EV_WRITE);
561 	goto reply;
562 
563 reply:
564 	reply.stream = msg->stream;
565 	reply.error = error;
566 	proc_send(client_peer, MSG_WRITE_READY, -1, &reply, sizeof reply);
567 }
568 
569 /* Write to client file. */
570 static void
571 client_write_data(void *data, size_t datalen)
572 {
573 	struct msg_write_data	*msg = data;
574 	struct client_file	 find, *cf;
575 	size_t			 size = datalen - sizeof *msg;
576 
577 	if (datalen < sizeof *msg)
578 		fatalx("bad MSG_WRITE size");
579 	find.stream = msg->stream;
580 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
581 		fatalx("unknown stream number");
582 	log_debug("write %zu to file %d", size, cf->stream);
583 
584 	if (cf->event != NULL)
585 		bufferevent_write(cf->event, msg + 1, size);
586 }
587 
588 /* Close client file. */
589 static void
590 client_write_close(void *data, size_t datalen)
591 {
592 	struct msg_write_close	*msg = data;
593 	struct client_file	 find, *cf;
594 
595 	if (datalen != sizeof *msg)
596 		fatalx("bad MSG_WRITE_CLOSE size");
597 	find.stream = msg->stream;
598 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
599 		fatalx("unknown stream number");
600 	log_debug("close file %d", cf->stream);
601 
602 	if (cf->event == NULL || EVBUFFER_LENGTH(cf->event->output) == 0) {
603 		if (cf->event != NULL)
604 			bufferevent_free(cf->event);
605 		if (cf->fd != -1)
606 			close(cf->fd);
607 		RB_REMOVE(client_files, &client_files, cf);
608 		file_free(cf);
609 	}
610 }
611 
612 /* File read callback. */
613 static void
614 client_read_callback(__unused struct bufferevent *bev, void *arg)
615 {
616 	struct client_file	*cf = arg;
617 	void			*bdata;
618 	size_t			 bsize;
619 	struct msg_read_data	*msg;
620 	size_t			 msglen;
621 
622 	msg = xmalloc(sizeof *msg);
623 	for (;;) {
624 		bdata = EVBUFFER_DATA(cf->event->input);
625 		bsize = EVBUFFER_LENGTH(cf->event->input);
626 
627 		if (bsize == 0)
628 			break;
629 		if (bsize > MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg)
630 			bsize = MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg;
631 		log_debug("read %zu from file %d", bsize, cf->stream);
632 
633 		msglen = (sizeof *msg) + bsize;
634 		msg = xrealloc(msg, msglen);
635 		msg->stream = cf->stream;
636 		memcpy(msg + 1, bdata, bsize);
637 		proc_send(client_peer, MSG_READ, -1, msg, msglen);
638 
639 		evbuffer_drain(cf->event->input, bsize);
640 	}
641 	free(msg);
642 }
643 
644 /* File read error callback. */
645 static void
646 client_read_error_callback(__unused struct bufferevent *bev,
647     __unused short what, void *arg)
648 {
649 	struct client_file	*cf = arg;
650 	struct msg_read_done	 msg;
651 
652 	log_debug("read error file %d", cf->stream);
653 
654 	msg.stream = cf->stream;
655 	msg.error = 0;
656 	proc_send(client_peer, MSG_READ_DONE, -1, &msg, sizeof msg);
657 
658 	bufferevent_free(cf->event);
659 	close(cf->fd);
660 	RB_REMOVE(client_files, &client_files, cf);
661 	file_free(cf);
662 }
663 
664 /* Open read file. */
665 static void
666 client_read_open(void *data, size_t datalen)
667 {
668 	struct msg_read_open	*msg = data;
669 	const char		*path;
670 	struct msg_read_done	 reply;
671 	struct client_file	 find, *cf;
672 	const int		 flags = O_NONBLOCK|O_RDONLY;
673 	int			 error;
674 
675 	if (datalen < sizeof *msg)
676 		fatalx("bad MSG_READ_OPEN size");
677 	if (datalen == sizeof *msg)
678 		path = "-";
679 	else
680 		path = (const char *)(msg + 1);
681 	log_debug("open read file %d %s", msg->stream, path);
682 
683 	find.stream = msg->stream;
684 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
685 		cf = file_create(NULL, msg->stream, NULL, NULL);
686 		RB_INSERT(client_files, &client_files, cf);
687 	} else {
688 		error = EBADF;
689 		goto reply;
690 	}
691 	if (cf->closed) {
692 		error = EBADF;
693 		goto reply;
694 	}
695 
696 	cf->fd = -1;
697 	if (msg->fd == -1)
698 		cf->fd = open(path, flags);
699 	else {
700 		if (msg->fd != STDIN_FILENO)
701 			errno = EBADF;
702 		else {
703 			cf->fd = dup(msg->fd);
704 			if (~client_flags & CLIENT_CONTROL)
705 				close(msg->fd); /* can only be used once */
706 		}
707 	}
708 	if (cf->fd == -1) {
709 		error = errno;
710 		goto reply;
711 	}
712 
713 	cf->event = bufferevent_new(cf->fd, client_read_callback, NULL,
714 	    client_read_error_callback, cf);
715 	bufferevent_enable(cf->event, EV_READ);
716 	return;
717 
718 reply:
719 	reply.stream = msg->stream;
720 	reply.error = error;
721 	proc_send(client_peer, MSG_READ_DONE, -1, &reply, sizeof reply);
722 }
723 
724 /* Run command in shell; used for -c. */
725 static __dead void
726 client_exec(const char *shell, const char *shellcmd)
727 {
728 	const char	*name, *ptr;
729 	char		*argv0;
730 
731 	log_debug("shell %s, command %s", shell, shellcmd);
732 
733 	ptr = strrchr(shell, '/');
734 	if (ptr != NULL && *(ptr + 1) != '\0')
735 		name = ptr + 1;
736 	else
737 		name = shell;
738 	if (client_flags & CLIENT_LOGIN)
739 		xasprintf(&argv0, "-%s", name);
740 	else
741 		xasprintf(&argv0, "%s", name);
742 	setenv("SHELL", shell, 1);
743 
744 	proc_clear_signals(client_proc, 1);
745 
746 	setblocking(STDIN_FILENO, 1);
747 	setblocking(STDOUT_FILENO, 1);
748 	setblocking(STDERR_FILENO, 1);
749 	closefrom(STDERR_FILENO + 1);
750 
751 	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
752 	fatal("execl failed");
753 }
754 
755 /* Callback to handle signals in the client. */
756 static void
757 client_signal(int sig)
758 {
759 	struct sigaction sigact;
760 	int		 status;
761 
762 	if (sig == SIGCHLD)
763 		waitpid(WAIT_ANY, &status, WNOHANG);
764 	else if (!client_attached) {
765 		if (sig == SIGTERM)
766 			proc_exit(client_proc);
767 	} else {
768 		switch (sig) {
769 		case SIGHUP:
770 			client_exitreason = CLIENT_EXIT_LOST_TTY;
771 			client_exitval = 1;
772 			proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
773 			break;
774 		case SIGTERM:
775 			client_exitreason = CLIENT_EXIT_TERMINATED;
776 			client_exitval = 1;
777 			proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
778 			break;
779 		case SIGWINCH:
780 			proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
781 			break;
782 		case SIGCONT:
783 			memset(&sigact, 0, sizeof sigact);
784 			sigemptyset(&sigact.sa_mask);
785 			sigact.sa_flags = SA_RESTART;
786 			sigact.sa_handler = SIG_IGN;
787 			if (sigaction(SIGTSTP, &sigact, NULL) != 0)
788 				fatal("sigaction failed");
789 			proc_send(client_peer, MSG_WAKEUP, -1, NULL, 0);
790 			break;
791 		}
792 	}
793 }
794 
795 /* Callback for client read events. */
796 static void
797 client_dispatch(struct imsg *imsg, __unused void *arg)
798 {
799 	if (imsg == NULL) {
800 		client_exitreason = CLIENT_EXIT_LOST_SERVER;
801 		client_exitval = 1;
802 		proc_exit(client_proc);
803 		return;
804 	}
805 
806 	if (client_attached)
807 		client_dispatch_attached(imsg);
808 	else
809 		client_dispatch_wait(imsg);
810 }
811 
812 /* Process an exit message. */
813 static void
814 client_dispatch_exit_message(char *data, size_t datalen)
815 {
816 	int	retval;
817 
818 	if (datalen < sizeof retval && datalen != 0)
819 		fatalx("bad MSG_EXIT size");
820 
821 	if (datalen >= sizeof retval) {
822 		memcpy(&retval, data, sizeof retval);
823 		client_exitval = retval;
824 	}
825 
826 	if (datalen > sizeof retval) {
827 		datalen -= sizeof retval;
828 		data += sizeof retval;
829 
830 		client_exitmessage = xmalloc(datalen);
831 		memcpy(client_exitmessage, data, datalen);
832 		client_exitmessage[datalen - 1] = '\0';
833 
834 		client_exitreason = CLIENT_EXIT_MESSAGE_PROVIDED;
835 	}
836 }
837 
838 /* Dispatch imsgs when in wait state (before MSG_READY). */
839 static void
840 client_dispatch_wait(struct imsg *imsg)
841 {
842 	char		*data;
843 	ssize_t		 datalen;
844 	static int	 pledge_applied;
845 
846 	/*
847 	 * "sendfd" is no longer required once all of the identify messages
848 	 * have been sent. We know the server won't send us anything until that
849 	 * point (because we don't ask it to), so we can drop "sendfd" once we
850 	 * get the first message from the server.
851 	 */
852 	if (!pledge_applied) {
853 		if (pledge(
854 		    "stdio rpath wpath cpath unix proc exec tty",
855 		    NULL) != 0)
856 			fatal("pledge failed");
857 		pledge_applied = 1;
858 	}
859 
860 	data = imsg->data;
861 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
862 
863 	switch (imsg->hdr.type) {
864 	case MSG_EXIT:
865 	case MSG_SHUTDOWN:
866 		client_dispatch_exit_message(data, datalen);
867 		client_exitflag = 1;
868 		client_exit();
869 		break;
870 	case MSG_READY:
871 		if (datalen != 0)
872 			fatalx("bad MSG_READY size");
873 
874 		client_attached = 1;
875 		proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
876 		break;
877 	case MSG_VERSION:
878 		if (datalen != 0)
879 			fatalx("bad MSG_VERSION size");
880 
881 		fprintf(stderr, "protocol version mismatch "
882 		    "(client %d, server %u)\n", PROTOCOL_VERSION,
883 		    imsg->hdr.peerid & 0xff);
884 		client_exitval = 1;
885 		proc_exit(client_proc);
886 		break;
887 	case MSG_FLAGS:
888 		if (datalen != sizeof client_flags)
889 			fatalx("bad MSG_FLAGS string");
890 
891 		memcpy(&client_flags, data, sizeof client_flags);
892 		log_debug("new flags are %#llx", client_flags);
893 		break;
894 	case MSG_SHELL:
895 		if (datalen == 0 || data[datalen - 1] != '\0')
896 			fatalx("bad MSG_SHELL string");
897 
898 		client_exec(data, shell_command);
899 		/* NOTREACHED */
900 	case MSG_DETACH:
901 	case MSG_DETACHKILL:
902 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
903 		break;
904 	case MSG_EXITED:
905 		proc_exit(client_proc);
906 		break;
907 	case MSG_READ_OPEN:
908 		client_read_open(data, datalen);
909 		break;
910 	case MSG_WRITE_OPEN:
911 		client_write_open(data, datalen);
912 		break;
913 	case MSG_WRITE:
914 		client_write_data(data, datalen);
915 		break;
916 	case MSG_WRITE_CLOSE:
917 		client_write_close(data, datalen);
918 		break;
919 	case MSG_OLDSTDERR:
920 	case MSG_OLDSTDIN:
921 	case MSG_OLDSTDOUT:
922 		fprintf(stderr, "server version is too old for client\n");
923 		proc_exit(client_proc);
924 		break;
925 	}
926 }
927 
928 /* Dispatch imsgs in attached state (after MSG_READY). */
929 static void
930 client_dispatch_attached(struct imsg *imsg)
931 {
932 	struct sigaction	 sigact;
933 	char			*data;
934 	ssize_t			 datalen;
935 
936 	data = imsg->data;
937 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
938 
939 	switch (imsg->hdr.type) {
940 	case MSG_FLAGS:
941 		if (datalen != sizeof client_flags)
942 			fatalx("bad MSG_FLAGS string");
943 
944 		memcpy(&client_flags, data, sizeof client_flags);
945 		log_debug("new flags are %#llx", client_flags);
946 		break;
947 	case MSG_DETACH:
948 	case MSG_DETACHKILL:
949 		if (datalen == 0 || data[datalen - 1] != '\0')
950 			fatalx("bad MSG_DETACH string");
951 
952 		client_exitsession = xstrdup(data);
953 		client_exittype = imsg->hdr.type;
954 		if (imsg->hdr.type == MSG_DETACHKILL)
955 			client_exitreason = CLIENT_EXIT_DETACHED_HUP;
956 		else
957 			client_exitreason = CLIENT_EXIT_DETACHED;
958 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
959 		break;
960 	case MSG_EXEC:
961 		if (datalen == 0 || data[datalen - 1] != '\0' ||
962 		    strlen(data) + 1 == (size_t)datalen)
963 			fatalx("bad MSG_EXEC string");
964 		client_execcmd = xstrdup(data);
965 		client_execshell = xstrdup(data + strlen(data) + 1);
966 
967 		client_exittype = imsg->hdr.type;
968 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
969 		break;
970 	case MSG_EXIT:
971 		client_dispatch_exit_message(data, datalen);
972 		if (client_exitreason == CLIENT_EXIT_NONE)
973 			client_exitreason = CLIENT_EXIT_EXITED;
974 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
975 		break;
976 	case MSG_EXITED:
977 		if (datalen != 0)
978 			fatalx("bad MSG_EXITED size");
979 
980 		proc_exit(client_proc);
981 		break;
982 	case MSG_SHUTDOWN:
983 		if (datalen != 0)
984 			fatalx("bad MSG_SHUTDOWN size");
985 
986 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
987 		client_exitreason = CLIENT_EXIT_SERVER_EXITED;
988 		client_exitval = 1;
989 		break;
990 	case MSG_SUSPEND:
991 		if (datalen != 0)
992 			fatalx("bad MSG_SUSPEND size");
993 
994 		memset(&sigact, 0, sizeof sigact);
995 		sigemptyset(&sigact.sa_mask);
996 		sigact.sa_flags = SA_RESTART;
997 		sigact.sa_handler = SIG_DFL;
998 		if (sigaction(SIGTSTP, &sigact, NULL) != 0)
999 			fatal("sigaction failed");
1000 		kill(getpid(), SIGTSTP);
1001 		break;
1002 	case MSG_LOCK:
1003 		if (datalen == 0 || data[datalen - 1] != '\0')
1004 			fatalx("bad MSG_LOCK string");
1005 
1006 		system(data);
1007 		proc_send(client_peer, MSG_UNLOCK, -1, NULL, 0);
1008 		break;
1009 	}
1010 }
1011