-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
mormot.net.sock.windows.inc
2542 lines (2347 loc) · 81.2 KB
/
mormot.net.sock.windows.inc
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
{
This file is a part of the Open Source Synopse mORMot framework 2,
licensed under a MPL/GPL/LGPL three license - see LICENSE.md
Implements WinSock2 API calls, as used by mormot.net.sock.pas on Windows.
Using our own unit makes code easier to maintain between Delphi/FPC versions,
and allow to increase FD_SETSIZE for better TPollSocketSelect performance.
Oldest Delphis didn't even include WinSock2.pas, so we redefined everything.
}
uses
Windows,
mormot.lib.sspi; // for Low-Level SSPI/SChannel Functions
{ ******** WinSock2 Type Definitions }
const
ws2 = 'ws2_32.dll';
host_file = 'c:\windows\system32\drivers\etc\hosts';
const
// default on Windows is 64, but we grow it to 512 for TPollSocketSelect
// as stated by Raymond Chen: "you can make FD_SETSIZE bigger if you need to"
// https://devblogs.microsoft.com/oldnewthing/20161221-00/?p=94985
// -> Xitami uses 1024 since 1996
// -> safe since our TFDSet is INTERNAL to this unit, and never published :)
// -> not too big, since TFDSet is allocated on stack
FD_SETSIZE = 512;
type
/// a socket is always pointer-sized on Windows
// - and we also use PtrInt for our TNetSocketWrap cast
TSocket = PtrInt;
TSockLen = integer;
PFDSet = ^TFDSet;
TFDSet = record
fd_count: integer;
fd_array: array[0 .. FD_SETSIZE - 1] of TSocket;
end;
const
FIONREAD = $4004667f;
FIONBIO = $8004667e;
FIOASYNC = $8004667d;
type
PTimeVal = ^TTimeVal;
TTimeVal = record
tv_sec: integer;
tv_usec: integer;
end;
const
IPPROTO_IP = 0; // Abstract
IPPROTO_ICMP = 1; // Internet Control Message Protocol
IPPROTO_IGMP = 2; // Internet Group Management Protocol
IPPROTO_TCP = 6; // TCP
IPPROTO_UDP = 17; // User Datagram Protocol
IPPROTO_IPV6 = 41;
IPPROTO_ICMPV6 = 58;
const
SIO_GET_EXTENSION_FUNCTION_POINTER = $c8000006;
WSAID_ACCEPTEX: TGuid =
(D1: $b5367df1; D2: $cbac; D3: $11cf;
D4: ($95, $ca, $00, $80, $5f, $48, $a1, $92));
WSAID_GETACCEPTEXSOCKADDRS: TGuid =
(D1: $b5367df2; D2: $cbac; D3: $11cf;
D4: ($95, $ca, $00, $80, $5f, $48, $a1, $92));
WSAID_CONNECTEX: TGuid = (
D1: $25a207b9; D2:$ddf3; D3:$4660;
D4: ($8e, $e9, $76, $e5, $8c, $74, $06, $3e));
{
WSAID_TRANSMITFILE: TGuid =
(D1: $b5367df0; D2: $cbac; D3: $11cf;
D4: ($95, $ca, $00, $80, $5f, $48, $a1, $92));
}
type
PInAddr = ^in_addr;
in_addr = packed record
case integer of
0: (S_bytes: packed array [0..3] of byte);
1: (S_addr: cardinal);
end;
PSockAddrIn = ^sockaddr_in;
sockaddr_in = packed record
case integer of
0: (sin_family: word;
sin_port: word;
sin_addr: in_addr;
sin_zero: array[0..7] of AnsiChar);
1: (sa_family: word;
sa_data: array[0..13] of AnsiChar)
end;
PInAddr6 = ^in6_addr;
in6_addr = packed record
case integer of
0: (S6_addr: packed array [0..15] of byte);
1: (u6_addr8: packed array [0..15] of byte);
2: (u6_addr16: packed array [0..7] of word);
3: (u6_addr32: packed array [0..3] of integer);
end;
PSockAddrIn6 = ^sockaddr_in6;
sockaddr_in6 = packed record
sin6_family: word; // AF_INET6
sin6_port: word; // Transport level port number
sin6_flowinfo: cardinal; // IPv6 flow information
sin6_addr: in6_addr; // IPv6 address
sin6_scope_id: cardinal; // Scope Id: IF number for link-local
// SITE id for site-local
end;
const
INADDR_ANY = $00000000;
INADDR_LOOPBACK = $7f000001;
INADDR_BROADCAST = $ffffffff;
INADDR_NONE = $ffffffff;
ADDR_ANY = INADDR_ANY;
INVALID_SOCKET = TSocket(NOT(0));
SOCKET_ERROR = -1;
const
IP_OPTIONS = 1;
IP_HDRINCL = 2;
IP_TOS = 3; // set/get IP Type Of Service
IP_TTL = 4; // set/get IP Time To Live
IP_MULTICAST_IF = 9; // set/get IP multicast interface
IP_MULTICAST_TTL = 10; // set/get IP multicast timetolive
IP_MULTICAST_LOOP = 11; // set/get IP multicast loopback
IP_ADD_MEMBERSHIP = 12; // add an IP group membership
IP_DROP_MEMBERSHIP = 13; // drop an IP group membership
IP_DONTFRAGMENT = 14; // set/get IP Don't Fragment flag
IP_DEFAULT_MULTICAST_TTL = 1; // normally limit m'casts to 1 hop
IP_DEFAULT_MULTICAST_LOOP = 1; // normally hear sends if a member
IP_MAX_MEMBERSHIPS = 20; // per socket; must fit in one mbuf
SOL_SOCKET = $ffff; // options for socket level
// Option flags per-socket
SO_DEBUG = $0001; // turn on debugging info recording
SO_ACCEPTCONN = $0002; // socket has had listen()
SO_REUSEADDR = $0004; // allow local address reuse
SO_KEEPALIVE = $0008; // keep connections alive
SO_DONTROUTE = $0010; // just use interface addresses
SO_BROADCAST = $0020; // permit sending of broadcast msgs
SO_USELOOPBACK = $0040; // bypass hardware when possible
SO_LINGER = $0080; // linger on close if data present
SO_OOBINLINE = $0100; // leave received OOB data in line
SO_DONTLINGER = $ff7f;
// Additional options
SO_SNDBUF = $1001; // send buffer size
SO_RCVBUF = $1002; // receive buffer size
SO_SNDLOWAT = $1003; // send low-water mark
SO_RCVLOWAT = $1004; // receive low-water mark
SO_SNDTIMEO = $1005; // send timeout
SO_RCVTIMEO = $1006; // receive timeout
SO_ERROR = $1007; // get error status and clear
SO_TYPE = $1008; // get socket type
// WinSock 2 extension -- new options
SO_GROUP_ID = $2001; // ID of a socket group}
SO_GROUP_PRIORITY = $2002; // the relative priority within a group}
SO_MAX_MSG_SIZE = $2003; // maximum message size
SO_PROTOCOL_INFOA = $2004; // WSAPROTOCOL_INFOA structure
SO_PROTOCOL_INFOW = $2005; // WSAPROTOCOL_INFOW structure
SO_PROTOCOL_INFO = SO_PROTOCOL_INFOA;
PVD_CONFIG = $3001; // configuration info for service provider
// Option for opening sockets for synchronous access
SO_SYNCHRONOUS_ALERT = $10;
SO_SYNCHRONOUS_NONALERT = $20;
// Other NT-specific options
SO_OPENTYPE = $7008;
SO_MAXDG = $7009;
SO_MAXPATHDG = $700a;
SO_UPDATE_ACCEPT_CONTEXT = $700b;
SO_CONNECT_TIME = $700c;
SOMAXCONN = $7fffffff;
IPV6_UNICAST_HOPS = 8; // ???
IPV6_MULTICAST_IF = 9; // set/get IP multicast i/f
IPV6_MULTICAST_HOPS = 10; // set/get IP multicast ttl
IPV6_MULTICAST_LOOP = 11; // set/get IP multicast loopback
IPV6_JOIN_GROUP = 12; // add an IP group membership
IPV6_LEAVE_GROUP = 13; // drop an IP group membership
// getnameinfo constants
NI_MAXHOST = 1025;
NI_MAXSERV = 32;
NI_NOFQDN = $1;
NI_NUMERICHOST = $2;
NI_NAMEREQD = $4;
NI_NUMERICSERV = $8;
NI_DGRAM = $10;
const
SOCK_STREAM = 1; // stream socket
SOCK_DGRAM = 2; // datagram socket
SOCK_RAW = 3; // raw-protocol interface
SOCK_RDM = 4; // reliably-delivered message
SOCK_SEQPACKET = 5; // sequenced packet stream
// TCP options
TCP_NODELAY = $0001;
// Address families
AF_UNSPEC = 0; // unspecified
AF_INET = 2; // internetwork: UDP, TCP, etc
AF_INET6 = 23; // Internetwork Version 6
AF_MAX = 24;
// Protocol families, same as address families for now
PF_UNSPEC = AF_UNSPEC;
PF_INET = AF_INET;
PF_INET6 = AF_INET6;
PF_MAX = AF_MAX;
type
// Structure used by kernel to store most addresses
PSockAddr = ^TSockAddr;
TSockAddr = sockaddr_in;
type
PAddrInfo = ^TAddrInfo;
TAddrInfo = record
ai_flags: integer; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
ai_family: integer; // PF_xxx
ai_socktype: integer; // SOCK_xxx
ai_protocol: integer; // 0 or IPPROTO_xxx for IPv4 and IPv6
ai_addrlen: integer; // Length of ai_addr
ai_canonname: PAnsiChar; // Canonical name for nodename
ai_addr: PSockAddr; // Binary address
ai_next: PAddrInfo; // Next structure in linked list
end;
const
// Flags used in "hints" argument to getaddrinfo().
AI_PASSIVE = $1; // Socket address will be used in bind() call
AI_CANONNAME = $2; // Return canonical name in first ai_canonname
AI_NUMERICHOST = $4; // Nodename must be a numeric address AnsiString
type
// Structure used for manipulating the linger option
PLinger = ^TLinger;
TLinger = packed record
l_onoff: word;
l_linger: word;
end;
const
MSG_NOSIGNAL = $00; // do not generate SIGPIPE (not defined on Windows)
MSG_OOB = $01; // Process out-of-band data
MSG_PEEK = $02; // Peek at incoming messages
const
// All Windows Sockets error constants are biased by WSABASEERR offset
WSABASEERR = 10000;
// Windows Sockets definitions of regular Microsoft C error constants
WSAEINTR = WSABASEERR + 4; // legacy flag
WSAEBADF = WSABASEERR + 9;
WSAEACCES = WSABASEERR + 13;
WSAEFAULT = WSABASEERR + 14;
WSAEINVAL = WSABASEERR + 22;
WSAEMFILE = WSABASEERR + 24;
// Windows Sockets definitions of regular Berkeley error constants
WSAEWOULDBLOCK = WSABASEERR + 35;
WSAEINPROGRESS = WSABASEERR + 36;
WSAEALREADY = WSABASEERR + 37;
WSAENOTSOCK = WSABASEERR + 38;
WSAEDESTADDRREQ = WSABASEERR + 39;
WSAEMSGSIZE = WSABASEERR + 40;
WSAEPROTOTYPE = WSABASEERR + 41;
WSAENOPROTOOPT = WSABASEERR + 42;
WSAEPROTONOSUPPORT = WSABASEERR + 43;
WSAESOCKTNOSUPPORT = WSABASEERR + 44;
WSAEOPNOTSUPP = WSABASEERR + 45;
WSAEPFNOSUPPORT = WSABASEERR + 46;
WSAEAFNOSUPPORT = WSABASEERR + 47;
WSAEADDRINUSE = WSABASEERR + 48;
WSAEADDRNOTAVAIL = WSABASEERR + 49;
WSAENETDOWN = WSABASEERR + 50;
WSAENETUNREACH = WSABASEERR + 51;
WSAENETRESET = WSABASEERR + 52;
WSAECONNABORTED = WSABASEERR + 53;
WSAECONNRESET = WSABASEERR + 54;
WSAENOBUFS = WSABASEERR + 55;
WSAEISCONN = WSABASEERR + 56;
WSAENOTCONN = WSABASEERR + 57;
WSAESHUTDOWN = WSABASEERR + 58;
WSAETOOMANYREFS = WSABASEERR + 59;
WSAETIMEDOUT = WSABASEERR + 60;
WSAECONNREFUSED = WSABASEERR + 61;
WSAELOOP = WSABASEERR + 62;
WSAENAMETOOLONG = WSABASEERR + 63;
WSAEHOSTDOWN = WSABASEERR + 64;
WSAEHOSTUNREACH = WSABASEERR + 65;
WSAENOTEMPTY = WSABASEERR + 66;
WSAEPROCLIM = WSABASEERR + 67;
WSAEUSERS = WSABASEERR + 68;
WSAEDQUOT = WSABASEERR + 69;
WSAESTALE = WSABASEERR + 70;
WSAEREMOTE = WSABASEERR + 71;
// Extended Windows Sockets error constant definitions
WSASYSNOTREADY = WSABASEERR + 91;
WSAVERNOTSUPPORTED = WSABASEERR + 92;
WSANOTINITIALISED = WSABASEERR + 93;
WSAEDISCON = WSABASEERR + 101;
WSAENOMORE = WSABASEERR + 102;
WSAECANCELLED = WSABASEERR + 103;
WSAEEINVALIDPROCTABLE = WSABASEERR + 104;
WSAEINVALIDPROVIDER = WSABASEERR + 105;
WSAEPROVIDERFAILEDINIT = WSABASEERR + 106;
WSASYSCALLFAILURE = WSABASEERR + 107;
WSASERVICE_NOT_FOUND = WSABASEERR + 108;
WSATYPE_NOT_FOUND = WSABASEERR + 109;
WSA_E_NO_MORE = WSABASEERR + 110;
WSA_E_CANCELLED = WSABASEERR + 111;
WSAEREFUSED = WSABASEERR + 112;
// Error return codes from gethostbyname and gethostbyaddr
// Authoritative Answer: Host not found
WSAHOST_NOT_FOUND = WSABASEERR + 1001;
// Non-Authoritative: Host not found, or SERVERFAIL
WSATRY_AGAIN = WSABASEERR + 1002;
// Non recoverable errors, FORMERR, REFUSED, NOTIMP
WSANO_RECOVERY = WSABASEERR + 1003;
// Valid name, no data record of requested type
WSANO_DATA = WSABASEERR + 1004;
// no address, look for MX record
WSANO_ADDRESS = WSANO_DATA;
// WinSock 2 extension
WSAIOPENDING = ERROR_IO_PENDING;
WSAIOINCOMPLETE = ERROR_IO_INCOMPLETE;
WSAINVALIDHANDLE = ERROR_INVALID_HANDLE;
WSAINVALIDPARAMETER = ERROR_INVALID_PARAMETER;
WSANOTENOUGHMEMORY = ERROR_NOT_ENOUGH_MEMORY;
WSAOPERATIONABORTED = ERROR_OPERATION_ABORTED;
const
WSADESCRIPTION_LEN = 256;
WSASYS_STATUS_LEN = 128;
SHUT_RD = 0;
SHUT_WR = 1;
SHUT_RDWR = 2;
type
PWSAData = ^TWSAData;
TWSAData = record
wVersion: word;
wHighVersion: word;
{$ifdef WIN64}
iMaxSockets: word;
iMaxUdpDg: word;
lpVendorInfo: PAnsiChar;
szDescription: array[0..WSADESCRIPTION_LEN] of AnsiChar;
szSystemStatus: array[0..WSASYS_STATUS_LEN] of AnsiChar;
{$else}
szDescription: array[0..WSADESCRIPTION_LEN] of AnsiChar;
szSystemStatus: array[0..WSASYS_STATUS_LEN] of AnsiChar;
iMaxSockets: word;
iMaxUdpDg: word;
lpVendorInfo: PAnsiChar;
{$endif WIN64}
end;
WSAData = TWSAData;
PTransmitFileBuffers = ^TTransmitFileBuffers;
TTransmitFileBuffers = record
Head: pointer;
HeadLength: cardinal;
Tail: pointer;
TailLength: cardinal;
end;
const
_ST: array[TNetLayer] of integer = (
SOCK_STREAM,
SOCK_DGRAM,
0);
_IP: array[TNetLayer] of integer = (
IPPROTO_TCP,
IPPROTO_UDP,
0);
_SF: array[TNetFamily] of integer = (
0,
AF_INET,
AF_INET6,
0);
{ ******** WinSock2 API calls }
function WSAStartup(wVersionRequired: word; var WSData: TWSAData): integer; stdcall;
external ws2 name 'WSAStartup';
function WSACleanup: integer; stdcall;
external ws2 name 'WSACleanup';
function RawSocketErrNo: integer; stdcall;
external ws2 name 'WSAGetLastError';
function getaddrinfo(NodeName, ServName: PAnsiChar; Hints: PAddrInfo;
var Addrinfo: PAddrInfo): integer; stdcall;
external ws2 name 'getaddrinfo';
procedure freeaddrinfo(ai: PAddrInfo); stdcall;
external ws2 name 'freeaddrinfo';
function socket(af, struct, protocol: integer): TSocket; stdcall;
external ws2 name 'socket';
function setsockopt(s: TSocket; level, optname: integer;
optval: pointer; optlen: integer): integer; stdcall;
external ws2 name 'setsockopt';
function getsockopt(s: TSocket; level, optname: integer;
optval: pointer; optlen: PInteger): integer; stdcall;
external ws2 name 'getsockopt';
function ioctlsocket(s: TSocket; cmd: cardinal; arg: PCardinal): integer; stdcall;
external ws2 name 'ioctlsocket';
function shutdown(s: TSocket; how: integer): integer; stdcall;
external ws2 name 'shutdown';
function closesocket(s: TSocket): integer; stdcall;
external ws2 name 'closesocket';
function getnameinfo(addr: PSockAddr; namelen: integer; host: PAnsiChar;
hostlen: cardinal; serv: PAnsiChar; servlen: cardinal; flags: integer): integer; stdcall;
external ws2 name 'getnameinfo';
function bind(s: TSocket; addr: PSockAddr; namelen: integer): integer; stdcall;
external ws2 name 'bind';
function listen(s: TSocket; backlog: integer): integer; stdcall;
external ws2 name 'listen';
function accept(s: TSocket; addr: PSockAddr; var addrlen: integer): TSocket; stdcall;
external ws2 name 'accept';
function connect(s: TSocket; name: PSockAddr; namelen: integer): integer; stdcall;
external ws2 name 'connect';
function select(nfds: integer; readfds, writefds, exceptfds: PFDSet;
timeout: PTimeVal): integer; stdcall;
external ws2 name 'select';
function recv(s: TSocket; Buf: pointer; len, flags: integer): integer; stdcall;
external ws2 name 'recv';
type
TWsaBuf = record
cLength: cardinal;
pBuffer: pointer;
end;
PWsaBuf = ^TWsaBuf;
function WSAConnect(s: TSocket; name: PSockAddr; namelen: integer;
caller, callee, sqos, gqos: pointer): integer; stdcall;
external ws2 name 'WSAConnect';
function WSARecv(s: TSocket; var lpBuffers: TWsaBuf; dwBufferCount: cardinal;
var lpNumberOfBytesRecvd: cardinal; var lpFlags: cardinal;
lpOverlapped: POverlapped; lpCompletionRoutine: pointer = nil): integer; stdcall;
external ws2 name 'WSARecv';
function WSASend(s: TSocket; var lpBuffers: TWsaBuf; dwBufferCount: cardinal;
var lpNumberOfBytesRecvd: cardinal; dwFlags: cardinal;
lpOverlapped: POverlapped; lpCompletionRoutine: pointer = nil): integer; stdcall;
external ws2 name 'WSASend';
function WSAIoctl(s: TSocket; dwIoControlCode: cardinal; lpvInBuffer: pointer;
cbInBuffer: cardinal; lpvOutBuffer: pointer; cbOutBuffer: cardinal;
lpcbBytesReturned: PCardinal; lpOverlapped: POverlapped;
lpCompletionRoutine: pointer): integer; stdcall;
external ws2 name 'WSAIoctl';
function recvfrom(s: TSocket; Buf: pointer; len, flags: integer;
from: PSockAddr; fromlen: Pinteger): integer; stdcall;
external ws2 name 'recvfrom';
function send(s: TSocket; Buf: pointer; len, flags: integer): integer; stdcall;
external ws2 name 'send';
function sendto(s: TSocket; Buf: pointer; len, flags: integer;
addrto: PSockAddr; tolen: integer): integer; stdcall;
external ws2 name 'sendto';
function getsockname(s: TSocket; name: PSockAddr; var namelen: integer): integer; stdcall;
external ws2 name 'getsockname';
function getpeername(s: TSocket; name: PSockAddr; var namelen: integer): integer; stdcall;
external ws2 name 'getpeername';
function doaccept(s: TSocket; addr: PSockAddr; var async: boolean): TSocket;
var
len: integer;
begin
len := SOCKADDR_SIZE;
result := accept(s, addr, len);
// no accept4() on Windows -> async will be done later
end;
var
// some extended WinSock functions resolved in InitializeUnit below
acceptex: function(ListenSocket, AcceptSocket: TSocket; pOutBuff: pointer;
ReceiveDataLen, LocalAddrLen, RemoteAddrLen: DWORD; var BytesReceived: DWORD;
pOverlapped: POverlapped): BOOL; stdcall;
getacceptexsockaddrs: procedure(lpOutputBuffer: pointer;
dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength: DWORD;
var LocalSockaddr: PSockAddr; var LocalSockaddrLength: integer;
var RemoteSockaddr: PSockAddr; var RemoteSockaddrLength: integer); stdcall;
connectex: function(Sock: TSocket; Name: PSockAddr; NameLen: integer;
SendBuf: pointer; SendLen: DWORD; var BytesSent: DWORD;
Overlapped: POverlapped): BOOL; stdcall;
{
transmitfile: function(s: TSocket; hFile: THandle;
NumberOfBytesToWrite, NumberOfBytesPerSend: DWORD; pOvp: POverlapped;
pTransmitBuffers: PTransmitFileBuffers; dwFlags: DWORD): BOOL; stdcall;
}
{ ******** TNetSocket Cross-Platform Wrapper }
{ TNetAddr }
function SetWinAddr(const host, port: RawUtf8; family: cardinal; layer: TNetLayer;
out addr): boolean;
var
h: TAddrInfo;
res: PAddrInfo;
begin
// use regular OS resolution for known addresses or host names
FillCharFast(h, SizeOf(h), 0);
h.ai_family := family;
h.ai_socktype := _ST[layer];
h.ai_protocol := _IP[layer];
res := nil;
result := getaddrinfo(pointer(host), pointer(port), @h, res) = NO_ERROR;
if result then
MoveFast(res^.ai_addr^, addr, res^.ai_addrlen); // return the first result
if res <> nil then
freeaddrinfo(res);
end;
function TNetAddr.SetFrom(const address, addrport: RawUtf8;
layer: TNetLayer): TNetResult;
var
p: cardinal;
begin
FillCharFast(Addr, SizeOf(Addr), 0);
result := nrNotImplemented;
if layer = nlUnix then
exit;
result := nrNotFound;
if address = '' then
exit;
// check supplied IP port
p := GetCardinal(pointer(addrport));
if (p = 0) and
(addrport <> '0') then // explicit '0' to get ephemeral port
exit;
PSockAddr(@Addr)^.sin_port := bswap16(p);
// first check most simple IPv4 resolution (maybe using mormot.net.dns)
if SetFromIP4(address, false) or
// fallback to OS getaddrinfo() resolution, first try as IP4, then IP6
SetWinAddr(address, addrport, AF_INET, layer, Addr) or
SetWinAddr(address, addrport, AF_INET6, layer, Addr) then
result := nrOk;
end;
{ TNetSocketWrap }
procedure TNetSocketWrap.SetSendTimeout(ms: integer);
begin
// WinAPI expects the time out directly as ms integer
SetOpt(SOL_SOCKET, SO_SNDTIMEO, @ms, SizeOf(ms));
end;
procedure TNetSocketWrap.SetReceiveTimeout(ms: integer);
begin
SetOpt(SOL_SOCKET, SO_RCVTIMEO, @ms, SizeOf(ms));
end;
procedure TNetSocketWrap.SetReuseAddrPort;
begin
// do nothing on Windows
end;
procedure TNetSocketWrap.ReusePort;
var
v: integer;
begin
v := ord(true);
SetOpt(SOL_SOCKET, SO_REUSEADDR, @v, SizeOf(v));
end;
procedure TNetSocketWrap.SetLinger(linger: integer);
var
v: TLinger;
begin
v.l_linger := linger;
v.l_onoff := 0; // don't wait - ord(linger >= 0) would wait
// https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-closesocket
SetOpt(SOL_SOCKET, SO_LINGER, @v, SizeOf(v));
end;
procedure TNetSocketWrap.SetCork(cork: boolean);
begin
// do nothing on Windows
end;
const
// https://techcommunity.microsoft.com/t5/networking-blog/ledbat-background-data-transfer-for-windows/ba-p/3639278
SIO_PRIORITY_HINT = integer($98000018); // _WSAIOW(IOC_VENDOR,$18)
SocketPriorityHintVeryLow = 0;
SocketPriorityHintLow = 1;
SocketPriorityHintNormal = 2;
SocketMaximumPriorityHintType = 3;
procedure TNetSocketWrap.SetLowPriority;
var
v: integer;
begin
v := SocketPriorityHintVeryLow;
setsockopt(TSocket(@self), SOL_SOCKET, SIO_PRIORITY_HINT, @v, SizeOf(v));
// don't call SetOpt() which raise ENetSock on oldest Windows
end;
function TNetSocketWrap.HasLowPriority: boolean;
var
v, l: integer;
begin
v := -1;
l := SizeOf(v);
result :=
(getsockopt(TSocket(@self), SOL_SOCKET, SIO_PRIORITY_HINT, @v, @l) = NO_ERROR) and
(v = SocketPriorityHintVeryLow);
end;
procedure SetTimeVal(ms: cardinal; out tv: TTimeVal);
{$ifdef HASINLINE} inline; {$endif}
begin
if ms = 0 then
begin
tv.tv_sec := 0;
tv.tv_usec := 0;
end
else
begin
tv.tv_sec := ms div 1000;
tv.tv_usec := (ms - (cardinal(tv.tv_sec) * 1000)) * 1000;
end;
end;
function TNetSocketWrap.WaitFor(ms: integer; scope: TNetEvents;
loerr: system.PInteger): TNetEvents;
var
sock: TSocket;
rd, wr, er: record
fd_count: integer;
fd_array: array[0..0] of TSocket; // no need of the 512 entries of TFDSet
end;
rdp, wrp, erp: PFDSet;
tv: TTimeVal;
ptv: pointer;
res: integer;
pending: cardinal;
begin
if loerr <> nil then
loerr^ := 0;
result := [neError];
if @self = nil then
exit;
rdp := nil;
wrp := nil;
erp := nil;
ptv := nil; // infinite timeout
sock := TSocket(@self);
if neWrite in scope then
begin
wr.fd_array[0] := sock;
wr.fd_count := 1;
wrp := @wr;
end;
if neError in scope then
begin
er.fd_array[0] := sock;
er.fd_count := 1;
erp := @er;
end;
if (neRead in scope) or
((wrp = nil) and
(erp = nil)) then // select() needs at least one descriptor
begin
rd.fd_array[0] := sock;
rd.fd_count := 1;
rdp := @rd;
end;
if ms >= 0 then
begin
SetTimeVal(ms, tv);
ptv := @tv;
end;
res := select({ignored=}0, rdp, wrp, erp, ptv);
if res < 0 then
begin
if loerr <> nil then
loerr^ := RawSocketErrNo;
exit; // returning [neError]
end;
result := [];
if res = 0 then
// nothing new detected
exit;
if (rdp <> nil) and
({%H-}rd.fd_count = 1) and
(rd.fd_array[0] = sock) then
if ioctlsocket(sock, FIONREAD, @pending) <> NO_ERROR then
include(result, neError)
else
// FIONREAD is not enough on Windows for graceful disconnection
// -> recv() should be called: https://stackoverflow.com/a/1586817/458259
// -> return neRead and not neClosed if pending=0
include(result, neRead);
if (wrp <> nil) and
({%H-}wr.fd_count = 1) and
(wr.fd_array[0] = sock) then
include(result, neWrite);
if (erp <> nil) and
({%H-}er.fd_count = 1) and
(er.fd_array[0] = sock) then
include(result, neError);
end;
{ ******************** IP Addresses Support }
type
PMIB_IPADDRTABLE = ^MIB_IPADDRTABLE;
MIB_IPADDRTABLE = record
dwNumEntries: DWORD;
ip: array[byte] of record
dwAddr: DWORD;
dwIndex: DWORD;
dwMask: DWORD;
dwBCastAddr: DWORD;
dwReasmSize: DWORD;
unused1: Word;
wType: Word;
end;
end;
var
iphlpapiDll: THandle;
// some iphlpapi.dll late-binded API via DelayedProc()
GetIpAddrTable: function (pIpAddrTable: PMIB_IPADDRTABLE;
var pdwSize: DWORD; bOrder: BOOL): DWORD; stdcall;
function GetIPAddresses(Kind: TIPAddress): TRawUtf8DynArray;
var
Table: MIB_IPADDRTABLE;
Size: DWORD;
i: PtrInt;
n: PtrUInt;
begin
result := nil;
if Kind = tiaIPv6 then
exit; // GetIpAddrTable() is an IPv4 only API
Size := SizeOf(Table);
if not DelayedProc(GetIpAddrTable, iphlpapiDll, 'iphlpapi.dll',
'GetIpAddrTable') or
(GetIpAddrTable(@Table, Size, false) <> NO_ERROR) then
exit;
SetLength(result, Table.dwNumEntries);
n := 0;
for i := 0 to Table.dwNumEntries-1 do
with Table.ip[i] do
if IP4Filter(dwAddr, Kind) then
begin
IP4Text(@dwAddr, result[n]);
inc(n);
end;
if n <> Table.dwNumEntries then
SetLength(result, n);
end;
{ ******************** MAC and DNS Addresses Support }
const
GAA_FLAG_SKIP_UNICAST = $1;
GAA_FLAG_SKIP_ANYCAST = $2;
GAA_FLAG_SKIP_MULTICAST = $4;
GAA_FLAG_SKIP_DNS_SERVER = $8;
GAA_FLAG_INCLUDE_PREFIX = $10;
GAA_FLAG_SKIP_FRIENDLY_NAME = $20;
// below flags are only available on Windows Vista and later
GAA_FLAG_INCLUDE_WINS_INFO = $40;
GAA_FLAG_INCLUDE_GATEWAYS = $80;
GAA_FLAG_INCLUDE_ALL_INTERFACES = $100;
IfOperStatusUp = 1;
IfOperStatusDown = 2;
IF_TYPE_ETHERNET_CSMACD = 6;
IF_TYPE_PPP = 23;
IF_TYPE_SOFTWARE_LOOPBACK = 24;
IF_TYPE_IEEE80211 = 71; // Vista+
IF_TYPE_TUNNEL = 131;
MAX_HOSTNAME_LEN = 128;
MAX_DOMAIN_NAME_LEN = 128;
MAX_SCOPE_ID_LEN = 256;
MAX_ADAPTER_ADDRESS_LEN = 8;
type
SOCKET_ADDRESS = record
lpSockaddr: PSOCKADDR;
iSockaddrLength: integer;
end;
IP_PREFIX_ORIGIN = DWORD;
IP_SUFFIX_ORIGIN = DWORD;
IP_DAD_STATE = DWORD;
IP_ADAPTER_UNION = record
case integer of
0: (
Alignment: QWord);
1: (
Length: ULONG;
FlagsOrIfIndex: DWORD);
end;
PIP_ADAPTER_UNICAST_ADDRESS = ^IP_ADAPTER_UNICAST_ADDRESS;
IP_ADAPTER_UNICAST_ADDRESS = record
Union: IP_ADAPTER_UNION;
Next: PIP_ADAPTER_UNICAST_ADDRESS;
Address: SOCKET_ADDRESS;
PrefixOrigin: IP_PREFIX_ORIGIN;
SuffixOrigin: IP_SUFFIX_ORIGIN;
DadState: IP_DAD_STATE;
ValidLifetime: ULONG;
PreferredLifetime: ULONG;
LeaseLifetime: ULONG;
// below fields are only available on Windows Vista and later
OnLinkPrefixLength: Byte;
end;
PIP_ADAPTER = ^IP_ADAPTER;
// used for IP_ADAPTER_PREFIX, IP_ADAPTER_DNS_SERVER_ADDRESS,
// IP_ADAPTER_GATEWAY_ADDRESS and IP_ADAPTER_WINS_SERVER_ADDRESS
IP_ADAPTER = record
Union: IP_ADAPTER_UNION;
Next: PIP_ADAPTER;
Address: SOCKET_ADDRESS;
PrefixLength: ULONG; // used for IP_ADAPTER_PREFIX only
end;
PIP_ADAPTER_PREFIX = PIP_ADAPTER;
PIP_ADAPTER_ANYCAST_ADDRESS = PIP_ADAPTER;
PIP_ADAPTER_DNS_SERVER_ADDRESS = PIP_ADAPTER;
PIP_ADAPTER_MULTICAST_ADDRESS = PIP_ADAPTER;
PIP_ADAPTER_WINS_SERVER_ADDRESS = PIP_ADAPTER;
PIP_ADAPTER_GATEWAY_ADDRESS = PIP_ADAPTER;
PIP_ADAPTER_ADDRESSES = ^IP_ADAPTER_ADDRESSES;
IP_ADAPTER_ADDRESSES = record
Union: IP_ADAPTER_UNION;
Next: PIP_ADAPTER_ADDRESSES;
AdapterName: PAnsiChar;
FirstUnicastAddress: PIP_ADAPTER_UNICAST_ADDRESS;
FirstAnycastAddress: PIP_ADAPTER_ANYCAST_ADDRESS;
FirstMulticastAddress: PIP_ADAPTER_MULTICAST_ADDRESS;
FirstDnsServerAddress: PIP_ADAPTER_DNS_SERVER_ADDRESS;
DnsSuffix: PWCHAR;
Description: PWCHAR;
FriendlyName: PWCHAR;
PhysicalAddress: array [0 .. MAX_ADAPTER_ADDRESS_LEN - 1] of BYTE;
PhysicalAddressLength: DWORD;
Flags: DWORD;
Mtu: DWORD;
IfType: ULONG;
OperStatus: DWORD;
// below fields are only available on Windows XP with SP1 and later
Ipv6IfIndex: DWORD;
ZoneIndices: array [0..15] of DWORD;
FirstPrefix: PIP_ADAPTER_PREFIX;
// below fields are only available on Windows Vista and later
TransmitLinkSpeed: Int64;
ReceiveLinkSpeed: Int64;
FirstWinsServerAddress: PIP_ADAPTER_WINS_SERVER_ADDRESS;
FirstGatewayAddress: PIP_ADAPTER_GATEWAY_ADDRESS;
Ipv4Metric: ULONG;
Ipv6Metric: ULONG;
Luid: Int64;
Dhcpv4Server: SOCKET_ADDRESS;
CompartmentId: DWORD;
NetworkGuid: TGuid;
ConnectionType: DWORD;
TunnelType: DWORD;
// DHCP v6 Info following (not used by our code)
end;
IP_ADDRESS_STRING = array [0..15] of AnsiChar;
IP_ADDR_IP4 = cardinal;
IP_ADDR_STRING = packed record
IpAddress: IP_ADDRESS_STRING;
IpMask: IP_ADDRESS_STRING;
Context: IP_ADDR_IP4;
end;
PIP_ADDR_STRING = ^IP_ADDR_STRING;
PIP_ADDR_STRING_LINKED_LIST = ^IP_ADDR_STRING_LINKED_LIST;
IP_ADDR_STRING_LINKED_LIST = packed record
Next: PIP_ADDR_STRING_LINKED_LIST;
Current: IP_ADDR_STRING;
end;
FIXED_INFO = packed record
HostName: array[0..MAX_HOSTNAME_LEN + 3] of AnsiChar;
DomainName: array[0..MAX_DOMAIN_NAME_LEN + 3] of AnsiChar;
CurrentDnsServer: PIP_ADDR_STRING;
DnsServerList: IP_ADDR_STRING_LINKED_LIST;
NodeType: DWORD;
ScopeId: array[0 .. MAX_SCOPE_ID_LEN + 3] of AnsiChar;
EnableRouting: DWORD;
EnableProxy: DWORD;
EnableDns: DWORD;
end;
PFIXED_INFO = ^FIXED_INFO;
var
// some iphlpapi.dll late-binded API via DelayedProc()
GetAdaptersAddresses: function(Family: ULONG; Flags: DWORD; Reserved: pointer;
pAdapterAddresses: PIP_ADAPTER_ADDRESSES; pOutBufLen: PULONG): DWORD; stdcall;
SendARP: function(DestIp: DWORD; srcIP: DWORD; pMacAddr: pointer;
PhyAddrLen: pointer): DWORD; stdcall;
GetNetworkParams: function(pFixedInfo: PFIXED_INFO;
pOutBufLen: PULONG): DWORD; stdcall;
GetBestInterface: function(dwDestAddrIPv4: cardinal;
var pdwBestIfIndex: DWORD): DWORD; stdcall;
function _GetDnsAddresses(usePosixEnv, getAD: boolean): TRawUtf8DynArray;
var
n, l: PtrInt;
siz: ULONG;
p: PIP_ADDR_STRING_LINKED_LIST;
tmp: RawByteString;
begin
result := nil;
siz := 0;
if not DelayedProc(GetNetworkParams, iphlpapiDll, 'iphlpapi.dll',
'GetNetworkParams') or
(GetNetworkParams(nil, @siz) <> ERROR_BUFFER_OVERFLOW) then
exit;
SetLength(tmp, siz);
if GetNetworkParams(pointer(tmp), @siz) <> ERROR_SUCCESS then
exit;
if getAD then
begin
l := StrLen(@PFIXED_INFO(tmp)^.DomainName);
if l <> 0 then
begin
SetLength(result, 1);
FastSetString(result[0], @PFIXED_INFO(tmp)^.DomainName, l);
end;
exit;
end;
n := 0;
p := @PFIXED_INFO(tmp)^.DnsServerList;
repeat
l := StrLen(@p^.Current.IpAddress);
if l <> 0 then
begin
SetLength(result, n + 1);
FastSetString(result[n], @p^.Current.IpAddress, l);
inc(n);
end;
p := p^.Next;
until p = nil;
end;