xref: /openbsd-src/usr.bin/tmux/control.c (revision 48950c12d106c85f315112191a0228d7b83b9510)
1 /* $OpenBSD: control.c,v 1.9 2013/03/25 11:35:55 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2012 Nicholas Marriott <nicm@users.sourceforge.net>
5  * Copyright (c) 2012 George Nachman <tmux@georgester.com>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
16  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
17  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/types.h>
21 
22 #include <event.h>
23 #include <stdlib.h>
24 #include <string.h>
25 
26 #include "tmux.h"
27 
28 /* Write a line. */
29 void printflike2
30 control_write(struct client *c, const char *fmt, ...)
31 {
32 	va_list		 ap;
33 
34 	va_start(ap, fmt);
35 	evbuffer_add_vprintf(c->stdout_data, fmt, ap);
36 	va_end(ap);
37 
38 	evbuffer_add(c->stdout_data, "\n", 1);
39 	server_push_stdout(c);
40 }
41 
42 /* Write a buffer, adding a terminal newline. Empties buffer. */
43 void
44 control_write_buffer(struct client *c, struct evbuffer *buffer)
45 {
46 	evbuffer_add_buffer(c->stdout_data, buffer);
47 	evbuffer_add(c->stdout_data, "\n", 1);
48 	server_push_stdout(c);
49 }
50 
51 /* Control input callback. Read lines and fire commands. */
52 void
53 control_callback(struct client *c, int closed, unused void *data)
54 {
55 	char		*line, *cause;
56 	struct cmd_list	*cmdlist;
57 
58 	if (closed)
59 		c->flags |= CLIENT_EXIT;
60 
61 	for (;;) {
62 		line = evbuffer_readln(c->stdin_data, NULL, EVBUFFER_EOL_LF);
63 		if (line == NULL)
64 			break;
65 		if (*line == '\0') { /* empty line exit */
66 			c->flags |= CLIENT_EXIT;
67 			break;
68 		}
69 
70 		if (cmd_string_parse(line, &cmdlist, NULL, 0, &cause) != 0) {
71 			c->cmdq->time = time(NULL);
72 			c->cmdq->number++;
73 
74 			cmdq_guard(c->cmdq, "begin");
75 			control_write(c, "parse error: %s", cause);
76 			cmdq_guard(c->cmdq, "error");
77 
78 			free(cause);
79 		} else {
80 			cmdq_run(c->cmdq, cmdlist);
81 			cmd_list_free(cmdlist);
82 		}
83 
84 		free(line);
85 	}
86 }
87