xref: /openbsd-src/usr.bin/tmux/tmux.c (revision 357766745fc3b9569b97549679da6320628eb37f)
1 /* $OpenBSD: tmux.c,v 1.88 2010/09/26 20:43:30 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 	options_set_number(oo, "exit-unattached", 0);
335 
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-path", "%s", "");
343 	options_set_string(so, "default-shell", "%s", getshell());
344 	options_set_string(so, "default-terminal", "screen");
345 	options_set_number(so, "destroy-unattached", 0);
346 	options_set_number(so, "detach-on-destroy", 1);
347 	options_set_number(so, "display-panes-active-colour", 1);
348 	options_set_number(so, "display-panes-colour", 4);
349 	options_set_number(so, "display-panes-time", 1000);
350 	options_set_number(so, "display-time", 750);
351 	options_set_number(so, "history-limit", 2000);
352 	options_set_number(so, "lock-after-time", 0);
353 	options_set_string(so, "lock-command", "lock -np");
354 	options_set_number(so, "lock-server", 1);
355 	options_set_number(so, "message-attr", 0);
356 	options_set_number(so, "message-bg", 3);
357 	options_set_number(so, "message-fg", 0);
358 	options_set_number(so, "message-limit", 20);
359 	options_set_number(so, "mouse-select-pane", 0);
360 	options_set_number(so, "pane-active-border-bg", 8);
361 	options_set_number(so, "pane-active-border-fg", 2);
362 	options_set_number(so, "pane-border-bg", 8);
363 	options_set_number(so, "pane-border-fg", 8);
364 	options_set_number(so, "repeat-time", 500);
365 	options_set_number(so, "set-remain-on-exit", 0);
366 	options_set_number(so, "set-titles", 0);
367 	options_set_string(so, "set-titles-string", "#S:#I:#W - \"#T\"");
368 	options_set_number(so, "status", 1);
369 	options_set_number(so, "status-attr", 0);
370 	options_set_number(so, "status-bg", 2);
371 	options_set_number(so, "status-fg", 0);
372 	options_set_number(so, "status-interval", 15);
373 	options_set_number(so, "status-justify", 0);
374 	options_set_number(so, "status-keys", MODEKEY_EMACS);
375 	options_set_string(so, "status-left", "[#S]");
376 	options_set_number(so, "status-left-attr", 0);
377 	options_set_number(so, "status-left-bg", 8);
378 	options_set_number(so, "status-left-fg", 8);
379 	options_set_number(so, "status-left-length", 10);
380 	options_set_string(so, "status-right", "\"#22T\" %%H:%%M %%d-%%b-%%y");
381 	options_set_number(so, "status-right-attr", 0);
382 	options_set_number(so, "status-right-bg", 8);
383 	options_set_number(so, "status-right-fg", 8);
384 	options_set_number(so, "status-right-length", 40);
385 	options_set_string(so, "terminal-overrides",
386 	    "*88col*:colors=88,*256col*:colors=256");
387 	options_set_string(so, "update-environment", "DISPLAY "
388 	    "WINDOWID SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION");
389 	options_set_number(so, "visual-activity", 0);
390 	options_set_number(so, "visual-bell", 0);
391 	options_set_number(so, "visual-content", 0);
392 
393 	keylist = xmalloc(sizeof *keylist);
394 	ARRAY_INIT(keylist);
395 	ARRAY_ADD(keylist, '\002');
396 	options_set_data(so, "prefix", keylist, xfree);
397 
398 	options_init(&global_w_options, NULL);
399 	wo = &global_w_options;
400 	options_set_number(wo, "aggressive-resize", 0);
401 	options_set_number(wo, "alternate-screen", 1);
402 	options_set_number(wo, "automatic-rename", 1);
403 	options_set_number(wo, "clock-mode-colour", 4);
404 	options_set_number(wo, "clock-mode-style", 1);
405 	options_set_number(wo, "force-height", 0);
406 	options_set_number(wo, "force-width", 0);
407 	options_set_number(wo, "main-pane-height", 24);
408 	options_set_number(wo, "main-pane-width", 81);
409 	options_set_number(wo, "mode-attr", 0);
410 	options_set_number(wo, "mode-bg", 3);
411 	options_set_number(wo, "mode-fg", 0);
412 	options_set_number(wo, "mode-keys", MODEKEY_EMACS);
413 	options_set_number(wo, "mode-mouse", 0);
414 	options_set_number(wo, "monitor-activity", 0);
415 	options_set_string(wo, "monitor-content", "%s", "");
416 	options_set_number(wo, "window-status-attr", 0);
417 	options_set_number(wo, "window-status-bg", 8);
418 	options_set_number(wo, "window-status-current-attr", 0);
419 	options_set_number(wo, "window-status-current-bg", 8);
420 	options_set_number(wo, "window-status-current-fg", 8);
421 	options_set_number(wo, "window-status-fg", 8);
422 	options_set_number(wo, "window-status-alert-attr", GRID_ATTR_REVERSE);
423 	options_set_number(wo, "window-status-alert-bg", 8);
424 	options_set_number(wo, "window-status-alert-fg", 8);
425 	options_set_string(wo, "window-status-format", "#I:#W#F");
426 	options_set_string(wo, "window-status-current-format", "#I:#W#F");
427 	options_set_string(wo, "word-separators", " -_@");
428 	options_set_number(wo, "xterm-keys", 0);
429 	options_set_number(wo, "remain-on-exit", 0);
430 	options_set_number(wo, "synchronize-panes", 0);
431 
432 	if (flags & IDENTIFY_UTF8) {
433 		options_set_number(so, "status-utf8", 1);
434 		options_set_number(wo, "utf8", 1);
435 	} else {
436 		options_set_number(so, "status-utf8", 0);
437 		options_set_number(wo, "utf8", 0);
438 	}
439 
440 	if (cfg_file == NULL) {
441 		home = getenv("HOME");
442 		if (home == NULL || *home == '\0') {
443 			pw = getpwuid(getuid());
444 			if (pw != NULL)
445 				home = pw->pw_dir;
446 		}
447 		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
448 		if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
449 			xfree(cfg_file);
450 			cfg_file = NULL;
451 		}
452 	}
453 
454 	/*
455 	 * Figure out the socket path. If specified on the command-line with
456 	 * -S or -L, use it, otherwise try $TMUX or assume -L default.
457 	 */
458 	parse_env(&envdata);
459 	if (path == NULL) {
460 		/* No -L. Try $TMUX, or default. */
461 		if (label == NULL) {
462 			path = envdata.path;
463 			if (path == NULL)
464 				label = xstrdup("default");
465 		}
466 
467 		/* -L or default set. */
468 		if (label != NULL) {
469 			if ((path = makesockpath(label)) == NULL) {
470 				log_warn("can't create socket");
471 				exit(1);
472 			}
473 		}
474 	}
475 	if (label != NULL)
476 		xfree(label);
477 
478 	if (shellcmd != NULL) {
479 		msg = MSG_SHELL;
480 		buf = NULL;
481 		len = 0;
482 	} else {
483 		cmddata.pid = envdata.pid;
484 		cmddata.idx = envdata.idx;
485 
486 		/* Prepare command for server. */
487 		cmddata.argc = argc;
488 		if (cmd_pack_argv(
489 		    argc, argv, cmddata.argv, sizeof cmddata.argv) != 0) {
490 			log_warnx("command too long");
491 			exit(1);
492 		}
493 
494 		msg = MSG_COMMAND;
495 		buf = &cmddata;
496 		len = sizeof cmddata;
497 	}
498 
499 	if (shellcmd != NULL)
500 		cmdflags |= CMD_STARTSERVER;
501 	else if (argc == 0)	/* new-session is the default */
502 		cmdflags |= CMD_STARTSERVER|CMD_SENDENVIRON|CMD_CANTNEST;
503 	else {
504 		/*
505 		 * It sucks parsing the command string twice (in client and
506 		 * later in server) but it is necessary to get the start server
507 		 * flag.
508 		 */
509 		if ((cmdlist = cmd_list_parse(argc, argv, &cause)) == NULL) {
510 			log_warnx("%s", cause);
511 			exit(1);
512 		}
513 		cmdflags &= ~CMD_STARTSERVER;
514 		TAILQ_FOREACH(cmd, &cmdlist->list, qentry) {
515 			if (cmd->entry->flags & CMD_STARTSERVER)
516 				cmdflags |= CMD_STARTSERVER;
517 			if (cmd->entry->flags & CMD_SENDENVIRON)
518 				cmdflags |= CMD_SENDENVIRON;
519 			if (cmd->entry->flags & CMD_CANTNEST)
520 				cmdflags |= CMD_CANTNEST;
521 		}
522 		cmd_list_free(cmdlist);
523 	}
524 
525 	/*
526 	 * Check if this could be a nested session, if the command can't nest:
527 	 * if the socket path matches $TMUX, this is probably the same server.
528 	 */
529 	if (shellcmd == NULL && envdata.path != NULL &&
530 	    cmdflags & CMD_CANTNEST &&
531 	    (path == envdata.path || strcmp(path, envdata.path) == 0)) {
532 		log_warnx("sessions should be nested with care. "
533 		    "unset $TMUX to force.");
534 		exit(1);
535 	}
536 
537 	ev_base = event_init();
538 	set_signals(main_signal);
539 
540 	/* Initialise the client socket/start the server. */
541 	if ((main_ibuf = client_init(path, cmdflags, flags)) == NULL)
542 		exit(1);
543 	xfree(path);
544 
545 	imsg_compose(main_ibuf, msg, PROTOCOL_VERSION, -1, -1, buf, len);
546 
547 	events = EV_READ;
548 	if (main_ibuf->w.queued > 0)
549 		events |= EV_WRITE;
550 	event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
551 
552 	event_dispatch();
553 
554 	clear_signals(0);
555 
556 	client_main();	/* doesn't return */
557 }
558 
559 /* ARGSUSED */
560 void
561 main_signal(int sig, unused short events, unused void *data)
562 {
563 	int	status;
564 
565 	switch (sig) {
566 	case SIGTERM:
567 		exit(1);
568 	case SIGCHLD:
569 		waitpid(WAIT_ANY, &status, WNOHANG);
570 		break;
571 	}
572 }
573 
574 /* ARGSUSED */
575 void
576 main_callback(unused int fd, short events, void *data)
577 {
578 	char	*shellcmd = data;
579 
580 	if (events & EV_READ)
581 		main_dispatch(shellcmd);
582 
583 	if (events & EV_WRITE) {
584 		if (msgbuf_write(&main_ibuf->w) < 0)
585 			fatalx("msgbuf_write failed");
586 	}
587 
588 	events = EV_READ;
589 	if (main_ibuf->w.queued > 0)
590 		events |= EV_WRITE;
591 	event_once(main_ibuf->fd, events, main_callback, shellcmd, NULL);
592 }
593 
594 void
595 main_dispatch(const char *shellcmd)
596 {
597 	struct imsg		imsg;
598 	ssize_t			n, datalen;
599 	struct msg_shell_data	shelldata;
600 	struct msg_exit_data	exitdata;
601 
602 	if ((n = imsg_read(main_ibuf)) == -1 || n == 0)
603 		fatalx("imsg_read failed");
604 
605 	for (;;) {
606 		if ((n = imsg_get(main_ibuf, &imsg)) == -1)
607 			fatalx("imsg_get failed");
608 		if (n == 0)
609 			return;
610 		datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
611 
612 		switch (imsg.hdr.type) {
613 		case MSG_EXIT:
614 		case MSG_SHUTDOWN:
615 			if (datalen != sizeof exitdata) {
616 				if (datalen != 0)
617 					fatalx("bad MSG_EXIT size");
618 				exit(0);
619 			}
620 			memcpy(&exitdata, imsg.data, sizeof exitdata);
621 			exit(exitdata.retcode);
622 		case MSG_READY:
623 			if (datalen != 0)
624 				fatalx("bad MSG_READY size");
625 
626 			event_loopexit(NULL);	/* move to client_main() */
627 			break;
628 		case MSG_VERSION:
629 			if (datalen != 0)
630 				fatalx("bad MSG_VERSION size");
631 
632 			log_warnx("protocol version mismatch (client %u, "
633 			    "server %u)", PROTOCOL_VERSION, imsg.hdr.peerid);
634 			exit(1);
635 		case MSG_SHELL:
636 			if (datalen != sizeof shelldata)
637 				fatalx("bad MSG_SHELL size");
638 			memcpy(&shelldata, imsg.data, sizeof shelldata);
639 			shelldata.shell[(sizeof shelldata.shell) - 1] = '\0';
640 
641 			clear_signals(0);
642 
643 			shell_exec(shelldata.shell, shellcmd);
644 		default:
645 			fatalx("unexpected message");
646 		}
647 
648 		imsg_free(&imsg);
649 	}
650 }
651