]> git.sur5r.net Git - i3/i3/blob - libi3/ipc_recv_message.c
Merge branch 'fix-key-release'
[i3/i3] / libi3 / ipc_recv_message.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <string.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <stdint.h>
12 #include <unistd.h>
13
14 #include <i3/ipc.h>
15
16 #include "libi3.h"
17
18 /*
19  * Reads a message from the given socket file descriptor and stores its length
20  * (reply_length) as well as a pointer to its contents (reply).
21  *
22  * Returns -1 when read() fails, errno will remain.
23  * Returns -2 when the IPC protocol is violated (invalid magic, unexpected
24  * message type, EOF instead of a message). Additionally, the error will be
25  * printed to stderr.
26  * Returns 0 on success.
27  *
28  */
29 int ipc_recv_message(int sockfd, uint32_t message_type,
30                      uint32_t *reply_length, uint8_t **reply) {
31     /* Read the message header first */
32     uint32_t to_read = strlen(I3_IPC_MAGIC) + sizeof(uint32_t) + sizeof(uint32_t);
33     char msg[to_read];
34     char *walk = msg;
35
36     uint32_t read_bytes = 0;
37     while (read_bytes < to_read) {
38         int n = read(sockfd, msg + read_bytes, to_read);
39         if (n == -1)
40             return -1;
41         if (n == 0) {
42             fprintf(stderr, "IPC: received EOF instead of reply\n");
43             return -2;
44         }
45
46         read_bytes += n;
47         to_read -= n;
48     }
49
50     if (memcmp(walk, I3_IPC_MAGIC, strlen(I3_IPC_MAGIC)) != 0) {
51         fprintf(stderr, "IPC: invalid magic in reply\n");
52         return -2;
53     }
54
55     walk += strlen(I3_IPC_MAGIC);
56     *reply_length = *((uint32_t*)walk);
57     walk += sizeof(uint32_t);
58     if (*((uint32_t*)walk) != message_type) {
59         fprintf(stderr, "IPC: unexpected reply type (got %d, expected %d)\n", *((uint32_t*)walk), message_type);
60         return -2;
61     }
62
63     *reply = smalloc(*reply_length);
64
65     to_read = *reply_length;
66     read_bytes = 0;
67     while (read_bytes < to_read) {
68         int n = read(sockfd, *reply + read_bytes, to_read);
69         if (n == -1)
70             return -1;
71
72         read_bytes += n;
73         to_read -= n;
74     }
75
76     return 0;
77 }