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