1/* $OpenBSD$ */
2
3/*
4 * Copyright (c) 2007 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/time.h>
21
22#include <string.h>
23#include <stdlib.h>
24#include <unistd.h>
25#include <time.h>
26
27#include "tmux.h"
28
29struct sessions		sessions;
30u_int			next_session_id;
31struct session_groups	session_groups = RB_INITIALIZER(&session_groups);
32
33static void	session_free(int, short, void *);
34
35static void	session_lock_timer(int, short, void *);
36
37static struct winlink *session_next_alert(struct winlink *);
38static struct winlink *session_previous_alert(struct winlink *);
39
40static void	session_group_remove(struct session *);
41static void	session_group_synchronize1(struct session *, struct session *);
42
43int
44session_cmp(struct session *s1, struct session *s2)
45{
46	return (strcmp(s1->name, s2->name));
47}
48RB_GENERATE(sessions, session, entry, session_cmp);
49
50static int
51session_group_cmp(struct session_group *s1, struct session_group *s2)
52{
53	return (strcmp(s1->name, s2->name));
54}
55RB_GENERATE_STATIC(session_groups, session_group, entry, session_group_cmp);
56
57/*
58 * Find if session is still alive. This is true if it is still on the global
59 * sessions list.
60 */
61int
62session_alive(struct session *s)
63{
64	struct session *s_loop;
65
66	RB_FOREACH(s_loop, sessions, &sessions) {
67		if (s_loop == s)
68			return (1);
69	}
70	return (0);
71}
72
73/* Find session by name. */
74struct session *
75session_find(const char *name)
76{
77	struct session	s;
78
79	s.name = __UNCONST(name);
80	return (RB_FIND(sessions, &sessions, &s));
81}
82
83/* Find session by id parsed from a string. */
84struct session *
85session_find_by_id_str(const char *s)
86{
87	const char	*errstr;
88	u_int		 id;
89
90	if (*s != '$')
91		return (NULL);
92
93	id = strtonum(s + 1, 0, UINT_MAX, &errstr);
94	if (errstr != NULL)
95		return (NULL);
96	return (session_find_by_id(id));
97}
98
99/* Find session by id. */
100struct session *
101session_find_by_id(u_int id)
102{
103	struct session	*s;
104
105	RB_FOREACH(s, sessions, &sessions) {
106		if (s->id == id)
107			return (s);
108	}
109	return (NULL);
110}
111
112/* Create a new session. */
113struct session *
114session_create(const char *prefix, const char *name, const char *cwd,
115    struct environ *env, struct options *oo, struct termios *tio)
116{
117	struct session	*s;
118
119	s = xcalloc(1, sizeof *s);
120	s->references = 1;
121	s->flags = 0;
122
123	s->cwd = xstrdup(cwd);
124
125	TAILQ_INIT(&s->lastw);
126	RB_INIT(&s->windows);
127
128	s->environ = env;
129	s->options = oo;
130
131	status_update_cache(s);
132
133	s->tio = NULL;
134	if (tio != NULL) {
135		s->tio = xmalloc(sizeof *s->tio);
136		memcpy(s->tio, tio, sizeof *s->tio);
137	}
138
139	if (name != NULL) {
140		s->name = xstrdup(name);
141		s->id = next_session_id++;
142	} else {
143		do {
144			s->id = next_session_id++;
145			free(s->name);
146			if (prefix != NULL)
147				xasprintf(&s->name, "%s-%u", prefix, s->id);
148			else
149				xasprintf(&s->name, "%u", s->id);
150		} while (RB_FIND(sessions, &sessions, s) != NULL);
151	}
152	RB_INSERT(sessions, &sessions, s);
153
154	log_debug("new session %s $%u", s->name, s->id);
155
156	if (gettimeofday(&s->creation_time, NULL) != 0)
157		fatal("gettimeofday failed");
158	session_update_activity(s, &s->creation_time);
159
160	return (s);
161}
162
163/* Add a reference to a session. */
164void
165session_add_ref(struct session *s, const char *from)
166{
167	s->references++;
168	log_debug("%s: %s %s, now %d", __func__, s->name, from, s->references);
169}
170
171/* Remove a reference from a session. */
172void
173session_remove_ref(struct session *s, const char *from)
174{
175	s->references--;
176	log_debug("%s: %s %s, now %d", __func__, s->name, from, s->references);
177
178	if (s->references == 0)
179		event_once(-1, EV_TIMEOUT, session_free, s, NULL);
180}
181
182/* Free session. */
183static void
184session_free(__unused int fd, __unused short events, void *arg)
185{
186	struct session	*s = arg;
187
188	log_debug("session %s freed (%d references)", s->name, s->references);
189
190	if (s->references == 0) {
191		environ_free(s->environ);
192		options_free(s->options);
193
194		free(s->name);
195		free(s);
196	}
197}
198
199/* Destroy a session. */
200void
201session_destroy(struct session *s, int notify, const char *from)
202{
203	struct winlink	*wl;
204
205	log_debug("session %s destroyed (%s)", s->name, from);
206
207	if (s->curw == NULL)
208		return;
209	s->curw = NULL;
210
211	RB_REMOVE(sessions, &sessions, s);
212	if (notify)
213		notify_session("session-closed", s);
214
215	free(s->tio);
216
217	if (event_initialized(&s->lock_timer))
218		event_del(&s->lock_timer);
219
220	session_group_remove(s);
221
222	while (!TAILQ_EMPTY(&s->lastw))
223		winlink_stack_remove(&s->lastw, TAILQ_FIRST(&s->lastw));
224	while (!RB_EMPTY(&s->windows)) {
225		wl = RB_ROOT(&s->windows);
226		notify_session_window("window-unlinked", s, wl->window);
227		winlink_remove(&s->windows, wl);
228	}
229
230	free(__UNCONST(s->cwd));
231
232	session_remove_ref(s, __func__);
233}
234
235/* Sanitize session name. */
236char *
237session_check_name(const char *name)
238{
239	char	*copy, *cp, *new_name;
240
241	if (*name == '\0')
242		return (NULL);
243	copy = xstrdup(name);
244	for (cp = copy; *cp != '\0'; cp++) {
245		if (*cp == ':' || *cp == '.')
246			*cp = '_';
247	}
248	utf8_stravis(&new_name, copy, VIS_OCTAL|VIS_CSTYLE|VIS_TAB|VIS_NL);
249	free(copy);
250	return (new_name);
251}
252
253/* Lock session if it has timed out. */
254static void
255session_lock_timer(__unused int fd, __unused short events, void *arg)
256{
257	struct session	*s = arg;
258
259	if (s->attached == 0)
260		return;
261
262	log_debug("session %s locked, activity time %lld", s->name,
263	    (long long)s->activity_time.tv_sec);
264
265	server_lock_session(s);
266	recalculate_sizes();
267}
268
269/* Update activity time. */
270void
271session_update_activity(struct session *s, struct timeval *from)
272{
273	struct timeval	*last = &s->last_activity_time;
274	struct timeval	 tv;
275
276	memcpy(last, &s->activity_time, sizeof *last);
277	if (from == NULL)
278		gettimeofday(&s->activity_time, NULL);
279	else
280		memcpy(&s->activity_time, from, sizeof s->activity_time);
281
282	log_debug("session $%u %s activity %lld.%06d (last %lld.%06d)", s->id,
283	    s->name, (long long)s->activity_time.tv_sec,
284	    (int)s->activity_time.tv_usec, (long long)last->tv_sec,
285	    (int)last->tv_usec);
286
287	if (evtimer_initialized(&s->lock_timer))
288		evtimer_del(&s->lock_timer);
289	else
290		evtimer_set(&s->lock_timer, session_lock_timer, s);
291
292	if (s->attached != 0) {
293		timerclear(&tv);
294		tv.tv_sec = options_get_number(s->options, "lock-after-time");
295		if (tv.tv_sec != 0)
296			evtimer_add(&s->lock_timer, &tv);
297	}
298}
299
300/* Find the next usable session. */
301struct session *
302session_next_session(struct session *s)
303{
304	struct session *s2;
305
306	if (RB_EMPTY(&sessions) || !session_alive(s))
307		return (NULL);
308
309	s2 = RB_NEXT(sessions, &sessions, s);
310	if (s2 == NULL)
311		s2 = RB_MIN(sessions, &sessions);
312	if (s2 == s)
313		return (NULL);
314	return (s2);
315}
316
317/* Find the previous usable session. */
318struct session *
319session_previous_session(struct session *s)
320{
321	struct session *s2;
322
323	if (RB_EMPTY(&sessions) || !session_alive(s))
324		return (NULL);
325
326	s2 = RB_PREV(sessions, &sessions, s);
327	if (s2 == NULL)
328		s2 = RB_MAX(sessions, &sessions);
329	if (s2 == s)
330		return (NULL);
331	return (s2);
332}
333
334/* Attach a window to a session. */
335struct winlink *
336session_attach(struct session *s, struct window *w, int idx, char **cause)
337{
338	struct winlink	*wl;
339
340	if ((wl = winlink_add(&s->windows, idx)) == NULL) {
341		xasprintf(cause, "index in use: %d", idx);
342		return (NULL);
343	}
344	wl->session = s;
345	winlink_set_window(wl, w);
346	notify_session_window("window-linked", s, w);
347
348	session_group_synchronize_from(s);
349	return (wl);
350}
351
352/* Detach a window from a session. */
353int
354session_detach(struct session *s, struct winlink *wl)
355{
356	if (s->curw == wl &&
357	    session_last(s) != 0 &&
358	    session_previous(s, 0) != 0)
359		session_next(s, 0);
360
361	wl->flags &= ~WINLINK_ALERTFLAGS;
362	notify_session_window("window-unlinked", s, wl->window);
363	winlink_stack_remove(&s->lastw, wl);
364	winlink_remove(&s->windows, wl);
365
366	session_group_synchronize_from(s);
367
368	if (RB_EMPTY(&s->windows))
369		return (1);
370       	return (0);
371}
372
373/* Return if session has window. */
374int
375session_has(struct session *s, struct window *w)
376{
377	struct winlink	*wl;
378
379	TAILQ_FOREACH(wl, &w->winlinks, wentry) {
380		if (wl->session == s)
381			return (1);
382	}
383	return (0);
384}
385
386/*
387 * Return 1 if a window is linked outside this session (not including session
388 * groups). The window must be in this session!
389 */
390int
391session_is_linked(struct session *s, struct window *w)
392{
393	struct session_group	*sg;
394
395	if ((sg = session_group_contains(s)) != NULL)
396		return (w->references != session_group_count(sg));
397	return (w->references != 1);
398}
399
400static struct winlink *
401session_next_alert(struct winlink *wl)
402{
403	while (wl != NULL) {
404		if (wl->flags & WINLINK_ALERTFLAGS)
405			break;
406		wl = winlink_next(wl);
407	}
408	return (wl);
409}
410
411/* Move session to next window. */
412int
413session_next(struct session *s, int alert)
414{
415	struct winlink	*wl;
416
417	if (s->curw == NULL)
418		return (-1);
419
420	wl = winlink_next(s->curw);
421	if (alert)
422		wl = session_next_alert(wl);
423	if (wl == NULL) {
424		wl = RB_MIN(winlinks, &s->windows);
425		if (alert && ((wl = session_next_alert(wl)) == NULL))
426			return (-1);
427	}
428	return (session_set_current(s, wl));
429}
430
431static struct winlink *
432session_previous_alert(struct winlink *wl)
433{
434	while (wl != NULL) {
435		if (wl->flags & WINLINK_ALERTFLAGS)
436			break;
437		wl = winlink_previous(wl);
438	}
439	return (wl);
440}
441
442/* Move session to previous window. */
443int
444session_previous(struct session *s, int alert)
445{
446	struct winlink	*wl;
447
448	if (s->curw == NULL)
449		return (-1);
450
451	wl = winlink_previous(s->curw);
452	if (alert)
453		wl = session_previous_alert(wl);
454	if (wl == NULL) {
455		wl = RB_MAX(winlinks, &s->windows);
456		if (alert && (wl = session_previous_alert(wl)) == NULL)
457			return (-1);
458	}
459	return (session_set_current(s, wl));
460}
461
462/* Move session to specific window. */
463int
464session_select(struct session *s, int idx)
465{
466	struct winlink	*wl;
467
468	wl = winlink_find_by_index(&s->windows, idx);
469	return (session_set_current(s, wl));
470}
471
472/* Move session to last used window. */
473int
474session_last(struct session *s)
475{
476	struct winlink	*wl;
477
478	wl = TAILQ_FIRST(&s->lastw);
479	if (wl == NULL)
480		return (-1);
481	if (wl == s->curw)
482		return (1);
483
484	return (session_set_current(s, wl));
485}
486
487/* Set current winlink to wl .*/
488int
489session_set_current(struct session *s, struct winlink *wl)
490{
491	struct winlink	*old = s->curw;
492
493	if (wl == NULL)
494		return (-1);
495	if (wl == s->curw)
496		return (1);
497
498	winlink_stack_remove(&s->lastw, wl);
499	winlink_stack_push(&s->lastw, s->curw);
500	s->curw = wl;
501	if (options_get_number(global_options, "focus-events")) {
502		if (old != NULL)
503			window_update_focus(old->window);
504		window_update_focus(wl->window);
505	}
506	winlink_clear_flags(wl);
507	window_update_activity(wl->window);
508	tty_update_window_offset(wl->window);
509	notify_session("session-window-changed", s);
510	return (0);
511}
512
513/* Find the session group containing a session. */
514struct session_group *
515session_group_contains(struct session *target)
516{
517	struct session_group	*sg;
518	struct session		*s;
519
520	RB_FOREACH(sg, session_groups, &session_groups) {
521		TAILQ_FOREACH(s, &sg->sessions, gentry) {
522			if (s == target)
523				return (sg);
524		}
525	}
526	return (NULL);
527}
528
529/* Find session group by name. */
530struct session_group *
531session_group_find(const char *name)
532{
533	struct session_group	sg;
534
535	sg.name = name;
536	return (RB_FIND(session_groups, &session_groups, &sg));
537}
538
539/* Create a new session group. */
540struct session_group *
541session_group_new(const char *name)
542{
543	struct session_group	*sg;
544
545	if ((sg = session_group_find(name)) != NULL)
546		return (sg);
547
548	sg = xcalloc(1, sizeof *sg);
549	sg->name = xstrdup(name);
550	TAILQ_INIT(&sg->sessions);
551
552	RB_INSERT(session_groups, &session_groups, sg);
553	return (sg);
554}
555
556/* Add a session to a session group. */
557void
558session_group_add(struct session_group *sg, struct session *s)
559{
560	if (session_group_contains(s) == NULL)
561		TAILQ_INSERT_TAIL(&sg->sessions, s, gentry);
562}
563
564/* Remove a session from its group and destroy the group if empty. */
565static void
566session_group_remove(struct session *s)
567{
568	struct session_group	*sg;
569
570	if ((sg = session_group_contains(s)) == NULL)
571		return;
572	TAILQ_REMOVE(&sg->sessions, s, gentry);
573	if (TAILQ_EMPTY(&sg->sessions)) {
574		RB_REMOVE(session_groups, &session_groups, sg);
575		free(__UNCONST(sg->name));
576		free(sg);
577	}
578}
579
580/* Count number of sessions in session group. */
581u_int
582session_group_count(struct session_group *sg)
583{
584	struct session	*s;
585	u_int		 n;
586
587	n = 0;
588	TAILQ_FOREACH(s, &sg->sessions, gentry)
589		n++;
590	return (n);
591}
592
593/* Count number of clients attached to sessions in session group. */
594u_int
595session_group_attached_count(struct session_group *sg)
596{
597	struct session	*s;
598	u_int		 n;
599
600	n = 0;
601	TAILQ_FOREACH(s, &sg->sessions, gentry)
602		n += s->attached;
603	return (n);
604}
605
606/* Synchronize a session to its session group. */
607void
608session_group_synchronize_to(struct session *s)
609{
610	struct session_group	*sg;
611	struct session		*target;
612
613	if ((sg = session_group_contains(s)) == NULL)
614		return;
615
616	target = NULL;
617	TAILQ_FOREACH(target, &sg->sessions, gentry) {
618		if (target != s)
619			break;
620	}
621	if (target != NULL)
622		session_group_synchronize1(target, s);
623}
624
625/* Synchronize a session group to a session. */
626void
627session_group_synchronize_from(struct session *target)
628{
629	struct session_group	*sg;
630	struct session		*s;
631
632	if ((sg = session_group_contains(target)) == NULL)
633		return;
634
635	TAILQ_FOREACH(s, &sg->sessions, gentry) {
636		if (s != target)
637			session_group_synchronize1(target, s);
638	}
639}
640
641/*
642 * Synchronize a session with a target session. This means destroying all
643 * winlinks then recreating them, then updating the current window, last window
644 * stack and alerts.
645 */
646static void
647session_group_synchronize1(struct session *target, struct session *s)
648{
649	struct winlinks		 old_windows, *ww;
650	struct winlink_stack	 old_lastw;
651	struct winlink		*wl, *wl2;
652
653	/* Don't do anything if the session is empty (it'll be destroyed). */
654	ww = &target->windows;
655	if (RB_EMPTY(ww))
656		return;
657
658	/* If the current window has vanished, move to the next now. */
659	if (s->curw != NULL &&
660	    winlink_find_by_index(ww, s->curw->idx) == NULL &&
661	    session_last(s) != 0 && session_previous(s, 0) != 0)
662		session_next(s, 0);
663
664	/* Save the old pointer and reset it. */
665	memcpy(&old_windows, &s->windows, sizeof old_windows);
666	RB_INIT(&s->windows);
667
668	/* Link all the windows from the target. */
669	RB_FOREACH(wl, winlinks, ww) {
670		wl2 = winlink_add(&s->windows, wl->idx);
671		wl2->session = s;
672		winlink_set_window(wl2, wl->window);
673		notify_session_window("window-linked", s, wl2->window);
674		wl2->flags |= wl->flags & WINLINK_ALERTFLAGS;
675	}
676
677	/* Fix up the current window. */
678	if (s->curw != NULL)
679		s->curw = winlink_find_by_index(&s->windows, s->curw->idx);
680	else
681		s->curw = winlink_find_by_index(&s->windows, target->curw->idx);
682
683	/* Fix up the last window stack. */
684	memcpy(&old_lastw, &s->lastw, sizeof old_lastw);
685	TAILQ_INIT(&s->lastw);
686	TAILQ_FOREACH(wl, &old_lastw, sentry) {
687		wl2 = winlink_find_by_index(&s->windows, wl->idx);
688		if (wl2 != NULL) {
689			TAILQ_INSERT_TAIL(&s->lastw, wl2, sentry);
690			wl2->flags |= WINLINK_VISITED;
691		}
692	}
693
694	/* Then free the old winlinks list. */
695	while (!RB_EMPTY(&old_windows)) {
696		wl = RB_ROOT(&old_windows);
697		wl2 = winlink_find_by_window_id(&s->windows, wl->window->id);
698		if (wl2 == NULL)
699			notify_session_window("window-unlinked", s, wl->window);
700		winlink_remove(&old_windows, wl);
701	}
702}
703
704/* Renumber the windows across winlinks attached to a specific session. */
705void
706session_renumber_windows(struct session *s)
707{
708	struct winlink		*wl, *wl1, *wl_new;
709	struct winlinks		 old_wins;
710	struct winlink_stack	 old_lastw;
711	int			 new_idx, new_curw_idx, marked_idx = -1;
712
713	/* Save and replace old window list. */
714	memcpy(&old_wins, &s->windows, sizeof old_wins);
715	RB_INIT(&s->windows);
716
717	/* Start renumbering from the base-index if it's set. */
718	new_idx = options_get_number(s->options, "base-index");
719	new_curw_idx = 0;
720
721	/* Go through the winlinks and assign new indexes. */
722	RB_FOREACH(wl, winlinks, &old_wins) {
723		wl_new = winlink_add(&s->windows, new_idx);
724		wl_new->session = s;
725		winlink_set_window(wl_new, wl->window);
726		wl_new->flags |= wl->flags & WINLINK_ALERTFLAGS;
727
728		if (wl == marked_pane.wl)
729			marked_idx = wl_new->idx;
730		if (wl == s->curw)
731			new_curw_idx = wl_new->idx;
732
733		new_idx++;
734	}
735
736	/* Fix the stack of last windows now. */
737	memcpy(&old_lastw, &s->lastw, sizeof old_lastw);
738	TAILQ_INIT(&s->lastw);
739	TAILQ_FOREACH(wl, &old_lastw, sentry) {
740		wl->flags &= ~WINLINK_VISITED;
741		wl_new = winlink_find_by_window(&s->windows, wl->window);
742		if (wl_new != NULL) {
743			TAILQ_INSERT_TAIL(&s->lastw, wl_new, sentry);
744			wl_new->flags |= WINLINK_VISITED;
745		}
746	}
747
748	/* Set the current window. */
749	if (marked_idx != -1) {
750		marked_pane.wl = winlink_find_by_index(&s->windows, marked_idx);
751		if (marked_pane.wl == NULL)
752			server_clear_marked();
753	}
754	s->curw = winlink_find_by_index(&s->windows, new_curw_idx);
755
756	/* Free the old winlinks (reducing window references too). */
757	RB_FOREACH_SAFE(wl, winlinks, &old_wins, wl1)
758		winlink_remove(&old_wins, wl);
759}
760