Expand format variables in the run-shell and if-shell shell commands,
[tmux-openbsd.git] / server.c
blob994f39686fc361491201cd5085fb6c41693cc7c4
1 /* $OpenBSD$ */
3 /*
4 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
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 <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 <syslog.h>
35 #include <termios.h>
36 #include <time.h>
37 #include <unistd.h>
39 #include "tmux.h"
42 * Main server functions.
45 /* Client list. */
46 struct clients clients;
47 struct clients dead_clients;
49 int server_fd;
50 int server_shutdown;
51 struct event server_ev_accept;
52 struct event server_ev_second;
54 struct paste_stack global_buffers;
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_clean_dead(void);
61 void server_accept_callback(int, short, void *);
62 void server_signal_callback(int, short, void *);
63 void server_child_signal(void);
64 void server_child_exited(pid_t, int);
65 void server_child_stopped(pid_t, int);
66 void server_second_callback(int, short, void *);
67 void server_lock_server(void);
68 void server_lock_sessions(void);
70 /* Create server socket. */
71 int
72 server_create_socket(void)
74 struct sockaddr_un sa;
75 size_t size;
76 mode_t mask;
77 int fd;
79 memset(&sa, 0, sizeof sa);
80 sa.sun_family = AF_UNIX;
81 size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path);
82 if (size >= sizeof sa.sun_path) {
83 errno = ENAMETOOLONG;
84 fatal("socket failed");
86 unlink(sa.sun_path);
88 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
89 fatal("socket failed");
91 mask = umask(S_IXUSR|S_IXGRP|S_IRWXO);
92 if (bind(fd, (struct sockaddr *) &sa, SUN_LEN(&sa)) == -1)
93 fatal("bind failed");
94 umask(mask);
96 if (listen(fd, 16) == -1)
97 fatal("listen failed");
98 setblocking(fd, 0);
100 server_update_socket();
102 return (fd);
105 /* Fork new server. */
107 server_start(int lockfd, char *lockfile)
109 int pair[2];
110 struct timeval tv;
112 /* The first client is special and gets a socketpair; create it. */
113 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
114 fatal("socketpair failed");
116 switch (fork()) {
117 case -1:
118 fatal("fork failed");
119 case 0:
120 break;
121 default:
122 close(pair[1]);
123 return (pair[0]);
125 close(pair[0]);
128 * Must daemonise before loading configuration as the PID changes so
129 * $TMUX would be wrong for sessions created in the config file.
131 if (daemon(1, 0) != 0)
132 fatal("daemon failed");
134 /* event_init() was called in our parent, need to reinit. */
135 if (event_reinit(ev_base) != 0)
136 fatal("event_reinit failed");
137 clear_signals(0);
139 logfile("server");
140 log_debug("server started, pid %ld", (long) getpid());
142 ARRAY_INIT(&windows);
143 RB_INIT(&all_window_panes);
144 ARRAY_INIT(&clients);
145 ARRAY_INIT(&dead_clients);
146 RB_INIT(&sessions);
147 RB_INIT(&dead_sessions);
148 TAILQ_INIT(&session_groups);
149 ARRAY_INIT(&global_buffers);
150 mode_key_init_trees();
151 key_bindings_init();
152 utf8_build();
154 start_time = time(NULL);
155 log_debug("socket path %s", socket_path);
156 setproctitle("server (%s)", socket_path);
158 server_fd = server_create_socket();
159 server_client_create(pair[1]);
161 unlink(lockfile);
162 free(lockfile);
163 close(lockfd);
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", SYSTEM_CFG, strerror(errno));
171 if (cfg_file != NULL)
172 load_cfg(cfg_file, NULL, &cfg_causes);
175 * If there is a session already, put the current window and pane into
176 * more mode.
178 if (!RB_EMPTY(&sessions) && !ARRAY_EMPTY(&cfg_causes))
179 show_cfg_causes(RB_MIN(sessions, &sessions));
181 cfg_finished = 1;
183 server_add_accept(0);
185 memset(&tv, 0, sizeof tv);
186 tv.tv_sec = 1;
187 evtimer_set(&server_ev_second, server_second_callback, NULL);
188 evtimer_add(&server_ev_second, &tv);
190 set_signals(server_signal_callback);
191 server_loop();
192 exit(0);
195 /* Main server loop. */
196 void
197 server_loop(void)
199 while (!server_should_shutdown()) {
200 event_loop(EVLOOP_ONCE);
202 server_window_loop();
203 server_client_loop();
205 key_bindings_clean();
206 server_clean_dead();
210 /* Check if the server should be shutting down (no more clients or sessions). */
212 server_should_shutdown(void)
214 u_int i;
216 if (!options_get_number(&global_options, "exit-unattached")) {
217 if (!RB_EMPTY(&sessions))
218 return (0);
220 for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
221 if (ARRAY_ITEM(&clients, i) != NULL)
222 return (0);
224 return (1);
227 /* Shutdown the server by killing all clients and windows. */
228 void
229 server_send_shutdown(void)
231 struct client *c;
232 struct session *s, *next_s;
233 u_int i;
235 for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
236 c = ARRAY_ITEM(&clients, i);
237 if (c != NULL) {
238 if (c->flags & (CLIENT_BAD|CLIENT_SUSPENDED))
239 server_client_lost(c);
240 else
241 server_write_client(c, MSG_SHUTDOWN, NULL, 0);
242 c->session = NULL;
246 s = RB_MIN(sessions, &sessions);
247 while (s != NULL) {
248 next_s = RB_NEXT(sessions, &sessions, s);
249 session_destroy(s);
250 s = next_s;
254 /* Free dead, unreferenced clients and sessions. */
255 void
256 server_clean_dead(void)
258 struct session *s, *next_s;
259 struct client *c;
260 u_int i;
262 s = RB_MIN(sessions, &dead_sessions);
263 while (s != NULL) {
264 next_s = RB_NEXT(sessions, &dead_sessions, s);
265 if (s->references == 0) {
266 RB_REMOVE(sessions, &dead_sessions, s);
267 free(s->name);
268 free(s);
270 s = next_s;
273 for (i = 0; i < ARRAY_LENGTH(&dead_clients); i++) {
274 c = ARRAY_ITEM(&dead_clients, i);
275 if (c == NULL || c->references != 0)
276 continue;
277 ARRAY_SET(&dead_clients, i, NULL);
278 free(c);
282 /* Update socket execute permissions based on whether sessions are attached. */
283 void
284 server_update_socket(void)
286 struct session *s;
287 static int last = -1;
288 int n, mode;
289 struct stat sb;
291 n = 0;
292 RB_FOREACH(s, sessions, &sessions) {
293 if (!(s->flags & SESSION_UNATTACHED)) {
294 n++;
295 break;
299 if (n != last) {
300 last = n;
302 if (stat(socket_path, &sb) != 0)
303 return;
304 mode = sb.st_mode;
305 if (n != 0) {
306 if (mode & S_IRUSR)
307 mode |= S_IXUSR;
308 if (mode & S_IRGRP)
309 mode |= S_IXGRP;
310 if (mode & S_IROTH)
311 mode |= S_IXOTH;
312 } else
313 mode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
314 chmod(socket_path, mode);
318 /* Callback for server socket. */
319 void
320 server_accept_callback(int fd, short events, unused void *data)
322 struct sockaddr_storage sa;
323 socklen_t slen = sizeof sa;
324 int newfd;
326 server_add_accept(0);
327 if (!(events & EV_READ))
328 return;
330 newfd = accept(fd, (struct sockaddr *) &sa, &slen);
331 if (newfd == -1) {
332 if (errno == EAGAIN || errno == EINTR || errno == ECONNABORTED)
333 return;
334 if (errno == ENFILE || errno == EMFILE) {
335 /* Delete and don't try again for 1 second. */
336 server_add_accept(1);
337 return;
339 fatal("accept failed");
341 if (server_shutdown) {
342 close(newfd);
343 return;
345 server_client_create(newfd);
349 * Add accept event. If timeout is nonzero, add as a timeout instead of a read
350 * event - used to backoff when running out of file descriptors.
352 void
353 server_add_accept(int timeout)
355 struct timeval tv = { timeout, 0 };
357 if (event_initialized(&server_ev_accept))
358 event_del(&server_ev_accept);
360 if (timeout == 0) {
361 event_set(&server_ev_accept,
362 server_fd, EV_READ, server_accept_callback, NULL);
363 event_add(&server_ev_accept, NULL);
364 } else {
365 event_set(&server_ev_accept,
366 server_fd, EV_TIMEOUT, server_accept_callback, NULL);
367 event_add(&server_ev_accept, &tv);
371 /* Signal handler. */
372 void
373 server_signal_callback(int sig, unused short events, unused void *data)
375 switch (sig) {
376 case SIGTERM:
377 server_shutdown = 1;
378 server_send_shutdown();
379 break;
380 case SIGCHLD:
381 server_child_signal();
382 break;
383 case SIGUSR1:
384 event_del(&server_ev_accept);
385 close(server_fd);
386 server_fd = server_create_socket();
387 server_add_accept(0);
388 break;
392 /* Handle SIGCHLD. */
393 void
394 server_child_signal(void)
396 int status;
397 pid_t pid;
399 for (;;) {
400 switch (pid = waitpid(WAIT_ANY, &status, WNOHANG|WUNTRACED)) {
401 case -1:
402 if (errno == ECHILD)
403 return;
404 fatal("waitpid failed");
405 case 0:
406 return;
408 if (WIFSTOPPED(status))
409 server_child_stopped(pid, status);
410 else if (WIFEXITED(status) || WIFSIGNALED(status))
411 server_child_exited(pid, status);
415 /* Handle exited children. */
416 void
417 server_child_exited(pid_t pid, int status)
419 struct window *w;
420 struct window_pane *wp;
421 struct job *job;
422 u_int i;
424 for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
425 if ((w = ARRAY_ITEM(&windows, i)) == NULL)
426 continue;
427 TAILQ_FOREACH(wp, &w->panes, entry) {
428 if (wp->pid == pid) {
429 server_destroy_pane(wp);
430 break;
435 LIST_FOREACH(job, &all_jobs, lentry) {
436 if (pid == job->pid) {
437 job_died(job, status); /* might free job */
438 break;
443 /* Handle stopped children. */
444 void
445 server_child_stopped(pid_t pid, int status)
447 struct window *w;
448 struct window_pane *wp;
449 u_int i;
451 if (WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU)
452 return;
454 for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
455 if ((w = ARRAY_ITEM(&windows, i)) == NULL)
456 continue;
457 TAILQ_FOREACH(wp, &w->panes, entry) {
458 if (wp->pid == pid) {
459 if (killpg(pid, SIGCONT) != 0)
460 kill(pid, SIGCONT);
466 /* Handle once-per-second timer events. */
467 void
468 server_second_callback(unused int fd, unused short events, unused void *arg)
470 struct window *w;
471 struct window_pane *wp;
472 struct timeval tv;
473 u_int i;
475 if (options_get_number(&global_s_options, "lock-server"))
476 server_lock_server();
477 else
478 server_lock_sessions();
480 for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
481 w = ARRAY_ITEM(&windows, i);
482 if (w == NULL)
483 continue;
485 TAILQ_FOREACH(wp, &w->panes, entry) {
486 if (wp->mode != NULL && wp->mode->timer != NULL)
487 wp->mode->timer(wp);
491 server_client_status_timer();
493 evtimer_del(&server_ev_second);
494 memset(&tv, 0, sizeof tv);
495 tv.tv_sec = 1;
496 evtimer_add(&server_ev_second, &tv);
499 /* Lock the server if ALL sessions have hit the time limit. */
500 void
501 server_lock_server(void)
503 struct session *s;
504 int timeout;
505 time_t t;
507 t = time(NULL);
508 RB_FOREACH(s, sessions, &sessions) {
509 if (s->flags & SESSION_UNATTACHED)
510 continue;
511 timeout = options_get_number(&s->options, "lock-after-time");
512 if (timeout <= 0 || t <= s->activity_time.tv_sec + timeout)
513 return; /* not timed out */
516 server_lock();
517 recalculate_sizes();
520 /* Lock any sessions which have timed out. */
521 void
522 server_lock_sessions(void)
524 struct session *s;
525 int timeout;
526 time_t t;
528 t = time(NULL);
529 RB_FOREACH(s, sessions, &sessions) {
530 if (s->flags & SESSION_UNATTACHED)
531 continue;
532 timeout = options_get_number(&s->options, "lock-after-time");
533 if (timeout > 0 && t > s->activity_time.tv_sec + timeout) {
534 server_lock_session(s);
535 recalculate_sizes();