xref: /openbsd-src/usr.bin/tmux/tmux.c (revision bd0e97c47a8bc38fd99774f7689a790da15de717)
1 /* $OpenBSD: tmux.c,v 1.42 2009/09/04 15:15:24 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 
22 #include <errno.h>
23 #include <paths.h>
24 #include <pwd.h>
25 #include <signal.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <syslog.h>
29 #include <unistd.h>
30 
31 #include "tmux.h"
32 
33 #ifdef DEBUG
34 const char	*malloc_options = "AFGJPX";
35 #endif
36 
37 volatile sig_atomic_t sigwinch;
38 volatile sig_atomic_t sigterm;
39 volatile sig_atomic_t sigcont;
40 volatile sig_atomic_t sigchld;
41 volatile sig_atomic_t sigusr1;
42 volatile sig_atomic_t sigusr2;
43 
44 char		*cfg_file;
45 struct options	 global_s_options;	/* session options */
46 struct options	 global_w_options;	/* window options */
47 struct environ	 global_environ;
48 
49 int		 server_locked;
50 struct passwd	*server_locked_pw;
51 u_int		 password_failures;
52 time_t		 password_backoff;
53 char		*server_password;
54 time_t		 server_activity;
55 
56 int		 debug_level;
57 int		 be_quiet;
58 time_t		 start_time;
59 char		*socket_path;
60 int		 login_shell;
61 
62 __dead void	 usage(void);
63 char 		*makesockpath(const char *);
64 int		 prepare_unlock(enum msgtype *, void **, size_t *, int);
65 int		 prepare_cmd(enum msgtype *, void **, size_t *, int, char **);
66 int		 dispatch_imsg(struct client_ctx *, int *);
67 
68 __dead void
69 usage(void)
70 {
71 	fprintf(stderr,
72 	    "usage: %s [-28dlqUuv] [-f file] [-L socket-name]\n"
73 	    "            [-S socket-path] [command [flags]]\n",
74 	    __progname);
75 	exit(1);
76 }
77 
78 void
79 logfile(const char *name)
80 {
81 	char	*path;
82 
83 	log_close();
84 	if (debug_level > 0) {
85 		xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
86 		log_open_file(debug_level, path);
87 		xfree(path);
88 	}
89 }
90 
91 void
92 sighandler(int sig)
93 {
94 	int	saved_errno;
95 
96 	saved_errno = errno;
97 	switch (sig) {
98 	case SIGWINCH:
99 		sigwinch = 1;
100 		break;
101 	case SIGTERM:
102 		sigterm = 1;
103 		break;
104 	case SIGCHLD:
105 		sigchld = 1;
106 		break;
107 	case SIGCONT:
108 		sigcont = 1;
109 		break;
110 	case SIGUSR1:
111 		sigusr1 = 1;
112 		break;
113 	case SIGUSR2:
114 		sigusr2 = 1;
115 		break;
116 	}
117 	errno = saved_errno;
118 }
119 
120 void
121 siginit(void)
122 {
123 	struct sigaction	 act;
124 
125 	memset(&act, 0, sizeof act);
126 	sigemptyset(&act.sa_mask);
127 	act.sa_flags = SA_RESTART;
128 
129 	act.sa_handler = SIG_IGN;
130 	if (sigaction(SIGPIPE, &act, NULL) != 0)
131 		fatal("sigaction failed");
132 	if (sigaction(SIGINT, &act, NULL) != 0)
133 		fatal("sigaction failed");
134 	if (sigaction(SIGTSTP, &act, NULL) != 0)
135 		fatal("sigaction failed");
136 	if (sigaction(SIGQUIT, &act, NULL) != 0)
137 		fatal("sigaction failed");
138 
139 	act.sa_handler = sighandler;
140 	if (sigaction(SIGWINCH, &act, NULL) != 0)
141 		fatal("sigaction failed");
142 	if (sigaction(SIGTERM, &act, NULL) != 0)
143 		fatal("sigaction failed");
144 	if (sigaction(SIGCHLD, &act, NULL) != 0)
145 		fatal("sigaction failed");
146 	if (sigaction(SIGUSR1, &act, NULL) != 0)
147 		fatal("sigaction failed");
148 	if (sigaction(SIGUSR2, &act, NULL) != 0)
149 		fatal("sigaction failed");
150 }
151 
152 void
153 sigreset(void)
154 {
155 	struct sigaction act;
156 
157 	memset(&act, 0, sizeof act);
158 	sigemptyset(&act.sa_mask);
159 
160 	act.sa_handler = SIG_DFL;
161 	if (sigaction(SIGPIPE, &act, NULL) != 0)
162 		fatal("sigaction failed");
163 	if (sigaction(SIGUSR1, &act, NULL) != 0)
164 		fatal("sigaction failed");
165 	if (sigaction(SIGUSR2, &act, NULL) != 0)
166 		fatal("sigaction failed");
167 	if (sigaction(SIGINT, &act, NULL) != 0)
168 		fatal("sigaction failed");
169 	if (sigaction(SIGTSTP, &act, NULL) != 0)
170 		fatal("sigaction failed");
171 	if (sigaction(SIGQUIT, &act, NULL) != 0)
172 		fatal("sigaction failed");
173 	if (sigaction(SIGWINCH, &act, NULL) != 0)
174 		fatal("sigaction failed");
175 	if (sigaction(SIGTERM, &act, NULL) != 0)
176 		fatal("sigaction failed");
177 	if (sigaction(SIGCHLD, &act, NULL) != 0)
178 		fatal("sigaction failed");
179 }
180 
181 const char *
182 getshell(void)
183 {
184 	struct passwd	*pw;
185 	const char	*shell;
186 
187 	shell = getenv("SHELL");
188 	if (checkshell(shell))
189 		return (shell);
190 
191 	pw = getpwuid(getuid());
192 	if (pw != NULL && checkshell(pw->pw_shell))
193 		return (pw->pw_shell);
194 
195 	return (_PATH_BSHELL);
196 }
197 
198 int
199 checkshell(const char *shell)
200 {
201 	if (shell == NULL || *shell == '\0' || areshell(shell))
202 		return (0);
203 	if (access(shell, X_OK) != 0)
204 		return (0);
205 	return (1);
206 }
207 
208 int
209 areshell(const char *shell)
210 {
211 	const char	*progname, *ptr;
212 
213 	if ((ptr = strrchr(shell, '/')) != NULL)
214 		ptr++;
215 	else
216 		ptr = shell;
217 	progname = __progname;
218 	if (*progname == '-')
219 		progname++;
220 	if (strcmp(ptr, progname) == 0)
221 		return (1);
222 	return (0);
223 }
224 
225 char *
226 makesockpath(const char *label)
227 {
228 	char		base[MAXPATHLEN], *path;
229 	struct stat	sb;
230 	u_int		uid;
231 
232 	uid = getuid();
233 	xsnprintf(base, MAXPATHLEN, "%s/tmux-%d", _PATH_TMP, uid);
234 
235 	if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST)
236 		return (NULL);
237 
238 	if (lstat(base, &sb) != 0)
239 		return (NULL);
240 	if (!S_ISDIR(sb.st_mode)) {
241 		errno = ENOTDIR;
242 		return (NULL);
243 	}
244 	if (sb.st_uid != uid || (sb.st_mode & (S_IRWXG|S_IRWXO)) != 0) {
245 		errno = EACCES;
246 		return (NULL);
247 	}
248 
249 	xasprintf(&path, "%s/%s", base, label);
250 	return (path);
251 }
252 
253 int
254 prepare_unlock(enum msgtype *msg, void **buf, size_t *len, int argc)
255 {
256 	static struct msg_unlock_data	 unlockdata;
257 	char				*pass;
258 
259 	if (argc != 0) {
260 		log_warnx("can't specify a command when unlocking");
261 		return (-1);
262 	}
263 
264 	if ((pass = getpass("Password:")) == NULL)
265 		return (-1);
266 
267 	if (strlen(pass) >= sizeof unlockdata.pass) {
268 		log_warnx("password too long");
269 		return (-1);
270 	}
271 
272 	strlcpy(unlockdata.pass, pass, sizeof unlockdata.pass);
273 	memset(pass, 0, strlen(pass));
274 
275 	*buf = &unlockdata;
276 	*len = sizeof unlockdata;
277 
278 	*msg = MSG_UNLOCK;
279 	return (0);
280 }
281 
282 int
283 prepare_cmd(enum msgtype *msg, void **buf, size_t *len, int argc, char **argv)
284 {
285 	static struct msg_command_data	 cmddata;
286 
287 	client_fill_session(&cmddata);
288 
289 	cmddata.argc = argc;
290 	if (cmd_pack_argv(argc, argv, cmddata.argv, sizeof cmddata.argv) != 0) {
291 		log_warnx("command too long");
292 		return (-1);
293 	}
294 
295 	*buf = &cmddata;
296 	*len = sizeof cmddata;
297 
298 	*msg = MSG_COMMAND;
299 	return (0);
300 }
301 
302 int
303 main(int argc, char **argv)
304 {
305 	struct client_ctx	 cctx;
306 	struct cmd_list		*cmdlist;
307  	struct cmd		*cmd;
308 	struct pollfd	 	 pfd;
309 	enum msgtype		 msg;
310 	struct passwd		*pw;
311 	struct options		*so, *wo;
312 	char			*s, *path, *label, *home, *cause, **var;
313 	char			 cwd[MAXPATHLEN];
314 	void			*buf;
315 	size_t			 len;
316 	int	 		 retcode, opt, flags, unlock, cmdflags = 0;
317 	int			 nfds;
318 
319 	unlock = flags = 0;
320 	label = path = NULL;
321 	login_shell = (**argv == '-');
322 	while ((opt = getopt(argc, argv, "28df:lL:qS:uUv")) != -1) {
323 		switch (opt) {
324 		case '2':
325 			flags |= IDENTIFY_256COLOURS;
326 			flags &= ~IDENTIFY_88COLOURS;
327 			break;
328 		case '8':
329 			flags |= IDENTIFY_88COLOURS;
330 			flags &= ~IDENTIFY_256COLOURS;
331 			break;
332 		case 'd':
333 			flags |= IDENTIFY_HASDEFAULTS;
334 			break;
335 		case 'f':
336 			if (cfg_file != NULL)
337 				xfree(cfg_file);
338 			cfg_file = xstrdup(optarg);
339 			break;
340 		case 'l':
341 			login_shell = 1;
342 			break;
343 		case 'L':
344 			if (label != NULL)
345 				xfree(label);
346 			label = xstrdup(optarg);
347 			break;
348 		case 'q':
349 			be_quiet = 1;
350 			break;
351 		case 'S':
352 			if (path != NULL)
353 				xfree(path);
354 			path = xstrdup(optarg);
355 			break;
356 		case 'u':
357 			flags |= IDENTIFY_UTF8;
358 			break;
359 		case 'U':
360 			unlock = 1;
361 			break;
362 		case 'v':
363 			debug_level++;
364 			break;
365                 default:
366 			usage();
367                 }
368         }
369 	argc -= optind;
370 	argv += optind;
371 
372 	log_open_tty(debug_level);
373 	siginit();
374 
375 	if (!(flags & IDENTIFY_UTF8)) {
376 		/*
377 		 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
378 		 * exist (in that order) to contain UTF-8, it is a safe
379 		 * assumption that either they are using a UTF-8 terminal, or
380 		 * if not they know that output from UTF-8-capable programs may
381 		 * be wrong.
382 		 */
383 		if ((s = getenv("LC_ALL")) == NULL) {
384 			if ((s = getenv("LC_CTYPE")) == NULL)
385 				s = getenv("LANG");
386 		}
387 		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
388 		    strcasestr(s, "UTF8") != NULL))
389 			flags |= IDENTIFY_UTF8;
390 	}
391 
392 	environ_init(&global_environ);
393  	for (var = environ; *var != NULL; var++)
394 		environ_put(&global_environ, *var);
395 
396 	options_init(&global_s_options, NULL);
397 	so = &global_s_options;
398 	options_set_number(so, "base-index", 0);
399 	options_set_number(so, "bell-action", BELL_ANY);
400 	options_set_number(so, "buffer-limit", 9);
401 	options_set_string(so, "default-command", "%s", "");
402 	options_set_string(so, "default-shell", "%s", getshell());
403 	options_set_string(so, "default-terminal", "screen");
404 	options_set_number(so, "display-panes-colour", 4);
405 	options_set_number(so, "display-panes-time", 1000);
406 	options_set_number(so, "display-time", 750);
407 	options_set_number(so, "history-limit", 2000);
408 	options_set_number(so, "lock-after-time", 0);
409 	options_set_number(so, "message-attr", 0);
410 	options_set_number(so, "message-bg", 3);
411 	options_set_number(so, "message-fg", 0);
412 	options_set_number(so, "prefix", '\002');
413 	options_set_number(so, "repeat-time", 500);
414 	options_set_number(so, "set-remain-on-exit", 0);
415 	options_set_number(so, "set-titles", 0);
416 	options_set_number(so, "status", 1);
417 	options_set_number(so, "status-attr", 0);
418 	options_set_number(so, "status-bg", 2);
419 	options_set_number(so, "status-fg", 0);
420 	options_set_number(so, "status-interval", 15);
421 	options_set_number(so, "status-justify", 0);
422 	options_set_number(so, "status-keys", MODEKEY_EMACS);
423 	options_set_string(so, "status-left", "[#S]");
424 	options_set_number(so, "status-left-attr", 0);
425 	options_set_number(so, "status-left-bg", 8);
426 	options_set_number(so, "status-left-fg", 8);
427 	options_set_number(so, "status-left-length", 10);
428 	options_set_string(so, "status-right", "\"#22T\" %%H:%%M %%d-%%b-%%y");
429 	options_set_number(so, "status-right-attr", 0);
430 	options_set_number(so, "status-right-bg", 8);
431 	options_set_number(so, "status-right-fg", 8);
432 	options_set_number(so, "status-right-length", 40);
433 	options_set_string(so, "terminal-overrides",
434 	    "*88col*:colors=88,*256col*:colors=256");
435 	options_set_string(so, "update-environment", "DISPLAY "
436 	    "WINDOWID SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION");
437 	options_set_number(so, "visual-activity", 0);
438 	options_set_number(so, "visual-bell", 0);
439 	options_set_number(so, "visual-content", 0);
440 
441 	options_init(&global_w_options, NULL);
442 	wo = &global_w_options;
443 	options_set_number(wo, "aggressive-resize", 0);
444 	options_set_number(wo, "automatic-rename", 1);
445 	options_set_number(wo, "clock-mode-colour", 4);
446 	options_set_number(wo, "clock-mode-style", 1);
447 	options_set_number(wo, "force-height", 0);
448 	options_set_number(wo, "force-width", 0);
449 	options_set_number(wo, "main-pane-height", 24);
450 	options_set_number(wo, "main-pane-width", 81);
451 	options_set_number(wo, "mode-attr", 0);
452 	options_set_number(wo, "mode-bg", 3);
453 	options_set_number(wo, "mode-fg", 0);
454 	options_set_number(wo, "mode-keys", MODEKEY_EMACS);
455 	options_set_number(wo, "mode-mouse", 0);
456 	options_set_number(wo, "monitor-activity", 0);
457 	options_set_string(wo, "monitor-content", "%s", "");
458 	options_set_number(wo, "window-status-attr", 0);
459 	options_set_number(wo, "window-status-bg", 8);
460 	options_set_number(wo, "window-status-current-attr", 0);
461 	options_set_number(wo, "window-status-current-bg", 8);
462 	options_set_number(wo, "window-status-current-fg", 8);
463 	options_set_number(wo, "window-status-fg", 8);
464 	options_set_number(wo, "xterm-keys", 0);
465  	options_set_number(wo, "remain-on-exit", 0);
466 
467  	if (flags & IDENTIFY_UTF8) {
468 		options_set_number(so, "status-utf8", 1);
469 		options_set_number(wo, "utf8", 1);
470 	} else {
471 		options_set_number(so, "status-utf8", 0);
472 		options_set_number(wo, "utf8", 0);
473 	}
474 
475 	if (getcwd(cwd, sizeof cwd) == NULL) {
476 		pw = getpwuid(getuid());
477 		if (pw->pw_dir != NULL && *pw->pw_dir != '\0')
478 			strlcpy(cwd, pw->pw_dir, sizeof cwd);
479 		else
480 			strlcpy(cwd, "/", sizeof cwd);
481 	}
482 	options_set_string(so, "default-path", "%s", cwd);
483 
484 	if (cfg_file == NULL) {
485 		home = getenv("HOME");
486 		if (home == NULL || *home == '\0') {
487 			pw = getpwuid(getuid());
488 			if (pw != NULL)
489 				home = pw->pw_dir;
490 		}
491 		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
492 		if (access(cfg_file, R_OK) != 0) {
493 			xfree(cfg_file);
494 			cfg_file = NULL;
495 		}
496 	} else {
497 		if (access(cfg_file, R_OK) != 0) {
498 			log_warn("%s", cfg_file);
499 			exit(1);
500 		}
501 	}
502 
503 	if (label == NULL)
504 		label = xstrdup("default");
505 	if (path == NULL && (path = makesockpath(label)) == NULL) {
506 		log_warn("can't create socket");
507 		exit(1);
508 	}
509 	xfree(label);
510 
511 	if (unlock) {
512 		if (prepare_unlock(&msg, &buf, &len, argc) != 0)
513 			exit(1);
514 	} else {
515 		if (prepare_cmd(&msg, &buf, &len, argc, argv) != 0)
516 			exit(1);
517 	}
518 
519 	if (unlock)
520 		cmdflags &= ~CMD_STARTSERVER;
521 	else if (argc == 0)	/* new-session is the default */
522 		cmdflags |= CMD_STARTSERVER|CMD_SENDENVIRON;
523 	else {
524 		/*
525 		 * It sucks parsing the command string twice (in client and
526 		 * later in server) but it is necessary to get the start server
527 		 * flag.
528 		 */
529 		if ((cmdlist = cmd_list_parse(argc, argv, &cause)) == NULL) {
530 			log_warnx("%s", cause);
531 			exit(1);
532 		}
533 		cmdflags &= ~CMD_STARTSERVER;
534 		TAILQ_FOREACH(cmd, cmdlist, qentry) {
535 			if (cmd->entry->flags & CMD_STARTSERVER)
536 				cmdflags |= CMD_STARTSERVER;
537 			if (cmd->entry->flags & CMD_SENDENVIRON)
538 				cmdflags |= CMD_SENDENVIRON;
539 		}
540 		cmd_list_free(cmdlist);
541 	}
542 
543  	memset(&cctx, 0, sizeof cctx);
544 	if (client_init(path, &cctx, cmdflags, flags) != 0)
545 		exit(1);
546 	xfree(path);
547 
548 	client_write_server(&cctx, msg, buf, len);
549 	memset(buf, 0, len);
550 
551 	retcode = 0;
552 	for (;;) {
553 		pfd.fd = cctx.ibuf.fd;
554 		pfd.events = POLLIN;
555 		if (cctx.ibuf.w.queued != 0)
556 			pfd.events |= POLLOUT;
557 
558 		if ((nfds = poll(&pfd, 1, INFTIM)) == -1) {
559 			if (errno == EAGAIN || errno == EINTR)
560 				continue;
561 			fatal("poll failed");
562 		}
563 		if (nfds == 0)
564 			continue;
565 
566 		if (pfd.revents & (POLLERR|POLLHUP|POLLNVAL))
567 			fatalx("socket error");
568 
569                 if (pfd.revents & POLLIN) {
570 			if (dispatch_imsg(&cctx, &retcode) != 0)
571 				break;
572 		}
573 
574 		if (pfd.revents & POLLOUT) {
575 			if (msgbuf_write(&cctx.ibuf.w) < 0)
576 				fatalx("msgbuf_write failed");
577 		}
578 	}
579 
580 	options_free(&global_s_options);
581 	options_free(&global_w_options);
582 
583 	return (retcode);
584 }
585 
586 int
587 dispatch_imsg(struct client_ctx *cctx, int *retcode)
588 {
589 	struct imsg		imsg;
590 	ssize_t			n, datalen;
591 	struct msg_print_data	printdata;
592 
593         if ((n = imsg_read(&cctx->ibuf)) == -1 || n == 0)
594 		fatalx("imsg_read failed");
595 
596 	for (;;) {
597 		if ((n = imsg_get(&cctx->ibuf, &imsg)) == -1)
598 			fatalx("imsg_get failed");
599 		if (n == 0)
600 			return (0);
601 		datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
602 
603 		switch (imsg.hdr.type) {
604 		case MSG_EXIT:
605 		case MSG_SHUTDOWN:
606 			if (datalen != 0)
607 				fatalx("bad MSG_EXIT size");
608 
609 			return (-1);
610 		case MSG_ERROR:
611 			*retcode = 1;
612 			/* FALLTHROUGH */
613 		case MSG_PRINT:
614 			if (datalen != sizeof printdata)
615 				fatalx("bad MSG_PRINT size");
616 			memcpy(&printdata, imsg.data, sizeof printdata);
617 			printdata.msg[(sizeof printdata.msg) - 1] = '\0';
618 
619 			log_info("%s", printdata.msg);
620 			break;
621 		case MSG_READY:
622 			if (datalen != 0)
623 				fatalx("bad MSG_READY size");
624 
625 			*retcode = client_main(cctx);
626 			return (-1);
627 		case MSG_VERSION:
628 			if (datalen != 0)
629 				fatalx("bad MSG_VERSION size");
630 
631 			log_warnx("protocol version mismatch (client %u, "
632 			    "server %u)", PROTOCOL_VERSION, imsg.hdr.peerid);
633 			*retcode = 1;
634 			return (-1);
635 		default:
636 			fatalx("unexpected message");
637 		}
638 
639 		imsg_free(&imsg);
640 	}
641 }
642