xref: /netbsd-src/external/bsd/tmux/dist/tmux.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /* $Id: tmux.c,v 1.1.1.1 2011/03/10 09:15:39 jmmv 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 <pwd.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 
30 #include "tmux.h"
31 
32 #if defined(DEBUG) && defined(__OpenBSD__)
33 extern char	*malloc_options;
34 #endif
35 
36 struct options	 global_options;	/* server options */
37 struct options	 global_s_options;	/* session options */
38 struct options	 global_w_options;	/* window options */
39 struct environ	 global_environ;
40 
41 struct event_base *ev_base;
42 
43 char		*cfg_file;
44 char		*shell_cmd;
45 int		 debug_level;
46 time_t		 start_time;
47 char		 socket_path[MAXPATHLEN];
48 int		 login_shell;
49 char		*environ_path;
50 pid_t		 environ_pid;
51 u_int		 environ_idx;
52 
53 __dead void	 usage(void);
54 void	 	 parseenvironment(void);
55 char 		*makesocketpath(const char *);
56 
57 #ifndef HAVE_PROGNAME
58 char      *__progname = (char *) "tmux";
59 #endif
60 
61 __dead void
62 usage(void)
63 {
64 	fprintf(stderr,
65 	    "usage: %s [-28lquvV] [-c shell-command] [-f file] [-L socket-name]\n"
66 	    "            [-S socket-path] [command [flags]]\n",
67 	    __progname);
68 	exit(1);
69 }
70 
71 void
72 logfile(const char *name)
73 {
74 	char	*path;
75 
76 	log_close();
77 	if (debug_level > 0) {
78 		xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
79 		log_open_file(debug_level, path);
80 		xfree(path);
81 	}
82 }
83 
84 const char *
85 getshell(void)
86 {
87 	struct passwd	*pw;
88 	const char	*shell;
89 
90 	shell = getenv("SHELL");
91 	if (checkshell(shell))
92 		return (shell);
93 
94 	pw = getpwuid(getuid());
95 	if (pw != NULL && checkshell(pw->pw_shell))
96 		return (pw->pw_shell);
97 
98 	return (_PATH_BSHELL);
99 }
100 
101 int
102 checkshell(const char *shell)
103 {
104 	if (shell == NULL || *shell == '\0' || areshell(shell))
105 		return (0);
106 	if (access(shell, X_OK) != 0)
107 		return (0);
108 	return (1);
109 }
110 
111 int
112 areshell(const char *shell)
113 {
114 	const char	*progname, *ptr;
115 
116 	if ((ptr = strrchr(shell, '/')) != NULL)
117 		ptr++;
118 	else
119 		ptr = shell;
120 	progname = __progname;
121 	if (*progname == '-')
122 		progname++;
123 	if (strcmp(ptr, progname) == 0)
124 		return (1);
125 	return (0);
126 }
127 
128 void
129 parseenvironment(void)
130 {
131 	char		*env, *path_pid, *pid_idx, buf[256];
132 	size_t		 len;
133 	const char	*errstr;
134 	long long	 ll;
135 
136 	environ_pid = -1;
137 	if ((env = getenv("TMUX")) == NULL)
138 		return;
139 
140 	if ((path_pid = strchr(env, ',')) == NULL || path_pid == env)
141 		return;
142 	if ((pid_idx = strchr(path_pid + 1, ',')) == NULL)
143 		return;
144 	if ((pid_idx == path_pid + 1 || pid_idx[1] == '\0'))
145 		return;
146 
147 	/* path */
148 	len = path_pid - env;
149 	environ_path = xmalloc(len + 1);
150 	memcpy(environ_path, env, len);
151 	environ_path[len] = '\0';
152 
153 	/* pid */
154 	len = pid_idx - path_pid - 1;
155 	if (len > (sizeof buf) - 1)
156 		return;
157 	memcpy(buf, path_pid + 1, len);
158 	buf[len] = '\0';
159 
160 	ll = strtonum(buf, 0, LONG_MAX, &errstr);
161 	if (errstr != NULL)
162 		return;
163 	environ_pid = ll;
164 
165 	/* idx */
166 	ll = strtonum(pid_idx + 1, 0, UINT_MAX, &errstr);
167 	if (errstr != NULL)
168 		return;
169 	environ_idx = ll;
170 }
171 
172 char *
173 makesocketpath(const char *label)
174 {
175 	char		base[MAXPATHLEN], *path;
176 	struct stat	sb;
177 	u_int		uid;
178 
179 	uid = getuid();
180 	xsnprintf(base, MAXPATHLEN, "%s/tmux-%d", _PATH_TMP, 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 __dead void
201 shell_exec(const char *shell, const char *shellcmd)
202 {
203 	const char	*shellname, *ptr;
204 	char		*argv0;
205 	int		 mode;
206 
207 	ptr = strrchr(shell, '/');
208 	if (ptr != NULL && *(ptr + 1) != '\0')
209 		shellname = ptr + 1;
210 	else
211 		shellname = shell;
212 	if (login_shell)
213 		xasprintf(&argv0, "-%s", shellname);
214 	else
215 		xasprintf(&argv0, "%s", shellname);
216 	setenv("SHELL", shell, 1);
217 
218 	if ((mode = fcntl(STDIN_FILENO, F_GETFL)) != -1)
219 		fcntl(STDIN_FILENO, F_SETFL, mode & ~O_NONBLOCK);
220 	if ((mode = fcntl(STDOUT_FILENO, F_GETFL)) != -1)
221 		fcntl(STDOUT_FILENO, F_SETFL, mode & ~O_NONBLOCK);
222 	if ((mode = fcntl(STDERR_FILENO, F_GETFL)) != -1)
223 		fcntl(STDERR_FILENO, F_SETFL, mode & ~O_NONBLOCK);
224 	closefrom(STDERR_FILENO + 1);
225 
226 	execl(shell, argv0, "-c", shellcmd, (char *) NULL);
227 	fatal("execl failed");
228 }
229 
230 int
231 main(int argc, char **argv)
232 {
233 	struct passwd	*pw;
234 	struct options	*oo, *so, *wo;
235 	struct keylist	*keylist;
236 	char		*s, *path, *label, *home, **var;
237 	int	 	 opt, flags, quiet, keys;
238 
239 #if defined(DEBUG) && defined(__OpenBSD__)
240 	malloc_options = (char *) "AFGJPX";
241 #endif
242 
243 	quiet = flags = 0;
244 	label = path = NULL;
245 	login_shell = (**argv == '-');
246 	while ((opt = getopt(argc, argv, "28c:df:lL:qS:uUvV")) != -1) {
247 		switch (opt) {
248 		case '2':
249 			flags |= IDENTIFY_256COLOURS;
250 			flags &= ~IDENTIFY_88COLOURS;
251 			break;
252 		case '8':
253 			flags |= IDENTIFY_88COLOURS;
254 			flags &= ~IDENTIFY_256COLOURS;
255 			break;
256 		case 'c':
257 			if (shell_cmd != NULL)
258 				xfree(shell_cmd);
259 			shell_cmd = xstrdup(optarg);
260 			break;
261 		case 'V':
262 			printf("%s %s\n", __progname, BUILD);
263 			exit(0);
264 		case 'f':
265 			if (cfg_file != NULL)
266 				xfree(cfg_file);
267 			cfg_file = xstrdup(optarg);
268 			break;
269 		case 'l':
270 			login_shell = 1;
271 			break;
272 		case 'L':
273 			if (label != NULL)
274 				xfree(label);
275 			label = xstrdup(optarg);
276 			break;
277 		case 'q':
278 			quiet = 1;
279 			break;
280 		case 'S':
281 			if (path != NULL)
282 				xfree(path);
283 			path = xstrdup(optarg);
284 			break;
285 		case 'u':
286 			flags |= IDENTIFY_UTF8;
287 			break;
288 		case 'v':
289 			debug_level++;
290 			break;
291 		default:
292 			usage();
293 		}
294 	}
295 	argc -= optind;
296 	argv += optind;
297 
298 	if (shell_cmd != NULL && argc != 0)
299 		usage();
300 
301 	log_open_tty(debug_level);
302 
303 	if (!(flags & IDENTIFY_UTF8)) {
304 		/*
305 		 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
306 		 * exist (in that order) to contain UTF-8, it is a safe
307 		 * assumption that either they are using a UTF-8 terminal, or
308 		 * if not they know that output from UTF-8-capable programs may
309 		 * be wrong.
310 		 */
311 		if ((s = getenv("LC_ALL")) == NULL) {
312 			if ((s = getenv("LC_CTYPE")) == NULL)
313 				s = getenv("LANG");
314 		}
315 		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
316 		    strcasestr(s, "UTF8") != NULL))
317 			flags |= IDENTIFY_UTF8;
318 	}
319 
320 	environ_init(&global_environ);
321 	for (var = environ; *var != NULL; var++)
322 		environ_put(&global_environ, *var);
323 
324 	options_init(&global_options, NULL);
325 	oo = &global_options;
326 	options_set_number(oo, "quiet", quiet);
327 	options_set_number(oo, "escape-time", 500);
328 	options_set_number(oo, "exit-unattached", 0);
329 
330 	options_init(&global_s_options, NULL);
331 	so = &global_s_options;
332 	options_set_number(so, "base-index", 0);
333 	options_set_number(so, "bell-action", BELL_ANY);
334 	options_set_number(so, "buffer-limit", 9);
335 	options_set_string(so, "default-command", "%s", "");
336 	options_set_string(so, "default-path", "%s", "");
337 	options_set_string(so, "default-shell", "%s", getshell());
338 	options_set_string(so, "default-terminal", "screen");
339 	options_set_number(so, "destroy-unattached", 0);
340 	options_set_number(so, "detach-on-destroy", 1);
341 	options_set_number(so, "display-panes-active-colour", 1);
342 	options_set_number(so, "display-panes-colour", 4);
343 	options_set_number(so, "display-panes-time", 1000);
344 	options_set_number(so, "display-time", 750);
345 	options_set_number(so, "history-limit", 2000);
346 	options_set_number(so, "lock-after-time", 0);
347 	options_set_string(so, "lock-command", "lock -np");
348 	options_set_number(so, "lock-server", 1);
349 	options_set_number(so, "message-attr", 0);
350 	options_set_number(so, "message-bg", 3);
351 	options_set_number(so, "message-fg", 0);
352 	options_set_number(so, "message-limit", 20);
353 	options_set_number(so, "mouse-select-pane", 0);
354 	options_set_number(so, "pane-active-border-bg", 8);
355 	options_set_number(so, "pane-active-border-fg", 2);
356 	options_set_number(so, "pane-border-bg", 8);
357 	options_set_number(so, "pane-border-fg", 8);
358 	options_set_number(so, "repeat-time", 500);
359 	options_set_number(so, "set-remain-on-exit", 0);
360 	options_set_number(so, "set-titles", 0);
361 	options_set_string(so, "set-titles-string", "#S:#I:#W - \"#T\"");
362 	options_set_number(so, "status", 1);
363 	options_set_number(so, "status-attr", 0);
364 	options_set_number(so, "status-bg", 2);
365 	options_set_number(so, "status-fg", 0);
366 	options_set_number(so, "status-interval", 15);
367 	options_set_number(so, "status-justify", 0);
368 	options_set_string(so, "status-left", "[#S]");
369 	options_set_number(so, "status-left-attr", 0);
370 	options_set_number(so, "status-left-bg", 8);
371 	options_set_number(so, "status-left-fg", 8);
372 	options_set_number(so, "status-left-length", 10);
373 	options_set_string(so, "status-right", "\"#22T\" %%H:%%M %%d-%%b-%%y");
374 	options_set_number(so, "status-right-attr", 0);
375 	options_set_number(so, "status-right-bg", 8);
376 	options_set_number(so, "status-right-fg", 8);
377 	options_set_number(so, "status-right-length", 40);
378 	options_set_string(so, "terminal-overrides",
379 	    "*88col*:colors=88,*256col*:colors=256");
380 	options_set_string(so, "update-environment",
381 	    "DISPLAY "
382 	    "SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION "
383 	    "WINDOWID "
384 	    "XAUTHORITY");
385 	options_set_number(so, "visual-activity", 0);
386 	options_set_number(so, "visual-bell", 0);
387 	options_set_number(so, "visual-content", 0);
388 	options_set_number(so, "visual-silence", 0);
389 
390 	keylist = xmalloc(sizeof *keylist);
391 	ARRAY_INIT(keylist);
392 	ARRAY_ADD(keylist, '\002');
393 	options_set_data(so, "prefix", keylist, xfree);
394 
395 	options_init(&global_w_options, NULL);
396 	wo = &global_w_options;
397 	options_set_number(wo, "aggressive-resize", 0);
398 	options_set_number(wo, "alternate-screen", 1);
399 	options_set_number(wo, "automatic-rename", 1);
400 	options_set_number(wo, "clock-mode-colour", 4);
401 	options_set_number(wo, "clock-mode-style", 1);
402 	options_set_number(wo, "force-height", 0);
403 	options_set_number(wo, "force-width", 0);
404 	options_set_number(wo, "main-pane-height", 24);
405 	options_set_number(wo, "main-pane-width", 80);
406 	options_set_number(wo, "mode-attr", 0);
407 	options_set_number(wo, "mode-bg", 3);
408 	options_set_number(wo, "mode-fg", 0);
409 	options_set_number(wo, "mode-mouse", 0);
410 	options_set_number(wo, "monitor-activity", 0);
411 	options_set_string(wo, "monitor-content", "%s", "");
412 	options_set_number(wo, "monitor-silence", 0);
413 	options_set_number(wo, "other-pane-height", 0);
414 	options_set_number(wo, "other-pane-width", 0);
415 	options_set_number(wo, "window-status-attr", 0);
416 	options_set_number(wo, "window-status-bg", 8);
417 	options_set_number(wo, "window-status-current-attr", 0);
418 	options_set_number(wo, "window-status-current-bg", 8);
419 	options_set_number(wo, "window-status-current-fg", 8);
420 	options_set_number(wo, "window-status-fg", 8);
421 	options_set_number(wo, "window-status-alert-attr", GRID_ATTR_REVERSE);
422 	options_set_number(wo, "window-status-alert-bg", 8);
423 	options_set_number(wo, "window-status-alert-fg", 8);
424 	options_set_string(wo, "window-status-format", "#I:#W#F");
425 	options_set_string(wo, "window-status-current-format", "#I:#W#F");
426 	options_set_string(wo, "word-separators", " -_@");
427 	options_set_number(wo, "xterm-keys", 0);
428 	options_set_number(wo, "remain-on-exit", 0);
429 	options_set_number(wo, "synchronize-panes", 0);
430 
431 	if (flags & IDENTIFY_UTF8) {
432 		options_set_number(so, "status-utf8", 1);
433 		options_set_number(wo, "utf8", 1);
434 	} else {
435 		options_set_number(so, "status-utf8", 0);
436 		options_set_number(wo, "utf8", 0);
437 	}
438 
439 	keys = MODEKEY_EMACS;
440 	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
441 		if (strrchr(s, '/') != NULL)
442 			s = strrchr(s, '/') + 1;
443 		if (strstr(s, "vi") != NULL)
444 			keys = MODEKEY_VI;
445 	}
446 	options_set_number(so, "status-keys", keys);
447 	options_set_number(wo, "mode-keys", keys);
448 
449 	/* Locate the configuration file. */
450 	if (cfg_file == NULL) {
451 		home = getenv("HOME");
452 		if (home == NULL || *home == '\0') {
453 			pw = getpwuid(getuid());
454 			if (pw != NULL)
455 				home = pw->pw_dir;
456 		}
457 		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
458 		if (access(cfg_file, R_OK) != 0 && errno == ENOENT) {
459 			xfree(cfg_file);
460 			cfg_file = NULL;
461 		}
462 	}
463 
464 	/*
465 	 * Figure out the socket path. If specified on the command-line with -S
466 	 * or -L, use it, otherwise try $TMUX or assume -L default.
467 	 */
468 	parseenvironment();
469 	if (path == NULL) {
470 		/* If no -L, use the environment. */
471 		if (label == NULL) {
472 			if (environ_path != NULL)
473 				path = xstrdup(environ_path);
474 			else
475 				label = xstrdup("default");
476 		}
477 
478 		/* -L or default set. */
479 		if (label != NULL) {
480 			if ((path = makesocketpath(label)) == NULL) {
481 				log_warn("can't create socket");
482 				exit(1);
483 			}
484 		}
485 	}
486 	if (label != NULL)
487 		xfree(label);
488 	if (realpath(path, socket_path) == NULL)
489 		strlcpy(socket_path, path, sizeof socket_path);
490 	xfree(path);
491 
492 #ifdef HAVE_SETPROCTITLE
493 	/* Set process title. */
494 	setproctitle("%s (%s)", __progname, socket_path);
495 #endif
496 
497 	/* Pass control to the client. */
498 #ifdef HAVE_BROKEN_KQUEUE
499 	if (setenv("EVENT_NOKQUEUE", "1", 1) != 0)
500 		fatal("setenv failed");
501 #endif
502 #ifdef HAVE_BROKEN_POLL
503 	if (setenv("EVENT_NOPOLL", "1", 1) != 0)
504 		fatal("setenv failed");
505 #endif
506 	ev_base = event_init();
507 #ifdef HAVE_BROKEN_KQUEUE
508 	unsetenv("EVENT_NOKQUEUE");
509 #endif
510 #ifdef HAVE_BROKEN_POLL
511 	unsetenv("EVENT_NOPOLL");
512 #endif
513 	exit(client_main(argc, argv, flags));
514 }
515