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