xref: /openbsd-src/usr.bin/tmux/client.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /* $OpenBSD: client.c,v 1.137 2020/01/29 16:22:32 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 *);
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 start_server)
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 (!start_server)
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, 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)
237 {
238 	struct cmd_parse_result	*pr;
239 	struct cmd		*cmd;
240 	struct msg_command	*data;
241 	int			 cmdflags, fd, i;
242 	const char		*ttynam, *cwd;
243 	pid_t			 ppid;
244 	enum msgtype		 msg;
245 	struct termios		 tio, saved_tio;
246 	size_t			 size;
247 
248 	/* Ignore SIGCHLD now or daemon() in the server will leave a zombie. */
249 	signal(SIGCHLD, SIG_IGN);
250 
251 	/* Save the flags. */
252 	client_flags = flags;
253 
254 	/* Set up the initial command. */
255 	cmdflags = 0;
256 	if (shell_command != NULL) {
257 		msg = MSG_SHELL;
258 		cmdflags = CMD_STARTSERVER;
259 	} else if (argc == 0) {
260 		msg = MSG_COMMAND;
261 		cmdflags = CMD_STARTSERVER;
262 	} else {
263 		msg = MSG_COMMAND;
264 
265 		/*
266 		 * It sucks parsing the command string twice (in client and
267 		 * later in server) but it is necessary to get the start server
268 		 * flag.
269 		 */
270 		pr = cmd_parse_from_arguments(argc, argv, NULL);
271 		if (pr->status == CMD_PARSE_SUCCESS) {
272 			TAILQ_FOREACH(cmd, &pr->cmdlist->list, qentry) {
273 				if (cmd->entry->flags & CMD_STARTSERVER)
274 					cmdflags |= CMD_STARTSERVER;
275 			}
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 	/* Initialize the client socket and start the server. */
286 	fd = client_connect(base, socket_path, cmdflags & CMD_STARTSERVER);
287 	if (fd == -1) {
288 		if (errno == ECONNREFUSED) {
289 			fprintf(stderr, "no server running on %s\n",
290 			    socket_path);
291 		} else {
292 			fprintf(stderr, "error connecting to %s (%s)\n",
293 			    socket_path, strerror(errno));
294 		}
295 		return (1);
296 	}
297 	client_peer = proc_add_peer(client_proc, fd, client_dispatch, NULL);
298 
299 	/* Save these before pledge(). */
300 	if ((cwd = find_cwd()) == NULL && (cwd = find_home()) == NULL)
301 		cwd = "/";
302 	if ((ttynam = ttyname(STDIN_FILENO)) == NULL)
303 		ttynam = "";
304 
305 	/*
306 	 * Drop privileges for client. "proc exec" is needed for -c and for
307 	 * locking (which uses system(3)).
308 	 *
309 	 * "tty" is needed to restore termios(4) and also for some reason -CC
310 	 * does not work properly without it (input is not recognised).
311 	 *
312 	 * "sendfd" is dropped later in client_dispatch_wait().
313 	 */
314 	if (pledge(
315 	    "stdio rpath wpath cpath unix sendfd proc exec tty",
316 	    NULL) != 0)
317 		fatal("pledge failed");
318 
319 	/* Free stuff that is not used in the client. */
320 	if (ptm_fd != -1)
321 		close(ptm_fd);
322 	options_free(global_options);
323 	options_free(global_s_options);
324 	options_free(global_w_options);
325 	environ_free(global_environ);
326 
327 	/* Set up control mode. */
328 	if (client_flags & CLIENT_CONTROLCONTROL) {
329 		if (tcgetattr(STDIN_FILENO, &saved_tio) != 0) {
330 			fprintf(stderr, "tcgetattr failed: %s\n",
331 			    strerror(errno));
332 			return (1);
333 		}
334 		cfmakeraw(&tio);
335 		tio.c_iflag = ICRNL|IXANY;
336 		tio.c_oflag = OPOST|ONLCR;
337 		tio.c_lflag = NOKERNINFO;
338 		tio.c_cflag = CREAD|CS8|HUPCL;
339 		tio.c_cc[VMIN] = 1;
340 		tio.c_cc[VTIME] = 0;
341 		cfsetispeed(&tio, cfgetispeed(&saved_tio));
342 		cfsetospeed(&tio, cfgetospeed(&saved_tio));
343 		tcsetattr(STDIN_FILENO, TCSANOW, &tio);
344 	}
345 
346 	/* Send identify messages. */
347 	client_send_identify(ttynam, cwd);
348 
349 	/* Send first command. */
350 	if (msg == MSG_COMMAND) {
351 		/* How big is the command? */
352 		size = 0;
353 		for (i = 0; i < argc; i++)
354 			size += strlen(argv[i]) + 1;
355 		if (size > MAX_IMSGSIZE - (sizeof *data)) {
356 			fprintf(stderr, "command too long\n");
357 			return (1);
358 		}
359 		data = xmalloc((sizeof *data) + size);
360 
361 		/* Prepare command for server. */
362 		data->argc = argc;
363 		if (cmd_pack_argv(argc, argv, (char *)(data + 1), size) != 0) {
364 			fprintf(stderr, "command too long\n");
365 			free(data);
366 			return (1);
367 		}
368 		size += sizeof *data;
369 
370 		/* Send the command. */
371 		if (proc_send(client_peer, msg, -1, data, size) != 0) {
372 			fprintf(stderr, "failed to send command\n");
373 			free(data);
374 			return (1);
375 		}
376 		free(data);
377 	} else if (msg == MSG_SHELL)
378 		proc_send(client_peer, msg, -1, NULL, 0);
379 
380 	/* Start main loop. */
381 	proc_loop(client_proc, NULL);
382 
383 	/* Run command if user requested exec, instead of exiting. */
384 	if (client_exittype == MSG_EXEC) {
385 		if (client_flags & CLIENT_CONTROLCONTROL)
386 			tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
387 		client_exec(client_execshell, client_execcmd);
388 	}
389 
390 	/* Print the exit message, if any, and exit. */
391 	if (client_attached) {
392 		if (client_exitreason != CLIENT_EXIT_NONE)
393 			printf("[%s]\n", client_exit_message());
394 
395 		ppid = getppid();
396 		if (client_exittype == MSG_DETACHKILL && ppid > 1)
397 			kill(ppid, SIGHUP);
398 	} else if (client_flags & CLIENT_CONTROLCONTROL) {
399 		if (client_exitreason != CLIENT_EXIT_NONE)
400 			printf("%%exit %s\n", client_exit_message());
401 		else
402 			printf("%%exit\n");
403 		printf("\033\\");
404 		tcsetattr(STDOUT_FILENO, TCSAFLUSH, &saved_tio);
405 	} else if (client_exitreason != CLIENT_EXIT_NONE)
406 		fprintf(stderr, "%s\n", client_exit_message());
407 	setblocking(STDIN_FILENO, 1);
408 	return (client_exitval);
409 }
410 
411 /* Send identify messages to server. */
412 static void
413 client_send_identify(const char *ttynam, const char *cwd)
414 {
415 	const char	 *s;
416 	char		**ss;
417 	size_t		  sslen;
418 	int		  fd, flags = client_flags;
419 	pid_t		  pid;
420 
421 	proc_send(client_peer, MSG_IDENTIFY_FLAGS, -1, &flags, sizeof flags);
422 
423 	if ((s = getenv("TERM")) == NULL)
424 		s = "";
425 	proc_send(client_peer, MSG_IDENTIFY_TERM, -1, s, strlen(s) + 1);
426 
427 	proc_send(client_peer, MSG_IDENTIFY_TTYNAME, -1, ttynam,
428 	    strlen(ttynam) + 1);
429 	proc_send(client_peer, MSG_IDENTIFY_CWD, -1, cwd, strlen(cwd) + 1);
430 
431 	if ((fd = dup(STDIN_FILENO)) == -1)
432 		fatal("dup failed");
433 	proc_send(client_peer, MSG_IDENTIFY_STDIN, fd, NULL, 0);
434 
435 	pid = getpid();
436 	proc_send(client_peer, MSG_IDENTIFY_CLIENTPID, -1, &pid, sizeof pid);
437 
438 	for (ss = environ; *ss != NULL; ss++) {
439 		sslen = strlen(*ss) + 1;
440 		if (sslen > MAX_IMSGSIZE - IMSG_HEADER_SIZE)
441 			continue;
442 		proc_send(client_peer, MSG_IDENTIFY_ENVIRON, -1, *ss, sslen);
443 	}
444 
445 	proc_send(client_peer, MSG_IDENTIFY_DONE, -1, NULL, 0);
446 }
447 
448 /* File write error callback. */
449 static void
450 client_write_error_callback(__unused struct bufferevent *bev,
451     __unused short what, void *arg)
452 {
453 	struct client_file	*cf = arg;
454 
455 	log_debug("write error file %d", cf->stream);
456 
457 	bufferevent_free(cf->event);
458 	cf->event = NULL;
459 
460 	close(cf->fd);
461 	cf->fd = -1;
462 
463 	if (client_exitflag)
464 		client_exit();
465 }
466 
467 /* File write callback. */
468 static void
469 client_write_callback(__unused struct bufferevent *bev, void *arg)
470 {
471 	struct client_file	*cf = arg;
472 
473 	if (cf->closed && EVBUFFER_LENGTH(cf->event->output) == 0) {
474 		bufferevent_free(cf->event);
475 		close(cf->fd);
476 		RB_REMOVE(client_files, &client_files, cf);
477 		file_free(cf);
478 	}
479 
480 	if (client_exitflag)
481 		client_exit();
482 }
483 
484 /* Open write file. */
485 static void
486 client_write_open(void *data, size_t datalen)
487 {
488 	struct msg_write_open	*msg = data;
489 	const char		*path;
490 	struct msg_write_ready	 reply;
491 	struct client_file	 find, *cf;
492 	const int		 flags = O_NONBLOCK|O_WRONLY|O_CREAT;
493 	int			 error = 0;
494 
495 	if (datalen < sizeof *msg)
496 		fatalx("bad MSG_WRITE_OPEN size");
497 	if (datalen == sizeof *msg)
498 		path = "-";
499 	else
500 		path = (const char *)(msg + 1);
501 	log_debug("open write file %d %s", msg->stream, path);
502 
503 	find.stream = msg->stream;
504 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
505 		cf = file_create(NULL, msg->stream, NULL, NULL);
506 		RB_INSERT(client_files, &client_files, cf);
507 	} else {
508 		error = EBADF;
509 		goto reply;
510 	}
511 	if (cf->closed) {
512 		error = EBADF;
513 		goto reply;
514 	}
515 
516 	cf->fd = -1;
517 	if (msg->fd == -1)
518 		cf->fd = open(path, msg->flags|flags, 0644);
519 	else {
520 		if (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)
521 			errno = EBADF;
522 		else {
523 			cf->fd = dup(msg->fd);
524 			if (client_flags & CLIENT_CONTROL)
525 				close(msg->fd); /* can only be used once */
526 		}
527 	}
528 	if (cf->fd == -1) {
529 		error = errno;
530 		goto reply;
531 	}
532 
533 	cf->event = bufferevent_new(cf->fd, NULL, client_write_callback,
534 	    client_write_error_callback, cf);
535 	bufferevent_enable(cf->event, EV_WRITE);
536 	goto reply;
537 
538 reply:
539 	reply.stream = msg->stream;
540 	reply.error = error;
541 	proc_send(client_peer, MSG_WRITE_READY, -1, &reply, sizeof reply);
542 }
543 
544 /* Write to client file. */
545 static void
546 client_write_data(void *data, size_t datalen)
547 {
548 	struct msg_write_data	*msg = data;
549 	struct client_file	 find, *cf;
550 	size_t			 size = datalen - sizeof *msg;
551 
552 	if (datalen < sizeof *msg)
553 		fatalx("bad MSG_WRITE size");
554 	find.stream = msg->stream;
555 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
556 		fatalx("unknown stream number");
557 	log_debug("write %zu to file %d", size, cf->stream);
558 
559 	if (cf->event != NULL)
560 		bufferevent_write(cf->event, msg + 1, size);
561 }
562 
563 /* Close client file. */
564 static void
565 client_write_close(void *data, size_t datalen)
566 {
567 	struct msg_write_close	*msg = data;
568 	struct client_file	 find, *cf;
569 
570 	if (datalen != sizeof *msg)
571 		fatalx("bad MSG_WRITE_CLOSE size");
572 	find.stream = msg->stream;
573 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL)
574 		fatalx("unknown stream number");
575 	log_debug("close file %d", cf->stream);
576 
577 	if (cf->event == NULL || EVBUFFER_LENGTH(cf->event->output) == 0) {
578 		if (cf->event != NULL)
579 			bufferevent_free(cf->event);
580 		if (cf->fd != -1)
581 			close(cf->fd);
582 		RB_REMOVE(client_files, &client_files, cf);
583 		file_free(cf);
584 	}
585 }
586 
587 /* File read callback. */
588 static void
589 client_read_callback(__unused struct bufferevent *bev, void *arg)
590 {
591 	struct client_file	*cf = arg;
592 	void			*bdata;
593 	size_t			 bsize;
594 	struct msg_read_data	*msg;
595 	size_t			 msglen;
596 
597 	msg = xmalloc(sizeof *msg);
598 	for (;;) {
599 		bdata = EVBUFFER_DATA(cf->event->input);
600 		bsize = EVBUFFER_LENGTH(cf->event->input);
601 
602 		if (bsize == 0)
603 			break;
604 		if (bsize > MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg)
605 			bsize = MAX_IMSGSIZE - IMSG_HEADER_SIZE - sizeof *msg;
606 		log_debug("read %zu from file %d", bsize, cf->stream);
607 
608 		msglen = (sizeof *msg) + bsize;
609 		msg = xrealloc(msg, msglen);
610 		msg->stream = cf->stream;
611 		memcpy(msg + 1, bdata, bsize);
612 		proc_send(client_peer, MSG_READ, -1, msg, msglen);
613 
614 		evbuffer_drain(cf->event->input, bsize);
615 	}
616 	free(msg);
617 }
618 
619 /* File read error callback. */
620 static void
621 client_read_error_callback(__unused struct bufferevent *bev,
622     __unused short what, void *arg)
623 {
624 	struct client_file	*cf = arg;
625 	struct msg_read_done	 msg;
626 
627 	log_debug("read error file %d", cf->stream);
628 
629 	msg.stream = cf->stream;
630 	msg.error = 0;
631 	proc_send(client_peer, MSG_READ_DONE, -1, &msg, sizeof msg);
632 
633 	bufferevent_free(cf->event);
634 	close(cf->fd);
635 	RB_REMOVE(client_files, &client_files, cf);
636 	file_free(cf);
637 }
638 
639 /* Open read file. */
640 static void
641 client_read_open(void *data, size_t datalen)
642 {
643 	struct msg_read_open	*msg = data;
644 	const char		*path;
645 	struct msg_read_done	 reply;
646 	struct client_file	 find, *cf;
647 	const int		 flags = O_NONBLOCK|O_RDONLY;
648 	int			 error = 0;
649 
650 	if (datalen < sizeof *msg)
651 		fatalx("bad MSG_READ_OPEN size");
652 	if (datalen == sizeof *msg)
653 		path = "-";
654 	else
655 		path = (const char *)(msg + 1);
656 	log_debug("open read file %d %s", msg->stream, path);
657 
658 	find.stream = msg->stream;
659 	if ((cf = RB_FIND(client_files, &client_files, &find)) == NULL) {
660 		cf = file_create(NULL, msg->stream, NULL, NULL);
661 		RB_INSERT(client_files, &client_files, cf);
662 	} else {
663 		error = EBADF;
664 		goto reply;
665 	}
666 	if (cf->closed) {
667 		error = EBADF;
668 		goto reply;
669 	}
670 
671 	cf->fd = -1;
672 	if (msg->fd == -1)
673 		cf->fd = open(path, flags);
674 	else {
675 		if (msg->fd != STDIN_FILENO)
676 			errno = EBADF;
677 		else {
678 			cf->fd = dup(msg->fd);
679 			close(msg->fd); /* can only be used once */
680 		}
681 	}
682 	if (cf->fd == -1) {
683 		error = errno;
684 		goto reply;
685 	}
686 
687 	cf->event = bufferevent_new(cf->fd, client_read_callback, NULL,
688 	    client_read_error_callback, cf);
689 	bufferevent_enable(cf->event, EV_READ);
690 	return;
691 
692 reply:
693 	reply.stream = msg->stream;
694 	reply.error = error;
695 	proc_send(client_peer, MSG_READ_DONE, -1, &reply, sizeof reply);
696 }
697 
698 /* Run command in shell; used for -c. */
699 static __dead void
700 client_exec(const char *shell, const char *shellcmd)
701 {
702 	const char	*name, *ptr;
703 	char		*argv0;
704 
705 	log_debug("shell %s, command %s", shell, shellcmd);
706 
707 	ptr = strrchr(shell, '/');
708 	if (ptr != NULL && *(ptr + 1) != '\0')
709 		name = ptr + 1;
710 	else
711 		name = shell;
712 	if (client_flags & CLIENT_LOGIN)
713 		xasprintf(&argv0, "-%s", name);
714 	else
715 		xasprintf(&argv0, "%s", name);
716 	setenv("SHELL", shell, 1);
717 
718 	proc_clear_signals(client_proc, 1);
719 
720 	setblocking(STDIN_FILENO, 1);
721 	setblocking(STDOUT_FILENO, 1);
722 	setblocking(STDERR_FILENO, 1);
723 	closefrom(STDERR_FILENO + 1);
724 
725 	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
726 	fatal("execl failed");
727 }
728 
729 /* Callback to handle signals in the client. */
730 static void
731 client_signal(int sig)
732 {
733 	struct sigaction sigact;
734 	int		 status;
735 
736 	if (sig == SIGCHLD)
737 		waitpid(WAIT_ANY, &status, WNOHANG);
738 	else if (!client_attached) {
739 		if (sig == SIGTERM)
740 			proc_exit(client_proc);
741 	} else {
742 		switch (sig) {
743 		case SIGHUP:
744 			client_exitreason = CLIENT_EXIT_LOST_TTY;
745 			client_exitval = 1;
746 			proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
747 			break;
748 		case SIGTERM:
749 			client_exitreason = CLIENT_EXIT_TERMINATED;
750 			client_exitval = 1;
751 			proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
752 			break;
753 		case SIGWINCH:
754 			proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
755 			break;
756 		case SIGCONT:
757 			memset(&sigact, 0, sizeof sigact);
758 			sigemptyset(&sigact.sa_mask);
759 			sigact.sa_flags = SA_RESTART;
760 			sigact.sa_handler = SIG_IGN;
761 			if (sigaction(SIGTSTP, &sigact, NULL) != 0)
762 				fatal("sigaction failed");
763 			proc_send(client_peer, MSG_WAKEUP, -1, NULL, 0);
764 			break;
765 		}
766 	}
767 }
768 
769 /* Callback for client read events. */
770 static void
771 client_dispatch(struct imsg *imsg, __unused void *arg)
772 {
773 	if (imsg == NULL) {
774 		client_exitreason = CLIENT_EXIT_LOST_SERVER;
775 		client_exitval = 1;
776 		proc_exit(client_proc);
777 		return;
778 	}
779 
780 	if (client_attached)
781 		client_dispatch_attached(imsg);
782 	else
783 		client_dispatch_wait(imsg);
784 }
785 
786 /* Dispatch imsgs when in wait state (before MSG_READY). */
787 static void
788 client_dispatch_wait(struct imsg *imsg)
789 {
790 	char		*data;
791 	ssize_t		 datalen;
792 	int		 retval;
793 	static int	 pledge_applied;
794 
795 	/*
796 	 * "sendfd" is no longer required once all of the identify messages
797 	 * have been sent. We know the server won't send us anything until that
798 	 * point (because we don't ask it to), so we can drop "sendfd" once we
799 	 * get the first message from the server.
800 	 */
801 	if (!pledge_applied) {
802 		if (pledge(
803 		    "stdio rpath wpath cpath unix proc exec tty",
804 		    NULL) != 0)
805 			fatal("pledge failed");
806 		pledge_applied = 1;
807 	}
808 
809 	data = imsg->data;
810 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
811 
812 	switch (imsg->hdr.type) {
813 	case MSG_EXIT:
814 	case MSG_SHUTDOWN:
815 		if (datalen != sizeof retval && datalen != 0)
816 			fatalx("bad MSG_EXIT size");
817 		if (datalen == sizeof retval) {
818 			memcpy(&retval, data, sizeof retval);
819 			client_exitval = retval;
820 		}
821 		client_exitflag = 1;
822 		client_exit();
823 		break;
824 	case MSG_READY:
825 		if (datalen != 0)
826 			fatalx("bad MSG_READY size");
827 
828 		client_attached = 1;
829 		proc_send(client_peer, MSG_RESIZE, -1, NULL, 0);
830 		break;
831 	case MSG_VERSION:
832 		if (datalen != 0)
833 			fatalx("bad MSG_VERSION size");
834 
835 		fprintf(stderr, "protocol version mismatch "
836 		    "(client %d, server %u)\n", PROTOCOL_VERSION,
837 		    imsg->hdr.peerid & 0xff);
838 		client_exitval = 1;
839 		proc_exit(client_proc);
840 		break;
841 	case MSG_SHELL:
842 		if (datalen == 0 || data[datalen - 1] != '\0')
843 			fatalx("bad MSG_SHELL string");
844 
845 		client_exec(data, shell_command);
846 		/* NOTREACHED */
847 	case MSG_DETACH:
848 	case MSG_DETACHKILL:
849 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
850 		break;
851 	case MSG_EXITED:
852 		proc_exit(client_proc);
853 		break;
854 	case MSG_READ_OPEN:
855 		client_read_open(data, datalen);
856 		break;
857 	case MSG_WRITE_OPEN:
858 		client_write_open(data, datalen);
859 		break;
860 	case MSG_WRITE:
861 		client_write_data(data, datalen);
862 		break;
863 	case MSG_WRITE_CLOSE:
864 		client_write_close(data, datalen);
865 		break;
866 	case MSG_OLDSTDERR:
867 	case MSG_OLDSTDIN:
868 	case MSG_OLDSTDOUT:
869 		fprintf(stderr, "server version is too old for client\n");
870 		proc_exit(client_proc);
871 		break;
872 	}
873 }
874 
875 /* Dispatch imsgs in attached state (after MSG_READY). */
876 static void
877 client_dispatch_attached(struct imsg *imsg)
878 {
879 	struct sigaction	 sigact;
880 	char			*data;
881 	ssize_t			 datalen;
882 
883 	data = imsg->data;
884 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
885 
886 	switch (imsg->hdr.type) {
887 	case MSG_DETACH:
888 	case MSG_DETACHKILL:
889 		if (datalen == 0 || data[datalen - 1] != '\0')
890 			fatalx("bad MSG_DETACH string");
891 
892 		client_exitsession = xstrdup(data);
893 		client_exittype = imsg->hdr.type;
894 		if (imsg->hdr.type == MSG_DETACHKILL)
895 			client_exitreason = CLIENT_EXIT_DETACHED_HUP;
896 		else
897 			client_exitreason = CLIENT_EXIT_DETACHED;
898 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
899 		break;
900 	case MSG_EXEC:
901 		if (datalen == 0 || data[datalen - 1] != '\0' ||
902 		    strlen(data) + 1 == (size_t)datalen)
903 			fatalx("bad MSG_EXEC string");
904 		client_execcmd = xstrdup(data);
905 		client_execshell = xstrdup(data + strlen(data) + 1);
906 
907 		client_exittype = imsg->hdr.type;
908 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
909 		break;
910 	case MSG_EXIT:
911 		if (datalen != 0 && datalen != sizeof (int))
912 			fatalx("bad MSG_EXIT size");
913 
914 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
915 		client_exitreason = CLIENT_EXIT_EXITED;
916 		break;
917 	case MSG_EXITED:
918 		if (datalen != 0)
919 			fatalx("bad MSG_EXITED size");
920 
921 		proc_exit(client_proc);
922 		break;
923 	case MSG_SHUTDOWN:
924 		if (datalen != 0)
925 			fatalx("bad MSG_SHUTDOWN size");
926 
927 		proc_send(client_peer, MSG_EXITING, -1, NULL, 0);
928 		client_exitreason = CLIENT_EXIT_SERVER_EXITED;
929 		client_exitval = 1;
930 		break;
931 	case MSG_SUSPEND:
932 		if (datalen != 0)
933 			fatalx("bad MSG_SUSPEND size");
934 
935 		memset(&sigact, 0, sizeof sigact);
936 		sigemptyset(&sigact.sa_mask);
937 		sigact.sa_flags = SA_RESTART;
938 		sigact.sa_handler = SIG_DFL;
939 		if (sigaction(SIGTSTP, &sigact, NULL) != 0)
940 			fatal("sigaction failed");
941 		kill(getpid(), SIGTSTP);
942 		break;
943 	case MSG_LOCK:
944 		if (datalen == 0 || data[datalen - 1] != '\0')
945 			fatalx("bad MSG_LOCK string");
946 
947 		system(data);
948 		proc_send(client_peer, MSG_UNLOCK, -1, NULL, 0);
949 		break;
950 	}
951 }
952