Merge branch 'obsd-master'
[tmux.git] / server.c
blob96a638cbf5f456a74bd36da79b669c29b8e9a476
1 /* $OpenBSD$ */
3 /*
4 * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
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.
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.
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>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <termios.h>
33 #include <time.h>
34 #include <unistd.h>
36 #include "tmux.h"
39 * Main server functions.
42 struct clients clients;
44 struct tmuxproc *server_proc;
45 static int server_fd = -1;
46 static uint64_t server_client_flags;
47 static int server_exit;
48 static struct event server_ev_accept;
49 static struct event server_ev_tidy;
51 struct cmd_find_state marked_pane;
53 static u_int message_next;
54 struct message_list message_log;
56 time_t current_time;
58 static int server_loop(void);
59 static void server_send_exit(void);
60 static void server_accept(int, short, void *);
61 static void server_signal(int);
62 static void server_child_signal(void);
63 static void server_child_exited(pid_t, int);
64 static void server_child_stopped(pid_t, int);
66 /* Set marked pane. */
67 void
68 server_set_marked(struct session *s, struct winlink *wl, struct window_pane *wp)
70 cmd_find_clear_state(&marked_pane, 0);
71 marked_pane.s = s;
72 marked_pane.wl = wl;
73 marked_pane.w = wl->window;
74 marked_pane.wp = wp;
77 /* Clear marked pane. */
78 void
79 server_clear_marked(void)
81 cmd_find_clear_state(&marked_pane, 0);
84 /* Is this the marked pane? */
85 int
86 server_is_marked(struct session *s, struct winlink *wl, struct window_pane *wp)
88 if (s == NULL || wl == NULL || wp == NULL)
89 return (0);
90 if (marked_pane.s != s || marked_pane.wl != wl)
91 return (0);
92 if (marked_pane.wp != wp)
93 return (0);
94 return (server_check_marked());
97 /* Check if the marked pane is still valid. */
98 int
99 server_check_marked(void)
101 return (cmd_find_valid_state(&marked_pane));
104 /* Create server socket. */
106 server_create_socket(int flags, char **cause)
108 struct sockaddr_un sa;
109 size_t size;
110 mode_t mask;
111 int fd, saved_errno;
113 memset(&sa, 0, sizeof sa);
114 sa.sun_family = AF_UNIX;
115 size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path);
116 if (size >= sizeof sa.sun_path) {
117 errno = ENAMETOOLONG;
118 goto fail;
120 unlink(sa.sun_path);
122 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
123 goto fail;
125 if (flags & CLIENT_DEFAULTSOCKET)
126 mask = umask(S_IXUSR|S_IXGRP|S_IRWXO);
127 else
128 mask = umask(S_IXUSR|S_IRWXG|S_IRWXO);
129 if (bind(fd, (struct sockaddr *)&sa, sizeof sa) == -1) {
130 saved_errno = errno;
131 close(fd);
132 errno = saved_errno;
133 goto fail;
135 umask(mask);
137 if (listen(fd, 128) == -1) {
138 saved_errno = errno;
139 close(fd);
140 errno = saved_errno;
141 goto fail;
143 setblocking(fd, 0);
145 return (fd);
147 fail:
148 if (cause != NULL) {
149 xasprintf(cause, "error creating %s (%s)", socket_path,
150 strerror(errno));
152 return (-1);
155 /* Tidy up every hour. */
156 static void
157 server_tidy_event(__unused int fd, __unused short events, __unused void *data)
159 struct timeval tv = { .tv_sec = 3600 };
160 uint64_t t = get_timer();
162 format_tidy_jobs();
164 #ifdef HAVE_MALLOC_TRIM
165 malloc_trim(0);
166 #endif
168 log_debug("%s: took %llu milliseconds", __func__,
169 (unsigned long long)(get_timer() - t));
170 evtimer_add(&server_ev_tidy, &tv);
173 /* Fork new server. */
175 server_start(struct tmuxproc *client, int flags, struct event_base *base,
176 int lockfd, char *lockfile)
178 int fd;
179 sigset_t set, oldset;
180 struct client *c = NULL;
181 char *cause = NULL;
182 struct timeval tv = { .tv_sec = 3600 };
184 sigfillset(&set);
185 sigprocmask(SIG_BLOCK, &set, &oldset);
187 if (~flags & CLIENT_NOFORK) {
188 if (proc_fork_and_daemon(&fd) != 0) {
189 sigprocmask(SIG_SETMASK, &oldset, NULL);
190 return (fd);
193 proc_clear_signals(client, 0);
194 server_client_flags = flags;
196 if (event_reinit(base) != 0)
197 fatalx("event_reinit failed");
198 server_proc = proc_start("server");
200 proc_set_signals(server_proc, server_signal);
201 sigprocmask(SIG_SETMASK, &oldset, NULL);
203 if (log_get_level() > 1)
204 tty_create_log();
205 if (pledge("stdio rpath wpath cpath fattr unix getpw recvfd proc exec "
206 "tty ps", NULL) != 0)
207 fatal("pledge failed");
209 input_key_build();
210 RB_INIT(&windows);
211 RB_INIT(&all_window_panes);
212 TAILQ_INIT(&clients);
213 RB_INIT(&sessions);
214 key_bindings_init();
215 TAILQ_INIT(&message_log);
216 gettimeofday(&start_time, NULL);
218 #ifdef HAVE_SYSTEMD
219 server_fd = systemd_create_socket(flags, &cause);
220 #else
221 server_fd = server_create_socket(flags, &cause);
222 #endif
223 if (server_fd != -1)
224 server_update_socket();
225 if (~flags & CLIENT_NOFORK)
226 c = server_client_create(fd);
227 else
228 options_set_number(global_options, "exit-empty", 0);
230 if (lockfd >= 0) {
231 unlink(lockfile);
232 free(lockfile);
233 close(lockfd);
236 if (cause != NULL) {
237 if (c != NULL) {
238 c->exit_message = cause;
239 c->flags |= CLIENT_EXIT;
240 } else {
241 fprintf(stderr, "%s\n", cause);
242 exit(1);
246 evtimer_set(&server_ev_tidy, server_tidy_event, NULL);
247 evtimer_add(&server_ev_tidy, &tv);
249 server_acl_init();
251 server_add_accept(0);
252 proc_loop(server_proc, server_loop);
254 job_kill_all();
255 status_prompt_save_history();
257 exit(0);
260 /* Server loop callback. */
261 static int
262 server_loop(void)
264 struct client *c;
265 u_int items;
267 current_time = time(NULL);
269 do {
270 items = cmdq_next(NULL);
271 TAILQ_FOREACH(c, &clients, entry) {
272 if (c->flags & CLIENT_IDENTIFIED)
273 items += cmdq_next(c);
275 } while (items != 0);
277 server_client_loop();
279 if (!options_get_number(global_options, "exit-empty") && !server_exit)
280 return (0);
282 if (!options_get_number(global_options, "exit-unattached")) {
283 if (!RB_EMPTY(&sessions))
284 return (0);
287 TAILQ_FOREACH(c, &clients, entry) {
288 if (c->session != NULL)
289 return (0);
293 * No attached clients therefore want to exit - flush any waiting
294 * clients but don't actually exit until they've gone.
296 cmd_wait_for_flush();
297 if (!TAILQ_EMPTY(&clients))
298 return (0);
300 if (job_still_running())
301 return (0);
303 return (1);
306 /* Exit the server by killing all clients and windows. */
307 static void
308 server_send_exit(void)
310 struct client *c, *c1;
311 struct session *s, *s1;
313 cmd_wait_for_flush();
315 TAILQ_FOREACH_SAFE(c, &clients, entry, c1) {
316 if (c->flags & CLIENT_SUSPENDED)
317 server_client_lost(c);
318 else {
319 c->flags |= CLIENT_EXIT;
320 c->exit_type = CLIENT_EXIT_SHUTDOWN;
322 c->session = NULL;
325 RB_FOREACH_SAFE(s, sessions, &sessions, s1)
326 session_destroy(s, 1, __func__);
329 /* Update socket execute permissions based on whether sessions are attached. */
330 void
331 server_update_socket(void)
333 struct session *s;
334 static int last = -1;
335 int n, mode;
336 struct stat sb;
338 n = 0;
339 RB_FOREACH(s, sessions, &sessions) {
340 if (s->attached != 0) {
341 n++;
342 break;
346 if (n != last) {
347 last = n;
349 if (stat(socket_path, &sb) != 0)
350 return;
351 mode = sb.st_mode & ACCESSPERMS;
352 if (n != 0) {
353 if (mode & S_IRUSR)
354 mode |= S_IXUSR;
355 if (mode & S_IRGRP)
356 mode |= S_IXGRP;
357 if (mode & S_IROTH)
358 mode |= S_IXOTH;
359 } else
360 mode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
361 chmod(socket_path, mode);
365 /* Callback for server socket. */
366 static void
367 server_accept(int fd, short events, __unused void *data)
369 struct sockaddr_storage sa;
370 socklen_t slen = sizeof sa;
371 int newfd;
372 struct client *c;
374 server_add_accept(0);
375 if (!(events & EV_READ))
376 return;
378 newfd = accept(fd, (struct sockaddr *) &sa, &slen);
379 if (newfd == -1) {
380 if (errno == EAGAIN || errno == EINTR || errno == ECONNABORTED)
381 return;
382 if (errno == ENFILE || errno == EMFILE) {
383 /* Delete and don't try again for 1 second. */
384 server_add_accept(1);
385 return;
387 fatal("accept failed");
390 if (server_exit) {
391 close(newfd);
392 return;
394 c = server_client_create(newfd);
395 if (!server_acl_join(c)) {
396 c->exit_message = xstrdup("access not allowed");
397 c->flags |= CLIENT_EXIT;
402 * Add accept event. If timeout is nonzero, add as a timeout instead of a read
403 * event - used to backoff when running out of file descriptors.
405 void
406 server_add_accept(int timeout)
408 struct timeval tv = { timeout, 0 };
410 if (server_fd == -1)
411 return;
413 if (event_initialized(&server_ev_accept))
414 event_del(&server_ev_accept);
416 if (timeout == 0) {
417 event_set(&server_ev_accept, server_fd, EV_READ, server_accept,
418 NULL);
419 event_add(&server_ev_accept, NULL);
420 } else {
421 event_set(&server_ev_accept, server_fd, EV_TIMEOUT,
422 server_accept, NULL);
423 event_add(&server_ev_accept, &tv);
427 /* Signal handler. */
428 static void
429 server_signal(int sig)
431 int fd;
433 log_debug("%s: %s", __func__, strsignal(sig));
434 switch (sig) {
435 case SIGINT:
436 case SIGTERM:
437 server_exit = 1;
438 server_send_exit();
439 break;
440 case SIGCHLD:
441 server_child_signal();
442 break;
443 case SIGUSR1:
444 event_del(&server_ev_accept);
445 fd = server_create_socket(server_client_flags, NULL);
446 if (fd != -1) {
447 close(server_fd);
448 server_fd = fd;
449 server_update_socket();
451 server_add_accept(0);
452 break;
453 case SIGUSR2:
454 proc_toggle_log(server_proc);
455 break;
459 /* Handle SIGCHLD. */
460 static void
461 server_child_signal(void)
463 int status;
464 pid_t pid;
466 for (;;) {
467 switch (pid = waitpid(WAIT_ANY, &status, WNOHANG|WUNTRACED)) {
468 case -1:
469 if (errno == ECHILD)
470 return;
471 fatal("waitpid failed");
472 case 0:
473 return;
475 if (WIFSTOPPED(status))
476 server_child_stopped(pid, status);
477 else if (WIFEXITED(status) || WIFSIGNALED(status))
478 server_child_exited(pid, status);
482 /* Handle exited children. */
483 static void
484 server_child_exited(pid_t pid, int status)
486 struct window *w, *w1;
487 struct window_pane *wp;
489 RB_FOREACH_SAFE(w, windows, &windows, w1) {
490 TAILQ_FOREACH(wp, &w->panes, entry) {
491 if (wp->pid == pid) {
492 wp->status = status;
493 wp->flags |= PANE_STATUSREADY;
495 log_debug("%%%u exited", wp->id);
496 wp->flags |= PANE_EXITED;
498 if (window_pane_destroy_ready(wp))
499 server_destroy_pane(wp, 1);
500 break;
504 job_check_died(pid, status);
507 /* Handle stopped children. */
508 static void
509 server_child_stopped(pid_t pid, int status)
511 struct window *w;
512 struct window_pane *wp;
514 if (WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU)
515 return;
517 RB_FOREACH(w, windows, &windows) {
518 TAILQ_FOREACH(wp, &w->panes, entry) {
519 if (wp->pid == pid) {
520 if (killpg(pid, SIGCONT) != 0)
521 kill(pid, SIGCONT);
525 job_check_died(pid, status);
528 /* Add to message log. */
529 void
530 server_add_message(const char *fmt, ...)
532 struct message_entry *msg, *msg1;
533 char *s;
534 va_list ap;
535 u_int limit;
537 va_start(ap, fmt);
538 xvasprintf(&s, fmt, ap);
539 va_end(ap);
541 log_debug("message: %s", s);
543 msg = xcalloc(1, sizeof *msg);
544 gettimeofday(&msg->msg_time, NULL);
545 msg->msg_num = message_next++;
546 msg->msg = s;
547 TAILQ_INSERT_TAIL(&message_log, msg, entry);
549 limit = options_get_number(global_options, "message-limit");
550 TAILQ_FOREACH_SAFE(msg, &message_log, entry, msg1) {
551 if (msg->msg_num + limit >= message_next)
552 break;
553 free(msg->msg);
554 TAILQ_REMOVE(&message_log, msg, entry);
555 free(msg);