Merge the before and after attach client code into one in client.c
[tmux-openbsd.git] / server.c
blob7a4e5fcfe3dde2ed2a5193b05a11536f8c522c9f
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 int server_create_socket(void);
55 void server_loop(void);
56 int server_should_shutdown(void);
57 void server_send_shutdown(void);
58 void server_clean_dead(void);
59 void server_accept_callback(int, short, void *);
60 void server_signal_callback(int, short, void *);
61 void server_child_signal(void);
62 void server_child_exited(pid_t, int);
63 void server_child_stopped(pid_t, int);
64 void server_second_callback(int, short, void *);
65 void server_lock_server(void);
66 void server_lock_sessions(void);
68 /* Create server socket. */
69 int
70 server_create_socket(void)
72 struct sockaddr_un sa;
73 size_t size;
74 mode_t mask;
75 int fd, mode;
77 memset(&sa, 0, sizeof sa);
78 sa.sun_family = AF_UNIX;
79 size = strlcpy(sa.sun_path, socket_path, sizeof sa.sun_path);
80 if (size >= sizeof sa.sun_path) {
81 errno = ENAMETOOLONG;
82 fatal("socket failed");
84 unlink(sa.sun_path);
86 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
87 fatal("socket failed");
89 mask = umask(S_IXUSR|S_IXGRP|S_IRWXO);
90 if (bind(fd, (struct sockaddr *) &sa, SUN_LEN(&sa)) == -1)
91 fatal("bind failed");
92 umask(mask);
94 if (listen(fd, 16) == -1)
95 fatal("listen failed");
97 if ((mode = fcntl(fd, F_GETFL)) == -1)
98 fatal("fcntl failed");
99 if (fcntl(fd, F_SETFL, mode|O_NONBLOCK) == -1)
100 fatal("fcntl failed");
102 server_update_socket();
104 return (fd);
107 /* Fork new server. */
109 server_start(void)
111 struct window_pane *wp;
112 int pair[2];
113 char *cause;
114 struct timeval tv;
115 u_int i;
117 /* The first client is special and gets a socketpair; create it. */
118 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
119 fatal("socketpair failed");
121 switch (fork()) {
122 case -1:
123 fatal("fork failed");
124 case 0:
125 break;
126 default:
127 close(pair[1]);
128 return (pair[0]);
130 close(pair[0]);
133 * Must daemonise before loading configuration as the PID changes so
134 * $TMUX would be wrong for sessions created in the config file.
136 if (daemon(1, 0) != 0)
137 fatal("daemon failed");
139 /* event_init() was called in our parent, need to reinit. */
140 if (event_reinit(ev_base) != 0)
141 fatal("event_reinit failed");
142 clear_signals(0);
144 logfile("server");
145 log_debug("server started, pid %ld", (long) getpid());
147 ARRAY_INIT(&windows);
148 ARRAY_INIT(&clients);
149 ARRAY_INIT(&dead_clients);
150 ARRAY_INIT(&sessions);
151 ARRAY_INIT(&dead_sessions);
152 TAILQ_INIT(&session_groups);
153 mode_key_init_trees();
154 key_bindings_init();
155 utf8_build();
157 start_time = time(NULL);
158 log_debug("socket path %s", socket_path);
159 setproctitle("server (%s)", socket_path);
161 server_fd = server_create_socket();
162 server_client_create(pair[1]);
164 if (access(SYSTEM_CFG, R_OK) == 0)
165 load_cfg(SYSTEM_CFG, NULL, &cfg_causes);
166 else if (errno != ENOENT) {
167 cfg_add_cause(
168 &cfg_causes, "%s: %s", strerror(errno), SYSTEM_CFG);
170 if (cfg_file != NULL)
171 load_cfg(cfg_file, NULL, &cfg_causes);
174 * If there is a session already, put the current window and pane into
175 * more mode.
177 if (!ARRAY_EMPTY(&sessions) && !ARRAY_EMPTY(&cfg_causes)) {
178 wp = ARRAY_FIRST(&sessions)->curw->window->active;
179 window_pane_set_mode(wp, &window_copy_mode);
180 window_copy_init_for_output(wp);
181 for (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {
182 cause = ARRAY_ITEM(&cfg_causes, i);
183 window_copy_add(wp, "%s", cause);
184 xfree(cause);
186 ARRAY_FREE(&cfg_causes);
188 cfg_finished = 1;
190 event_set(&server_ev_accept,
191 server_fd, EV_READ|EV_PERSIST, server_accept_callback, NULL);
192 event_add(&server_ev_accept, NULL);
194 memset(&tv, 0, sizeof tv);
195 tv.tv_sec = 1;
196 evtimer_set(&server_ev_second, server_second_callback, NULL);
197 evtimer_add(&server_ev_second, &tv);
199 set_signals(server_signal_callback);
200 server_loop();
201 exit(0);
204 /* Main server loop. */
205 void
206 server_loop(void)
208 while (!server_should_shutdown()) {
209 event_loop(EVLOOP_ONCE);
211 server_window_loop();
212 server_client_loop();
214 key_bindings_clean();
215 server_clean_dead();
219 /* Check if the server should be shutting down (no more clients or sessions). */
221 server_should_shutdown(void)
223 u_int i;
225 if (!options_get_number(&global_options, "exit-unattached")) {
226 for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
227 if (ARRAY_ITEM(&sessions, i) != NULL)
228 return (0);
231 for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
232 if (ARRAY_ITEM(&clients, i) != NULL)
233 return (0);
235 return (1);
238 /* Shutdown the server by killing all clients and windows. */
239 void
240 server_send_shutdown(void)
242 struct client *c;
243 struct session *s;
244 u_int i;
246 for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
247 c = ARRAY_ITEM(&clients, i);
248 if (c != NULL) {
249 if (c->flags & (CLIENT_BAD|CLIENT_SUSPENDED))
250 server_client_lost(c);
251 else
252 server_write_client(c, MSG_SHUTDOWN, NULL, 0);
253 c->session = NULL;
257 for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
258 if ((s = ARRAY_ITEM(&sessions, i)) != NULL)
259 session_destroy(s);
263 /* Free dead, unreferenced clients and sessions. */
264 void
265 server_clean_dead(void)
267 struct session *s;
268 struct client *c;
269 u_int i;
271 for (i = 0; i < ARRAY_LENGTH(&dead_sessions); i++) {
272 s = ARRAY_ITEM(&dead_sessions, i);
273 if (s == NULL || s->references != 0)
274 continue;
275 ARRAY_SET(&dead_sessions, i, NULL);
276 xfree(s);
279 for (i = 0; i < ARRAY_LENGTH(&dead_clients); i++) {
280 c = ARRAY_ITEM(&dead_clients, i);
281 if (c == NULL || c->references != 0)
282 continue;
283 ARRAY_SET(&dead_clients, i, NULL);
284 xfree(c);
288 /* Update socket execute permissions based on whether sessions are attached. */
289 void
290 server_update_socket(void)
292 struct session *s;
293 u_int i;
294 static int last = -1;
295 int n, mode;
296 struct stat sb;
298 n = 0;
299 for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
300 s = ARRAY_ITEM(&sessions, i);
301 if (s != NULL && !(s->flags & SESSION_UNATTACHED)) {
302 n++;
303 break;
307 if (n != last) {
308 last = n;
310 if (stat(socket_path, &sb) != 0)
311 return;
312 mode = sb.st_mode;
313 if (n != 0) {
314 if (mode & S_IRUSR)
315 mode |= S_IXUSR;
316 if (mode & S_IRGRP)
317 mode |= S_IXGRP;
318 if (mode & S_IROTH)
319 mode |= S_IXOTH;
320 } else
321 mode &= ~(S_IXUSR|S_IXGRP|S_IXOTH);
322 chmod(socket_path, mode);
326 /* Callback for server socket. */
327 /* ARGSUSED */
328 void
329 server_accept_callback(int fd, short events, unused void *data)
331 struct sockaddr_storage sa;
332 socklen_t slen = sizeof sa;
333 int newfd;
335 if (!(events & EV_READ))
336 return;
338 newfd = accept(fd, (struct sockaddr *) &sa, &slen);
339 if (newfd == -1) {
340 if (errno == EAGAIN || errno == EINTR || errno == ECONNABORTED)
341 return;
342 fatal("accept failed");
344 if (server_shutdown) {
345 close(newfd);
346 return;
348 server_client_create(newfd);
351 /* Signal handler. */
352 /* ARGSUSED */
353 void
354 server_signal_callback(int sig, unused short events, unused void *data)
356 switch (sig) {
357 case SIGTERM:
358 server_shutdown = 1;
359 server_send_shutdown();
360 break;
361 case SIGCHLD:
362 server_child_signal();
363 break;
364 case SIGUSR1:
365 event_del(&server_ev_accept);
366 close(server_fd);
367 server_fd = server_create_socket();
368 event_set(&server_ev_accept, server_fd,
369 EV_READ|EV_PERSIST, server_accept_callback, NULL);
370 event_add(&server_ev_accept, NULL);
371 break;
375 /* Handle SIGCHLD. */
376 void
377 server_child_signal(void)
379 int status;
380 pid_t pid;
382 for (;;) {
383 switch (pid = waitpid(WAIT_ANY, &status, WNOHANG|WUNTRACED)) {
384 case -1:
385 if (errno == ECHILD)
386 return;
387 fatal("waitpid failed");
388 case 0:
389 return;
391 if (WIFSTOPPED(status))
392 server_child_stopped(pid, status);
393 else if (WIFEXITED(status) || WIFSIGNALED(status))
394 server_child_exited(pid, status);
398 /* Handle exited children. */
399 void
400 server_child_exited(pid_t pid, int status)
402 struct window *w;
403 struct window_pane *wp;
404 struct job *job;
405 u_int i;
407 for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
408 if ((w = ARRAY_ITEM(&windows, i)) == NULL)
409 continue;
410 TAILQ_FOREACH(wp, &w->panes, entry) {
411 if (wp->pid == pid) {
412 server_destroy_pane(wp);
413 break;
418 SLIST_FOREACH(job, &all_jobs, lentry) {
419 if (pid == job->pid) {
420 job_died(job, status); /* might free job */
421 break;
426 /* Handle stopped children. */
427 void
428 server_child_stopped(pid_t pid, int status)
430 struct window *w;
431 struct window_pane *wp;
432 u_int i;
434 if (WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU)
435 return;
437 for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
438 if ((w = ARRAY_ITEM(&windows, i)) == NULL)
439 continue;
440 TAILQ_FOREACH(wp, &w->panes, entry) {
441 if (wp->pid == pid) {
442 if (killpg(pid, SIGCONT) != 0)
443 kill(pid, SIGCONT);
449 /* Handle once-per-second timer events. */
450 /* ARGSUSED */
451 void
452 server_second_callback(unused int fd, unused short events, unused void *arg)
454 struct window *w;
455 struct window_pane *wp;
456 struct timeval tv;
457 u_int i;
459 if (options_get_number(&global_s_options, "lock-server"))
460 server_lock_server();
461 else
462 server_lock_sessions();
464 for (i = 0; i < ARRAY_LENGTH(&windows); i++) {
465 w = ARRAY_ITEM(&windows, i);
466 if (w == NULL)
467 continue;
469 TAILQ_FOREACH(wp, &w->panes, entry) {
470 if (wp->mode != NULL && wp->mode->timer != NULL)
471 wp->mode->timer(wp);
475 server_client_status_timer();
477 evtimer_del(&server_ev_second);
478 memset(&tv, 0, sizeof tv);
479 tv.tv_sec = 1;
480 evtimer_add(&server_ev_second, &tv);
483 /* Lock the server if ALL sessions have hit the time limit. */
484 void
485 server_lock_server(void)
487 struct session *s;
488 u_int i;
489 int timeout;
490 time_t t;
492 t = time(NULL);
493 for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
494 if ((s = ARRAY_ITEM(&sessions, i)) == NULL)
495 continue;
497 if (s->flags & SESSION_UNATTACHED) {
498 if (gettimeofday(&s->activity_time, NULL) != 0)
499 fatal("gettimeofday failed");
500 continue;
503 timeout = options_get_number(&s->options, "lock-after-time");
504 if (timeout <= 0 || t <= s->activity_time.tv_sec + timeout)
505 return; /* not timed out */
508 server_lock();
509 recalculate_sizes();
512 /* Lock any sessions which have timed out. */
513 void
514 server_lock_sessions(void)
516 struct session *s;
517 u_int i;
518 int timeout;
519 time_t t;
521 t = time(NULL);
522 for (i = 0; i < ARRAY_LENGTH(&sessions); i++) {
523 if ((s = ARRAY_ITEM(&sessions, i)) == NULL)
524 continue;
526 if (s->flags & SESSION_UNATTACHED) {
527 if (gettimeofday(&s->activity_time, NULL) != 0)
528 fatal("gettimeofday failed");
529 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();