tmux.c revision 1.205
1/* $OpenBSD: tmux.c,v 1.205 2021/02/22 08:18:13 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
40struct options	*global_options;	/* server options */
41struct options	*global_s_options;	/* session options */
42struct options	*global_w_options;	/* window options */
43struct environ	*global_environ;
44
45struct timeval	 start_time;
46const char	*socket_path;
47int		 ptm_fd = -1;
48const char	*shell_command;
49
50static __dead void	 usage(void);
51static char		*make_label(const char *, char **);
52
53static int		 areshell(const char *);
54static const char	*getshell(void);
55
56static __dead void
57usage(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
66static const char *
67getshell(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
83int
84checkshell(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
95static int
96areshell(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
112static char *
113expand_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
145static void
146expand_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
190static char *
191make_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		goto fail;
216	if (lstat(base, &sb) != 0)
217		goto fail;
218	if (!S_ISDIR(sb.st_mode)) {
219		errno = ENOTDIR;
220		goto fail;
221	}
222	if (sb.st_uid != uid || (sb.st_mode & S_IRWXO) != 0) {
223		errno = EACCES;
224		goto fail;
225	}
226	xasprintf(&path, "%s/%s", base, label);
227	free(base);
228	return (path);
229
230fail:
231	xasprintf(cause, "error creating %s (%s)", base, strerror(errno));
232	free(base);
233	return (NULL);
234}
235
236void
237setblocking(int fd, int state)
238{
239	int mode;
240
241	if ((mode = fcntl(fd, F_GETFL)) != -1) {
242		if (!state)
243			mode |= O_NONBLOCK;
244		else
245			mode &= ~O_NONBLOCK;
246		fcntl(fd, F_SETFL, mode);
247	}
248}
249
250uint64_t
251get_timer(void)
252{
253	struct timespec	ts;
254
255	/*
256	 * We want a timestamp in milliseconds suitable for time measurement,
257	 * so prefer the monotonic clock.
258	 */
259	if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
260		clock_gettime(CLOCK_REALTIME, &ts);
261	return ((ts.tv_sec * 1000ULL) + (ts.tv_nsec / 1000000ULL));
262}
263
264const char *
265sig2name(int signo)
266{
267     static char	s[11];
268
269     if (signo > 0 && signo < NSIG)
270	     return (sys_signame[signo]);
271     xsnprintf(s, sizeof s, "%d", signo);
272     return (s);
273}
274
275const char *
276find_cwd(void)
277{
278	char		 resolved1[PATH_MAX], resolved2[PATH_MAX];
279	static char	 cwd[PATH_MAX];
280	const char	*pwd;
281
282	if (getcwd(cwd, sizeof cwd) == NULL)
283		return (NULL);
284	if ((pwd = getenv("PWD")) == NULL || *pwd == '\0')
285		return (cwd);
286
287	/*
288	 * We want to use PWD so that symbolic links are maintained,
289	 * but only if it matches the actual working directory.
290	 */
291	if (realpath(pwd, resolved1) == NULL)
292		return (cwd);
293	if (realpath(cwd, resolved2) == NULL)
294		return (cwd);
295	if (strcmp(resolved1, resolved2) != 0)
296		return (cwd);
297	return (pwd);
298}
299
300const char *
301find_home(void)
302{
303	struct passwd		*pw;
304	static const char	*home;
305
306	if (home != NULL)
307		return (home);
308
309	home = getenv("HOME");
310	if (home == NULL || *home == '\0') {
311		pw = getpwuid(getuid());
312		if (pw != NULL)
313			home = pw->pw_dir;
314		else
315			home = NULL;
316	}
317
318	return (home);
319}
320
321const char *
322getversion(void)
323{
324	static char	*version;
325	struct utsname	 u;
326
327	if (version == NULL) {
328		if (uname(&u) < 0)
329			fatalx("uname failed");
330		xasprintf(&version, "openbsd-%s", u.release);
331	}
332	return (version);
333}
334
335int
336main(int argc, char **argv)
337{
338	char					*path = NULL, *label = NULL;
339	char					*cause, **var;
340	const char				*s, *cwd;
341	int					 opt, keys, feat = 0;
342	uint64_t				 flags = 0;
343	const struct options_table_entry	*oe;
344	u_int					 i;
345
346	if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL &&
347	    setlocale(LC_CTYPE, "C.UTF-8") == NULL) {
348		if (setlocale(LC_CTYPE, "") == NULL)
349			errx(1, "invalid LC_ALL, LC_CTYPE or LANG");
350		s = nl_langinfo(CODESET);
351		if (strcasecmp(s, "UTF-8") != 0 && strcasecmp(s, "UTF8") != 0)
352			errx(1, "need UTF-8 locale (LC_CTYPE) but have %s", s);
353	}
354
355	setlocale(LC_TIME, "");
356	tzset();
357
358	if (**argv == '-')
359		flags = CLIENT_LOGIN;
360	expand_paths(TMUX_CONF, &cfg_files, &cfg_nfiles, 1);
361
362	while ((opt = getopt(argc, argv, "2c:CDdf:lL:NqS:T:uUvV")) != -1) {
363		switch (opt) {
364		case '2':
365			tty_add_features(&feat, "256", ":,");
366			break;
367		case 'c':
368			shell_command = optarg;
369			break;
370		case 'D':
371			flags |= CLIENT_NOFORK;
372			break;
373		case 'C':
374			if (flags & CLIENT_CONTROL)
375				flags |= CLIENT_CONTROLCONTROL;
376			else
377				flags |= CLIENT_CONTROL;
378			break;
379		case 'f':
380			for (i = 0; i < cfg_nfiles; i++)
381				free(cfg_files[i]);
382			free(cfg_files);
383			expand_paths(optarg, &cfg_files, &cfg_nfiles, 0);
384			cfg_quiet = 0;
385			break;
386 		case 'V':
387			printf("%s %s\n", getprogname(), getversion());
388 			exit(0);
389		case 'l':
390			flags |= CLIENT_LOGIN;
391			break;
392		case 'L':
393			free(label);
394			label = xstrdup(optarg);
395			break;
396		case 'N':
397			flags |= CLIENT_NOSTARTSERVER;
398			break;
399		case 'q':
400			break;
401		case 'S':
402			free(path);
403			path = xstrdup(optarg);
404			break;
405		case 'T':
406			tty_add_features(&feat, optarg, ":,");
407			break;
408		case 'u':
409			flags |= CLIENT_UTF8;
410			break;
411		case 'v':
412			log_add_level();
413			break;
414		default:
415			usage();
416		}
417	}
418	argc -= optind;
419	argv += optind;
420
421	if (shell_command != NULL && argc != 0)
422		usage();
423	if ((flags & CLIENT_NOFORK) && argc != 0)
424		usage();
425
426	if ((ptm_fd = getptmfd()) == -1)
427		err(1, "getptmfd");
428	if (pledge("stdio rpath wpath cpath flock fattr unix getpw sendfd "
429	    "recvfd proc exec tty ps", NULL) != 0)
430		err(1, "pledge");
431
432	/*
433	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
434	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
435	 * UTF-8, it is a safe assumption that either they are using a UTF-8
436	 * terminal, or if not they know that output from UTF-8-capable
437	 * programs may be wrong.
438	 */
439	if (getenv("TMUX") != NULL)
440		flags |= CLIENT_UTF8;
441	else {
442		s = getenv("LC_ALL");
443		if (s == NULL || *s == '\0')
444			s = getenv("LC_CTYPE");
445		if (s == NULL || *s == '\0')
446			s = getenv("LANG");
447		if (s == NULL || *s == '\0')
448			s = "";
449		if (strcasestr(s, "UTF-8") != NULL ||
450		    strcasestr(s, "UTF8") != NULL)
451			flags |= CLIENT_UTF8;
452	}
453
454	global_environ = environ_create();
455	for (var = environ; *var != NULL; var++)
456		environ_put(global_environ, *var, 0);
457	if ((cwd = find_cwd()) != NULL)
458		environ_set(global_environ, "PWD", 0, "%s", cwd);
459
460	global_options = options_create(NULL);
461	global_s_options = options_create(NULL);
462	global_w_options = options_create(NULL);
463	for (oe = options_table; oe->name != NULL; oe++) {
464		if (oe->scope & OPTIONS_TABLE_SERVER)
465			options_default(global_options, oe);
466		if (oe->scope & OPTIONS_TABLE_SESSION)
467			options_default(global_s_options, oe);
468		if (oe->scope & OPTIONS_TABLE_WINDOW)
469			options_default(global_w_options, oe);
470	}
471
472	/*
473	 * The default shell comes from SHELL or from the user's passwd entry
474	 * if available.
475	 */
476	options_set_string(global_s_options, "default-shell", 0, "%s",
477	    getshell());
478
479	/* Override keys to vi if VISUAL or EDITOR are set. */
480	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
481		options_set_string(global_options, "editor", 0, "%s", s);
482		if (strrchr(s, '/') != NULL)
483			s = strrchr(s, '/') + 1;
484		if (strstr(s, "vi") != NULL)
485			keys = MODEKEY_VI;
486		else
487			keys = MODEKEY_EMACS;
488		options_set_number(global_s_options, "status-keys", keys);
489		options_set_number(global_w_options, "mode-keys", keys);
490	}
491
492	/*
493	 * If socket is specified on the command-line with -S or -L, it is
494	 * used. Otherwise, $TMUX is checked and if that fails "default" is
495	 * used.
496	 */
497	if (path == NULL && label == NULL) {
498		s = getenv("TMUX");
499		if (s != NULL && *s != '\0' && *s != ',') {
500			path = xstrdup(s);
501			path[strcspn(path, ",")] = '\0';
502		}
503	}
504	if (path == NULL) {
505		if ((path = make_label(label, &cause)) == NULL) {
506			if (cause != NULL) {
507				fprintf(stderr, "%s\n", cause);
508				free(cause);
509			}
510			exit(1);
511		}
512		flags |= CLIENT_DEFAULTSOCKET;
513	}
514	socket_path = path;
515	free(label);
516
517	/* Pass control to the client. */
518	exit(client_main(event_init(), argc, argv, flags, feat));
519}
520