-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
mormot.net.sock.posix.inc
1562 lines (1401 loc) · 43.9 KB
/
mormot.net.sock.posix.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
The POSIX Sockets API is called via the libc, since SOCKDIRECTSYSCALL does not
make any difference in terms of stability or performance.
}
uses
baseunix,
termio,
sockets,
{$ifdef OSLINUXANDROID}
linux, // for epoll
{$endif OSLINUXANDROID}
initc; // link clib='c' for our socket purpose
{$ifdef OSLINUX}
{$define HASACCEPT4} // use Linux-specific accept4() enhanced API call
// define OLDLIBC conditional to disable this feature and fallback to accept()
{$endif OSLINUX}
{$ifdef OSBSDDARWIN}
{$define USEPOLL} // epoll API is Linux-specific -> force use poll() on BSD
{$endif OSBSDDARWIN}
{.$define USEPOLL} // to validate poll API on Linux
{ ******** Sockets Type Definitions }
const
host_file = '/etc/hosts';
NI_MAXHOST = 1025;
NI_MAXSERV = 32;
WSATRY_AGAIN = ESysEAGAIN;
WSAEADDRNOTAVAIL = ESysEADDRNOTAVAIL;
WSAECONNABORTED = ESysECONNABORTED;
WSAECONNRESET = ESysECONNRESET;
WSAETIMEDOUT = ESysETIMEDOUT;
WSAEINVAL = ESysEINVAL;
WSAEMFILE = ESysEMFILE;
WSAECONNREFUSED = ESysECONNREFUSED;
WSAEINPROGRESS = ESysEINPROGRESS;
{$ifdef OSLINUX}
SOCK_NONBLOCK = O_NONBLOCK; // see net.h
{$endif OSLINUX}
{$ifdef OSLINUXANDROID}
SO_REUSEPORT = 15; // available since Kernel 3.9 - not defined by FPC yet
{$endif OSLINUXANDROID}
{$ifdef OSFREEBSD}
NI_NUMERICHOST = 2;
NI_NUMERICSERV = 8;
{$else}
NI_NUMERICHOST = 1;
NI_NUMERICSERV = 2;
{$endif OSFREEBSD}
FIONREAD = termio.FIONREAD;
FIONBIO = termio.FIONBIO;
{$ifdef OSBSDDARWIN}
{$ifndef OSOPENBSD}
{$ifdef OSDARWIN}
SO_NOSIGPIPE = $1022;
{$else}
SO_NOSIGPIPE = $800;
{$endif OSDARWIN}
{$endif OSOPENBSD}
{$ifndef OSOPENBSD}
// Works under MAC OS X and FreeBSD, but is undocumented, so FPC doesn't include it
MSG_NOSIGNAL = $20000; // Do not generate SIGPIPE.
{$else}
MSG_NOSIGNAL = $400;
{$endif OSOPENBSD}
{$else}
{$ifdef SUNOS}
MSG_NOSIGNAL = $20000; // Do not generate SIGPIPE.
{$else}
MSG_NOSIGNAL = sockets.MSG_NOSIGNAL; // Do not generate SIGPIPE
{$endif SUNOS}
{$endif OSBSDDARWIN}
_ST: array[TNetLayer] of integer = (
SOCK_STREAM,
SOCK_DGRAM,
SOCK_STREAM);
_IP: array[TNetLayer] of integer = (
IPPROTO_TCP,
IPPROTO_UDP,
0);
_SF: array[TNetFamily] of integer = (
0,
AF_INET,
AF_INET6,
AF_UNIX);
{$packrecords C}
type
/// a socket is always cint = 32-bit integer sized on POSIX
// - we extend it to PtrInt for our TNetSocketWrap cast
TSocket = PtrInt;
PSockAddrIn6 = ^sockaddr_in6;
THostEnt = record
h_name: PAnsiChar;
h_aliases: PPAnsiChar;
h_addrtype: integer;
h_length: socklen_t;
case integer of
0: (
h_addr_list: PPAnsiChar);
1: (
h_addr: ^pin_addr);
2: (
h_addr6: ^pin6_addr);
end;
PHostEnt = ^THostEnt;
const
// poll() flag when there is data to read
POLLIN = $0001;
// poll() flag when there is urgent data to read
POLLPRI = $0002;
// poll() flag when writing now will not block
POLLOUT = $0004;
// poll() flag error condition (always implicitly polled for)
POLLERR = $0008;
// poll() flag hung up (always implicitly polled for)
POLLHUP = $0010;
// poll() flag invalid polling request (always implicitly polled for)
POLLNVAL = $0020;
// poll() flag when normal data may be read
POLLRDNORM = $0040;
// poll() flag when priority data may be read
POLLRDBAND = $0080;
// poll() flag when writing now will not block
POLLWRNORM = $0100;
// poll() flag when priority data may be written
POLLWRBAND = $0200;
// poll() flag extension for Linux
POLLMSG = $0400;
type
/// polling request data structure for poll()
TPollFD = record
/// file descriptor to poll
fd: integer;
/// types of events poller cares about
// - mainly POLLIN and/or POLLOUT
events: Smallint;
/// types of events that actually occurred
// - caller could just reset revents := 0 to reuse the structure
revents: Smallint;
end;
PPollFD = ^TPollFD;
{ ******** Sockets API calls via the libc }
// note: POSIX sockets are fd = C int = 32-bit integer, not our TSocket = PtrInt
// so we use plain integer in the Sockets API calls below
{$ifdef OLDLIBC}
{$undef HASACCEPT4}
{$endif OLDLIBC}
{.$define SOCKDIRECTSYSCALL} // no noticeable performance or stability change
{$ifdef SOCKDIRECTSYSCALL}
function gethostbyname(name: PAnsiChar): PHostEnt; cdecl;
external clib name 'gethostbyname' + LIBC_SUFFIX;
// no syscall available from FPC -> use libc wrapper anyway
function socket(af, struct, protocol: integer): integer; inline;
begin
result := fpsocket(af, struct, protocol);
end;
function setsockopt(s: integer; level, optname: integer;
optval: pointer; optlen: integer): integer; inline;
begin
result := fpsetsockopt(s, level, optname, optval, optlen);
end;
function getsockopt(s: integer; level, optname: integer;
optval: pointer; optlen: pSocklen): integer; inline;
begin
result := fpgetsockopt(s, level, optname, optval, optlen);
end;
function ioctlsocket(s: integer; cmd: cardinal; arg: PCardinal): integer; inline;
begin
result := fpioctl(s, cmd, arg);
end;
function shutdown(s: integer; how: integer): integer; inline;
begin
result := fpshutdown(s, how);
end;
function closesocket(s: integer): integer; inline;
begin
result := fpclose(s);
end;
function getnameinfo(addr: PSockAddr; namelen: TSockLen; host: PAnsiChar;
hostlen: TSockLen; serv: PAnsiChar; servlen: TSockLen; flags: integer): integer; cdecl;
external clib name 'getnameinfo' + LIBC_SUFFIX;
// no syscall available from FPC
function bind(s: integer; addr: PSockAddr; namelen: TSockLen): integer; inline;
begin
result := fpbind(s, addr, namelen);
end;
function getsockname(s: integer; name: PSockAddr; var namelen: TSockLen): integer; inline;
begin
result := fpgetsockname(s, name, @namelen);
end;
function listen(s: integer; backlog: integer): integer; inline;
begin
result := fplisten(s, backlog);
end;
function accept(s: integer; addr: PSockAddr; var addrlen: TSockLen): integer; inline;
begin
result := fpaccept(s, addr, @addrlen);
end;
{$ifdef HASACCEPT4}
function accept4(s: integer; addr: PSockAddr; var addrlen: TSockLen; flags: integer): integer; cdecl;
external clib name 'accept4';
// no syscall available from FPC
{$endif HASACCEPT4}
function connect(s: integer; name: PSockAddr; namelen: TSockLen): integer; inline;
begin
result := fpconnect(s, name, namelen);
end;
function select(nfds: integer; readfds, writefds, exceptfds: PFDSet;
timeout: PTimeVal): integer; inline;
begin
result := fpselect(nfds, readfds, writefds, exceptfds, timeout);
end;
function recv(s: integer; Buf: pointer; len: size_t; flags: integer): ssize_t; inline;
begin
result := fprecv(s, Buf, len, flags);
end;
function recvfrom(s: integer; Buf: pointer; len: size_t; flags: integer;
from: PSockAddr; fromlen: pSocklen): ssize_t; inline;
begin
result := fprecvfrom(s, Buf, len, flags, from, fromlen);
end;
function send(s: integer; Buf: pointer; len: size_t; flags: integer): ssize_t; inline;
begin
result := fpsend(s, Buf, len, flags);
end;
function sendto(s: integer; Buf: pointer; len: size_t; flags: integer;
addrto: PSockAddr; tolen: integer): ssize_t; inline;
begin
result := fpsendto(s, Buf, len, flags, addrto, tolen);
end;
function getpeername(s: integer; name: PSockAddr; var namelen: TSockLen): integer; inline;
begin
result := fpgetpeername(s, name, @namelen);
end;
{$else}
// we use the libc rather than fp*() low-level functions because the libc
// may be implemented via vDSO and avoid a syscall, and some high-level API
// like gethostbyname() or accept4() are not available as fp* syscalls
function gethostbyname(name: PAnsiChar): PHostEnt; cdecl;
external clib name 'gethostbyname' + LIBC_SUFFIX;
function socket(af, struct, protocol: integer): integer; cdecl;
external clib name 'socket' + LIBC_SUFFIX;
function setsockopt(s: integer; level, optname: integer;
optval: pointer; optlen: integer): integer; cdecl;
external clib name 'setsockopt' + LIBC_SUFFIX;
function getsockopt(s: integer; level, optname: integer;
optval: pointer; optlen: PInteger): integer; cdecl;
external clib name 'getsockopt' + LIBC_SUFFIX;
function ioctlsocket(s: integer; cmd: cardinal): integer; cdecl; varargs;
external clib name 'ioctl' + LIBC_SUFFIX;
function shutdown(s: integer; how: integer): integer; cdecl;
external clib name 'shutdown' + LIBC_SUFFIX;
function closesocket(s: integer): integer; cdecl;
external clib name 'close' + LIBC_SUFFIX;
function getnameinfo(addr: PSockAddr; namelen: TSockLen; host: PAnsiChar;
hostlen: TSockLen; serv: PAnsiChar; servlen: TSockLen; flags: integer): integer; cdecl;
external clib name 'getnameinfo' + LIBC_SUFFIX;
function bind(s: integer; addr: PSockAddr; namelen: TSockLen): integer; cdecl;
external clib name 'bind' + LIBC_SUFFIX;
function getsockname(s: integer; name: PSockAddr; var namelen: TSockLen): integer; cdecl;
external clib name 'getsockname' + LIBC_SUFFIX;
function listen(s: integer; backlog: integer): integer; cdecl;
external clib name 'listen' + LIBC_SUFFIX;
function accept(s: integer; addr: PSockAddr; var addrlen: TSockLen): integer; cdecl;
external clib name 'accept' + LIBC_SUFFIX;
{$undef ACCEPT4_SYSCALL}
{$ifdef HASACCEPT4}
function accept4(s: integer; addr: PSockAddr; var addrlen: TSockLen; flags: integer): integer;
cdecl; external clib name 'accept4' // no LIBC_SUFFIX: libc 2.10 is required
{$ifdef OSLINUXINTEL} + '@GLIBC_2.10' {$endif} ;
{$endif HASACCEPT4}
function connect(s: integer; name: PSockAddr; namelen: TSockLen): integer; cdecl;
external clib name 'connect' + LIBC_SUFFIX;
function select(nfds: integer; readfds, writefds, exceptfds: PFDSet;
timeout: PTimeVal): integer; cdecl;
external clib name 'select' + LIBC_SUFFIX;
function recv(s: integer; Buf: pointer; len: size_t; flags: integer): ssize_t; cdecl;
external clib name 'recv' + LIBC_SUFFIX;
function recvfrom(s: integer; Buf: pointer; len: size_t; flags: integer;
from: PSockAddr; fromlen: Pinteger): ssize_t; cdecl;
external clib name 'recvfrom' + LIBC_SUFFIX;
function send(s: integer; Buf: pointer; len: size_t; flags: integer): ssize_t; cdecl;
external clib name 'send' + LIBC_SUFFIX;
function sendto(s: integer; Buf: pointer; len: size_t; flags: integer;
addrto: PSockAddr; tolen: integer): ssize_t; cdecl;
external clib name 'sendto' + LIBC_SUFFIX;
function getpeername(s: integer; name: PSockAddr; var namelen: TSockLen): integer; cdecl;
external clib name 'getpeername' + LIBC_SUFFIX;
{$endif SOCKDIRECTSYSCALL}
{$ifdef OSDARWIN2}
// circumvent linking issue on Mac OSX
function poll(fds: PPollFD; nfds, timeout: integer): integer; inline;
begin
result := fppoll(pointer(fds), nfds, timeout);
end;
{$else}
function poll(fds: PPollFD; nfds, timeout: integer): integer; cdecl;
external clib name 'poll' + LIBC_SUFFIX;
{$endif OSDARWIN}
function RawSocketErrNo: integer;
begin
result := cerrno; // thread-locale variable from libc
end;
{$ifdef HASACCEPT4}
var
Accept4Unsupported: boolean;
{$endif HASACCEPT4}
function doaccept(s: TSocket; addr: PSockAddr; var async: boolean): integer;
var
len: TSockLen;
begin
len := SOCKADDR_SIZE;
{$ifdef HASACCEPT4}
if async and
not Accept4Unsupported then
begin
// see https://github.com/eudev-project/eudev/issues/7#issuecomment-10502344
result := accept4(s, addr, len, SOCK_NONBLOCK);
if (result < 0) and
((cerrno = ESysENOSYS) or
(cerrno = ESysEOPNOTSUPP)) then
begin
Accept4Unsupported := true; // will fallback from now on on old systems
len := SOCKADDR_SIZE;
result := accept(s, addr, len);
end
else
async := false; // no need to call MakeAsync
end
else
{$endif HASACCEPT4}
result := accept(s, addr, len);
end;
{ ******** TNetSocket Cross-Platform Wrapper }
{ TNetAddr }
var
_gethostbynamesafe: TOSLightLock;
// gethostbyname() result is NOT thread-safe: we need to protect its calls;
// since this may take some time, we use a pthread mutex, not a TLightLock
function TNetAddr.SetFrom(const address, addrport: RawUtf8;
layer: TNetLayer): TNetResult;
var
h: PHostEnt;
addr4: sockaddr absolute Addr;
begin
FillCharFast(Addr, SizeOf(Addr), 0);
result := nrNotFound;
if address = '' then
exit;
// handle domain socket name
if layer = nlUnix then
begin
if length(address) >= SizeOf(psockaddr_un(@Addr)^.sun_path) then
// avoid buffer overflow or truncated socket name
result := nrFatalError
else
// socket file name is just copied to the address struct
with psockaddr_un(@Addr)^ do
begin
sun_family := AF_UNIX;
MoveFast(pointer(address)^, sun_path, length(address));
result := nrOK;
end;
exit;
end;
// check supplied IP port
addr4.sin_port := bswap16(GetCardinal(pointer(addrport)));
if (addr4.sin_port = 0) and
(addrport <> '0') then // explicit '0' to get ephemeral port
exit;
// check most simple IPv4 resolution (maybe using mormot.net.dns)
result := nrOk;
if SetFromIP4(address, false) then
exit;
// use OS API (getaddrinfo is more recent, but addrinfo is not cross-platform)
_gethostbynamesafe.Lock;
try
h := gethostbyname(pointer(address));
if h = nil then
result := nrNotFound
else
begin
addr4.sin_family := h^.h_addrtype;
case h^.h_addrtype of
AF_INET:
addr4.sin_addr := h^.h_addr^^;
AF_INET6:
psockaddr6(@Addr)^.sin6_addr := h^.h_addr6^^;
else
result := nrNotImplemented;
end;
end;
finally
_gethostbynamesafe.UnLock;
end;
end;
{ TNetSocketWrap }
procedure SetTimeVal(ms: PtrUInt; out tv: TTimeVal);
var
d: PtrUInt;
begin
if ms = 0 then
begin
tv.tv_sec := 0;
tv.tv_usec := 0;
end
else
begin
d := ms div 1000;
tv.tv_sec := d;
tv.tv_usec := (ms - (d * 1000)) * 1000;
end;
end;
procedure TNetSocketWrap.ReusePort;
var
v: integer;
begin
// see https://lwn.net/Articles/542629 for Linux (available since Kernel 3.9)
v := ord(true);
if @self <> nil then
setsockopt(TSocket(@self), SOL_SOCKET, SO_REUSEPORT, @v, SizeOf(v));
// don't call SetOpt() which raise ENetSock on old kernel without SO_REUSEPORT
end;
procedure TNetSocketWrap.SetSendTimeout(ms: integer);
var
tv: TTimeVal; // POSIX uses a timeval (not Windows)
begin
SetTimeVal(ms, tv);
SetOpt(SOL_SOCKET, SO_SNDTIMEO, @tv, SizeOf(tv));
end;
procedure TNetSocketWrap.SetReceiveTimeout(ms: integer);
var
tv: TTimeVal;
begin
SetTimeVal(ms, tv);
SetOpt(SOL_SOCKET, SO_RCVTIMEO, @tv, SizeOf(tv));
end;
procedure TNetSocketWrap.SetReuseAddrPort;
var
v: integer;
begin
v := ord(true);
{$ifdef OSBSDDARWIN}
SetOpt(SOL_SOCKET, SO_REUSEPORT, @v, SizeOf(v));
{$ifndef OSOPENBSD}
SetOpt(SOL_SOCKET, SO_NOSIGPIPE, @v, SizeOf(v));
{$endif OSOPENBSD}
{$else}
SetOpt(SOL_SOCKET, SO_REUSEADDR, @v, SizeOf(v));
{$endif OSBSDDARWIN}
end;
procedure TNetSocketWrap.SetLinger(linger: integer);
var
v: TLinger;
begin
v.l_linger := linger;
v.l_onoff := ord(linger >= 0);
SetOpt(SOL_SOCKET, SO_LINGER, @v, SizeOf(v));
if linger > 0 then
SetReuseAddrPort;
end;
procedure TNetSocketWrap.SetCork(cork: boolean);
var
v: integer;
begin
v := ord(cork);
{$ifdef OSLINUXANDROID}
SetOpt(IPPROTO_TCP, TCP_CORK, @v, SizeOf(v));
{$else}
{$ifdef OSBSDDARWIN}
SetOpt(IPPROTO_TCP, TCP_NOPUSH, @v, SizeOf(v));
{$endif OSBSDDARWIN}
{$endif OSLINUXANDROID}
end;
{$ifdef OSLINUXANDROID}
procedure TNetSocketWrap.SetLowPriority;
var
v: integer;
begin
v := 0; // lowest priority
SetOpt(SOL_SOCKET, SO_PRIORITY, @v, SizeOf(v));
end;
{$else}
procedure TNetSocketWrap.SetLowPriority;
begin
end;
{$endif OSLINUXANDROID}
function TNetSocketWrap.HasLowPriority: boolean;
begin
result := false; // not applicable on POSIX
end;
function TNetSocketWrap.WaitFor(ms: integer; scope: TNetEvents;
loerr: system.PInteger): TNetEvents;
var
res: integer;
p: TPollFD; // select() limits p.fd<FD_SETSIZE=1024 on POSIX -> use poll()
// https://moythreads.com/wordpress/2009/12/22/select-system-call-limitation
begin
if loerr <> nil then
loerr^ := 0;
result := [neError];
if @self = nil then
exit;
p.fd := TSocket(@self);
p.events := 0;
if neRead in scope then
p.events := POLLIN or POLLPRI;
if neWrite in scope then
p.events := p.events or POLLOUT;
// POLLERR and POLLHUP are ignored in p.events: implicit [neError]
p.revents := 0;
res := poll(@p, 1, ms);
if res < 0 then
begin
res := RawSocketErrNo;
if loerr <> nil then
loerr^ := res;
if res = ESysEAGAIN then
// timeout, not a true error
result := [];
exit;
end;
result := [];
if p.revents and (POLLIN or POLLPRI) <> 0 then
include(result, neRead);
if p.revents and POLLOUT <> 0 then
include(result, neWrite);
if p.revents and POLLERR <> 0 then
include(result, neError);
if p.revents and POLLHUP <> 0 then
include(result, neClosed); // may return neClosed + neRead e.g. on HTTP/1.0
end;
{ ******************** Mac and IP Addresses Support }
const
IFF_UP = $1;
IFF_BROADCAST = $2;
IFF_LOOPBACK = $8;
{$ifdef OSBSDDARWIN}
// https://github.com/apple/darwin-xnu/blob/main/bsd/net/if_types.h
IFT_ETHER = $06;
IFT_PPP = $17;
IFT_CELLULAR = $ff;
{$else}
// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/if_arp.h
ARPHRD_ETHER = 1;
ARPHRD_PPP = 512;
ARPHRD_TUNNEL = 768;
ARPHRD_TUNNEL6 = 769;
ARPHRD_IEEE80211 = 801;
{$endif OSBSDDARWIN}
{$ifndef OSANDROID}
// on POSIX, use getifaddrs/freeifaddrs from libc
{$define USE_IFADDRS}
{$endif OSANDROID}
{$ifdef OSANDROIDARM64}
{$define USE_IFADDRS}
// Android BIONIC seems to implement it since Android N (API level 24)
// https://android.googlesource.com/platform/bionic/+/master/docs/status.md
{$endif OSANDROID}
{$ifdef OSLINUX}
procedure RetrieveEnhancedInfo(var a: TMacAddress);
var
sysfs: RawUtf8;
p: PUtf8Char;
l: PtrInt;
ip: cardinal;
begin
// see https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net
sysfs := NetConcat(['/sys/class/net/', a.Name, '/']);
a.FriendlyName := TrimU(StringFromFile(sysfs + 'ifalias', {nosize=}true));
a.Speed := GetCardinal(pointer(StringFromFile(sysfs + 'speed', true)));
a.Mtu := GetCardinal(pointer(StringFromFile(sysfs + 'mtu', true)));
// we retrieve the gateway from /proc/net/route
l := length(a.Name);
p := pointer(StringFromFile('/proc/net/route', true));
while p <> nil do
begin
if (MemCmp(pointer(p), pointer(a.Name), l) = 0) and
(p[l] in [#9, ' ']) then
begin
inc(p, l + 1);
if NetGetNextSpaced(p) = '00000000' then // destination=0.0.0.0
begin
ip := 0;
ParseHex(pointer(NetGetNextSpaced(p)), @ip, 4);
ip := bswap32(ip);
IP4Text(@ip, a.Gateway);
break;
end;
end;
p := GotoNextLine(p);
end;
end;
{$endif OSLINUX}
{$ifdef USE_IFADDRS}
type
pifaddrs = ^ifaddrs;
ifaddrs = record
// Next item in list
ifa_next: pifaddrs;
// null-terminated interface name
ifa_name: PAnsiChar;
// mainly IFF_UP, IFF_BROADCAST and IFF_LOOPBACK
ifa_flags: cardinal;
// Address of interface
ifa_addr: Psockaddr;
// netmask associated with ifa_addr (may be nil)
ifa_netmask: Psockaddr;
// if IFF_BROADCAST is set, the broadcast address associated with ifa_addr
ifa_broadaddr: Psockaddr;
// address-family-specific data - e.g. statistics on AF_PACKET
ifa_data: pointer;
end;
{$ifdef OSBSDDARWIN} // from bsd/net/if_dl.h
psockaddr_dl = ^sockaddr_dl;
sockaddr_dl = record
sdl_len: byte; // Total length of sockaddr
sdl_family: byte; // AF_LINK
sdl_index: word; // if != 0, system given index for interface
sdl_type: byte; // interface type
sdl_nlen: byte; // interface name length, no trailing 0 required
sdl_alen: byte; // link level address length
sdl_slen: byte; // link layer selector length
sdl_data: array[byte] of byte; // interface name + link level address
end;
{$else}
psockaddr_ll = ^sockaddr_ll;
sockaddr_ll = record
sll_family: word;
sll_protocol: word;
sll_ifindex: integer;
sll_hatype: word;
sll_pkttype: byte;
sll_halen: byte;
sll_addr: array[byte] of byte;
end;
{$endif OSBSDDARWIN}
function getifaddrs(var ifap: pifaddrs): integer; cdecl;
external clib name 'getifaddrs';
procedure freeifaddrs(ifap: pifaddrs); cdecl;
external clib name 'freeifaddrs';
function GetIPAddresses(Kind: TIPAddress): TRawUtf8DynArray;
var
list, info: pifaddrs;
n: PtrInt;
s: RawUtf8;
begin
result := nil;
n := 0;
if getifaddrs(list) = NO_ERROR then
try
info := list;
repeat
if (info^.ifa_addr <> nil) and
(info^.ifa_flags and IFF_LOOPBACK = 0) and
(info^.ifa_flags and IFF_UP <> 0) then
begin
s := '';
case info^.ifa_addr^.sa_family of
AF_INET:
if IP4Filter(integer(info^.ifa_addr^.sin_addr), Kind) then
IP4Text(@info^.ifa_addr^.sin_addr,s);
AF_INET6:
if kind in [tiaAny, tiaIPv6] then
with PSockAddrIn6(info^.ifa_addr)^ do
if sin6_scope_id = 0 then // don't include scoped IPv6
IP6Text(@sin6_addr, s);
end;
if s <> '' then
begin
if n = length(result) then
SetLength(result, NextGrow(n));
result[n] := s;
inc(n);
end;
end;
info := info^.ifa_next;
until info = nil;
finally
freeifaddrs(list);
end;
if n <> length(result) then
SetLength(result, n);
end;
function RetrieveMacAddresses(UpAndDown: boolean): TMacAddressDynArray;
var
list, info: pifaddrs;
i, n: PtrInt;
mac: RawUtf8;
begin
// https://github.com/zeromq/czmq/blob/899f81985961513c7f4e/src/ziflist.c#L210
result := nil;
if getifaddrs(list) = NO_ERROR then
try
n := 0;
info := list;
repeat
mac := '';
if (info^.ifa_name <> nil) and
(info^.ifa_flags and IFF_LOOPBACK = 0) and
(UpAndDown or
(info^.ifa_flags and IFF_UP <> 0)) and
((info^.ifa_addr = nil) or
// see https://stackoverflow.com/a/51218583/458259
{$ifdef OSBSDDARWIN}
(info^.ifa_addr^.sa_family = AF_LINK)) then
begin
if info^.ifa_addr <> nil then
with psockaddr_dl(info^.ifa_addr)^ do
if sdl_alen = 6 then
// #define LLADDR(s) ((caddr_t)((s)->sdl_data + (s)->sdl_nlen))
{$ifdef OSDARWIN}
if PCardinal(@sdl_data[sdl_nlen])^ <> 2 then
// iOS7+ return always 02:00:00:00:00:00 as MAC addresses :(
{$endif OSDARWIN}
mac := MacToText(@sdl_data[sdl_nlen]);
{$else}
(info^.ifa_addr^.sa_family = AF_PACKET)) then
begin
if info^.ifa_addr <> nil then
mac := MacToText(@psockaddr_ll(info^.ifa_addr)^.sll_addr);
{$endif OSBSDDARWIN}
if mac = '' then
mac := '00:00:00:00:00:00' // for makSoftware (e.g. tunnel)
else
for i := 0 to n - 1 do
if result[i].Address = mac then
begin
mac := ''; // avoid any duplicate (paranoid)
break;
end;
if mac <> '' then
begin
if n = length(result) then
SetLength(result, NextGrow(n));
with result[n] do
begin
Name := info^.ifa_name; // e.g. 'eth0' on Linux
AdapterName := Name;
Address := mac;
if info^.ifa_addr <> nil then
begin
{$ifdef OSBSDDARWIN}
// BSD/DARWIN do name the networks from their manufacturer
// -> parse net.wlan.devices ?
IfIndex := psockaddr_dl(info^.ifa_addr)^.sdl_index;
case psockaddr_dl(info^.ifa_addr)^.sdl_type of
IFT_ETHER:
Kind := makEthernet;
IFT_PPP:
Kind := makPpp;
IFT_CELLULAR:
Kind := makCellular;
{$else}
IfIndex := psockaddr_ll(info^.ifa_addr)^.sll_ifindex;
case psockaddr_ll(info^.ifa_addr)^.sll_hatype of
ARPHRD_ETHER:
begin
Kind := makEthernet;
if Name <> '' then
// set also for some wifi adapters
if PWord(Name)^ = ord('w') + ord('l') shl 8 then
Kind := makWifi; // detect by convention
end;
ARPHRD_IEEE80211:
Kind := makWifi;
ARPHRD_TUNNEL,
ARPHRD_TUNNEL6:
Kind := makTunnel;
ARPHRD_PPP:
Kind := makPpp;
{$endif OSBSDDARWIN}
else
// https://systemd.io/PREDICTABLE_INTERFACE_NAMES
if Name <> '' then
case PWord(Name)^ of
ord('e') + ord('t') shl 8, // 'ethX'
ord('e') + ord('n') shl 8: // systemd v197 'enpXsX'
Kind := makEthernet;
ord('w') + ord('l') shl 8: // 'wlanX' and systemd v197 'wlX'
Kind := makWifi;
end;
end;
end
else
begin
IfIndex := -1; // non physical interface
Kind := makSoftware;
end
end;
{$ifdef OSLINUX}
if info^.ifa_flags and IFF_UP <> 0 then
RetrieveEnhancedInfo(result[n]);
{$endif OSLINUX}
// on POSIX, there is no such things as per-interface DNS, and
// no standard way of knowing the Gateway
inc(n);
end;
end;
info := info^.ifa_next;
until info = nil;
SetLength(result, n);
// retrieve the IP configuration from a second loop
info := list;
repeat
if (info^.ifa_addr <> nil) and
(info^.ifa_flags and IFF_LOOPBACK = 0) and
(info^.ifa_flags and IFF_UP <> 0) and
(info^.ifa_addr^.sa_family = AF_INET) then
for i := 0 to n - 1 do
with result[i] do
if StrComp(pointer(Name), info^.ifa_name) = 0 then
begin
if IP = '' then // only return the first IPv4 (paranoid)
begin
IP4Text(@info^.ifa_addr^.sin_addr, IP);
if (info^.ifa_netmask <> nil) and
(info^.ifa_netmask^.sa_family = AF_INET) then
IP4Text(@info^.ifa_netmask^.sin_addr, NetMask);
if (info^.ifa_flags and IFF_BROADCAST <> 0) and
(info^.ifa_broadaddr <> nil) and
(info^.ifa_broadaddr^.sa_family = AF_INET) then
IP4Text(@info^.ifa_broadaddr^.sin_addr, Broadcast);
// don't use IP4Broadcast() because if the OS says there is
// no broadcast address, then there is no broadcasting enabled
end;
break;
end;
info := info^.ifa_next;
until info = nil;
finally
freeifaddrs(list);
end;
end;
{$else}
function GetIPAddresses(Kind: TIPAddress): TRawUtf8DynArray;
begin
result := nil;
end;
{$ifdef OSLINUX}
// on Android, /sys/class/net is not readable from the standard user :(
function RetrieveMacAddresses(UpAndDown: boolean): TMacAddressDynArray;
var
n: integer;
SR: TSearchRec;
fn: TFileName;
f: RawUtf8;
begin
result := nil;
if FindFirst('/sys/class/net/*', faDirectory, SR) = 0 then
begin
n := 0;
repeat
if (SR.Name <> 'lo') and
SearchRecValidFolder(SR) then
begin
fn := '/sys/class/net/' + SR.Name;
f := StringFromFile(fn + '/flags', {nosize=}true);
if (length(f) > 2) and // e.g. '0x40' or '0x1043'
(ParseHex0x(pointer(f)) and (IFF_UP or IFF_LOOPBACK) = IFF_UP) then
begin
f := TrimU(StringFromFile(fn + '/address', {nosize=}true));
if f <> '' then
begin
SetLength(result, n + 1);
result[n].Name := SR.Name;
result[n].Address := f;
RetrieveEnhancedInfo(result[n]);
// sadly, retrieving IP and mask from /proc is very complex
// https://stackoverflow.com/a/14725655/458259
// a solution may be to use ioctl()
// https://github.com/zeromq/czmq/blob/899f81985961513c7f4e/src/ziflist.c#L277
inc(n);
end;
end;
end;
until FindNext(SR) <> 0;
FindClose(SR);
end;