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