-
Notifications
You must be signed in to change notification settings - Fork 9
/
common.c
1870 lines (1668 loc) · 49.1 KB
/
common.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <poll.h>
#include <inttypes.h>
#include <sys/time.h>
#include <time.h>
#include <gnu/lib-names.h>
#include <X11/Xproto.h>
#include <X11/Xatom.h>
#include <X11/X.h>
#include <X11/extensions/xf86vmproto.h>
#include <X11/extensions/randr.h>
#include <X11/extensions/randrproto.h>
#include <X11/extensions/panoramiXproto.h>
// ****************************************************************************
struct Config
{
int mainX;
int mainY;
unsigned int mainW;
unsigned int mainH;
unsigned int desktopW;
unsigned int desktopH;
int actualX;
int actualY;
int mst2X;
int mst2Y;
unsigned int mst2W;
unsigned int mst2H;
int mst3X;
int mst3Y;
unsigned int mst3W;
unsigned int mst3H;
int mst4X;
int mst4Y;
unsigned int mst4W;
unsigned int mst4H;
char enable;
char debug;
char logTimestamp;
char joinMST;
char maskOtherMonitors;
char resizeWindows;
char resizeAll;
char moveWindows;
char fork;
char filterFocus;
char noMouseGrab;
char noKeyboardGrab;
char noPrimarySelection;
char noMinSize;
char noMaxSize;
char dumb; // undocumented - act as a dumb pipe, nothing more
char confineMouse;
char noResolutionChange;
char noWindowStackMove;
char noWMRaise;
unsigned int fakeScreenW;
unsigned int fakeScreenH;
unsigned int fakeScreenDimW;
unsigned int fakeScreenDimH;
struct MapConfig *maps;
};
static struct Config config = {};
static void log_error(const char *fmt, ...)
__attribute__ ((format (printf, 1, 2)));
static const char* get_curtime_string()
{
// This will invalidate previous return pointer on the next call.
// Doesn't really matter for us, since we're using it immediately.
static char buffer[40];
// https://stackoverflow.com/a/32983646
struct timeval tv;
gettimeofday(&tv, NULL);
int millisec = tv.tv_usec/1000;
struct tm* tm_info = localtime(&tv.tv_sec);
// https://stackoverflow.com/a/2023961
size_t len = strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
sprintf(buffer+len, ".%03d", millisec);
return buffer;
}
static void log_error(const char *fmt, ...)
{
const char* timestamp;
if (config.logTimestamp)
timestamp = get_curtime_string();
va_list args;
va_start(args, fmt);
if (config.logTimestamp)
fprintf(stderr, "hax11 %s: ", timestamp);
else
fprintf(stderr, "hax11: ");
vfprintf(stderr, fmt, args);
va_end(args);
FILE* f = fopen("/tmp/hax11.log", "ab");
if (f)
{
if (config.logTimestamp)
fprintf(f, "%s [%d] ", timestamp, getpid());
else
fprintf(f, "[%d] ", getpid());
va_start(args, fmt);
vfprintf(f, fmt, args);
va_end(args);
fclose(f);
}
}
#define log_debug(...) do { if (config.debug >= 1) log_error(__VA_ARGS__); } while(0)
#define log_debug2(...) do { if (config.debug >= 2) log_error(__VA_ARGS__); } while(0)
// Mirrors CARD32/CARD64 defines in /usr/include/X11/Xmd.h:
#ifdef LONG64
#define PRIuCARD32 "u"
#define PRIuCARD64 "lu"
#define PRIxCARD32 "x"
#define PRIxCARD64 "lx"
#else
#define PRIuCARD32 "lu"
#define PRIuCARD64 "llu"
#define PRIxCARD32 "lx"
#define PRIxCARD64 "llx"
#endif
// ****************************************************************************
enum
{
MAP_KIND_KEY,
MAP_KIND_BUTTON,
};
//typedef CARD8 KEYCODE;
struct MapInput
{
unsigned char kind;
unsigned int code;
};
struct MapConfig
{
struct MapInput from, to;
struct MapConfig *next;
};
static char configLoaded = 0;
enum { maxMST = 4 };
static int* mstConfigX[maxMST] = { &config.mainX, &config.mst2X, &config.mst3X, &config.mst4X };
static int* mstConfigY[maxMST] = { &config.mainY, &config.mst2Y, &config.mst3Y, &config.mst4Y };
static unsigned int* mstConfigW[maxMST] = { &config.mainW, &config.mst2W, &config.mst3W, &config.mst4W };
static unsigned int* mstConfigH[maxMST] = { &config.mainH, &config.mst2H, &config.mst3H, &config.mst4H };
int parseInt(const char *s)
{
char *endptr = 0;
long int result = strtol(s, &endptr, 0);
if (!endptr)
log_error("Bad number: %s\n", s);
return result;
}
bool parseInput(struct MapInput *input, const char *s)
{
if (tolower(*s) == 'k')
input->kind = MAP_KIND_KEY;
else
if (tolower(*s) == 'b')
input->kind = MAP_KIND_BUTTON;
else
{
log_error("Bad map kind: %s\n", s);
return false;
}
input->code = parseInt(s + 1);
return true;
}
static void readConfig(const char* fn)
{
//log_debug("Reading config from %s\n", fn);
FILE* f = fopen(fn, "r");
if (!f)
{
// Create empty file if it does not exist
f = fopen(fn, "w");
if (f) fclose(f);
return;
}
while (!feof(f))
{
char buf[1024];
if (!fgets(buf, sizeof(buf), f))
break;
if (buf[0] == '#')
continue;
//log_debug("Got line: %s'\n", buf);
char *p = strchr(buf, '=');
if (!p)
continue;
*p = 0;
p++;
//log_debug("Got line: '%s' = '%s'\n", buf, p);
if (strncasecmp("Map", buf, 3) == 0)
{
struct MapConfig *map = malloc(sizeof(struct MapConfig));
map->next = config.maps;
if (parseInput(&map->from, buf + 3) &&
parseInput(&map->to, p))
config.maps = map;
continue;
}
#define PARSE_INT(x) \
if (!strcasecmp(buf, #x)) \
config.x = parseInt(p); \
else
PARSE_INT(mainX)
PARSE_INT(mainY)
PARSE_INT(mainW)
PARSE_INT(mainH)
PARSE_INT(desktopW)
PARSE_INT(desktopH)
PARSE_INT(actualX)
PARSE_INT(actualY)
PARSE_INT(mst2X)
PARSE_INT(mst2Y)
PARSE_INT(mst2W)
PARSE_INT(mst2H)
PARSE_INT(mst3X)
PARSE_INT(mst3Y)
PARSE_INT(mst3W)
PARSE_INT(mst3H)
PARSE_INT(mst4X)
PARSE_INT(mst4Y)
PARSE_INT(mst4W)
PARSE_INT(mst4H)
PARSE_INT(enable)
PARSE_INT(debug)
PARSE_INT(logTimestamp)
PARSE_INT(joinMST)
PARSE_INT(maskOtherMonitors)
PARSE_INT(resizeWindows)
PARSE_INT(resizeAll)
PARSE_INT(moveWindows)
PARSE_INT(fork)
PARSE_INT(filterFocus)
PARSE_INT(noMouseGrab)
PARSE_INT(noKeyboardGrab)
PARSE_INT(noPrimarySelection)
PARSE_INT(noMinSize)
PARSE_INT(noMaxSize)
PARSE_INT(dumb)
PARSE_INT(confineMouse)
PARSE_INT(noResolutionChange)
PARSE_INT(noWindowStackMove)
PARSE_INT(noWMRaise)
PARSE_INT(fakeScreenW)
PARSE_INT(fakeScreenH)
PARSE_INT(fakeScreenDimW)
PARSE_INT(fakeScreenDimH)
/* else */
log_error("Unknown option: %s\n", buf);
#undef PARSE_INT
}
fclose(f);
//log_debug("Read config: %d %d %d %d\n", config.joinMST, config.maskOtherMonitors, config.resizeWindows, config.moveWindows);
}
// ****************************************************************************
static void getProfileName(char *buf, size_t size);
static void needConfig()
{
if (configLoaded)
return;
configLoaded = 1;
// Default settings
config.mainX = 0;
config.mainY = 0;
config.mainW = 3840;
config.mainH = 2160;
config.desktopW = 3840;
config.desktopH = 2160;
char buf[1024] = {0};
char *home = getenv("HOME");
if (!home)
return;
strncpy(buf, home, sizeof(buf)-100);
strcat(buf, "/.config" ); mkdir(buf, 0700); // TODO: XDG_CONFIG_HOME
strcat(buf, "/hax11"); mkdir(buf, 0700);
strcat(buf, "/profiles" ); mkdir(buf, 0700);
char *p = buf + strlen(buf);
strcpy(p, "/default");
readConfig(buf);
getProfileName(p + 1, sizeof(buf) - (p-buf));
readConfig(buf);
}
// ****************************************************************************
static void fixSize(
CARD16* width,
CARD16* height)
{
if (config.resizeAll && *width >= 640 && *height >= 480)
{
*width = config.mainW;
*height = config.mainH;
}
// Fix windows spanning multiple monitors
if (config.resizeWindows && *width == config.desktopW)
*width = config.mainW;
// Fix spanning one half of a MST monitor
if (config.joinMST && *width == config.mainW/2 && *height == config.mainH)
*width = config.mainW;
}
static void fixCoords(INT16* x, INT16* y, CARD16 *width, CARD16 *height)
{
fixSize(width, height);
if (!config.moveWindows)
return;
if (*width == config.mainW && *height == config.mainH)
{
*x = config.mainX;
*y = config.mainY;
}
}
static bool fixMonitor(INT16* x, INT16* y, CARD16 *width, CARD16 *height)
{
if (config.joinMST)
{
for (int n=0; n<maxMST; n++)
if (*mstConfigW[n])
{
if (*width == *mstConfigW[n] / 2
&& *height == *mstConfigH[n]
&& *y == *mstConfigY[n]) // Is MST panel?
{
if (*x == *mstConfigX[n]) // Left panel
{
*width = *mstConfigW[n]; // resize
//*height = 2160;
}
else
if (*x == (INT16)(*mstConfigX[n] + *mstConfigW[n] / 2)) // Right panel
*x = *y = *width = *height = 0; // disable
}
}
}
if (config.maskOtherMonitors)
if (*width != config.mainW || *height != config.mainH)
{
// return false;
*x = config.mainX;
*y = config.mainY;
*width = config.mainW;
*height = config.mainH;
}
return true;
}
static void hexDump(const void* buf, size_t len, char prefix1, char prefix2)
{
if (config.debug < 3)
return;
while (len)
{
size_t n = len > 16 ? 16 : len;
char textbuf[16*3+1];
char *textptr = textbuf;
for (size_t i = 0; i < n; i++)
textptr += sprintf(textptr, " %02X", ((const unsigned char*)buf)[i]);
log_error("%c%c%s\n", prefix1, prefix2, textbuf);
/*
Hex dump arrow legend:
- Char 1:
< - request (client (application) to server (Xorg))
> - reply (server (Xorg) to client (application))
{ - request (synthesized by hax11)
} - reply (synthesized by hax11)
- Char 2:
- - data, incoming into hax11
= - data, outgoing from hax11
* - metadata, incoming into hax11
% - metadata, outgoing from hax11
*/
buf += n;
len -= n;
}
}
#include <sys/socket.h>
#define ANCIL_SIZE 256
struct Connection
{
int recvfd, sendfd;
char dir; // for logging
// Ancillary data buffer.
// Necessary to pass around file descriptors needed for DRI3.
char ancilBuf[ANCIL_SIZE];
size_t ancilRead, ancilWrite;
};
static char sendAll(struct Connection* conn, const void* buf, size_t length)
{
int remaining = length;
while (remaining)
{
struct iovec iov;
iov.iov_base = (void*)buf;
iov.iov_len = remaining;
struct msghdr msg;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = conn->ancilBuf + conn->ancilRead;
msg.msg_controllen = conn->ancilWrite - conn->ancilRead;
int len = sendmsg(conn->sendfd, &msg, MSG_NOSIGNAL);
if (len <= 0)
log_debug("%c sendmsg returned %d\n", conn->dir, len);
if (len <= 0)
return 0;
hexDump(msg.msg_control, msg.msg_controllen, conn->dir, '%');
conn->ancilRead += msg.msg_controllen;
if (conn->ancilRead == conn->ancilWrite)
conn->ancilRead = conn->ancilWrite = 0;
hexDump(buf, len, conn->dir, '=');
buf += len;
remaining -= len;
}
return 1;
}
static char recvAll(struct Connection* conn, void* buf, size_t length)
{
int remaining = length;
while (remaining)
{
struct iovec iov;
iov.iov_base = buf;
iov.iov_len = remaining;
struct msghdr msg;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = conn->ancilBuf + conn->ancilWrite;
msg.msg_controllen = ANCIL_SIZE - conn->ancilWrite;
int len = recvmsg(conn->recvfd, &msg, 0);
if (len <= 0)
log_debug("%c recvmsg returned %d\n", conn->dir, len);
if (len < 0)
return 0;
hexDump(msg.msg_control, msg.msg_controllen, conn->dir, '*');
conn->ancilWrite += msg.msg_controllen;
if (len == 0)
return 0;
hexDump(buf, len, conn->dir, '-');
buf += len;
remaining -= len;
}
return 1;
}
static size_t pad(size_t n)
{
return (n+3) & ~3;
}
static const char* requestNames[256] =
{
NULL, // 0
"CreateWindow",
"ChangeWindowAttributes",
"GetWindowAttributes",
"DestroyWindow",
"DestroySubwindows",
"ChangeSaveSet",
"ReparentWindow",
"MapWindow",
"MapSubwindows",
"UnmapWindow",
"UnmapSubwindows",
"ConfigureWindow",
"CirculateWindow",
"GetGeometry",
"QueryTree",
"InternAtom",
"GetAtomName",
"ChangeProperty",
"DeleteProperty",
"GetProperty",
"ListProperties",
"SetSelectionOwner",
"GetSelectionOwner",
"ConvertSelection",
"SendEvent",
"GrabPointer",
"UngrabPointer",
"GrabButton",
"UngrabButton",
"ChangeActivePointerGrab",
"GrabKeyboard",
"UngrabKeyboard",
"GrabKey",
"UngrabKey",
"AllowEvents",
"GrabServer",
"UngrabServer",
"QueryPointer",
"GetMotionEvents",
"TranslateCoords",
"WarpPointer",
"SetInputFocus",
"GetInputFocus",
"QueryKeymap",
"OpenFont",
"CloseFont",
"QueryFont",
"QueryTextExtents",
"ListFonts",
"ListFontsWithInfo",
"SetFontPath",
"GetFontPath",
"CreatePixmap",
"FreePixmap",
"CreateGC",
"ChangeGC",
"CopyGC",
"SetDashes",
"SetClipRectangles",
"FreeGC",
"ClearArea",
"CopyArea",
"CopyPlane",
"PolyPoint",
"PolyLine",
"PolySegment",
"PolyRectangle",
"PolyArc",
"FillPoly",
"PolyFillRectangle",
"PolyFillArc",
"PutImage",
"GetImage",
"PolyText8",
"PolyText16",
"ImageText8",
"ImageText16",
"CreateColormap",
"FreeColormap",
"CopyColormapAndFree",
"InstallColormap",
"UninstallColormap",
"ListInstalledColormaps",
"AllocColor",
"AllocNamedColor",
"AllocColorCells",
"AllocColorPlanes",
"FreeColors",
"StoreColors",
"StoreNamedColor",
"QueryColors",
"LookupColor",
"CreateCursor",
"CreateGlyphCursor",
"FreeCursor",
"RecolorCursor",
"QueryBestSize",
"QueryExtension",
"ListExtensions",
"ChangeKeyboardMapping",
"GetKeyboardMapping",
"ChangeKeyboardControl",
"GetKeyboardControl",
"Bell",
"ChangePointerControl",
"GetPointerControl",
"SetScreenSaver",
"GetScreenSaver",
"ChangeHosts",
"ListHosts",
"SetAccessControl",
"SetCloseDownMode",
"KillClient",
"RotateProperties",
"ForceScreenSaver",
"SetPointerMapping",
"GetPointerMapping",
"SetModifierMapping",
"GetModifierMapping",
NULL, // 120
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
"NoOperation", // 127
// from this point on the opcodes are dynamically assigned to extensions.
// you can see their names with "xdpyinfo -queryExt | grep opcode"
// https://www.x.org/wiki/Development/Documentation/Protocol/OpCodes/
NULL,
};
static const char *responseNames[256] =
{
"Error", // 0
"Reply",
"KeyPress",
"KeyRelease",
"ButtonPress",
"ButtonRelease",
"MotionNotify",
"EnterNotify",
"LeaveNotify",
"FocusIn",
"FocusOut",
"KeymapNotify",
"Expose",
"GraphicsExpose",
"NoExpose",
"VisibilityNotify",
"CreateNotify",
"DestroyNotify",
"UnmapNotify",
"MapNotify",
"MapRequest",
"ReparentNotify",
"ConfigureNotify",
"ConfigureRequest",
"GravityNotify",
"ResizeRequest",
"CirculateNotify",
"CirculateRequest",
"PropertyNotify",
"SelectionClear",
"SelectionRequest",
"SelectionNotify",
"ColormapNotify",
"ClientMessage",
"MappingNotify",
"GenericEvent",
NULL, // 36
// 64-127 are dynamically assigned to extensions
// 128-255 are events originating from a SendEvent request
// https://www.x.org/releases/current/doc/xproto/x11protocol.html#event_format
};
static const char* focusModes[] = {
"Normal",
"Grab",
"Ungrab",
"WhileGrabbed",
};
static const char* focusDetail[] = {
"Ancestor",
"Virtual",
"Inferior",
"Nonlinear",
"NonlinearVirtual",
"Pointer",
"PointerRoot",
"DetailNone",
};
static void bufSize(unsigned char** ptr, size_t *len, size_t needed)
{
if (needed > *len)
{
*ptr = realloc(*ptr, needed);
*len = needed;
}
}
static int strmemcmp(const char* str, const void* mem, size_t meml)
{
size_t strl = strlen(str);
if (strl != meml)
return strl - meml;
return memcmp(str, mem, meml);
}
typedef struct
{
/// Number of this X server connection for this process
int index;
/// Sockets for the connection to the X server (Xorg) and client (host application)
int server, client;
/// Reusable data buffer
unsigned char *buf;
size_t bufLen;
/// Connection prefix received and sent
bool clientInitialized, serverInitialized;
/// Notes for correlating replies to their requests (see Note_* enum)
unsigned char notes[1<<16];
/// Learned opcodes for X extensions, as returned by QueryExtension
unsigned char opcode_XFree86_VidModeExtension;
unsigned char opcode_RANDR;
unsigned char opcode_Xinerama;
unsigned char opcode_NV_GLX;
/// Learned atoms, as returned by InternAtom
CARD32 atom__NET_ACTIVE_WINDOW;
/// Reply serial tracking and correction
CARD16 serial; // The serial of the last sent request (as seen by the server)
CARD16 serialLast; // The serial of the last received reply
CARD16 serialDelta;
unsigned char skip[1<<16];
Window grabWindow;
} X11ConnData;
enum
{
Note_None,
Note_X_GetGeometry,
Note_X_InternAtom__NET_ACTIVE_WINDOW,
Note_X_InternAtom_Other,
Note_X_QueryExtension_XFree86_VidModeExtension,
Note_X_QueryExtension_RANDR,
Note_X_QueryExtension_Xinerama,
Note_X_QueryExtension_NV_GLX,
Note_X_QueryExtension_Other,
Note_X_XF86VidModeGetModeLine,
Note_X_XF86VidModeGetAllModeLines,
Note_X_RRGetScreenInfo,
Note_X_RRGetScreenResources,
Note_X_RRGetCrtcInfo,
Note_X_RRGetScreenResourcesCurrent,
Note_X_XineramaQueryScreens,
Note_X_GrabPointer,
Note_NV_GLX,
};
// definition stolen from libX11/src/Xatomtype.h
typedef struct {
CARD32 flags;
INT32 x, y, width, height;
INT32 minWidth, minHeight;
INT32 maxWidth, maxHeight;
INT32 widthInc, heightInc;
INT32 minAspectX, minAspectY;
INT32 maxAspectX, maxAspectY;
INT32 baseWidth,baseHeight;
CARD32 winGravity;
} xPropSizeHints;
#define PMinSize (1L << 4) /* program specified minimum size */
#define PMaxSize (1L << 5) /* program specified maximum size */
static void debugPropSizeHints(xPropSizeHints* hints) {
log_debug2(
"PropSizeHints: flags=0x%"PRIxCARD32" pos=%"PRIuCARD32"x%"PRIuCARD32" size=%"PRIuCARD32"x%"PRIuCARD32
" min_size=%"PRIuCARD32"x%"PRIuCARD32" base_size=%"PRIuCARD32"x%"PRIuCARD32
" max_size=%"PRIuCARD32"x%"PRIuCARD32" size_inc=%"PRIuCARD32"x%"PRIuCARD32
" min_aspect=%"PRIuCARD32"x%"PRIuCARD32" max_aspect=%"PRIuCARD32"x%"PRIuCARD32" win_gravity=%"PRIuCARD32"\n",
hints->flags,
hints->x, hints->y,
hints->width, hints->height,
hints->minWidth, hints->minHeight,
hints->baseWidth, hints->baseHeight,
hints->maxWidth, hints->maxHeight,
hints->widthInc, hints->heightInc,
hints->minAspectX, hints->minAspectY,
hints->maxAspectX, hints->maxAspectY,
hints->winGravity
);
}
static void logXReply(X11ConnData *data, const char* name, const xReply* reply, size_t length)
{
// https://www.x.org/releases/current/doc/xproto/x11protocol.html#event_format
// Event codes 64 through 127 are reserved for extensions
bool isDynamicOp = (reply->generic.type & 0x40) != 0;
// The most significant bit in this code is set if the event was generated from a SendEvent request
bool isOriginSendEvent = (reply->generic.type & 0x80) != 0;
const char* responseName = isDynamicOp ? "*DYN_OP*" : responseNames[reply->generic.type & 0x7f];
if (isOriginSendEvent)
{
log_debug2(" [%d][%d] %s from SendEvent: %d (%s) length=%zu\n",
data->index, reply->generic.sequenceNumber, name,
reply->generic.type & 0x7f, responseName, length);
}
else
{
log_debug2(" [%d][%d] %s: %d (%s) length=%zu\n",
data->index, reply->generic.sequenceNumber, name,
reply->generic.type, responseName, length);
}
}
static void logXReq(X11ConnData *data, const char* name, const xReq* req, size_t length, CARD16 sequenceNumber)
{
// https://www.x.org/releases/current/doc/xproto/x11protocol.html#request_format
// Major opcodes 128 through 255 are reserved for extensions
bool isDynamicOp = (req->reqType & 0x80) != 0;
// TODO: catch those dynamic opcode names
const char* reqName = isDynamicOp ? "*DYN_OP*" : requestNames[req->reqType & 0x7f];
log_debug2("[%d][%d] %s: %d (%s) with data %d, length=%zu\n",
data->index, sequenceNumber, name, req->reqType, reqName, req->data, length);
/* log_debug2(" [server: %d] <- [client: %d]\n", sequenceNumber, sequenceNumber - data->serialDelta); */
}
static CARD16 injectRequest(X11ConnData *data, void* buf, size_t size)
{
struct Connection conn = {};
conn.recvfd = data->client;
conn.sendfd = data->server;
conn.dir = '{';
const xReq* req = (xReq*)buf;
sendAll(&conn, req, size);
CARD16 sequenceNumber = ++data->serial;
data->skip[sequenceNumber] = true;
logXReq(data, "Injected request", req, size, sequenceNumber);
return sequenceNumber;
}
static CARD16 injectReply(X11ConnData *data, void* buf, size_t size)
{
struct Connection conn = {};
conn.recvfd = data->server;
conn.sendfd = data->client;
conn.dir = '}';
xReply* reply = (xReply*)buf;
reply->generic.sequenceNumber = data->serial - data->serialDelta--;
reply->generic.length = ((size < sz_xReply ? sz_xReply : size) - sz_xReply + 3) / 4;
sendAll(&conn, reply, size);
logXReply(data, "Injected reply", reply, size);
return reply->generic.sequenceNumber;
}
static void injectEvent(X11ConnData *data, xEvent* event)
{
struct Connection conn = {};
conn.recvfd = data->server;
conn.sendfd = data->client;
conn.dir = '}';
size_t size = sizeof(xEvent);
sendAll(&conn, event, size);
logXReply(data, "Injected event", (const xReply *) event, size);
}
static void grabPointer(X11ConnData* data, Window window)
{
xGrabPointerReq req;
req.reqType = X_GrabPointer;
req.ownerEvents = true; // ?
req.length = sizeof(req)/4;
req.grabWindow = window;
req.eventMask = ~0xFFFF8003;
req.pointerMode = 1 /* Asynchronous */;
req.keyboardMode = 1 /* Asynchronous */;
req.confineTo = window;
req.cursor = None;
req.time = CurrentTime;
CARD16 serial = injectRequest(data, &req, sizeof(req));
data->notes[serial] = Note_X_GrabPointer;
}
static void handleServerHandshake(void* buf, size_t length)
{
size_t usedbytes = sz_xConnSetup;
if (length < usedbytes)
{
log_debug2("malformed handshake: Too short\n");
return;
}
xConnSetup* c = (xConnSetup *)buf;
buf += sz_xConnSetup;
log_debug2(" xConnSetup vendor='%.*s' numRoots=%d numFormats=%d\n",
c->nbytesVendor, (char*) buf, c->numRoots, c->numFormats);
// fakeScreenResolution
if (config.fakeScreenW == 0
&& config.fakeScreenH == 0
&& config.fakeScreenDimW == 0
&& config.fakeScreenDimH == 0)
return;
// vendor length is padded to 4 bytes
// https://github.com/mirror/libX11/blob/ff8706a5eae25b8bafce300527079f68a201d27f/src/OpenDis.c#L311-L336
usedbytes += pad(c->nbytesVendor) + sz_xPixmapFormat * c->numFormats;
if (length < usedbytes)
{
log_debug2("malformed handshake: Too short\n");
return;
}
buf += pad(c->nbytesVendor) + sz_xPixmapFormat * c->numFormats;
for (int i = 0; i < c->numRoots; ++i)
{
usedbytes += sz_xWindowRoot;
if (length < usedbytes)
{
log_debug2("malformed handshake: Too short\n");
return;
}
xWindowRoot* root = (xWindowRoot *)buf;
buf += sz_xWindowRoot;
log_debug2(" xWindowRoot #%d (%dx%d %dmmx%dmm)\n",
i, root->pixWidth, root->pixHeight, root->mmWidth, root->mmHeight);
if (config.fakeScreenW > 0)
root->pixWidth = config.fakeScreenW;
if (config.fakeScreenH > 0)
root->pixHeight = config.fakeScreenH;
if (config.fakeScreenDimW > 0)
root->mmWidth = config.fakeScreenDimW;
if (config.fakeScreenDimH > 0)
root->mmHeight = config.fakeScreenDimH;
log_debug2(" -> (%dx%d %dmmx%dmm)\n",
root->pixWidth, root->pixHeight, root->mmWidth, root->mmHeight);
// now skip to the next root
// after each root there are nDepths of xDepth
for (int j = 0; j < root->nDepths; ++j) {