]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
8ed455dd13ab15406ea457d7dd910fe7eb683880
[i3/i3] / src / ipc.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009-2010 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * ipc.c: Everything about the UNIX domain sockets for IPC
11  *
12  */
13 #include <sys/types.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include <errno.h>
20 #include <err.h>
21 #include <stdlib.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <ev.h>
25 #include <yajl/yajl_gen.h>
26 #include <yajl/yajl_parse.h>
27
28 #include "queue.h"
29 #include "ipc.h"
30 #include "i3.h"
31 #include "util.h"
32 #include "commands.h"
33 #include "log.h"
34 #include "table.h"
35 #include "randr.h"
36
37 /* Shorter names for all those yajl_gen_* functions */
38 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
39 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
40
41 TAILQ_HEAD(ipc_client_head, ipc_client) all_clients = TAILQ_HEAD_INITIALIZER(all_clients);
42
43 /*
44  * Puts the given socket file descriptor into non-blocking mode or dies if
45  * setting O_NONBLOCK failed. Non-blocking sockets are a good idea for our
46  * IPC model because we should by no means block the window manager.
47  *
48  */
49 static void set_nonblock(int sockfd) {
50         int flags = fcntl(sockfd, F_GETFL, 0);
51         flags |= O_NONBLOCK;
52         if (fcntl(sockfd, F_SETFL, flags) < 0)
53                 err(-1, "Could not set O_NONBLOCK");
54 }
55
56 static void ipc_send_message(int fd, const unsigned char *payload,
57                              int message_type, int message_size) {
58         int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) +
59                           sizeof(uint32_t) + message_size;
60         char msg[buffer_size];
61         char *walk = msg;
62
63         strcpy(walk, "i3-ipc");
64         walk += strlen("i3-ipc");
65         memcpy(walk, &message_size, sizeof(uint32_t));
66         walk += sizeof(uint32_t);
67         memcpy(walk, &message_type, sizeof(uint32_t));
68         walk += sizeof(uint32_t);
69         memcpy(walk, payload, message_size);
70
71         int sent_bytes = 0;
72         int bytes_to_go = buffer_size;
73         while (sent_bytes < bytes_to_go) {
74                 int n = write(fd, msg + sent_bytes, bytes_to_go);
75                 if (n == -1) {
76                         DLOG("write() failed: %s\n", strerror(errno));
77                         return;
78                 }
79
80                 sent_bytes += n;
81                 bytes_to_go -= n;
82         }
83 }
84
85 /*
86  * Sends the specified event to all IPC clients which are currently connected
87  * and subscribed to this kind of event.
88  *
89  */
90 void ipc_send_event(const char *event, uint32_t message_type, const char *payload) {
91         ipc_client *current;
92         TAILQ_FOREACH(current, &all_clients, clients) {
93                 /* see if this client is interested in this event */
94                 bool interested = false;
95                 for (int i = 0; i < current->num_events; i++) {
96                         if (strcasecmp(current->events[i], event) != 0)
97                                 continue;
98                         interested = true;
99                         break;
100                 }
101                 if (!interested)
102                         continue;
103
104                 ipc_send_message(current->fd, (const unsigned char*)payload,
105                                  message_type, strlen(payload));
106         }
107 }
108
109 /*
110  * Calls shutdown() on each socket and closes it. This function to be called
111  * when exiting or restarting only!
112  *
113  */
114 void ipc_shutdown() {
115         ipc_client *current;
116         TAILQ_FOREACH(current, &all_clients, clients) {
117                 shutdown(current->fd, SHUT_RDWR);
118                 close(current->fd);
119         }
120 }
121
122 /*
123  * Executes the command and returns whether it could be successfully parsed
124  * or not (at the moment, always returns true).
125  *
126  */
127 IPC_HANDLER(command) {
128         /* To get a properly terminated buffer, we copy
129          * message_size bytes out of the buffer */
130         char *command = scalloc(message_size);
131         strncpy(command, (const char*)message, message_size);
132         parse_command(global_conn, (const char*)command);
133         free(command);
134
135         /* For now, every command gets a positive acknowledge
136          * (will change with the new command parser) */
137         const char *reply = "{\"success\":true}";
138         ipc_send_message(fd, (const unsigned char*)reply,
139                          I3_IPC_REPLY_TYPE_COMMAND, strlen(reply));
140 }
141
142 /*
143  * Formats the reply message for a GET_WORKSPACES request and sends it to the
144  * client
145  *
146  */
147 IPC_HANDLER(get_workspaces) {
148         Workspace *ws;
149
150         Client *last_focused = SLIST_FIRST(&(c_ws->focus_stack));
151         if (last_focused == SLIST_END(&(c_ws->focus_stack)))
152                 last_focused = NULL;
153
154         yajl_gen gen = yajl_gen_alloc(NULL, NULL);
155         y(array_open);
156
157         TAILQ_FOREACH(ws, workspaces, workspaces) {
158                 if (ws->output == NULL)
159                         continue;
160
161                 y(map_open);
162                 ystr("num");
163                 y(integer, ws->num + 1);
164
165                 ystr("name");
166                 ystr(ws->utf8_name);
167
168                 ystr("visible");
169                 y(bool, ws->output->current_workspace == ws);
170
171                 ystr("focused");
172                 y(bool, c_ws == ws);
173
174                 ystr("rect");
175                 y(map_open);
176                 ystr("x");
177                 y(integer, ws->rect.x);
178                 ystr("y");
179                 y(integer, ws->rect.y);
180                 ystr("width");
181                 y(integer, ws->rect.width);
182                 ystr("height");
183                 y(integer, ws->rect.height);
184                 y(map_close);
185
186                 ystr("output");
187                 ystr(ws->output->name);
188
189                 ystr("urgent");
190                 y(bool, ws->urgent);
191
192                 y(map_close);
193         }
194
195         y(array_close);
196
197         const unsigned char *payload;
198         unsigned int length;
199         y(get_buf, &payload, &length);
200
201         ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_WORKSPACES, length);
202         y(free);
203 }
204
205 /*
206  * Formats the reply message for a GET_OUTPUTS request and sends it to the
207  * client
208  *
209  */
210 IPC_HANDLER(get_outputs) {
211         Output *output;
212
213         yajl_gen gen = yajl_gen_alloc(NULL, NULL);
214         y(array_open);
215
216         TAILQ_FOREACH(output, &outputs, outputs) {
217                 y(map_open);
218
219                 ystr("name");
220                 ystr(output->name);
221
222                 ystr("active");
223                 y(bool, output->active);
224
225                 ystr("rect");
226                 y(map_open);
227                 ystr("x");
228                 y(integer, output->rect.x);
229                 ystr("y");
230                 y(integer, output->rect.y);
231                 ystr("width");
232                 y(integer, output->rect.width);
233                 ystr("height");
234                 y(integer, output->rect.height);
235                 y(map_close);
236
237                 ystr("current_workspace");
238                 if (output->current_workspace == NULL)
239                         y(null);
240                 else y(integer, output->current_workspace->num + 1);
241
242                 y(map_close);
243         }
244
245         y(array_close);
246
247         const unsigned char *payload;
248         unsigned int length;
249         y(get_buf, &payload, &length);
250
251         ipc_send_message(fd, payload, I3_IPC_REPLY_TYPE_OUTPUTS, length);
252         y(free);
253 }
254
255 /*
256  * Callback for the YAJL parser (will be called when a string is parsed).
257  *
258  */
259 static int add_subscription(void *extra, const unsigned char *s,
260                             unsigned int len) {
261         ipc_client *client = extra;
262
263         DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
264         int event = client->num_events;
265
266         client->num_events++;
267         client->events = realloc(client->events, client->num_events * sizeof(char*));
268         /* We copy the string because it is not null-terminated and strndup()
269          * is missing on some BSD systems */
270         client->events[event] = scalloc(len+1);
271         memcpy(client->events[event], s, len);
272
273         DLOG("client is now subscribed to:\n");
274         for (int i = 0; i < client->num_events; i++)
275                 DLOG("event %s\n", client->events[i]);
276         DLOG("(done)\n");
277
278         return 1;
279 }
280
281 /*
282  * Subscribes this connection to the event types which were given as a JSON
283  * serialized array in the payload field of the message.
284  *
285  */
286 IPC_HANDLER(subscribe) {
287         yajl_handle p;
288         yajl_callbacks callbacks;
289         yajl_status stat;
290         ipc_client *current, *client = NULL;
291
292         /* Search the ipc_client structure for this connection */
293         TAILQ_FOREACH(current, &all_clients, clients) {
294                 if (current->fd != fd)
295                         continue;
296
297                 client = current;
298                 break;
299         }
300
301         if (client == NULL) {
302                 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
303                 return;
304         }
305
306         /* Setup the JSON parser */
307         memset(&callbacks, 0, sizeof(yajl_callbacks));
308         callbacks.yajl_string = add_subscription;
309
310         p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
311         stat = yajl_parse(p, (const unsigned char*)message, message_size);
312         if (stat != yajl_status_ok) {
313                 unsigned char *err;
314                 err = yajl_get_error(p, true, (const unsigned char*)message,
315                                      message_size);
316                 ELOG("YAJL parse error: %s\n", err);
317                 yajl_free_error(p, err);
318
319                 const char *reply = "{\"success\":false}";
320                 ipc_send_message(fd, (const unsigned char*)reply,
321                                  I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
322                 yajl_free(p);
323                 return;
324         }
325         yajl_free(p);
326         const char *reply = "{\"success\":true}";
327         ipc_send_message(fd, (const unsigned char*)reply,
328                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
329 }
330
331 /* The index of each callback function corresponds to the numeric
332  * value of the message type (see include/i3/ipc.h) */
333 handler_t handlers[4] = {
334         handle_command,
335         handle_get_workspaces,
336         handle_subscribe,
337         handle_get_outputs
338 };
339
340 /*
341  * Handler for activity on a client connection, receives a message from a
342  * client.
343  *
344  * For now, the maximum message size is 2048. I’m not sure for what the
345  * IPC interface will be used in the future, thus I’m not implementing a
346  * mechanism for arbitrarily long messages, as it seems like overkill
347  * at the moment.
348  *
349  */
350 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
351         char buf[2048];
352         int n = read(w->fd, buf, sizeof(buf));
353
354         /* On error or an empty message, we close the connection */
355         if (n <= 0) {
356 #if 0
357                 /* FIXME: I get these when closing a client socket,
358                  * therefore we just treat them as an error. Is this
359                  * correct? */
360                 if (errno == EAGAIN || errno == EWOULDBLOCK)
361                         return;
362 #endif
363
364                 /* If not, there was some kind of error. We don’t bother
365                  * and close the connection */
366                 close(w->fd);
367
368                 /* Delete the client from the list of clients */
369                 ipc_client *current;
370                 TAILQ_FOREACH(current, &all_clients, clients) {
371                         if (current->fd != w->fd)
372                                 continue;
373
374                         for (int i = 0; i < current->num_events; i++)
375                                 free(current->events[i]);
376                         /* We can call TAILQ_REMOVE because we break out of the
377                          * TAILQ_FOREACH afterwards */
378                         TAILQ_REMOVE(&all_clients, current, clients);
379                         break;
380                 }
381
382                 ev_io_stop(EV_A_ w);
383
384                 DLOG("IPC: client disconnected\n");
385                 return;
386         }
387
388         /* Terminate the message correctly */
389         buf[n] = '\0';
390
391         /* Check if the message starts with the i3 IPC magic code */
392         if (n < strlen(I3_IPC_MAGIC)) {
393                 DLOG("IPC: message too short, ignoring\n");
394                 return;
395         }
396
397         if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
398                 DLOG("IPC: message does not start with the IPC magic\n");
399                 return;
400         }
401
402         uint8_t *message = (uint8_t*)buf;
403         while (n > 0) {
404                 DLOG("IPC: n = %d\n", n);
405                 message += strlen(I3_IPC_MAGIC);
406                 n -= strlen(I3_IPC_MAGIC);
407
408                 /* The next 32 bit after the magic are the message size */
409                 uint32_t message_size = *((uint32_t*)message);
410                 message += sizeof(uint32_t);
411                 n -= sizeof(uint32_t);
412
413                 if (message_size > n) {
414                         DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
415                         return;
416                 }
417
418                 /* The last 32 bits of the header are the message type */
419                 uint32_t message_type = *((uint32_t*)message);
420                 message += sizeof(uint32_t);
421                 n -= sizeof(uint32_t);
422
423                 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
424                         DLOG("Unhandled message type: %d\n", message_type);
425                 else {
426                         handler_t h = handlers[message_type];
427                         h(w->fd, message, n, message_size, message_type);
428                 }
429                 n -= message_size;
430                 message += message_size;
431         }
432 }
433
434 /*
435  * Handler for activity on the listening socket, meaning that a new client
436  * has just connected and we should accept() him. Sets up the event handler
437  * for activity on the new connection and inserts the file descriptor into
438  * the list of clients.
439  *
440  */
441 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
442         struct sockaddr_un peer;
443         socklen_t len = sizeof(struct sockaddr_un);
444         int client;
445         if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
446                 if (errno == EINTR)
447                         return;
448                 else perror("accept()");
449                 return;
450         }
451
452         set_nonblock(client);
453
454         struct ev_io *package = scalloc(sizeof(struct ev_io));
455         ev_io_init(package, ipc_receive_message, client, EV_READ);
456         ev_io_start(EV_A_ package);
457
458         DLOG("IPC: new client connected\n");
459
460         ipc_client *new = scalloc(sizeof(ipc_client));
461         new->fd = client;
462
463         TAILQ_INSERT_TAIL(&all_clients, new, clients);
464 }
465
466 /*
467  * Creates the UNIX domain socket at the given path, sets it to non-blocking
468  * mode, bind()s and listen()s on it.
469  *
470  */
471 int ipc_create_socket(const char *filename) {
472         int sockfd;
473
474         /* Unlink the unix domain socket before */
475         unlink(filename);
476
477         if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
478                 perror("socket()");
479                 return -1;
480         }
481
482         (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
483
484         struct sockaddr_un addr;
485         memset(&addr, 0, sizeof(struct sockaddr_un));
486         addr.sun_family = AF_LOCAL;
487         strcpy(addr.sun_path, filename);
488         if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
489                 perror("bind()");
490                 return -1;
491         }
492
493         set_nonblock(sockfd);
494
495         if (listen(sockfd, 5) < 0) {
496                 perror("listen()");
497                 return -1;
498         }
499
500         return sockfd;
501 }