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