-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathmormot.net.sock.pas
6466 lines (5995 loc) · 217 KB
/
mormot.net.sock.pas
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
/// low-level access to the OperatingSystem Sockets API (e.g. WinSock2)
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.net.sock;
{
*****************************************************************************
Cross-Platform Raw Sockets API Definition
- Socket Process High-Level Encapsulation
- MAC and IP Addresses Support
- TLS / HTTPS Encryption Abstract Layer
- Efficient Multiple Sockets Polling
- Windows IOCP sockets support
- TUri parsing/generating URL wrapper
- TCrtSocket Buffered Socket Read/Write Class
- NTP / SNTP Protocol Client
The Low-Level Sockets API, which is complex and inconsistent among OS, is
not made public and shouldn't be used in end-user code. This unit
encapsultates all Sockets features into a single set of functions, and
around the TNetSocket abstract wrapper.
*****************************************************************************
Notes:
OS-specific code is located in mormot.net.sock.windows/posix.inc files.
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
mormot.core.base,
mormot.core.os;
{ ******************** Socket Process High-Level Encapsulation }
const
cLocalhost = '127.0.0.1';
cAnyHost = '0.0.0.0';
cBroadcast = '255.255.255.255';
c6Localhost = '::1';
c6AnyHost = '::';
c6Broadcast = 'ffff::1';
cAnyPort = '0';
cLocalhost32 = $0100007f;
{$ifdef OSWINDOWS}
SOCKADDR_SIZE = 28;
{$else}
SOCKADDR_SIZE = 110; // able to store UNIX domain socket name
{$endif OSWINDOWS}
var
/// global variable containing '127.0.0.1'
// - defined as var not as const to use reference counting from TNetAddr.IP
IP4local: RawUtf8;
type
/// the error codes returned by TNetSocket wrapper
// - convenient cross-platform error handling is not possible, mostly because
// Windows doesn't behave exactly like other targets: this enumeration
// flattens socket execution results, and allow easy ToText() text conversion
TNetResult = (
nrOK,
nrRetry,
nrNoSocket,
nrNotFound,
nrNotImplemented,
nrClosed,
nrFatalError,
nrUnknownError,
nrTooManyConnections,
nrRefused,
nrTimeout,
nrInvalidParameter);
/// a pointer to a TNetSocket error
PNetResult = ^TNetResult;
/// exception class raised by this unit
ENetSock = class(ExceptionWithProps)
protected
fLastError: TNetResult;
public
/// reintroduced constructor with TNetResult information
constructor Create(msg: string; const args: array of const;
error: TNetResult = nrOK; errnumber: system.PInteger = nil); reintroduce;
/// reintroduced constructor with NetLastError call
constructor CreateLastError(const msg: string; const args: array of const;
error: TNetResult = nrOk);
/// raise ENetSock if res is not nrOK or nrRetry
class procedure Check(res: TNetResult; const context: ShortString;
errnumber: system.PInteger = nil);
/// call NetLastError and raise ENetSock if not nrOK nor nrRetry
class procedure CheckLastError(const Context: ShortString;
ForceRaise: boolean = false; AnotherNonFatal: integer = 0);
published
property LastError: TNetResult
read fLastError default nrOk;
end;
/// one data state to be tracked on a given socket
TNetEvent = (
neRead,
neWrite,
neError,
neClosed);
/// the current whole read/write state on a given socket
TNetEvents = set of TNetEvent;
/// the available socket protocol layers
// - by definition, nlUnix will return nrNotImplemented on Windows
TNetLayer = (
nlTcp,
nlUdp,
nlUnix);
/// the available socket families - mapping AF_INET/AF_INET6/AF_UNIX
TNetFamily = (
nfUnknown,
nfIP4,
nfIP6,
nfUnix);
/// the IP port to connect/bind to
TNetPort = cardinal;
const
NO_ERROR = 0;
/// the socket protocol layers over the IP protocol
nlIP = [nlTcp, nlUdp];
type
/// end-user code should use this TNetSocket type to hold a socket handle
// - then its methods will allow cross-platform access to the connection
TNetSocket = ^TNetSocketWrap;
/// pointer reference to a cross-platformsocket handle
PNetSocket = ^TNetSocket;
/// dynamic array of socket handles
TNetSocketDynArray = array of TNetSocket;
/// pointer reference to a dynamic array of socket handles
// - used e.g. as optional parameter to GetReachableNetAddr()
PNetSocketDynArray = ^TNetSocketDynArray;
/// internal mapping of an address, in any supported socket layer
{$ifdef USERECORDWITHMETHODS}
TNetAddr = record
{$else}
TNetAddr = object
{$endif USERECORDWITHMETHODS}
private
// opaque wrapper with len: sockaddr_un=110 (POSIX) or sockaddr_in6=28 (Win)
Addr: array[0..SOCKADDR_SIZE - 1] of byte;
public
/// initialize this address from standard IPv4/IPv6 or nlUnix textual value
// - calls NewSocketIP4Lookup if available from mormot.net.dns (with a 32
// seconds cache) or the proper getaddrinfo/gethostbyname OS API
// - see also NewSocket() overload or GetSocketAddressFromCache() if you
// want to use the global NewSocketAddressCache
function SetFrom(const address, addrport: RawUtf8; layer: TNetLayer): TNetResult;
/// internal host resolution from IPv4, known hosts, NetAddrCache or
// NewSocketIP4Lookup (mormot.net.dns)
// - as called by SetFrom() high-level method
function SetFromIP4(const address: RawUtf8; noNewSocketIP4Lookup: boolean): boolean;
/// initialize this address from a standard IPv4
// - set a given 32-bit IPv4 address and its network port (0..65535)
function SetIP4Port(ipv4: cardinal; netport: TNetPort): TNetResult;
/// returns the network family of this address
function Family: TNetFamily;
/// compare two IPv4/IPv6 network addresses
// - only compare the IP part of the address, not the port, nor any nlUnix
function IPEqual(const another: TNetAddr): boolean;
{$ifdef FPC}inline;{$endif}
/// convert this address into its IPv4/IPv6 textual representation
procedure IP(var res: RawUtf8; localasvoid: boolean = false); overload;
/// convert this address into its IPv4/IPv6 textual representation
function IP(localasvoid: boolean = false): RawUtf8; overload;
{$ifdef HASSAFEINLINE}inline;{$endif}
/// convert this address into its 32-bit IPv4 value, 0 on IPv6/nlUnix
// - may return cLocalhost32 for 127.0.0.1
// - returns 0 (i.e. 0.0.0.0) for AF_INET6 or AF_UNIX
function IP4: cardinal;
{$ifdef FPC}inline;{$endif}
/// convert this address into its shortstring IPv4/IPv6 textual representation
function IPShort(withport: boolean = false): ShortString; overload;
{$ifdef HASINLINE}inline;{$endif}
/// convert this address into its shortstring IPv4/IPv6 textual representation
procedure IPShort(out result: ShortString; withport: boolean = false); overload;
/// convert this address into its 'IPv4/IPv6:port' textual representation
function IPWithPort: RawUtf8;
/// returns the network port (0..65535) of this address
function Port: TNetPort;
/// set the network port (0..65535) of this address
function SetPort(p: TNetPort): TNetResult;
/// compute the number of bytes actually used in this address buffer
function Size: integer;
{$ifdef FPC}inline;{$endif}
/// create a new TNetSocket instance on this network address
// - returns nil on API error
// - SetFrom() should have been called before running this method
function NewSocket(layer: TNetLayer): TNetSocket;
/// connect a TNetSocket instance to this network address
// - by default, blocking connect() timeout is not customizable: this method
// will call MakeAsync/MakeBlocking and wait for the actual connection
// - as called by NewSocket() high-level wrapper function
// - you can specify ms<0 to make an asynchronous connect() on this address
// without waiting yet
function SocketConnect(socket: TNetSocket; ms: integer): TNetResult;
/// bind a TNetSocket instance to this network address
function SocketBind(socket: TNetSocket): TNetResult;
end;
/// pointer reference to a socket address mapping
PNetAddr = ^TNetAddr;
/// dynamic array of socket addresses
TNetAddrDynArray = array of TNetAddr;
PTerminated = ^boolean; // on FPC system.PBoolean doesn't exist :(
/// convenient object-oriented wrapper around a socket connection
// - encapsulate a cross-platform low-level access to the socket API
// - TNetSocket is a pointer to this, so TSocket(@self) is used for OS calls
{$ifdef USERECORDWITHMETHODS}
TNetSocketWrap = record
{$else}
TNetSocketWrap = object
{$endif USERECORDWITHMETHODS}
private
procedure SetOpt(prot, name: integer; value: pointer; valuelen: integer);
function GetOptInt(prot, name: integer): integer;
function SetIoMode(async: cardinal): TNetResult;
procedure SetSendBufferSize(bytes: integer);
procedure SetRecvBufferSize(bytes: integer);
function GetSendBufferSize: integer;
function GetRecvBufferSize: integer;
public
/// called by NewSocket to finalize a socket attributes
procedure SetupConnection(layer: TNetLayer; sendtimeout, recvtimeout: integer);
/// change the sending timeout of this socket, in milliseconds
procedure SetSendTimeout(ms: integer);
/// change the receiving timeout of this socket, in milliseconds
procedure SetReceiveTimeout(ms: integer);
/// change if this socket should enable TCP level keep-alive packets
procedure SetKeepAlive(keepalive: boolean);
/// change the SO_LINGER option, i.e. let the socket remain open for a while
// - on POSIX, will also set the SO_REUSEADDR/SO_REUSEPORT option
procedure SetLinger(linger: integer);
/// allow to disable the Nagle's algorithm and send packets without delay
procedure SetNoDelay(nodelay: boolean);
/// set the TCP_CORK (Linux) or TCP_NOPUSH (BSD) option
procedure SetCork(cork: boolean);
/// set the SO_BROADCAST option for UDP
procedure SetBroadcast(broadcast: boolean);
/// set the SO_REUSEADDR/SO_REUSEPORT option for UDP
// - this method is already called by SetLinger(true) for TCP on POSIX
// - do nothing on Windows, since SO_REUSEADDR does something else than
// on Linux, and is set by SetReuseAddrPort
procedure SetReuseAddrPort;
/// set low SIO_SET_PRIORITY_HINT (Windows 10+) or SO_PRIORITY (Linux)
// - on Windows, try to use LEDBAT algorithm - to be set before accept/connect
procedure SetLowPriority;
/// check if SetLowPriority was successful on the connection
// - on Windows, to be called after accept/connect to see e.g. if LEDBAT is
// used on the connection (false for old Windows, or e.g. if TCP timestamps
// are disabled on the other side)
// - on POSIX, always return false
function HasLowPriority: boolean;
/// set the SO_REUSEPORT option, to allow several servers to bind on a port
// - calls SetReuseAddrPort on Windows
procedure ReusePort;
/// accept an incoming socket, optionally asynchronous
// - async=true will force clientsocket to be defined as asynchronous;
// supporting accept4() syscall on Linux
function Accept(out clientsocket: TNetSocket; out addr: TNetAddr;
async: boolean): TNetResult;
/// retrieve the current address associated on this connected socket
function GetName(out addr: TNetAddr): TNetResult;
/// retrieve the peer address associated on this connected socket
function GetPeer(out addr: TNetAddr): TNetResult;
/// change the socket state to non-blocking
// - note that on Windows, there is no easy way to check the non-blocking
// state of the socket (WSAIoctl has been deprecated for this)
function MakeAsync: TNetResult;
/// change the socket state to blocking
function MakeBlocking: TNetResult;
/// low-level sending of some data via this socket
function Send(Buf: pointer; var len: integer): TNetResult;
/// low-level receiving of some data from this socket
function Recv(Buf: pointer; var len: integer): TNetResult;
/// low-level UDP sending to an address of some data
function SendTo(Buf: pointer; len: integer; const addr: TNetAddr): TNetResult;
/// low-level UDP receiving from an address of some data
function RecvFrom(Buf: pointer; len: integer; out addr: TNetAddr): integer;
/// wait for the socket to a given set of receiving/sending state
// - using poll() on POSIX (as required), and select() on Windows
// - ms < 0 means an infinite timeout (blocking until events happen)
function WaitFor(ms: integer; scope: TNetEvents;
loerr: system.PInteger = nil): TNetEvents;
/// compute how many bytes are actually pending in the receiving queue
function RecvPending(out pending: integer): TNetResult;
/// return how many pending bytes are in the receiving queue
// - returns 0 if no data is available, or if the connection is broken: call
// RecvPending() to check for the actual state of the connection
function HasData: integer;
/// wrapper around WaitFor / RecvPending / Recv methods for a given time
function RecvWait(ms: integer; out data: RawByteString;
terminated: PTerminated = nil): TNetResult;
/// low-level receiving of some data of known length from this socket
function RecvAll(ms: integer; Buf: PByte; len: integer;
terminated: PTerminated = nil): TNetResult;
/// call send in loop until the whole data buffer is sent
function SendAll(Buf: PByte; len: integer;
terminated: PTerminated = nil): TNetResult;
/// check if the socket is not closed nor broken
// - i.e. check if it is likely to be accept Send() and Recv() calls
// - calls WaitFor(neRead) then Recv() to check e.g. WSACONNRESET on Windows
function Available(loerr: system.PInteger = nil): boolean;
/// finalize a socket, calling Close after shutdown() if needed
function ShutdownAndClose(rdwr: boolean): TNetResult;
/// close the socket - consider ShutdownAndClose() for clean closing
function Close: TNetResult;
/// access to the raw socket handle, i.e. @self
function Socket: PtrInt;
{$ifdef HASSAFEINLINE}inline;{$endif}
/// change the OS sending buffer size of this socket, in bytes
// - do not use on Windows, because those values are indicative only and
// are not working as documented by the standard for SO_SNDBUF
property SendBufferSize: integer
read GetSendBufferSize write SetSendBufferSize;
/// change the OS receiving buffer size of this socket, in bytes
// - do not use on Windows, because those values are indicative only and
// are not working as documented by the standard for SO_RCVBUF
property RecvBufferSize: integer
read GetRecvBufferSize write SetRecvBufferSize;
end;
/// used by NewSocket() to cache the host names via NewSocketAddressCache global
// - defined in this unit, but implemented in mormot.net.client.pas
// - the implementation should be thread-safe
INewSocketAddressCache = interface
/// method called by NewSocket() to resolve its address
function Search(const Host: RawUtf8; out NetAddr: TNetAddr): boolean;
/// once resolved, NewSocket() will call this method to cache the TNetAddr
procedure Add(const Host: RawUtf8; const NetAddr: TNetAddr);
/// called by NewSocket() if connection failed, and force DNS resolution
procedure Flush(const Host: RawUtf8);
/// you can call this method to change the default timeout of 10 minutes
// - is likely to flush the cache
procedure SetTimeOut(aSeconds: integer);
end;
/// internal very low-level function retrieving the latest socket OS error code
function RawSocketErrNo: integer; {$ifdef OSWINDOWS} stdcall; {$endif}
/// internal low-level function retrieving the latest socket error information
function NetLastError(AnotherNonFatal: integer = NO_ERROR;
Error: system.PInteger = nil): TNetResult;
/// internal low-level function retrieving the latest socket error message
function NetLastErrorMsg(AnotherNonFatal: integer = NO_ERROR): ShortString;
/// create a new Socket connected or bound to a given ip:port
function NewSocket(const address, port: RawUtf8; layer: TNetLayer;
dobind: boolean; connecttimeout, sendtimeout, recvtimeout, retry: integer;
out netsocket: TNetSocket; netaddr: PNetAddr = nil;
bindReusePort: boolean = false): TNetResult;
/// create a new raw TNetSocket instance
// - returns nil on error
function NewRawSocket(family: TNetFamily; layer: TNetLayer): TNetSocket;
/// create several new raw TNetSocket instances
// - raise ENetSock on error
function NewRawSockets(family: TNetFamily; layer: TNetLayer;
count: integer): TNetSocketDynArray;
/// delete a hostname from TNetAddr.SetFrom internal short-living cache
procedure NetAddrFlush(const hostname: RawUtf8);
/// resolve the TNetAddr of the address:port layer - maybe from NewSocketAddressCache
function GetSocketAddressFromCache(const address, port: RawUtf8;
layer: TNetLayer; out addr: TNetAddr; var fromcache, tobecached: boolean): TNetResult;
/// check if an address is known from the current NewSocketAddressCache
// - calls GetSocketAddressFromCache() so would use the internal cache, if any
function ExistSocketAddressFromCache(const host: RawUtf8): boolean;
/// try to connect to several address:port servers simultaneously
// - return up to neededcount connected TNetAddr, until timeoutms expires
// - sockets are closed unless sockets^[] should contain the result[] sockets
function GetReachableNetAddr(const address, port: array of RawUtf8;
timeoutms: integer = 1000; neededcount: integer = 1;
sockets: PNetSocketDynArray = nil): TNetAddrDynArray;
var
/// contains the raw Socket API version, as returned by the Operating System
// - equals e.g. 'Debian Linux 6.1.0 epoll'
SocketApiVersion: RawUtf8;
/// callback used by NewSocket() to resolve the host name as IPv4
// - not assigned by default, to use the OS default API, i.e. getaddrinfo()
// on Windows, and gethostbyname() on POSIX
// - if you include mormot.net.dns, its own IPv4 DNS resolution function will
// be registered here
// - this level of DNS resolution has a simple in-memory cache of 32 seconds
// - NewSocketAddressCache from mormot.net.client will implement a more
// tunable cache, for both IPv4 and IPv6 resolutions
NewSocketIP4Lookup: function(const HostName: RawUtf8; out IP4: cardinal): boolean;
/// the DNS resolver address(es) to be used by NewSocketIP4Lookup() callback
// - default '' would call GetDnsAddresses to ask the server known by the OS
// - you can specify an alternate CSV list of DNS servers to be called in order
NewSocketIP4LookupServer: RawUtf8;
/// interface used by NewSocket() to cache the host names
// - avoiding DNS resolution is a always a good idea
// - if you include mormot.net.client, will register its own implementation
// class using a TSynDictionary over a 10 minutes default timeout
// - you may call its SetTimeOut or Flush methods to tune the caching
NewSocketAddressCache: INewSocketAddressCache;
/// Queue length for completely established sockets waiting to be accepted,
// a backlog parameter for listen() function. If queue overflows client count,
// ECONNREFUSED error is returned from connect() call
// - for Windows default $7fffffff should not be modified. Actual limit is 200
// - for Unix default is taken from constant (128 as in linux kernel >2.2),
// but actual value is min(DefaultListenBacklog, /proc/sys/net/core/somaxconn)
DefaultListenBacklog: integer;
/// defines if a connection from the loopback should be reported as ''
// - loopback connection will have no Remote-IP - for the default true
// - or loopback connection will be explicitly '127.0.0.1' - if equals false
// - used by both TCrtSock.AcceptRequest and THttpApiServer.Execute servers
RemoteIPLocalHostAsVoidInServers: boolean = true;
/// returns the plain English text of a network result
// - e.g. ToText(nrNotFound)='Not Found'
function ToText(res: TNetResult): PShortString; overload;
/// convert a WaitFor() result set into a regular TNetResult enumerate
function NetEventsToNetResult(ev: TNetEvents): TNetResult;
{ ******************** Mac and IP Addresses Support }
type
/// the filter used by GetIPAddresses() and IP4Filter()
// - the "Public"/"Private" suffix maps IsPublicIP() IANA ranges of IPv4
// address space, i.e. 10.x.x.x, 172.16-31.x.x and 192.168.x.x addresses
// - the "Dhcp" suffix excludes IsApipaIP() 169.254.0.1 - 169.254.254.255
// range, i.e. ensure the address actually came from a real DHCP server
// - tiaAny always return true, for any IPv4 or IPv6 address
// - tiaIPv4 identify any IPv4 address
// - tiaIPv6 identify any IPv6 address
// - tiaIPv4Public identify any IPv4 public address
// - tiaIPv4Private identify any IPv4 private address
// - tiaIPv4Dhcp identify any IPv4 address excluding APIPA range
// - tiaIPv4DhcpPublic identify any IPv4 public address excluding APIPA range
// - tiaIPv4DhcpPrivate identify any IPv4 private address excluding APIPA range
TIPAddress = (
tiaAny,
tiaIPv4,
tiaIPv6,
tiaIPv4Public,
tiaIPv4Private,
tiaIPv4Dhcp,
tiaIPv4DhcpPublic,
tiaIPv4DhcpPrivate);
/// detect IANA private IPv4 address space from its 32-bit raw value
// - i.e. 10.x.x.x, 172.16-31.x.x and 192.168.x.x addresses
function IsPublicIP(ip4: cardinal): boolean;
/// detect APIPA private IPv4 address space from its 32-bit raw value
// - Automatic Private IP Addressing (APIPA) is used by Windows clients to
// setup some IP in case of local DHCP failure
// - it covers the 169.254.0.1 - 169.254.254.255 range
// - see tiaIPv4Dhcp, tiaIPv4DhcpPublic and tiaIPv4DhcpPrivate filters
function IsApipaIP(ip4: cardinal): boolean;
/// detect IANA private IPv4 masks as 32-bit raw values
// - i.e. 10.x.x.x, 172.16-31.x.x and 192.168.x.x addresses into
// 255.0.0.0, 255.255.0.0, 255.255.255.0 or 255.255.255.255
function IP4Mask(ip4: cardinal): cardinal;
/// compute a broadcast address from a IPv4 current address and its known mask
// - e.g. ip4=172.16.144.160 and mask4=255.255.255.0 returns 172.16.144.255
function IP4Broadcast(ip4, mask4: cardinal): cardinal;
/// compute the prefix size of a IPv4 prefix from a 32-bit network mask
// - e.g. returns 8 for 255.0.0.0
function IP4Prefix(netmask4: cardinal): integer; overload;
/// compute the prefix size of a IPv4 prefix from a text network mask
// - e.g. IP4Prefix('255.255.255.0') returns 24
function IP4Prefix(const netmask4: RawUtf8): integer; overload;
/// reverse conversion of IP4Prefix() into a 32-bit network mask
// - e.g. IP4Netmask(24) returns 255.255.255.0
function IP4Netmask(prefix: integer): cardinal; overload;
/// reverse conversion of IP4Prefix() into a 32-bit network mask
function IP4Netmask(prefix: integer; out mask: cardinal): boolean; overload;
{$ifdef HASINLINE} inline; {$endif}
/// compute a subnet value from a 32-bit IP4 and its associated NetMask
// - e.g. ip4=192.168.0.16 and mask4=255.255.255.0 returns '192.168.0.0/24'
function IP4Subnet(ip4, netmask4: cardinal): shortstring; overload;
/// compute a subnet value from an IP4 and its associated NetMask
// - e.g. ip4='192.168.0.16' and mask4='255.255.255.0' returns '192.168.0.0/24'
function IP4Subnet(const ip4, netmask4: RawUtf8): RawUtf8; overload;
/// check if an IP4 match a sub-network
// - e.g. IP4Match('192.168.1.1', '192.168.1.0/24') = true
function IP4Match(const ip4, subnet: RawUtf8): boolean;
/// filter an IPv4 address to a given TIPAddress kind
// - return true if the supplied address does match the filter
// - by design, both 0.0.0.0 and 127.0.0.1 always return false
function IP4Filter(ip4: cardinal; filter: TIPAddress): boolean;
/// convert an IPv4 raw value into a ShortString text
// - won't use the Operating System network layer API so works on XP too
// - zero is returned as '0.0.0.0' and loopback as '127.0.0.1'
procedure IP4Short(ip4addr: PByteArray; var s: ShortString);
/// convert an IPv4 raw value into a ShortString text
function IP4ToShort(ip4addr: PByteArray): TShort16;
{$ifdef HASINLINE} inline; {$endif}
/// convert an IPv4 raw value into a RawUtf8 text
// - zero 0.0.0.0 address (i.e. bound to any host) is returned as ''
procedure IP4Text(ip4addr: PByteArray; var result: RawUtf8);
/// convert an IPv4 raw value into a RawUtf8 text
function IP4ToText(ip4addr: PByteArray): RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
/// convert an IPv6 raw value into a ShortString text
// - will shorten the address using the regular 0 removal scheme, e.g.
// 2001:00b8:0a0b:12f0:0000:0000:0000:0001 returns '2001:b8:a0b:12f0::1'
// - zero is returned as '::' and loopback as '::1'
// - does not support mapped IPv4 so never returns '::1.2.3.4' but '::102:304'
// - won't use the Operating System network layer API so is fast and consistent
procedure IP6Short(ip6addr: PByteArray; var s: ShortString);
/// convert an IPv6 raw value into a RawUtf8 text
// - zero '::' address (i.e. bound to any host) is returned as ''
// - loopback address is returned as its '127.0.0.1' IPv4 representation
// for consistency with our high-level HTTP/REST code
// - does not support mapped IPv4 so never returns '::1.2.3.4' but '::102:304'
procedure IP6Text(ip6addr: PByteArray; var result: RawUtf8);
/// convert a MAC address value into its standard RawUtf8 text representation
// - calls ToHumanHex(mac, 6), returning e.g. '12:50:b6:1e:c6:aa'
function MacToText(mac: PByteArray): RawUtf8;
{$ifdef HASINLINE} inline; {$endif}
/// convert a MAC address value from its standard hexadecimal text representation
// - returns e.g. '12:50:b6:1e:c6:aa' from '1250b61ec6aa' or '1250B61EC6AA'
function MacTextFromHex(const Hex: RawUtf8): RawUtf8;
/// convert a MAC address value into a RawUtf8 hexadecimal text with no ':'
// - returns e.g. '1250b61ec6aa'
function MacToHex(mac: PByteArray; maclen: PtrInt = 6): RawUtf8;
/// enumerate all IP addresses of the current computer
// - may be used to enumerate all adapters
// - no cache is used for this function - consider GetIPAddressesText instead
// - by design, 127.0.0.1 is excluded from the list
function GetIPAddresses(Kind: TIPAddress = tiaIPv4): TRawUtf8DynArray;
/// returns all IP addresses of the current computer as a single CSV text
// - may be used to enumerate all adapters
// - an internal cache of the result is refreshed every 32 seconds
function GetIPAddressesText(const Sep: RawUtf8 = ' ';
Kind: TIPAddress = tiaIPv4): RawUtf8;
/// check if Host is in 127.0.0.0/8 range - warning: Host should be not nil
function IsLocalHost(Host: PUtf8Char): boolean;
{$ifdef HASINLINE} inline; {$endif}
type
/// the network interface type, as stored in TMacAddress.Kind
// - we don't define all ARP models, but try to detect most basic types
TMacAddressKind = (
makUndefined,
makEthernet,
makWifi,
makTunnel,
makPpp,
makCellular,
makSoftware);
/// a set of network interface types
TMacAddressKinds = set of TMacAddressKind;
/// interface name/address pairs as returned by GetMacAddresses
// - associated IPv4 information is available on most systems
TMacAddress = record
/// short text description of this interface
// - contains e.g. 'eth0' on Linux
Name: RawUtf8;
/// user-friendly name for the adapter
// - e.g. on Windows: 'Local Area Connection 1.'
// - on Linux, returns /sys/class/net/eth0/ifalias content, i.e. the value
// fixed by "ip link set eth0 alias somename"
// - not available on Android or BSD
FriendlyName: RawUtf8;
/// name of the adapter with which these addresses are associated
// - unlike FriendlyName, it can't be renamed by the end user
// - e.g. on Windows: '{1C7CAE9E-3256-4784-8CA4-B721D3B5A00F}'
// - equals Name on POSIX
AdapterName: RawUtf8;
/// the hardware MAC address of this adapter
// - contains e.g. '12:50:b6:1e:c6:aa' from /sys/class/net/eth0/adddress
// - may equal '00:00:00:00:00:00' for a non-physical interface (makSoftware)
Address: RawUtf8;
/// the raw IPv4 address of this interface
// - not available on Android
IP: RawUtf8;
/// the raw IPv4 network mask of this interface
// - not available on Android
NetMask: RawUtf8;
/// the raw IPv4 broadcast address of this interface
Broadcast: RawUtf8;
/// the raw IPv4 gateway address of this interface
// - not available on Windows XP or BSD
Gateway: RawUtf8;
{$ifdef OSWINDOWS}
/// the raw IPv4 address(es) of the associated DNS server(s), as CSV
// - not available on POSIX (DNS are part of the routing, not interfaces)
Dns: RawUtf8;
/// the optional DNS suffix of this connection, e.g. 'ad.mycorp.com'
// - not available on POSIX (DNS are part of the routing, not interfaces)
DnsSuffix: RawUtf8;
/// the raw IPv4 binary address of the main associated DHCP server
// - not available on Windows XP or POSIX
Dhcp: RawUtf8;
{$endif OSWINDOWS}
/// the current adapter Maximum Transmission Unit size (MTU), in bytes
// - typically 1500 over an Ethernet network
// - not available on BSD
Mtu: cardinal;
/// the current link speed in Mbits per second (typically 100 or 1000)
// - not available on Windows XP or BSD
// - some interfaces (e.g. makWifi on Linux) may have a 0 value
Speed: cardinal;
/// the interface index, as internally used by the OS
// - may equal -1 for a non-physical interface (makSoftware)
IfIndex: integer;
/// the hardware model of this network interface
// - retrieved from ARP protocol hardware identifiers on Linux, and
// IfType field on Windows (seems accurate since Vista)
// - not available on BSD
Kind: TMacAddressKind;
end;
TMacAddressDynArray = array of TMacAddress;
/// enumerate all network MAC addresses and their associated IP information
// - an internal 65-seconds cache is used, with explicit MacIPAddressFlush
function GetMacAddresses(UpAndDown: boolean = false): TMacAddressDynArray;
/// enumerate all MAC addresses of the current computer as 'name1=addr1 name2=addr2'
// - an internal 65-seconds cache is used, with explicit MacIPAddressFlush
function GetMacAddressesText(WithoutName: boolean = true;
UpAndDown: boolean = false): RawUtf8;
/// flush the GetIPAddressesText/GetMacAddresses internal caches
// - may be called to force detection after HW configuration change (e.g. when
// wifi has been turned on)
procedure MacIPAddressFlush;
{$ifdef OSWINDOWS}
/// remotely get the MAC address of a computer, from its IP Address
// - only works under Windows, which features a SendARP() API in user space:
// on POSIX, implementing ARP sadly requires root rights
// - return the MAC address as a 12 hexa chars ('0050C204C80A' e.g.)
function GetRemoteMacAddress(const IP: RawUtf8): RawUtf8;
{$endif OSWINDOWS}
/// get the local MAC address used to reach a computer, from its IP or Host name
// - return the local interface as a TMacAddress, with all its available info
// - under Windows, will call the GetBestInterface() API to retrieve a IfIndex
// - on POSIX, will call GetLocalIpAddress() to retrive a local IP
// - always eventually makes a lookup to the GetMacAddresses() list per IfIndex
// (Windows) or IP (POSIX)
function GetLocalMacAddress(const Remote: RawUtf8; var Mac: TMacAddress): boolean;
/// get the local IP address used to reach a computer, from its IP Address
// - will create a SOCK_DGRAM socket over the supplied IP, and check
// the local socket address created
function GetLocalIpAddress(const Remote: RawUtf8): RawUtf8;
/// retrieve all DNS (Domain Name Servers) addresses known by the Operating System
// - on POSIX, return "nameserver" from /etc/resolv.conf unless usePosixEnv is set
// - on Windows, calls GetNetworkParams API from iphlpapi
// - an internal cache of the result will be refreshed every 8 seconds
function GetDnsAddresses(usePosixEnv: boolean = false): TRawUtf8DynArray;
/// append a custom resolver address for GetDnsAddresses() in addition to the OS
procedure RegisterDnsAddress(const DnsResolver: RawUtf8);
var
/// if manually set, GetDomainNames() will return this value
// - e.g. 'ad.mycompany.com'
ForcedDomainName: RawUtf8;
/// retrieve the AD Domain Name addresses known by the Operating System
// - on POSIX, return all "search" from /etc/resolv.conf unless usePosixEnv is set
// - on Windows, calls GetNetworkParams API from iphlpapi to retrieve a single item
// - no cache is used for this function
// - you can force for a given value using ForcedDomainName, e.g. if the
// machine is not actually registered for / part of the domain, but has access
// to the domain controller
function GetDomainNames(usePosixEnv: boolean = false): TRawUtf8DynArray;
/// resolve a host name from the OS hosts file content
// - i.e. use a cache of /etc/hosts or c:\windows\system32\drivers\etc\hosts
// - returns true and the IPv4 address of the stored host found
// - if the file is modified on disk, the internal cache will be flushed
function GetKnownHost(const HostName: RawUtf8; out ip4: cardinal): boolean;
/// append a custom host/ipv4 pair in addition to the OS hosts file
// - to be appended to GetKnownHost() internal cache
procedure RegisterKnownHost(const HostName, Ip4: RawUtf8);
{ ******************** TLS / HTTPS Encryption Abstract Layer }
type
/// pointer to TLS Options and Information for a given TCrtSocket connection
PNetTlsContext = ^TNetTlsContext;
/// callback raised by INetTls.AfterConnection to return a private key
// password - typically prompting the user for it
// - TLS is an opaque structure, typically an OpenSSL PSSL_CTX pointer
TOnNetTlsGetPassword = function(Socket: TNetSocket;
Context: PNetTlsContext; TLS: pointer): RawUtf8 of object;
/// callback raised by INetTls.AfterConnection to validate a peer
// - at this point, Context.CipherName is set, but PeerInfo, PeerIssuer and
// PeerSubject are not - it is up to the event to compute the PeerInfo value
// - TLS is an opaque structure, typically an OpenSSL PSSL pointer, so you
// could use e.g. PSSL(TLS).PeerCertificate or PSSL(TLS).PeerCertificates array
TOnNetTlsPeerValidate = procedure(Socket: TNetSocket;
Context: PNetTlsContext; TLS: pointer) of object;
/// callback raised by INetTls.AfterConnection after validating a peer
// - called after standard peer validation - ignored by TOnNetTlsPeerValidate
// - Context.CipherName, LastError PeerIssuer and PeerSubject are set
// - TLS and Peer are opaque structures, typically OpenSSL PSSL and PX509
TOnNetTlsAfterPeerValidate = procedure(Socket: TNetSocket;
Context: PNetTlsContext; TLS, Peer: pointer) of object;
/// callback raised by INetTls.AfterConnection for each peer verification
// - wasok=true if the TLS library did validate the incoming certificate
// - should process the supplied peer information, and return true to continue
// and accept the connection, or false to abort the connection
// - Context.PeerIssuer and PeerSubject have been properly populated from Peer
// - TLS and Peer are opaque structures, typically OpenSSL PSSL and PX509 pointers
TOnNetTlsEachPeerVerify = function(Socket: TNetSocket; Context: PNetTlsContext;
wasok: boolean; TLS, Peer: pointer): boolean of object;
/// callback raised by INetTls.AfterAccept for SNI resolution
// - should check the ServerName and return the proper certificate context,
// typically one OpenSSL PSSL_CTX instance
// - if the ServerName has no match, and the default certificate is good
// enough, should return nil
// - on any error, should raise an exception
// - TLS is an opaque structure, typically OpenSSL PSSL
TOnNetTlsAcceptServerName = function(Context: PNetTlsContext; TLS: pointer;
const ServerName: RawUtf8): pointer of object;
/// TLS Options and Information for a given TCrtSocket/INetTls connection
// - currently only properly implemented by mormot.lib.openssl11 - SChannel
// on Windows only recognizes IgnoreCertificateErrors and sets CipherName
// - typical usage is the following:
// $ with THttpClientSocket.Create do
// $ try
// $ TLS.WithPeerInfo := true;
// $ TLS.IgnoreCertificateErrors := true;
// $ TLS.CipherList := 'ECDHE-RSA-AES256-GCM-SHA384';
// $ ConnectUri('https://synopse.info');
// $ ConsoleWrite(TLS.PeerInfo);
// $ ConsoleWrite(TLS.CipherName);
// $ ConsoleWrite([Get('/forum/', 1000), ' len=', ContentLength]);
// $ ConsoleWrite(Get('/fossil/wiki/Synopse+OpenSource', 1000));
// $ finally
// $ Free;
// $ end;
// - for passing a PNetTlsContext, use InitNetTlsContext for initialization
TNetTlsContext = record
/// output: set by ConnectUri/OpenBind method once TLS is established
Enabled: boolean;
/// input: let HTTPS be less paranoid about TLS certificates
// - on client: will avoid checking the server certificate, so will
// allow to connect and encrypt e.g. with secTLSSelfSigned servers
// - on OpenSSL server, should be true if no mutual authentication is done,
// i.e. if OnPeerValidate/OnEachPeerVerify callbacks are not set
IgnoreCertificateErrors: boolean;
/// input: if PeerInfo field should be retrieved once connected
WithPeerInfo: boolean;
/// input: if deprecated TLS 1.0 or TLS 1.1 are allowed
// - default is TLS 1.2+ only, and deprecated SSL 2/3 are always disabled
AllowDeprecatedTls: boolean;
/// input: enable two-way TLS for the server
// - to be used with OnEachPeerVerify callback
// - on OpenSSL client or server, set SSL_VERIFY_FAIL_IF_NO_PEER_CERT mode
// - not used on SChannel
ClientCertificateAuthentication: boolean;
/// input: if two-way TLS client should be verified only once on the server
// - to be used with OnEachPeerVerify callback
// - on OpenSSL client or server, set SSL_VERIFY_CLIENT_ONCE mode
// - not used on SChannel
ClientVerifyOnce: boolean;
/// input: allow legacy insecure renegotiation for unpatched/unsafe servers
// - on OpenSSL client, set the SSL_OP_LEGACY_SERVER_CONNECT option
// - not used on SChannel
// - clients that are willing to connect to servers that don't implement RFC
// 5746 secure renegotiation are subject to attacks such as CVE-2009-3555
ClientAllowUnsafeRenegotation: boolean;
/// input: PEM/PFX file name containing a certificate to be loaded
// - (Delphi) warning: encoded as UTF-8 not UnicodeString/TFileName
// - on OpenSSL client or server, calls SSL_CTX_use_certificate_file() API
// - not used on SChannel client
// - on SChannel server, expects a .pfx / PKCS#12 file format including
// the certificate and the private key, e.g. generated from
// ICryptCert.SaveToFile(FileName, cccCertWithPrivateKey, ', ccfBinary) or
// openssl pkcs12 -inkey privkey.pem -in cert.pem -export -out mycert.pfx
CertificateFile: RawUtf8;
/// input: opaque pointer containing a certificate to be used
// - on OpenSSL client or server, calls SSL_CTX_use_certificate() API
// expecting the pointer to be of PX509 type
// - not used on SChannel client
CertificateRaw: pointer;
/// input: PEM file name containing a private key to be loaded
// - (Delphi) warning: encoded as UTF-8 not UnicodeString/TFileName
// - on OpenSSL client or server, calls SSL_CTX_use_PrivateKey_file() API
// - not used on SChannel
PrivateKeyFile: RawUtf8;
/// input: optional password to load the PrivateKey file
// - see also OnPrivatePassword callback
// - on OpenSSL client or server, calls
// SSL_CTX_set_default_passwd_cb_userdata() API
// - not used on SChannel
PrivatePassword: RawUtf8;
/// input: opaque pointer containing a private key to be used
// - on OpenSSL client or server, calls SSL_CTX_use_PrivateKey() API
// expecting the pointer to be of PEVP_PKEY type
// - not used on SChannel
PrivateKeyRaw: pointer;
/// input: file containing a specific set of CA certificates chain
// - e.g. entrust_2048_ca.cer from https://web.entrust.com
// - (Delphi) warning: encoded as UTF-8 not UnicodeString/TFileName
// - on OpenSSL, calls the SSL_CTX_load_verify_locations() API
// - not used on SChannel
CACertificatesFile: RawUtf8;
/// input: preferred Cipher List
// - not used on SChannel
CipherList: RawUtf8;
/// input: a CSV list of host names to be validated
// - e.g. 'smtp.example.com,example.com'
// - not used on SChannel
HostNamesCsv: RawUtf8;
/// output: the cipher description, as used for the current connection
// - text format depends on the used TLS library e.g. on OpenSSL may be e.g.
// 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD'
// or 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P256 TLSv1.2' with SChannel
// (or less complete 'ECDHE256-AES128-SHA256 TLSv1.2' information on XP)
CipherName: RawUtf8;
/// output: the connected Peer issuer name
// - e.g. '/C=US/O=Let''s Encrypt/CN=R3'
// - populated on both SChannel and OpenSSL
PeerIssuer: RawUtf8;
/// output: the connected Peer subject name
// - e.g. 'CN=synopse.info'
// - populated on both SChannel and OpenSSL
PeerSubject: RawUtf8;
/// output: detailed information about the connected Peer
// - stored in the native format of the TLS library, e.g. X509_print()
// or ToText(TWinCertInfo)
// - only populated if WithPeerInfo was set to true, or an error occurred
PeerInfo: RawUtf8;
/// output: low-level details about the last error at TLS level
// - typically one X509_V_ERR_* integer constant
LastError: RawUtf8;
/// called by INetTls.AfterConnection to fully customize peer validation
// - not used on SChannel
OnPeerValidate: TOnNetTlsPeerValidate;
/// called by INetTls.AfterConnection for each peer validation
// - allow e.g. to verify CN or DNSName fields of each peer certificate
// - see also ClientCertificateAuthentication and ClientVerifyOnce options
// - not used on SChannel
OnEachPeerVerify: TOnNetTlsEachPeerVerify;
/// called by INetTls.AfterConnection after standard peer validation
// - allow e.g. to verify CN or DNSName fields of the peer certificate
// - not used on SChannel
OnAfterPeerValidate: TOnNetTlsAfterPeerValidate;
/// called by INetTls.AfterConnection to retrieve a private password
// - not used on SChannel
OnPrivatePassword: TOnNetTlsGetPassword;
/// called by INetTls.AfterAccept to set a server/host-specific certificate
// - not used on SChannel
OnAcceptServerName: TOnNetTlsAcceptServerName;
/// opaque pointer used by INetTls.AfterBind/AfterAccept to propagate the
// bound server certificate context into each accepted connection
// - so that certificates are decoded only once in AfterBind
// - is typically a PSSL_CTX on OpenSSL, or a PCCERT_CONTEXT on SChannel
AcceptCert: pointer;
end;
/// abstract definition of the TLS encrypted layer
// - is implemented e.g. by the SChannel API on Windows by this unit, or
// OpenSSL on POSIX if you include mormot.lib.openssl11 to your project
// - on Windows, you can define USE_OPENSSL and FORCE_OPENSSL conditionals
// in YOUR project options to switch to OpenSSL instead of SChannel
INetTls = interface
/// method called once to attach the socket from the client side
// - should make the proper client-side TLS handshake and create a session
// - should raise an exception on error
procedure AfterConnection(Socket: TNetSocket; var Context: TNetTlsContext;
const ServerAddress: RawUtf8);
/// method called once the socket has been bound on server side
// - will set Context.AcceptCert with reusable server certificates info
procedure AfterBind(var Context: TNetTlsContext);
/// method called for each new connection accepted on server side
// - should make the proper server-side TLS handshake and create a session
// - should raise an exception on error
// - BoundContext is the associated server instance with proper AcceptCert
// as filled by AfterBind()
procedure AfterAccept(Socket: TNetSocket; const BoundContext: TNetTlsContext;
LastError, CipherName: PRawUtf8);
/// retrieve the textual name of the cipher used following AfterAccept()
function GetCipherName: RawUtf8;
/// return the low-level TLS instance used, depending on the engine
// - typically a PSSL on OpenSSL, so you can use e.g. PSSL().PeerCertificate,
// or a PCtxtHandle on SChannel
function GetRawTls: pointer;
/// receive some data from the TLS layer
function Receive(Buffer: pointer; var Length: integer): TNetResult;
/// check if there are some input data within the TLS buffers
// - may be the case even with no data any more at TCP/socket level
// - returns -1 if there is no TLS connection opened
// - returns the number of bytes in the internal buffer
// - returns 0 if the internal buffer is void - but there may be some
// data ready to be unciphered at socket level
function ReceivePending: integer;
/// send some data from the TLS layer
function Send(Buffer: pointer; var Length: integer): TNetResult;
end;
/// event called by HTTPS server to publish HTTP-01 challenges on port 80
// - Let's Encrypt typical uri is '/.well-known/acme-challenge/<TOKEN>'
// - the server should send back the returned content as response with
// application/octet-stream (i.e. BINARY_CONTENT_TYPE)
TOnNetTlsAcceptChallenge = function(const domain, uri: RawUtf8;
var content: RawUtf8): boolean;
/// initialize a stack-allocated TNetTlsContext instance
procedure InitNetTlsContext(var TLS: TNetTlsContext; Server: boolean = false;
const CertificateFile: TFileName = ''; const PrivateKeyFile: TFileName = '';
const PrivateKeyPassword: RawUtf8 = ''; const CACertificatesFile: TFileName = '');
/// purge all output fields for a TNetTlsContext instance for proper reuse
procedure ResetNetTlsContext(var TLS: TNetTlsContext);
/// compare the main fields of twoTNetTlsContext instances
// - won't compare the callbacks
function SameNetTlsContext(const tls1, tls2: TNetTlsContext): boolean;
var
/// global factory for a new TLS encrypted layer for TCrtSocket
// - on Windows, this unit will set a factory using the system SChannel API
// - could also be overriden e.g. by the mormot.lib.openssl11.pas unit
NewNetTls: function: INetTls;
/// global callback set to TNetTlsContext.AfterAccept from InitNetTlsContext()
// - defined e.g. by mormot.net.acme.pas unit to support Let's Encrypt
// - any HTTPS server should also publish a HTTP server on port 80 to serve
// HTTP-01 challenges via the OnNetTlsAcceptChallenge callback