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