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