xref: /openbsd-src/usr.bin/tmux/server.c (revision 7bbe964f6b7d22ad07ca46292495604f942eba4e)
1 /* $OpenBSD: server.c,v 1.63 2009/10/27 13:03:33 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
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/socket.h>
22 #include <sys/stat.h>
23 #include <sys/un.h>
24 #include <sys/wait.h>
25 
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <paths.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <termios.h>
35 #include <time.h>
36 #include <unistd.h>
37 
38 #include "tmux.h"
39 
40 /*
41  * Main server functions.
42  */
43 
44 /* Client list. */
45 struct clients	 clients;
46 struct clients	 dead_clients;
47 
48 /* Mapping of a pollfd to an fd independent of its position in the array. */
49 struct poll_item {
50 	int	 fd;
51 	int	 events;
52 
53 	void	 (*fn)(int, int, void *);
54 	void	*data;
55 
56 	RB_ENTRY(poll_item) entry;
57 };
58 RB_HEAD(poll_items, poll_item) poll_items;
59 
60 int		 server_poll_cmp(struct poll_item *, struct poll_item *);
61 struct poll_item*server_poll_lookup(int);
62 struct pollfd	*server_poll_flatten(int *);
63 void		 server_poll_dispatch(struct pollfd *, int);
64 void		 server_poll_reset(void);
65 RB_PROTOTYPE(poll_items, poll_item, entry, server_poll_cmp);
66 RB_GENERATE(poll_items, poll_item, entry, server_poll_cmp);
67 
68 int		 server_create_socket(void);
69 void		 server_callback(int, int, void *);
70 int		 server_main(int);
71 void		 server_shutdown(void);
72 int		 server_should_shutdown(void);
73 void		 server_child_signal(void);
74 void		 server_clean_dead(void);
75 void		 server_second_timers(void);
76 void		 server_lock_server(void);
77 void		 server_lock_sessions(void);
78 int		 server_update_socket(void);
79 
80 int
81 server_poll_cmp(struct poll_item *pitem1, struct poll_item *pitem2)
82 {
83 	return (pitem1->fd - pitem2->fd);
84 }
85 
86 void
87 server_poll_add(int fd, int events, void (*fn)(int, int, void *), void *data)
88 {
89 	struct poll_item	*pitem;
90 
91 	pitem = xmalloc(sizeof *pitem);
92 	pitem->fd = fd;
93 	pitem->events = events;
94 
95 	pitem->fn = fn;
96 	pitem->data = data;
97 
98 	RB_INSERT(poll_items, &poll_items, pitem);
99 }
100 
101 struct poll_item *
102 server_poll_lookup(int fd)
103 {
104 	struct poll_item	pitem;
105 
106 	pitem.fd = fd;
107 	return (RB_FIND(poll_items, &poll_items, &pitem));
108 }
109 
110 struct pollfd *
111 server_poll_flatten(int *nfds)
112 {
113 	struct poll_item	*pitem;
114 	struct pollfd		*pfds;
115 
116 	pfds = NULL;
117 	*nfds = 0;
118 	RB_FOREACH(pitem, poll_items, &poll_items) {
119 		pfds = xrealloc(pfds, (*nfds) + 1, sizeof *pfds);
120 		pfds[*nfds].fd = pitem->fd;
121 		pfds[*nfds].events = pitem->events;
122 		(*nfds)++;
123 	}
124 	return (pfds);
125 }
126 
127 void
128 server_poll_dispatch(struct pollfd *pfds, int nfds)
129 {
130 	struct poll_item	*pitem;
131 	struct pollfd		*pfd;
132 
133 	while (nfds > 0) {
134 		pfd = &pfds[--nfds];
135 		if (pfd->revents != 0) {
136 			pitem = server_poll_lookup(pfd->fd);
137 			pitem->fn(pitem->fd, pfd->revents, pitem->data);
138 		}
139 	}
140 	xfree(pfds);
141 }
142 
143 void
144 server_poll_reset(void)
145 {
146 	struct poll_item	*pitem;
147 
148 	while (!RB_EMPTY(&poll_items)) {
149 		pitem = RB_ROOT(&poll_items);
150 		RB_REMOVE(poll_items, &poll_items, pitem);
151 		xfree(pitem);
152 	}
153 }
154 
155 /* Create server socket. */
156 int
157 server_create_socket(void)
158 {
159 	struct sockaddr_un	sa;
160 	size_t			size;
161 	mode_t			mask;
162 	int			fd, mode;
163 
164 	memset(&sa, 0, sizeof sa);
165 	sa.sun_family = AF_UNIX;
166 	size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path);
167 	if (size >= sizeof sa.sun_path) {
168 		errno = ENAMETOOLONG;
169 		fatal("socket failed");
170 	}
171 	unlink(sa.sun_path);
172 
173 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
174 		fatal("socket failed");
175 
176 	mask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
177 	if (bind(fd, (struct sockaddr *) &sa, SUN_LEN(&sa)) == -1)
178 		fatal("bind failed");
179 	umask(mask);
180 
181 	if (listen(fd, 16) == -1)
182 		fatal("listen failed");
183 
184 	if ((mode = fcntl(fd, F_GETFL)) == -1)
185 		fatal("fcntl failed");
186 	if (fcntl(fd, F_SETFL, mode|O_NONBLOCK) == -1)
187 		fatal("fcntl failed");
188 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
189 		fatal("fcntl failed");
190 
191 	return (fd);
192 }
193 
194 /* Callback for server socket. */
195 void
196 server_callback(int fd, int events, unused void *data)
197 {
198 	struct sockaddr_storage	sa;
199 	socklen_t		slen = sizeof sa;
200 	int			newfd;
201 
202 	if (events & (POLLERR|POLLNVAL|POLLHUP))
203 		fatalx("lost server socket");
204 	if (!(events & POLLIN))
205 		return;
206 
207 	newfd = accept(fd, (struct sockaddr *) &sa, &slen);
208 	if (newfd == -1) {
209 		if (errno == EAGAIN || errno == EINTR || errno == ECONNABORTED)
210 			return;
211 		fatal("accept failed");
212 	}
213 	if (sigterm) {
214 		close(newfd);
215 		return;
216 	}
217 	server_client_create(newfd);
218 }
219 
220 /* Fork new server. */
221 int
222 server_start(char *path)
223 {
224 	struct client	*c;
225 	int		 pair[2], srv_fd;
226 	char		*cause;
227 	char		 rpathbuf[MAXPATHLEN];
228 
229 	/* The first client is special and gets a socketpair; create it. */
230 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
231 		fatal("socketpair failed");
232 
233 	switch (fork()) {
234 	case -1:
235 		fatal("fork failed");
236 	case 0:
237 		break;
238 	default:
239 		close(pair[1]);
240 		return (pair[0]);
241 	}
242 	close(pair[0]);
243 
244 	/*
245 	 * Must daemonise before loading configuration as the PID changes so
246 	 * $TMUX would be wrong for sessions created in the config file.
247 	 */
248 	if (daemon(1, 0) != 0)
249 		fatal("daemon failed");
250 
251 	logfile("server");
252 	log_debug("server started, pid %ld", (long) getpid());
253 
254 	ARRAY_INIT(&windows);
255 	ARRAY_INIT(&clients);
256 	ARRAY_INIT(&dead_clients);
257 	ARRAY_INIT(&sessions);
258 	ARRAY_INIT(&dead_sessions);
259 	TAILQ_INIT(&session_groups);
260 	mode_key_init_trees();
261 	key_bindings_init();
262 	utf8_build();
263 
264 	start_time = time(NULL);
265 	socket_path = path;
266 
267 	if (realpath(socket_path, rpathbuf) == NULL)
268 		strlcpy(rpathbuf, socket_path, sizeof rpathbuf);
269 	log_debug("socket path %s", socket_path);
270 	setproctitle("server (%s)", rpathbuf);
271 
272 	srv_fd = server_create_socket();
273 	server_client_create(pair[1]);
274 
275 	if (access(SYSTEM_CFG, R_OK) != 0) {
276 		if (errno != ENOENT) {
277 			xasprintf(
278 			    &cause, "%s: %s", strerror(errno), SYSTEM_CFG);
279 			goto error;
280 		}
281 	} else if (load_cfg(SYSTEM_CFG, NULL, &cause) != 0)
282 		goto error;
283 	if (cfg_file != NULL && load_cfg(cfg_file, NULL, &cause) != 0)
284 		goto error;
285 
286 	exit(server_main(srv_fd));
287 
288 error:
289 	/* Write the error and shutdown the server. */
290 	c = ARRAY_FIRST(&clients);
291 
292 	server_write_error(c, cause);
293 	xfree(cause);
294 
295 	sigterm = 1;
296 	server_shutdown();
297 
298 	exit(server_main(srv_fd));
299 }
300 
301 /* Main server loop. */
302 int
303 server_main(int srv_fd)
304 {
305 	struct pollfd	*pfds;
306 	int		 nfds, xtimeout;
307 	u_int		 i;
308 	time_t		 now, last;
309 
310 	siginit();
311 	log_debug("server socket is %d", srv_fd);
312 
313 	last = time(NULL);
314 
315 	pfds = NULL;
316 	for (;;) {
317 		/* If sigterm, kill all windows and clients. */
318 		if (sigterm)
319 			server_shutdown();
320 
321 		/* Stop if no sessions or clients left. */
322 		if (server_should_shutdown())
323 			break;
324 
325 		/* Handle child exit. */
326 		if (sigchld) {
327 			sigchld = 0;
328 			server_child_signal();
329 			continue;
330 		}
331 
332 		/* Recreate socket on SIGUSR1. */
333 		if (sigusr1) {
334 			sigusr1 = 0;
335 			close(srv_fd);
336 			srv_fd = server_create_socket();
337 			continue;
338 		}
339 
340 		/* Initialise pollfd array and add server socket. */
341 		server_poll_reset();
342 		server_poll_add(srv_fd, POLLIN, server_callback, NULL);
343 
344 		/* Fill window and client sockets. */
345 		server_job_prepare();
346 		server_window_prepare();
347 		server_client_prepare();
348 
349 		/* Update socket permissions. */
350 		xtimeout = INFTIM;
351 		if (server_update_socket() != 0)
352 			xtimeout = POLL_TIMEOUT;
353 
354 		/* Do the poll. */
355 		pfds = server_poll_flatten(&nfds);
356 		if (poll(pfds, nfds, xtimeout) == -1) {
357 			if (errno == EAGAIN || errno == EINTR)
358 				continue;
359 			fatal("poll failed");
360 		}
361 		server_poll_dispatch(pfds, nfds);
362 
363 		/* Call second-based timers. */
364 		now = time(NULL);
365 		if (now != last) {
366 			last = now;
367 			server_second_timers();
368 		}
369 
370 		/* Run once-per-loop events. */
371 		server_job_loop();
372 		server_window_loop();
373 		server_client_loop();
374 
375 		/* Collect any unset key bindings. */
376 		key_bindings_clean();
377 
378 		/* Collect dead clients and sessions. */
379 		server_clean_dead();
380 	}
381 	server_poll_reset();
382 
383 	for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
384 		if (ARRAY_ITEM(&sessions, i) != NULL)
385 			session_destroy(ARRAY_ITEM(&sessions, i));
386 	}
387 	ARRAY_FREE(&sessions);
388 
389 	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
390 		if (ARRAY_ITEM(&clients, i) != NULL)
391 			server_client_lost(ARRAY_ITEM(&clients, i));
392 	}
393 	ARRAY_FREE(&clients);
394 
395 	mode_key_free_trees();
396 	key_bindings_free();
397 
398 	close(srv_fd);
399 
400 	unlink(socket_path);
401 	xfree(socket_path);
402 
403 	options_free(&global_s_options);
404 	options_free(&global_w_options);
405 
406 	return (0);
407 }
408 
409 /* Kill all clients. */
410 void
411 server_shutdown(void)
412 {
413 	struct session	*s;
414 	struct client	*c;
415 	u_int		 i, j;
416 
417 	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
418 		c = ARRAY_ITEM(&clients, i);
419 		if (c != NULL) {
420 			if (c->flags & (CLIENT_BAD|CLIENT_SUSPENDED))
421 				server_client_lost(c);
422 			else
423 				server_write_client(c, MSG_SHUTDOWN, NULL, 0);
424 		}
425 	}
426 
427 	for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
428 		s = ARRAY_ITEM(&sessions, i);
429 		for (j = 0; j < ARRAY_LENGTH(&clients); j++) {
430 			c = ARRAY_ITEM(&clients, j);
431 			if (c != NULL && c->session == s) {
432 				s = NULL;
433 				break;
434 			}
435 		}
436 		if (s != NULL)
437 			session_destroy(s);
438 	}
439 }
440 
441 /* Check if the server should be shutting down (no more clients or windows). */
442 int
443 server_should_shutdown(void)
444 {
445 	u_int	i;
446 
447 	for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
448 		if (ARRAY_ITEM(&sessions, i) != NULL)
449 			return (0);
450 	}
451 	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
452 		if (ARRAY_ITEM(&clients, i) != NULL)
453 			return (0);
454 	}
455 	return (1);
456 }
457 
458 /* Handle SIGCHLD. */
459 void
460 server_child_signal(void)
461 {
462 	struct window		*w;
463 	struct window_pane	*wp;
464 	struct job		*job;
465 	int		 	 status;
466 	pid_t		 	 pid;
467 	u_int		 	 i;
468 
469 	for (;;) {
470 		switch (pid = waitpid(WAIT_ANY, &status, WNOHANG|WUNTRACED)) {
471 		case -1:
472 			if (errno == ECHILD)
473 				return;
474 			fatal("waitpid failed");
475 		case 0:
476 			return;
477 		}
478 		if (!WIFSTOPPED(status)) {
479 			SLIST_FOREACH(job, &all_jobs, lentry) {
480 				if (pid == job->pid) {
481 					job->pid = -1;
482 					job->status = status;
483 				}
484 			}
485 			continue;
486 		}
487 		if (WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU)
488 			continue;
489 
490 		for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
491 			w = ARRAY_ITEM(&windows, i);
492 			if (w == NULL)
493 				continue;
494 			TAILQ_FOREACH(wp, &w->panes, entry) {
495 				if (wp->pid == pid) {
496 					if (killpg(pid, SIGCONT) != 0)
497 						kill(pid, SIGCONT);
498 				}
499 			}
500 		}
501 	}
502 }
503 
504 /* Free dead, unreferenced clients and sessions. */
505 void
506 server_clean_dead(void)
507 {
508 	struct session	*s;
509 	struct client	*c;
510 	u_int		 i;
511 
512 	for (i = 0; i < ARRAY_LENGTH(&dead_sessions); i++) {
513 		s = ARRAY_ITEM(&dead_sessions, i);
514 		if (s == NULL || s->references != 0)
515 			continue;
516 		ARRAY_SET(&dead_sessions, i, NULL);
517 		xfree(s);
518 	}
519 
520 	for (i = 0; i < ARRAY_LENGTH(&dead_clients); i++) {
521 		c = ARRAY_ITEM(&dead_clients, i);
522 		if (c == NULL || c->references != 0)
523 			continue;
524 		ARRAY_SET(&dead_clients, i, NULL);
525 		xfree(c);
526 	}
527 }
528 
529 /* Call any once-per-second timers. */
530 void
531 server_second_timers(void)
532 {
533 	struct window		*w;
534 	struct window_pane	*wp;
535 	u_int		 	 i;
536 
537 	if (options_get_number(&global_s_options, "lock-server"))
538 		server_lock_server();
539 	else
540 		server_lock_sessions();
541 
542 	for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
543 		w = ARRAY_ITEM(&windows, i);
544 		if (w == NULL)
545 			continue;
546 
547 		TAILQ_FOREACH(wp, &w->panes, entry) {
548 			if (wp->mode != NULL && wp->mode->timer != NULL)
549 				wp->mode->timer(wp);
550 		}
551 	}
552 }
553 
554 /* Lock the server if ALL sessions have hit the time limit. */
555 void
556 server_lock_server(void)
557 {
558 	struct session  *s;
559 	u_int            i;
560 	int		 timeout;
561 	time_t           t;
562 
563 	t = time(NULL);
564 	for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
565 		if ((s = ARRAY_ITEM(&sessions, i)) == NULL)
566 			continue;
567 
568 		if (s->flags & SESSION_UNATTACHED) {
569 			s->activity = time(NULL);
570 			continue;
571 		}
572 
573 		timeout = options_get_number(&s->options, "lock-after-time");
574 		if (timeout <= 0 || t <= s->activity + timeout)
575 			return;	/* not timed out */
576 	}
577 
578 	server_lock();
579 	recalculate_sizes();
580 }
581 
582 /* Lock any sessions which have timed out. */
583 void
584 server_lock_sessions(void)
585 {
586         struct session  *s;
587 	u_int		 i;
588 	int		 timeout;
589 	time_t		 t;
590 
591 	t = time(NULL);
592 	for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
593 		if ((s = ARRAY_ITEM(&sessions, i)) == NULL)
594 			continue;
595 
596 		if (s->flags & SESSION_UNATTACHED) {
597 			s->activity = time(NULL);
598 			continue;
599 		}
600 
601 		timeout = options_get_number(&s->options, "lock-after-time");
602 		if (timeout > 0 && t > s->activity + timeout) {
603 			server_lock_session(s);
604 			recalculate_sizes();
605 		}
606 	}
607 }
608 
609 /* Update socket execute permissions based on whether sessions are attached. */
610 int
611 server_update_socket(void)
612 {
613 	struct session	*s;
614 	u_int		 i;
615 	static int	 last = -1;
616 	int		 n;
617 
618 	n = 0;
619 	for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
620 		s = ARRAY_ITEM(&sessions, i);
621 		if (s != NULL && !(s->flags & SESSION_UNATTACHED)) {
622 			n++;
623 			break;
624 		}
625 	}
626 
627 	if (n != last) {
628 		last = n;
629 		if (n != 0)
630 			chmod(socket_path, S_IRWXU);
631 		else
632 			chmod(socket_path, S_IRUSR|S_IWUSR);
633 	}
634 
635 	return (n);
636 }
637