]> git.sur5r.net Git - i3/i3/blob - i3-config-wizard/ipc.c
Merge i3bar into next
[i3/i3] / i3-config-wizard / ipc.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  */
11 #include <stdint.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <unistd.h>
17 #include <err.h>
18
19 /*
20  * Formats a message (payload) of the given size and type and sends it to i3 via
21  * the given socket file descriptor.
22  *
23  */
24 void ipc_send_message(int sockfd, uint32_t message_size,
25                       uint32_t message_type, uint8_t *payload) {
26         int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) + sizeof(uint32_t) + message_size;
27         char msg[buffer_size];
28         char *walk = msg;
29
30         strcpy(walk, "i3-ipc");
31         walk += strlen("i3-ipc");
32         memcpy(walk, &message_size, sizeof(uint32_t));
33         walk += sizeof(uint32_t);
34         memcpy(walk, &message_type, sizeof(uint32_t));
35         walk += sizeof(uint32_t);
36         memcpy(walk, payload, message_size);
37
38         int sent_bytes = 0;
39         int bytes_to_go = buffer_size;
40         while (sent_bytes < bytes_to_go) {
41                 int n = write(sockfd, msg + sent_bytes, bytes_to_go);
42                 if (n == -1)
43                         err(EXIT_FAILURE, "write() failed");
44
45                 sent_bytes += n;
46                 bytes_to_go -= n;
47         }
48 }
49
50 /*
51  * Connects to the i3 IPC socket and returns the file descriptor for the
52  * socket. die()s if anything goes wrong.
53  *
54  */
55 int connect_ipc(char *socket_path) {
56         int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
57         if (sockfd == -1)
58                 err(EXIT_FAILURE, "Could not create socket");
59
60         struct sockaddr_un addr;
61         memset(&addr, 0, sizeof(struct sockaddr_un));
62         addr.sun_family = AF_LOCAL;
63         strcpy(addr.sun_path, socket_path);
64         if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
65                 err(EXIT_FAILURE, "Could not connect to i3");
66
67         return sockfd;
68 }