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