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