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