tmux.c revision 1.100
1/* $OpenBSD: tmux.c,v 1.100 2011/01/03 23:35:21 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
34extern char	*malloc_options;
35#endif
36
37struct options	 global_options;	/* server options */
38struct options	 global_s_options;	/* session options */
39struct options	 global_w_options;	/* window options */
40struct environ	 global_environ;
41
42struct event_base *ev_base;
43
44char		*cfg_file;
45char		*shell_cmd;
46int		 debug_level;
47time_t		 start_time;
48char		 socket_path[MAXPATHLEN];
49int		 login_shell;
50char		*environ_path;
51pid_t		 environ_pid;
52u_int		 environ_idx;
53
54__dead void	 usage(void);
55void	 	 parseenvironment(void);
56char 		*makesocketpath(const char *);
57
58__dead void
59usage(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
68void
69logfile(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
81const char *
82getshell(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
98int
99checkshell(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
108int
109areshell(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
125void
126parseenvironment(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
169char *
170makesocketpath(const char *label)
171{
172	char		base[MAXPATHLEN], *path;
173	struct stat	sb;
174	u_int		uid;
175
176	uid = getuid();
177	xsnprintf(base, MAXPATHLEN, "%s/tmux-%d", _PATH_TMP, uid);
178
179	if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST)
180		return (NULL);
181
182	if (lstat(base, &sb) != 0)
183		return (NULL);
184	if (!S_ISDIR(sb.st_mode)) {
185		errno = ENOTDIR;
186		return (NULL);
187	}
188	if (sb.st_uid != uid || (sb.st_mode & (S_IRWXG|S_IRWXO)) != 0) {
189		errno = EACCES;
190		return (NULL);
191	}
192
193	xasprintf(&path, "%s/%s", base, label);
194	return (path);
195}
196
197__dead void
198shell_exec(const char *shell, const char *shellcmd)
199{
200	const char	*shellname, *ptr;
201	char		*argv0;
202	int		 mode;
203
204	ptr = strrchr(shell, '/');
205	if (ptr != NULL && *(ptr + 1) != '\0')
206		shellname = ptr + 1;
207	else
208		shellname = shell;
209	if (login_shell)
210		xasprintf(&argv0, "-%s", shellname);
211	else
212		xasprintf(&argv0, "%s", shellname);
213	setenv("SHELL", shell, 1);
214
215	if ((mode = fcntl(STDIN_FILENO, F_GETFL)) != -1)
216		fcntl(STDIN_FILENO, F_SETFL, mode & ~O_NONBLOCK);
217	if ((mode = fcntl(STDOUT_FILENO, F_GETFL)) != -1)
218		fcntl(STDOUT_FILENO, F_SETFL, mode & ~O_NONBLOCK);
219	if ((mode = fcntl(STDERR_FILENO, F_GETFL)) != -1)
220		fcntl(STDERR_FILENO, F_SETFL, mode & ~O_NONBLOCK);
221	closefrom(STDERR_FILENO + 1);
222
223	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
224	fatal("execl failed");
225}
226
227int
228main(int argc, char **argv)
229{
230	struct passwd	*pw;
231	struct keylist	*keylist;
232	char		*s, *path, *label, *home, **var;
233	int	 	 opt, flags, quiet, keys;
234
235#ifdef DEBUG
236	malloc_options = (char *) "AFGJPX";
237#endif
238
239	quiet = flags = 0;
240	label = path = NULL;
241	login_shell = (**argv == '-');
242	while ((opt = getopt(argc, argv, "28c:df:lL:qS:uUv")) != -1) {
243		switch (opt) {
244		case '2':
245			flags |= IDENTIFY_256COLOURS;
246			flags &= ~IDENTIFY_88COLOURS;
247			break;
248		case '8':
249			flags |= IDENTIFY_88COLOURS;
250			flags &= ~IDENTIFY_256COLOURS;
251			break;
252		case 'c':
253			if (shell_cmd != NULL)
254				xfree(shell_cmd);
255			shell_cmd = xstrdup(optarg);
256			break;
257		case 'f':
258			if (cfg_file != NULL)
259				xfree(cfg_file);
260			cfg_file = xstrdup(optarg);
261			break;
262		case 'l':
263			login_shell = 1;
264			break;
265		case 'L':
266			if (label != NULL)
267				xfree(label);
268			label = xstrdup(optarg);
269			break;
270		case 'q':
271			quiet = 1;
272			break;
273		case 'S':
274			if (path != NULL)
275				xfree(path);
276			path = xstrdup(optarg);
277			break;
278		case 'u':
279			flags |= IDENTIFY_UTF8;
280			break;
281		case 'v':
282			debug_level++;
283			break;
284		default:
285			usage();
286		}
287	}
288	argc -= optind;
289	argv += optind;
290
291	if (shell_cmd != NULL && argc != 0)
292		usage();
293
294	log_open_tty(debug_level);
295
296	if (!(flags & IDENTIFY_UTF8)) {
297		/*
298		 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
299		 * exist (in that order) to contain UTF-8, it is a safe
300		 * assumption that either they are using a UTF-8 terminal, or
301		 * if not they know that output from UTF-8-capable programs may
302		 * be wrong.
303		 */
304		if ((s = getenv("LC_ALL")) == NULL) {
305			if ((s = getenv("LC_CTYPE")) == NULL)
306				s = getenv("LANG");
307		}
308		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
309		    strcasestr(s, "UTF8") != NULL))
310			flags |= IDENTIFY_UTF8;
311	}
312
313	environ_init(&global_environ);
314	for (var = environ; *var != NULL; var++)
315		environ_put(&global_environ, *var);
316
317	options_init(&global_options, NULL);
318	options_table_populate_tree(server_options_table, &global_options);
319	options_set_number(&global_options, "quiet", quiet);
320
321	options_init(&global_s_options, NULL);
322	options_table_populate_tree(session_options_table, &global_s_options);
323	options_set_string(&global_s_options, "default-shell", "%s", getshell());
324
325	options_init(&global_w_options, NULL);
326	options_table_populate_tree(window_options_table, &global_w_options);
327
328	/* Set the prefix option (its a list, so not in the table). */
329	keylist = xmalloc(sizeof *keylist);
330	ARRAY_INIT(keylist);
331	ARRAY_ADD(keylist, '\002');
332	options_set_data(&global_s_options, "prefix", keylist, xfree);
333
334	/* Enable UTF-8 if the first client is on UTF-8 terminal. */
335	if (flags & IDENTIFY_UTF8) {
336		options_set_number(&global_s_options, "status-utf8", 1);
337		options_set_number(&global_s_options, "mouse-utf8", 1);
338		options_set_number(&global_w_options, "utf8", 1);
339	}
340
341	/* Override keys to vi if VISUAL or EDITOR are set. */
342	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
343		if (strrchr(s, '/') != NULL)
344			s = strrchr(s, '/') + 1;
345		if (strstr(s, "vi") != NULL)
346			keys = MODEKEY_VI;
347		else
348			keys = MODEKEY_EMACS;
349		options_set_number(&global_s_options, "status-keys", keys);
350		options_set_number(&global_w_options, "mode-keys", keys);
351	}
352
353	/* Locate the configuration file. */
354	if (cfg_file == NULL) {
355		home = getenv("HOME");
356		if (home == NULL || *home == '\0') {
357			pw = getpwuid(getuid());
358			if (pw != NULL)
359				home = pw->pw_dir;
360		}
361		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
362		if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
363			xfree(cfg_file);
364			cfg_file = NULL;
365		}
366	}
367
368	/*
369	 * Figure out the socket path. If specified on the command-line with -S
370	 * or -L, use it, otherwise try $TMUX or assume -L default.
371	 */
372	parseenvironment();
373	if (path == NULL) {
374		/* If no -L, use the environment. */
375		if (label == NULL) {
376			if (environ_path != NULL)
377				path = xstrdup(environ_path);
378			else
379				label = xstrdup("default");
380		}
381
382		/* -L or default set. */
383		if (label != NULL) {
384			if ((path = makesocketpath(label)) == NULL) {
385				log_warn("can't create socket");
386				exit(1);
387			}
388		}
389	}
390	if (label != NULL)
391		xfree(label);
392	if (realpath(path, socket_path) == NULL)
393		strlcpy(socket_path, path, sizeof socket_path);
394	xfree(path);
395
396	/* Set process title. */
397	setproctitle("%s (%s)", __progname, socket_path);
398
399	/* Pass control to the client. */
400	ev_base = event_init();
401	exit(client_main(argc, argv, flags));
402}
403