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