tmux.c revision 1.45
1/* $OpenBSD: tmux.c,v 1.45 2009/09/23 06:18:48 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 <paths.h>
24#include <pwd.h>
25#include <signal.h>
26#include <stdlib.h>
27#include <string.h>
28#include <syslog.h>
29#include <unistd.h>
30
31#include "tmux.h"
32
33#ifdef DEBUG
34const char	*malloc_options = "AFGJPX";
35#endif
36
37volatile sig_atomic_t sigwinch;
38volatile sig_atomic_t sigterm;
39volatile sig_atomic_t sigcont;
40volatile sig_atomic_t sigchld;
41volatile sig_atomic_t sigusr1;
42volatile sig_atomic_t sigusr2;
43
44char		*cfg_file;
45struct options	 global_s_options;	/* session options */
46struct options	 global_w_options;	/* window options */
47struct environ	 global_environ;
48
49time_t		 server_activity;
50
51int		 debug_level;
52int		 be_quiet;
53time_t		 start_time;
54char		*socket_path;
55int		 login_shell;
56
57__dead void	 usage(void);
58char 		*makesockpath(const char *);
59int		 prepare_cmd(enum msgtype *, void **, size_t *, int, char **);
60int		 dispatch_imsg(struct client_ctx *, int *);
61
62__dead void
63usage(void)
64{
65	fprintf(stderr,
66	    "usage: %s [-28dlquv] [-f file] [-L socket-name]\n"
67	    "            [-S socket-path] [command [flags]]\n",
68	    __progname);
69	exit(1);
70}
71
72void
73logfile(const char *name)
74{
75	char	*path;
76
77	log_close();
78	if (debug_level > 0) {
79		xasprintf(&path, "tmux-%s-%ld.log", name, (long) getpid());
80		log_open_file(debug_level, path);
81		xfree(path);
82	}
83}
84
85void
86sighandler(int sig)
87{
88	int	saved_errno;
89
90	saved_errno = errno;
91	switch (sig) {
92	case SIGWINCH:
93		sigwinch = 1;
94		break;
95	case SIGTERM:
96		sigterm = 1;
97		break;
98	case SIGCHLD:
99		sigchld = 1;
100		break;
101	case SIGCONT:
102		sigcont = 1;
103		break;
104	case SIGUSR1:
105		sigusr1 = 1;
106		break;
107	case SIGUSR2:
108		sigusr2 = 1;
109		break;
110	}
111	errno = saved_errno;
112}
113
114void
115siginit(void)
116{
117	struct sigaction	 act;
118
119	memset(&act, 0, sizeof act);
120	sigemptyset(&act.sa_mask);
121	act.sa_flags = SA_RESTART;
122
123	act.sa_handler = SIG_IGN;
124	if (sigaction(SIGPIPE, &act, NULL) != 0)
125		fatal("sigaction failed");
126	if (sigaction(SIGINT, &act, NULL) != 0)
127		fatal("sigaction failed");
128	if (sigaction(SIGTSTP, &act, NULL) != 0)
129		fatal("sigaction failed");
130	if (sigaction(SIGQUIT, &act, NULL) != 0)
131		fatal("sigaction failed");
132
133	act.sa_handler = sighandler;
134	if (sigaction(SIGWINCH, &act, NULL) != 0)
135		fatal("sigaction failed");
136	if (sigaction(SIGTERM, &act, NULL) != 0)
137		fatal("sigaction failed");
138	if (sigaction(SIGCHLD, &act, NULL) != 0)
139		fatal("sigaction failed");
140	if (sigaction(SIGUSR1, &act, NULL) != 0)
141		fatal("sigaction failed");
142	if (sigaction(SIGUSR2, &act, NULL) != 0)
143		fatal("sigaction failed");
144}
145
146void
147sigreset(void)
148{
149	struct sigaction act;
150
151	memset(&act, 0, sizeof act);
152	sigemptyset(&act.sa_mask);
153
154	act.sa_handler = SIG_DFL;
155	if (sigaction(SIGPIPE, &act, NULL) != 0)
156		fatal("sigaction failed");
157	if (sigaction(SIGUSR1, &act, NULL) != 0)
158		fatal("sigaction failed");
159	if (sigaction(SIGUSR2, &act, NULL) != 0)
160		fatal("sigaction failed");
161	if (sigaction(SIGINT, &act, NULL) != 0)
162		fatal("sigaction failed");
163	if (sigaction(SIGTSTP, &act, NULL) != 0)
164		fatal("sigaction failed");
165	if (sigaction(SIGQUIT, &act, NULL) != 0)
166		fatal("sigaction failed");
167	if (sigaction(SIGWINCH, &act, NULL) != 0)
168		fatal("sigaction failed");
169	if (sigaction(SIGTERM, &act, NULL) != 0)
170		fatal("sigaction failed");
171	if (sigaction(SIGCHLD, &act, NULL) != 0)
172		fatal("sigaction failed");
173}
174
175const char *
176getshell(void)
177{
178	struct passwd	*pw;
179	const char	*shell;
180
181	shell = getenv("SHELL");
182	if (checkshell(shell))
183		return (shell);
184
185	pw = getpwuid(getuid());
186	if (pw != NULL && checkshell(pw->pw_shell))
187		return (pw->pw_shell);
188
189	return (_PATH_BSHELL);
190}
191
192int
193checkshell(const char *shell)
194{
195	if (shell == NULL || *shell == '\0' || areshell(shell))
196		return (0);
197	if (access(shell, X_OK) != 0)
198		return (0);
199	return (1);
200}
201
202int
203areshell(const char *shell)
204{
205	const char	*progname, *ptr;
206
207	if ((ptr = strrchr(shell, '/')) != NULL)
208		ptr++;
209	else
210		ptr = shell;
211	progname = __progname;
212	if (*progname == '-')
213		progname++;
214	if (strcmp(ptr, progname) == 0)
215		return (1);
216	return (0);
217}
218
219char *
220makesockpath(const char *label)
221{
222	char		base[MAXPATHLEN], *path;
223	struct stat	sb;
224	u_int		uid;
225
226	uid = getuid();
227	xsnprintf(base, MAXPATHLEN, "%s/tmux-%d", _PATH_TMP, uid);
228
229	if (mkdir(base, S_IRWXU) != 0 && errno != EEXIST)
230		return (NULL);
231
232	if (lstat(base, &sb) != 0)
233		return (NULL);
234	if (!S_ISDIR(sb.st_mode)) {
235		errno = ENOTDIR;
236		return (NULL);
237	}
238	if (sb.st_uid != uid || (sb.st_mode & (S_IRWXG|S_IRWXO)) != 0) {
239		errno = EACCES;
240		return (NULL);
241	}
242
243	xasprintf(&path, "%s/%s", base, label);
244	return (path);
245}
246
247int
248prepare_cmd(enum msgtype *msg, void **buf, size_t *len, int argc, char **argv)
249{
250	static struct msg_command_data	 cmddata;
251
252	client_fill_session(&cmddata);
253
254	cmddata.argc = argc;
255	if (cmd_pack_argv(argc, argv, cmddata.argv, sizeof cmddata.argv) != 0) {
256		log_warnx("command too long");
257		return (-1);
258	}
259
260	*buf = &cmddata;
261	*len = sizeof cmddata;
262
263	*msg = MSG_COMMAND;
264	return (0);
265}
266
267int
268main(int argc, char **argv)
269{
270	struct client_ctx	 cctx;
271	struct cmd_list		*cmdlist;
272 	struct cmd		*cmd;
273	struct pollfd	 	 pfd;
274	enum msgtype		 msg;
275	struct passwd		*pw;
276	struct options		*so, *wo;
277	struct keylist		*keylist;
278	char			*s, *path, *label, *home, *cause, **var;
279	char			 cwd[MAXPATHLEN];
280	void			*buf;
281	size_t			 len;
282	int	 		 retcode, opt, flags, cmdflags = 0;
283	int			 nfds;
284
285	flags = 0;
286	label = path = NULL;
287	login_shell = (**argv == '-');
288	while ((opt = getopt(argc, argv, "28df:lL:qS:uUv")) != -1) {
289		switch (opt) {
290		case '2':
291			flags |= IDENTIFY_256COLOURS;
292			flags &= ~IDENTIFY_88COLOURS;
293			break;
294		case '8':
295			flags |= IDENTIFY_88COLOURS;
296			flags &= ~IDENTIFY_256COLOURS;
297			break;
298		case 'd':
299			flags |= IDENTIFY_HASDEFAULTS;
300			break;
301		case 'f':
302			if (cfg_file != NULL)
303				xfree(cfg_file);
304			cfg_file = xstrdup(optarg);
305			break;
306		case 'l':
307			login_shell = 1;
308			break;
309		case 'L':
310			if (label != NULL)
311				xfree(label);
312			label = xstrdup(optarg);
313			break;
314		case 'q':
315			be_quiet = 1;
316			break;
317		case 'S':
318			if (path != NULL)
319				xfree(path);
320			path = xstrdup(optarg);
321			break;
322		case 'u':
323			flags |= IDENTIFY_UTF8;
324			break;
325		case 'v':
326			debug_level++;
327			break;
328                default:
329			usage();
330                }
331        }
332	argc -= optind;
333	argv += optind;
334
335	log_open_tty(debug_level);
336	siginit();
337
338	if (!(flags & IDENTIFY_UTF8)) {
339		/*
340		 * If the user has set whichever of LC_ALL, LC_CTYPE or LANG
341		 * exist (in that order) to contain UTF-8, it is a safe
342		 * assumption that either they are using a UTF-8 terminal, or
343		 * if not they know that output from UTF-8-capable programs may
344		 * be wrong.
345		 */
346		if ((s = getenv("LC_ALL")) == NULL) {
347			if ((s = getenv("LC_CTYPE")) == NULL)
348				s = getenv("LANG");
349		}
350		if (s != NULL && (strcasestr(s, "UTF-8") != NULL ||
351		    strcasestr(s, "UTF8") != NULL))
352			flags |= IDENTIFY_UTF8;
353	}
354
355	environ_init(&global_environ);
356 	for (var = environ; *var != NULL; var++)
357		environ_put(&global_environ, *var);
358
359	options_init(&global_s_options, NULL);
360	so = &global_s_options;
361	options_set_number(so, "base-index", 0);
362	options_set_number(so, "bell-action", BELL_ANY);
363	options_set_number(so, "buffer-limit", 9);
364	options_set_string(so, "default-command", "%s", "");
365	options_set_string(so, "default-shell", "%s", getshell());
366	options_set_string(so, "default-terminal", "screen");
367	options_set_number(so, "display-panes-colour", 4);
368	options_set_number(so, "display-panes-time", 1000);
369	options_set_number(so, "display-time", 750);
370	options_set_number(so, "history-limit", 2000);
371	options_set_number(so, "lock-after-time", 0);
372	options_set_string(so, "lock-command", "lock -np");
373	options_set_number(so, "message-attr", 0);
374	options_set_number(so, "message-bg", 3);
375	options_set_number(so, "message-fg", 0);
376	options_set_number(so, "repeat-time", 500);
377	options_set_number(so, "set-remain-on-exit", 0);
378	options_set_number(so, "set-titles", 0);
379	options_set_string(so, "set-titles-string", "#S:#I:#W - \"#T\"");
380	options_set_number(so, "status", 1);
381	options_set_number(so, "status-attr", 0);
382	options_set_number(so, "status-bg", 2);
383	options_set_number(so, "status-fg", 0);
384	options_set_number(so, "status-interval", 15);
385	options_set_number(so, "status-justify", 0);
386	options_set_number(so, "status-keys", MODEKEY_EMACS);
387	options_set_string(so, "status-left", "[#S]");
388	options_set_number(so, "status-left-attr", 0);
389	options_set_number(so, "status-left-bg", 8);
390	options_set_number(so, "status-left-fg", 8);
391	options_set_number(so, "status-left-length", 10);
392	options_set_string(so, "status-right", "\"#22T\" %%H:%%M %%d-%%b-%%y");
393	options_set_number(so, "status-right-attr", 0);
394	options_set_number(so, "status-right-bg", 8);
395	options_set_number(so, "status-right-fg", 8);
396	options_set_number(so, "status-right-length", 40);
397	options_set_string(so, "terminal-overrides",
398	    "*88col*:colors=88,*256col*:colors=256");
399	options_set_string(so, "update-environment", "DISPLAY "
400	    "WINDOWID SSH_ASKPASS SSH_AUTH_SOCK SSH_AGENT_PID SSH_CONNECTION");
401	options_set_number(so, "visual-activity", 0);
402	options_set_number(so, "visual-bell", 0);
403	options_set_number(so, "visual-content", 0);
404
405	keylist = xmalloc(sizeof *keylist);
406	ARRAY_INIT(keylist);
407	ARRAY_ADD(keylist, '\002');
408	options_set_data(so, "prefix", keylist, xfree);
409
410	options_init(&global_w_options, NULL);
411	wo = &global_w_options;
412	options_set_number(wo, "aggressive-resize", 0);
413	options_set_number(wo, "automatic-rename", 1);
414	options_set_number(wo, "clock-mode-colour", 4);
415	options_set_number(wo, "clock-mode-style", 1);
416	options_set_number(wo, "force-height", 0);
417	options_set_number(wo, "force-width", 0);
418	options_set_number(wo, "main-pane-height", 24);
419	options_set_number(wo, "main-pane-width", 81);
420	options_set_number(wo, "mode-attr", 0);
421	options_set_number(wo, "mode-bg", 3);
422	options_set_number(wo, "mode-fg", 0);
423	options_set_number(wo, "mode-keys", MODEKEY_EMACS);
424	options_set_number(wo, "mode-mouse", 0);
425	options_set_number(wo, "monitor-activity", 0);
426	options_set_string(wo, "monitor-content", "%s", "");
427	options_set_number(wo, "window-status-attr", 0);
428	options_set_number(wo, "window-status-bg", 8);
429	options_set_number(wo, "window-status-current-attr", 0);
430	options_set_number(wo, "window-status-current-bg", 8);
431	options_set_number(wo, "window-status-current-fg", 8);
432	options_set_number(wo, "window-status-fg", 8);
433	options_set_number(wo, "xterm-keys", 0);
434 	options_set_number(wo, "remain-on-exit", 0);
435
436 	if (flags & IDENTIFY_UTF8) {
437		options_set_number(so, "status-utf8", 1);
438		options_set_number(wo, "utf8", 1);
439	} else {
440		options_set_number(so, "status-utf8", 0);
441		options_set_number(wo, "utf8", 0);
442	}
443
444	if (getcwd(cwd, sizeof cwd) == NULL) {
445		pw = getpwuid(getuid());
446		if (pw->pw_dir != NULL && *pw->pw_dir != '\0')
447			strlcpy(cwd, pw->pw_dir, sizeof cwd);
448		else
449			strlcpy(cwd, "/", sizeof cwd);
450	}
451	options_set_string(so, "default-path", "%s", cwd);
452
453	if (cfg_file == NULL) {
454		home = getenv("HOME");
455		if (home == NULL || *home == '\0') {
456			pw = getpwuid(getuid());
457			if (pw != NULL)
458				home = pw->pw_dir;
459		}
460		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
461		if (access(cfg_file, R_OK) != 0) {
462			xfree(cfg_file);
463			cfg_file = NULL;
464		}
465	} else {
466		if (access(cfg_file, R_OK) != 0) {
467			log_warn("%s", cfg_file);
468			exit(1);
469		}
470	}
471
472	if (label == NULL)
473		label = xstrdup("default");
474	if (path == NULL && (path = makesockpath(label)) == NULL) {
475		log_warn("can't create socket");
476		exit(1);
477	}
478	xfree(label);
479
480	if (prepare_cmd(&msg, &buf, &len, argc, argv) != 0)
481		exit(1);
482
483	if (argc == 0)	/* new-session is the default */
484		cmdflags |= CMD_STARTSERVER|CMD_SENDENVIRON;
485	else {
486		/*
487		 * It sucks parsing the command string twice (in client and
488		 * later in server) but it is necessary to get the start server
489		 * flag.
490		 */
491		if ((cmdlist = cmd_list_parse(argc, argv, &cause)) == NULL) {
492			log_warnx("%s", cause);
493			exit(1);
494		}
495		cmdflags &= ~CMD_STARTSERVER;
496		TAILQ_FOREACH(cmd, cmdlist, qentry) {
497			if (cmd->entry->flags & CMD_STARTSERVER)
498				cmdflags |= CMD_STARTSERVER;
499			if (cmd->entry->flags & CMD_SENDENVIRON)
500				cmdflags |= CMD_SENDENVIRON;
501		}
502		cmd_list_free(cmdlist);
503	}
504
505 	memset(&cctx, 0, sizeof cctx);
506	if (client_init(path, &cctx, cmdflags, flags) != 0)
507		exit(1);
508	xfree(path);
509
510	client_write_server(&cctx, msg, buf, len);
511	memset(buf, 0, len);
512
513	retcode = 0;
514	for (;;) {
515		pfd.fd = cctx.ibuf.fd;
516		pfd.events = POLLIN;
517		if (cctx.ibuf.w.queued != 0)
518			pfd.events |= POLLOUT;
519
520		if ((nfds = poll(&pfd, 1, INFTIM)) == -1) {
521			if (errno == EAGAIN || errno == EINTR)
522				continue;
523			fatal("poll failed");
524		}
525		if (nfds == 0)
526			continue;
527
528		if (pfd.revents & (POLLERR|POLLHUP|POLLNVAL))
529			fatalx("socket error");
530
531                if (pfd.revents & POLLIN) {
532			if (dispatch_imsg(&cctx, &retcode) != 0)
533				break;
534		}
535
536		if (pfd.revents & POLLOUT) {
537			if (msgbuf_write(&cctx.ibuf.w) < 0)
538				fatalx("msgbuf_write failed");
539		}
540	}
541
542	options_free(&global_s_options);
543	options_free(&global_w_options);
544
545	return (retcode);
546}
547
548int
549dispatch_imsg(struct client_ctx *cctx, int *retcode)
550{
551	struct imsg		imsg;
552	ssize_t			n, datalen;
553	struct msg_print_data	printdata;
554
555        if ((n = imsg_read(&cctx->ibuf)) == -1 || n == 0)
556		fatalx("imsg_read failed");
557
558	for (;;) {
559		if ((n = imsg_get(&cctx->ibuf, &imsg)) == -1)
560			fatalx("imsg_get failed");
561		if (n == 0)
562			return (0);
563		datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
564
565		switch (imsg.hdr.type) {
566		case MSG_EXIT:
567		case MSG_SHUTDOWN:
568			if (datalen != 0)
569				fatalx("bad MSG_EXIT size");
570
571			return (-1);
572		case MSG_ERROR:
573			*retcode = 1;
574			/* FALLTHROUGH */
575		case MSG_PRINT:
576			if (datalen != sizeof printdata)
577				fatalx("bad MSG_PRINT size");
578			memcpy(&printdata, imsg.data, sizeof printdata);
579			printdata.msg[(sizeof printdata.msg) - 1] = '\0';
580
581			log_info("%s", printdata.msg);
582			break;
583		case MSG_READY:
584			if (datalen != 0)
585				fatalx("bad MSG_READY size");
586
587			*retcode = client_main(cctx);
588			return (-1);
589		case MSG_VERSION:
590			if (datalen != 0)
591				fatalx("bad MSG_VERSION size");
592
593			log_warnx("protocol version mismatch (client %u, "
594			    "server %u)", PROTOCOL_VERSION, imsg.hdr.peerid);
595			*retcode = 1;
596			return (-1);
597		default:
598			fatalx("unexpected message");
599		}
600
601		imsg_free(&imsg);
602	}
603}
604