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