-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSockClient.pas
More file actions
1746 lines (1482 loc) · 48.2 KB
/
SockClient.pas
File metadata and controls
1746 lines (1482 loc) · 48.2 KB
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
// LightWeight Delphi Library For MySQL.
// Copyright (C) 2008 Miroslav Marchev (http://blog.ieti.eu/)
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
unit SockClient;
interface
uses Windows;
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
type
WSAEVENT = THandle;
TSocket = Integer;
PInAddr = ^TInAddr;
TInAddr = packed record
case Integer of
0: (S_bytes: packed array [0..3] of Byte);
1: (S_addr: Longint);
end;
TSockAddrIn = packed record
case Integer of
0: (sin_family: Word;
sin_port: Word;
sin_addr: TInAddr;
sin_zero: array[0..7] of Char);
1: (sa_family: Word;
sa_data: array[0..13] of Char)
end;
TSockAddr = TSockAddrIn;
PSockAddr = ^TSockAddr;
TWSAData = packed record
wVersion: Word;
wHighVersion: Word;
szDescription: array[0..256] of Char;
szSystemStatus: array[0..128] of Char;
iMaxSockets: Word;
iMaxUdpDg: Word;
lpVendorInfo: PChar;
end;
PHostEnt = ^THostEnt;
THostEnt = packed record
h_name: PChar;
h_aliases: ^PChar;
h_addrtype: Smallint;
h_length: Smallint;
case Integer of
0: (h_addr_list: ^PChar);
1: (h_addr: ^PInAddr);
end;
const
AF_INET = 2;
SOCK_STREAM = 1;
FIONBIO = $8004667E;
SOCKET_ERROR = -1;
WSA_INVALID_EVENT = WSAEVENT(nil);
INVALID_SOCKET = TSocket(not(0));
INADDR_NONE = $FFFFFFFF;
WSAEWOULDBLOCK = 10035;
FD_CONNECT = $10;
FD_WRITE = $02;
FD_READ = $01;
FD_CLOSE = $20;
SD_SEND = $01;
SOL_SOCKET = $FFFF;
SO_SNDTIMEO = $1005;
SO_RCVTIMEO = $1006;
SO_ERROR = $1007;
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
const
DNS_TYPE_MX = $000F;
DNS_QUERY_BYPASS_CACHE = $00000008;
type
IP4_ADDRESS = DWORD;
QWORD = Int64;
IN6_ADDR = Pointer;
PPVOID = ^Pointer;
DNS_STATUS = Longint;
DNS_FREE_TYPE = (DnsFreeFlat, DnsFreeRecordList);
IP4_ARRAY = record
AddrCount: DWORD;
AddrArray: array [0..0] of IP4_ADDRESS;
end;
PIP4_ARRAY = ^IP4_ARRAY;
DNS_RECORD_FLAGS = record
Flags: DWORD;
end;
DNS_A_DATA = record
IpAddress: IP4_ADDRESS;
end;
DNS_SOA_DATA = record
pNamePrimaryServer: LPTSTR;
pNameAdministrator: LPTSTR;
dwSerialNo: DWORD;
dwRefresh: DWORD;
dwRetry: DWORD;
dwExpire: DWORD;
dwDefaultTtl: DWORD;
end;
DNS_PTR_DATA = record
pNameHost: LPTSTR;
end;
DNS_MINFO_DATA = record
pNameMailbox: LPTSTR;
pNameErrorsMailbox: LPTSTR;
end;
DNS_MX_DATA = record
pNameExchange: LPTSTR;
wPreference: Word;
Pad: Word;
end;
DNS_TXT_DATA = record
dwStringCount: DWORD;
pStringArray: array [0..0] of LPTSTR;
end;
DNS_NULL_DATA = record
dwByteCount: DWORD;
Data: array [0..0] of Byte;
end;
DNS_WKS_DATA = record
IpAddress: IP4_ADDRESS;
chProtocol: UCHAR;
BitMask: array [0..0] of Byte;
end;
DNS_IP6_ADDRESS = record
case Integer of
0: (IP6Qword: array [0..1] of QWORD);
1: (IP6Dword: array [0..3] of DWORD);
2: (IP6Word: array [0..7] of Word);
3: (IP6Byte: array [0..15] of Byte);
4: (In6: IN6_ADDR);
end;
DNS_AAAA_DATA = record
Ip6Address: DNS_IP6_ADDRESS;
end;
DNS_KEY_DATA = record
wFlags: Word;
chProtocol: Byte;
chAlgorithm: Byte;
Key: array [0..1 - 1] of Byte;
end;
DNS_SIG_DATA = record
pNameSigner: LPTSTR;
wTypeCovered: Word;
chAlgorithm: Byte;
chLabelCount: Byte;
dwOriginalTtl: DWORD;
dwExpiration: DWORD;
dwTimeSigned: DWORD;
wKeyTag: Word;
Pad: Word;
Signature: array [0..0] of Byte;
end;
DNS_ATMA_DATA = record
AddressType: Byte;
Address: array [0..20 - 1] of Byte;
end;
DNS_NXT_DATA = record
pNameNext: LPTSTR;
wNumTypes: Word;
wTypes: array [0..0] of Word;
end;
DNS_SRV_DATA = record
pNameTarget: LPTSTR;
wPriority: Word;
wWeight: Word;
wPort: Word;
Pad: Word;
end;
DNS_TKEY_DATA = record
pNameAlgorithm: LPTSTR;
pAlgorithmPacket: PByte;
pKey: PByte;
pOtherData: PByte;
dwCreateTime: DWORD;
dwExpireTime: DWORD;
wMode: Word;
wError: Word;
wKeyLength: Word;
wOtherLength: Word;
cAlgNameLength: UCHAR;
bPacketPointers: BOOL;
end;
DNS_TSIG_DATA = record
pNameAlgorithm: LPTSTR;
pAlgorithmPacket: PByte;
pSignature: PByte;
pOtherData: PByte;
i64CreateTime: LONGLONG;
wFudgeTime: Word;
wOriginalXid: Word;
wError: Word;
wSigLength: Word;
wOtherLength: Word;
cAlgNameLength: UCHAR;
bPacketPointers: BOOL;
end;
DNS_WINS_DATA = record
dwMappingFlag: DWORD;
dwLookupTimeout: DWORD;
dwCacheTimeout: DWORD;
cWinsServerCount: DWORD;
WinsServers: array [0..0] of IP4_ADDRESS;
end;
DNS_WINSR_DATA = record
dwMappingFlag: DWORD;
dwLookupTimeout: DWORD;
dwCacheTimeout: DWORD;
pNameResultDomain: LPTSTR;
end;
PPDNS_RECORD = ^PDNS_RECORD;
PDNS_RECORD = ^DNS_RECORD;
DNS_RECORD = record
pNext: PDNS_RECORD;
pName: LPTSTR;
wType: Word;
wDataLength: Word;
Flags: record
case Integer of
0: (DW: DWORD);
1: (S: DNS_RECORD_FLAGS);
end;
dwTtl: DWORD;
dwReserved: DWORD;
Data: record
case Integer of
0: (A: DNS_A_DATA);
1: (SOA, Soa_: DNS_SOA_DATA);
2: (PTR, Ptr_,
NS, Ns_,
CNAME, Cname_,
MB, Mb_,
MD, Md_,
MF, Mf_,
MG, Mg_,
MR, Mr_: DNS_PTR_DATA);
3: (MINFO, Minfo_,
RP, Rp_: DNS_MINFO_DATA);
4: (MX, Mx_,
AFSDB, Afsdb_,
RT, Rt_: DNS_MX_DATA);
5: (HINFO, Hinfo_,
ISDN, Isdn_,
TXT, Txt_,
X25: DNS_TXT_DATA);
6: (Null: DNS_NULL_DATA);
7: (WKS, Wks_: DNS_WKS_DATA);
8: (AAAA: DNS_AAAA_DATA);
9: (KEY, Key_: DNS_KEY_DATA);
10: (SIG, Sig_: DNS_SIG_DATA);
11: (ATMA, Atma_: DNS_ATMA_DATA);
12: (NXT, Nxt_: DNS_NXT_DATA);
13: (SRV, Srv_: DNS_SRV_DATA);
14: (TKEY, Tkey_: DNS_TKEY_DATA);
15: (TSIG, Tsig_: DNS_TSIG_DATA);
16: (WINS, Wins_: DNS_WINS_DATA);
17: (WINSR, WinsR_, NBSTAT, Nbstat_: DNS_WINSR_DATA);
end;
end;
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
const
ERROR_BUFFER_OVERFLOW = DWORD(111);
IP_STATUS_BASE = 11000;
IP_SUCCESS = 0;
type
HANDLE = THandle;
LPVOID = Pointer;
IPAddr = ULONG;
USHORT = Word;
IP_ADDRESS_STRING = record
S: array [0..15] of Char;
end;
PIP_ADDRESS_STRING = ^IP_ADDRESS_STRING;
IP_MASK_STRING = IP_ADDRESS_STRING;
PIP_ADDR_STRING = ^IP_ADDR_STRING;
IP_ADDR_STRING = record
Next: PIP_ADDR_STRING;
IpAddress: IP_ADDRESS_STRING;
IpMask: IP_MASK_STRING;
Context: DWORD;
end;
FIXED_INFO = record
HostName: array [0..128 + 3] of Char;
DomainName: array[0..128 + 3] of Char;
CurrentDnsServer: PIP_ADDR_STRING;
DnsServerList: IP_ADDR_STRING;
NodeType: UINT;
ScopeId: array [0..256 + 3] of Char;
EnableRouting: UINT;
EnableProxy: UINT;
EnableDns: UINT;
end;
PFIXED_INFO = ^FIXED_INFO;
IP_OPTION_INFORMATION = record
Ttl: UCHAR;
Tos: UCHAR;
Flags: UCHAR;
OptionsSize: UCHAR;
OptionsData: PUCHAR;
end;
PIP_OPTION_INFORMATION = ^IP_OPTION_INFORMATION;
ICMP_ECHO_REPLY = record
Address: IPAddr;
Status: ULONG;
RoundTripTime: ULONG;
DataSize: USHORT;
Reserved: USHORT;
Data: LPVOID;
Options: IP_OPTION_INFORMATION;
end;
PICMP_ECHO_REPLY = ^ICMP_ECHO_REPLY;
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
type
TWSAStartup = function(wVersionRequested: Word; var lpWSAData: TWSAData): Integer; stdcall;
TWSACleanup = function: Integer; stdcall;
TWSAGetLastError = function: Integer; stdcall;
TWSASetLastError = procedure(iError: Integer); stdcall;
TGetSockOpt = function(s: TSocket; level, optname: Integer; optval: PChar;
var optlen: Integer): Integer; stdcall;
TSetSockOpt = function(s: TSocket; level, optname: Integer; optval: PChar;
optlen: Integer): Integer; stdcall;
TTSocket = function(af, _type, protocol: Integer): TSocket; stdcall;
TIoctlSocket = function(s: TSocket; cmd: DWORD; var argp: Integer): Integer; stdcall;
TConnect = function(s: TSocket; name: PSockAddr; namelen: Integer): Integer; stdcall;
TSend = function(s: TSocket; const buf; len, flags: Integer): Integer; stdcall;
TRecv = function(s: TSocket; var buf; len, flags: Integer): Integer; stdcall;
TShutdown = function(s: TSocket; how: Integer): Integer; stdcall;
TCloseSocket = function(s: TSocket): Integer; stdcall;
TWSACreateEvent = function: WSAEVENT; stdcall;
TWSAEventSelect = function(s: TSOCKET; hEventObject: WSAEVENT;
lNetworkEvents: Longint): Integer; stdcall;
TWSACloseEvent = function(hEvent: WSAEVENT):BOOL; stdcall;
Thtons = function(hostshort: Word): Word; stdcall;
TInet_addr = function(cp: PChar): Longint; stdcall;
TGetHostByName = function(name: PChar): PHostEnt; stdcall;
TDnsQuery = function(pszName: LPCTSTR; wType: Word; Options: DWORD; aipServers: PIP4_ARRAY;
ppQueryResults: PPDNS_RECORD; pReserved: PPVOID): DNS_STATUS; stdcall;
TDnsRecordListFree = procedure(pRecordList: PDNS_RECORD; FreeType: DNS_FREE_TYPE); stdcall;
TGetNetworkParams = function(pFixedInfo: PFIXED_INFO; var pOutBufLen: ULONG): DWORD; stdcall;
TIcmpCreateFile = function: HANDLE; stdcall;
TIcmpSendEcho = function(IcmpHandle: HANDLE; DestinationAddress: IpAddr; RequestData: LPVOID;
RequestSize: Word; RequestOptions: PIP_OPTION_INFORMATION; ReplyBuffer: LPVOID;
ReplySize: DWORD; Timeout: DWORD): DWORD; stdcall;
TIcmpCloseHandle = function(IcmpHandle: HANDLE): BOOL; stdcall;
const
LIB_WIN_SOCK = 'ws2_32.dll';
LIB_DNS_API = 'dnsapi.dll';
LIB_IPHLP_API = 'iphlpapi.dll';
LIB_ICMP = 'icmp.dll';
FUN_WSA_STARTUP = 'WSAStartup';
FUN_WSA_CLEANUP = 'WSACleanup';
FUN_WSA_GET_LAST_ERROR = 'WSAGetLastError';
FUN_WSA_SET_LAST_ERROR = 'WSASetLastError';
FUN_GET_SOCK_OPT = 'getsockopt';
FUN_SET_SOCK_OPT = 'setsockopt';
FUN_SOCKET = 'socket';
FUN_IO_CTL_SOCKET = 'ioctlsocket';
FUN_CONNECT = 'connect';
FUN_SEND = 'send';
FUN_RECV = 'recv';
FUN_SHUTDOWN = 'shutdown';
FUN_CLOSE_SOCKET = 'closesocket';
FUN_WSA_CREATE_EVENT = 'WSACreateEvent';
FUN_WSA_EVENT_SELECT = 'WSAEventSelect';
FUN_WSA_CLOSE_EVENT = 'WSACloseEvent';
FUN_HTONS = 'htons';
FUN_INET_ADDR = 'inet_addr';
FUN_GET_HOST_BY_NAME = 'gethostbyname';
FUN_DNS_QUERY = 'DnsQuery_A';
FUN_DNS_RECORD_LIST_FREE = 'DnsRecordListFree';
FUN_GET_NETWORK_PARAMS = 'GetNetworkParams';
FUN_ICMP_CREATE_FILE = 'IcmpCreateFile';
FUN_ICMP_SEND_ECHO = 'IcmpSendEcho';
FUN_ICMP_CLOSE_HANDLE = 'IcmpCloseHandle';
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
// -------------------------------------------------------------------------- //
const
INET_BUFF_LEN = 2048; // Buffer Resize Step
SOCK_MAX_CHUN = 32768; // Max Buffer Size
TROTTLE_WAIT = 10; // Trottle Loop Timeout
PROBE_WAIT = 0; // Event Probe
SOCK_NO_ERROR = 0; // WinSock Success
SOCKS_VERSION = $04; // SOCKS4 Protocol Ident
SOCKS_CONNECT = $01; // SOCKS4 CONNECT Command
SOCKS_GRANTED = $5A; // SOCKS4 Proxy Success
SOCKS_USER_ID = 'nobody'; // SOCKS4 Default UserId
SOCKS_HOST = '0.0.0.1'; // SOCKS4A Default Host
type
// Custom Buffers
TBufferRec = packed record
Buffer : Pointer; // Buffer Pointer
Length : Integer; // Alloc Buffer Len
Actual : Integer; // Actual Data Len
Initial : Integer; // Initial Buffer Len
end;
// SOCKS4 Request Stuff
TSocksReq = packed record
Version : Byte; // SOCKS Protocol Version
Cmd : Byte; // SOCKS Command
Port : Word; // Network Byte Order Port Number
HostAddr : DWORD; // Network Byte Order IP Address
end;
TSocksResp = packed record
Zero : Byte; // Always $00
Status : Byte; // SOCKS Result Code
Dummy2 : Word; // Ignored
Dummy3 : DWORD; // Ignored
end;
TStringArray = array of string;
type
TSockClient = class(TObject)
private
FSocket : TSocket;
FDocument : TBufferRec;
FTimeout : Integer;
FTargetHost : string;
FTargetPort : Word;
FProxyHost : string;
FProxyPort : Word;
FProxyCode : Integer;
FResolver : Boolean;
// Timeout Control
function TimerStart(var TimerHwnd: THandle; Timeout: Integer): Boolean;
procedure TimerAbort(var TimerHwnd: THandle);
// Socket Connect
function SocketConnect(const ConnectHost: string; ConnectPort: Word): Boolean;
function ProxyConnect(const ConnectHost: string; ConnectPort: Word; ProxyResolve: Boolean = False): Boolean;
function SocketResolve(const TargetHost: string): Longint;
procedure SocketClose(CloseGraceful: Boolean = False);
// Socket Operations
function SocketWrite: Boolean;
function SocketRead(MsgRecv: Boolean = False; SockShut: Boolean = False): Boolean;
// Socket Errors
function SocketError: Integer;
procedure SocketReset;
// Read Document Result
function GetDocument: string;
public
constructor Create;
destructor Destroy; override;
// Multi Request Stuff
function OpenConnection: Boolean;
function SendString(const Request: string; MsgRecv: Boolean = False): Boolean;
procedure CloseConnection(CloseGraceful: Boolean);
// Simple Request Stuff
function SimpleRequest(const Request: string): Boolean;
function SimpleSend(const Request: string): Boolean;
function SimpleRecv(MsgRecv: Boolean = False): Boolean;
// DNS Stuff
function GetMXRecords(const DNSServer, HostName: string; var MxRecords: TStringArray): Boolean;
function GetDnsAddrList(var DNSServers: TStringArray): Boolean;
function PingHost(const TargetHost: string; PingTimeout: Integer = 1000): Boolean;
// Socket Connect Stuff
property Timeout: Integer read FTimeout write FTimeout;
property TargetHost: string read FTargetHost write FTargetHost;
property TargetPort: Word read FTargetPort write FTargetPort;
property ProxyHost: string read FProxyHost write FProxyHost;
property ProxyPort: Word read FProxyPort write FProxyPort;
// SOCKS4, SOCKS4A Toggle
property Resolver: Boolean read FResolver write FResolver;
// Request Result
property Document: string read GetDocument;
// Socket, Proxy Error Codes
property ResultCode: Integer read SocketError;
property ProxyCode: Integer read FProxyCode;
end;
// Buffer Routines
procedure ResizeBuffer(var BufferRec: TBufferRec; Needed: Integer; Initial: Integer = 0);
procedure WriteBuffer(var BufferRec: TBufferRec; BuffData: Pointer; BuffLen: Integer; WritePos: Integer = 0);
function ReadBuffer(DataPtr: Pointer; DataLen: Cardinal; TrimIt: Boolean = False): string; overload
function ReadBuffer(BufferRec: TBufferRec; ChunkSize: Integer): string; overload;
procedure ReadBuffer(BufferRec: TBufferRec; BuffData: Pointer; ChunkSize: Integer); overload;
// Loader Routines
function LoadLib(var LibHandle: THandle; const LibName: string): Boolean;
function LoadFunc(LibHandle: THandle; var FuncPtr: FARPROC; const FuncName: string): Boolean;
function ReleaseLib(var LibHandle: THandle): Boolean;
// Init Routines
procedure InitLib;
procedure FreeLib;
var
IsWinSockOk: Boolean = False;
IsDnsApiOk: Boolean = False;
IsIpHlpOk: Boolean = False;
WSAData: TWSAData;
WSALock: TRTLCriticalSection;
WSLibHandle: THandle = 0;
DNSLibHandle: THandle = 0;
IPHlpLibHandle: THandle = 0;
IcmpLibHandle: THandle = 0;
WSAStartup: TWSAStartup = nil;
WSACleanup: TWSACleanup = nil;
WSAGetLastError: TWSAGetLastError = nil;
WSASetLastError: TWSASetLastError = nil;
getsockopt: TGetSockOpt = nil;
setsockopt: TSetSockOpt = nil;
socket: TTSocket = nil;
ioctlsocket: TIoctlSocket = nil;
connect: TConnect = nil;
send: TSend = nil;
recv: TRecv = nil;
shutdown: TShutdown = nil;
closesocket: TCloseSocket = nil;
WSACreateEvent: TWSACreateEvent = nil;
WSAEventSelect: TWSAEventSelect = nil;
WSACloseEvent: TWSACloseEvent = nil;
htons: Thtons = nil;
inet_addr: TInet_addr = nil;
gethostbyname: TGetHostByName = nil;
DnsQuery: TDnsQuery = nil;
DnsRecordListFree: TDnsRecordListFree = nil;
GetNetworkParams: TGetNetworkParams = nil;
IcmpCreateFile: TIcmpCreateFile = nil;
IcmpSendEcho: TIcmpSendEcho = nil;
IcmpCloseHandle: TIcmpCloseHandle = nil;
implementation
uses SysUtils;
{ TSockClient }
constructor TSockClient.Create;
begin
inherited Create;
// Init Conn Fields
FTimeout := 60000;
FTargetHost := '';
FTargetPort := 0;
FProxyHost := '';
FProxyPort := 0;
FResolver := False;
// Init Buffers
ResizeBuffer(FDocument, INET_BUFF_LEN, INET_BUFF_LEN);
// Init Socket
SocketReset;
end;
destructor TSockClient.Destroy;
begin
// Destroy Socket
SocketClose;
// Free Buffers
ResizeBuffer(FDocument, 0);
inherited Destroy;
end;
function TSockClient.TimerStart(var TimerHwnd: THandle; Timeout: Integer): Boolean;
var
TimerDue: LARGE_INTEGER;
begin
try
Result := False;
TimerHwnd := INVALID_HANDLE_VALUE;
// Check Timeout Valid
if (Timeout <= 0) then Exit;
TimerHwnd := CreateWaitableTimer(nil, True, nil);
// Check Timer Created
if (TimerHwnd = 0) then Exit;
// Set Timeout
TimerDue.QuadPart := -10000000 * (Timeout div 1000);
// Start Timeout Timer
Result := SetWaitableTimer(TimerHwnd, TLargeInteger(TimerDue), 0, nil, nil, False);
except
TimerHwnd := INVALID_HANDLE_VALUE;
Result := False;
end;
end;
procedure TSockClient.TimerAbort(var TimerHwnd: THandle);
begin
try
// Check Handle
if (TimerHwnd = INVALID_HANDLE_VALUE) then Exit;
try
// Reset Timer Abort All
CancelWaitableTimer(TimerHwnd);
finally
// Release Timer
CloseHandle(TimerHwnd);
// Reset Handle
TimerHwnd := INVALID_HANDLE_VALUE;
end;
except
TimerHwnd := INVALID_HANDLE_VALUE;
end;
end;
function TSockClient.SocketConnect(const ConnectHost: string; ConnectPort: Word): Boolean;
var
argp : Longint;
SockAddr : TSockAddr;
SockRes : Integer;
EventArray : array[0..1] of THandle;
EventHwnd : WSAEVENT;
TimerHwnd : THandle;
begin
try
Result := False;
// Check Machine Data
if (Length(Trim(ConnectHost)) <= 0) or (ConnectPort <= 0) then Exit;
// Get Socket
FSocket := socket(AF_INET, SOCK_STREAM, 0);
// Check Socket
if (FSocket = INVALID_SOCKET) then Exit;
// Enable Non Block Mode
argp := 1;
// Check Results To Be Sure
if (ioctlsocket(FSocket, FIONBIO, argp) <> SOCK_NO_ERROR) then Exit;
// Set Socket Timeouts Do Not Rely On Default Values
if (setsockopt(FSocket, SOL_SOCKET, SO_SNDTIMEO, @FTimeout, SizeOf(FTimeout)) <> SOCK_NO_ERROR) then Exit;
if (setsockopt(FSocket, SOL_SOCKET, SO_RCVTIMEO, @FTimeout, SizeOf(FTimeout)) <> SOCK_NO_ERROR) then Exit;
// Create Async Event
EventHwnd := WSACreateEvent;
// Check Event
if (EventHwnd = WSA_INVALID_EVENT) then Exit;
try
// Trigger Timeout Timer
if (TimerStart(TimerHwnd, FTimeout) = False) then Exit;
// Attach Event, Check Attached
if (WSAEventSelect(FSocket, EventHwnd, FD_CONNECT) <> SOCK_NO_ERROR) then Exit;
// Populate Struct
SockAddr.sin_port := htons(ConnectPort);
SockAddr.sa_family := AF_INET;
SockAddr.sin_addr.S_addr := SocketResolve(ConnectHost);
// Check Resolve Result
if (SockAddr.sin_addr.S_addr = 0) then Exit;
// Connect To Target Machine
SockRes := connect(FSocket, @SockAddr, SizeOf(SockAddr));
// Check Return Values To Be Sure
if (SockRes = SOCKET_ERROR) and (SocketError = WSAEWOULDBLOCK) then
begin
// Attach Events
EventArray[0] := TimerHwnd;
EventArray[1] := EventHwnd;
// Success On Connect Event Fail On Timer Elapse
if (WaitForMultipleObjects(2, @EventArray, False, INFINITE) = (WAIT_OBJECT_0 + 1)) then
begin
// Check Socket Errors
// Detect Connection Reset
Result := (SocketError = SOCK_NO_ERROR);
end;
end;
finally
// Detach Event
WSAEventSelect(FSocket, EventHwnd, 0);
// Close Event
WSACloseEvent(EventHwnd);
// Abort Timeout Timer
TimerAbort(TimerHwnd);
end;
except
Result := False;
end;
end;
function TSockClient.ProxyConnect(const ConnectHost: string; ConnectPort: Word; ProxyResolve: Boolean = False): Boolean;
var
SocksIn : TSocksReq;
SocksOut : TSocksResp;
ZeroTerm : Byte;
begin
try
Result := False;
// Check Machine Data
if (Length(Trim(ConnectHost)) <= 0) or (ConnectPort <= 0) then Exit;
// Clear Records Populate With $00
ZeroMemory(@SocksIn, SizeOf(SocksIn));
// Clear Terminator
ZeroTerm := 0;
// Populate SOCKS4 Request
SocksIn.Version := SOCKS_VERSION;
SocksIn.Cmd := SOCKS_CONNECT;
SocksIn.Port := htons(ConnectPort);
// Use SOCKS4A Resolve In Proxy
// Add Invalid IP(0.0.0.x) In Strtuct
if ProxyResolve then
SocksIn.HostAddr := SocketResolve(SOCKS_HOST)
else
SocksIn.HostAddr := SocketResolve(ConnectHost);
// Check Resolve Result
if (SocksIn.HostAddr = 0) then Exit;
// Write To Temporary Buffer
WriteBuffer(FDocument, @SocksIn, SizeOf(SocksIn));
// Write UserId
WriteBuffer(FDocument, PChar(SOCKS_USER_ID), Length(SOCKS_USER_ID), FDocument.Actual);
// Write Separator
WriteBuffer(FDocument, @ZeroTerm, SizeOf(ZeroTerm), FDocument.Actual);
// Use SOCKS4A Resolve In Proxy
// Add Additional Field For Host Resolve
if ProxyResolve then
begin
// Write Resolve Host
WriteBuffer(FDocument, PChar(ConnectHost), Length(ConnectHost), FDocument.Actual);
// Write Separator
WriteBuffer(FDocument, @ZeroTerm, SizeOf(ZeroTerm), FDocument.Actual);
end;
// Send Request
if (SocketWrite = False) then Exit;
// Recieve Only Result Struct Message Recv
if (SocketRead(True) = False) then Exit;
// Check Size Prevent Memory Corruption
if (FDocument.Actual <> SizeOf(SocksOut)) then Exit;
// Clear Records
ZeroMemory(@SocksOut, SizeOf(SocksOut));
// Read SOCKS4 Result
ReadBuffer(FDocument, @SocksOut, FDocument.Actual);
// Check First Byte Good
if (SocksOut.Zero = 0) then
begin
// Set Proxy Status
FProxyCode := SocksOut.Status;
// Check Wish Granted :F
Result := (SocksOut.Status = SOCKS_GRANTED);
end;
except
Result := False;
end;
end;
function TSockClient.SocketWrite: Boolean;
var
BytesSent : Integer;
BytesTotal : Integer;
EventHwnd : WSAEVENT;
BuffLen : Integer;
TimerHwnd : THandle;
begin
try
Result := False;
// Total Bytes Send
BytesTotal := 0;
// Check Request Length
if (FDocument.Actual <= 0) then Exit;
// Check Socket
if (FSocket = INVALID_SOCKET) then Exit;
// Create Event
EventHwnd := WSACreateEvent;
// Check Event
if (EventHwnd = WSA_INVALID_EVENT) then Exit;
try
// Trigger Timeout Timer
if (TimerStart(TimerHwnd, FTimeout) = False) then Exit;
// Attach Event, Check Attached
if (WSAEventSelect(FSocket, EventHwnd, FD_WRITE) <> SOCK_NO_ERROR) then Exit;
// SlowDown Do Not Drain CPU. Watch For Abort
while (WaitForSingleObject(TimerHwnd, TROTTLE_WAIT) = WAIT_TIMEOUT) do
begin
// SlowDown Do Not Drain CPU
if (WaitForSingleObject(EventHwnd, PROBE_WAIT) = WAIT_OBJECT_0) then
begin
// Send Max SOCK_MAX_CHUN Len
BuffLen := FDocument.Actual - BytesTotal;
if (BuffLen > SOCK_MAX_CHUN) then
begin
BuffLen := SOCK_MAX_CHUN;
end;
// Send Always Right Data
BytesSent := send(FSocket, Pointer(DWORD(FDocument.Buffer) + DWORD(BytesTotal))^, BuffLen, 0);
// Caclulate Total Bytes Send
if (BytesSent > 0) then
begin
Inc(BytesTotal, BytesSent);
end;
// Stop When Done
if (((BytesSent = SOCKET_ERROR) or (BytesSent = 0)) and (SocketError <> WSAEWOULDBLOCK))
or (BytesTotal = FDocument.Actual) then
begin
Break;
end;
end;
end;
// Check Send All
Result := (BytesTotal = FDocument.Actual);
finally
// Detach Event
WSAEventSelect(FSocket, EventHwnd, 0);
// Close Event
WSACloseEvent(EventHwnd);
// Abort Timeout Timer
TimerAbort(TimerHwnd);
end;
except
Result := False;
end;
end;
function TSockClient.SocketRead(MsgRecv: Boolean = False; SockShut: Boolean = False): Boolean;
var
EventHwnd : WSAEVENT;
BuffLen : Integer;
BytesRead : Integer;
BytesTotal : Integer;
WritePoint : Integer;
TimerHwnd : THandle;
begin
try
Result := False;
// Total Bytes Recv
BytesTotal := 0;
// Check Socket
if (FSocket = INVALID_SOCKET) then Exit;
// Create Event
EventHwnd := WSACreateEvent;
// Check Event
if (EventHwnd = WSA_INVALID_EVENT) then Exit;
try
// Trigger Timeout Timer
if (TimerStart(TimerHwnd, FTimeout) = False) then Exit;
// Attach Event, Check Attached, Check Operation Type
if SockShut then
begin
if (WSAEventSelect(FSocket, EventHwnd, FD_CLOSE) <> SOCK_NO_ERROR) then Exit;
// Disable Socket Operations
if (shutdown(FSocket, SD_SEND) <> SOCK_NO_ERROR) then Exit;
end
else
begin
if (WSAEventSelect(FSocket, EventHwnd, FD_READ) <> SOCK_NO_ERROR) then Exit;
// Reset Output Buffer
FDocument.Actual := 0;
end;
// SlowDown Do Not Drain CPU. Watch For Abort
while (WaitForSingleObject(TimerHwnd, TROTTLE_WAIT) = WAIT_TIMEOUT) do
begin
// SlowDown Do Not Drain CPU
if (WaitForSingleObject(EventHwnd, PROBE_WAIT) = WAIT_OBJECT_0) then
begin
// Reset To Be Sure
BuffLen := SOCK_MAX_CHUN;
// Write Position Mainly For ShutDown Case
// Reset Only On Receive. ShutDown Appends Buffer
WritePoint := FDocument.Actual + BytesTotal;
// Resize Buffer If Needed
ResizeBuffer(FDocument, WritePoint + BuffLen);
BytesRead := recv(FSocket, Pointer(DWORD(FDocument.Buffer) + DWORD(WritePoint))^, BuffLen, 0);
// Caclulate Total Bytes Received
if (BytesRead > 0) then
begin
Inc(BytesTotal, BytesRead);
end;
// Stop When Done
// Stream - Stop On All Except WSAEWOULDBLOCK
// Message - WSAEWOULDBLOCK Waiting For Request
if (((BytesRead = SOCKET_ERROR) or (BytesRead = 0))
and ((MsgRecv = True) or (SocketError <> WSAEWOULDBLOCK))) then
begin