xref: /openbsd-src/usr.bin/tmux/tmux.c (revision 57fbede61a07780ace8600ea11c09e2bdafb3612)
1 /* $OpenBSD: tmux.c,v 1.85 2010/07/24 19:25:31 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
5  *
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.
9  *
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.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
22 
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>
32 
33 #include "tmux.h"
34 
35 #ifdef DEBUG
36 extern char	*malloc_options;
37 #endif
38 
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;
44 
45 struct event_base *ev_base;
46 
47 int		 debug_level;
48 time_t		 start_time;
49 char		*socket_path;
50 int		 login_shell;
51 
52 struct env_data {
53 	char	*path;
54 	pid_t	 pid;
55 	u_int	 idx;
56 };
57 
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 *);
62 
63 struct imsgbuf	*main_ibuf;
64 
65 void		 main_signal(int, short, unused void *);
66 void		 main_callback(int, short, void *);
67 void		 main_dispatch(const char *);
68 
69 __dead void
70 usage(void)
71 {
72 	fprintf(stderr,
73 	    "usage: %s [-28lquv] [-c shell-command] [-f file] [-L socket-name]\n"
74 	    "            [-S socket-path] [command [flags]]\n",
75 	    __progname);
76 	exit(1);
77 }
78 
79 void
80 logfile(const char *name)
81 {
82 	char	*path;
83 
84 	log_close();
85 	if (debug_level > 0) {
86 		xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
87 		log_open_file(debug_level, path);
88 		xfree(path);
89 	}
90 }
91 
92 const char *
93 getshell(void)
94 {
95 	struct passwd	*pw;
96 	const char	*shell;
97 
98 	shell = getenv("SHELL");
99 	if (checkshell(shell))
100 		return (shell);
101 
102 	pw = getpwuid(getuid());
103 	if (pw != NULL && checkshell(pw->pw_shell))
104 		return (pw->pw_shell);
105 
106 	return (_PATH_BSHELL);
107 }
108 
109 int
110 checkshell(const char *shell)
111 {
112 	if (shell == NULL || *shell == '\0' || areshell(shell))
113 		return (0);
114 	if (access(shell, X_OK) != 0)
115 		return (0);
116 	return (1);
117 }
118 
119 int
120 areshell(const char *shell)
121 {
122 	const char	*progname, *ptr;
123 
124 	if ((ptr = strrchr(shell, '/')) != NULL)
125 		ptr++;
126 	else
127 		ptr = shell;
128 	progname = __progname;
129 	if (*progname == '-')
130 		progname++;
131 	if (strcmp(ptr, progname) == 0)
132 		return (1);
133 	return (0);
134 }
135 
136 void
137 parse_env(struct env_data *data)
138 {
139 	char		*env, *path_pid, *pid_idx, buf[256];
140 	size_t		 len;
141 	const char	*errstr;
142 	long long	 ll;
143 
144 	data->pid = -1;
145 	if ((env = getenv("TMUX")) == NULL)
146 		return;
147 
148 	if ((path_pid = strchr(env, ',')) == NULL || path_pid == env)
149 		return;
150 	if ((pid_idx = strchr(path_pid + 1, ',')) == NULL)
151 		return;
152 	if ((pid_idx == path_pid + 1 || pid_idx[1] == '\0'))
153 		return;
154 
155 	/* path */
156 	len = path_pid - env;
157 	data->path = xmalloc (len + 1);
158 	memcpy(data->path, env, len);
159 	data->path[len] = '\0';
160 
161 	/* pid */
162 	len = pid_idx - path_pid - 1;
163 	if (len > (sizeof buf) - 1)
164 		return;
165 	memcpy(buf, path_pid + 1, len);
166 	buf[len] = '\0';
167 
168 	ll = strtonum(buf, 0, LONG_MAX, &errstr);
169 	if (errstr != NULL)
170 		return;
171 	data->pid = ll;
172 
173 	/* idx */
174 	ll = strtonum(pid_idx+1, 0, UINT_MAX, &errstr);
175 	if (errstr != NULL)
176 		return;
177 	data->idx = ll;
178 }
179 
180 char *
181 makesockpath(const char *label)
182 {
183 	char		base[MAXPATHLEN], *path;
184 	struct stat	sb;
185 	u_int		uid;
186 
187 	uid = getuid();
188 	xsnprintf(base, MAXPATHLEN, "%s/tmux-%d", _PATH_TMP, uid);
189 
190 	if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST)
191 		return (NULL);
192 
193 	if (lstat(base, &sb) != 0)
194 		return (NULL);
195 	if (!S_ISDIR(sb.st_mode)) {
196 		errno = ENOTDIR;
197 		return (NULL);
198 	}
199 	if (sb.st_uid != uid || (sb.st_mode & (S_IRWXG|S_IRWXO)) != 0) {
200 		errno = EACCES;
201 		return (NULL);
202 	}
203 
204 	xasprintf(&path, "%s/%s", base, label);
205 	return (path);
206 }
207 
208 __dead void
209 shell_exec(const char *shell, const char *shellcmd)
210 {
211 	const char	*shellname, *ptr;
212 	char		*argv0;
213 
214 	ptr = strrchr(shell, '/');
215 	if (ptr != NULL && *(ptr + 1) != '\0')
216 		shellname = ptr + 1;
217 	else
218 		shellname = shell;
219 	if (login_shell)
220 		xasprintf(&argv0, "-%s", shellname);
221 	else
222 		xasprintf(&argv0, "%s", shellname);
223 	setenv("SHELL", shell, 1);
224 
225 	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
226 	fatal("execl failed");
227 }
228 
229 int
230 main(int argc, char **argv)
231 {
232 	struct cmd_list		*cmdlist;
233 	struct cmd		*cmd;
234 	enum msgtype		 msg;
235 	struct passwd		*pw;
236 	struct options		*oo, *so, *wo;
237 	struct keylist		*keylist;
238 	struct env_data		 envdata;
239 	struct msg_command_data	 cmddata;
240 	char			*s, *shellcmd, *path, *label, *home, *cause;
241 	char		       **var;
242 	void			*buf;
243 	size_t			 len;
244 	int	 		 opt, flags, quiet = 0, cmdflags = 0;
245 	short		 	 events;
246 
247 #ifdef DEBUG
248 	malloc_options = (char *) "AFGJPX";
249 #endif
250 
251 	flags = 0;
252 	shellcmd = label = path = NULL;
253 	envdata.path = NULL;
254 	login_shell = (**argv == '-');
255 	while ((opt = getopt(argc, argv, "28c:df:lL:qS:uUv")) != -1) {
256 		switch (opt) {
257 		case '2':
258 			flags |= IDENTIFY_256COLOURS;
259 			flags &= ~IDENTIFY_88COLOURS;
260 			break;
261 		case '8':
262 			flags |= IDENTIFY_88COLOURS;
263 			flags &= ~IDENTIFY_256COLOURS;
264 			break;
265 		case 'c':
266 			if (shellcmd != NULL)
267 				xfree(shellcmd);
268 			shellcmd = xstrdup(optarg);
269 			break;
270 		case 'f':
271 			if (cfg_file != NULL)
272 				xfree(cfg_file);
273 			cfg_file = xstrdup(optarg);
274 			break;
275 		case 'l':
276 			login_shell = 1;
277 			break;
278 		case 'L':
279 			if (label != NULL)
280 				xfree(label);
281 			label = xstrdup(optarg);
282 			break;
283 		case 'q':
284 			quiet = 1;
285 			break;
286 		case 'S':
287 			if (path != NULL)
288 				xfree(path);
289 			path = xstrdup(optarg);
290 			break;
291 		case 'u':
292 			flags |= IDENTIFY_UTF8;
293 			break;
294 		case 'v':
295 			debug_level++;
296 			break;
297 		default:
298 			usage();
299 		}
300 	}
301 	argc -= optind;
302 	argv += optind;
303 
304 	if (shellcmd != NULL && argc != 0)
305 		usage();
306 
307 	log_open_tty(debug_level);
308 
309 	if (!(flags & IDENTIFY_UTF8)) {
310 		/*
311 		 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
312 		 * exist (in that order) to contain UTF-8, it is a safe
313 		 * assumption that either they are using a UTF-8 terminal, or
314 		 * if not they know that output from UTF-8-capable programs may
315 		 * be wrong.
316 		 */
317 		if ((s = getenv("LC_ALL")) == NULL) {
318 			if ((s = getenv("LC_CTYPE")) == NULL)
319 				s = getenv("LANG");
320 		}
321 		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
322 		    strcasestr(s, "UTF8") != NULL))
323 			flags |= IDENTIFY_UTF8;
324 	}
325 
326 	environ_init(&global_environ);
327 	for (var = environ; *var != NULL; var++)
328 		environ_put(&global_environ, *var);
329 
330 	options_init(&global_options, NULL);
331 	oo = &global_options;
332 	options_set_number(oo, "quiet", quiet);
333 	options_set_number(oo, "escape-time", 500);
334 
335 	options_init(&global_s_options, NULL);
336 	so = &global_s_options;
337 	options_set_number(so, "base-index", 0);
338 	options_set_number(so, "bell-action", BELL_ANY);
339 	options_set_number(so, "buffer-limit", 9);
340 	options_set_string(so, "default-command", "%s", "");
341 	options_set_string(so, "default-path", "%s", "");
342 	options_set_string(so, "default-shell", "%s", getshell());
343 	options_set_string(so, "default-terminal", "screen");
344 	options_set_number(so, "detach-on-destroy", 1);
345 	options_set_number(so, "display-panes-active-colour", 1);
346 	options_set_number(so, "display-panes-colour", 4);
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);
390 
391 	keylist = xmalloc(sizeof *keylist);
392 	ARRAY_INIT(keylist);
393 	ARRAY_ADD(keylist, '\002');
394 	options_set_data(so, "prefix", keylist, xfree);
395 
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_number(wo, "window-status-alert-attr", GRID_ATTR_REVERSE);
421 	options_set_number(wo, "window-status-alert-bg", 8);
422 	options_set_number(wo, "window-status-alert-fg", 8);
423 	options_set_string(wo, "window-status-format", "#I:#W#F");
424 	options_set_string(wo, "window-status-current-format", "#I:#W#F");
425 	options_set_string(wo, "word-separators", " -_@");
426 	options_set_number(wo, "xterm-keys", 0);
427 	options_set_number(wo, "remain-on-exit", 0);
428 	options_set_number(wo, "synchronize-panes", 0);
429 
430 	if (flags & IDENTIFY_UTF8) {
431 		options_set_number(so, "status-utf8", 1);
432 		options_set_number(wo, "utf8", 1);
433 	} else {
434 		options_set_number(so, "status-utf8", 0);
435 		options_set_number(wo, "utf8", 0);
436 	}
437 
438 	if (cfg_file == NULL) {
439 		home = getenv("HOME");
440 		if (home == NULL || *home == '\0') {
441 			pw = getpwuid(getuid());
442 			if (pw != NULL)
443 				home = pw->pw_dir;
444 		}
445 		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
446 		if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
447 			xfree(cfg_file);
448 			cfg_file = NULL;
449 		}
450 	}
451 
452 	/*
453 	 * Figure out the socket path. If specified on the command-line with
454 	 * -S or -L, use it, otherwise try $TMUX or assume -L default.
455 	 */
456 	parse_env(&envdata);
457 	if (path == NULL) {
458 		/* No -L. Try $TMUX, or default. */
459 		if (label == NULL) {
460 			path = envdata.path;
461 			if (path == NULL)
462 				label = xstrdup("default");
463 		}
464 
465 		/* -L or default set. */
466 		if (label != NULL) {
467 			if ((path = makesockpath(label)) == NULL) {
468 				log_warn("can't create socket");
469 				exit(1);
470 			}
471 		}
472 	}
473 	if (label != NULL)
474 		xfree(label);
475 
476 	if (shellcmd != NULL) {
477 		msg = MSG_SHELL;
478 		buf = NULL;
479 		len = 0;
480 	} else {
481 		cmddata.pid = envdata.pid;
482 		cmddata.idx = envdata.idx;
483 
484 		/* Prepare command for server. */
485 		cmddata.argc = argc;
486 		if (cmd_pack_argv(
487 		    argc, argv, cmddata.argv, sizeof cmddata.argv) != 0) {
488 			log_warnx("command too long");
489 			exit(1);
490 		}
491 
492 		msg = MSG_COMMAND;
493 		buf = &cmddata;
494 		len = sizeof cmddata;
495 	}
496 
497 	if (shellcmd != NULL)
498 		cmdflags |= CMD_STARTSERVER;
499 	else if (argc == 0)	/* new-session is the default */
500 		cmdflags |= CMD_STARTSERVER|CMD_SENDENVIRON|CMD_CANTNEST;
501 	else {
502 		/*
503 		 * It sucks parsing the command string twice (in client and
504 		 * later in server) but it is necessary to get the start server
505 		 * flag.
506 		 */
507 		if ((cmdlist = cmd_list_parse(argc, argv, &cause)) == NULL) {
508 			log_warnx("%s", cause);
509 			exit(1);
510 		}
511 		cmdflags &= ~CMD_STARTSERVER;
512 		TAILQ_FOREACH(cmd, &cmdlist->list, qentry) {
513 			if (cmd->entry->flags & CMD_STARTSERVER)
514 				cmdflags |= CMD_STARTSERVER;
515 			if (cmd->entry->flags & CMD_SENDENVIRON)
516 				cmdflags |= CMD_SENDENVIRON;
517 			if (cmd->entry->flags & CMD_CANTNEST)
518 				cmdflags |= CMD_CANTNEST;
519 		}
520 		cmd_list_free(cmdlist);
521 	}
522 
523 	/*
524 	 * Check if this could be a nested session, if the command can't nest:
525 	 * if the socket path matches $TMUX, this is probably the same server.
526 	 */
527 	if (shellcmd == NULL && envdata.path != NULL &&
528 	    cmdflags & CMD_CANTNEST &&
529 	    (path == envdata.path || strcmp(path, envdata.path) == 0)) {
530 		log_warnx("sessions should be nested with care. "
531 		    "unset $TMUX to force.");
532 		exit(1);
533 	}
534 
535 	if (setenv("EVENT_NOKQUEUE", "1", 1) != 0)
536 		fatal("setenv");
537 	ev_base = event_init();
538 	unsetenv("EVENT_NOKQUEUE");
539 	set_signals(main_signal);
540 
541 	/* Initialise the client socket/start the server. */
542 	if ((main_ibuf = client_init(path, cmdflags, flags)) == NULL)
543 		exit(1);
544 	xfree(path);
545 
546 	imsg_compose(main_ibuf, msg, PROTOCOL_VERSION, -1, -1, buf, len);
547 
548 	events = EV_READ;
549 	if (main_ibuf->w.queued > 0)
550 		events |= EV_WRITE;
551 	event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
552 
553 	event_dispatch();
554 
555 	clear_signals();
556 
557 	client_main();	/* doesn't return */
558 }
559 
560 /* ARGSUSED */
561 void
562 main_signal(int sig, unused short events, unused void *data)
563 {
564 	int	status;
565 
566 	switch (sig) {
567 	case SIGTERM:
568 		exit(1);
569 	case SIGCHLD:
570 		waitpid(WAIT_ANY, &status, WNOHANG);
571 		break;
572 	}
573 }
574 
575 /* ARGSUSED */
576 void
577 main_callback(unused int fd, short events, void *data)
578 {
579 	char	*shellcmd = data;
580 
581 	if (events & EV_READ)
582 		main_dispatch(shellcmd);
583 
584 	if (events & EV_WRITE) {
585 		if (msgbuf_write(&main_ibuf->w) < 0)
586 			fatalx("msgbuf_write failed");
587 	}
588 
589 	events = EV_READ;
590 	if (main_ibuf->w.queued > 0)
591 		events |= EV_WRITE;
592 	event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
593 }
594 
595 void
596 main_dispatch(const char *shellcmd)
597 {
598 	struct imsg		imsg;
599 	ssize_t			n, datalen;
600 	struct msg_shell_data	shelldata;
601 	struct msg_exit_data	exitdata;
602 
603 	if ((n = imsg_read(main_ibuf)) == -1 || n == 0)
604 		fatalx("imsg_read failed");
605 
606 	for (;;) {
607 		if ((n = imsg_get(main_ibuf, &imsg)) == -1)
608 			fatalx("imsg_get failed");
609 		if (n == 0)
610 			return;
611 		datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
612 
613 		switch (imsg.hdr.type) {
614 		case MSG_EXIT:
615 		case MSG_SHUTDOWN:
616 			if (datalen != sizeof exitdata) {
617 				if (datalen != 0)
618 					fatalx("bad MSG_EXIT size");
619 				exit(0);
620 			}
621 			memcpy(&exitdata, imsg.data, sizeof exitdata);
622 			exit(exitdata.retcode);
623 		case MSG_READY:
624 			if (datalen != 0)
625 				fatalx("bad MSG_READY size");
626 
627 			event_loopexit(NULL);	/* move to client_main() */
628 			break;
629 		case MSG_VERSION:
630 			if (datalen != 0)
631 				fatalx("bad MSG_VERSION size");
632 
633 			log_warnx("protocol version mismatch (client %u, "
634 			    "server %u)", PROTOCOL_VERSION, imsg.hdr.peerid);
635 			exit(1);
636 		case MSG_SHELL:
637 			if (datalen != sizeof shelldata)
638 				fatalx("bad MSG_SHELL size");
639 			memcpy(&shelldata, imsg.data, sizeof shelldata);
640 			shelldata.shell[(sizeof shelldata.shell) - 1] = '\0';
641 
642 			clear_signals();
643 
644 			shell_exec(shelldata.shell, shellcmd);
645 		default:
646 			fatalx("unexpected message");
647 		}
648 
649 		imsg_free(&imsg);
650 	}
651 }
652