]> git.sur5r.net Git - i3/i3/blob - i3-msg/main.c
Use safe wrappers wherever possible
[i3/i3] / i3-msg / main.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * i3-msg/main.c: Utility which sends messages to a running i3-instance using
8  * IPC via UNIX domain sockets.
9  *
10  * This (in combination with libi3/ipc_send_message.c and
11  * libi3/ipc_recv_message.c) serves as an example for how to send your own
12  * messages to i3.
13  *
14  * Additionally, it’s even useful sometimes :-).
15  *
16  */
17 #include <stdio.h>
18 #include <stdbool.h>
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <err.h>
27 #include <stdint.h>
28 #include <getopt.h>
29 #include <limits.h>
30
31 #include <yajl/yajl_parse.h>
32 #include <yajl/yajl_version.h>
33
34 #include <xcb/xcb.h>
35 #include <xcb/xcb_aux.h>
36
37 #include "libi3.h"
38 #include <i3/ipc.h>
39
40 static char *socket_path;
41
42 /*
43  * Having verboselog() and errorlog() is necessary when using libi3.
44  *
45  */
46 void verboselog(char *fmt, ...) {
47     va_list args;
48
49     va_start(args, fmt);
50     vfprintf(stdout, fmt, args);
51     va_end(args);
52 }
53
54 void errorlog(char *fmt, ...) {
55     va_list args;
56
57     va_start(args, fmt);
58     vfprintf(stderr, fmt, args);
59     va_end(args);
60 }
61
62 static char *last_key = NULL;
63
64 typedef struct reply_t {
65     bool success;
66     char *error;
67     char *input;
68     char *errorposition;
69 } reply_t;
70
71 static reply_t last_reply;
72
73 static int reply_boolean_cb(void *params, int val) {
74     if (strcmp(last_key, "success") == 0)
75         last_reply.success = val;
76     return 1;
77 }
78
79 static int reply_string_cb(void *params, const unsigned char *val, size_t len) {
80     char *str = scalloc(len + 1, 1);
81     strncpy(str, (const char *)val, len);
82     if (strcmp(last_key, "error") == 0)
83         last_reply.error = str;
84     else if (strcmp(last_key, "input") == 0)
85         last_reply.input = str;
86     else if (strcmp(last_key, "errorposition") == 0)
87         last_reply.errorposition = str;
88     else
89         free(str);
90     return 1;
91 }
92
93 static int reply_start_map_cb(void *params) {
94     return 1;
95 }
96
97 static int reply_end_map_cb(void *params) {
98     if (!last_reply.success) {
99         fprintf(stderr, "ERROR: Your command: %s\n", last_reply.input);
100         fprintf(stderr, "ERROR:               %s\n", last_reply.errorposition);
101         fprintf(stderr, "ERROR: %s\n", last_reply.error);
102     }
103     return 1;
104 }
105
106 static int reply_map_key_cb(void *params, const unsigned char *keyVal, size_t keyLen) {
107     free(last_key);
108     last_key = scalloc(keyLen + 1, 1);
109     strncpy(last_key, (const char *)keyVal, keyLen);
110     return 1;
111 }
112
113 static yajl_callbacks reply_callbacks = {
114     .yajl_boolean = reply_boolean_cb,
115     .yajl_string = reply_string_cb,
116     .yajl_start_map = reply_start_map_cb,
117     .yajl_map_key = reply_map_key_cb,
118     .yajl_end_map = reply_end_map_cb,
119 };
120
121 int main(int argc, char *argv[]) {
122     socket_path = getenv("I3SOCK");
123     int o, option_index = 0;
124     uint32_t message_type = I3_IPC_MESSAGE_TYPE_COMMAND;
125     char *payload = NULL;
126     bool quiet = false;
127
128     static struct option long_options[] = {
129         {"socket", required_argument, 0, 's'},
130         {"type", required_argument, 0, 't'},
131         {"version", no_argument, 0, 'v'},
132         {"quiet", no_argument, 0, 'q'},
133         {"help", no_argument, 0, 'h'},
134         {0, 0, 0, 0}};
135
136     char *options_string = "s:t:vhq";
137
138     while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
139         if (o == 's') {
140             if (socket_path != NULL)
141                 free(socket_path);
142             socket_path = sstrdup(optarg);
143         } else if (o == 't') {
144             if (strcasecmp(optarg, "command") == 0)
145                 message_type = I3_IPC_MESSAGE_TYPE_COMMAND;
146             else if (strcasecmp(optarg, "get_workspaces") == 0)
147                 message_type = I3_IPC_MESSAGE_TYPE_GET_WORKSPACES;
148             else if (strcasecmp(optarg, "get_outputs") == 0)
149                 message_type = I3_IPC_MESSAGE_TYPE_GET_OUTPUTS;
150             else if (strcasecmp(optarg, "get_tree") == 0)
151                 message_type = I3_IPC_MESSAGE_TYPE_GET_TREE;
152             else if (strcasecmp(optarg, "get_marks") == 0)
153                 message_type = I3_IPC_MESSAGE_TYPE_GET_MARKS;
154             else if (strcasecmp(optarg, "get_bar_config") == 0)
155                 message_type = I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG;
156             else if (strcasecmp(optarg, "get_version") == 0)
157                 message_type = I3_IPC_MESSAGE_TYPE_GET_VERSION;
158             else {
159                 printf("Unknown message type\n");
160                 printf("Known types: command, get_workspaces, get_outputs, get_tree, get_marks, get_bar_config, get_version\n");
161                 exit(EXIT_FAILURE);
162             }
163         } else if (o == 'q') {
164             quiet = true;
165         } else if (o == 'v') {
166             printf("i3-msg " I3_VERSION "\n");
167             return 0;
168         } else if (o == 'h') {
169             printf("i3-msg " I3_VERSION "\n");
170             printf("i3-msg [-s <socket>] [-t <type>] <message>\n");
171             return 0;
172         }
173     }
174
175     if (socket_path == NULL)
176         socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
177
178     /* Fall back to the default socket path */
179     if (socket_path == NULL)
180         socket_path = sstrdup("/tmp/i3-ipc.sock");
181
182     /* Use all arguments, separated by whitespace, as payload.
183      * This way, you don’t have to do i3-msg 'mark foo', you can use
184      * i3-msg mark foo */
185     while (optind < argc) {
186         if (!payload) {
187             payload = sstrdup(argv[optind]);
188         } else {
189             char *both;
190             sasprintf(&both, "%s %s", payload, argv[optind]);
191             free(payload);
192             payload = both;
193         }
194         optind++;
195     }
196
197     if (!payload)
198         payload = "";
199
200     int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
201     if (sockfd == -1)
202         err(EXIT_FAILURE, "Could not create socket");
203
204     struct sockaddr_un addr;
205     memset(&addr, 0, sizeof(struct sockaddr_un));
206     addr.sun_family = AF_LOCAL;
207     strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
208     if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
209         err(EXIT_FAILURE, "Could not connect to i3 on socket \"%s\"", socket_path);
210
211     if (ipc_send_message(sockfd, strlen(payload), message_type, (uint8_t *)payload) == -1)
212         err(EXIT_FAILURE, "IPC: write()");
213
214     if (quiet)
215         return 0;
216
217     uint32_t reply_length;
218     uint32_t reply_type;
219     uint8_t *reply;
220     int ret;
221     if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
222         if (ret == -1)
223             err(EXIT_FAILURE, "IPC: read()");
224         exit(1);
225     }
226     if (reply_type != message_type)
227         errx(EXIT_FAILURE, "IPC: Received reply of type %d but expected %d", reply_type, message_type);
228     /* For the reply of commands, have a look if that command was successful.
229      * If not, nicely format the error message. */
230     if (reply_type == I3_IPC_MESSAGE_TYPE_COMMAND) {
231         yajl_handle handle;
232         handle = yajl_alloc(&reply_callbacks, NULL, NULL);
233         yajl_status state = yajl_parse(handle, (const unsigned char *)reply, reply_length);
234         switch (state) {
235             case yajl_status_ok:
236                 break;
237             case yajl_status_client_canceled:
238             case yajl_status_error:
239                 errx(EXIT_FAILURE, "IPC: Could not parse JSON reply.");
240         }
241
242         /* NB: We still fall-through and print the reply, because even if one
243          * command failed, that doesn’t mean that all commands failed. */
244     }
245     printf("%.*s\n", reply_length, reply);
246     free(reply);
247
248     close(sockfd);
249
250     return 0;
251 }