]> git.sur5r.net Git - i3/i3/blob - src/ipc.c
Make code compatible with yajl 2.0 *and* 1.0
[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         strncpy(walk, "i3-ipc", buffer_size - 1);
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 static int add_subscription(void *extra, const unsigned char *s,
308                             unsigned int len) {
309         ipc_client *client = extra;
310
311         DLOG("should add subscription to extra %p, sub %.*s\n", client, len, s);
312         int event = client->num_events;
313
314         client->num_events++;
315         client->events = realloc(client->events, client->num_events * sizeof(char*));
316         /* We copy the string because it is not null-terminated and strndup()
317          * is missing on some BSD systems */
318         client->events[event] = scalloc(len+1);
319         memcpy(client->events[event], s, len);
320
321         DLOG("client is now subscribed to:\n");
322         for (int i = 0; i < client->num_events; i++)
323                 DLOG("event %s\n", client->events[i]);
324         DLOG("(done)\n");
325
326         return 1;
327 }
328
329 /*
330  * Subscribes this connection to the event types which were given as a JSON
331  * serialized array in the payload field of the message.
332  *
333  */
334 IPC_HANDLER(subscribe) {
335         yajl_handle p;
336         yajl_callbacks callbacks;
337         yajl_status stat;
338         ipc_client *current, *client = NULL;
339
340         /* Search the ipc_client structure for this connection */
341         TAILQ_FOREACH(current, &all_clients, clients) {
342                 if (current->fd != fd)
343                         continue;
344
345                 client = current;
346                 break;
347         }
348
349         if (client == NULL) {
350                 ELOG("Could not find ipc_client data structure for fd %d\n", fd);
351                 return;
352         }
353
354         /* Setup the JSON parser */
355         memset(&callbacks, 0, sizeof(yajl_callbacks));
356         callbacks.yajl_string = add_subscription;
357
358 #if YAJL_MAJOR >= 2
359         p = yajl_alloc(&callbacks, NULL, (void*)client);
360 #else
361         p = yajl_alloc(&callbacks, NULL, NULL, (void*)client);
362 #endif
363         stat = yajl_parse(p, (const unsigned char*)message, message_size);
364         if (stat != yajl_status_ok) {
365                 unsigned char *err;
366                 err = yajl_get_error(p, true, (const unsigned char*)message,
367                                      message_size);
368                 ELOG("YAJL parse error: %s\n", err);
369                 yajl_free_error(p, err);
370
371                 const char *reply = "{\"success\":false}";
372                 ipc_send_message(fd, (const unsigned char*)reply,
373                                  I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
374                 yajl_free(p);
375                 return;
376         }
377         yajl_free(p);
378         const char *reply = "{\"success\":true}";
379         ipc_send_message(fd, (const unsigned char*)reply,
380                          I3_IPC_REPLY_TYPE_SUBSCRIBE, strlen(reply));
381 }
382
383 /* The index of each callback function corresponds to the numeric
384  * value of the message type (see include/i3/ipc.h) */
385 handler_t handlers[4] = {
386         handle_command,
387         handle_get_workspaces,
388         handle_subscribe,
389         handle_get_outputs
390 };
391
392 /*
393  * Handler for activity on a client connection, receives a message from a
394  * client.
395  *
396  * For now, the maximum message size is 2048. I’m not sure for what the
397  * IPC interface will be used in the future, thus I’m not implementing a
398  * mechanism for arbitrarily long messages, as it seems like overkill
399  * at the moment.
400  *
401  */
402 static void ipc_receive_message(EV_P_ struct ev_io *w, int revents) {
403         char buf[2048];
404         int n = read(w->fd, buf, sizeof(buf));
405
406         /* On error or an empty message, we close the connection */
407         if (n <= 0) {
408 #if 0
409                 /* FIXME: I get these when closing a client socket,
410                  * therefore we just treat them as an error. Is this
411                  * correct? */
412                 if (errno == EAGAIN || errno == EWOULDBLOCK)
413                         return;
414 #endif
415
416                 /* If not, there was some kind of error. We don’t bother
417                  * and close the connection */
418                 close(w->fd);
419
420                 /* Delete the client from the list of clients */
421                 ipc_client *current;
422                 TAILQ_FOREACH(current, &all_clients, clients) {
423                         if (current->fd != w->fd)
424                                 continue;
425
426                         for (int i = 0; i < current->num_events; i++)
427                                 free(current->events[i]);
428                         /* We can call TAILQ_REMOVE because we break out of the
429                          * TAILQ_FOREACH afterwards */
430                         TAILQ_REMOVE(&all_clients, current, clients);
431                         break;
432                 }
433
434                 ev_io_stop(EV_A_ w);
435
436                 DLOG("IPC: client disconnected\n");
437                 return;
438         }
439
440         /* Terminate the message correctly */
441         buf[n] = '\0';
442
443         /* Check if the message starts with the i3 IPC magic code */
444         if (n < strlen(I3_IPC_MAGIC)) {
445                 DLOG("IPC: message too short, ignoring\n");
446                 return;
447         }
448
449         if (strncmp(buf, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
450                 DLOG("IPC: message does not start with the IPC magic\n");
451                 return;
452         }
453
454         uint8_t *message = (uint8_t*)buf;
455         while (n > 0) {
456                 DLOG("IPC: n = %d\n", n);
457                 message += strlen(I3_IPC_MAGIC);
458                 n -= strlen(I3_IPC_MAGIC);
459
460                 /* The next 32 bit after the magic are the message size */
461                 uint32_t message_size = *((uint32_t*)message);
462                 message += sizeof(uint32_t);
463                 n -= sizeof(uint32_t);
464
465                 if (message_size > n) {
466                         DLOG("IPC: Either the message size was wrong or the message was not read completely, dropping\n");
467                         return;
468                 }
469
470                 /* The last 32 bits of the header are the message type */
471                 uint32_t message_type = *((uint32_t*)message);
472                 message += sizeof(uint32_t);
473                 n -= sizeof(uint32_t);
474
475                 if (message_type >= (sizeof(handlers) / sizeof(handler_t)))
476                         DLOG("Unhandled message type: %d\n", message_type);
477                 else {
478                         handler_t h = handlers[message_type];
479                         h(w->fd, message, n, message_size, message_type);
480                 }
481                 n -= message_size;
482                 message += message_size;
483         }
484 }
485
486 /*
487  * Handler for activity on the listening socket, meaning that a new client
488  * has just connected and we should accept() him. Sets up the event handler
489  * for activity on the new connection and inserts the file descriptor into
490  * the list of clients.
491  *
492  */
493 void ipc_new_client(EV_P_ struct ev_io *w, int revents) {
494         struct sockaddr_un peer;
495         socklen_t len = sizeof(struct sockaddr_un);
496         int client;
497         if ((client = accept(w->fd, (struct sockaddr*)&peer, &len)) < 0) {
498                 if (errno == EINTR)
499                         return;
500                 else perror("accept()");
501                 return;
502         }
503
504         set_nonblock(client);
505
506         struct ev_io *package = scalloc(sizeof(struct ev_io));
507         ev_io_init(package, ipc_receive_message, client, EV_READ);
508         ev_io_start(EV_A_ package);
509
510         DLOG("IPC: new client connected\n");
511
512         ipc_client *new = scalloc(sizeof(ipc_client));
513         new->fd = client;
514
515         TAILQ_INSERT_TAIL(&all_clients, new, clients);
516 }
517
518 /*
519  * Creates the UNIX domain socket at the given path, sets it to non-blocking
520  * mode, bind()s and listen()s on it.
521  *
522  */
523 int ipc_create_socket(const char *filename) {
524         int sockfd;
525
526         char *resolved = resolve_tilde(filename);
527         DLOG("Creating IPC-socket at %s\n", resolved);
528         char *copy = sstrdup(resolved);
529         const char *dir = dirname(copy);
530         if (!path_exists(dir))
531                 mkdirp(dir);
532         free(copy);
533
534         /* Unlink the unix domain socket before */
535         unlink(resolved);
536
537         if ((sockfd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) {
538                 perror("socket()");
539                 free(resolved);
540                 return -1;
541         }
542
543         (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
544
545         struct sockaddr_un addr;
546         memset(&addr, 0, sizeof(struct sockaddr_un));
547         addr.sun_family = AF_LOCAL;
548         strncpy(addr.sun_path, resolved, sizeof(addr.sun_path) - 1);
549         if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) {
550                 perror("bind()");
551                 free(resolved);
552                 return -1;
553         }
554
555         free(resolved);
556         set_nonblock(sockfd);
557
558         if (listen(sockfd, 5) < 0) {
559                 perror("listen()");
560                 return -1;
561         }
562
563         return sockfd;
564 }