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