xref: /openbsd-src/usr.bin/tmux/tmux.c (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 /* $OpenBSD: tmux.c,v 1.208 2021/07/06 08:26:00 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
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/utsname.h>
22 
23 #include <err.h>
24 #include <errno.h>
25 #include <event.h>
26 #include <fcntl.h>
27 #include <langinfo.h>
28 #include <locale.h>
29 #include <paths.h>
30 #include <pwd.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <time.h>
35 #include <unistd.h>
36 #include <util.h>
37 
38 #include "tmux.h"
39 
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 timeval	 start_time;
46 const char	*socket_path;
47 int		 ptm_fd = -1;
48 const char	*shell_command;
49 
50 static __dead void	 usage(void);
51 static char		*make_label(const char *, char **);
52 
53 static int		 areshell(const char *);
54 static const char	*getshell(void);
55 
56 static __dead void
57 usage(void)
58 {
59 	fprintf(stderr,
60 	    "usage: %s [-2CDlNuvV] [-c shell-command] [-f file] [-L socket-name]\n"
61 	    "            [-S socket-path] [-T features] [command [flags]]\n",
62 	    getprogname());
63 	exit(1);
64 }
65 
66 static const char *
67 getshell(void)
68 {
69 	struct passwd	*pw;
70 	const char	*shell;
71 
72 	shell = getenv("SHELL");
73 	if (checkshell(shell))
74 		return (shell);
75 
76 	pw = getpwuid(getuid());
77 	if (pw != NULL && checkshell(pw->pw_shell))
78 		return (pw->pw_shell);
79 
80 	return (_PATH_BSHELL);
81 }
82 
83 int
84 checkshell(const char *shell)
85 {
86 	if (shell == NULL || *shell != '/')
87 		return (0);
88 	if (areshell(shell))
89 		return (0);
90 	if (access(shell, X_OK) != 0)
91 		return (0);
92 	return (1);
93 }
94 
95 static int
96 areshell(const char *shell)
97 {
98 	const char	*progname, *ptr;
99 
100 	if ((ptr = strrchr(shell, '/')) != NULL)
101 		ptr++;
102 	else
103 		ptr = shell;
104 	progname = getprogname();
105 	if (*progname == '-')
106 		progname++;
107 	if (strcmp(ptr, progname) == 0)
108 		return (1);
109 	return (0);
110 }
111 
112 static char *
113 expand_path(const char *path, const char *home)
114 {
115 	char			*expanded, *name;
116 	const char		*end;
117 	struct environ_entry	*value;
118 
119 	if (strncmp(path, "~/", 2) == 0) {
120 		if (home == NULL)
121 			return (NULL);
122 		xasprintf(&expanded, "%s%s", home, path + 1);
123 		return (expanded);
124 	}
125 
126 	if (*path == '$') {
127 		end = strchr(path, '/');
128 		if (end == NULL)
129 			name = xstrdup(path + 1);
130 		else
131 			name = xstrndup(path + 1, end - path - 1);
132 		value = environ_find(global_environ, name);
133 		free(name);
134 		if (value == NULL)
135 			return (NULL);
136 		if (end == NULL)
137 			end = "";
138 		xasprintf(&expanded, "%s%s", value->value, end);
139 		return (expanded);
140 	}
141 
142 	return (xstrdup(path));
143 }
144 
145 static void
146 expand_paths(const char *s, char ***paths, u_int *n, int ignore_errors)
147 {
148 	const char	*home = find_home();
149 	char		*copy, *next, *tmp, resolved[PATH_MAX], *expanded;
150 	char		*path;
151 	u_int		 i;
152 
153 	*paths = NULL;
154 	*n = 0;
155 
156 	copy = tmp = xstrdup(s);
157 	while ((next = strsep(&tmp, ":")) != NULL) {
158 		expanded = expand_path(next, home);
159 		if (expanded == NULL) {
160 			log_debug("%s: invalid path: %s", __func__, next);
161 			continue;
162 		}
163 		if (realpath(expanded, resolved) == NULL) {
164 			log_debug("%s: realpath(\"%s\") failed: %s", __func__,
165 			    expanded, strerror(errno));
166 			if (ignore_errors) {
167 				free(expanded);
168 				continue;
169 			}
170 			path = expanded;
171 		} else {
172 			path = xstrdup(resolved);
173 			free(expanded);
174 		}
175 		for (i = 0; i < *n; i++) {
176 			if (strcmp(path, (*paths)[i]) == 0)
177 				break;
178 		}
179 		if (i != *n) {
180 			log_debug("%s: duplicate path: %s", __func__, path);
181 			free(path);
182 			continue;
183 		}
184 		*paths = xreallocarray(*paths, (*n) + 1, sizeof *paths);
185 		(*paths)[(*n)++] = path;
186 	}
187 	free(copy);
188 }
189 
190 static char *
191 make_label(const char *label, char **cause)
192 {
193 	char		**paths, *path, *base;
194 	u_int		  i, n;
195 	struct stat	  sb;
196 	uid_t		  uid;
197 
198 	*cause = NULL;
199 	if (label == NULL)
200 		label = "default";
201 	uid = getuid();
202 
203 	expand_paths(TMUX_SOCK, &paths, &n, 1);
204 	if (n == 0) {
205 		xasprintf(cause, "no suitable socket path");
206 		return (NULL);
207 	}
208 	path = paths[0]; /* can only have one socket! */
209 	for (i = 1; i < n; i++)
210 		free(paths[i]);
211 	free(paths);
212 
213 	xasprintf(&base, "%s/tmux-%ld", path, (long)uid);
214 	if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST) {
215 		xasprintf(cause, "couldn't create directory %s (%s)", base,
216 		    strerror(errno));
217 		goto fail;
218 	}
219 	if (lstat(base, &sb) != 0) {
220 		xasprintf(cause, "couldn't read directory %s (%s)", base,
221 		    strerror(errno));
222 		goto fail;
223 	}
224 	if (!S_ISDIR(sb.st_mode)) {
225 		xasprintf(cause, "%s is not a directory", base);
226 		goto fail;
227 	}
228 	if (sb.st_uid != uid || (sb.st_mode & S_IRWXO) != 0) {
229 		xasprintf(cause, "directory %s has unsafe permissions", base);
230 		goto fail;
231 	}
232 	xasprintf(&path, "%s/%s", base, label);
233 	free(base);
234 	return (path);
235 
236 fail:
237 	free(base);
238 	return (NULL);
239 }
240 
241 void
242 setblocking(int fd, int state)
243 {
244 	int mode;
245 
246 	if ((mode = fcntl(fd, F_GETFL)) != -1) {
247 		if (!state)
248 			mode |= O_NONBLOCK;
249 		else
250 			mode &= ~O_NONBLOCK;
251 		fcntl(fd, F_SETFL, mode);
252 	}
253 }
254 
255 uint64_t
256 get_timer(void)
257 {
258 	struct timespec	ts;
259 
260 	/*
261 	 * We want a timestamp in milliseconds suitable for time measurement,
262 	 * so prefer the monotonic clock.
263 	 */
264 	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
265 		clock_gettime(CLOCK_REALTIME, &ts);
266 	return ((ts.tv_sec * 1000ULL) + (ts.tv_nsec / 1000000ULL));
267 }
268 
269 const char *
270 sig2name(int signo)
271 {
272      static char	s[11];
273 
274      if (signo > 0 && signo < NSIG)
275 	     return (sys_signame[signo]);
276      xsnprintf(s, sizeof s, "%d", signo);
277      return (s);
278 }
279 
280 const char *
281 find_cwd(void)
282 {
283 	char		 resolved1[PATH_MAX], resolved2[PATH_MAX];
284 	static char	 cwd[PATH_MAX];
285 	const char	*pwd;
286 
287 	if (getcwd(cwd, sizeof cwd) == NULL)
288 		return (NULL);
289 	if ((pwd = getenv("PWD")) == NULL || *pwd == '\0')
290 		return (cwd);
291 
292 	/*
293 	 * We want to use PWD so that symbolic links are maintained,
294 	 * but only if it matches the actual working directory.
295 	 */
296 	if (realpath(pwd, resolved1) == NULL)
297 		return (cwd);
298 	if (realpath(cwd, resolved2) == NULL)
299 		return (cwd);
300 	if (strcmp(resolved1, resolved2) != 0)
301 		return (cwd);
302 	return (pwd);
303 }
304 
305 const char *
306 find_home(void)
307 {
308 	struct passwd		*pw;
309 	static const char	*home;
310 
311 	if (home != NULL)
312 		return (home);
313 
314 	home = getenv("HOME");
315 	if (home == NULL || *home == '\0') {
316 		pw = getpwuid(getuid());
317 		if (pw != NULL)
318 			home = pw->pw_dir;
319 		else
320 			home = NULL;
321 	}
322 
323 	return (home);
324 }
325 
326 const char *
327 getversion(void)
328 {
329 	static char	*version;
330 	struct utsname	 u;
331 
332 	if (version == NULL) {
333 		if (uname(&u) < 0)
334 			fatalx("uname failed");
335 		xasprintf(&version, "openbsd-%s", u.release);
336 	}
337 	return (version);
338 }
339 
340 int
341 main(int argc, char **argv)
342 {
343 	char					*path = NULL, *label = NULL;
344 	char					*cause, **var;
345 	const char				*s, *cwd;
346 	int					 opt, keys, feat = 0, fflag = 0;
347 	uint64_t				 flags = 0;
348 	const struct options_table_entry	*oe;
349 	u_int					 i;
350 
351 	if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL &&
352 	    setlocale(LC_CTYPE, "C.UTF-8") == NULL) {
353 		if (setlocale(LC_CTYPE, "") == NULL)
354 			errx(1, "invalid LC_ALL, LC_CTYPE or LANG");
355 		s = nl_langinfo(CODESET);
356 		if (strcasecmp(s, "UTF-8") != 0 && strcasecmp(s, "UTF8") != 0)
357 			errx(1, "need UTF-8 locale (LC_CTYPE) but have %s", s);
358 	}
359 
360 	setlocale(LC_TIME, "");
361 	tzset();
362 
363 	if (**argv == '-')
364 		flags = CLIENT_LOGIN;
365 
366 	global_environ = environ_create();
367 	for (var = environ; *var != NULL; var++)
368 		environ_put(global_environ, *var, 0);
369 	if ((cwd = find_cwd()) != NULL)
370 		environ_set(global_environ, "PWD", 0, "%s", cwd);
371 	expand_paths(TMUX_CONF, &cfg_files, &cfg_nfiles, 1);
372 
373 	while ((opt = getopt(argc, argv, "2c:CDdf:lL:NqS:T:uUvV")) != -1) {
374 		switch (opt) {
375 		case '2':
376 			tty_add_features(&feat, "256", ":,");
377 			break;
378 		case 'c':
379 			shell_command = optarg;
380 			break;
381 		case 'D':
382 			flags |= CLIENT_NOFORK;
383 			break;
384 		case 'C':
385 			if (flags & CLIENT_CONTROL)
386 				flags |= CLIENT_CONTROLCONTROL;
387 			else
388 				flags |= CLIENT_CONTROL;
389 			break;
390 		case 'f':
391 			if (!fflag) {
392 				fflag = 1;
393 				for (i = 0; i < cfg_nfiles; i++)
394 					free(cfg_files[i]);
395 				cfg_nfiles = 0;
396 			}
397 			cfg_files = xreallocarray(cfg_files, cfg_nfiles + 1,
398 			    sizeof *cfg_files);
399 			cfg_files[cfg_nfiles++] = xstrdup(optarg);
400 			cfg_quiet = 0;
401 			break;
402  		case 'V':
403 			printf("%s %s\n", getprogname(), getversion());
404  			exit(0);
405 		case 'l':
406 			flags |= CLIENT_LOGIN;
407 			break;
408 		case 'L':
409 			free(label);
410 			label = xstrdup(optarg);
411 			break;
412 		case 'N':
413 			flags |= CLIENT_NOSTARTSERVER;
414 			break;
415 		case 'q':
416 			break;
417 		case 'S':
418 			free(path);
419 			path = xstrdup(optarg);
420 			break;
421 		case 'T':
422 			tty_add_features(&feat, optarg, ":,");
423 			break;
424 		case 'u':
425 			flags |= CLIENT_UTF8;
426 			break;
427 		case 'v':
428 			log_add_level();
429 			break;
430 		default:
431 			usage();
432 		}
433 	}
434 	argc -= optind;
435 	argv += optind;
436 
437 	if (shell_command != NULL && argc != 0)
438 		usage();
439 	if ((flags & CLIENT_NOFORK) && argc != 0)
440 		usage();
441 
442 	if ((ptm_fd = getptmfd()) == -1)
443 		err(1, "getptmfd");
444 	if (pledge("stdio rpath wpath cpath flock fattr unix getpw sendfd "
445 	    "recvfd proc exec tty ps", NULL) != 0)
446 		err(1, "pledge");
447 
448 	/*
449 	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
450 	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
451 	 * UTF-8, it is a safe assumption that either they are using a UTF-8
452 	 * terminal, or if not they know that output from UTF-8-capable
453 	 * programs may be wrong.
454 	 */
455 	if (getenv("TMUX") != NULL)
456 		flags |= CLIENT_UTF8;
457 	else {
458 		s = getenv("LC_ALL");
459 		if (s == NULL || *s == '\0')
460 			s = getenv("LC_CTYPE");
461 		if (s == NULL || *s == '\0')
462 			s = getenv("LANG");
463 		if (s == NULL || *s == '\0')
464 			s = "";
465 		if (strcasestr(s, "UTF-8") != NULL ||
466 		    strcasestr(s, "UTF8") != NULL)
467 			flags |= CLIENT_UTF8;
468 	}
469 
470 	global_options = options_create(NULL);
471 	global_s_options = options_create(NULL);
472 	global_w_options = options_create(NULL);
473 	for (oe = options_table; oe->name != NULL; oe++) {
474 		if (oe->scope & OPTIONS_TABLE_SERVER)
475 			options_default(global_options, oe);
476 		if (oe->scope & OPTIONS_TABLE_SESSION)
477 			options_default(global_s_options, oe);
478 		if (oe->scope & OPTIONS_TABLE_WINDOW)
479 			options_default(global_w_options, oe);
480 	}
481 
482 	/*
483 	 * The default shell comes from SHELL or from the user's passwd entry
484 	 * if available.
485 	 */
486 	options_set_string(global_s_options, "default-shell", 0, "%s",
487 	    getshell());
488 
489 	/* Override keys to vi if VISUAL or EDITOR are set. */
490 	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
491 		options_set_string(global_options, "editor", 0, "%s", s);
492 		if (strrchr(s, '/') != NULL)
493 			s = strrchr(s, '/') + 1;
494 		if (strstr(s, "vi") != NULL)
495 			keys = MODEKEY_VI;
496 		else
497 			keys = MODEKEY_EMACS;
498 		options_set_number(global_s_options, "status-keys", keys);
499 		options_set_number(global_w_options, "mode-keys", keys);
500 	}
501 
502 	/*
503 	 * If socket is specified on the command-line with -S or -L, it is
504 	 * used. Otherwise, $TMUX is checked and if that fails "default" is
505 	 * used.
506 	 */
507 	if (path == NULL && label == NULL) {
508 		s = getenv("TMUX");
509 		if (s != NULL && *s != '\0' && *s != ',') {
510 			path = xstrdup(s);
511 			path[strcspn(path, ",")] = '\0';
512 		}
513 	}
514 	if (path == NULL) {
515 		if ((path = make_label(label, &cause)) == NULL) {
516 			if (cause != NULL) {
517 				fprintf(stderr, "%s\n", cause);
518 				free(cause);
519 			}
520 			exit(1);
521 		}
522 		flags |= CLIENT_DEFAULTSOCKET;
523 	}
524 	socket_path = path;
525 	free(label);
526 
527 	/* Pass control to the client. */
528 	exit(client_main(event_init(), argc, argv, flags, feat));
529 }
530