Make the active pane border have a green foreground instead of
[tmux-openbsd.git] / tmux.c
blob741ee38e2659ed48312177aa734003c0baf46098
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/stat.h>
22 #include <errno.h>
23 #include <event.h>
24 #include <paths.h>
25 #include <pwd.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <unistd.h>
32 #include "tmux.h"
34 #ifdef DEBUG
35 extern char *malloc_options;
36 #endif
38 char *cfg_file;
39 struct options global_options; /* server options */
40 struct options global_s_options; /* session options */
41 struct options global_w_options; /* window options */
42 struct environ global_environ;
44 int debug_level;
45 time_t start_time;
46 char *socket_path;
47 int login_shell;
49 struct env_data {
50 char *path;
51 pid_t pid;
52 u_int idx;
55 __dead void usage(void);
56 void parse_env(struct env_data *);
57 char *makesockpath(const char *);
58 __dead void shell_exec(const char *, const char *);
60 struct imsgbuf *main_ibuf;
61 struct event main_ev_sigterm;
62 int main_exitval;
64 void main_set_signals(void);
65 void main_clear_signals(void);
66 void main_signal(int, short, unused void *);
67 void main_callback(int, short, void *);
68 void main_dispatch(const char *);
70 __dead void
71 usage(void)
73 fprintf(stderr,
74 "usage: %s [-28lquv] [-c shell-command] [-f file] [-L socket-name]\n"
75 " [-S socket-path] [command [flags]]\n",
76 __progname);
77 exit(1);
80 void
81 logfile(const char *name)
83 char *path;
85 log_close();
86 if (debug_level > 0) {
87 xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
88 log_open_file(debug_level, path);
89 xfree(path);
93 const char *
94 getshell(void)
96 struct passwd *pw;
97 const char *shell;
99 shell = getenv("SHELL");
100 if (checkshell(shell))
101 return (shell);
103 pw = getpwuid(getuid());
104 if (pw != NULL && checkshell(pw->pw_shell))
105 return (pw->pw_shell);
107 return (_PATH_BSHELL);
111 checkshell(const char *shell)
113 if (shell == NULL || *shell == '\0' || areshell(shell))
114 return (0);
115 if (access(shell, X_OK) != 0)
116 return (0);
117 return (1);
121 areshell(const char *shell)
123 const char *progname, *ptr;
125 if ((ptr = strrchr(shell, '/')) != NULL)
126 ptr++;
127 else
128 ptr = shell;
129 progname = __progname;
130 if (*progname == '-')
131 progname++;
132 if (strcmp(ptr, progname) == 0)
133 return (1);
134 return (0);
137 void
138 parse_env(struct env_data *data)
140 char *env, *path_pid, *pid_idx, buf[256];
141 size_t len;
142 const char *errstr;
143 long long ll;
145 data->pid = -1;
146 if ((env = getenv("TMUX")) == NULL)
147 return;
149 if ((path_pid = strchr(env, ',')) == NULL || path_pid == env)
150 return;
151 if ((pid_idx = strchr(path_pid + 1, ',')) == NULL)
152 return;
153 if ((pid_idx == path_pid + 1 || pid_idx[1] == '\0'))
154 return;
156 /* path */
157 len = path_pid - env;
158 data->path = xmalloc (len + 1);
159 memcpy(data->path, env, len);
160 data->path[len] = '\0';
162 /* pid */
163 len = pid_idx - path_pid - 1;
164 if (len > (sizeof buf) - 1)
165 return;
166 memcpy(buf, path_pid + 1, len);
167 buf[len] = '\0';
169 ll = strtonum(buf, 0, LONG_MAX, &errstr);
170 if (errstr != NULL)
171 return;
172 data->pid = ll;
174 /* idx */
175 ll = strtonum(pid_idx+1, 0, UINT_MAX, &errstr);
176 if (errstr != NULL)
177 return;
178 data->idx = ll;
181 char *
182 makesockpath(const char *label)
184 char base[MAXPATHLEN], *path;
185 struct stat sb;
186 u_int uid;
188 uid = getuid();
189 xsnprintf(base, MAXPATHLEN, "%s/tmux-%d", _PATH_TMP, uid);
191 if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST)
192 return (NULL);
194 if (lstat(base, &sb) != 0)
195 return (NULL);
196 if (!S_ISDIR(sb.st_mode)) {
197 errno = ENOTDIR;
198 return (NULL);
200 if (sb.st_uid != uid || (sb.st_mode & (S_IRWXG|S_IRWXO)) != 0) {
201 errno = EACCES;
202 return (NULL);
205 xasprintf(&path, "%s/%s", base, label);
206 return (path);
209 __dead void
210 shell_exec(const char *shell, const char *shellcmd)
212 const char *shellname, *ptr;
213 char *argv0;
215 ptr = strrchr(shell, '/');
216 if (ptr != NULL && *(ptr + 1) != '\0')
217 shellname = ptr + 1;
218 else
219 shellname = shell;
220 if (login_shell)
221 xasprintf(&argv0, "-%s", shellname);
222 else
223 xasprintf(&argv0, "%s", shellname);
224 setenv("SHELL", shell, 1);
226 execl(shell, argv0, "-c", shellcmd, (char *) NULL);
227 fatal("execl failed");
231 main(int argc, char **argv)
233 struct cmd_list *cmdlist;
234 struct cmd *cmd;
235 enum msgtype msg;
236 struct passwd *pw;
237 struct options *oo, *so, *wo;
238 struct keylist *keylist;
239 struct env_data envdata;
240 struct msg_command_data cmddata;
241 struct sigaction sigact;
242 char *s, *shellcmd, *path, *label, *home, *cause;
243 char cwd[MAXPATHLEN], **var;
244 void *buf;
245 size_t len;
246 int opt, flags, quiet = 0, cmdflags = 0;
247 short events;
249 #ifdef DEBUG
250 malloc_options = (char *) "AFGJPX";
251 #endif
253 flags = 0;
254 shellcmd = label = path = NULL;
255 envdata.path = NULL;
256 login_shell = (**argv == '-');
257 while ((opt = getopt(argc, argv, "28c:df:lL:qS:uUv")) != -1) {
258 switch (opt) {
259 case '2':
260 flags |= IDENTIFY_256COLOURS;
261 flags &= ~IDENTIFY_88COLOURS;
262 break;
263 case '8':
264 flags |= IDENTIFY_88COLOURS;
265 flags &= ~IDENTIFY_256COLOURS;
266 break;
267 case 'c':
268 if (shellcmd != NULL)
269 xfree(shellcmd);
270 shellcmd = xstrdup(optarg);
271 break;
272 case 'f':
273 if (cfg_file != NULL)
274 xfree(cfg_file);
275 cfg_file = xstrdup(optarg);
276 break;
277 case 'l':
278 login_shell = 1;
279 break;
280 case 'L':
281 if (label != NULL)
282 xfree(label);
283 label = xstrdup(optarg);
284 break;
285 case 'q':
286 quiet = 1;
287 break;
288 case 'S':
289 if (path != NULL)
290 xfree(path);
291 path = xstrdup(optarg);
292 break;
293 case 'u':
294 flags |= IDENTIFY_UTF8;
295 break;
296 case 'v':
297 debug_level++;
298 break;
299 default:
300 usage();
303 argc -= optind;
304 argv += optind;
306 if (shellcmd != NULL && argc != 0)
307 usage();
309 log_open_tty(debug_level);
311 if (!(flags & IDENTIFY_UTF8)) {
313 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
314 * exist (in that order) to contain UTF-8, it is a safe
315 * assumption that either they are using a UTF-8 terminal, or
316 * if not they know that output from UTF-8-capable programs may
317 * be wrong.
319 if ((s = getenv("LC_ALL")) == NULL) {
320 if ((s = getenv("LC_CTYPE")) == NULL)
321 s = getenv("LANG");
323 if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
324 strcasestr(s, "UTF8") != NULL))
325 flags |= IDENTIFY_UTF8;
328 environ_init(&global_environ);
329 for (var = environ; *var != NULL; var++)
330 environ_put(&global_environ, *var);
332 options_init(&global_options, NULL);
333 oo = &global_options;
334 options_set_number(oo, "quiet", quiet);
335 options_set_number(oo, "escape-time", 500);
337 options_init(&global_s_options, NULL);
338 so = &global_s_options;
339 options_set_number(so, "base-index", 0);
340 options_set_number(so, "bell-action", BELL_ANY);
341 options_set_number(so, "buffer-limit", 9);
342 options_set_string(so, "default-command", "%s", "");
343 options_set_string(so, "default-shell", "%s", getshell());
344 options_set_string(so, "default-terminal", "screen");
345 options_set_number(so, "display-panes-colour", 4);
346 options_set_number(so, "display-panes-active-colour", 1);
347 options_set_number(so, "display-panes-time", 1000);
348 options_set_number(so, "display-time", 750);
349 options_set_number(so, "history-limit", 2000);
350 options_set_number(so, "lock-after-time", 0);
351 options_set_string(so, "lock-command", "lock -np");
352 options_set_number(so, "lock-server", 1);
353 options_set_number(so, "message-attr", 0);
354 options_set_number(so, "message-bg", 3);
355 options_set_number(so, "message-fg", 0);
356 options_set_number(so, "message-limit", 20);
357 options_set_number(so, "mouse-select-pane", 0);
358 options_set_number(so, "pane-active-border-bg", 8);
359 options_set_number(so, "pane-active-border-fg", 2);
360 options_set_number(so, "pane-border-bg", 8);
361 options_set_number(so, "pane-border-fg", 8);
362 options_set_number(so, "repeat-time", 500);
363 options_set_number(so, "set-remain-on-exit", 0);
364 options_set_number(so, "set-titles", 0);
365 options_set_string(so, "set-titles-string", "#S:#I:#W - \"#T\"");
366 options_set_number(so, "status", 1);
367 options_set_number(so, "status-attr", 0);
368 options_set_number(so, "status-bg", 2);
369 options_set_number(so, "status-fg", 0);
370 options_set_number(so, "status-interval", 15);
371 options_set_number(so, "status-justify", 0);
372 options_set_number(so, "status-keys", MODEKEY_EMACS);
373 options_set_string(so, "status-left", "[#S]");
374 options_set_number(so, "status-left-attr", 0);
375 options_set_number(so, "status-left-bg", 8);
376 options_set_number(so, "status-left-fg", 8);
377 options_set_number(so, "status-left-length", 10);
378 options_set_string(so, "status-right", "\"#22T\" %%H:%%M %%d-%%b-%%y");
379 options_set_number(so, "status-right-attr", 0);
380 options_set_number(so, "status-right-bg", 8);
381 options_set_number(so, "status-right-fg", 8);
382 options_set_number(so, "status-right-length", 40);
383 options_set_string(so, "terminal-overrides",
384 "*88col*:colors=88,*256col*:colors=256");
385 options_set_string(so, "update-environment", "DISPLAY "
386 "WINDOWID SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION");
387 options_set_number(so, "visual-activity", 0);
388 options_set_number(so, "visual-bell", 0);
389 options_set_number(so, "visual-content", 0);
391 keylist = xmalloc(sizeof *keylist);
392 ARRAY_INIT(keylist);
393 ARRAY_ADD(keylist, '\002');
394 options_set_data(so, "prefix", keylist, xfree);
396 options_init(&global_w_options, NULL);
397 wo = &global_w_options;
398 options_set_number(wo, "aggressive-resize", 0);
399 options_set_number(wo, "alternate-screen", 1);
400 options_set_number(wo, "automatic-rename", 1);
401 options_set_number(wo, "clock-mode-colour", 4);
402 options_set_number(wo, "clock-mode-style", 1);
403 options_set_number(wo, "force-height", 0);
404 options_set_number(wo, "force-width", 0);
405 options_set_number(wo, "main-pane-height", 24);
406 options_set_number(wo, "main-pane-width", 81);
407 options_set_number(wo, "mode-attr", 0);
408 options_set_number(wo, "mode-bg", 3);
409 options_set_number(wo, "mode-fg", 0);
410 options_set_number(wo, "mode-keys", MODEKEY_EMACS);
411 options_set_number(wo, "mode-mouse", 0);
412 options_set_number(wo, "monitor-activity", 0);
413 options_set_string(wo, "monitor-content", "%s", "");
414 options_set_number(wo, "window-status-attr", 0);
415 options_set_number(wo, "window-status-bg", 8);
416 options_set_number(wo, "window-status-current-attr", 0);
417 options_set_number(wo, "window-status-current-bg", 8);
418 options_set_number(wo, "window-status-current-fg", 8);
419 options_set_number(wo, "window-status-fg", 8);
420 options_set_string(wo, "window-status-format", "#I:#W#F");
421 options_set_string(wo, "window-status-current-format", "#I:#W#F");
422 options_set_string(wo, "word-separators", " -_@");
423 options_set_number(wo, "xterm-keys", 0);
424 options_set_number(wo, "remain-on-exit", 0);
425 options_set_number(wo, "synchronize-panes", 0);
427 if (flags & IDENTIFY_UTF8) {
428 options_set_number(so, "status-utf8", 1);
429 options_set_number(wo, "utf8", 1);
430 } else {
431 options_set_number(so, "status-utf8", 0);
432 options_set_number(wo, "utf8", 0);
435 if (getcwd(cwd, sizeof cwd) == NULL) {
436 pw = getpwuid(getuid());
437 if (pw->pw_dir != NULL && *pw->pw_dir != '\0')
438 strlcpy(cwd, pw->pw_dir, sizeof cwd);
439 else
440 strlcpy(cwd, "/", sizeof cwd);
442 options_set_string(so, "default-path", "%s", cwd);
444 if (cfg_file == NULL) {
445 home = getenv("HOME");
446 if (home == NULL || *home == '\0') {
447 pw = getpwuid(getuid());
448 if (pw != NULL)
449 home = pw->pw_dir;
451 xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
452 if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
453 xfree(cfg_file);
454 cfg_file = NULL;
459 * Figure out the socket path. If specified on the command-line with
460 * -S or -L, use it, otherwise try $TMUX or assume -L default.
462 parse_env(&envdata);
463 if (path == NULL) {
464 /* No -L. Try $TMUX, or default. */
465 if (label == NULL) {
466 path = envdata.path;
467 if (path == NULL)
468 label = xstrdup("default");
471 /* -L or default set. */
472 if (label != NULL) {
473 if ((path = makesockpath(label)) == NULL) {
474 log_warn("can't create socket");
475 exit(1);
479 if (label != NULL)
480 xfree(label);
482 if (shellcmd != NULL) {
483 msg = MSG_SHELL;
484 buf = NULL;
485 len = 0;
486 } else {
487 cmddata.pid = envdata.pid;
488 cmddata.idx = envdata.idx;
490 /* Prepare command for server. */
491 cmddata.argc = argc;
492 if (cmd_pack_argv(
493 argc, argv, cmddata.argv, sizeof cmddata.argv) != 0) {
494 log_warnx("command too long");
495 exit(1);
498 msg = MSG_COMMAND;
499 buf = &cmddata;
500 len = sizeof cmddata;
503 if (shellcmd != NULL)
504 cmdflags |= CMD_STARTSERVER;
505 else if (argc == 0) /* new-session is the default */
506 cmdflags |= CMD_STARTSERVER|CMD_SENDENVIRON|CMD_CANTNEST;
507 else {
509 * It sucks parsing the command string twice (in client and
510 * later in server) but it is necessary to get the start server
511 * flag.
513 if ((cmdlist = cmd_list_parse(argc, argv, &cause)) == NULL) {
514 log_warnx("%s", cause);
515 exit(1);
517 cmdflags &= ~CMD_STARTSERVER;
518 TAILQ_FOREACH(cmd, cmdlist, qentry) {
519 if (cmd->entry->flags & CMD_STARTSERVER)
520 cmdflags |= CMD_STARTSERVER;
521 if (cmd->entry->flags & CMD_SENDENVIRON)
522 cmdflags |= CMD_SENDENVIRON;
523 if (cmd->entry->flags & CMD_CANTNEST)
524 cmdflags |= CMD_CANTNEST;
526 cmd_list_free(cmdlist);
530 * Check if this could be a nested session, if the command can't nest:
531 * if the socket path matches $TMUX, this is probably the same server.
533 if (shellcmd == NULL && envdata.path != NULL &&
534 cmdflags & CMD_CANTNEST &&
535 (path == envdata.path || strcmp(path, envdata.path) == 0)) {
536 log_warnx("sessions should be nested with care. "
537 "unset $TMUX to force.");
538 exit(1);
541 /* Catch SIGCHLD to avoid a zombie when starting the server. */
542 memset(&sigact, 0, sizeof sigact);
543 sigemptyset(&sigact.sa_mask);
544 sigact.sa_handler = SIG_IGN;
545 if (sigaction(SIGCHLD, &sigact, NULL) != 0)
546 fatal("sigaction failed");
548 /* Initialise the client socket/start the server. */
549 if ((main_ibuf = client_init(path, cmdflags, flags)) == NULL)
550 exit(1);
551 xfree(path);
553 event_init();
555 imsg_compose(main_ibuf, msg, PROTOCOL_VERSION, -1, -1, buf, len);
557 main_set_signals();
559 events = EV_READ;
560 if (main_ibuf->w.queued > 0)
561 events |= EV_WRITE;
562 event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
564 main_exitval = 0;
565 event_dispatch();
567 main_clear_signals();
569 client_main(); /* doesn't return */
572 void
573 main_set_signals(void)
575 struct sigaction sigact;
577 memset(&sigact, 0, sizeof sigact);
578 sigemptyset(&sigact.sa_mask);
579 sigact.sa_flags = SA_RESTART;
580 sigact.sa_handler = SIG_IGN;
581 if (sigaction(SIGINT, &sigact, NULL) != 0)
582 fatal("sigaction failed");
583 if (sigaction(SIGPIPE, &sigact, NULL) != 0)
584 fatal("sigaction failed");
585 if (sigaction(SIGUSR1, &sigact, NULL) != 0)
586 fatal("sigaction failed");
587 if (sigaction(SIGUSR2, &sigact, NULL) != 0)
588 fatal("sigaction failed");
589 if (sigaction(SIGTSTP, &sigact, NULL) != 0)
590 fatal("sigaction failed");
592 signal_set(&main_ev_sigterm, SIGTERM, main_signal, NULL);
593 signal_add(&main_ev_sigterm, NULL);
596 void
597 main_clear_signals(void)
599 struct sigaction sigact;
601 memset(&sigact, 0, sizeof sigact);
602 sigemptyset(&sigact.sa_mask);
603 sigact.sa_flags = SA_RESTART;
604 sigact.sa_handler = SIG_DFL;
605 if (sigaction(SIGINT, &sigact, NULL) != 0)
606 fatal("sigaction failed");
607 if (sigaction(SIGPIPE, &sigact, NULL) != 0)
608 fatal("sigaction failed");
609 if (sigaction(SIGUSR1, &sigact, NULL) != 0)
610 fatal("sigaction failed");
611 if (sigaction(SIGUSR2, &sigact, NULL) != 0)
612 fatal("sigaction failed");
613 if (sigaction(SIGTSTP, &sigact, NULL) != 0)
614 fatal("sigaction failed");
616 event_del(&main_ev_sigterm);
619 /* ARGSUSED */
620 void
621 main_signal(int sig, unused short events, unused void *data)
623 switch (sig) {
624 case SIGTERM:
625 exit(1);
629 /* ARGSUSED */
630 void
631 main_callback(unused int fd, short events, void *data)
633 char *shellcmd = data;
635 if (events & EV_READ)
636 main_dispatch(shellcmd);
638 if (events & EV_WRITE) {
639 if (msgbuf_write(&main_ibuf->w) < 0)
640 fatalx("msgbuf_write failed");
643 events = EV_READ;
644 if (main_ibuf->w.queued > 0)
645 events |= EV_WRITE;
646 event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
649 void
650 main_dispatch(const char *shellcmd)
652 struct imsg imsg;
653 ssize_t n, datalen;
654 struct msg_print_data printdata;
655 struct msg_shell_data shelldata;
657 if ((n = imsg_read(main_ibuf)) == -1 || n == 0)
658 fatalx("imsg_read failed");
660 for (;;) {
661 if ((n = imsg_get(main_ibuf, &imsg)) == -1)
662 fatalx("imsg_get failed");
663 if (n == 0)
664 return;
665 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
667 switch (imsg.hdr.type) {
668 case MSG_EXIT:
669 case MSG_SHUTDOWN:
670 if (datalen != 0)
671 fatalx("bad MSG_EXIT size");
673 exit(main_exitval);
674 case MSG_ERROR:
675 case MSG_PRINT:
676 if (datalen != sizeof printdata)
677 fatalx("bad MSG_PRINT size");
678 memcpy(&printdata, imsg.data, sizeof printdata);
679 printdata.msg[(sizeof printdata.msg) - 1] = '\0';
681 log_info("%s", printdata.msg);
682 if (imsg.hdr.type == MSG_ERROR)
683 main_exitval = 1;
684 break;
685 case MSG_READY:
686 if (datalen != 0)
687 fatalx("bad MSG_READY size");
689 event_loopexit(NULL); /* move to client_main() */
690 break;
691 case MSG_VERSION:
692 if (datalen != 0)
693 fatalx("bad MSG_VERSION size");
695 log_warnx("protocol version mismatch (client %u, "
696 "server %u)", PROTOCOL_VERSION, imsg.hdr.peerid);
697 exit(1);
698 case MSG_SHELL:
699 if (datalen != sizeof shelldata)
700 fatalx("bad MSG_SHELL size");
701 memcpy(&shelldata, imsg.data, sizeof shelldata);
702 shelldata.shell[(sizeof shelldata.shell) - 1] = '\0';
704 main_clear_signals();
706 shell_exec(shelldata.shell, shellcmd);
707 default:
708 fatalx("unexpected message");
711 imsg_free(&imsg);