]> git.sur5r.net Git - i3/i3/blob - testcases/inject_randr1.5.c
5796ef05519edf5b6ed34b751e6fbdbb4eccfdaf
[i3/i3] / testcases / inject_randr1.5.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  * inject_randr1.5.c: An X11 proxy which interprets RandR 1.5 GetMonitors
8  * requests and overwrites their reply with a custom reply.
9  *
10  * This tool can be refactored as necessary in order to perform the same
11  * purpose for other request types. The RandR 1.5 specific portions of the code
12  * have been marked as such to make such a refactoring easier.
13  *
14  */
15 #include "all.h"
16
17 #include <ev.h>
18 #include <fcntl.h>
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22 #include <sys/time.h>
23 #include <sys/resource.h>
24 #include <sys/mman.h>
25 #include <sys/stat.h>
26 #include <libgen.h>
27
28 static void uds_connection_cb(EV_P_ ev_io *w, int revents);
29 static void read_client_setup_request_cb(EV_P_ ev_io *w, int revents);
30 static void read_server_setup_reply_cb(EV_P_ ev_io *w, int revents);
31 static void read_client_x11_packet_cb(EV_P_ ev_io *w, int revents);
32 static void read_server_x11_packet_cb(EV_P_ ev_io *w, int revents);
33
34 static char *sun_path = NULL;
35
36 void cleanup_socket(void) {
37     if (sun_path != NULL) {
38         unlink(sun_path);
39         free(sun_path);
40         sun_path = NULL;
41     }
42 }
43
44 /* BEGIN RandR 1.5 specific */
45 static void *injected_reply = NULL;
46 static off_t injected_reply_len = 0;
47 /* END RandR 1.5 specific */
48
49 #define XCB_PAD(i) (-(i)&3)
50
51 struct connstate {
52     /* clientw is a libev watcher for the connection which we accept()ed. */
53     ev_io *clientw;
54
55     /* serverw is a libev watcher for the connection to X11 which we initiated
56          * on behalf of the client. */
57     ev_io *serverw;
58
59     /* sequence is the client-side sequence number counter. In X11’s wire
60      * encoding, sequence counters are not included in requests, only in
61      * replies. */
62     int sequence;
63
64     /* BEGIN RandR 1.5 specific */
65     /* sequence number of the most recent GetExtension request for RANDR */
66     int getext_randr;
67     /* sequence number of the most recent RRGetMonitors request */
68     int getmonitors;
69
70     int randr_major_opcode;
71     /* END RandR 1.5 specific */
72 };
73
74 /*
75  * Returns 0 on EOF
76  * Returns -1 on error (with errno from read() untouched)
77  *
78  */
79 static size_t readall_into(void *buffer, const size_t len, int fd) {
80     size_t read_bytes = 0;
81     while (read_bytes < len) {
82         ssize_t n = read(fd, buffer + read_bytes, len - read_bytes);
83         if (n <= 0) {
84             return n;
85         }
86         read_bytes += (size_t)n;
87     }
88     return read_bytes;
89 }
90
91 /*
92  * Exits the program with an error if the read failed.
93  *
94  */
95 static void must_read(int n) {
96     if (n == -1) {
97         err(EXIT_FAILURE, "read()");
98     }
99     if (n == 0) {
100         errx(EXIT_FAILURE, "EOF");
101     }
102 }
103
104 /*
105  * Exits the program with an error if the write failed.
106  *
107  */
108 static void must_write(int n) {
109     if (n == -1) {
110         err(EXIT_FAILURE, "write()");
111     }
112 }
113
114 static void uds_connection_cb(EV_P_ ev_io *w, int revents) {
115     struct sockaddr_un addr;
116     socklen_t addrlen = sizeof(addr);
117     const int clientfd = accept(w->fd, (struct sockaddr *)&addr, &addrlen);
118     if (clientfd == -1) {
119         if (errno == EINTR) {
120             return;
121         }
122         err(EXIT_FAILURE, "accept()");
123     }
124
125     struct connstate *connstate = scalloc(1, sizeof(struct connstate));
126
127     ev_io *clientw = scalloc(1, sizeof(ev_io));
128     connstate->clientw = clientw;
129     clientw->data = connstate;
130     ev_io_init(clientw, read_client_setup_request_cb, clientfd, EV_READ);
131     ev_io_start(EV_A_ clientw);
132 }
133
134 // https://www.x.org/releases/current/doc/xproto/x11protocol.html#Encoding::Connection_Setup
135 static void read_client_setup_request_cb(EV_P_ ev_io *w, int revents) {
136     ev_io_stop(EV_A_ w);
137     struct connstate *connstate = (struct connstate *)w->data;
138
139     /* Read X11 setup request in its entirety. */
140     xcb_setup_request_t setup_request;
141     must_read(readall_into(&setup_request, sizeof(setup_request), w->fd));
142
143     /* Establish a connection to X11. */
144     int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
145     if (fd == -1) {
146         err(EXIT_FAILURE, "socket()");
147     }
148
149     char *host;
150     int displayp;
151     if (xcb_parse_display(getenv("DISPLAY"), &host, &displayp, NULL) == 0) {
152         errx(EXIT_FAILURE, "Could not parse DISPLAY=%s", getenv("DISPLAY"));
153     }
154     free(host);
155
156     struct sockaddr_un addr;
157     memset(&addr, 0, sizeof(addr));
158     addr.sun_family = AF_LOCAL;
159     snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/.X11-unix/X%d", displayp);
160     if (connect(fd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
161         err(EXIT_FAILURE, "connect(%s)", addr.sun_path);
162     }
163
164     /* Relay setup request. */
165     must_write(writeall(fd, &setup_request, sizeof(setup_request)));
166
167     if (setup_request.authorization_protocol_name_len > 0 ||
168         setup_request.authorization_protocol_data_len > 0) {
169         const size_t authlen = setup_request.authorization_protocol_name_len +
170                                XCB_PAD(setup_request.authorization_protocol_name_len) +
171                                setup_request.authorization_protocol_data_len +
172                                XCB_PAD(setup_request.authorization_protocol_data_len);
173         void *buf = smalloc(authlen);
174         must_read(readall_into(buf, authlen, w->fd));
175         must_write(writeall(fd, buf, authlen));
176         free(buf);
177     }
178
179     /* Wait for a response from the X11 server. */
180     ev_io *serverw = scalloc(1, sizeof(ev_io));
181     connstate->serverw = serverw;
182     serverw->data = connstate;
183     ev_io_init(serverw, read_server_setup_reply_cb, fd, EV_READ);
184     ev_io_start(EV_A_ serverw);
185 }
186
187 static void read_server_setup_reply_cb(EV_P_ ev_io *w, int revents) {
188     struct connstate *connstate = (struct connstate *)w->data;
189     xcb_setup_failed_t setup_failed;
190     must_read(readall_into(&setup_failed, sizeof(setup_failed), w->fd));
191
192     switch (setup_failed.status) {
193         case 0:
194             errx(EXIT_FAILURE, "error authenticating at the X11 server");
195
196         case 2:
197             errx(EXIT_FAILURE, "two-factor auth not implemented");
198
199         case 1:
200             must_write(writeall(connstate->clientw->fd, &setup_failed, sizeof(xcb_setup_failed_t)));
201             const size_t len = (setup_failed.length * 4);
202             void *buf = smalloc(len);
203             must_read(readall_into(buf, len, w->fd));
204             must_write(writeall(connstate->clientw->fd, buf, len));
205             free(buf);
206
207             ev_set_cb(connstate->clientw, read_client_x11_packet_cb);
208             ev_set_cb(connstate->serverw, read_server_x11_packet_cb);
209             ev_io_start(EV_A_ connstate->clientw);
210             break;
211
212         default:
213             errx(EXIT_FAILURE, "X11 protocol error: expected setup_failed.status in [0..2], got %d", setup_failed.status);
214     }
215 }
216
217 // https://www.x.org/releases/current/doc/xproto/x11protocol.html#request_format
218 typedef struct {
219     uint8_t opcode;
220     uint8_t pad0;
221     uint16_t length;
222 } generic_x11_request_t;
223
224 // https://www.x.org/releases/current/doc/xproto/x11protocol.html#reply_format
225 typedef struct {
226     uint8_t code; /* if 1, this is a reply. if 0, this is an error. else, an event */
227     uint8_t pad0;
228     uint16_t sequence;
229     uint32_t length;
230 } generic_x11_reply_t;
231
232 static void read_client_x11_packet_cb(EV_P_ ev_io *w, int revents) {
233     struct connstate *connstate = (struct connstate *)w->data;
234
235     void *request = smalloc(sizeof(generic_x11_request_t));
236     must_read(readall_into(request, sizeof(generic_x11_request_t), connstate->clientw->fd));
237     const size_t len = (((generic_x11_request_t *)request)->length * 4);
238     if (len > sizeof(generic_x11_request_t)) {
239         request = srealloc(request, len);
240         must_read(readall_into(request + sizeof(generic_x11_request_t),
241                                len - sizeof(generic_x11_request_t),
242                                connstate->clientw->fd));
243     }
244
245     // XXX: sequence counter wrapping is not implemented, but should not be
246     // necessary given that this tool is scoped for test cases.
247     connstate->sequence++;
248
249     /* BEGIN RandR 1.5 specific */
250     const uint8_t opcode = ((generic_x11_request_t *)request)->opcode;
251     if (opcode == XCB_QUERY_EXTENSION) {
252         xcb_query_extension_request_t *req = request;
253         const char *name = request + sizeof(xcb_query_extension_request_t);
254         if (req->name_len == strlen("RANDR") &&
255             strncmp(name, "RANDR", strlen("RANDR")) == 0) {
256             connstate->getext_randr = connstate->sequence;
257         }
258     } else if (opcode == connstate->randr_major_opcode) {
259         const uint8_t randr_opcode = ((generic_x11_request_t *)request)->pad0;
260         if (randr_opcode == XCB_RANDR_GET_MONITORS) {
261             connstate->getmonitors = connstate->sequence;
262         }
263     }
264     /* END RandR 1.5 specific */
265
266     must_write(writeall(connstate->serverw->fd, request, len));
267     free(request);
268 }
269
270 static void read_server_x11_packet_cb(EV_P_ ev_io *w, int revents) {
271     struct connstate *connstate = (struct connstate *)w->data;
272     // all packets from the server are at least 32 bytes in length
273     size_t len = 32;
274     void *packet = smalloc(len);
275     must_read(readall_into(packet, len, connstate->serverw->fd));
276     switch (((generic_x11_reply_t *)packet)->code) {
277         case 0:  // error
278             break;
279
280         case 1:  // reply
281             len += ((generic_x11_reply_t *)packet)->length * 4;
282             if (len > 32) {
283                 packet = srealloc(packet, len);
284                 must_read(readall_into(packet + 32, len - 32, connstate->serverw->fd));
285             }
286
287             /* BEGIN RandR 1.5 specific */
288             const uint16_t sequence = ((generic_x11_reply_t *)packet)->sequence;
289
290             if (sequence == connstate->getext_randr) {
291                 xcb_query_extension_reply_t *reply = packet;
292                 connstate->randr_major_opcode = reply->major_opcode;
293             }
294
295             if (sequence == connstate->getmonitors) {
296                 printf("RRGetMonitors reply!\n");
297                 if (injected_reply != NULL) {
298                     printf("injecting reply\n");
299                     ((generic_x11_reply_t *)injected_reply)->sequence = sequence;
300                     must_write(writeall(connstate->clientw->fd, injected_reply, injected_reply_len));
301                     free(packet);
302                     return;
303                 }
304             }
305             /* END RandR 1.5 specific */
306
307             break;
308
309         default:  // event
310             break;
311     }
312     must_write(writeall(connstate->clientw->fd, packet, len));
313     free(packet);
314 }
315
316 static void child_cb(EV_P_ ev_child *w, int revents) {
317     ev_child_stop(EV_A_ w);
318     if (WIFEXITED(w->rstatus)) {
319         exit(WEXITSTATUS(w->rstatus));
320     } else {
321         exit(WTERMSIG(w->rstatus) + 128);
322     }
323 }
324
325 static void must_read_reply(const char *filename) {
326     FILE *f;
327     if ((f = fopen(filename, "r")) == NULL) {
328         err(EXIT_FAILURE, "fopen(%s)", filename);
329     }
330     struct stat stbuf;
331     if (fstat(fileno(f), &stbuf) != 0) {
332         err(EXIT_FAILURE, "fstat(%s)", filename);
333     }
334     /* BEGIN RandR 1.5 specific */
335     injected_reply_len = stbuf.st_size;
336     injected_reply = smalloc(stbuf.st_size);
337     int n = fread(injected_reply, 1, stbuf.st_size, f);
338     /* END RandR 1.5 specific */
339     if (n != stbuf.st_size) {
340         err(EXIT_FAILURE, "fread(%s)", filename);
341     }
342     fclose(f);
343 }
344
345 int main(int argc, char *argv[]) {
346     static struct option long_options[] = {
347         {"getmonitors_reply", required_argument, 0, 0},
348         {0, 0, 0, 0},
349     };
350     char *options_string = "";
351     int opt;
352     int option_index = 0;
353
354     while ((opt = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
355         switch (opt) {
356             case 0:
357                 if (strcmp(long_options[option_index].name, "getmonitors_reply") == 0) {
358                     must_read_reply(optarg);
359                 }
360                 break;
361             default:
362                 exit(EXIT_FAILURE);
363         }
364     }
365
366     if (optind >= argc) {
367         errx(EXIT_FAILURE, "syntax: %s [options] <command>\n", argv[0]);
368     }
369
370     int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
371     if (fd == -1) {
372         err(EXIT_FAILURE, "socket(AF_UNIX)");
373     }
374
375     if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
376         warn("Could not set FD_CLOEXEC");
377     }
378
379     struct sockaddr_un addr;
380     memset(&addr, 0, sizeof(struct sockaddr_un));
381     addr.sun_family = AF_UNIX;
382     int i;
383     bool bound = false;
384     for (i = 0; i < 100; i++) {
385         /* XXX: The path to X11 sockets differs on some platforms (e.g. Trusted
386          * Solaris, HPUX), but since libxcb doesn’t provide a function to
387          * generate the path, we’ll just have to hard-code it for now. */
388         snprintf(addr.sun_path, sizeof(addr.sun_path), "/tmp/.X11-unix/X%d", i);
389
390         if (bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
391             warn("bind(%s)", addr.sun_path);
392         } else {
393             bound = true;
394             /* Let the user know bind() was successful, so that they know the
395              * error messages can be disregarded. */
396             fprintf(stderr, "Successfuly bound to %s\n", addr.sun_path);
397             sun_path = sstrdup(addr.sun_path);
398             break;
399         }
400     }
401
402     if (!bound) {
403         err(EXIT_FAILURE, "bind()");
404     }
405
406     atexit(cleanup_socket);
407
408     /* This program will be started for each testcase which requires it, so we
409      * expect precisely one connection. */
410     if (listen(fd, 1) == -1) {
411         err(EXIT_FAILURE, "listen()");
412     }
413
414     pid_t child = fork();
415     if (child == -1) {
416         err(EXIT_FAILURE, "fork()");
417     }
418     if (child == 0) {
419         char *display;
420         sasprintf(&display, ":%d", i);
421         setenv("DISPLAY", display, 1);
422         free(display);
423
424         char **child_args = argv + optind;
425         execvp(child_args[0], child_args);
426         err(EXIT_FAILURE, "exec()");
427     }
428
429     struct ev_loop *loop = ev_default_loop(0);
430
431     ev_child cw;
432     ev_child_init(&cw, child_cb, child, 0);
433     ev_child_start(loop, &cw);
434
435     ev_io watcher;
436     ev_io_init(&watcher, uds_connection_cb, fd, EV_READ);
437     ev_io_start(loop, &watcher);
438
439     ev_run(loop, 0);
440 }