forked from Soreepeong/XivMitmLatencyMitigator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mitigate.py
1674 lines (1438 loc) · 67.2 KB
/
mitigate.py
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
#!/usr/bin/sudo python
import argparse
import collections
import ctypes
import dataclasses
import datetime
import enum
import ipaddress
import json
import logging.handlers
import math
import os
import platform
import random
import shlex
import signal
import socket
import struct
import subprocess
import sys
import time
import typing
import urllib.request
import zlib
import select
ACTION_ID_AUTO_ATTACK = 0x0007
ACTION_ID_AUTO_ATTACK_MCH = 0x0008
AUTO_ATTACK_DELAY = 0.1
SO_ORIGINAL_DST = 80
OPCODE_DEFINITION_LIST_URL = "https://api.github.com/repos/Soreepeong/XivAlexander/contents/StaticData/OpcodeDefinition"
EXTRA_DELAY_HELP = """Server responses have been usually taking between 50ms and 100ms on below-1ms latency to server, so 75ms is a good average.
The server will do sanity check on the frequency of action use requests,
and it's very easy to identify whether you're trying to go below allowed minimum value.
This addon is already in gray area. Do NOT decrease this value. You've been warned.
Feel free to increase and see how does it feel like to play on high latency instead, though."""
T = typing.TypeVar("T")
ArgumentTuple = collections.namedtuple("ArgumentTuple", ("region", "extra_delay", "measure_ping", "update_opcodes"))
OODLE_HELPER_CODE = r"""
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <span>
#include <type_traits>
#include <vector>
#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16
#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5
#define IMAGE_SIZEOF_SHORT_NAME 8
struct IMAGE_DOS_HEADER {
uint16_t e_magic;
uint16_t e_cblp;
uint16_t e_cp;
uint16_t e_crlc;
uint16_t e_cparhdr;
uint16_t e_minalloc;
uint16_t e_maxalloc;
uint16_t e_ss;
uint16_t e_sp;
uint16_t e_csum;
uint16_t e_ip;
uint16_t e_cs;
uint16_t e_lfarlc;
uint16_t e_ovno;
uint16_t e_res[4];
uint16_t e_oemid;
uint16_t e_oeminfo;
uint16_t e_res2[10];
uint32_t e_lfanew;
};
struct IMAGE_FILE_HEADER {
uint16_t Machine;
uint16_t NumberOfSections;
uint32_t TimeDateStamp;
uint32_t PointerToSymbolTable;
uint32_t NumberOfSymbols;
uint16_t SizeOfOptionalHeader;
uint16_t Characteristics;
};
struct IMAGE_DATA_DIRECTORY {
uint32_t VirtualAddress;
uint32_t Size;
};
struct IMAGE_OPTIONAL_HEADER32 {
uint16_t Magic;
uint8_t MajorLinkerVersion;
uint8_t MinorLinkerVersion;
uint32_t SizeOfCode;
uint32_t SizeOfInitializedData;
uint32_t SizeOfUninitializedData;
uint32_t AddressOfEntryPoint;
uint32_t BaseOfCode;
uint32_t BaseOfData;
uint32_t ImageBase;
uint32_t SectionAlignment;
uint32_t FileAlignment;
uint16_t MajorOperatingSystemVersion;
uint16_t MinorOperatingSystemVersion;
uint16_t MajorImageVersion;
uint16_t MinorImageVersion;
uint16_t MajorSubsystemVersion;
uint16_t MinorSubsystemVersion;
uint32_t Win32VersionValue;
uint32_t SizeOfImage;
uint32_t SizeOfHeaders;
uint32_t CheckSum;
uint16_t Subsystem;
uint16_t DllCharacteristics;
uint32_t SizeOfStackReserve;
uint32_t SizeOfStackCommit;
uint32_t SizeOfHeapReserve;
uint32_t SizeOfHeapCommit;
uint32_t LoaderFlags;
uint32_t NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
};
struct IMAGE_OPTIONAL_HEADER64 {
uint16_t Magic;
uint8_t MajorLinkerVersion;
uint8_t MinorLinkerVersion;
uint32_t SizeOfCode;
uint32_t SizeOfInitializedData;
uint32_t SizeOfUninitializedData;
uint32_t AddressOfEntryPoint;
uint32_t BaseOfCode;
uint64_t ImageBase;
uint32_t SectionAlignment;
uint32_t FileAlignment;
uint16_t MajorOperatingSystemVersion;
uint16_t MinorOperatingSystemVersion;
uint16_t MajorImageVersion;
uint16_t MinorImageVersion;
uint16_t MajorSubsystemVersion;
uint16_t MinorSubsystemVersion;
uint32_t Win32VersionValue;
uint32_t SizeOfImage;
uint32_t SizeOfHeaders;
uint32_t CheckSum;
uint16_t Subsystem;
uint16_t DllCharacteristics;
uint64_t SizeOfStackReserve;
uint64_t SizeOfStackCommit;
uint64_t SizeOfHeapReserve;
uint64_t SizeOfHeapCommit;
uint32_t LoaderFlags;
uint32_t NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
};
template<typename TOptionalHeader>
struct IMAGE_NT_HEADERS_SIZED {
uint32_t Signature;
IMAGE_FILE_HEADER FileHeader;
TOptionalHeader OptionalHeader;
};
struct IMAGE_SECTION_HEADER {
char Name[IMAGE_SIZEOF_SHORT_NAME];
union {
uint32_t PhysicalAddress;
uint32_t VirtualSize;
} Misc;
uint32_t VirtualAddress;
uint32_t SizeOfRawData;
uint32_t PointerToRawData;
uint32_t PointerToRelocations;
uint32_t PointerToLinenumbers;
uint16_t NumberOfRelocations;
uint16_t NumberOfLinenumbers;
uint32_t Characteristics;
};
struct IMAGE_BASE_RELOCATION {
uint32_t VirtualAddress;
uint32_t SizeOfBlock;
};
#define FIELD_OFFSET(type, field) ((int32_t)(int64_t)&(((type *)0)->field))
#define IMAGE_FIRST_SECTION( ntheader ) ((IMAGE_SECTION_HEADER*) \
((const char*)(ntheader) + \
FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader ) + \
((ntheader))->FileHeader.SizeOfOptionalHeader \
))
#if defined(_WIN64)
#define STDCALL __stdcall
const auto GamePath = LR"(C:\Program Files (x86)\SquareEnix\FINAL FANTASY XIV - A Realm Reborn\game\ffxiv_dx11.exe)";
extern "C" void* __stdcall VirtualAlloc(void* lpAddress, size_t dwSize, uint32_t flAllocationType, uint32_t flProtect);
void* executable_allocate(size_t size) {
return VirtualAlloc(nullptr, size, 0x3000 /* MEM_COMMIT | MEM_RESERVE */, 0x40 /* PAGE_EXECUTE_READWRITE */);
}
using IMAGE_NT_HEADERS = IMAGE_NT_HEADERS_SIZED<IMAGE_OPTIONAL_HEADER64>;
#elif defined(_WIN32)
#define STDCALL __stdcall
const auto GamePath = LR"(C:\Program Files (x86)\SquareEnix\FINAL FANTASY XIV - A Realm Reborn\game\ffxiv.exe)";
extern "C" void* __stdcall VirtualAlloc(void* lpAddress, size_t dwSize, uint32_t flAllocationType, uint32_t flProtect);
void* executable_allocate(size_t size) {
return VirtualAlloc(nullptr, size, 0x3000 /* MEM_COMMIT | MEM_RESERVE */, 0x40 /* PAGE_EXECUTE_READWRITE */);
}
using IMAGE_NT_HEADERS = IMAGE_NT_HEADERS_SIZED<IMAGE_OPTIONAL_HEADER32>;
#elif defined(__linux__)
#define STDCALL __attribute__((stdcall))
const auto GamePath = R"(ffxiv.exe)";
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <unistd.h>
#include <sys/mman.h>
void* executable_allocate(size_t size) {
const auto p = memalign(sysconf(_SC_PAGE_SIZE), size);
mprotect(p, size, PROT_READ | PROT_WRITE | PROT_EXEC);
return p;
}
using IMAGE_NT_HEADERS = IMAGE_NT_HEADERS_SIZED<IMAGE_OPTIONAL_HEADER32>;
#endif
using OodleNetwork1_Shared_Size = std::remove_pointer_t<int(STDCALL*)(int htbits)>;
using OodleNetwork1_Shared_SetWindow = std::remove_pointer_t<void(STDCALL*)(void* data, int htbits, void* window, int windowSize)>;
using OodleNetwork1UDP_Train = std::remove_pointer_t<void(STDCALL*)(void* state, void* shared, const void* const* trainingPacketPointers, const int* trainingPacketSizes, int trainingPacketCount)>;
using OodleNetwork1UDP_Decode = std::remove_pointer_t<bool(STDCALL*)(void* state, void* shared, const void* compressed, size_t compressedSize, void* raw, size_t rawSize)>;
using OodleNetwork1UDP_Encode = std::remove_pointer_t<int(STDCALL*)(const void* state, const void* shared, const void* raw, size_t rawSize, void* compressed)>;
using OodleNetwork1UDP_State_Size = std::remove_pointer_t<int(STDCALL*)(void)>;
using Oodle_Malloc = std::remove_pointer_t<void*(STDCALL*)(size_t size, int align)>;
using Oodle_Free = std::remove_pointer_t<void(STDCALL*)(void* p)>;
using Oodle_SetMallocFree = std::remove_pointer_t<void(STDCALL*)(Oodle_Malloc* pfnMalloc, Oodle_Free* pfnFree)>;
void* STDCALL my_malloc(size_t size, int align) {
const auto pRaw = (char*)malloc(size + align + sizeof(void*) - 1);
if (!pRaw)
return nullptr;
const auto pAligned = (void*)(((size_t)pRaw + align + 7) & (size_t)-align);
*((void**)pAligned - 1) = pRaw;
return pAligned;
}
void STDCALL my_free(void* p) {
free(*((void**)p - 1));
}
const char* lookup_in_text(const char* pBaseAddress, const char* sPattern, const char* sMask, size_t length) {
std::vector<void*> result;
const std::string_view mask(sMask, length);
const std::string_view pattern(sPattern, length);
const auto& dosh = *(IMAGE_DOS_HEADER*)(&pBaseAddress[0]);
const auto& nth = *(IMAGE_NT_HEADERS*)(&pBaseAddress[dosh.e_lfanew]);
const auto pSectionHeaders = IMAGE_FIRST_SECTION(&nth);
for (size_t i = 0; i < nth.FileHeader.NumberOfSections; ++i) {
if (strncmp(pSectionHeaders[i].Name, ".text", 8) == 0) {
std::string_view section(pBaseAddress + pSectionHeaders[i].VirtualAddress, pSectionHeaders[i].Misc.VirtualSize);
const auto nUpperLimit = section.length() - pattern.length();
for (size_t i = 0; i < nUpperLimit; ++i) {
for (size_t j = 0; j < pattern.length(); ++j) {
if ((section[i + j] & mask[j]) != (pattern[j] & mask[j]))
goto next_char;
}
return section.data() + i;
next_char:;
}
}
}
std::cerr << "Could not find signature" << std::endl;
exit(-1);
return nullptr;
}
int main() {
std::cerr << std::hex;
freopen(NULL, "rb", stdin);
freopen(NULL, "wb", stdout);
std::ifstream game(GamePath, std::ios::binary);
game.seekg(0, std::ios::end);
std::vector<char> buf((size_t)game.tellg());
game.seekg(0, std::ios::beg);
game.read(&buf[0], buf.size());
const auto& dosh = *(IMAGE_DOS_HEADER*)(&buf[0]);
const auto& nth = *(IMAGE_NT_HEADERS*)(&buf[dosh.e_lfanew]);
std::span<char> virt((char*)executable_allocate(nth.OptionalHeader.SizeOfImage), nth.OptionalHeader.SizeOfImage);
std::cerr << std::hex << "Base: 0x" << (size_t)&virt[0] << std::endl;
const auto ddoff = dosh.e_lfanew + sizeof(uint32_t) + sizeof(IMAGE_FILE_HEADER) + nth.FileHeader.SizeOfOptionalHeader;
memcpy(&virt[0], &buf[0], ddoff + sizeof(IMAGE_SECTION_HEADER) * nth.FileHeader.NumberOfSections);
for (const auto& s : std::span((IMAGE_SECTION_HEADER*)&buf[ddoff], nth.FileHeader.NumberOfSections)) {
const auto src = std::span(&buf[s.PointerToRawData], s.SizeOfRawData);
const auto dst = std::span(&virt[s.VirtualAddress], s.Misc.VirtualSize);
memcpy(&dst[0], &src[0], std::min(src.size(), dst.size()));
}
const auto base = nth.OptionalHeader.ImageBase;
for (size_t i = nth.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress,
i_ = i + nth.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
i < i_; ) {
const auto& page = *(IMAGE_BASE_RELOCATION*)&virt[i];
for (const auto relo : std::span((uint16_t*)(&page + 1), (page.SizeOfBlock - sizeof page) / 2)) {
if ((relo >> 12) == 0)
void();
else if ((relo >> 12) == 3)
*(uint32_t*)&virt[(size_t)page.VirtualAddress + (relo & 0xFFF)] += (uint32_t)((size_t)&virt[0] - base);
else if ((relo >> 12) == 10)
*(uint64_t*)&virt[(size_t)page.VirtualAddress + (relo & 0xFFF)] += (uint64_t)((size_t)&virt[0] - base);
else
std::abort();
}
i += page.SizeOfBlock;
}
const auto cpfnOodleSetMallocFree = lookup_in_text(
&virt[0],
"\x75\x16\x68\x00\x00\x00\x00\x68\x00\x00\x00\x00\xe8",
"\xff\xff\xff\x00\x00\x00\x00\xff\x00\x00\x00\x00\xe8",
13) + 12;
const auto pfnOodleSetMallocFree = (Oodle_SetMallocFree*)(cpfnOodleSetMallocFree + 5 + *(int*)(cpfnOodleSetMallocFree + 1));
std::vector<const char*> calls;
for (auto sig1 = lookup_in_text(
&virt[0],
"\x83\x7e\x00\x00\x75\x00\x6a\x00\xe8\x00\x00\x00\x00\x6a\x00\x6a\x00\x50\xe8",
"\xff\xff\x00\x00\xff\x00\xff\x00\xff\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff",
19), sig2 = sig1 + 1024; calls.size() < 6 && sig1 < sig2; sig1++) {
if (*sig1 != (char)0xe8)
continue;
const auto pTargetAddress = sig1 + 5 + *(int*)(sig1 + 1);
if (pTargetAddress < virt.data() || pTargetAddress >= virt.data() + virt.size())
continue;
calls.push_back(pTargetAddress);
}
if (calls.size() < 3) {
std::cerr << "Could not find signature" << std::endl;
return -1;
}
const auto pfnOodleNetwork1_Shared_Size = (OodleNetwork1_Shared_Size*)calls[0];
const auto pfnOodleNetwork1_Shared_SetWindow = (OodleNetwork1_Shared_SetWindow*)calls[2];
const auto pfnOodleNetwork1UDP_State_Size= (OodleNetwork1UDP_State_Size*)(lookup_in_text(
&virt[0],
"\xcc\xb8\x00\xb4\x2e\x00\xc3",
"\xff\xff\xff\xff\xff\xff",
6) + 1);
const auto pfnOodleNetwork1UDP_Train = (OodleNetwork1UDP_Train*)lookup_in_text(
&virt[0],
"\x56\x6a\x08\x68\x00\x84\x4a\x00",
"\xff\xff\xff\xff\xff\xff\xff\xff",
8);
const auto pfnOodleNetwork1UDP_Decode = (OodleNetwork1UDP_Decode*)lookup_in_text(
&virt[0],
"\x8b\x44\x24\x18\x56\x85\xc0\x7e\x00\x8b\x74\x24\x14\x85\xf6\x7e\x00\x3b\xf0",
"\xff\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff",
19);
const auto pfnOodleNetwork1UDP_Encode = (OodleNetwork1UDP_Encode*)lookup_in_text(
&virt[0],
"\xff\x74\x24\x14\x8b\x4c\x24\x08\xff\x74\x24\x14\xff\x74\x24\x14\xff\x74\x24\x14\xe8\x00\x00\x00\x00\xc2\x14\x00\xcc\xcc\xcc\xcc\xb8",
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff",
33);
int htbits = 19;
std::vector<uint8_t> state(pfnOodleNetwork1UDP_State_Size());
std::vector<uint8_t> shared(pfnOodleNetwork1_Shared_Size(htbits));
std::vector<uint8_t> window(0x8000);
pfnOodleSetMallocFree(&my_malloc, &my_free);
pfnOodleNetwork1_Shared_SetWindow(&shared[0], htbits, &window[0], static_cast<int>(window.size()));
pfnOodleNetwork1UDP_Train(&state[0], &shared[0], nullptr, nullptr, 0);
std::vector<uint8_t> src, dst;
src.resize(256);
for (int i = 0; i < 256; i++)
src[i] = i;
dst.resize(src.size());
dst.resize(pfnOodleNetwork1UDP_Encode(&state[0], &shared[0], &src[0], src.size(), &dst[0]));
if (!pfnOodleNetwork1UDP_Decode(&state[0], &shared[0], &dst[0], dst.size(), &src[0], src.size())) {
std::cerr << "Oodle encode/decode test failure" << std::endl;
return -1;
} else {
std::cerr << "Oodle encode test: 256 -> " << dst.size() << std::endl;
}
for (int i = 0; i < 256; i++) {
if (src[i] != i) {
std::cerr << "Oodle encode/decode test failure" << std::endl;
break;
}
}
std::cerr << "Oodle helper running: state=" << state.size() << " shared=" << shared.size() << " window=" << window.size() << std::endl;
while (true) {
struct my_header_t {
uint32_t SourceLength;
uint32_t TargetLength;
} hdr{};
fread(&hdr, sizeof(hdr), 1, stdin);
if (!hdr.SourceLength)
return 0;
// std::cerr << "Request: src=0x" << hdr.SourceLength << " dst=0x" << hdr.TargetLength << std::endl;
src.resize(hdr.SourceLength);
fread(&src[0], 1, src.size(), stdin);
if (hdr.TargetLength == 0xFFFFFFFFU) {
dst.resize(src.size());
dst.resize(pfnOodleNetwork1UDP_Encode(&state[0], &shared[0], &src[0], src.size(), &dst[0]));
// std::cerr << "Encoded: res=0x" << dst.size() << std::endl;
} else {
dst.resize(hdr.TargetLength);
if (!pfnOodleNetwork1UDP_Decode(&state[0], &shared[0], &src[0], src.size(), &dst[0], dst.size())) {
dst.resize(0);
dst.resize(hdr.TargetLength);
}
}
uint32_t size = (uint32_t)dst.size();
fwrite(&size, sizeof(size), 1, stdout);
fwrite(&dst[0], 1, dst.size(), stdout);
fflush(stdout);
}
}
"""
def clamp(v: T, min_: T, max_: T) -> T:
return max(min_, min(max_, v))
class InvalidDataException(ValueError):
pass
class RootRequiredError(RuntimeError):
pass
class TcpInfo(ctypes.Structure):
"""TCP_INFO struct in linux 4.2
see /usr/include/linux/tcp.h for details"""
__u8 = ctypes.c_uint8
__u32 = ctypes.c_uint32
__u64 = ctypes.c_uint64
_fields_ = [
("tcpi_state", __u8),
("tcpi_ca_state", __u8),
("tcpi_retransmits", __u8),
("tcpi_probes", __u8),
("tcpi_backoff", __u8),
("tcpi_options", __u8),
("tcpi_snd_wscale", __u8, 4), ("tcpi_rcv_wscale", __u8, 4),
("tcpi_rto", __u32),
("tcpi_ato", __u32),
("tcpi_snd_mss", __u32),
("tcpi_rcv_mss", __u32),
("tcpi_unacked", __u32),
("tcpi_sacked", __u32),
("tcpi_lost", __u32),
("tcpi_retrans", __u32),
("tcpi_fackets", __u32),
# Times
("tcpi_last_data_sent", __u32),
("tcpi_last_ack_sent", __u32),
("tcpi_last_data_recv", __u32),
("tcpi_last_ack_recv", __u32),
# Metrics
("tcpi_pmtu", __u32),
("tcpi_rcv_ssthresh", __u32),
("tcpi_rtt", __u32),
("tcpi_rttvar", __u32),
("tcpi_snd_ssthresh", __u32),
("tcpi_snd_cwnd", __u32),
("tcpi_advmss", __u32),
("tcpi_reordering", __u32),
("tcpi_rcv_rtt", __u32),
("tcpi_rcv_space", __u32),
("tcpi_total_retrans", __u32),
("tcpi_pacing_rate", __u64),
("tcpi_max_pacing_rate", __u64),
# RFC4898 tcpEStatsAppHCThruOctetsAcked
("tcpi_bytes_acked", __u64),
# RFC4898 tcpEStatsAppHCThruOctetsReceived
("tcpi_bytes_received", __u64),
# RFC4898 tcpEStatsPerfSegsOut
("tcpi_segs_out", __u32),
# RFC4898 tcpEStatsPerfSegsIn
("tcpi_segs_in", __u32),
]
del __u8, __u32, __u64
def __repr__(self):
keyval = ["{}={!r}".format(x[0], getattr(self, x[0]))
for x in self._fields_]
fields = ", ".join(keyval)
return "{}({})".format(self.__class__.__name__, fields)
@classmethod
def from_socket(cls, sock: socket.socket):
"""Takes a socket, and attempts to get TCP_INFO stats on it. Returns a
TcpInfo struct"""
# http://linuxgazette.net/136/pfeiffer.html
padsize = ctypes.sizeof(TcpInfo)
data = sock.getsockopt(socket.SOL_TCP, socket.TCP_INFO, padsize)
# On older kernels, we get fewer bytes, pad with null to fit
padded = data.ljust(padsize, b'\0')
return cls.from_buffer_copy(padded)
@classmethod
def get_latency(cls, sock: socket.socket) -> typing.Optional[float]:
info = cls.from_socket(sock)
if info.tcpi_rtt:
return info.tcpi_rtt / 1000000
else:
return None
class XivMessageIpcActionEffect(ctypes.LittleEndianStructure):
_fields_ = (
("animation_target_actor", ctypes.c_uint32),
("unknown_0x004", ctypes.c_uint32),
("action_id", ctypes.c_uint32),
("global_effect_counter", ctypes.c_uint32),
("animation_lock_duration", ctypes.c_float),
("unknown_target_id", ctypes.c_uint32),
("source_sequence", ctypes.c_uint16),
("rotation", ctypes.c_uint16),
("action_animation_id", ctypes.c_uint16),
("variation", ctypes.c_uint8),
("effect_display_type", ctypes.c_uint8),
("unknonw_0x020", ctypes.c_uint8),
("effect_count", ctypes.c_uint8),
("padding_0x022", ctypes.c_uint16),
)
animation_target_actor: typing.Union[int, ctypes.c_uint32]
unknown_0x004: typing.Union[int, ctypes.c_uint32]
action_id: typing.Union[int, ctypes.c_uint32]
global_effect_counter: typing.Union[int, ctypes.c_uint32]
animation_lock_duration: typing.Union[float, ctypes.c_float]
unknown_target_id: typing.Union[int, ctypes.c_uint32]
source_sequence: typing.Union[int, ctypes.c_uint16]
rotation: typing.Union[int, ctypes.c_uint16]
action_animation_id: typing.Union[int, ctypes.c_uint16]
variation: typing.Union[int, ctypes.c_uint8]
effect_display_type: typing.Union[int, ctypes.c_uint8]
unknown_0x020: typing.Union[int, ctypes.c_uint8]
effect_count: typing.Union[int, ctypes.c_uint8]
padding_0x022: typing.Union[int, ctypes.c_uint16]
class XivMessageIpcActorControlCategory(enum.IntEnum):
CancelCast = 0x000f
Rollback = 0x02bc
class XivMessageIpcActorControl(ctypes.LittleEndianStructure):
_fields_ = (
("category_int", ctypes.c_uint16),
("padding_0x002", ctypes.c_uint16),
("param_1", ctypes.c_uint32),
("param_2", ctypes.c_uint32),
("param_3", ctypes.c_uint32),
("param_4", ctypes.c_uint32),
("padding_0x014", ctypes.c_uint32),
)
category_int: typing.Union[int, ctypes.c_uint16]
padding_0x002: typing.Union[int, ctypes.c_uint16]
param_1: typing.Union[int, ctypes.c_uint32]
param_2: typing.Union[int, ctypes.c_uint32]
param_3: typing.Union[int, ctypes.c_uint32]
param_4: typing.Union[int, ctypes.c_uint32]
padding_0x014: typing.Union[int, ctypes.c_uint32]
@property
def category(self):
try:
return XivMessageIpcActorControlCategory(self.category_int)
except ValueError:
return None
@category.setter
def category(self, value: typing.Union[int, XivMessageIpcActorControlCategory]):
self.category_int = int(value)
class XivMessageIpcActorControlSelf(ctypes.LittleEndianStructure):
_fields_ = (
("category_int", ctypes.c_uint16),
("padding_0x002", ctypes.c_uint16),
("param_1", ctypes.c_uint32),
("param_2", ctypes.c_uint32),
("param_3", ctypes.c_uint32),
("param_4", ctypes.c_uint32),
("param_5", ctypes.c_uint32),
("param_6", ctypes.c_uint32),
("padding_0x01c", ctypes.c_uint32),
)
category_int: typing.Union[int, ctypes.c_uint16]
padding_0x002: typing.Union[int, ctypes.c_uint16]
param_1: typing.Union[int, ctypes.c_uint32]
param_2: typing.Union[int, ctypes.c_uint32]
param_3: typing.Union[int, ctypes.c_uint32]
param_4: typing.Union[int, ctypes.c_uint32]
param_5: typing.Union[int, ctypes.c_uint32]
param_6: typing.Union[int, ctypes.c_uint32]
padding_0x01c: typing.Union[int, ctypes.c_uint32]
@property
def category(self):
try:
return XivMessageIpcActorControlCategory(self.category_int)
except ValueError:
return None
@category.setter
def category(self, value: typing.Union[int, XivMessageIpcActorControlCategory]):
self.category_int = int(value)
class XivMessageIpcActorCast(ctypes.LittleEndianStructure):
_fields_ = (
("action_id", ctypes.c_uint16),
("skill_type", ctypes.c_uint8),
("unknown_0x003", ctypes.c_uint8),
("action_id_2", ctypes.c_uint16),
("unknown_0x006", ctypes.c_uint16),
("cast_time", ctypes.c_float),
("target_id", ctypes.c_uint32),
("rotation", ctypes.c_float),
("unknown_0x014", ctypes.c_uint32),
("x", ctypes.c_uint16),
("y", ctypes.c_uint16),
("z", ctypes.c_uint16),
("unknown_0x01e", ctypes.c_uint16),
)
action_id: typing.Union[int, ctypes.c_uint16]
skill_type: typing.Union[int, ctypes.c_uint8]
unknown_0x003: typing.Union[int, ctypes.c_uint8]
action_id_2: typing.Union[int, ctypes.c_uint16]
unknown_0x006: typing.Union[int, ctypes.c_uint16]
cast_time: typing.Union[float, ctypes.c_float]
target_id: typing.Union[int, ctypes.c_uint32]
rotation: typing.Union[float, ctypes.c_float]
unknown_0x014: typing.Union[int, ctypes.c_uint32]
x: typing.Union[int, ctypes.c_uint16]
y: typing.Union[int, ctypes.c_uint16]
z: typing.Union[int, ctypes.c_uint16]
unknown_0x01e: typing.Union[int, ctypes.c_uint16]
class XivMessageIpcActionRequest(ctypes.LittleEndianStructure):
_fields_ = (
("unknown_0x000", ctypes.c_uint8),
("type", ctypes.c_uint8),
("unknown_0x002", ctypes.c_uint16),
("action_id", ctypes.c_uint32),
("sequence", ctypes.c_uint16),
("unknown_0x00a", ctypes.c_uint16),
("unknown_0x00c", ctypes.c_uint32),
("unknown_0x010", ctypes.c_uint32),
("target_id", ctypes.c_uint32),
("item_source_slot", ctypes.c_uint16),
("item_source_container", ctypes.c_uint16),
("unknown_0x01c", ctypes.c_uint32),
)
unknown_0x000: typing.Union[int, ctypes.c_uint8]
type: typing.Union[int, ctypes.c_uint8]
unknown_0x002: typing.Union[int, ctypes.c_uint16]
action_id: typing.Union[int, ctypes.c_uint32]
sequence: typing.Union[int, ctypes.c_uint16]
unknown_0x00a: typing.Union[int, ctypes.c_uint16]
unknown_0x00c: typing.Union[int, ctypes.c_uint32]
unknown_0x010: typing.Union[int, ctypes.c_uint32]
target_id: typing.Union[int, ctypes.c_uint32]
item_source_slot: typing.Union[int, ctypes.c_uint16]
item_source_container: typing.Union[int, ctypes.c_uint16]
unknown_0x01c: typing.Union[int, ctypes.c_uint32]
class XivMessageIpcCustomOriginalWaitTime(ctypes.LittleEndianStructure):
_fields_ = (
("source_sequence", ctypes.c_uint16),
("padding_0x002", ctypes.c_uint16),
("original_wait_time", ctypes.c_float),
)
source_sequence: typing.Union[int, ctypes.c_uint16]
padding_0x002: typing.Union[int, ctypes.c_uint16] = 0
original_wait_time: typing.Union[float, ctypes.c_float]
class XivMessageIpcType(enum.IntEnum):
UnknownButInterested = 0x0014
XivMitmLatencyMitigatorCustom = 0xe852
class XivMitmLatencyMitigatorCustomSubtype(enum.IntEnum):
OriginalWaitTime = 0x0000
class XivMessageIpcHeader(ctypes.LittleEndianStructure):
_fields_ = (
("type_int", ctypes.c_uint16),
("subtype", ctypes.c_uint16),
("unknown_0x004", ctypes.c_uint16),
("server_id", ctypes.c_uint16),
("epoch", ctypes.c_uint32),
("unknown_0x00c", ctypes.c_uint32),
)
type_int: typing.Union[int, ctypes.c_uint16]
subtype: typing.Union[int, ctypes.c_uint16]
unknown_0x004: typing.Union[int, ctypes.c_uint16]
server_id: typing.Union[int, ctypes.c_uint16]
epoch: typing.Union[int, ctypes.c_uint32]
unknown_0x00c: typing.Union[int, ctypes.c_uint32]
@property
def type(self):
try:
return XivMessageIpcType(self.type_int)
except ValueError:
return None
@type.setter
def type(self, value: typing.Union[int, XivMessageIpcType]):
self.type_int = int(value)
class XivMessageType(enum.IntEnum):
Ipc = 3
class XivMessageHeader(ctypes.LittleEndianStructure):
_fields_ = (
("length", ctypes.c_uint32),
("source_actor", ctypes.c_uint32),
("target_actor", ctypes.c_uint32),
("type_int", ctypes.c_uint16),
("unknown_0x00e", ctypes.c_uint16),
)
length: typing.Union[int, ctypes.c_uint32]
source_actor: typing.Union[int, ctypes.c_uint32]
target_actor: typing.Union[int, ctypes.c_uint32]
type_int: typing.Union[int, ctypes.c_uint16]
unknown_0x00e: typing.Union[int, ctypes.c_uint16]
@property
def type(self):
try:
return XivMessageType(self.type_int)
except ValueError:
return None
@type.setter
def type(self, value: typing.Union[int, XivMessageType]):
self.type_int = int(value)
class OodleHelper:
oodle_helper_path: typing.Optional[str] = None
_process: typing.ClassVar[typing.Optional[subprocess.Popen]] = None
@classmethod
def _init(cls):
if cls._process is not None and cls._process.poll() is None:
return
cls._process = subprocess.Popen(cls.oodle_helper_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
@classmethod
def decode(cls, data: bytes, declen: int) -> bytes:
cls._init()
cls._process: subprocess.Popen
cls._process.stdin.write(int.to_bytes(len(data), 4, "little") + int.to_bytes(declen, 4, "little") + data)
cls._process.stdin.flush()
reslen = int.from_bytes(cls._process.stdout.read(4), "little")
return cls._process.stdout.read(reslen)
@classmethod
def encode(cls, data: bytes) -> bytes:
cls._init()
cls._process: subprocess.Popen
cls._process.stdin.write(int.to_bytes(len(data), 4, "little") + b'\xFF\xFF\xFF\xFF' + data)
cls._process.stdin.flush()
reslen = int.from_bytes(cls._process.stdout.read(4), "little")
return cls._process.stdout.read(reslen)
@classmethod
def init_executable(cls):
if not os.path.exists("ffxiv.exe"):
raise RuntimeError("Need ffxiv.exe in the same directory. "
"Copy one from your local Windows/Mac installation.")
cls.oodle_helper_path = os.path.join(os.getcwd(), "oodle_helper")
with open(cls.oodle_helper_path + ".cpp", "w") as fp:
fp.write(OODLE_HELPER_CODE)
if platform.machine() not in ('i386', 'x86_64'):
raise RuntimeError("Need to be able to run x86 binary natively")
if os.system(f"g++ {shlex.quote(cls.oodle_helper_path)}.cpp -o {shlex.quote(cls.oodle_helper_path)}"
f" -std=c++20 -g -Og -m32"):
os.unlink(cls.oodle_helper_path + ".cpp")
raise RuntimeError("Failed to compile helper")
os.unlink(cls.oodle_helper_path + ".cpp")
class XivBundleHeader(ctypes.LittleEndianStructure):
MAGIC_CONSTANT_1: typing.ClassVar[bytes] = b"\x52\x52\xa0\x41\xff\x5d\x46\xe2\x7f\x2a\x64\x4d\x7b\x99\xc4\x75"
MAGIC_CONSTANT_2: typing.ClassVar[bytes] = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
MAX_LENGTH: typing.ClassVar[int] = 65536
_fields_ = (
("magic", ctypes.c_byte * 16),
("timestamp", ctypes.c_uint64),
("length", ctypes.c_uint32),
("conn_type", ctypes.c_uint16),
("message_count", ctypes.c_uint16),
("encoding", ctypes.c_uint8),
("compression", ctypes.c_uint8),
("unknown_0x022", ctypes.c_uint16),
("decoded_body_length", ctypes.c_uint32),
)
magic: typing.Union[bytearray, ctypes.c_byte * 16]
timestamp: typing.Union[int, ctypes.c_uint64]
length: typing.Union[int, ctypes.c_uint32]
conn_type: typing.Union[int, ctypes.c_uint16]
message_count: typing.Union[int, ctypes.c_uint16]
encoding: typing.Union[int, ctypes.c_uint8]
compression: typing.Union[int, ctypes.c_uint8]
unknown_0x022: typing.Union[int, ctypes.c_uint16]
decoded_body_length: typing.Union[int, ctypes.c_uint32]
@classmethod
def find(cls, data: typing.Union[bytearray, memoryview]):
offset = 0
while offset < len(data):
available_bytes = len(data) - offset
if available_bytes >= len(cls.MAGIC_CONSTANT_1):
mc1 = data.find(cls.MAGIC_CONSTANT_1, offset)
mc2 = data.find(cls.MAGIC_CONSTANT_2, offset)
else:
mc1 = data.find(cls.MAGIC_CONSTANT_1[:available_bytes], offset)
mc2 = data.find(cls.MAGIC_CONSTANT_2[:available_bytes], offset)
if mc1 == -1:
i = mc2
elif mc2 == -1:
i = mc1
else:
i = min(mc1, mc2)
if i == -1: # no hope
yield data[offset:]
offset = len(data)
break
if i != offset:
yield data[offset:i]
offset = i
try:
bundle_header = cls.from_buffer(data, offset)
if len(data) - offset < bundle_header.length:
raise ValueError
bundle_data = data[offset + ctypes.sizeof(bundle_header):offset + bundle_header.length]
bundle_length = bundle_header.length # copy it, as it may get changed later
except ValueError:
break # incomplete data
try:
if bundle_header.compression == 0:
pass
elif bundle_header.compression == 1:
bundle_data = bytearray(zlib.decompress(bundle_data))
elif bundle_header.compression == 2:
bundle_data = bytearray(OodleHelper.decode(bundle_data, bundle_header.decoded_body_length))
else:
raise RuntimeError(f"Unsupported compression method {bundle_header.compression}")
bundle_data_offset = 0
messages = list()
for i in range(bundle_header.message_count):
message_header = XivMessageHeader.from_buffer(bundle_data, bundle_data_offset)
if message_header.length < ctypes.sizeof(message_header):
raise InvalidDataException
message_data = bundle_data[bundle_data_offset + ctypes.sizeof(message_header):
bundle_data_offset + message_header.length]
messages.append((message_header, message_data))
bundle_data_offset += message_header.length
if bundle_data_offset > len(bundle_data):
raise InvalidDataException
offset += bundle_length
yield bundle_header, messages
except Exception as e:
if not isinstance(e, InvalidDataException):
logging.exception("Unknown error occurred while trying to parse bundle")
yield data[offset:offset + 1]
offset += 1
return offset
@dataclasses.dataclass
class OpcodeDefinition:
Name: str
C2S_ActionRequest: int
C2S_ActionRequestGroundTargeted: int
S2C_ActionEffect01: int
S2C_ActionEffect08: int
S2C_ActionEffect16: int
S2C_ActionEffect24: int
S2C_ActionEffect32: int
S2C_ActorCast: int
S2C_ActorControl: int
S2C_ActorControlSelf: int
Server_IpRange: typing.List[typing.Union[ipaddress.IPv4Network,
typing.Tuple[ipaddress.IPv4Address, ipaddress.IPv4Address]]]
Server_PortRange: typing.List[typing.Tuple[int, int]]
@classmethod
def from_dict(cls, data: dict):
kwargs = {}
for field in dataclasses.fields(cls):
field: dataclasses.Field
if field.type is int:
kwargs[field.name] = int(data[field.name], 0)
elif field.name == "Server_IpRange":
iplist = []
for partstr in data[field.name].split(","):
part = [x.strip() for x in partstr.split("-")]
try:
if len(part) == 1:
iplist.append(ipaddress.IPv4Network(part[0]))
elif len(part) == 2:
iplist.append(tuple(sorted(ipaddress.IPv4Address(x) for x in part)))
else:
raise ValueError
except ValueError:
print("Skipping invalid IP address definition", partstr)
kwargs[field.name] = iplist
elif field.name == "Server_PortRange":
portlist = []
for partstr in data[field.name].split(","):
part = [x.strip() for x in partstr.split("-")]
try:
if len(part) == 1:
portlist.append((int(part[0], 0), int(part[0], 0)))
elif len(part) == 2:
portlist.append((int(part[0], 0), int(part[1], 0)))
else:
raise ValueError
except ValueError:
print("Skipping invalid port definition", partstr)
kwargs[field.name] = portlist
else:
kwargs[field.name] = None if data[field.name] is None else field.type(data[field.name])
return OpcodeDefinition(**kwargs)
def is_request(self, opcode: int):
return (opcode == self.C2S_ActionRequest
or opcode == self.C2S_ActionRequestGroundTargeted)
def is_action_effect(self, opcode: int):
return (opcode == self.S2C_ActionEffect01
or opcode == self.S2C_ActionEffect08
or opcode == self.S2C_ActionEffect16