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