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