Add a missing command and some missing Ic, from Tiago Cunha.
[tmux-openbsd.git] / tmux.c
blob28f822ce4e6a93f8a3745b89b0b8f5cb63cd431c
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>
21 #include <sys/wait.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <paths.h>
26 #include <pwd.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <syslog.h>
31 #include <unistd.h>
33 #include "tmux.h"
35 #ifdef DEBUG
36 extern char *malloc_options;
37 #endif
39 char *cfg_file;
40 struct options global_options; /* server options */
41 struct options global_s_options; /* session options */
42 struct options global_w_options; /* window options */
43 struct environ global_environ;
45 struct event_base *ev_base;
47 int debug_level;
48 time_t start_time;
49 char *socket_path;
50 int login_shell;
52 struct env_data {
53 char *path;
54 pid_t pid;
55 u_int idx;
58 __dead void usage(void);
59 void parse_env(struct env_data *);
60 char *makesockpath(const char *);
61 __dead void shell_exec(const char *, const char *);
63 struct imsgbuf *main_ibuf;
64 int main_exitval;
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 char *s, *shellcmd, *path, *label, *home, *cause;
242 char cwd[MAXPATHLEN], **var;
243 void *buf;
244 size_t len;
245 int opt, flags, quiet = 0, cmdflags = 0;
246 short events;
248 #ifdef DEBUG
249 malloc_options = (char *) "AFGJPX";
250 #endif
252 flags = 0;
253 shellcmd = label = path = NULL;
254 envdata.path = NULL;
255 login_shell = (**argv == '-');
256 while ((opt = getopt(argc, argv, "28c:df:lL:qS:uUv")) != -1) {
257 switch (opt) {
258 case '2':
259 flags |= IDENTIFY_256COLOURS;
260 flags &= ~IDENTIFY_88COLOURS;
261 break;
262 case '8':
263 flags |= IDENTIFY_88COLOURS;
264 flags &= ~IDENTIFY_256COLOURS;
265 break;
266 case 'c':
267 if (shellcmd != NULL)
268 xfree(shellcmd);
269 shellcmd = xstrdup(optarg);
270 break;
271 case 'f':
272 if (cfg_file != NULL)
273 xfree(cfg_file);
274 cfg_file = xstrdup(optarg);
275 break;
276 case 'l':
277 login_shell = 1;
278 break;
279 case 'L':
280 if (label != NULL)
281 xfree(label);
282 label = xstrdup(optarg);
283 break;
284 case 'q':
285 quiet = 1;
286 break;
287 case 'S':
288 if (path != NULL)
289 xfree(path);
290 path = xstrdup(optarg);
291 break;
292 case 'u':
293 flags |= IDENTIFY_UTF8;
294 break;
295 case 'v':
296 debug_level++;
297 break;
298 default:
299 usage();
302 argc -= optind;
303 argv += optind;
305 if (shellcmd != NULL && argc != 0)
306 usage();
308 log_open_tty(debug_level);
310 if (!(flags & IDENTIFY_UTF8)) {
312 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
313 * exist (in that order) to contain UTF-8, it is a safe
314 * assumption that either they are using a UTF-8 terminal, or
315 * if not they know that output from UTF-8-capable programs may
316 * be wrong.
318 if ((s = getenv("LC_ALL")) == NULL) {
319 if ((s = getenv("LC_CTYPE")) == NULL)
320 s = getenv("LANG");
322 if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
323 strcasestr(s, "UTF8") != NULL))
324 flags |= IDENTIFY_UTF8;
327 environ_init(&global_environ);
328 for (var = environ; *var != NULL; var++)
329 environ_put(&global_environ, *var);
331 options_init(&global_options, NULL);
332 oo = &global_options;
333 options_set_number(oo, "quiet", quiet);
334 options_set_number(oo, "escape-time", 500);
336 options_init(&global_s_options, NULL);
337 so = &global_s_options;
338 options_set_number(so, "base-index", 0);
339 options_set_number(so, "bell-action", BELL_ANY);
340 options_set_number(so, "buffer-limit", 9);
341 options_set_string(so, "default-command", "%s", "");
342 options_set_string(so, "default-shell", "%s", getshell());
343 options_set_string(so, "default-terminal", "screen");
344 options_set_number(so, "display-panes-colour", 4);
345 options_set_number(so, "display-panes-active-colour", 1);
346 options_set_number(so, "display-panes-time", 1000);
347 options_set_number(so, "display-time", 750);
348 options_set_number(so, "history-limit", 2000);
349 options_set_number(so, "lock-after-time", 0);
350 options_set_string(so, "lock-command", "lock -np");
351 options_set_number(so, "lock-server", 1);
352 options_set_number(so, "message-attr", 0);
353 options_set_number(so, "message-bg", 3);
354 options_set_number(so, "message-fg", 0);
355 options_set_number(so, "message-limit", 20);
356 options_set_number(so, "mouse-select-pane", 0);
357 options_set_number(so, "pane-active-border-bg", 8);
358 options_set_number(so, "pane-active-border-fg", 2);
359 options_set_number(so, "pane-border-bg", 8);
360 options_set_number(so, "pane-border-fg", 8);
361 options_set_number(so, "repeat-time", 500);
362 options_set_number(so, "set-remain-on-exit", 0);
363 options_set_number(so, "set-titles", 0);
364 options_set_string(so, "set-titles-string", "#S:#I:#W - \"#T\"");
365 options_set_number(so, "status", 1);
366 options_set_number(so, "status-attr", 0);
367 options_set_number(so, "status-bg", 2);
368 options_set_number(so, "status-fg", 0);
369 options_set_number(so, "status-interval", 15);
370 options_set_number(so, "status-justify", 0);
371 options_set_number(so, "status-keys", MODEKEY_EMACS);
372 options_set_string(so, "status-left", "[#S]");
373 options_set_number(so, "status-left-attr", 0);
374 options_set_number(so, "status-left-bg", 8);
375 options_set_number(so, "status-left-fg", 8);
376 options_set_number(so, "status-left-length", 10);
377 options_set_string(so, "status-right", "\"#22T\" %%H:%%M %%d-%%b-%%y");
378 options_set_number(so, "status-right-attr", 0);
379 options_set_number(so, "status-right-bg", 8);
380 options_set_number(so, "status-right-fg", 8);
381 options_set_number(so, "status-right-length", 40);
382 options_set_string(so, "terminal-overrides",
383 "*88col*:colors=88,*256col*:colors=256");
384 options_set_string(so, "update-environment", "DISPLAY "
385 "WINDOWID SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION");
386 options_set_number(so, "visual-activity", 0);
387 options_set_number(so, "visual-bell", 0);
388 options_set_number(so, "visual-content", 0);
390 keylist = xmalloc(sizeof *keylist);
391 ARRAY_INIT(keylist);
392 ARRAY_ADD(keylist, '\002');
393 options_set_data(so, "prefix", keylist, xfree);
395 options_init(&global_w_options, NULL);
396 wo = &global_w_options;
397 options_set_number(wo, "aggressive-resize", 0);
398 options_set_number(wo, "alternate-screen", 1);
399 options_set_number(wo, "automatic-rename", 1);
400 options_set_number(wo, "clock-mode-colour", 4);
401 options_set_number(wo, "clock-mode-style", 1);
402 options_set_number(wo, "force-height", 0);
403 options_set_number(wo, "force-width", 0);
404 options_set_number(wo, "main-pane-height", 24);
405 options_set_number(wo, "main-pane-width", 81);
406 options_set_number(wo, "mode-attr", 0);
407 options_set_number(wo, "mode-bg", 3);
408 options_set_number(wo, "mode-fg", 0);
409 options_set_number(wo, "mode-keys", MODEKEY_EMACS);
410 options_set_number(wo, "mode-mouse", 0);
411 options_set_number(wo, "monitor-activity", 0);
412 options_set_string(wo, "monitor-content", "%s", "");
413 options_set_number(wo, "window-status-attr", 0);
414 options_set_number(wo, "window-status-bg", 8);
415 options_set_number(wo, "window-status-current-attr", 0);
416 options_set_number(wo, "window-status-current-bg", 8);
417 options_set_number(wo, "window-status-current-fg", 8);
418 options_set_number(wo, "window-status-fg", 8);
419 options_set_number(wo, "window-status-alert-attr", GRID_ATTR_REVERSE);
420 options_set_number(wo, "window-status-alert-bg", 8);
421 options_set_number(wo, "window-status-alert-fg", 8);
422 options_set_string(wo, "window-status-format", "#I:#W#F");
423 options_set_string(wo, "window-status-current-format", "#I:#W#F");
424 options_set_string(wo, "word-separators", " -_@");
425 options_set_number(wo, "xterm-keys", 0);
426 options_set_number(wo, "remain-on-exit", 0);
427 options_set_number(wo, "synchronize-panes", 0);
429 if (flags & IDENTIFY_UTF8) {
430 options_set_number(so, "status-utf8", 1);
431 options_set_number(wo, "utf8", 1);
432 } else {
433 options_set_number(so, "status-utf8", 0);
434 options_set_number(wo, "utf8", 0);
437 if (getcwd(cwd, sizeof cwd) == NULL) {
438 pw = getpwuid(getuid());
439 if (pw->pw_dir != NULL && *pw->pw_dir != '\0')
440 strlcpy(cwd, pw->pw_dir, sizeof cwd);
441 else
442 strlcpy(cwd, "/", sizeof cwd);
444 options_set_string(so, "default-path", "%s", cwd);
446 if (cfg_file == NULL) {
447 home = getenv("HOME");
448 if (home == NULL || *home == '\0') {
449 pw = getpwuid(getuid());
450 if (pw != NULL)
451 home = pw->pw_dir;
453 xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
454 if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
455 xfree(cfg_file);
456 cfg_file = NULL;
461 * Figure out the socket path. If specified on the command-line with
462 * -S or -L, use it, otherwise try $TMUX or assume -L default.
464 parse_env(&envdata);
465 if (path == NULL) {
466 /* No -L. Try $TMUX, or default. */
467 if (label == NULL) {
468 path = envdata.path;
469 if (path == NULL)
470 label = xstrdup("default");
473 /* -L or default set. */
474 if (label != NULL) {
475 if ((path = makesockpath(label)) == NULL) {
476 log_warn("can't create socket");
477 exit(1);
481 if (label != NULL)
482 xfree(label);
484 if (shellcmd != NULL) {
485 msg = MSG_SHELL;
486 buf = NULL;
487 len = 0;
488 } else {
489 cmddata.pid = envdata.pid;
490 cmddata.idx = envdata.idx;
492 /* Prepare command for server. */
493 cmddata.argc = argc;
494 if (cmd_pack_argv(
495 argc, argv, cmddata.argv, sizeof cmddata.argv) != 0) {
496 log_warnx("command too long");
497 exit(1);
500 msg = MSG_COMMAND;
501 buf = &cmddata;
502 len = sizeof cmddata;
505 if (shellcmd != NULL)
506 cmdflags |= CMD_STARTSERVER;
507 else if (argc == 0) /* new-session is the default */
508 cmdflags |= CMD_STARTSERVER|CMD_SENDENVIRON|CMD_CANTNEST;
509 else {
511 * It sucks parsing the command string twice (in client and
512 * later in server) but it is necessary to get the start server
513 * flag.
515 if ((cmdlist = cmd_list_parse(argc, argv, &cause)) == NULL) {
516 log_warnx("%s", cause);
517 exit(1);
519 cmdflags &= ~CMD_STARTSERVER;
520 TAILQ_FOREACH(cmd, cmdlist, qentry) {
521 if (cmd->entry->flags & CMD_STARTSERVER)
522 cmdflags |= CMD_STARTSERVER;
523 if (cmd->entry->flags & CMD_SENDENVIRON)
524 cmdflags |= CMD_SENDENVIRON;
525 if (cmd->entry->flags & CMD_CANTNEST)
526 cmdflags |= CMD_CANTNEST;
528 cmd_list_free(cmdlist);
532 * Check if this could be a nested session, if the command can't nest:
533 * if the socket path matches $TMUX, this is probably the same server.
535 if (shellcmd == NULL && envdata.path != NULL &&
536 cmdflags & CMD_CANTNEST &&
537 (path == envdata.path || strcmp(path, envdata.path) == 0)) {
538 log_warnx("sessions should be nested with care. "
539 "unset $TMUX to force.");
540 exit(1);
543 ev_base = event_init();
544 set_signals(main_signal);
546 /* Initialise the client socket/start the server. */
547 if ((main_ibuf = client_init(path, cmdflags, flags)) == NULL)
548 exit(1);
549 xfree(path);
551 imsg_compose(main_ibuf, msg, PROTOCOL_VERSION, -1, -1, buf, len);
553 events = EV_READ;
554 if (main_ibuf->w.queued > 0)
555 events |= EV_WRITE;
556 event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
558 main_exitval = 0;
559 event_dispatch();
561 clear_signals();
563 client_main(); /* doesn't return */
566 /* ARGSUSED */
567 void
568 main_signal(int sig, unused short events, unused void *data)
570 int status;
572 switch (sig) {
573 case SIGTERM:
574 exit(1);
575 case SIGCHLD:
576 waitpid(WAIT_ANY, &status, WNOHANG);
577 break;
581 /* ARGSUSED */
582 void
583 main_callback(unused int fd, short events, void *data)
585 char *shellcmd = data;
587 if (events & EV_READ)
588 main_dispatch(shellcmd);
590 if (events & EV_WRITE) {
591 if (msgbuf_write(&main_ibuf->w) < 0)
592 fatalx("msgbuf_write failed");
595 events = EV_READ;
596 if (main_ibuf->w.queued > 0)
597 events |= EV_WRITE;
598 event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
601 void
602 main_dispatch(const char *shellcmd)
604 struct imsg imsg;
605 ssize_t n, datalen;
606 struct msg_print_data printdata;
607 struct msg_shell_data shelldata;
609 if ((n = imsg_read(main_ibuf)) == -1 || n == 0)
610 fatalx("imsg_read failed");
612 for (;;) {
613 if ((n = imsg_get(main_ibuf, &imsg)) == -1)
614 fatalx("imsg_get failed");
615 if (n == 0)
616 return;
617 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
619 switch (imsg.hdr.type) {
620 case MSG_EXIT:
621 case MSG_SHUTDOWN:
622 if (datalen != 0)
623 fatalx("bad MSG_EXIT size");
625 exit(main_exitval);
626 case MSG_ERROR:
627 case MSG_PRINT:
628 if (datalen != sizeof printdata)
629 fatalx("bad MSG_PRINT size");
630 memcpy(&printdata, imsg.data, sizeof printdata);
631 printdata.msg[(sizeof printdata.msg) - 1] = '\0';
633 log_info("%s", printdata.msg);
634 if (imsg.hdr.type == MSG_ERROR)
635 main_exitval = 1;
636 break;
637 case MSG_READY:
638 if (datalen != 0)
639 fatalx("bad MSG_READY size");
641 event_loopexit(NULL); /* move to client_main() */
642 break;
643 case MSG_VERSION:
644 if (datalen != 0)
645 fatalx("bad MSG_VERSION size");
647 log_warnx("protocol version mismatch (client %u, "
648 "server %u)", PROTOCOL_VERSION, imsg.hdr.peerid);
649 exit(1);
650 case MSG_SHELL:
651 if (datalen != sizeof shelldata)
652 fatalx("bad MSG_SHELL size");
653 memcpy(&shelldata, imsg.data, sizeof shelldata);
654 shelldata.shell[(sizeof shelldata.shell) - 1] = '\0';
656 clear_signals();
658 shell_exec(shelldata.shell, shellcmd);
659 default:
660 fatalx("unexpected message");
663 imsg_free(&imsg);