xref: /netbsd-src/external/bsd/tmux/dist/server.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /* $Id: server.c,v 1.1.1.1 2011/03/10 09:15:39 jmmv 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 <event.h>
28 #include <fcntl.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 int		 server_fd;
49 int		 server_shutdown;
50 struct event	 server_ev_accept;
51 struct event	 server_ev_second;
52 
53 int		 server_create_socket(void);
54 void		 server_loop(void);
55 int		 server_should_shutdown(void);
56 void		 server_send_shutdown(void);
57 void		 server_clean_dead(void);
58 void		 server_accept_callback(int, short, void *);
59 void		 server_signal_callback(int, short, void *);
60 void		 server_child_signal(void);
61 void		 server_child_exited(pid_t, int);
62 void		 server_child_stopped(pid_t, int);
63 void		 server_second_callback(int, short, void *);
64 void		 server_lock_server(void);
65 void		 server_lock_sessions(void);
66 
67 /* Create server socket. */
68 int
69 server_create_socket(void)
70 {
71 	struct sockaddr_un	sa;
72 	size_t			size;
73 	mode_t			mask;
74 	int			fd, mode;
75 
76 	memset(&sa, 0, sizeof sa);
77 	sa.sun_family = AF_UNIX;
78 	size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path);
79 	if (size >= sizeof sa.sun_path) {
80 		errno = ENAMETOOLONG;
81 		fatal("socket failed");
82 	}
83 	unlink(sa.sun_path);
84 
85 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
86 		fatal("socket failed");
87 
88 	mask = umask(S_IXUSR|S_IXGRP|S_IRWXO);
89 	if (bind(fd, (struct sockaddr *) &sa, SUN_LEN(&sa)) == -1)
90 		fatal("bind failed");
91 	umask(mask);
92 
93 	if (listen(fd, 16) == -1)
94 		fatal("listen failed");
95 
96 	if ((mode = fcntl(fd, F_GETFL)) == -1)
97 		fatal("fcntl failed");
98 	if (fcntl(fd, F_SETFL, mode|O_NONBLOCK) == -1)
99 		fatal("fcntl failed");
100 
101 	server_update_socket();
102 
103 	return (fd);
104 }
105 
106 /* Fork new server. */
107 int
108 server_start(void)
109 {
110 	struct window_pane	*wp;
111 	int	 		 pair[2];
112 	char			*cause;
113 	struct timeval		 tv;
114 	u_int			 i;
115 
116 	/* The first client is special and gets a socketpair; create it. */
117 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
118 		fatal("socketpair failed");
119 
120 	switch (fork()) {
121 	case -1:
122 		fatal("fork failed");
123 	case 0:
124 		break;
125 	default:
126 		close(pair[1]);
127 		return (pair[0]);
128 	}
129 	close(pair[0]);
130 
131 	/*
132 	 * Must daemonise before loading configuration as the PID changes so
133 	 * $TMUX would be wrong for sessions created in the config file.
134 	 */
135 	if (daemon(1, 0) != 0)
136 		fatal("daemon failed");
137 
138 	/* event_init() was called in our parent, need to reinit. */
139 	if (event_reinit(ev_base) != 0)
140 		fatal("event_reinit failed");
141 	clear_signals(0);
142 
143 	logfile("server");
144 	log_debug("server started, pid %ld", (long) getpid());
145 
146 	ARRAY_INIT(&windows);
147 	ARRAY_INIT(&clients);
148 	ARRAY_INIT(&dead_clients);
149 	RB_INIT(&sessions);
150 	RB_INIT(&dead_sessions);
151 	TAILQ_INIT(&session_groups);
152 	mode_key_init_trees();
153 	key_bindings_init();
154 	utf8_build();
155 
156 	start_time = time(NULL);
157 	log_debug("socket path %s", socket_path);
158 #ifdef HAVE_SETPROCTITLE
159 	setproctitle("server (%s)", socket_path);
160 #endif
161 
162 	server_fd = server_create_socket();
163 	server_client_create(pair[1]);
164 
165 	if (access(SYSTEM_CFG, R_OK) == 0)
166 		load_cfg(SYSTEM_CFG, NULL, &cfg_causes);
167 	else if (errno != ENOENT) {
168 		cfg_add_cause(
169 		    &cfg_causes, "%s: %s", strerror(errno), SYSTEM_CFG);
170 	}
171 	if (cfg_file != NULL)
172 		load_cfg(cfg_file, NULL, &cfg_causes);
173 
174 	/*
175 	 * If there is a session already, put the current window and pane into
176 	 * more mode.
177 	 */
178 	if (!RB_EMPTY(&sessions) && !ARRAY_EMPTY(&cfg_causes)) {
179 		wp = RB_MIN(sessions, &sessions)->curw->window->active;
180 		window_pane_set_mode(wp, &window_copy_mode);
181 		window_copy_init_for_output(wp);
182 		for (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {
183 			cause = ARRAY_ITEM(&cfg_causes, i);
184 			window_copy_add(wp, "%s", cause);
185 			xfree(cause);
186 		}
187 		ARRAY_FREE(&cfg_causes);
188 	}
189 	cfg_finished = 1;
190 
191 	event_set(&server_ev_accept,
192 	    server_fd, EV_READ|EV_PERSIST, server_accept_callback, NULL);
193 	event_add(&server_ev_accept, NULL);
194 
195 	memset(&tv, 0, sizeof tv);
196 	tv.tv_sec = 1;
197 	evtimer_set(&server_ev_second, server_second_callback, NULL);
198 	evtimer_add(&server_ev_second, &tv);
199 
200 	set_signals(server_signal_callback);
201 	server_loop();
202 	exit(0);
203 }
204 
205 /* Main server loop. */
206 void
207 server_loop(void)
208 {
209 	while (!server_should_shutdown()) {
210 		event_loop(EVLOOP_ONCE);
211 
212 		server_window_loop();
213 		server_client_loop();
214 
215 		key_bindings_clean();
216 		server_clean_dead();
217 	}
218 }
219 
220 /* Check if the server should be shutting down (no more clients or sessions). */
221 int
222 server_should_shutdown(void)
223 {
224 	u_int	i;
225 
226 	if (!options_get_number(&global_options, "exit-unattached")) {
227 		if (!RB_EMPTY(&sessions))
228 			return (0);
229 	}
230 	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
231 		if (ARRAY_ITEM(&clients, i) != NULL)
232 			return (0);
233 	}
234 	return (1);
235 }
236 
237 /* Shutdown the server by killing all clients and windows. */
238 void
239 server_send_shutdown(void)
240 {
241 	struct client	*c;
242 	struct session	*s, *next_s;
243 	u_int		 i;
244 
245 	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
246 		c = ARRAY_ITEM(&clients, i);
247 		if (c != NULL) {
248 			if (c->flags & (CLIENT_BAD|CLIENT_SUSPENDED))
249 				server_client_lost(c);
250 			else
251 				server_write_client(c, MSG_SHUTDOWN, NULL, 0);
252 			c->session = NULL;
253 		}
254 	}
255 
256 	s = RB_MIN(sessions, &sessions);
257 	while (s != NULL) {
258 		next_s = RB_NEXT(sessions, &sessions, s);
259 		session_destroy(s);
260 		s = next_s;
261 	}
262 }
263 
264 /* Free dead, unreferenced clients and sessions. */
265 void
266 server_clean_dead(void)
267 {
268 	struct session	*s, *next_s;
269 	struct client	*c;
270 	u_int		 i;
271 
272 	s = RB_MIN(sessions, &dead_sessions);
273 	while (s != NULL) {
274 		next_s = RB_NEXT(sessions, &dead_sessions, s);
275 		if (s->references == 0) {
276 			RB_REMOVE(sessions, &dead_sessions, s);
277 			xfree(s->name);
278 			xfree(s);
279 		}
280 		s = next_s;
281 	}
282 
283 	for (i = 0; i < ARRAY_LENGTH(&dead_clients); i++) {
284 		c = ARRAY_ITEM(&dead_clients, i);
285 		if (c == NULL || c->references != 0)
286 			continue;
287 		ARRAY_SET(&dead_clients, i, NULL);
288 		xfree(c);
289 	}
290 }
291 
292 /* Update socket execute permissions based on whether sessions are attached. */
293 void
294 server_update_socket(void)
295 {
296 	struct session	*s;
297 	static int	 last = -1;
298 	int		 n, mode;
299 	struct stat      sb;
300 
301 	n = 0;
302 	RB_FOREACH(s, sessions, &sessions) {
303 		if (!(s->flags & SESSION_UNATTACHED)) {
304 			n++;
305 			break;
306 		}
307 	}
308 
309 	if (n != last) {
310 		last = n;
311 
312 		if (stat(socket_path, &sb) != 0)
313 			return;
314 		mode = sb.st_mode;
315 		if (n != 0) {
316 			if (mode & S_IRUSR)
317 				mode |= S_IXUSR;
318 			if (mode & S_IRGRP)
319 				mode |= S_IXGRP;
320 			if (mode & S_IROTH)
321 				mode |= S_IXOTH;
322 		} else
323 			mode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
324 		chmod(socket_path, mode);
325 	}
326 }
327 
328 /* Callback for server socket. */
329 /* ARGSUSED */
330 void
331 server_accept_callback(int fd, short events, unused void *data)
332 {
333 	struct sockaddr_storage	sa;
334 	socklen_t		slen = sizeof sa;
335 	int			newfd;
336 
337 	if (!(events & EV_READ))
338 		return;
339 
340 	newfd = accept(fd, (struct sockaddr *) &sa, &slen);
341 	if (newfd == -1) {
342 		if (errno == EAGAIN || errno == EINTR || errno == ECONNABORTED)
343 			return;
344 		fatal("accept failed");
345 	}
346 	if (server_shutdown) {
347 		close(newfd);
348 		return;
349 	}
350 	server_client_create(newfd);
351 }
352 
353 /* Signal handler. */
354 /* ARGSUSED */
355 void
356 server_signal_callback(int sig, unused short events, unused void *data)
357 {
358 	switch (sig) {
359 	case SIGTERM:
360 		server_shutdown = 1;
361 		server_send_shutdown();
362 		break;
363 	case SIGCHLD:
364 		server_child_signal();
365 		break;
366 	case SIGUSR1:
367 		event_del(&server_ev_accept);
368 		close(server_fd);
369 		server_fd = server_create_socket();
370 		event_set(&server_ev_accept, server_fd,
371 		    EV_READ|EV_PERSIST, server_accept_callback, NULL);
372 		event_add(&server_ev_accept, NULL);
373 		break;
374 	}
375 }
376 
377 /* Handle SIGCHLD. */
378 void
379 server_child_signal(void)
380 {
381 	int	 status;
382 	pid_t	 pid;
383 
384 	for (;;) {
385 		switch (pid = waitpid(WAIT_ANY, &status, WNOHANG|WUNTRACED)) {
386 		case -1:
387 			if (errno == ECHILD)
388 				return;
389 			fatal("waitpid failed");
390 		case 0:
391 			return;
392 		}
393 		if (WIFSTOPPED(status))
394 			server_child_stopped(pid, status);
395 		else if (WIFEXITED(status) || WIFSIGNALED(status))
396 			server_child_exited(pid, status);
397 	}
398 }
399 
400 /* Handle exited children. */
401 void
402 server_child_exited(pid_t pid, int status)
403 {
404 	struct window		*w;
405 	struct window_pane	*wp;
406 	struct job		*job;
407 	u_int		 	 i;
408 
409 	for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
410 		if ((w = ARRAY_ITEM(&windows, i)) == NULL)
411 			continue;
412 		TAILQ_FOREACH(wp, &w->panes, entry) {
413 			if (wp->pid == pid) {
414 				server_destroy_pane(wp);
415 				break;
416 			}
417 		}
418 	}
419 
420 	SLIST_FOREACH(job, &all_jobs, lentry) {
421 		if (pid == job->pid) {
422 			job_died(job, status);	/* might free job */
423 			break;
424 		}
425 	}
426 }
427 
428 /* Handle stopped children. */
429 void
430 server_child_stopped(pid_t pid, int status)
431 {
432 	struct window		*w;
433 	struct window_pane	*wp;
434 	u_int			 i;
435 
436 	if (WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU)
437 		return;
438 
439 	for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
440 		if ((w = ARRAY_ITEM(&windows, i)) == NULL)
441 			continue;
442 		TAILQ_FOREACH(wp, &w->panes, entry) {
443 			if (wp->pid == pid) {
444 				if (killpg(pid, SIGCONT) != 0)
445 					kill(pid, SIGCONT);
446 			}
447 		}
448 	}
449 }
450 
451 /* Handle once-per-second timer events. */
452 /* ARGSUSED */
453 void
454 server_second_callback(unused int fd, unused short events, unused void *arg)
455 {
456 	struct window		*w;
457 	struct window_pane	*wp;
458 	struct timeval		 tv;
459 	u_int		 	 i;
460 
461 	if (options_get_number(&global_s_options, "lock-server"))
462 		server_lock_server();
463 	else
464 		server_lock_sessions();
465 
466 	for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
467 		w = ARRAY_ITEM(&windows, i);
468 		if (w == NULL)
469 			continue;
470 
471 		TAILQ_FOREACH(wp, &w->panes, entry) {
472 			if (wp->mode != NULL && wp->mode->timer != NULL)
473 				wp->mode->timer(wp);
474 		}
475 	}
476 
477 	server_client_status_timer();
478 
479 	evtimer_del(&server_ev_second);
480 	memset(&tv, 0, sizeof tv);
481 	tv.tv_sec = 1;
482 	evtimer_add(&server_ev_second, &tv);
483 }
484 
485 /* Lock the server if ALL sessions have hit the time limit. */
486 void
487 server_lock_server(void)
488 {
489 	struct session  *s;
490 	int		 timeout;
491 	time_t           t;
492 
493 	t = time(NULL);
494 	RB_FOREACH(s, sessions, &sessions) {
495 		if (s->flags & SESSION_UNATTACHED) {
496 			if (gettimeofday(&s->activity_time, NULL) != 0)
497 				fatal("gettimeofday failed");
498 			continue;
499 		}
500 
501 		timeout = options_get_number(&s->options, "lock-after-time");
502 		if (timeout <= 0 || t <= s->activity_time.tv_sec + timeout)
503 			return;	/* not timed out */
504 	}
505 
506 	server_lock();
507 	recalculate_sizes();
508 }
509 
510 /* Lock any sessions which have timed out. */
511 void
512 server_lock_sessions(void)
513 {
514 	struct session  *s;
515 	int		 timeout;
516 	time_t		 t;
517 
518 	t = time(NULL);
519 	RB_FOREACH(s, sessions, &sessions) {
520 		if (s->flags & SESSION_UNATTACHED) {
521 			if (gettimeofday(&s->activity_time, NULL) != 0)
522 				fatal("gettimeofday failed");
523 			continue;
524 		}
525 
526 		timeout = options_get_number(&s->options, "lock-after-time");
527 		if (timeout > 0 && t > s->activity_time.tv_sec + timeout) {
528 			server_lock_session(s);
529 			recalculate_sizes();
530 		}
531 	}
532 }
533