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