xref: /openbsd-src/usr.bin/tmux/server-client.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /* $OpenBSD: server-client.c,v 1.366 2020/12/03 07:12:11 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2009 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/ioctl.h>
21 #include <sys/uio.h>
22 
23 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <imsg.h>
27 #include <paths.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <time.h>
31 #include <unistd.h>
32 
33 #include "tmux.h"
34 
35 static void	server_client_free(int, short, void *);
36 static void	server_client_check_pane_focus(struct window_pane *);
37 static void	server_client_check_pane_resize(struct window_pane *);
38 static void	server_client_check_pane_buffer(struct window_pane *);
39 static void	server_client_check_window_resize(struct window *);
40 static key_code	server_client_check_mouse(struct client *, struct key_event *);
41 static void	server_client_repeat_timer(int, short, void *);
42 static void	server_client_click_timer(int, short, void *);
43 static void	server_client_check_exit(struct client *);
44 static void	server_client_check_redraw(struct client *);
45 static void	server_client_check_modes(struct client *);
46 static void	server_client_set_title(struct client *);
47 static void	server_client_reset_state(struct client *);
48 static int	server_client_assume_paste(struct session *);
49 
50 static void	server_client_dispatch(struct imsg *, void *);
51 static void	server_client_dispatch_command(struct client *, struct imsg *);
52 static void	server_client_dispatch_identify(struct client *, struct imsg *);
53 static void	server_client_dispatch_shell(struct client *);
54 static void	server_client_dispatch_write_ready(struct client *,
55 		    struct imsg *);
56 static void	server_client_dispatch_read_data(struct client *,
57 		    struct imsg *);
58 static void	server_client_dispatch_read_done(struct client *,
59 		    struct imsg *);
60 
61 /* Compare client windows. */
62 static int
63 server_client_window_cmp(struct client_window *cw1,
64     struct client_window *cw2)
65 {
66 	if (cw1->window < cw2->window)
67 		return (-1);
68 	if (cw1->window > cw2->window)
69 		return (1);
70 	return (0);
71 }
72 RB_GENERATE(client_windows, client_window, entry, server_client_window_cmp);
73 
74 /* Number of attached clients. */
75 u_int
76 server_client_how_many(void)
77 {
78 	struct client  	*c;
79 	u_int		 n;
80 
81 	n = 0;
82 	TAILQ_FOREACH(c, &clients, entry) {
83 		if (c->session != NULL && (~c->flags & CLIENT_UNATTACHEDFLAGS))
84 			n++;
85 	}
86 	return (n);
87 }
88 
89 /* Overlay timer callback. */
90 static void
91 server_client_overlay_timer(__unused int fd, __unused short events, void *data)
92 {
93 	server_client_clear_overlay(data);
94 }
95 
96 /* Set an overlay on client. */
97 void
98 server_client_set_overlay(struct client *c, u_int delay,
99     overlay_check_cb checkcb, overlay_mode_cb modecb,
100     overlay_draw_cb drawcb, overlay_key_cb keycb, overlay_free_cb freecb,
101     void *data)
102 {
103 	struct timeval	tv;
104 
105 	if (c->overlay_draw != NULL)
106 		server_client_clear_overlay(c);
107 
108 	tv.tv_sec = delay / 1000;
109 	tv.tv_usec = (delay % 1000) * 1000L;
110 
111 	if (event_initialized(&c->overlay_timer))
112 		evtimer_del(&c->overlay_timer);
113 	evtimer_set(&c->overlay_timer, server_client_overlay_timer, c);
114 	if (delay != 0)
115 		evtimer_add(&c->overlay_timer, &tv);
116 
117 	c->overlay_check = checkcb;
118 	c->overlay_mode = modecb;
119 	c->overlay_draw = drawcb;
120 	c->overlay_key = keycb;
121 	c->overlay_free = freecb;
122 	c->overlay_data = data;
123 
124 	c->tty.flags |= TTY_FREEZE;
125 	if (c->overlay_mode == NULL)
126 		c->tty.flags |= TTY_NOCURSOR;
127 	server_redraw_client(c);
128 }
129 
130 /* Clear overlay mode on client. */
131 void
132 server_client_clear_overlay(struct client *c)
133 {
134 	if (c->overlay_draw == NULL)
135 		return;
136 
137 	if (event_initialized(&c->overlay_timer))
138 		evtimer_del(&c->overlay_timer);
139 
140 	if (c->overlay_free != NULL)
141 		c->overlay_free(c);
142 
143 	c->overlay_check = NULL;
144 	c->overlay_mode = NULL;
145 	c->overlay_draw = NULL;
146 	c->overlay_key = NULL;
147 	c->overlay_free = NULL;
148 	c->overlay_data = NULL;
149 
150 	c->tty.flags &= ~(TTY_FREEZE|TTY_NOCURSOR);
151 	server_redraw_client(c);
152 }
153 
154 /* Check if this client is inside this server. */
155 int
156 server_client_check_nested(struct client *c)
157 {
158 	struct environ_entry	*envent;
159 	struct window_pane	*wp;
160 
161 	envent = environ_find(c->environ, "TMUX");
162 	if (envent == NULL || *envent->value == '\0')
163 		return (0);
164 
165 	RB_FOREACH(wp, window_pane_tree, &all_window_panes) {
166 		if (strcmp(wp->tty, c->ttyname) == 0)
167 			return (1);
168 	}
169 	return (0);
170 }
171 
172 /* Set client key table. */
173 void
174 server_client_set_key_table(struct client *c, const char *name)
175 {
176 	if (name == NULL)
177 		name = server_client_get_key_table(c);
178 
179 	key_bindings_unref_table(c->keytable);
180 	c->keytable = key_bindings_get_table(name, 1);
181 	c->keytable->references++;
182 }
183 
184 /* Get default key table. */
185 const char *
186 server_client_get_key_table(struct client *c)
187 {
188 	struct session	*s = c->session;
189 	const char	*name;
190 
191 	if (s == NULL)
192 		return ("root");
193 
194 	name = options_get_string(s->options, "key-table");
195 	if (*name == '\0')
196 		return ("root");
197 	return (name);
198 }
199 
200 /* Is this table the default key table? */
201 static int
202 server_client_is_default_key_table(struct client *c, struct key_table *table)
203 {
204 	return (strcmp(table->name, server_client_get_key_table(c)) == 0);
205 }
206 
207 /* Create a new client. */
208 struct client *
209 server_client_create(int fd)
210 {
211 	struct client	*c;
212 
213 	setblocking(fd, 0);
214 
215 	c = xcalloc(1, sizeof *c);
216 	c->references = 1;
217 	c->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);
218 
219 	if (gettimeofday(&c->creation_time, NULL) != 0)
220 		fatal("gettimeofday failed");
221 	memcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);
222 
223 	c->environ = environ_create();
224 
225 	c->fd = -1;
226 	c->out_fd = -1;
227 
228 	c->queue = cmdq_new();
229 	RB_INIT(&c->windows);
230 	RB_INIT(&c->files);
231 
232 	c->tty.sx = 80;
233 	c->tty.sy = 24;
234 
235 	status_init(c);
236 	c->flags |= CLIENT_FOCUSED;
237 
238 	c->keytable = key_bindings_get_table("root", 1);
239 	c->keytable->references++;
240 
241 	evtimer_set(&c->repeat_timer, server_client_repeat_timer, c);
242 	evtimer_set(&c->click_timer, server_client_click_timer, c);
243 
244 	TAILQ_INSERT_TAIL(&clients, c, entry);
245 	log_debug("new client %p", c);
246 	return (c);
247 }
248 
249 /* Open client terminal if needed. */
250 int
251 server_client_open(struct client *c, char **cause)
252 {
253 	const char	*ttynam = _PATH_TTY;
254 
255 	if (c->flags & CLIENT_CONTROL)
256 		return (0);
257 
258 	if (strcmp(c->ttyname, ttynam) == 0||
259 	    ((isatty(STDIN_FILENO) &&
260 	    (ttynam = ttyname(STDIN_FILENO)) != NULL &&
261 	    strcmp(c->ttyname, ttynam) == 0) ||
262 	    (isatty(STDOUT_FILENO) &&
263 	    (ttynam = ttyname(STDOUT_FILENO)) != NULL &&
264 	    strcmp(c->ttyname, ttynam) == 0) ||
265 	    (isatty(STDERR_FILENO) &&
266 	    (ttynam = ttyname(STDERR_FILENO)) != NULL &&
267 	    strcmp(c->ttyname, ttynam) == 0))) {
268 		xasprintf(cause, "can't use %s", c->ttyname);
269 		return (-1);
270 	}
271 
272 	if (!(c->flags & CLIENT_TERMINAL)) {
273 		*cause = xstrdup("not a terminal");
274 		return (-1);
275 	}
276 
277 	if (tty_open(&c->tty, cause) != 0)
278 		return (-1);
279 
280 	return (0);
281 }
282 
283 /* Lost a client. */
284 void
285 server_client_lost(struct client *c)
286 {
287 	struct client_file	*cf, *cf1;
288 	struct client_window	*cw, *cw1;
289 
290 	c->flags |= CLIENT_DEAD;
291 
292 	server_client_clear_overlay(c);
293 	status_prompt_clear(c);
294 	status_message_clear(c);
295 
296 	RB_FOREACH_SAFE(cf, client_files, &c->files, cf1) {
297 		cf->error = EINTR;
298 		file_fire_done(cf);
299 	}
300 	RB_FOREACH_SAFE(cw, client_windows, &c->windows, cw1) {
301 		RB_REMOVE(client_windows, &c->windows, cw);
302 		free(cw);
303 	}
304 
305 	TAILQ_REMOVE(&clients, c, entry);
306 	log_debug("lost client %p", c);
307 
308 	if (c->flags & CLIENT_CONTROL)
309 		control_stop(c);
310 	if (c->flags & CLIENT_TERMINAL)
311 		tty_free(&c->tty);
312 	free(c->ttyname);
313 
314 	free(c->term_name);
315 	free(c->term_type);
316 
317 	status_free(c);
318 
319 	free(c->title);
320 	free((void *)c->cwd);
321 
322 	evtimer_del(&c->repeat_timer);
323 	evtimer_del(&c->click_timer);
324 
325 	key_bindings_unref_table(c->keytable);
326 
327 	free(c->message_string);
328 	if (event_initialized(&c->message_timer))
329 		evtimer_del(&c->message_timer);
330 
331 	free(c->prompt_saved);
332 	free(c->prompt_string);
333 	free(c->prompt_buffer);
334 
335 	format_lost_client(c);
336 	environ_free(c->environ);
337 
338 	proc_remove_peer(c->peer);
339 	c->peer = NULL;
340 
341 	if (c->out_fd != -1)
342 		close(c->out_fd);
343 	if (c->fd != -1) {
344 		close(c->fd);
345 		c->fd = -1;
346 	}
347 	server_client_unref(c);
348 
349 	server_add_accept(0); /* may be more file descriptors now */
350 
351 	recalculate_sizes();
352 	server_check_unattached();
353 	server_update_socket();
354 }
355 
356 /* Remove reference from a client. */
357 void
358 server_client_unref(struct client *c)
359 {
360 	log_debug("unref client %p (%d references)", c, c->references);
361 
362 	c->references--;
363 	if (c->references == 0)
364 		event_once(-1, EV_TIMEOUT, server_client_free, c, NULL);
365 }
366 
367 /* Free dead client. */
368 static void
369 server_client_free(__unused int fd, __unused short events, void *arg)
370 {
371 	struct client	*c = arg;
372 
373 	log_debug("free client %p (%d references)", c, c->references);
374 
375 	cmdq_free(c->queue);
376 
377 	if (c->references == 0) {
378 		free((void *)c->name);
379 		free(c);
380 	}
381 }
382 
383 /* Suspend a client. */
384 void
385 server_client_suspend(struct client *c)
386 {
387 	struct session	*s = c->session;
388 
389 	if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
390 		return;
391 
392 	tty_stop_tty(&c->tty);
393 	c->flags |= CLIENT_SUSPENDED;
394 	proc_send(c->peer, MSG_SUSPEND, -1, NULL, 0);
395 }
396 
397 /* Detach a client. */
398 void
399 server_client_detach(struct client *c, enum msgtype msgtype)
400 {
401 	struct session	*s = c->session;
402 
403 	if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
404 		return;
405 
406 	c->flags |= CLIENT_EXIT;
407 
408 	c->exit_type = CLIENT_EXIT_DETACH;
409 	c->exit_msgtype = msgtype;
410 	c->exit_session = xstrdup(s->name);
411 }
412 
413 /* Execute command to replace a client. */
414 void
415 server_client_exec(struct client *c, const char *cmd)
416 {
417 	struct session	*s = c->session;
418 	char		*msg;
419 	const char	*shell;
420 	size_t		 cmdsize, shellsize;
421 
422 	if (*cmd == '\0')
423 		return;
424 	cmdsize = strlen(cmd) + 1;
425 
426 	if (s != NULL)
427 		shell = options_get_string(s->options, "default-shell");
428 	else
429 		shell = options_get_string(global_s_options, "default-shell");
430 	if (!checkshell(shell))
431 		shell = _PATH_BSHELL;
432 	shellsize = strlen(shell) + 1;
433 
434 	msg = xmalloc(cmdsize + shellsize);
435 	memcpy(msg, cmd, cmdsize);
436 	memcpy(msg + cmdsize, shell, shellsize);
437 
438 	proc_send(c->peer, MSG_EXEC, -1, msg, cmdsize + shellsize);
439 	free(msg);
440 }
441 
442 /* Check for mouse keys. */
443 static key_code
444 server_client_check_mouse(struct client *c, struct key_event *event)
445 {
446 	struct mouse_event	*m = &event->m;
447 	struct session		*s = c->session;
448 	struct winlink		*wl;
449 	struct window_pane	*wp;
450 	u_int			 x, y, b, sx, sy, px, py;
451 	int			 ignore = 0;
452 	key_code		 key;
453 	struct timeval		 tv;
454 	struct style_range	*sr;
455 	enum { NOTYPE,
456 	       MOVE,
457 	       DOWN,
458 	       UP,
459 	       DRAG,
460 	       WHEEL,
461 	       SECOND,
462 	       DOUBLE,
463 	       TRIPLE } type = NOTYPE;
464 	enum { NOWHERE,
465 	       PANE,
466 	       STATUS,
467 	       STATUS_LEFT,
468 	       STATUS_RIGHT,
469 	       STATUS_DEFAULT,
470 	       BORDER } where = NOWHERE;
471 
472 	log_debug("%s mouse %02x at %u,%u (last %u,%u) (%d)", c->name, m->b,
473 	    m->x, m->y, m->lx, m->ly, c->tty.mouse_drag_flag);
474 
475 	/* What type of event is this? */
476 	if (event->key == KEYC_DOUBLECLICK) {
477 		type = DOUBLE;
478 		x = m->x, y = m->y, b = m->b;
479 		ignore = 1;
480 		log_debug("double-click at %u,%u", x, y);
481 	} else if ((m->sgr_type != ' ' &&
482 	    MOUSE_DRAG(m->sgr_b) &&
483 	    MOUSE_BUTTONS(m->sgr_b) == 3) ||
484 	    (m->sgr_type == ' ' &&
485 	    MOUSE_DRAG(m->b) &&
486 	    MOUSE_BUTTONS(m->b) == 3 &&
487 	    MOUSE_BUTTONS(m->lb) == 3)) {
488 		type = MOVE;
489 		x = m->x, y = m->y, b = 0;
490 		log_debug("move at %u,%u", x, y);
491 	} else if (MOUSE_DRAG(m->b)) {
492 		type = DRAG;
493 		if (c->tty.mouse_drag_flag) {
494 			x = m->x, y = m->y, b = m->b;
495 			if (x == m->lx && y == m->ly)
496 				return (KEYC_UNKNOWN);
497 			log_debug("drag update at %u,%u", x, y);
498 		} else {
499 			x = m->lx, y = m->ly, b = m->lb;
500 			log_debug("drag start at %u,%u", x, y);
501 		}
502 	} else if (MOUSE_WHEEL(m->b)) {
503 		type = WHEEL;
504 		x = m->x, y = m->y, b = m->b;
505 		log_debug("wheel at %u,%u", x, y);
506 	} else if (MOUSE_RELEASE(m->b)) {
507 		type = UP;
508 		x = m->x, y = m->y, b = m->lb;
509 		log_debug("up at %u,%u", x, y);
510 	} else {
511 		if (c->flags & CLIENT_DOUBLECLICK) {
512 			evtimer_del(&c->click_timer);
513 			c->flags &= ~CLIENT_DOUBLECLICK;
514 			if (m->b == c->click_button) {
515 				type = SECOND;
516 				x = m->x, y = m->y, b = m->b;
517 				log_debug("second-click at %u,%u", x, y);
518 				c->flags |= CLIENT_TRIPLECLICK;
519 			}
520 		} else if (c->flags & CLIENT_TRIPLECLICK) {
521 			evtimer_del(&c->click_timer);
522 			c->flags &= ~CLIENT_TRIPLECLICK;
523 			if (m->b == c->click_button) {
524 				type = TRIPLE;
525 				x = m->x, y = m->y, b = m->b;
526 				log_debug("triple-click at %u,%u", x, y);
527 				goto have_event;
528 			}
529 		} else {
530 			type = DOWN;
531 			x = m->x, y = m->y, b = m->b;
532 			log_debug("down at %u,%u", x, y);
533 			c->flags |= CLIENT_DOUBLECLICK;
534 		}
535 
536 		if (KEYC_CLICK_TIMEOUT != 0) {
537 			memcpy(&c->click_event, m, sizeof c->click_event);
538 			c->click_button = m->b;
539 
540 			log_debug("click timer started");
541 			tv.tv_sec = KEYC_CLICK_TIMEOUT / 1000;
542 			tv.tv_usec = (KEYC_CLICK_TIMEOUT % 1000) * 1000L;
543 			evtimer_del(&c->click_timer);
544 			evtimer_add(&c->click_timer, &tv);
545 		}
546 	}
547 
548 have_event:
549 	if (type == NOTYPE)
550 		return (KEYC_UNKNOWN);
551 
552 	/* Save the session. */
553 	m->s = s->id;
554 	m->w = -1;
555 	m->ignore = ignore;
556 
557 	/* Is this on the status line? */
558 	m->statusat = status_at_line(c);
559 	m->statuslines = status_line_size(c);
560 	if (m->statusat != -1 &&
561 	    y >= (u_int)m->statusat &&
562 	    y < m->statusat + m->statuslines) {
563 		sr = status_get_range(c, x, y - m->statusat);
564 		if (sr == NULL) {
565 			where = STATUS_DEFAULT;
566 		} else {
567 			switch (sr->type) {
568 			case STYLE_RANGE_NONE:
569 				return (KEYC_UNKNOWN);
570 			case STYLE_RANGE_LEFT:
571 				where = STATUS_LEFT;
572 				break;
573 			case STYLE_RANGE_RIGHT:
574 				where = STATUS_RIGHT;
575 				break;
576 			case STYLE_RANGE_WINDOW:
577 				wl = winlink_find_by_index(&s->windows,
578 				    sr->argument);
579 				if (wl == NULL)
580 					return (KEYC_UNKNOWN);
581 				m->w = wl->window->id;
582 
583 				where = STATUS;
584 				break;
585 			}
586 		}
587 	}
588 
589 	/* Not on status line. Adjust position and check for border or pane. */
590 	if (where == NOWHERE) {
591 		px = x;
592 		if (m->statusat == 0 && y >= m->statuslines)
593 			py = y - m->statuslines;
594 		else if (m->statusat > 0 && y >= (u_int)m->statusat)
595 			py = m->statusat - 1;
596 		else
597 			py = y;
598 
599 		tty_window_offset(&c->tty, &m->ox, &m->oy, &sx, &sy);
600 		log_debug("mouse window @%u at %u,%u (%ux%u)",
601 		    s->curw->window->id, m->ox, m->oy, sx, sy);
602 		if (px > sx || py > sy)
603 			return (KEYC_UNKNOWN);
604 		px = px + m->ox;
605 		py = py + m->oy;
606 
607 		/* Try the pane borders if not zoomed. */
608 		if (~s->curw->window->flags & WINDOW_ZOOMED) {
609 			TAILQ_FOREACH(wp, &s->curw->window->panes, entry) {
610 				if ((wp->xoff + wp->sx == px &&
611 				    wp->yoff <= 1 + py &&
612 				    wp->yoff + wp->sy >= py) ||
613 				    (wp->yoff + wp->sy == py &&
614 				    wp->xoff <= 1 + px &&
615 				    wp->xoff + wp->sx >= px))
616 					break;
617 			}
618 			if (wp != NULL)
619 				where = BORDER;
620 		}
621 
622 		/* Otherwise try inside the pane. */
623 		if (where == NOWHERE) {
624 			wp = window_get_active_at(s->curw->window, px, py);
625 			if (wp != NULL)
626 				where = PANE;
627 			else
628 				return (KEYC_UNKNOWN);
629 		}
630 		if (where == PANE)
631 			log_debug("mouse %u,%u on pane %%%u", x, y, wp->id);
632 		else if (where == BORDER)
633 			log_debug("mouse on pane %%%u border", wp->id);
634 		m->wp = wp->id;
635 		m->w = wp->window->id;
636 	} else
637 		m->wp = -1;
638 
639 	/* Stop dragging if needed. */
640 	if (type != DRAG && type != WHEEL && c->tty.mouse_drag_flag) {
641 		if (c->tty.mouse_drag_release != NULL)
642 			c->tty.mouse_drag_release(c, m);
643 
644 		c->tty.mouse_drag_update = NULL;
645 		c->tty.mouse_drag_release = NULL;
646 
647 		/*
648 		 * End a mouse drag by passing a MouseDragEnd key corresponding
649 		 * to the button that started the drag.
650 		 */
651 		switch (c->tty.mouse_drag_flag) {
652 		case 1:
653 			if (where == PANE)
654 				key = KEYC_MOUSEDRAGEND1_PANE;
655 			if (where == STATUS)
656 				key = KEYC_MOUSEDRAGEND1_STATUS;
657 			if (where == STATUS_LEFT)
658 				key = KEYC_MOUSEDRAGEND1_STATUS_LEFT;
659 			if (where == STATUS_RIGHT)
660 				key = KEYC_MOUSEDRAGEND1_STATUS_RIGHT;
661 			if (where == STATUS_DEFAULT)
662 				key = KEYC_MOUSEDRAGEND1_STATUS_DEFAULT;
663 			if (where == BORDER)
664 				key = KEYC_MOUSEDRAGEND1_BORDER;
665 			break;
666 		case 2:
667 			if (where == PANE)
668 				key = KEYC_MOUSEDRAGEND2_PANE;
669 			if (where == STATUS)
670 				key = KEYC_MOUSEDRAGEND2_STATUS;
671 			if (where == STATUS_LEFT)
672 				key = KEYC_MOUSEDRAGEND2_STATUS_LEFT;
673 			if (where == STATUS_RIGHT)
674 				key = KEYC_MOUSEDRAGEND2_STATUS_RIGHT;
675 			if (where == STATUS_DEFAULT)
676 				key = KEYC_MOUSEDRAGEND2_STATUS_DEFAULT;
677 			if (where == BORDER)
678 				key = KEYC_MOUSEDRAGEND2_BORDER;
679 			break;
680 		case 3:
681 			if (where == PANE)
682 				key = KEYC_MOUSEDRAGEND3_PANE;
683 			if (where == STATUS)
684 				key = KEYC_MOUSEDRAGEND3_STATUS;
685 			if (where == STATUS_LEFT)
686 				key = KEYC_MOUSEDRAGEND3_STATUS_LEFT;
687 			if (where == STATUS_RIGHT)
688 				key = KEYC_MOUSEDRAGEND3_STATUS_RIGHT;
689 			if (where == STATUS_DEFAULT)
690 				key = KEYC_MOUSEDRAGEND3_STATUS_DEFAULT;
691 			if (where == BORDER)
692 				key = KEYC_MOUSEDRAGEND3_BORDER;
693 			break;
694 		default:
695 			key = KEYC_MOUSE;
696 			break;
697 		}
698 		c->tty.mouse_drag_flag = 0;
699 		goto out;
700 	}
701 
702 	/* Convert to a key binding. */
703 	key = KEYC_UNKNOWN;
704 	switch (type) {
705 	case NOTYPE:
706 		break;
707 	case MOVE:
708 		if (where == PANE)
709 			key = KEYC_MOUSEMOVE_PANE;
710 		if (where == STATUS)
711 			key = KEYC_MOUSEMOVE_STATUS;
712 		if (where == STATUS_LEFT)
713 			key = KEYC_MOUSEMOVE_STATUS_LEFT;
714 		if (where == STATUS_RIGHT)
715 			key = KEYC_MOUSEMOVE_STATUS_RIGHT;
716 		if (where == STATUS_DEFAULT)
717 			key = KEYC_MOUSEMOVE_STATUS_DEFAULT;
718 		if (where == BORDER)
719 			key = KEYC_MOUSEMOVE_BORDER;
720 		break;
721 	case DRAG:
722 		if (c->tty.mouse_drag_update != NULL)
723 			key = KEYC_DRAGGING;
724 		else {
725 			switch (MOUSE_BUTTONS(b)) {
726 			case 0:
727 				if (where == PANE)
728 					key = KEYC_MOUSEDRAG1_PANE;
729 				if (where == STATUS)
730 					key = KEYC_MOUSEDRAG1_STATUS;
731 				if (where == STATUS_LEFT)
732 					key = KEYC_MOUSEDRAG1_STATUS_LEFT;
733 				if (where == STATUS_RIGHT)
734 					key = KEYC_MOUSEDRAG1_STATUS_RIGHT;
735 				if (where == STATUS_DEFAULT)
736 					key = KEYC_MOUSEDRAG1_STATUS_DEFAULT;
737 				if (where == BORDER)
738 					key = KEYC_MOUSEDRAG1_BORDER;
739 				break;
740 			case 1:
741 				if (where == PANE)
742 					key = KEYC_MOUSEDRAG2_PANE;
743 				if (where == STATUS)
744 					key = KEYC_MOUSEDRAG2_STATUS;
745 				if (where == STATUS_LEFT)
746 					key = KEYC_MOUSEDRAG2_STATUS_LEFT;
747 				if (where == STATUS_RIGHT)
748 					key = KEYC_MOUSEDRAG2_STATUS_RIGHT;
749 				if (where == STATUS_DEFAULT)
750 					key = KEYC_MOUSEDRAG2_STATUS_DEFAULT;
751 				if (where == BORDER)
752 					key = KEYC_MOUSEDRAG2_BORDER;
753 				break;
754 			case 2:
755 				if (where == PANE)
756 					key = KEYC_MOUSEDRAG3_PANE;
757 				if (where == STATUS)
758 					key = KEYC_MOUSEDRAG3_STATUS;
759 				if (where == STATUS_LEFT)
760 					key = KEYC_MOUSEDRAG3_STATUS_LEFT;
761 				if (where == STATUS_RIGHT)
762 					key = KEYC_MOUSEDRAG3_STATUS_RIGHT;
763 				if (where == STATUS_DEFAULT)
764 					key = KEYC_MOUSEDRAG3_STATUS_DEFAULT;
765 				if (where == BORDER)
766 					key = KEYC_MOUSEDRAG3_BORDER;
767 				break;
768 			}
769 		}
770 
771 		/*
772 		 * Begin a drag by setting the flag to a non-zero value that
773 		 * corresponds to the mouse button in use.
774 		 */
775 		c->tty.mouse_drag_flag = MOUSE_BUTTONS(b) + 1;
776 		break;
777 	case WHEEL:
778 		if (MOUSE_BUTTONS(b) == MOUSE_WHEEL_UP) {
779 			if (where == PANE)
780 				key = KEYC_WHEELUP_PANE;
781 			if (where == STATUS)
782 				key = KEYC_WHEELUP_STATUS;
783 			if (where == STATUS_LEFT)
784 				key = KEYC_WHEELUP_STATUS_LEFT;
785 			if (where == STATUS_RIGHT)
786 				key = KEYC_WHEELUP_STATUS_RIGHT;
787 			if (where == STATUS_DEFAULT)
788 				key = KEYC_WHEELUP_STATUS_DEFAULT;
789 			if (where == BORDER)
790 				key = KEYC_WHEELUP_BORDER;
791 		} else {
792 			if (where == PANE)
793 				key = KEYC_WHEELDOWN_PANE;
794 			if (where == STATUS)
795 				key = KEYC_WHEELDOWN_STATUS;
796 			if (where == STATUS_LEFT)
797 				key = KEYC_WHEELDOWN_STATUS_LEFT;
798 			if (where == STATUS_RIGHT)
799 				key = KEYC_WHEELDOWN_STATUS_RIGHT;
800 			if (where == STATUS_DEFAULT)
801 				key = KEYC_WHEELDOWN_STATUS_DEFAULT;
802 			if (where == BORDER)
803 				key = KEYC_WHEELDOWN_BORDER;
804 		}
805 		break;
806 	case UP:
807 		switch (MOUSE_BUTTONS(b)) {
808 		case 0:
809 			if (where == PANE)
810 				key = KEYC_MOUSEUP1_PANE;
811 			if (where == STATUS)
812 				key = KEYC_MOUSEUP1_STATUS;
813 			if (where == STATUS_LEFT)
814 				key = KEYC_MOUSEUP1_STATUS_LEFT;
815 			if (where == STATUS_RIGHT)
816 				key = KEYC_MOUSEUP1_STATUS_RIGHT;
817 			if (where == STATUS_DEFAULT)
818 				key = KEYC_MOUSEUP1_STATUS_DEFAULT;
819 			if (where == BORDER)
820 				key = KEYC_MOUSEUP1_BORDER;
821 			break;
822 		case 1:
823 			if (where == PANE)
824 				key = KEYC_MOUSEUP2_PANE;
825 			if (where == STATUS)
826 				key = KEYC_MOUSEUP2_STATUS;
827 			if (where == STATUS_LEFT)
828 				key = KEYC_MOUSEUP2_STATUS_LEFT;
829 			if (where == STATUS_RIGHT)
830 				key = KEYC_MOUSEUP2_STATUS_RIGHT;
831 			if (where == STATUS_DEFAULT)
832 				key = KEYC_MOUSEUP2_STATUS_DEFAULT;
833 			if (where == BORDER)
834 				key = KEYC_MOUSEUP2_BORDER;
835 			break;
836 		case 2:
837 			if (where == PANE)
838 				key = KEYC_MOUSEUP3_PANE;
839 			if (where == STATUS)
840 				key = KEYC_MOUSEUP3_STATUS;
841 			if (where == STATUS_LEFT)
842 				key = KEYC_MOUSEUP3_STATUS_LEFT;
843 			if (where == STATUS_RIGHT)
844 				key = KEYC_MOUSEUP3_STATUS_RIGHT;
845 			if (where == STATUS_DEFAULT)
846 				key = KEYC_MOUSEUP3_STATUS_DEFAULT;
847 			if (where == BORDER)
848 				key = KEYC_MOUSEUP3_BORDER;
849 			break;
850 		}
851 		break;
852 	case DOWN:
853 		switch (MOUSE_BUTTONS(b)) {
854 		case 0:
855 			if (where == PANE)
856 				key = KEYC_MOUSEDOWN1_PANE;
857 			if (where == STATUS)
858 				key = KEYC_MOUSEDOWN1_STATUS;
859 			if (where == STATUS_LEFT)
860 				key = KEYC_MOUSEDOWN1_STATUS_LEFT;
861 			if (where == STATUS_RIGHT)
862 				key = KEYC_MOUSEDOWN1_STATUS_RIGHT;
863 			if (where == STATUS_DEFAULT)
864 				key = KEYC_MOUSEDOWN1_STATUS_DEFAULT;
865 			if (where == BORDER)
866 				key = KEYC_MOUSEDOWN1_BORDER;
867 			break;
868 		case 1:
869 			if (where == PANE)
870 				key = KEYC_MOUSEDOWN2_PANE;
871 			if (where == STATUS)
872 				key = KEYC_MOUSEDOWN2_STATUS;
873 			if (where == STATUS_LEFT)
874 				key = KEYC_MOUSEDOWN2_STATUS_LEFT;
875 			if (where == STATUS_RIGHT)
876 				key = KEYC_MOUSEDOWN2_STATUS_RIGHT;
877 			if (where == STATUS_DEFAULT)
878 				key = KEYC_MOUSEDOWN2_STATUS_DEFAULT;
879 			if (where == BORDER)
880 				key = KEYC_MOUSEDOWN2_BORDER;
881 			break;
882 		case 2:
883 			if (where == PANE)
884 				key = KEYC_MOUSEDOWN3_PANE;
885 			if (where == STATUS)
886 				key = KEYC_MOUSEDOWN3_STATUS;
887 			if (where == STATUS_LEFT)
888 				key = KEYC_MOUSEDOWN3_STATUS_LEFT;
889 			if (where == STATUS_RIGHT)
890 				key = KEYC_MOUSEDOWN3_STATUS_RIGHT;
891 			if (where == STATUS_DEFAULT)
892 				key = KEYC_MOUSEDOWN3_STATUS_DEFAULT;
893 			if (where == BORDER)
894 				key = KEYC_MOUSEDOWN3_BORDER;
895 			break;
896 		}
897 		break;
898 	case SECOND:
899 		switch (MOUSE_BUTTONS(b)) {
900 		case 0:
901 			if (where == PANE)
902 				key = KEYC_SECONDCLICK1_PANE;
903 			if (where == STATUS)
904 				key = KEYC_SECONDCLICK1_STATUS;
905 			if (where == STATUS_LEFT)
906 				key = KEYC_SECONDCLICK1_STATUS_LEFT;
907 			if (where == STATUS_RIGHT)
908 				key = KEYC_SECONDCLICK1_STATUS_RIGHT;
909 			if (where == STATUS_DEFAULT)
910 				key = KEYC_SECONDCLICK1_STATUS_DEFAULT;
911 			if (where == BORDER)
912 				key = KEYC_SECONDCLICK1_BORDER;
913 			break;
914 		case 1:
915 			if (where == PANE)
916 				key = KEYC_SECONDCLICK2_PANE;
917 			if (where == STATUS)
918 				key = KEYC_SECONDCLICK2_STATUS;
919 			if (where == STATUS_LEFT)
920 				key = KEYC_SECONDCLICK2_STATUS_LEFT;
921 			if (where == STATUS_RIGHT)
922 				key = KEYC_SECONDCLICK2_STATUS_RIGHT;
923 			if (where == STATUS_DEFAULT)
924 				key = KEYC_SECONDCLICK2_STATUS_DEFAULT;
925 			if (where == BORDER)
926 				key = KEYC_SECONDCLICK2_BORDER;
927 			break;
928 		case 2:
929 			if (where == PANE)
930 				key = KEYC_SECONDCLICK3_PANE;
931 			if (where == STATUS)
932 				key = KEYC_SECONDCLICK3_STATUS;
933 			if (where == STATUS_LEFT)
934 				key = KEYC_SECONDCLICK3_STATUS_LEFT;
935 			if (where == STATUS_RIGHT)
936 				key = KEYC_SECONDCLICK3_STATUS_RIGHT;
937 			if (where == STATUS_DEFAULT)
938 				key = KEYC_SECONDCLICK3_STATUS_DEFAULT;
939 			if (where == BORDER)
940 				key = KEYC_SECONDCLICK3_BORDER;
941 			break;
942 		}
943 		break;
944 	case DOUBLE:
945 		switch (MOUSE_BUTTONS(b)) {
946 		case 0:
947 			if (where == PANE)
948 				key = KEYC_DOUBLECLICK1_PANE;
949 			if (where == STATUS)
950 				key = KEYC_DOUBLECLICK1_STATUS;
951 			if (where == STATUS_LEFT)
952 				key = KEYC_DOUBLECLICK1_STATUS_LEFT;
953 			if (where == STATUS_RIGHT)
954 				key = KEYC_DOUBLECLICK1_STATUS_RIGHT;
955 			if (where == STATUS_DEFAULT)
956 				key = KEYC_DOUBLECLICK1_STATUS_DEFAULT;
957 			if (where == BORDER)
958 				key = KEYC_DOUBLECLICK1_BORDER;
959 			break;
960 		case 1:
961 			if (where == PANE)
962 				key = KEYC_DOUBLECLICK2_PANE;
963 			if (where == STATUS)
964 				key = KEYC_DOUBLECLICK2_STATUS;
965 			if (where == STATUS_LEFT)
966 				key = KEYC_DOUBLECLICK2_STATUS_LEFT;
967 			if (where == STATUS_RIGHT)
968 				key = KEYC_DOUBLECLICK2_STATUS_RIGHT;
969 			if (where == STATUS_DEFAULT)
970 				key = KEYC_DOUBLECLICK2_STATUS_DEFAULT;
971 			if (where == BORDER)
972 				key = KEYC_DOUBLECLICK2_BORDER;
973 			break;
974 		case 2:
975 			if (where == PANE)
976 				key = KEYC_DOUBLECLICK3_PANE;
977 			if (where == STATUS)
978 				key = KEYC_DOUBLECLICK3_STATUS;
979 			if (where == STATUS_LEFT)
980 				key = KEYC_DOUBLECLICK3_STATUS_LEFT;
981 			if (where == STATUS_RIGHT)
982 				key = KEYC_DOUBLECLICK3_STATUS_RIGHT;
983 			if (where == STATUS_DEFAULT)
984 				key = KEYC_DOUBLECLICK3_STATUS_DEFAULT;
985 			if (where == BORDER)
986 				key = KEYC_DOUBLECLICK3_BORDER;
987 			break;
988 		}
989 		break;
990 	case TRIPLE:
991 		switch (MOUSE_BUTTONS(b)) {
992 		case 0:
993 			if (where == PANE)
994 				key = KEYC_TRIPLECLICK1_PANE;
995 			if (where == STATUS)
996 				key = KEYC_TRIPLECLICK1_STATUS;
997 			if (where == STATUS_LEFT)
998 				key = KEYC_TRIPLECLICK1_STATUS_LEFT;
999 			if (where == STATUS_RIGHT)
1000 				key = KEYC_TRIPLECLICK1_STATUS_RIGHT;
1001 			if (where == STATUS_DEFAULT)
1002 				key = KEYC_TRIPLECLICK1_STATUS_DEFAULT;
1003 			if (where == BORDER)
1004 				key = KEYC_TRIPLECLICK1_BORDER;
1005 			break;
1006 		case 1:
1007 			if (where == PANE)
1008 				key = KEYC_TRIPLECLICK2_PANE;
1009 			if (where == STATUS)
1010 				key = KEYC_TRIPLECLICK2_STATUS;
1011 			if (where == STATUS_LEFT)
1012 				key = KEYC_TRIPLECLICK2_STATUS_LEFT;
1013 			if (where == STATUS_RIGHT)
1014 				key = KEYC_TRIPLECLICK2_STATUS_RIGHT;
1015 			if (where == STATUS_DEFAULT)
1016 				key = KEYC_TRIPLECLICK2_STATUS_DEFAULT;
1017 			if (where == BORDER)
1018 				key = KEYC_TRIPLECLICK2_BORDER;
1019 			break;
1020 		case 2:
1021 			if (where == PANE)
1022 				key = KEYC_TRIPLECLICK3_PANE;
1023 			if (where == STATUS)
1024 				key = KEYC_TRIPLECLICK3_STATUS;
1025 			if (where == STATUS_LEFT)
1026 				key = KEYC_TRIPLECLICK3_STATUS_LEFT;
1027 			if (where == STATUS_RIGHT)
1028 				key = KEYC_TRIPLECLICK3_STATUS_RIGHT;
1029 			if (where == STATUS_DEFAULT)
1030 				key = KEYC_TRIPLECLICK3_STATUS_DEFAULT;
1031 			if (where == BORDER)
1032 				key = KEYC_TRIPLECLICK3_BORDER;
1033 			break;
1034 		}
1035 		break;
1036 	}
1037 	if (key == KEYC_UNKNOWN)
1038 		return (KEYC_UNKNOWN);
1039 
1040 out:
1041 	/* Apply modifiers if any. */
1042 	if (b & MOUSE_MASK_META)
1043 		key |= KEYC_META;
1044 	if (b & MOUSE_MASK_CTRL)
1045 		key |= KEYC_CTRL;
1046 	if (b & MOUSE_MASK_SHIFT)
1047 		key |= KEYC_SHIFT;
1048 
1049 	if (log_get_level() != 0)
1050 		log_debug("mouse key is %s", key_string_lookup_key (key, 1));
1051 	return (key);
1052 }
1053 
1054 /* Is this fast enough to probably be a paste? */
1055 static int
1056 server_client_assume_paste(struct session *s)
1057 {
1058 	struct timeval	tv;
1059 	int		t;
1060 
1061 	if ((t = options_get_number(s->options, "assume-paste-time")) == 0)
1062 		return (0);
1063 
1064 	timersub(&s->activity_time, &s->last_activity_time, &tv);
1065 	if (tv.tv_sec == 0 && tv.tv_usec < t * 1000) {
1066 		log_debug("session %s pasting (flag %d)", s->name,
1067 		    !!(s->flags & SESSION_PASTING));
1068 		if (s->flags & SESSION_PASTING)
1069 			return (1);
1070 		s->flags |= SESSION_PASTING;
1071 		return (0);
1072 	}
1073 	log_debug("session %s not pasting", s->name);
1074 	s->flags &= ~SESSION_PASTING;
1075 	return (0);
1076 }
1077 
1078 /* Has the latest client changed? */
1079 static void
1080 server_client_update_latest(struct client *c)
1081 {
1082 	struct window	*w;
1083 
1084 	if (c->session == NULL)
1085 		return;
1086 	w = c->session->curw->window;
1087 
1088 	if (w->latest == c)
1089 		return;
1090 	w->latest = c;
1091 
1092 	if (options_get_number(w->options, "window-size") == WINDOW_SIZE_LATEST)
1093 		recalculate_size(w, 0);
1094 }
1095 
1096 /*
1097  * Handle data key input from client. This owns and can modify the key event it
1098  * is given and is responsible for freeing it.
1099  */
1100 static enum cmd_retval
1101 server_client_key_callback(struct cmdq_item *item, void *data)
1102 {
1103 	struct client			*c = cmdq_get_client(item);
1104 	struct key_event		*event = data;
1105 	key_code			 key = event->key;
1106 	struct mouse_event		*m = &event->m;
1107 	struct session			*s = c->session;
1108 	struct winlink			*wl;
1109 	struct window_pane		*wp;
1110 	struct window_mode_entry	*wme;
1111 	struct timeval			 tv;
1112 	struct key_table		*table, *first;
1113 	struct key_binding		*bd;
1114 	int				 xtimeout, flags;
1115 	struct cmd_find_state		 fs;
1116 	key_code			 key0;
1117 
1118 	/* Check the client is good to accept input. */
1119 	if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
1120 		goto out;
1121 	wl = s->curw;
1122 
1123 	/* Update the activity timer. */
1124 	if (gettimeofday(&c->activity_time, NULL) != 0)
1125 		fatal("gettimeofday failed");
1126 	session_update_activity(s, &c->activity_time);
1127 
1128 	/* Check for mouse keys. */
1129 	m->valid = 0;
1130 	if (key == KEYC_MOUSE || key == KEYC_DOUBLECLICK) {
1131 		if (c->flags & CLIENT_READONLY)
1132 			goto out;
1133 		key = server_client_check_mouse(c, event);
1134 		if (key == KEYC_UNKNOWN)
1135 			goto out;
1136 
1137 		m->valid = 1;
1138 		m->key = key;
1139 
1140 		/*
1141 		 * Mouse drag is in progress, so fire the callback (now that
1142 		 * the mouse event is valid).
1143 		 */
1144 		if ((key & KEYC_MASK_KEY) == KEYC_DRAGGING) {
1145 			c->tty.mouse_drag_update(c, m);
1146 			goto out;
1147 		}
1148 		event->key = key;
1149 	}
1150 
1151 	/* Find affected pane. */
1152 	if (!KEYC_IS_MOUSE(key) || cmd_find_from_mouse(&fs, m, 0) != 0)
1153 		cmd_find_from_client(&fs, c, 0);
1154 	wp = fs.wp;
1155 
1156 	/* Forward mouse keys if disabled. */
1157 	if (KEYC_IS_MOUSE(key) && !options_get_number(s->options, "mouse"))
1158 		goto forward_key;
1159 
1160 	/* Treat everything as a regular key when pasting is detected. */
1161 	if (!KEYC_IS_MOUSE(key) && server_client_assume_paste(s))
1162 		goto forward_key;
1163 
1164 	/*
1165 	 * Work out the current key table. If the pane is in a mode, use
1166 	 * the mode table instead of the default key table.
1167 	 */
1168 	if (server_client_is_default_key_table(c, c->keytable) &&
1169 	    wp != NULL &&
1170 	    (wme = TAILQ_FIRST(&wp->modes)) != NULL &&
1171 	    wme->mode->key_table != NULL)
1172 		table = key_bindings_get_table(wme->mode->key_table(wme), 1);
1173 	else
1174 		table = c->keytable;
1175 	first = table;
1176 
1177 table_changed:
1178 	/*
1179 	 * The prefix always takes precedence and forces a switch to the prefix
1180 	 * table, unless we are already there.
1181 	 */
1182 	key0 = (key & (KEYC_MASK_KEY|KEYC_MASK_MODIFIERS));
1183 	if ((key0 == (key_code)options_get_number(s->options, "prefix") ||
1184 	    key0 == (key_code)options_get_number(s->options, "prefix2")) &&
1185 	    strcmp(table->name, "prefix") != 0) {
1186 		server_client_set_key_table(c, "prefix");
1187 		server_status_client(c);
1188 		goto out;
1189 	}
1190 	flags = c->flags;
1191 
1192 try_again:
1193 	/* Log key table. */
1194 	if (wp == NULL)
1195 		log_debug("key table %s (no pane)", table->name);
1196 	else
1197 		log_debug("key table %s (pane %%%u)", table->name, wp->id);
1198 	if (c->flags & CLIENT_REPEAT)
1199 		log_debug("currently repeating");
1200 
1201 	/* Try to see if there is a key binding in the current table. */
1202 	bd = key_bindings_get(table, key0);
1203 	if (bd != NULL) {
1204 		/*
1205 		 * Key was matched in this table. If currently repeating but a
1206 		 * non-repeating binding was found, stop repeating and try
1207 		 * again in the root table.
1208 		 */
1209 		if ((c->flags & CLIENT_REPEAT) &&
1210 		    (~bd->flags & KEY_BINDING_REPEAT)) {
1211 			log_debug("found in key table %s (not repeating)",
1212 			    table->name);
1213 			server_client_set_key_table(c, NULL);
1214 			first = table = c->keytable;
1215 			c->flags &= ~CLIENT_REPEAT;
1216 			server_status_client(c);
1217 			goto table_changed;
1218 		}
1219 		log_debug("found in key table %s", table->name);
1220 
1221 		/*
1222 		 * Take a reference to this table to make sure the key binding
1223 		 * doesn't disappear.
1224 		 */
1225 		table->references++;
1226 
1227 		/*
1228 		 * If this is a repeating key, start the timer. Otherwise reset
1229 		 * the client back to the root table.
1230 		 */
1231 		xtimeout = options_get_number(s->options, "repeat-time");
1232 		if (xtimeout != 0 && (bd->flags & KEY_BINDING_REPEAT)) {
1233 			c->flags |= CLIENT_REPEAT;
1234 
1235 			tv.tv_sec = xtimeout / 1000;
1236 			tv.tv_usec = (xtimeout % 1000) * 1000L;
1237 			evtimer_del(&c->repeat_timer);
1238 			evtimer_add(&c->repeat_timer, &tv);
1239 		} else {
1240 			c->flags &= ~CLIENT_REPEAT;
1241 			server_client_set_key_table(c, NULL);
1242 		}
1243 		server_status_client(c);
1244 
1245 		/* Execute the key binding. */
1246 		key_bindings_dispatch(bd, item, c, event, &fs);
1247 		key_bindings_unref_table(table);
1248 		goto out;
1249 	}
1250 
1251 	/*
1252 	 * No match, try the ANY key.
1253 	 */
1254 	if (key0 != KEYC_ANY) {
1255 		key0 = KEYC_ANY;
1256 		goto try_again;
1257 	}
1258 
1259 	/*
1260 	 * No match in this table. If not in the root table or if repeating,
1261 	 * switch the client back to the root table and try again.
1262 	 */
1263 	log_debug("not found in key table %s", table->name);
1264 	if (!server_client_is_default_key_table(c, table) ||
1265 	    (c->flags & CLIENT_REPEAT)) {
1266 		log_debug("trying in root table");
1267 		server_client_set_key_table(c, NULL);
1268 		table = c->keytable;
1269 		if (c->flags & CLIENT_REPEAT)
1270 			first = table;
1271 		c->flags &= ~CLIENT_REPEAT;
1272 		server_status_client(c);
1273 		goto table_changed;
1274 	}
1275 
1276 	/*
1277 	 * No match in the root table either. If this wasn't the first table
1278 	 * tried, don't pass the key to the pane.
1279 	 */
1280 	if (first != table && (~flags & CLIENT_REPEAT)) {
1281 		server_client_set_key_table(c, NULL);
1282 		server_status_client(c);
1283 		goto out;
1284 	}
1285 
1286 forward_key:
1287 	if (c->flags & CLIENT_READONLY)
1288 		goto out;
1289 	if (wp != NULL)
1290 		window_pane_key(wp, c, s, wl, key, m);
1291 
1292 out:
1293 	if (s != NULL && key != KEYC_FOCUS_OUT)
1294 		server_client_update_latest(c);
1295 	free(event);
1296 	return (CMD_RETURN_NORMAL);
1297 }
1298 
1299 /* Handle a key event. */
1300 int
1301 server_client_handle_key(struct client *c, struct key_event *event)
1302 {
1303 	struct session		*s = c->session;
1304 	struct cmdq_item	*item;
1305 
1306 	/* Check the client is good to accept input. */
1307 	if (s == NULL || (c->flags & CLIENT_UNATTACHEDFLAGS))
1308 		return (0);
1309 
1310 	/*
1311 	 * Key presses in overlay mode and the command prompt are a special
1312 	 * case. The queue might be blocked so they need to be processed
1313 	 * immediately rather than queued.
1314 	 */
1315 	if (~c->flags & CLIENT_READONLY) {
1316 		status_message_clear(c);
1317 		if (c->overlay_key != NULL) {
1318 			switch (c->overlay_key(c, event)) {
1319 			case 0:
1320 				return (0);
1321 			case 1:
1322 				server_client_clear_overlay(c);
1323 				return (0);
1324 			}
1325 		}
1326 		server_client_clear_overlay(c);
1327 		if (c->prompt_string != NULL) {
1328 			if (status_prompt_key(c, event->key) == 0)
1329 				return (0);
1330 		}
1331 	}
1332 
1333 	/*
1334 	 * Add the key to the queue so it happens after any commands queued by
1335 	 * previous keys.
1336 	 */
1337 	item = cmdq_get_callback(server_client_key_callback, event);
1338 	cmdq_append(c, item);
1339 	return (1);
1340 }
1341 
1342 /* Client functions that need to happen every loop. */
1343 void
1344 server_client_loop(void)
1345 {
1346 	struct client		*c;
1347 	struct window		*w;
1348 	struct window_pane	*wp;
1349 	int			 focus;
1350 
1351 	/* Check for window resize. This is done before redrawing. */
1352 	RB_FOREACH(w, windows, &windows)
1353 		server_client_check_window_resize(w);
1354 
1355 	/* Check clients. */
1356 	TAILQ_FOREACH(c, &clients, entry) {
1357 		server_client_check_exit(c);
1358 		if (c->session != NULL) {
1359 			server_client_check_modes(c);
1360 			server_client_check_redraw(c);
1361 			server_client_reset_state(c);
1362 		}
1363 	}
1364 
1365 	/*
1366 	 * Any windows will have been redrawn as part of clients, so clear
1367 	 * their flags now. Also check pane focus and resize.
1368 	 */
1369 	focus = options_get_number(global_options, "focus-events");
1370 	RB_FOREACH(w, windows, &windows) {
1371 		TAILQ_FOREACH(wp, &w->panes, entry) {
1372 			if (wp->fd != -1) {
1373 				if (focus)
1374 					server_client_check_pane_focus(wp);
1375 				server_client_check_pane_resize(wp);
1376 				server_client_check_pane_buffer(wp);
1377 			}
1378 			wp->flags &= ~PANE_REDRAW;
1379 		}
1380 		check_window_name(w);
1381 	}
1382 }
1383 
1384 /* Check if window needs to be resized. */
1385 static void
1386 server_client_check_window_resize(struct window *w)
1387 {
1388 	struct winlink	*wl;
1389 
1390 	if (~w->flags & WINDOW_RESIZE)
1391 		return;
1392 
1393 	TAILQ_FOREACH(wl, &w->winlinks, wentry) {
1394 		if (wl->session->attached != 0 && wl->session->curw == wl)
1395 			break;
1396 	}
1397 	if (wl == NULL)
1398 		return;
1399 
1400 	log_debug("%s: resizing window @%u", __func__, w->id);
1401 	resize_window(w, w->new_sx, w->new_sy, w->new_xpixel, w->new_ypixel);
1402 }
1403 
1404 /* Resize timer event. */
1405 static void
1406 server_client_resize_timer(__unused int fd, __unused short events, void *data)
1407 {
1408 	struct window_pane	*wp = data;
1409 
1410 	log_debug("%s: %%%u resize timer expired", __func__, wp->id);
1411 	evtimer_del(&wp->resize_timer);
1412 }
1413 
1414 /* Start the resize timer. */
1415 static void
1416 server_client_start_resize_timer(struct window_pane *wp)
1417 {
1418 	struct timeval	tv = { .tv_usec = 250000 };
1419 
1420 	log_debug("%s: %%%u resize timer started", __func__, wp->id);
1421 	evtimer_add(&wp->resize_timer, &tv);
1422 }
1423 
1424 /* Force timer event. */
1425 static void
1426 server_client_force_timer(__unused int fd, __unused short events, void *data)
1427 {
1428 	struct window_pane	*wp = data;
1429 
1430 	log_debug("%s: %%%u force timer expired", __func__, wp->id);
1431 	evtimer_del(&wp->force_timer);
1432 	wp->flags |= PANE_RESIZENOW;
1433 }
1434 
1435 /* Start the force timer. */
1436 static void
1437 server_client_start_force_timer(struct window_pane *wp)
1438 {
1439 	struct timeval	tv = { .tv_usec = 10000 };
1440 
1441 	log_debug("%s: %%%u force timer started", __func__, wp->id);
1442 	evtimer_add(&wp->force_timer, &tv);
1443 }
1444 
1445 /* Check if pane should be resized. */
1446 static void
1447 server_client_check_pane_resize(struct window_pane *wp)
1448 {
1449 	if (!event_initialized(&wp->resize_timer))
1450 		evtimer_set(&wp->resize_timer, server_client_resize_timer, wp);
1451 	if (!event_initialized(&wp->force_timer))
1452 		evtimer_set(&wp->force_timer, server_client_force_timer, wp);
1453 
1454 	if (~wp->flags & PANE_RESIZE)
1455 		return;
1456 	log_debug("%s: %%%u needs to be resized", __func__, wp->id);
1457 
1458 	if (evtimer_pending(&wp->resize_timer, NULL)) {
1459 		log_debug("%s: %%%u resize timer is running", __func__, wp->id);
1460 		return;
1461 	}
1462 	server_client_start_resize_timer(wp);
1463 
1464 	if (~wp->flags & PANE_RESIZEFORCE) {
1465 		/*
1466 		 * The timer is not running and we don't need to force a
1467 		 * resize, so just resize immediately.
1468 		 */
1469 		log_debug("%s: resizing %%%u now", __func__, wp->id);
1470 		window_pane_send_resize(wp, 0);
1471 		wp->flags &= ~PANE_RESIZE;
1472 	} else {
1473 		/*
1474 		 * The timer is not running, but we need to force a resize. If
1475 		 * the force timer has expired, resize to the real size now.
1476 		 * Otherwise resize to the force size and start the timer.
1477 		 */
1478 		if (wp->flags & PANE_RESIZENOW) {
1479 			log_debug("%s: resizing %%%u after forced resize",
1480 			    __func__, wp->id);
1481 			window_pane_send_resize(wp, 0);
1482 			wp->flags &= ~(PANE_RESIZE|PANE_RESIZEFORCE|PANE_RESIZENOW);
1483 		} else if (!evtimer_pending(&wp->force_timer, NULL)) {
1484 			log_debug("%s: forcing resize of %%%u", __func__,
1485 			    wp->id);
1486 			window_pane_send_resize(wp, 1);
1487 			server_client_start_force_timer(wp);
1488 		}
1489 	}
1490 }
1491 
1492 /* Check pane buffer size. */
1493 static void
1494 server_client_check_pane_buffer(struct window_pane *wp)
1495 {
1496 	struct evbuffer			*evb = wp->event->input;
1497 	size_t				 minimum;
1498 	struct client			*c;
1499 	struct window_pane_offset	*wpo;
1500 	int				 off = 1, flag;
1501 	u_int				 attached_clients = 0;
1502 	size_t				 new_size;
1503 
1504 	/*
1505 	 * Work out the minimum used size. This is the most that can be removed
1506 	 * from the buffer.
1507 	 */
1508 	minimum = wp->offset.used;
1509 	if (wp->pipe_fd != -1 && wp->pipe_offset.used < minimum)
1510 		minimum = wp->pipe_offset.used;
1511 	TAILQ_FOREACH(c, &clients, entry) {
1512 		if (c->session == NULL)
1513 			continue;
1514 		attached_clients++;
1515 
1516 		if (~c->flags & CLIENT_CONTROL) {
1517 			off = 0;
1518 			continue;
1519 		}
1520 		wpo = control_pane_offset(c, wp, &flag);
1521 		if (wpo == NULL) {
1522 			off = 0;
1523 			continue;
1524 		}
1525 		if (!flag)
1526 			off = 0;
1527 
1528 		window_pane_get_new_data(wp, wpo, &new_size);
1529 		log_debug("%s: %s has %zu bytes used and %zu left for %%%u",
1530 		    __func__, c->name, wpo->used - wp->base_offset, new_size,
1531 		    wp->id);
1532 		if (wpo->used < minimum)
1533 			minimum = wpo->used;
1534 	}
1535 	if (attached_clients == 0)
1536 		off = 0;
1537 	minimum -= wp->base_offset;
1538 	if (minimum == 0)
1539 		goto out;
1540 
1541 	/* Drain the buffer. */
1542 	log_debug("%s: %%%u has %zu minimum (of %zu) bytes used", __func__,
1543 	    wp->id, minimum, EVBUFFER_LENGTH(evb));
1544 	evbuffer_drain(evb, minimum);
1545 
1546 	/*
1547 	 * Adjust the base offset. If it would roll over, all the offsets into
1548 	 * the buffer need to be adjusted.
1549 	 */
1550 	if (wp->base_offset > SIZE_MAX - minimum) {
1551 		log_debug("%s: %%%u base offset has wrapped", __func__, wp->id);
1552 		wp->offset.used -= wp->base_offset;
1553 		if (wp->pipe_fd != -1)
1554 			wp->pipe_offset.used -= wp->base_offset;
1555 		TAILQ_FOREACH(c, &clients, entry) {
1556 			if (c->session == NULL || (~c->flags & CLIENT_CONTROL))
1557 				continue;
1558 			wpo = control_pane_offset(c, wp, &flag);
1559 			if (wpo != NULL && !flag)
1560 				wpo->used -= wp->base_offset;
1561 		}
1562 		wp->base_offset = minimum;
1563 	} else
1564 		wp->base_offset += minimum;
1565 
1566 out:
1567 	/*
1568 	 * If there is data remaining, and there are no clients able to consume
1569 	 * it, do not read any more. This is true when there are attached
1570 	 * clients, all of which are control clients which are not able to
1571 	 * accept any more data.
1572 	 */
1573 	log_debug("%s: pane %%%u is %s", __func__, wp->id, off ? "off" : "on");
1574 	if (off)
1575 		bufferevent_disable(wp->event, EV_READ);
1576 	else
1577 		bufferevent_enable(wp->event, EV_READ);
1578 }
1579 
1580 /* Check whether pane should be focused. */
1581 static void
1582 server_client_check_pane_focus(struct window_pane *wp)
1583 {
1584 	struct client	*c;
1585 	int		 push;
1586 
1587 	/* Do we need to push the focus state? */
1588 	push = wp->flags & PANE_FOCUSPUSH;
1589 	wp->flags &= ~PANE_FOCUSPUSH;
1590 
1591 	/* If we're not the active pane in our window, we're not focused. */
1592 	if (wp->window->active != wp)
1593 		goto not_focused;
1594 
1595 	/*
1596 	 * If our window is the current window in any focused clients with an
1597 	 * attached session, we're focused.
1598 	 */
1599 	TAILQ_FOREACH(c, &clients, entry) {
1600 		if (c->session == NULL || !(c->flags & CLIENT_FOCUSED))
1601 			continue;
1602 		if (c->session->attached == 0)
1603 			continue;
1604 
1605 		if (c->session->curw->window == wp->window)
1606 			goto focused;
1607 	}
1608 
1609 not_focused:
1610 	if (push || (wp->flags & PANE_FOCUSED)) {
1611 		if (wp->base.mode & MODE_FOCUSON)
1612 			bufferevent_write(wp->event, "\033[O", 3);
1613 		notify_pane("pane-focus-out", wp);
1614 	}
1615 	wp->flags &= ~PANE_FOCUSED;
1616 	return;
1617 
1618 focused:
1619 	if (push || !(wp->flags & PANE_FOCUSED)) {
1620 		if (wp->base.mode & MODE_FOCUSON)
1621 			bufferevent_write(wp->event, "\033[I", 3);
1622 		notify_pane("pane-focus-in", wp);
1623 		session_update_activity(c->session, NULL);
1624 	}
1625 	wp->flags |= PANE_FOCUSED;
1626 }
1627 
1628 /*
1629  * Update cursor position and mode settings. The scroll region and attributes
1630  * are cleared when idle (waiting for an event) as this is the most likely time
1631  * a user may interrupt tmux, for example with ~^Z in ssh(1). This is a
1632  * compromise between excessive resets and likelihood of an interrupt.
1633  *
1634  * tty_region/tty_reset/tty_update_mode already take care of not resetting
1635  * things that are already in their default state.
1636  */
1637 static void
1638 server_client_reset_state(struct client *c)
1639 {
1640 	struct tty		*tty = &c->tty;
1641 	struct window		*w = c->session->curw->window;
1642 	struct window_pane	*wp = server_client_get_pane(c), *loop;
1643 	struct screen		*s = NULL;
1644 	struct options		*oo = c->session->options;
1645 	int			 mode = 0, cursor, flags;
1646 	u_int			 cx = 0, cy = 0, ox, oy, sx, sy;
1647 
1648 	if (c->flags & (CLIENT_CONTROL|CLIENT_SUSPENDED))
1649 		return;
1650 
1651 	/* Disable the block flag. */
1652 	flags = (tty->flags & TTY_BLOCK);
1653 	tty->flags &= ~TTY_BLOCK;
1654 
1655 	/* Get mode from overlay if any, else from screen. */
1656 	if (c->overlay_draw != NULL) {
1657 		if (c->overlay_mode != NULL)
1658 			s = c->overlay_mode(c, &cx, &cy);
1659 	} else
1660 		s = wp->screen;
1661 	if (s != NULL)
1662 		mode = s->mode;
1663 	log_debug("%s: client %s mode %x", __func__, c->name, mode);
1664 
1665 	/* Reset region and margin. */
1666 	tty_region_off(tty);
1667 	tty_margin_off(tty);
1668 
1669 	/* Move cursor to pane cursor and offset. */
1670 	if (c->overlay_draw == NULL) {
1671 		cursor = 0;
1672 		tty_window_offset(tty, &ox, &oy, &sx, &sy);
1673 		if (wp->xoff + s->cx >= ox && wp->xoff + s->cx <= ox + sx &&
1674 		    wp->yoff + s->cy >= oy && wp->yoff + s->cy <= oy + sy) {
1675 			cursor = 1;
1676 
1677 			cx = wp->xoff + s->cx - ox;
1678 			cy = wp->yoff + s->cy - oy;
1679 
1680 			if (status_at_line(c) == 0)
1681 				cy += status_line_size(c);
1682 		}
1683 		if (!cursor)
1684 			mode &= ~MODE_CURSOR;
1685 	}
1686 	log_debug("%s: cursor to %u,%u", __func__, cx, cy);
1687 	tty_cursor(tty, cx, cy);
1688 
1689 	/*
1690 	 * Set mouse mode if requested. To support dragging, always use button
1691 	 * mode.
1692 	 */
1693 	if (options_get_number(oo, "mouse")) {
1694 		if (c->overlay_draw == NULL) {
1695 			mode &= ~ALL_MOUSE_MODES;
1696 			TAILQ_FOREACH(loop, &w->panes, entry) {
1697 				if (loop->screen->mode & MODE_MOUSE_ALL)
1698 					mode |= MODE_MOUSE_ALL;
1699 			}
1700 		}
1701 		if (~mode & MODE_MOUSE_ALL)
1702 			mode |= MODE_MOUSE_BUTTON;
1703 	}
1704 
1705 	/* Clear bracketed paste mode if at the prompt. */
1706 	if (c->overlay_draw == NULL && c->prompt_string != NULL)
1707 		mode &= ~MODE_BRACKETPASTE;
1708 
1709 	/* Set the terminal mode and reset attributes. */
1710 	tty_update_mode(tty, mode, s);
1711 	tty_reset(tty);
1712 
1713 	/* All writing must be done, send a sync end (if it was started). */
1714 	tty_sync_end(tty);
1715 	tty->flags |= flags;
1716 }
1717 
1718 /* Repeat time callback. */
1719 static void
1720 server_client_repeat_timer(__unused int fd, __unused short events, void *data)
1721 {
1722 	struct client	*c = data;
1723 
1724 	if (c->flags & CLIENT_REPEAT) {
1725 		server_client_set_key_table(c, NULL);
1726 		c->flags &= ~CLIENT_REPEAT;
1727 		server_status_client(c);
1728 	}
1729 }
1730 
1731 /* Double-click callback. */
1732 static void
1733 server_client_click_timer(__unused int fd, __unused short events, void *data)
1734 {
1735 	struct client		*c = data;
1736 	struct key_event	*event;
1737 
1738 	log_debug("click timer expired");
1739 
1740 	if (c->flags & CLIENT_TRIPLECLICK) {
1741 		/*
1742 		 * Waiting for a third click that hasn't happened, so this must
1743 		 * have been a double click.
1744 		 */
1745 		event = xmalloc(sizeof *event);
1746 		event->key = KEYC_DOUBLECLICK;
1747 		memcpy(&event->m, &c->click_event, sizeof event->m);
1748 		if (!server_client_handle_key(c, event))
1749 			free(event);
1750 	}
1751 	c->flags &= ~(CLIENT_DOUBLECLICK|CLIENT_TRIPLECLICK);
1752 }
1753 
1754 /* Check if client should be exited. */
1755 static void
1756 server_client_check_exit(struct client *c)
1757 {
1758 	struct client_file	*cf;
1759 	const char		*name = c->exit_session;
1760 	char			*data;
1761 	size_t			 size, msize;
1762 
1763 	if (c->flags & (CLIENT_DEAD|CLIENT_EXITED))
1764 		return;
1765 	if (~c->flags & CLIENT_EXIT)
1766 		return;
1767 
1768 	if (c->flags & CLIENT_CONTROL) {
1769 		control_discard(c);
1770 		if (!control_all_done(c))
1771 			return;
1772 	}
1773 	RB_FOREACH(cf, client_files, &c->files) {
1774 		if (EVBUFFER_LENGTH(cf->buffer) != 0)
1775 			return;
1776 	}
1777 
1778 	if (c->flags & CLIENT_ATTACHED)
1779 		notify_client("client-detached", c);
1780 	c->flags |= CLIENT_EXITED;
1781 
1782 	switch (c->exit_type) {
1783 	case CLIENT_EXIT_RETURN:
1784 		if (c->exit_message != NULL) {
1785 			msize = strlen(c->exit_message) + 1;
1786 			size = (sizeof c->retval) + msize;
1787 		} else
1788 			size = (sizeof c->retval);
1789 		data = xmalloc(size);
1790 		memcpy(data, &c->retval, sizeof c->retval);
1791 		if (c->exit_message != NULL)
1792 			memcpy(data + sizeof c->retval, c->exit_message, msize);
1793 		proc_send(c->peer, MSG_EXIT, -1, data, size);
1794 		free(data);
1795 		break;
1796 	case CLIENT_EXIT_SHUTDOWN:
1797 		proc_send(c->peer, MSG_SHUTDOWN, -1, NULL, 0);
1798 		break;
1799 	case CLIENT_EXIT_DETACH:
1800 		proc_send(c->peer, c->exit_msgtype, -1, name, strlen(name) + 1);
1801 		break;
1802 	}
1803 	free(c->exit_session);
1804 	free(c->exit_message);
1805 }
1806 
1807 /* Redraw timer callback. */
1808 static void
1809 server_client_redraw_timer(__unused int fd, __unused short events,
1810     __unused void *data)
1811 {
1812 	log_debug("redraw timer fired");
1813 }
1814 
1815 /*
1816  * Check if modes need to be updated. Only modes in the current window are
1817  * updated and it is done when the status line is redrawn.
1818  */
1819 static void
1820 server_client_check_modes(struct client *c)
1821 {
1822 	struct window			*w = c->session->curw->window;
1823 	struct window_pane		*wp;
1824 	struct window_mode_entry	*wme;
1825 
1826 	if (c->flags & (CLIENT_CONTROL|CLIENT_SUSPENDED))
1827 		return;
1828 	if (~c->flags & CLIENT_REDRAWSTATUS)
1829 		return;
1830 	TAILQ_FOREACH(wp, &w->panes, entry) {
1831 		wme = TAILQ_FIRST(&wp->modes);
1832 		if (wme != NULL && wme->mode->update != NULL)
1833 			wme->mode->update(wme);
1834 	}
1835 }
1836 
1837 /* Check for client redraws. */
1838 static void
1839 server_client_check_redraw(struct client *c)
1840 {
1841 	struct session		*s = c->session;
1842 	struct tty		*tty = &c->tty;
1843 	struct window		*w = c->session->curw->window;
1844 	struct window_pane	*wp;
1845 	int			 needed, flags, mode = tty->mode, new_flags = 0;
1846 	int			 redraw;
1847 	u_int			 bit = 0;
1848 	struct timeval		 tv = { .tv_usec = 1000 };
1849 	static struct event	 ev;
1850 	size_t			 left;
1851 
1852 	if (c->flags & (CLIENT_CONTROL|CLIENT_SUSPENDED))
1853 		return;
1854 	if (c->flags & CLIENT_ALLREDRAWFLAGS) {
1855 		log_debug("%s: redraw%s%s%s%s%s", c->name,
1856 		    (c->flags & CLIENT_REDRAWWINDOW) ? " window" : "",
1857 		    (c->flags & CLIENT_REDRAWSTATUS) ? " status" : "",
1858 		    (c->flags & CLIENT_REDRAWBORDERS) ? " borders" : "",
1859 		    (c->flags & CLIENT_REDRAWOVERLAY) ? " overlay" : "",
1860 		    (c->flags & CLIENT_REDRAWPANES) ? " panes" : "");
1861 	}
1862 
1863 	/*
1864 	 * If there is outstanding data, defer the redraw until it has been
1865 	 * consumed. We can just add a timer to get out of the event loop and
1866 	 * end up back here.
1867 	 */
1868 	needed = 0;
1869 	if (c->flags & CLIENT_ALLREDRAWFLAGS)
1870 		needed = 1;
1871 	else {
1872 		TAILQ_FOREACH(wp, &w->panes, entry) {
1873 			if (wp->flags & PANE_REDRAW) {
1874 				needed = 1;
1875 				break;
1876 			}
1877 		}
1878 		if (needed)
1879 			new_flags |= CLIENT_REDRAWPANES;
1880 	}
1881 	if (needed && (left = EVBUFFER_LENGTH(tty->out)) != 0) {
1882 		log_debug("%s: redraw deferred (%zu left)", c->name, left);
1883 		if (!evtimer_initialized(&ev))
1884 			evtimer_set(&ev, server_client_redraw_timer, NULL);
1885 		if (!evtimer_pending(&ev, NULL)) {
1886 			log_debug("redraw timer started");
1887 			evtimer_add(&ev, &tv);
1888 		}
1889 
1890 		if (~c->flags & CLIENT_REDRAWWINDOW) {
1891 			TAILQ_FOREACH(wp, &w->panes, entry) {
1892 				if (wp->flags & PANE_REDRAW) {
1893 					log_debug("%s: pane %%%u needs redraw",
1894 					    c->name, wp->id);
1895 					c->redraw_panes |= (1 << bit);
1896 				}
1897 				if (++bit == 64) {
1898 					/*
1899 					 * If more that 64 panes, give up and
1900 					 * just redraw the window.
1901 					 */
1902 					new_flags &= CLIENT_REDRAWPANES;
1903 					new_flags |= CLIENT_REDRAWWINDOW;
1904 					break;
1905 				}
1906 			}
1907 			if (c->redraw_panes != 0)
1908 				c->flags |= CLIENT_REDRAWPANES;
1909 		}
1910 		c->flags |= new_flags;
1911 		return;
1912 	} else if (needed)
1913 		log_debug("%s: redraw needed", c->name);
1914 
1915 	flags = tty->flags & (TTY_BLOCK|TTY_FREEZE|TTY_NOCURSOR);
1916 	tty->flags = (tty->flags & ~(TTY_BLOCK|TTY_FREEZE))|TTY_NOCURSOR;
1917 
1918 	if (~c->flags & CLIENT_REDRAWWINDOW) {
1919 		/*
1920 		 * If not redrawing the entire window, check whether each pane
1921 		 * needs to be redrawn.
1922 		 */
1923 		TAILQ_FOREACH(wp, &w->panes, entry) {
1924 			redraw = 0;
1925 			if (wp->flags & PANE_REDRAW)
1926 				redraw = 1;
1927 			else if (c->flags & CLIENT_REDRAWPANES)
1928 				redraw = !!(c->redraw_panes & (1 << bit));
1929 			bit++;
1930 			if (!redraw)
1931 				continue;
1932 			log_debug("%s: redrawing pane %%%u", __func__, wp->id);
1933 			screen_redraw_pane(c, wp);
1934 		}
1935 		c->redraw_panes = 0;
1936 		c->flags &= ~CLIENT_REDRAWPANES;
1937 	}
1938 
1939 	if (c->flags & CLIENT_ALLREDRAWFLAGS) {
1940 		if (options_get_number(s->options, "set-titles"))
1941 			server_client_set_title(c);
1942 		screen_redraw_screen(c);
1943 	}
1944 
1945 	tty->flags = (tty->flags & ~TTY_NOCURSOR)|(flags & TTY_NOCURSOR);
1946 	tty_update_mode(tty, mode, NULL);
1947 	tty->flags = (tty->flags & ~(TTY_BLOCK|TTY_FREEZE|TTY_NOCURSOR))|flags;
1948 
1949 	c->flags &= ~(CLIENT_ALLREDRAWFLAGS|CLIENT_STATUSFORCE);
1950 
1951 	if (needed) {
1952 		/*
1953 		 * We would have deferred the redraw unless the output buffer
1954 		 * was empty, so we can record how many bytes the redraw
1955 		 * generated.
1956 		 */
1957 		c->redraw = EVBUFFER_LENGTH(tty->out);
1958 		log_debug("%s: redraw added %zu bytes", c->name, c->redraw);
1959 	}
1960 }
1961 
1962 /* Set client title. */
1963 static void
1964 server_client_set_title(struct client *c)
1965 {
1966 	struct session		*s = c->session;
1967 	const char		*template;
1968 	char			*title;
1969 	struct format_tree	*ft;
1970 
1971 	template = options_get_string(s->options, "set-titles-string");
1972 
1973 	ft = format_create(c, NULL, FORMAT_NONE, 0);
1974 	format_defaults(ft, c, NULL, NULL, NULL);
1975 
1976 	title = format_expand_time(ft, template);
1977 	if (c->title == NULL || strcmp(title, c->title) != 0) {
1978 		free(c->title);
1979 		c->title = xstrdup(title);
1980 		tty_set_title(&c->tty, c->title);
1981 	}
1982 	free(title);
1983 
1984 	format_free(ft);
1985 }
1986 
1987 /* Dispatch message from client. */
1988 static void
1989 server_client_dispatch(struct imsg *imsg, void *arg)
1990 {
1991 	struct client	*c = arg;
1992 	ssize_t		 datalen;
1993 	struct session	*s;
1994 
1995 	if (c->flags & CLIENT_DEAD)
1996 		return;
1997 
1998 	if (imsg == NULL) {
1999 		server_client_lost(c);
2000 		return;
2001 	}
2002 
2003 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
2004 
2005 	switch (imsg->hdr.type) {
2006 	case MSG_IDENTIFY_FEATURES:
2007 	case MSG_IDENTIFY_FLAGS:
2008 	case MSG_IDENTIFY_LONGFLAGS:
2009 	case MSG_IDENTIFY_TERM:
2010 	case MSG_IDENTIFY_TTYNAME:
2011 	case MSG_IDENTIFY_CWD:
2012 	case MSG_IDENTIFY_STDIN:
2013 	case MSG_IDENTIFY_STDOUT:
2014 	case MSG_IDENTIFY_ENVIRON:
2015 	case MSG_IDENTIFY_CLIENTPID:
2016 	case MSG_IDENTIFY_DONE:
2017 		server_client_dispatch_identify(c, imsg);
2018 		break;
2019 	case MSG_COMMAND:
2020 		server_client_dispatch_command(c, imsg);
2021 		break;
2022 	case MSG_RESIZE:
2023 		if (datalen != 0)
2024 			fatalx("bad MSG_RESIZE size");
2025 
2026 		if (c->flags & CLIENT_CONTROL)
2027 			break;
2028 		server_client_update_latest(c);
2029 		server_client_clear_overlay(c);
2030 		tty_resize(&c->tty);
2031 		recalculate_sizes();
2032 		server_redraw_client(c);
2033 		if (c->session != NULL)
2034 			notify_client("client-resized", c);
2035 		break;
2036 	case MSG_EXITING:
2037 		if (datalen != 0)
2038 			fatalx("bad MSG_EXITING size");
2039 		c->session = NULL;
2040 		tty_close(&c->tty);
2041 		proc_send(c->peer, MSG_EXITED, -1, NULL, 0);
2042 		break;
2043 	case MSG_WAKEUP:
2044 	case MSG_UNLOCK:
2045 		if (datalen != 0)
2046 			fatalx("bad MSG_WAKEUP size");
2047 
2048 		if (!(c->flags & CLIENT_SUSPENDED))
2049 			break;
2050 		c->flags &= ~CLIENT_SUSPENDED;
2051 
2052 		if (c->fd == -1 || c->session == NULL) /* exited already */
2053 			break;
2054 		s = c->session;
2055 
2056 		if (gettimeofday(&c->activity_time, NULL) != 0)
2057 			fatal("gettimeofday failed");
2058 
2059 		tty_start_tty(&c->tty);
2060 		server_redraw_client(c);
2061 		recalculate_sizes();
2062 
2063 		if (s != NULL)
2064 			session_update_activity(s, &c->activity_time);
2065 		break;
2066 	case MSG_SHELL:
2067 		if (datalen != 0)
2068 			fatalx("bad MSG_SHELL size");
2069 
2070 		server_client_dispatch_shell(c);
2071 		break;
2072 	case MSG_WRITE_READY:
2073 		server_client_dispatch_write_ready(c, imsg);
2074 		break;
2075 	case MSG_READ:
2076 		server_client_dispatch_read_data(c, imsg);
2077 		break;
2078 	case MSG_READ_DONE:
2079 		server_client_dispatch_read_done(c, imsg);
2080 		break;
2081 	}
2082 }
2083 
2084 /* Callback when command is done. */
2085 static enum cmd_retval
2086 server_client_command_done(struct cmdq_item *item, __unused void *data)
2087 {
2088 	struct client	*c = cmdq_get_client(item);
2089 
2090 	if (~c->flags & CLIENT_ATTACHED)
2091 		c->flags |= CLIENT_EXIT;
2092 	else if (~c->flags & CLIENT_EXIT)
2093 		tty_send_requests(&c->tty);
2094 	return (CMD_RETURN_NORMAL);
2095 }
2096 
2097 /* Handle command message. */
2098 static void
2099 server_client_dispatch_command(struct client *c, struct imsg *imsg)
2100 {
2101 	struct msg_command	  data;
2102 	char			 *buf;
2103 	size_t			  len;
2104 	int			  argc;
2105 	char			**argv, *cause;
2106 	struct cmd_parse_result	 *pr;
2107 
2108 	if (c->flags & CLIENT_EXIT)
2109 		return;
2110 
2111 	if (imsg->hdr.len - IMSG_HEADER_SIZE < sizeof data)
2112 		fatalx("bad MSG_COMMAND size");
2113 	memcpy(&data, imsg->data, sizeof data);
2114 
2115 	buf = (char *)imsg->data + sizeof data;
2116 	len = imsg->hdr.len  - IMSG_HEADER_SIZE - sizeof data;
2117 	if (len > 0 && buf[len - 1] != '\0')
2118 		fatalx("bad MSG_COMMAND string");
2119 
2120 	argc = data.argc;
2121 	if (cmd_unpack_argv(buf, len, argc, &argv) != 0) {
2122 		cause = xstrdup("command too long");
2123 		goto error;
2124 	}
2125 
2126 	if (argc == 0) {
2127 		argc = 1;
2128 		argv = xcalloc(1, sizeof *argv);
2129 		*argv = xstrdup("new-session");
2130 	}
2131 
2132 	pr = cmd_parse_from_arguments(argc, argv, NULL);
2133 	switch (pr->status) {
2134 	case CMD_PARSE_EMPTY:
2135 		cause = xstrdup("empty command");
2136 		goto error;
2137 	case CMD_PARSE_ERROR:
2138 		cause = pr->error;
2139 		goto error;
2140 	case CMD_PARSE_SUCCESS:
2141 		break;
2142 	}
2143 	cmd_free_argv(argc, argv);
2144 
2145 	cmdq_append(c, cmdq_get_command(pr->cmdlist, NULL));
2146 	cmdq_append(c, cmdq_get_callback(server_client_command_done, NULL));
2147 
2148 	cmd_list_free(pr->cmdlist);
2149 	return;
2150 
2151 error:
2152 	cmd_free_argv(argc, argv);
2153 
2154 	cmdq_append(c, cmdq_get_error(cause));
2155 	free(cause);
2156 
2157 	c->flags |= CLIENT_EXIT;
2158 }
2159 
2160 /* Handle identify message. */
2161 static void
2162 server_client_dispatch_identify(struct client *c, struct imsg *imsg)
2163 {
2164 	const char	*data, *home;
2165 	size_t		 datalen;
2166 	int		 flags, feat;
2167 	uint64_t	 longflags;
2168 	char		*name;
2169 
2170 	if (c->flags & CLIENT_IDENTIFIED)
2171 		fatalx("out-of-order identify message");
2172 
2173 	data = imsg->data;
2174 	datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
2175 
2176 	switch (imsg->hdr.type)	{
2177 	case MSG_IDENTIFY_FEATURES:
2178 		if (datalen != sizeof feat)
2179 			fatalx("bad MSG_IDENTIFY_FEATURES size");
2180 		memcpy(&feat, data, sizeof feat);
2181 		c->term_features |= feat;
2182 		log_debug("client %p IDENTIFY_FEATURES %s", c,
2183 		    tty_get_features(feat));
2184 		break;
2185 	case MSG_IDENTIFY_FLAGS:
2186 		if (datalen != sizeof flags)
2187 			fatalx("bad MSG_IDENTIFY_FLAGS size");
2188 		memcpy(&flags, data, sizeof flags);
2189 		c->flags |= flags;
2190 		log_debug("client %p IDENTIFY_FLAGS %#x", c, flags);
2191 		break;
2192 	case MSG_IDENTIFY_LONGFLAGS:
2193 		if (datalen != sizeof longflags)
2194 			fatalx("bad MSG_IDENTIFY_LONGFLAGS size");
2195 		memcpy(&longflags, data, sizeof longflags);
2196 		c->flags |= longflags;
2197 		log_debug("client %p IDENTIFY_LONGFLAGS %#llx", c,
2198 		    (unsigned long long)longflags);
2199 		break;
2200 	case MSG_IDENTIFY_TERM:
2201 		if (datalen == 0 || data[datalen - 1] != '\0')
2202 			fatalx("bad MSG_IDENTIFY_TERM string");
2203 		if (*data == '\0')
2204 			c->term_name = xstrdup("unknown");
2205 		else
2206 			c->term_name = xstrdup(data);
2207 		log_debug("client %p IDENTIFY_TERM %s", c, data);
2208 		break;
2209 	case MSG_IDENTIFY_TTYNAME:
2210 		if (datalen == 0 || data[datalen - 1] != '\0')
2211 			fatalx("bad MSG_IDENTIFY_TTYNAME string");
2212 		c->ttyname = xstrdup(data);
2213 		log_debug("client %p IDENTIFY_TTYNAME %s", c, data);
2214 		break;
2215 	case MSG_IDENTIFY_CWD:
2216 		if (datalen == 0 || data[datalen - 1] != '\0')
2217 			fatalx("bad MSG_IDENTIFY_CWD string");
2218 		if (access(data, X_OK) == 0)
2219 			c->cwd = xstrdup(data);
2220 		else if ((home = find_home()) != NULL)
2221 			c->cwd = xstrdup(home);
2222 		else
2223 			c->cwd = xstrdup("/");
2224 		log_debug("client %p IDENTIFY_CWD %s", c, data);
2225 		break;
2226 	case MSG_IDENTIFY_STDIN:
2227 		if (datalen != 0)
2228 			fatalx("bad MSG_IDENTIFY_STDIN size");
2229 		c->fd = imsg->fd;
2230 		log_debug("client %p IDENTIFY_STDIN %d", c, imsg->fd);
2231 		break;
2232 	case MSG_IDENTIFY_STDOUT:
2233 		if (datalen != 0)
2234 			fatalx("bad MSG_IDENTIFY_STDOUT size");
2235 		c->out_fd = imsg->fd;
2236 		log_debug("client %p IDENTIFY_STDOUT %d", c, imsg->fd);
2237 		break;
2238 	case MSG_IDENTIFY_ENVIRON:
2239 		if (datalen == 0 || data[datalen - 1] != '\0')
2240 			fatalx("bad MSG_IDENTIFY_ENVIRON string");
2241 		if (strchr(data, '=') != NULL)
2242 			environ_put(c->environ, data, 0);
2243 		log_debug("client %p IDENTIFY_ENVIRON %s", c, data);
2244 		break;
2245 	case MSG_IDENTIFY_CLIENTPID:
2246 		if (datalen != sizeof c->pid)
2247 			fatalx("bad MSG_IDENTIFY_CLIENTPID size");
2248 		memcpy(&c->pid, data, sizeof c->pid);
2249 		log_debug("client %p IDENTIFY_CLIENTPID %ld", c, (long)c->pid);
2250 		break;
2251 	default:
2252 		break;
2253 	}
2254 
2255 	if (imsg->hdr.type != MSG_IDENTIFY_DONE)
2256 		return;
2257 	c->flags |= CLIENT_IDENTIFIED;
2258 
2259 	if (*c->ttyname != '\0')
2260 		name = xstrdup(c->ttyname);
2261 	else
2262 		xasprintf(&name, "client-%ld", (long)c->pid);
2263 	c->name = name;
2264 	log_debug("client %p name is %s", c, c->name);
2265 
2266 	if (c->flags & CLIENT_CONTROL)
2267 		control_start(c);
2268 	else if (c->fd != -1) {
2269 		if (tty_init(&c->tty, c) != 0) {
2270 			close(c->fd);
2271 			c->fd = -1;
2272 		} else {
2273 			tty_resize(&c->tty);
2274 			c->flags |= CLIENT_TERMINAL;
2275 		}
2276 		close(c->out_fd);
2277 		c->out_fd = -1;
2278 	}
2279 
2280 	/*
2281 	 * If this is the first client, load configuration files. Any later
2282 	 * clients are allowed to continue with their command even if the
2283 	 * config has not been loaded - they might have been run from inside it
2284 	 */
2285 	if ((~c->flags & CLIENT_EXIT) &&
2286 	     !cfg_finished &&
2287 	     c == TAILQ_FIRST(&clients))
2288 		start_cfg();
2289 }
2290 
2291 /* Handle shell message. */
2292 static void
2293 server_client_dispatch_shell(struct client *c)
2294 {
2295 	const char	*shell;
2296 
2297 	shell = options_get_string(global_s_options, "default-shell");
2298 	if (!checkshell(shell))
2299 		shell = _PATH_BSHELL;
2300 	proc_send(c->peer, MSG_SHELL, -1, shell, strlen(shell) + 1);
2301 
2302 	proc_kill_peer(c->peer);
2303 }
2304 
2305 /* Handle write ready message. */
2306 static void
2307 server_client_dispatch_write_ready(struct client *c, struct imsg *imsg)
2308 {
2309 	struct msg_write_ready	*msg = imsg->data;
2310 	size_t			 msglen = imsg->hdr.len - IMSG_HEADER_SIZE;
2311 	struct client_file	 find, *cf;
2312 
2313 	if (msglen != sizeof *msg)
2314 		fatalx("bad MSG_WRITE_READY size");
2315 	find.stream = msg->stream;
2316 	if ((cf = RB_FIND(client_files, &c->files, &find)) == NULL)
2317 		return;
2318 	if (msg->error != 0) {
2319 		cf->error = msg->error;
2320 		file_fire_done(cf);
2321 	} else
2322 		file_push(cf);
2323 }
2324 
2325 /* Handle read data message. */
2326 static void
2327 server_client_dispatch_read_data(struct client *c, struct imsg *imsg)
2328 {
2329 	struct msg_read_data	*msg = imsg->data;
2330 	size_t			 msglen = imsg->hdr.len - IMSG_HEADER_SIZE;
2331 	struct client_file	 find, *cf;
2332 	void			*bdata = msg + 1;
2333 	size_t			 bsize = msglen - sizeof *msg;
2334 
2335 	if (msglen < sizeof *msg)
2336 		fatalx("bad MSG_READ_DATA size");
2337 	find.stream = msg->stream;
2338 	if ((cf = RB_FIND(client_files, &c->files, &find)) == NULL)
2339 		return;
2340 
2341 	log_debug("%s: file %d read %zu bytes", c->name, cf->stream, bsize);
2342 	if (cf->error == 0) {
2343 		if (evbuffer_add(cf->buffer, bdata, bsize) != 0) {
2344 			cf->error = ENOMEM;
2345 			file_fire_done(cf);
2346 		} else
2347 			file_fire_read(cf);
2348 	}
2349 }
2350 
2351 /* Handle read done message. */
2352 static void
2353 server_client_dispatch_read_done(struct client *c, struct imsg *imsg)
2354 {
2355 	struct msg_read_done	*msg = imsg->data;
2356 	size_t			 msglen = imsg->hdr.len - IMSG_HEADER_SIZE;
2357 	struct client_file	 find, *cf;
2358 
2359 	if (msglen != sizeof *msg)
2360 		fatalx("bad MSG_READ_DONE size");
2361 	find.stream = msg->stream;
2362 	if ((cf = RB_FIND(client_files, &c->files, &find)) == NULL)
2363 		return;
2364 
2365 	log_debug("%s: file %d read done", c->name, cf->stream);
2366 	cf->error = msg->error;
2367 	file_fire_done(cf);
2368 }
2369 
2370 /* Get client working directory. */
2371 const char *
2372 server_client_get_cwd(struct client *c, struct session *s)
2373 {
2374 	const char	*home;
2375 
2376 	if (!cfg_finished && cfg_client != NULL)
2377 		return (cfg_client->cwd);
2378 	if (c != NULL && c->session == NULL && c->cwd != NULL)
2379 		return (c->cwd);
2380 	if (s != NULL && s->cwd != NULL)
2381 		return (s->cwd);
2382 	if (c != NULL && (s = c->session) != NULL && s->cwd != NULL)
2383 		return (s->cwd);
2384 	if ((home = find_home()) != NULL)
2385 		return (home);
2386 	return ("/");
2387 }
2388 
2389 /* Get control client flags. */
2390 static uint64_t
2391 server_client_control_flags(struct client *c, const char *next)
2392 {
2393 	if (strcmp(next, "pause-after") == 0) {
2394 		c->pause_age = 0;
2395 		return (CLIENT_CONTROL_PAUSEAFTER);
2396 	}
2397 	if (sscanf(next, "pause-after=%u", &c->pause_age) == 1) {
2398 		c->pause_age *= 1000;
2399 		return (CLIENT_CONTROL_PAUSEAFTER);
2400 	}
2401 	if (strcmp(next, "no-output") == 0)
2402 		return (CLIENT_CONTROL_NOOUTPUT);
2403 	if (strcmp(next, "wait-exit") == 0)
2404 		return (CLIENT_CONTROL_WAITEXIT);
2405 	return (0);
2406 }
2407 
2408 /* Set client flags. */
2409 void
2410 server_client_set_flags(struct client *c, const char *flags)
2411 {
2412 	char	*s, *copy, *next;
2413 	uint64_t flag;
2414 	int	 not;
2415 
2416 	s = copy = xstrdup (flags);
2417 	while ((next = strsep(&s, ",")) != NULL) {
2418 		not = (*next == '!');
2419 		if (not)
2420 			next++;
2421 
2422 		if (c->flags & CLIENT_CONTROL)
2423 			flag = server_client_control_flags(c, next);
2424 		else
2425 			flag = 0;
2426 		if (strcmp(next, "read-only") == 0)
2427 			flag = CLIENT_READONLY;
2428 		else if (strcmp(next, "ignore-size") == 0)
2429 			flag = CLIENT_IGNORESIZE;
2430 		else if (strcmp(next, "active-pane") == 0)
2431 			flag = CLIENT_ACTIVEPANE;
2432 		if (flag == 0)
2433 			continue;
2434 
2435 		log_debug("client %s set flag %s", c->name, next);
2436 		if (not)
2437 			c->flags &= ~flag;
2438 		else
2439 			c->flags |= flag;
2440 		if (flag == CLIENT_CONTROL_NOOUTPUT)
2441 			control_reset_offsets(c);
2442 	}
2443 	free(copy);
2444 	proc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);
2445 }
2446 
2447 /* Get client flags. This is only flags useful to show to users. */
2448 const char *
2449 server_client_get_flags(struct client *c)
2450 {
2451 	static char	s[256];
2452 	char	 	tmp[32];
2453 
2454 	*s = '\0';
2455 	if (c->flags & CLIENT_ATTACHED)
2456 		strlcat(s, "attached,", sizeof s);
2457 	if (c->flags & CLIENT_CONTROL)
2458 		strlcat(s, "control-mode,", sizeof s);
2459 	if (c->flags & CLIENT_IGNORESIZE)
2460 		strlcat(s, "ignore-size,", sizeof s);
2461 	if (c->flags & CLIENT_CONTROL_NOOUTPUT)
2462 		strlcat(s, "no-output,", sizeof s);
2463 	if (c->flags & CLIENT_CONTROL_WAITEXIT)
2464 		strlcat(s, "wait-exit,", sizeof s);
2465 	if (c->flags & CLIENT_CONTROL_PAUSEAFTER) {
2466 		xsnprintf(tmp, sizeof tmp, "pause-after=%u,",
2467 		    c->pause_age / 1000);
2468 		strlcat(s, tmp, sizeof s);
2469 	}
2470 	if (c->flags & CLIENT_READONLY)
2471 		strlcat(s, "read-only,", sizeof s);
2472 	if (c->flags & CLIENT_ACTIVEPANE)
2473 		strlcat(s, "active-pane,", sizeof s);
2474 	if (c->flags & CLIENT_SUSPENDED)
2475 		strlcat(s, "suspended,", sizeof s);
2476 	if (c->flags & CLIENT_UTF8)
2477 		strlcat(s, "UTF-8,", sizeof s);
2478 	if (*s != '\0')
2479 		s[strlen(s) - 1] = '\0';
2480 	return (s);
2481 }
2482 
2483 /* Get client window. */
2484 static struct client_window *
2485 server_client_get_client_window(struct client *c, u_int id)
2486 {
2487 	struct client_window	cw = { .window = id };
2488 
2489 	return (RB_FIND(client_windows, &c->windows, &cw));
2490 }
2491 
2492 /* Get client active pane. */
2493 struct window_pane *
2494 server_client_get_pane(struct client *c)
2495 {
2496 	struct session		*s = c->session;
2497 	struct client_window	*cw;
2498 
2499 	if (s == NULL)
2500 		return (NULL);
2501 
2502 	if (~c->flags & CLIENT_ACTIVEPANE)
2503 		return (s->curw->window->active);
2504 	cw = server_client_get_client_window(c, s->curw->window->id);
2505 	if (cw == NULL)
2506 		return (s->curw->window->active);
2507 	return (cw->pane);
2508 }
2509 
2510 /* Set client active pane. */
2511 void
2512 server_client_set_pane(struct client *c, struct window_pane *wp)
2513 {
2514 	struct session		*s = c->session;
2515 	struct client_window	*cw;
2516 
2517 	if (s == NULL)
2518 		return;
2519 
2520 	cw = server_client_get_client_window(c, s->curw->window->id);
2521 	if (cw == NULL) {
2522 		cw = xcalloc(1, sizeof *cw);
2523 		cw->window = s->curw->window->id;
2524 		RB_INSERT(client_windows, &c->windows, cw);
2525 	}
2526 	cw->pane = wp;
2527 	log_debug("%s pane now %%%u", c->name, wp->id);
2528 }
2529 
2530 /* Remove pane from client lists. */
2531 void
2532 server_client_remove_pane(struct window_pane *wp)
2533 {
2534 	struct client		*c;
2535 	struct window		*w = wp->window;
2536 	struct client_window	*cw;
2537 
2538 	TAILQ_FOREACH(c, &clients, entry) {
2539 		cw = server_client_get_client_window(c, w->id);
2540 		if (cw != NULL && cw->pane == wp) {
2541 			RB_REMOVE(client_windows, &c->windows, cw);
2542 			free(cw);
2543 		}
2544 	}
2545 }
2546