xref: /openbsd-src/usr.bin/tmux/tmux.c (revision e3b883c97bfbe1fcc7b0e6f022f74c56cb278d0e)
1 /* $OpenBSD: tmux.c,v 1.102 2011/01/12 22:23:58 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 <event.h>
24 #include <fcntl.h>
25 #include <paths.h>
26 #include <pwd.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #include "tmux.h"
32 
33 #ifdef DEBUG
34 extern char	*malloc_options;
35 #endif
36 
37 struct options	 global_options;	/* server options */
38 struct options	 global_s_options;	/* session options */
39 struct options	 global_w_options;	/* window options */
40 struct environ	 global_environ;
41 
42 struct event_base *ev_base;
43 
44 char		*cfg_file;
45 char		*shell_cmd;
46 int		 debug_level;
47 time_t		 start_time;
48 char		 socket_path[MAXPATHLEN];
49 int		 login_shell;
50 char		*environ_path;
51 pid_t		 environ_pid;
52 u_int		 environ_idx;
53 
54 __dead void	 usage(void);
55 void	 	 parseenvironment(void);
56 char 		*makesocketpath(const char *);
57 
58 __dead void
59 usage(void)
60 {
61 	fprintf(stderr,
62 	    "usage: %s [-28lquv] [-c shell-command] [-f file] [-L socket-name]\n"
63 	    "            [-S socket-path] [command [flags]]\n",
64 	    __progname);
65 	exit(1);
66 }
67 
68 void
69 logfile(const char *name)
70 {
71 	char	*path;
72 
73 	log_close();
74 	if (debug_level > 0) {
75 		xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
76 		log_open_file(debug_level, path);
77 		xfree(path);
78 	}
79 }
80 
81 const char *
82 getshell(void)
83 {
84 	struct passwd	*pw;
85 	const char	*shell;
86 
87 	shell = getenv("SHELL");
88 	if (checkshell(shell))
89 		return (shell);
90 
91 	pw = getpwuid(getuid());
92 	if (pw != NULL && checkshell(pw->pw_shell))
93 		return (pw->pw_shell);
94 
95 	return (_PATH_BSHELL);
96 }
97 
98 int
99 checkshell(const char *shell)
100 {
101 	if (shell == NULL || *shell == '\0' || areshell(shell))
102 		return (0);
103 	if (access(shell, X_OK) != 0)
104 		return (0);
105 	return (1);
106 }
107 
108 int
109 areshell(const char *shell)
110 {
111 	const char	*progname, *ptr;
112 
113 	if ((ptr = strrchr(shell, '/')) != NULL)
114 		ptr++;
115 	else
116 		ptr = shell;
117 	progname = __progname;
118 	if (*progname == '-')
119 		progname++;
120 	if (strcmp(ptr, progname) == 0)
121 		return (1);
122 	return (0);
123 }
124 
125 void
126 parseenvironment(void)
127 {
128 	char		*env, *path_pid, *pid_idx, buf[256];
129 	size_t		 len;
130 	const char	*errstr;
131 	long long	 ll;
132 
133 	environ_pid = -1;
134 	if ((env = getenv("TMUX")) == NULL)
135 		return;
136 
137 	if ((path_pid = strchr(env, ',')) == NULL || path_pid == env)
138 		return;
139 	if ((pid_idx = strchr(path_pid + 1, ',')) == NULL)
140 		return;
141 	if ((pid_idx == path_pid + 1 || pid_idx[1] == '\0'))
142 		return;
143 
144 	/* path */
145 	len = path_pid - env;
146 	environ_path = xmalloc(len + 1);
147 	memcpy(environ_path, env, len);
148 	environ_path[len] = '\0';
149 
150 	/* pid */
151 	len = pid_idx - path_pid - 1;
152 	if (len > (sizeof buf) - 1)
153 		return;
154 	memcpy(buf, path_pid + 1, len);
155 	buf[len] = '\0';
156 
157 	ll = strtonum(buf, 0, LONG_MAX, &errstr);
158 	if (errstr != NULL)
159 		return;
160 	environ_pid = ll;
161 
162 	/* idx */
163 	ll = strtonum(pid_idx + 1, 0, UINT_MAX, &errstr);
164 	if (errstr != NULL)
165 		return;
166 	environ_idx = ll;
167 }
168 
169 char *
170 makesocketpath(const char *label)
171 {
172 	char		base[MAXPATHLEN], *path, *s;
173 	struct stat	sb;
174 	u_int		uid;
175 
176 	uid = getuid();
177 	if ((s = getenv("TMPDIR")) == NULL || *s == '\0')
178 		xsnprintf(base, sizeof base, "%s/tmux-%u", _PATH_TMP, uid);
179 	else
180 		xsnprintf(base, sizeof base, "%s/tmux-%u", s, uid);
181 
182 	if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST)
183 		return (NULL);
184 
185 	if (lstat(base, &sb) != 0)
186 		return (NULL);
187 	if (!S_ISDIR(sb.st_mode)) {
188 		errno = ENOTDIR;
189 		return (NULL);
190 	}
191 	if (sb.st_uid != uid || (sb.st_mode & (S_IRWXG|S_IRWXO)) != 0) {
192 		errno = EACCES;
193 		return (NULL);
194 	}
195 
196 	xasprintf(&path, "%s/%s", base, label);
197 	return (path);
198 }
199 
200 void
201 setblocking(int fd, int state)
202 {
203 	int mode;
204 
205 	if ((mode = fcntl(fd, F_GETFL)) != -1) {
206 		if (!state)
207 			mode |= O_NONBLOCK;
208 		else
209 			mode &= ~O_NONBLOCK;
210 		fcntl(fd, F_SETFL, mode);
211 	}
212 }
213 
214 __dead void
215 shell_exec(const char *shell, const char *shellcmd)
216 {
217 	const char	*shellname, *ptr;
218 	char		*argv0;
219 
220 	ptr = strrchr(shell, '/');
221 	if (ptr != NULL && *(ptr + 1) != '\0')
222 		shellname = ptr + 1;
223 	else
224 		shellname = shell;
225 	if (login_shell)
226 		xasprintf(&argv0, "-%s", shellname);
227 	else
228 		xasprintf(&argv0, "%s", shellname);
229 	setenv("SHELL", shell, 1);
230 
231 	setblocking(STDIN_FILENO, 1);
232 	setblocking(STDOUT_FILENO, 1);
233 	setblocking(STDERR_FILENO, 1);
234 	closefrom(STDERR_FILENO + 1);
235 
236 	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
237 	fatal("execl failed");
238 }
239 
240 int
241 main(int argc, char **argv)
242 {
243 	struct passwd	*pw;
244 	struct keylist	*keylist;
245 	char		*s, *path, *label, *home, **var;
246 	int	 	 opt, flags, quiet, keys;
247 
248 #ifdef DEBUG
249 	malloc_options = (char *) "AFGJPX";
250 #endif
251 
252 	quiet = flags = 0;
253 	label = 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 (shell_cmd != NULL)
267 				xfree(shell_cmd);
268 			shell_cmd = 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 (shell_cmd != 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 	options_table_populate_tree(server_options_table, &global_options);
332 	options_set_number(&global_options, "quiet", quiet);
333 
334 	options_init(&global_s_options, NULL);
335 	options_table_populate_tree(session_options_table, &global_s_options);
336 	options_set_string(&global_s_options, "default-shell", "%s", getshell());
337 
338 	options_init(&global_w_options, NULL);
339 	options_table_populate_tree(window_options_table, &global_w_options);
340 
341 	/* Set the prefix option (its a list, so not in the table). */
342 	keylist = xmalloc(sizeof *keylist);
343 	ARRAY_INIT(keylist);
344 	ARRAY_ADD(keylist, '\002');
345 	options_set_data(&global_s_options, "prefix", keylist, xfree);
346 
347 	/* Enable UTF-8 if the first client is on UTF-8 terminal. */
348 	if (flags & IDENTIFY_UTF8) {
349 		options_set_number(&global_s_options, "status-utf8", 1);
350 		options_set_number(&global_s_options, "mouse-utf8", 1);
351 		options_set_number(&global_w_options, "utf8", 1);
352 	}
353 
354 	/* Override keys to vi if VISUAL or EDITOR are set. */
355 	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
356 		if (strrchr(s, '/') != NULL)
357 			s = strrchr(s, '/') + 1;
358 		if (strstr(s, "vi") != NULL)
359 			keys = MODEKEY_VI;
360 		else
361 			keys = MODEKEY_EMACS;
362 		options_set_number(&global_s_options, "status-keys", keys);
363 		options_set_number(&global_w_options, "mode-keys", keys);
364 	}
365 
366 	/* Locate the configuration file. */
367 	if (cfg_file == NULL) {
368 		home = getenv("HOME");
369 		if (home == NULL || *home == '\0') {
370 			pw = getpwuid(getuid());
371 			if (pw != NULL)
372 				home = pw->pw_dir;
373 		}
374 		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
375 		if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
376 			xfree(cfg_file);
377 			cfg_file = NULL;
378 		}
379 	}
380 
381 	/*
382 	 * Figure out the socket path. If specified on the command-line with -S
383 	 * or -L, use it, otherwise try $TMUX or assume -L default.
384 	 */
385 	parseenvironment();
386 	if (path == NULL) {
387 		/* If no -L, use the environment. */
388 		if (label == NULL) {
389 			if (environ_path != NULL)
390 				path = xstrdup(environ_path);
391 			else
392 				label = xstrdup("default");
393 		}
394 
395 		/* -L or default set. */
396 		if (label != NULL) {
397 			if ((path = makesocketpath(label)) == NULL) {
398 				log_warn("can't create socket");
399 				exit(1);
400 			}
401 		}
402 	}
403 	if (label != NULL)
404 		xfree(label);
405 	if (realpath(path, socket_path) == NULL)
406 		strlcpy(socket_path, path, sizeof socket_path);
407 	xfree(path);
408 
409 	/* Set process title. */
410 	setproctitle("%s (%s)", __progname, socket_path);
411 
412 	/* Pass control to the client. */
413 	ev_base = event_init();
414 	exit(client_main(argc, argv, flags));
415 }
416