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