xref: /openbsd-src/usr.bin/tmux/server.c (revision 9b9d2a55a62c8e82206c25f94fcc7f4e2765250e)
1 /* $OpenBSD: server.c,v 1.138 2015/08/30 22:19:07 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 <event.h>
28 #include <fcntl.h>
29 #include <paths.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.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 struct clients	 clients;
45 
46 int		 server_fd;
47 int		 server_shutdown;
48 struct event	 server_ev_accept;
49 
50 struct session		*marked_session;
51 struct winlink		*marked_winlink;
52 struct window		*marked_window;
53 struct window_pane	*marked_window_pane;
54 struct layout_cell	*marked_layout_cell;
55 
56 int	server_create_socket(void);
57 void	server_loop(void);
58 int	server_should_shutdown(void);
59 void	server_send_shutdown(void);
60 void	server_accept_callback(int, short, void *);
61 void	server_signal_callback(int, short, void *);
62 void	server_child_signal(void);
63 void	server_child_exited(pid_t, int);
64 void	server_child_stopped(pid_t, int);
65 
66 /* Set marked pane. */
67 void
68 server_set_marked(struct session *s, struct winlink *wl, struct window_pane *wp)
69 {
70 	marked_session = s;
71 	marked_winlink = wl;
72 	marked_window = wl->window;
73 	marked_window_pane = wp;
74 	marked_layout_cell = wp->layout_cell;
75 }
76 
77 /* Clear marked pane. */
78 void
79 server_clear_marked(void)
80 {
81 	marked_session = NULL;
82 	marked_winlink = NULL;
83 	marked_window = NULL;
84 	marked_window_pane = NULL;
85 	marked_layout_cell = NULL;
86 }
87 
88 /* Is this the marked pane? */
89 int
90 server_is_marked(struct session *s, struct winlink *wl, struct window_pane *wp)
91 {
92 	if (s == NULL || wl == NULL || wp == NULL)
93 		return (0);
94 	if (marked_session != s || marked_winlink != wl)
95 		return (0);
96 	if (marked_window_pane != wp)
97 		return (0);
98 	return (server_check_marked());
99 }
100 
101 /* Check if the marked pane is still valid. */
102 int
103 server_check_marked(void)
104 {
105 	struct winlink	*wl;
106 
107 	if (marked_window_pane == NULL)
108 		return (0);
109 	if (marked_layout_cell != marked_window_pane->layout_cell)
110 		return (0);
111 
112 	if (!session_alive(marked_session))
113 		return (0);
114 	RB_FOREACH(wl, winlinks, &marked_session->windows) {
115 		if (wl->window == marked_window && wl == marked_winlink)
116 			break;
117 	}
118 	if (wl == NULL)
119 		return (0);
120 
121 	if (!window_has_pane(marked_window, marked_window_pane))
122 		return (0);
123 	return (window_pane_visible(marked_window_pane));
124 }
125 
126 /* Create server socket. */
127 int
128 server_create_socket(void)
129 {
130 	struct sockaddr_un	sa;
131 	size_t			size;
132 	mode_t			mask;
133 	int			fd;
134 
135 	memset(&sa, 0, sizeof sa);
136 	sa.sun_family = AF_UNIX;
137 	size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path);
138 	if (size >= sizeof sa.sun_path) {
139 		errno = ENAMETOOLONG;
140 		return (-1);
141 	}
142 	unlink(sa.sun_path);
143 
144 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
145 		return (-1);
146 
147 	mask = umask(S_IXUSR|S_IXGRP|S_IRWXO);
148 	if (bind(fd, (struct sockaddr *) &sa, SUN_LEN(&sa)) == -1)
149 		return (-1);
150 	umask(mask);
151 
152 	if (listen(fd, 16) == -1)
153 		return (-1);
154 	setblocking(fd, 0);
155 
156 	return (fd);
157 }
158 
159 /* Fork new server. */
160 int
161 server_start(struct event_base *base, int lockfd, char *lockfile)
162 {
163 	int	 pair[2];
164 	char	*cause;
165 
166 	/* The first client is special and gets a socketpair; create it. */
167 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
168 		fatal("socketpair failed");
169 	log_debug("starting server");
170 
171 	switch (fork()) {
172 	case -1:
173 		fatal("fork failed");
174 	case 0:
175 		break;
176 	default:
177 		close(pair[1]);
178 		return (pair[0]);
179 	}
180 	close(pair[0]);
181 
182 	/*
183 	 * Must daemonise before loading configuration as the PID changes so
184 	 * $TMUX would be wrong for sessions created in the config file.
185 	 */
186 	if (daemon(1, 0) != 0)
187 		fatal("daemon failed");
188 
189 	/* event_init() was called in our parent, need to reinit. */
190 	clear_signals(0);
191 	if (event_reinit(base) != 0)
192 		fatal("event_reinit failed");
193 
194 	logfile("server");
195 	log_debug("server started, pid %ld", (long) getpid());
196 
197 	RB_INIT(&windows);
198 	RB_INIT(&all_window_panes);
199 	TAILQ_INIT(&clients);
200 	RB_INIT(&sessions);
201 	TAILQ_INIT(&session_groups);
202 	mode_key_init_trees();
203 	key_bindings_init();
204 	utf8_build();
205 
206 	start_time = time(NULL);
207 	log_debug("socket path %s", socket_path);
208 	setproctitle("server (%s)", socket_path);
209 
210 	server_fd = server_create_socket();
211 	if (server_fd == -1)
212 		fatal("couldn't create socket");
213 	server_update_socket();
214 	server_client_create(pair[1]);
215 
216 	unlink(lockfile);
217 	free(lockfile);
218 	close(lockfd);
219 
220 	cfg_cmd_q = cmdq_new(NULL);
221 	cfg_cmd_q->emptyfn = cfg_default_done;
222 	cfg_finished = 0;
223 	cfg_references = 1;
224 	cfg_client = TAILQ_FIRST(&clients);
225 	if (cfg_client != NULL)
226 		cfg_client->references++;
227 
228 	if (access(TMUX_CONF, R_OK) == 0) {
229 		if (load_cfg(TMUX_CONF, cfg_cmd_q, &cause) == -1)
230 			cfg_add_cause("%s: %s", TMUX_CONF, cause);
231 	} else if (errno != ENOENT)
232 		cfg_add_cause("%s: %s", TMUX_CONF, strerror(errno));
233 	if (cfg_file != NULL) {
234 		if (load_cfg(cfg_file, cfg_cmd_q, &cause) == -1)
235 			cfg_add_cause("%s: %s", cfg_file, cause);
236 	}
237 	cmdq_continue(cfg_cmd_q);
238 	status_prompt_load_history();
239 
240 	server_add_accept(0);
241 
242 	set_signals(server_signal_callback);
243 	server_loop();
244 	status_prompt_save_history();
245 	exit(0);
246 }
247 
248 /* Main server loop. */
249 void
250 server_loop(void)
251 {
252 	while (!server_should_shutdown()) {
253 		log_debug("event dispatch enter");
254 		event_loop(EVLOOP_ONCE);
255 		log_debug("event dispatch exit");
256 
257 		server_client_loop();
258 	}
259 }
260 
261 /* Check if the server should exit (no more clients or sessions). */
262 int
263 server_should_shutdown(void)
264 {
265 	struct client	*c;
266 
267 	if (!options_get_number(&global_options, "exit-unattached")) {
268 		if (!RB_EMPTY(&sessions))
269 			return (0);
270 	}
271 
272 	TAILQ_FOREACH(c, &clients, entry) {
273 		if (c->session != NULL)
274 			return (0);
275 	}
276 
277 	/*
278 	 * No attached clients therefore want to exit - flush any waiting
279 	 * clients but don't actually exit until they've gone.
280 	 */
281 	cmd_wait_for_flush();
282 	if (!TAILQ_EMPTY(&clients))
283 		return (0);
284 
285 	return (1);
286 }
287 
288 /* Shutdown the server by killing all clients and windows. */
289 void
290 server_send_shutdown(void)
291 {
292 	struct client	*c, *c1;
293 	struct session	*s, *s1;
294 
295 	cmd_wait_for_flush();
296 
297 	TAILQ_FOREACH_SAFE(c, &clients, entry, c1) {
298 		if (c->flags & (CLIENT_BAD|CLIENT_SUSPENDED))
299 			server_client_lost(c);
300 		else
301 			server_write_client(c, MSG_SHUTDOWN, NULL, 0);
302 		c->session = NULL;
303 	}
304 
305 	RB_FOREACH_SAFE(s, sessions, &sessions, s1)
306 		session_destroy(s);
307 }
308 
309 /* Update socket execute permissions based on whether sessions are attached. */
310 void
311 server_update_socket(void)
312 {
313 	struct session	*s;
314 	static int	 last = -1;
315 	int		 n, mode;
316 	struct stat      sb;
317 
318 	n = 0;
319 	RB_FOREACH(s, sessions, &sessions) {
320 		if (!(s->flags & SESSION_UNATTACHED)) {
321 			n++;
322 			break;
323 		}
324 	}
325 
326 	if (n != last) {
327 		last = n;
328 
329 		if (stat(socket_path, &sb) != 0)
330 			return;
331 		mode = sb.st_mode;
332 		if (n != 0) {
333 			if (mode & S_IRUSR)
334 				mode |= S_IXUSR;
335 			if (mode & S_IRGRP)
336 				mode |= S_IXGRP;
337 			if (mode & S_IROTH)
338 				mode |= S_IXOTH;
339 		} else
340 			mode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
341 		chmod(socket_path, mode);
342 	}
343 }
344 
345 /* Callback for server socket. */
346 void
347 server_accept_callback(int fd, short events, unused void *data)
348 {
349 	struct sockaddr_storage	sa;
350 	socklen_t		slen = sizeof sa;
351 	int			newfd;
352 
353 	server_add_accept(0);
354 	if (!(events & EV_READ))
355 		return;
356 
357 	newfd = accept(fd, (struct sockaddr *) &sa, &slen);
358 	if (newfd == -1) {
359 		if (errno == EAGAIN || errno == EINTR || errno == ECONNABORTED)
360 			return;
361 		if (errno == ENFILE || errno == EMFILE) {
362 			/* Delete and don't try again for 1 second. */
363 			server_add_accept(1);
364 			return;
365 		}
366 		fatal("accept failed");
367 	}
368 	if (server_shutdown) {
369 		close(newfd);
370 		return;
371 	}
372 	server_client_create(newfd);
373 }
374 
375 /*
376  * Add accept event. If timeout is nonzero, add as a timeout instead of a read
377  * event - used to backoff when running out of file descriptors.
378  */
379 void
380 server_add_accept(int timeout)
381 {
382 	struct timeval tv = { timeout, 0 };
383 
384 	if (event_initialized(&server_ev_accept))
385 		event_del(&server_ev_accept);
386 
387 	if (timeout == 0) {
388 		event_set(&server_ev_accept,
389 		    server_fd, EV_READ, server_accept_callback, NULL);
390 		event_add(&server_ev_accept, NULL);
391 	} else {
392 		event_set(&server_ev_accept,
393 		    server_fd, EV_TIMEOUT, server_accept_callback, NULL);
394 		event_add(&server_ev_accept, &tv);
395 	}
396 }
397 
398 /* Signal handler. */
399 void
400 server_signal_callback(int sig, unused short events, unused void *data)
401 {
402 	int	fd;
403 
404 	switch (sig) {
405 	case SIGTERM:
406 		server_shutdown = 1;
407 		server_send_shutdown();
408 		break;
409 	case SIGCHLD:
410 		server_child_signal();
411 		break;
412 	case SIGUSR1:
413 		event_del(&server_ev_accept);
414 		fd = server_create_socket();
415 		if (fd != -1) {
416 			close(server_fd);
417 			server_fd = fd;
418 			server_update_socket();
419 		}
420 		server_add_accept(0);
421 		break;
422 	}
423 }
424 
425 /* Handle SIGCHLD. */
426 void
427 server_child_signal(void)
428 {
429 	int	 status;
430 	pid_t	 pid;
431 
432 	for (;;) {
433 		switch (pid = waitpid(WAIT_ANY, &status, WNOHANG|WUNTRACED)) {
434 		case -1:
435 			if (errno == ECHILD)
436 				return;
437 			fatal("waitpid failed");
438 		case 0:
439 			return;
440 		}
441 		if (WIFSTOPPED(status))
442 			server_child_stopped(pid, status);
443 		else if (WIFEXITED(status) || WIFSIGNALED(status))
444 			server_child_exited(pid, status);
445 	}
446 }
447 
448 /* Handle exited children. */
449 void
450 server_child_exited(pid_t pid, int status)
451 {
452 	struct window		*w, *w1;
453 	struct window_pane	*wp;
454 	struct job		*job;
455 
456 	RB_FOREACH_SAFE(w, windows, &windows, w1) {
457 		TAILQ_FOREACH(wp, &w->panes, entry) {
458 			if (wp->pid == pid) {
459 				wp->status = status;
460 				server_destroy_pane(wp);
461 				break;
462 			}
463 		}
464 	}
465 
466 	LIST_FOREACH(job, &all_jobs, lentry) {
467 		if (pid == job->pid) {
468 			job_died(job, status);	/* might free job */
469 			break;
470 		}
471 	}
472 }
473 
474 /* Handle stopped children. */
475 void
476 server_child_stopped(pid_t pid, int status)
477 {
478 	struct window		*w;
479 	struct window_pane	*wp;
480 
481 	if (WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU)
482 		return;
483 
484 	RB_FOREACH(w, windows, &windows) {
485 		TAILQ_FOREACH(wp, &w->panes, entry) {
486 			if (wp->pid == pid) {
487 				if (killpg(pid, SIGCONT) != 0)
488 					kill(pid, SIGCONT);
489 			}
490 		}
491 	}
492 }
493