Repository navigation
Expand file tree
/
Copy pathExport.cpp
More file actions
3758 lines (3417 loc) · 142 KB
/
Copy pathExport.cpp
File metadata and controls
3758 lines (3417 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#else
#include <arpa/inet.h>
#include <cerrno>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <poll.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <array>
#include <atomic>
#include <climits>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstddef>
#include <cstring>
#include <deque>
#include <memory>
#include <map>
#include <mutex>
#include <new>
#include <optional>
#include <random>
#include <vector>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestHeap.hpp"
#include "prx/libkernel/Socket/include/SocketError.hpp"
#include "prx/libkernel/Socket/include/SocketPoll.hpp"
#include "prx/libSceNet/include/VirtualNet.hpp"
#include "prx/libSceNet/include/VirtualStream.hpp"
#include "prx/libkernel/Socket/include/SocketRuntime.hpp"
#include "prx/libkernel/Time/include/Time.hpp"
#include "prx/libkernel/Pthread/include/ThreadLifecycle.hpp"
#include "src/ResolverTestHooks.hpp"
// Guest socket descriptors retain PS5 semantics while their transport is backed by host sockets.
struct NetWlanInformationElement;
struct NetWlanWakeParameter;
struct NetWlanScanParameter;
struct NetWlanScanResult;
struct NetWlanAdhocScanParameter;
struct NetWlanInfraScanParameter;
struct NetWlanJoinResult;
struct NetDumpFilterParameter;
struct NetWlanAdhocParameter;
struct NetWlanWakeInfo;
struct NetWlanPspWakeInfo;
struct NetWlanPspWakeParameter;
struct NetWlanApParameter;
struct NetWlanDeviceInfo;
struct NetWlanAntennaParameter;
struct NetWlanRateParameter;
struct NetWlanDeviceConfiguration;
struct NetWlanRssiInfo;
struct NetDhcpInfo;
struct NetAutoIpInfo;
struct NetAddress6Info;
struct NetDhcpOptionInfo {
std::uint32_t option;
std::uint32_t capacity;
void* data;
std::uint32_t size;
std::uint32_t reserved;
};
static_assert(sizeof(NetDhcpOptionInfo) == 24);
static_assert(offsetof(NetDhcpOptionInfo, capacity) == 4);
static_assert(offsetof(NetDhcpOptionInfo, data) == 8);
static_assert(offsetof(NetDhcpOptionInfo, size) == 16);
struct NetSockInfo6;
struct NetStatisticsInfo;
struct NetInterfaceStats;
struct NetRouteInfo;
struct NetDebugParameter;
struct NetArpInfo;
struct NetAppMemoryInfo;
struct NetSystemMemoryInfo;
struct NetBandwidthParameter;
struct NetDataTraffic;
struct NetEmulationParameter;
struct NetResolverConnection;
struct NetThreadParameter {
void (APS5_VABI *entry)(void*);
void* arg;
std::uint64_t reserved;
std::uint32_t flags;
};
struct NetIpv4InterfaceAddress;
struct NetStatisticsInfoInternal;
struct NetInitializeParameter;
struct NetDhcpStartParameter;
struct NetAddress6StartParameter;
using NetAddressCallback = void (APS5_VABI *)(void* userArg, std::int32_t event, std::int32_t error);
struct NetDhcpdStartParameter {
std::uint32_t addresses[5];
std::uint32_t maxClients;
};
struct NetPppoeStartParameter {
std::uint32_t dnsAddresses[2];
char userName[128];
char password[128];
std::int32_t mtu;
std::uint32_t flags;
};
struct NetRoutingAddressParameter {
std::uint32_t address;
std::uint32_t mask;
};
struct NetRoutingServerParameter {
std::int32_t count;
std::uint32_t localAddresses[2];
std::uint32_t remoteAddresses[2];
};
struct NetRoutingRule {
std::int32_t protocol;
std::uint32_t firstAddress;
std::uint16_t firstPort;
std::uint16_t reserved;
std::uint32_t secondAddress;
std::uint16_t secondPort;
std::uint16_t flags;
};
struct NetRoutingRuleParameter {
std::int32_t count;
const NetRoutingRule* rules;
};
static_assert(sizeof(NetRoutingAddressParameter) == 8);
static_assert(sizeof(NetRoutingServerParameter) == 20);
static_assert(offsetof(NetRoutingServerParameter, remoteAddresses) == 12);
static_assert(sizeof(NetRoutingRule) == 20);
static_assert(offsetof(NetRoutingRule, firstPort) == 8);
static_assert(offsetof(NetRoutingRule, secondAddress) == 12);
static_assert(offsetof(NetRoutingRule, flags) == 18);
static_assert(sizeof(NetRoutingRuleParameter) == 16);
static_assert(offsetof(NetRoutingRuleParameter, rules) == 8);
static_assert(sizeof(NetDhcpdStartParameter) == 24);
static_assert(offsetof(NetDhcpdStartParameter, maxClients) == 20);
static_assert(sizeof(NetPppoeStartParameter) == 272);
static_assert(offsetof(NetPppoeStartParameter, userName) == 8);
static_assert(offsetof(NetPppoeStartParameter, password) == 136);
static_assert(offsetof(NetPppoeStartParameter, mtu) == 264);
static_assert(offsetof(NetPppoeStartParameter, flags) == 268);
struct NetInfoDumpParameter {
std::uint32_t flags;
std::uint32_t intervalSeconds;
char path[64];
};
static_assert(sizeof(NetInfoDumpParameter) == 72);
static_assert(offsetof(NetInfoDumpParameter, path) == 8);
struct NetInterfaceInfo;
struct NetInterfaceStatistics;
struct NetResolverConnectOption {
std::int32_t connectionTimeout;
std::int32_t resolverTimeout;
std::int32_t resolverRetryCount;
std::uint32_t reserved;
};
static_assert(sizeof(NetResolverConnectOption) == 16);
static_assert(offsetof(NetResolverConnectOption, resolverTimeout) == 4);
static_assert(offsetof(NetResolverConnectOption, resolverRetryCount) == 8);
static_assert(offsetof(NetResolverConnectOption, reserved) == 12);
struct NetSyncObject {
void* mutex;
void* condition;
std::uint32_t signals;
std::uint32_t reserved;
};
static_assert(sizeof(NetSyncObject) == 24);
using NetEventCallback = std::uint64_t (APS5_VABI*)(std::uint32_t interfaceId, std::uint64_t events, void* userData, void* waitData);
struct NetIpv6Address {
std::uint8_t bytes[16];
};
static_assert(sizeof(NetIpv6Address) == 16);
struct NetDnsInfo {
std::uint32_t primaryAddress;
std::uint32_t secondaryAddress;
};
struct NetDns6Info {
NetIpv6Address primaryAddress;
NetIpv6Address secondaryAddress;
};
static_assert(sizeof(NetDnsInfo) == 8);
static_assert(sizeof(NetDns6Info) == 32);
struct NetIpv6InterfaceAddress {
NetIpv6Address address;
std::uint8_t prefixLength;
std::uint8_t reserved[3];
};
static_assert(sizeof(NetIpv6InterfaceAddress) == 20);
namespace {
// FreeBSD errno numbers as reported through sceNetErrnoLoc (SCE_NET_ERROR_* is 0x80410100 + errno).
constexpr int NET_ENOENT = 2;
constexpr int NET_EINTR = 4;
constexpr int NET_EBADF = 9;
constexpr int NET_EACCES = 13;
constexpr int NET_EFAULT = 14;
constexpr int NET_EINVAL = 22;
constexpr int NET_ENOTTY = 25;
constexpr int NET_ENOSPC = 28;
constexpr int NET_EDOM = 33;
constexpr int NET_EAGAIN = 35;
constexpr int NET_EINPROGRESS = 36;
constexpr int NET_EALREADY = 37;
constexpr int NET_ENOTSOCK = 38;
constexpr int NET_ENOPROTOOPT = 42;
constexpr int NET_EOPNOTSUPP = 45;
constexpr int NET_EPROTONOSUPPORT = 43;
constexpr int NET_EAFNOSUPPORT = 47;
constexpr int NET_EADDRINUSE = 48;
constexpr int NET_EADDRNOTAVAIL = 49;
constexpr int NET_ENETUNREACH = 51;
constexpr int NET_ECONNABORTED = 53;
constexpr int NET_ENOBUFS = 55;
constexpr int NET_EISCONN = 56;
constexpr int NET_ENOTCONN = 57;
constexpr int NET_EMSGSIZE = 40;
constexpr int NET_ETIMEDOUT = 60;
constexpr int NET_ECONNREFUSED = 61;
constexpr int NET_EHOSTUNREACH = 65;
constexpr int NET_ENOTINIT = 200;
constexpr int NET_ERROR_BASE = static_cast<int>(0x80410100u);
constexpr int NET_ERROR_RESOLVER_ENODNS = static_cast<int>(0x804101E1u);
constexpr int NET_RESOLVER_ABORT_FLAG_NTOA_PRESERVATION = 0x1;
constexpr int NET_RESOLVER_ABORT_FLAG_ATON_PRESERVATION = 0x2;
constexpr int NET_AF_INET = 2;
constexpr int NET_AF_INET6 = 28;
constexpr int NET_SOCK_STREAM = 1;
constexpr int NET_SOCK_DGRAM = 2;
constexpr int NET_SOCK_DGRAM_P2P = 6;
constexpr int NET_SOCK_STREAM_P2P = 10;
constexpr int NET_SOCK_RAW = 3;
constexpr int NET_EPOLL_CTL_ADD = 1;
constexpr int NET_EPOLL_CTL_MOD = 2;
constexpr int NET_EPOLL_CTL_DEL = 3;
constexpr int NET_SOL_SOCKET = 0xFFFF;
constexpr int NET_IPPROTO_TCP = 6;
constexpr int NET_TCP_NODELAY = 1;
constexpr int NET_TF_NODELAY = 4;
constexpr int NET_SO_SNDTIMEO = 0x1005;
constexpr int NET_SO_RCVTIMEO = 0x1006;
constexpr int NET_SO_ERROR = 0x1007;
constexpr int NET_SO_NBIO = 0x1200;
constexpr int NET_SO_REUSEADDR = 0x4;
constexpr int NET_SO_BROADCAST = 0x20;
constexpr int NET_SO_ONESBCAST = 0x10000;
constexpr int NET_SO_SNDBUF = 0x1001;
constexpr int NET_SO_RCVBUF = 0x1002;
constexpr int NET_SO_SCE_SNDTIMEO = 0x1105;
constexpr int NET_SO_SCE_RCVTIMEO = 0x1106;
constexpr int NET_MSG_PEEK = 0x2;
constexpr int NET_MSG_TRUNC = 0x10;
constexpr int NET_MSG_DONTWAIT = 0x80;
constexpr int NET_UIO_MAXIOV = 1024;
#ifdef _WIN32
using NativeSocket = SOCKET;
using NativeLength = int;
constexpr NativeSocket INVALID_NATIVE_SOCKET = INVALID_SOCKET;
constexpr int NATIVE_SEND_FLAGS = 0;
bool initialize_sockets() {
static const int result = [] {
WSADATA data{};
return WSAStartup(MAKEWORD(2, 2), &data);
}();
return result == 0;
}
void close_socket(NativeSocket socket) { closesocket(socket); }
int net_error(int code) { return GuestSockets::GuestErrorFromHost(code); }
int native_error() { return net_error(WSAGetLastError()); }
#else
using NativeSocket = int;
using NativeLength = socklen_t;
constexpr NativeSocket INVALID_NATIVE_SOCKET = -1;
constexpr int NATIVE_SEND_FLAGS = MSG_NOSIGNAL;
bool initialize_sockets() { return true; }
void close_socket(NativeSocket socket) { ::close(socket); }
int net_error(int code) { return GuestSockets::GuestErrorFromHost(code); }
int native_error() { return net_error(errno); }
#endif
#ifdef _WIN32
int TransferSocketForKernel(KernelSocketPoll::NativeOwner* owner, bool send, void* buffer, int length);
#endif
struct NativeSocketHandle : KernelSocketPoll::NativeOwner {
NativeSocket value;
const bool stream;
std::atomic<bool> nonblock{false};
std::atomic<int> receiveTimeout{0};
std::atomic<int> sendTimeout{0};
NativeSocketHandle(NativeSocket socket, bool stream) : value(socket), stream(stream) {
#ifdef _WIN32
transfer = &TransferSocketForKernel;
#endif
}
~NativeSocketHandle() {
if (value != INVALID_NATIVE_SOCKET) close_socket(value);
}
};
bool guest_to_native_address(const void* address, std::uint32_t length,
sockaddr_storage& native, NativeLength& native_length) {
if (!address || length < 2) return false;
const auto* bytes = static_cast<const std::uint8_t*>(address);
if (bytes[1] == NET_AF_INET && length >= 16) {
auto& v4 = reinterpret_cast<sockaddr_in&>(native);
v4.sin_family = AF_INET;
std::memcpy(&v4.sin_port, bytes + 2, 2);
std::memcpy(&v4.sin_addr, bytes + 4, 4);
native_length = sizeof(v4);
return true;
}
if (bytes[1] == NET_AF_INET6 && length >= 28) {
auto& v6 = reinterpret_cast<sockaddr_in6&>(native);
v6.sin6_family = AF_INET6;
std::memcpy(&v6.sin6_port, bytes + 2, 2);
std::memcpy(&v6.sin6_flowinfo, bytes + 4, 4);
std::memcpy(&v6.sin6_addr, bytes + 8, 16);
std::memcpy(&v6.sin6_scope_id, bytes + 24, 4);
native_length = sizeof(v6);
return true;
}
return false;
}
bool native_to_guest_address(const sockaddr_storage& native, void* address, std::uint32_t* length) {
if (!address || !length) return false;
if (native.ss_family == AF_UNSPEC) {
*length = 0;
return true;
}
std::uint8_t bytes[28]{};
if (native.ss_family == AF_INET) {
const auto& v4 = reinterpret_cast<const sockaddr_in&>(native);
bytes[0] = 16;
bytes[1] = NET_AF_INET;
std::memcpy(bytes + 2, &v4.sin_port, 2);
std::memcpy(bytes + 4, &v4.sin_addr, 4);
} else if (native.ss_family == AF_INET6) {
const auto& v6 = reinterpret_cast<const sockaddr_in6&>(native);
bytes[0] = 28;
bytes[1] = NET_AF_INET6;
std::memcpy(bytes + 2, &v6.sin6_port, 2);
std::memcpy(bytes + 4, &v6.sin6_flowinfo, 4);
std::memcpy(bytes + 8, &v6.sin6_addr, 16);
std::memcpy(bytes + 24, &v6.sin6_scope_id, 4);
} else {
return false;
}
const auto copied = std::min<std::uint32_t>(*length, bytes[0]);
std::memcpy(address, bytes, copied);
*length = copied;
return true;
}
struct Sock {
int family = 0;
int type = 0;
std::shared_ptr<NativeSocketHandle> native;
bool bound = false;
bool listening = false;
bool aborted = false;
bool read_shut = false;
int reported_error = 0;
int snd_buffer = 0;
int rcv_buffer = 0;
int onesbcast = 0;
bool p2p = false;
bool virtualRoute = false;
std::uint16_t gamePort = 0;
std::uint16_t gameVport = 0;
std::uint32_t virtualPeer = 0;
std::uint16_t virtualPeerPort = 0;
std::uint16_t virtualPeerVport = 0;
// A stream P2P socket (p2p with type NET_SOCK_STREAM) once connected or accepted: the player
// at the other end, as getpeername reports it.
std::uint32_t streamPeer = 0;
std::uint16_t streamPeerPort = 0;
std::uint16_t streamPeerVport = 0;
};
bool stream_p2p(const Sock& socket) {
return socket.p2p && socket.type == NET_SOCK_STREAM;
}
// Binds a stream P2P socket's host socket to 127.0.0.1 at a port the system picks, unless it has one.
bool bind_stream_loopback(NativeSocket native) {
sockaddr_in local{};
NativeLength length = sizeof(local);
if (::getsockname(native, reinterpret_cast<sockaddr*>(&local), &length) == 0 && local.sin_family == AF_INET && local.sin_port != 0) return true;
sockaddr_in loopback{};
loopback.sin_family = AF_INET;
loopback.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
return ::bind(native, reinterpret_cast<const sockaddr*>(&loopback), sizeof(loopback)) == 0;
}
#ifdef _WIN32
struct HostMutex {
SRWLOCK native = SRWLOCK_INIT;
HostMutex() = default;
HostMutex(const HostMutex&) = delete;
HostMutex& operator=(const HostMutex&) = delete;
void lock() { AcquireSRWLockExclusive(&native); }
void unlock() { ReleaseSRWLockExclusive(&native); }
};
#else
using HostMutex = std::mutex;
#endif
class HostCondition {
public:
HostCondition() = default;
HostCondition(const HostCondition&) = delete;
HostCondition& operator=(const HostCondition&) = delete;
void NotifyAll() {
#ifdef _WIN32
WakeAllConditionVariable(&native);
#else
native.notify_all();
#endif
}
void WaitUntil(std::unique_lock<HostMutex>& lock, std::chrono::steady_clock::time_point deadline) {
#ifdef _WIN32
const auto now = std::chrono::steady_clock::now();
if (deadline <= now) return;
const auto milliseconds = std::chrono::ceil<std::chrono::milliseconds>(deadline - now).count();
if (!SleepConditionVariableSRW(&native, &lock.mutex()->native, static_cast<DWORD>(milliseconds), 0) &&
GetLastError() != ERROR_TIMEOUT)
throw std::runtime_error("sceNetEpollWait: native condition wait failed");
#else
native.wait_until(lock, deadline);
#endif
}
private:
#ifdef _WIN32
CONDITION_VARIABLE native = CONDITION_VARIABLE_INIT;
#else
std::condition_variable native;
#endif
};
HostMutex g_mutex;
HostCondition g_cv;
std::map<int, Sock> g_socks;
std::set<int> g_epolls;
using EpollRegistrations = std::map<int, std::shared_ptr<const NetEpollEvent>>;
std::map<int, EpollRegistrations> g_epoll_socks;
// Registrations of descriptors made by libkernel's socket(), which have no Sock here. The weak owner tells a
// registration of a closed socket from one of a new socket that reuses its number.
struct KernelEpollWatch {
std::weak_ptr<void> owner;
NativeSocket native;
};
std::map<int, std::map<int, KernelEpollWatch>> g_epoll_kernel_watches;
std::set<int> g_epoll_aborted;
std::map<int, std::size_t> g_pools;
struct NetMemoryPoolStats {
std::size_t pool_size;
std::size_t max_inuse_size;
std::size_t current_inuse_size;
};
struct Resolver {
int error = 0;
int running = 0;
std::uint64_t aborts = 0;
bool abort_ntoa = false;
bool abort_aton = false;
};
std::map<int, Resolver> g_resolvers;
int g_next_sock = 32;
int g_next_epoll = 0x4000;
int g_next_pool = 1;
int g_next_resolver = 0x100;
bool g_net_inited = false;
std::atomic<GuestSceNetTest::ResolverLookup> g_resolverLookupForTests{nullptr};
int* errno_slot() {
static thread_local int e = 0;
return &e;
}
extern "C" int* APS5_VABI __error_nid_postfix();
extern "C" std::size_t NetCtlHostDnsServers_nid_no_patch(std::uint32_t* servers, std::size_t capacity);
void set_errno(int err) {
*errno_slot() = err;
*__error_nid_postfix() = err;
}
int fail(int err) {
set_errno(err);
return NET_ERROR_BASE | err;
}
// On the console socket() and sceNetSocket make descriptors in one kernel namespace, so libSceNet calls take
// either. IL2CPP (PPSA02429) makes its sockets with socket() and polls them with sceNetEpoll*. A socket() descriptor
// lives in libkernel; this finds its host socket. Call it without g_mutex: libkernel may ask libSceNet back.
struct KernelSocket {
std::shared_ptr<void> owner;
NativeSocket native = INVALID_NATIVE_SOCKET;
};
bool find_kernel_socket(int descriptor, KernelSocket& found) {
if (!GuestSocketIsOpen_nid_no_patch(descriptor)) return false;
std::uintptr_t native = 0;
if (!KernelLookupSocketNative_nid_no_patch(descriptor, &found.owner, &native) || !found.owner) return false;
found.native = static_cast<NativeSocket>(native);
return true;
}
extern "C" int APS5_VABI scePthreadCreate(Pthread* thread, const PthreadAttr* attr, PthreadEntry entry, void* arg, const char* name);
extern "C" int APS5_VABI scePthreadJoin(Pthread thread, void** retval);
void* APS5_VABI RunNetThread(void* param) {
const auto* thread = static_cast<const NetThreadParameter*>(param);
thread->entry(thread->arg);
return nullptr;
}
int set_native_timeout(NativeSocket native, int optname, std::int64_t microseconds) {
const int native_option = optname == NET_SO_RCVTIMEO ? SO_RCVTIMEO : SO_SNDTIMEO;
#ifdef _WIN32
const std::int64_t milliseconds = (microseconds + 999) / 1000;
const DWORD timeout_ms = milliseconds > static_cast<std::int64_t>(MAXDWORD) ? MAXDWORD : static_cast<DWORD>(milliseconds);
return ::setsockopt(native, SOL_SOCKET, native_option, reinterpret_cast<const char*>(&timeout_ms), sizeof(timeout_ms));
#else
timeval timeout{};
timeout.tv_sec = static_cast<time_t>(microseconds / 1000000);
timeout.tv_usec = static_cast<suseconds_t>(microseconds % 1000000);
return ::setsockopt(native, SOL_SOCKET, native_option, &timeout, sizeof(timeout));
#endif
}
int set_kernel_timeout(int descriptor, int optname, const void* value, std::uint32_t length) {
KernelTimeval timeout{};
if (value == nullptr && length != 0) return NET_EFAULT;
if (length < sizeof(timeout)) return NET_EINVAL;
std::memcpy(&timeout, value, sizeof(timeout));
if (timeout.tv_sec < 0 || timeout.tv_usec < 0 || timeout.tv_usec >= 1000000) return NET_EDOM;
const std::int64_t microseconds = std::min<std::int64_t>(timeout.tv_sec, INT32_MAX) * 1000000 + timeout.tv_usec;
Sock socket;
{
std::lock_guard lk(g_mutex);
const auto it = g_socks.find(descriptor);
if (it == g_socks.end()) return NET_EBADF;
socket = it->second;
}
if (set_native_timeout(socket.native->value, optname, microseconds) != 0) return native_error();
std::lock_guard lk(g_mutex);
const auto it = g_socks.find(descriptor);
if (it != g_socks.end()) {
const int stored = static_cast<int>(std::min<std::int64_t>(microseconds, INT_MAX));
if (optname == NET_SO_RCVTIMEO) it->second.native->receiveTimeout = stored;
else it->second.native->sendTimeout = stored;
}
return 0;
}
int begin_lookup(int rid, bool Resolver::*preservedAbort, std::uint64_t& generation) {
std::lock_guard lk(g_mutex);
const auto resolver = g_resolvers.find(rid);
if (resolver == g_resolvers.end()) return fail(NET_EBADF);
if (std::exchange(resolver->second.*preservedAbort, false)) {
resolver->second.error = NET_ERROR_BASE | NET_EINTR;
return fail(NET_EINTR);
}
++resolver->second.running;
generation = resolver->second.aborts;
return 0;
}
int end_lookup(int rid, std::uint64_t generation, int error) {
std::lock_guard lk(g_mutex);
const auto resolver = g_resolvers.find(rid);
if (resolver == g_resolvers.end()) return error;
--resolver->second.running;
if (resolver->second.aborts != generation) error = fail(NET_EINTR);
resolver->second.error = error;
return error;
}
void log_soft(const char* func, const char* what) {
static std::mutex mtx;
static std::map<std::string, int> hits;
std::lock_guard<std::mutex> lk(mtx);
if (++hits[func] > 3) {
return;
}
std::fprintf(stderr, "[SOFT-NET] %s -> %s\n", func, what);
std::fflush(stderr);
}
std::uint16_t swap16(std::uint16_t v) { return static_cast<std::uint16_t>((v << 8) | (v >> 8)); }
std::uint32_t swap32(std::uint32_t v) {
return (v << 24) | ((v & 0xFF00u) << 8) | ((v >> 8) & 0xFF00u) | (v >> 24);
}
std::uint64_t swap64(std::uint64_t v) {
return (v << 56) | ((v & 0xFF00u) << 40) | ((v & 0xFF0000u) << 24) | ((v & 0xFF000000u) << 8) |
((v >> 8) & 0xFF000000u) | ((v >> 24) & 0xFF0000u) | ((v >> 40) & 0xFF00u) | (v >> 56);
}
struct NetIovec {
void* base;
std::uint64_t length;
};
struct NetMsghdr {
void* name;
std::uint32_t name_length;
NetIovec* iov;
int iov_length;
void* control;
std::uint32_t control_length;
int flags;
};
static_assert(sizeof(NetMsghdr) == 48 && offsetof(NetMsghdr, iov) == 16 && offsetof(NetMsghdr, control) == 32 &&
offsetof(NetMsghdr, flags) == 44);
int timeout_option(int optname) {
if (optname == NET_SO_SCE_SNDTIMEO) return NET_SO_SNDTIMEO;
if (optname == NET_SO_SCE_RCVTIMEO) return NET_SO_RCVTIMEO;
return optname;
}
std::int64_t message_length(const NetMsghdr* message) {
if (!message) return fail(NET_EFAULT);
if (message->iov_length < 0 || message->iov_length > NET_UIO_MAXIOV) return fail(NET_EMSGSIZE);
if (message->iov_length && !message->iov) return fail(NET_EFAULT);
std::uint64_t total = 0;
for (int i = 0; i < message->iov_length; ++i) {
const auto& entry = message->iov[i];
if (!entry.base && entry.length) return fail(NET_EFAULT);
if (entry.length > INT_MAX - total) return fail(NET_EINVAL);
total += entry.length;
}
return static_cast<std::int64_t>(total);
}
bool message_flags_supported(int flags, int accepted) {
return (flags & ~accepted) == 0;
}
template <typename TOperation>
auto native_transfer(const NativeSocketHandle& socket, int flags, bool send, TOperation operation, bool timed = true, int length = 0) {
#ifdef _WIN32
using Result = decltype(operation(0));
const bool nonblocking = (flags & NET_MSG_DONTWAIT) != 0 || socket.nonblock.load();
const int completeLength = send && socket.stream && !nonblocking ? length : 0;
const int timeout = timed ? (send ? socket.sendTimeout.load() : socket.receiveTimeout.load()) : 0;
const auto deadline = timeout > 0 ? std::chrono::steady_clock::now() + std::chrono::microseconds(timeout)
: std::chrono::steady_clock::time_point::max();
int transferred = 0;
for (;;) {
const auto result = operation(transferred);
if (result != static_cast<Result>(-1)) {
if (completeLength == 0) return result;
transferred += static_cast<int>(result);
if (transferred == completeLength || result == 0) return static_cast<Result>(transferred);
} else if (WSAGetLastError() != WSAEWOULDBLOCK || nonblocking) {
return transferred > 0 ? static_cast<Result>(transferred) : result;
}
int milliseconds = 10;
if (timeout > 0) {
const auto remaining = deadline - std::chrono::steady_clock::now();
if (remaining <= std::chrono::steady_clock::duration::zero()) {
WSASetLastError(send && completeLength == 0 ? WSAETIMEDOUT : WSAEWOULDBLOCK);
return transferred > 0 ? static_cast<Result>(transferred) : static_cast<Result>(-1);
}
milliseconds = static_cast<int>(std::min<std::int64_t>(std::chrono::ceil<std::chrono::milliseconds>(remaining).count(), milliseconds));
}
WSAPOLLFD descriptor{};
descriptor.fd = socket.value;
descriptor.events = send ? POLLWRNORM : POLLRDNORM;
const int ready = WSAPoll(&descriptor, 1, milliseconds);
if (ready < 0) return transferred > 0 ? static_cast<Result>(transferred) : static_cast<Result>(-1);
}
#else
static_cast<void>(socket);
static_cast<void>(flags);
static_cast<void>(send);
static_cast<void>(timed);
static_cast<void>(length);
return operation(0);
#endif
}
#ifdef _WIN32
int TransferSocketForKernel(KernelSocketPoll::NativeOwner* owner, bool send, void* buffer, int length) {
const auto* socket = static_cast<NativeSocketHandle*>(owner);
return native_transfer(*socket, 0, send, [&](int offset) {
return send ? ::send(socket->value, offset ? static_cast<const char*>(buffer) + offset : static_cast<const char*>(buffer), length - offset, 0)
: ::recv(socket->value, static_cast<char*>(buffer), length, 0);
}, true, length);
}
#endif
int native_message_flags(int flags) {
int native = (flags & NET_MSG_PEEK) ? MSG_PEEK : 0;
#ifndef _WIN32
if (flags & NET_MSG_DONTWAIT) native |= MSG_DONTWAIT;
#endif
return native;
}
#if defined(_WIN32) || defined(__APPLE__)
#ifdef __APPLE__
bool has_local_address(NativeSocket native) {
sockaddr_storage local{};
NativeLength local_length = sizeof(local);
if (::getsockname(native, reinterpret_cast<sockaddr*>(&local), &local_length) != 0) return true;
if (local.ss_family == AF_INET) return reinterpret_cast<const sockaddr_in&>(local).sin_port != 0;
if (local.ss_family == AF_INET6) return reinterpret_cast<const sockaddr_in6&>(local).sin6_port != 0;
return true;
}
#else
bool has_local_address(NativeSocket native) {
sockaddr_storage local{};
NativeLength local_length = sizeof(local);
return ::getsockname(native, reinterpret_cast<sockaddr*>(&local), &local_length) == 0 || WSAGetLastError() != WSAEINVAL;
}
#endif
void note_local_address(int s, const Sock& socket) {
if (socket.type == NET_SOCK_STREAM || socket.bound || !has_local_address(socket.native->value)) return;
std::lock_guard lk(g_mutex);
const auto it = g_socks.find(s);
if (it != g_socks.end() && it->second.native == socket.native) it->second.bound = true;
g_cv.NotifyAll();
}
constexpr int RECEIVE_NOTHING = -1;
int wait_for_datagram(const Sock& socket, std::chrono::steady_clock::time_point deadline) {
if (deadline == std::chrono::steady_clock::time_point::max()) return 0;
const auto now = std::chrono::steady_clock::now();
if (now >= deadline) return NET_EAGAIN;
const auto remaining = std::chrono::ceil<std::chrono::milliseconds>(deadline - now).count();
#ifdef _WIN32
WSAPOLLFD descriptor{};
descriptor.fd = socket.native->value;
descriptor.events = POLLRDNORM;
return WSAPoll(&descriptor, 1, static_cast<INT>(std::min<long long>(remaining, INT_MAX))) == 0 ? NET_EAGAIN : 0;
#else
pollfd descriptor{};
descriptor.fd = socket.native->value;
descriptor.events = POLLIN;
return ::poll(&descriptor, 1, static_cast<int>(std::min<long long>(remaining, INT_MAX))) == 0 ? NET_EAGAIN : 0;
#endif
}
int wait_for_local_address(int s, const Sock& socket, bool empty, int flags) {
if (socket.type == NET_SOCK_STREAM || socket.bound) return 0;
const bool named = has_local_address(socket.native->value);
if (!named && (socket.read_shut || empty)) return RECEIVE_NOTHING;
if (!named && (socket.native->nonblock || (flags & NET_MSG_DONTWAIT) != 0)) return NET_EAGAIN;
const int timeout = socket.native->receiveTimeout;
const auto deadline = timeout > 0
? std::chrono::steady_clock::now() + std::chrono::microseconds(timeout)
: std::chrono::steady_clock::time_point::max();
std::unique_lock lk(g_mutex);
for (bool waited = false;; waited = true) {
const auto it = g_socks.find(s);
if (it == g_socks.end() || it->second.native != socket.native || it->second.aborted) return 0;
if (named || has_local_address(socket.native->value)) {
it->second.bound = true;
lk.unlock();
return waited ? wait_for_datagram(socket, deadline) : 0;
}
if (it->second.read_shut) return RECEIVE_NOTHING;
const auto now = std::chrono::steady_clock::now();
if (now >= deadline) return NET_EAGAIN;
g_cv.WaitUntil(lk, std::min(deadline, now + std::chrono::milliseconds(10)));
}
}
#endif
bool parse_ipv4_parts(const char* text, std::uint32_t& address) {
std::array<std::uint32_t, 3> parts{};
std::size_t count = 0;
std::uint32_t value = 0;
for (;;) {
if (*text < '0' || *text > '9') return false;
std::uint32_t base = 10;
if (*text == '0') {
++text;
if (*text == 'x' || *text == 'X') {
base = 16;
++text;
} else if (*text != '9') {
base = 8;
}
}
value = 0;
for (;; ++text) {
const char c = *text;
if (c >= '0' && c <= '9') {
if (base == 8 && c >= '8') return false;
value = value * base + static_cast<std::uint32_t>(c - '0');
} else if (base == 16 && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
value = value * 16 + static_cast<std::uint32_t>((c | 0x20) - 'a' + 10);
} else {
break;
}
}
if (*text != '.') break;
if (count == parts.size() || value > 0xff) return false;
parts[count++] = value;
++text;
}
if (*text != '\0' && std::strchr(" \t\n\v\f\r", *text) == nullptr) return false;
if (value > (0xffffffffu >> (8 * count))) return false;
for (std::size_t i = 0; i < count; ++i) value |= parts[i] << (24 - 8 * i);
address = value;
return true;
}
} // namespace
void GuestSceNetTest::SetResolverLookupForTests_nid_no_patch(ResolverLookup lookup) noexcept {
g_resolverLookupForTests.store(lookup);
}
std::uint16_t native_port(const NativeSocketHandle& handle) {
sockaddr_storage local{};
NativeLength length = sizeof(local);
if (::getsockname(handle.value, reinterpret_cast<sockaddr*>(&local), &length) != 0 || local.ss_family != AF_INET) return 0;
return ntohs(reinterpret_cast<const sockaddr_in&>(local).sin_port);
}
bool route_virtual(int s, Sock& socket) {
if (socket.virtualRoute) return true;
if (!socket.bound) {
sockaddr_in any{};
any.sin_family = AF_INET;
if (::bind(socket.native->value, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) != 0) return false;
}
const auto port = native_port(*socket.native);
if (!VirtualNet::Register(Online::Wire::DatagramKind::Udp, port, 0, port, s)) return false;
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it != g_socks.end()) {
it->second.bound = true;
it->second.virtualRoute = true;
}
socket.bound = true;
socket.virtualRoute = true;
return true;
}
std::int64_t send_virtual(int s, Sock& socket, const void* buf, std::size_t len, std::uint32_t peer, std::uint16_t peerPort, std::uint16_t peerVport) {
if (len > Online::Wire::MaxGameDatagram) return fail(NET_EMSGSIZE);
if (!socket.p2p && !route_virtual(s, socket)) return fail(NET_EADDRINUSE);
Online::Wire::Datagram datagram;
datagram.peer = peer;
datagram.peerPort = peerPort;
datagram.peerVport = socket.p2p ? peerVport : 0;
datagram.localPort = socket.p2p ? socket.gamePort : native_port(*socket.native);
datagram.localVport = socket.p2p ? socket.gameVport : 0;
datagram.kind = socket.p2p ? Online::Wire::DatagramKind::P2p : Online::Wire::DatagramKind::Udp;
if (len) datagram.data.assign(static_cast<const std::uint8_t*>(buf), static_cast<const std::uint8_t*>(buf) + len);
VirtualNet::Send(datagram);
return static_cast<std::int64_t>(len);
}
struct VirtualReceived {
std::int64_t length = 0;
bool fromVirtual = false;
VirtualNet::Source source;
sockaddr_storage peer{};
};
std::optional<VirtualReceived> receive_virtual(const Sock& socket, int flags, char* buf, std::size_t len) {
std::vector<char> buffer;
try {
buffer.resize(len + VirtualNet::HeaderSize);
} catch (const std::bad_alloc&) {
errno = ENOBUFS;
return std::nullopt;
}
VirtualReceived received;
NativeLength peer_length = sizeof(received.peer);
const int result = native_transfer(*socket.native, flags, false, [&](int) {
peer_length = sizeof(received.peer);
return ::recvfrom(socket.native->value, buffer.data(), static_cast<int>(buffer.size()), native_message_flags(flags),
reinterpret_cast<sockaddr*>(&received.peer), &peer_length);
});
if (result < 0) return std::nullopt;
const auto* bytes = reinterpret_cast<const std::uint8_t*>(buffer.data());
std::size_t offset = 0;
std::size_t size = static_cast<std::size_t>(result);
if (VirtualNet::FromRelay(received.peer)) {
if (const auto source = VirtualNet::ReadHeader({bytes, size})) {
received.fromVirtual = true;
received.source = *source;
offset = VirtualNet::HeaderSize;
size -= VirtualNet::HeaderSize;
}
}
const auto copied = std::min(size, len);
if (copied) std::memcpy(buf, buffer.data() + offset, copied);
received.length = static_cast<std::int64_t>(copied);
return received;
}
extern "C" {
extern const std::uint32_t sce_net_in6addr_any[4] = {};
alignas(std::uint32_t) extern const std::uint8_t sce_net_in6addr_linklocal_allnodes[16] = {0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
int* APS5_VABI sceNetErrnoLoc(void) {
return errno_slot();
}
int APS5_VABI sceNetShowNetstat(void) {
std::lock_guard lock(g_mutex);
if (!g_net_inited) return fail(NET_ENOTINIT);
std::fprintf(stderr, "[sceNet] %zu socket(s)\n", g_socks.size());
for (const auto& [id, sock] : g_socks) {
const char* family = sock.family == NET_AF_INET6 ? "inet6" : "inet";
const char* type = sock.type == NET_SOCK_STREAM ? "stream" : sock.type == NET_SOCK_DGRAM ? "dgram" : "raw";
const char* state = sock.listening ? "listen" : sock.bound ? "bound" : "-";
std::fprintf(stderr, "[sceNet] %d %s %s %s%s\n", id, family, type, state, sock.native && sock.native->nonblock ? " nbio" : "");
}
std::fflush(stderr);
return 0;
}
int PollSockets(KernelSocketPoll::Entry* entries, int count, int timeoutMilliseconds) {
std::vector<std::shared_ptr<NativeSocketHandle>> natives(static_cast<std::size_t>(count));
{
std::lock_guard lk(g_mutex);
for (int index = 0; index < count; ++index) {
const auto socket = g_socks.find(entries[index].descriptor);
if (socket != g_socks.end()) natives[static_cast<std::size_t>(index)] = socket->second.native;
}
}
#ifdef _WIN32
std::vector<WSAPOLLFD> descriptors;
constexpr short NativeReadable = POLLRDNORM;
constexpr short NativeUrgent = POLLRDBAND;
constexpr short NativeWritable = POLLWRNORM;
#else
std::vector<pollfd> descriptors;
constexpr short NativeReadable = POLLIN;
constexpr short NativeUrgent = POLLPRI;