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