Repository navigation
Expand file tree
/
Copy pathExport.cpp
More file actions
1727 lines (1613 loc) · 65 KB
/
Copy pathExport.cpp
File metadata and controls
1727 lines (1613 loc) · 65 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 <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 <memory>
#include <map>
#include <mutex>
#include <new>
#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/libkernel/Socket/include/SocketPoll.hpp"
// Guest socket descriptors retain PS5 semantics while their transport is backed by host sockets.
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_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_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_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_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_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) {
switch (code) {
case WSAEWOULDBLOCK: return NET_EAGAIN;
case WSAEINPROGRESS: return NET_EINPROGRESS;
case WSAEALREADY: return NET_EALREADY;
case WSAEADDRINUSE: return NET_EADDRINUSE;
case WSAEADDRNOTAVAIL: return NET_EADDRNOTAVAIL;
case WSAEAFNOSUPPORT: return NET_EAFNOSUPPORT;
case WSAENETUNREACH: return NET_ENETUNREACH;
case WSAEHOSTUNREACH: return NET_EHOSTUNREACH;
case WSAECONNABORTED: return NET_ECONNABORTED;
case WSAENOBUFS: return NET_ENOBUFS;
case WSAEISCONN: return NET_EISCONN;
case WSAENOTCONN: return NET_ENOTCONN;
case WSAEACCES: return NET_EACCES;
case WSAECONNRESET: return 54;
case WSAETIMEDOUT: return NET_ETIMEDOUT;
case WSAECONNREFUSED: return NET_ECONNREFUSED;
case WSAEMSGSIZE: return NET_EMSGSIZE;
case WSAEINTR: return 4;
case WSAEINVAL: return NET_EINVAL;
case WSAENOTSOCK: return NET_ENOTSOCK;
case WSAESHUTDOWN: return 32;
default: return 5;
}
}
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) {
switch (code) {
case EAGAIN: return NET_EAGAIN;
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK: return NET_EAGAIN;
#endif
case EINPROGRESS: return NET_EINPROGRESS;
case EALREADY: return NET_EALREADY;
case EADDRINUSE: return NET_EADDRINUSE;
case EADDRNOTAVAIL: return NET_EADDRNOTAVAIL;
case EAFNOSUPPORT: return NET_EAFNOSUPPORT;
case ENETUNREACH: return NET_ENETUNREACH;
case EHOSTUNREACH: return NET_EHOSTUNREACH;
case ECONNABORTED: return NET_ECONNABORTED;
case ENOBUFS: return NET_ENOBUFS;
case EISCONN: return NET_EISCONN;
case ENOTCONN: return NET_ENOTCONN;
case EACCES: return NET_EACCES;
case ECONNRESET: return 54;
case ETIMEDOUT: return NET_ETIMEDOUT;
case ECONNREFUSED: return NET_ECONNREFUSED;
case EMSGSIZE: return NET_EMSGSIZE;
case EINTR: return 4;
case EINVAL: return NET_EINVAL;
case ENOTSOCK: return NET_ENOTSOCK;
case EPIPE: return 32;
default: return 5;
}
}
int native_error() { return net_error(errno); }
#endif
struct NativeSocketHandle {
NativeSocket value;
explicit NativeSocketHandle(NativeSocket socket) : value(socket) {}
~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 nonblock = false;
bool bound = false;
bool listening = false;
bool aborted = false;
bool read_shut = false;
int rcv_timeout_us = 0;
int snd_timeout_us = 0;
int reported_error = 0;
int snd_buffer = 0;
int rcv_buffer = 0;
int onesbcast = 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;
std::map<int, std::map<int, NetEpollEvent>> g_epoll_socks;
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;
int* errno_slot() {
static thread_local int e = 0;
return &e;
}
extern "C" int* APS5_VABI __error_nid_postfix();
void set_errno(int err) {
*errno_slot() = err;
*__error_nid_postfix() = err;
}
int fail(int err) {
set_errno(err);
return NET_ERROR_BASE | err;
}
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.rcv_timeout_us = stored;
else it->second.snd_timeout_us = 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);
}
int receive_error(const Sock& socket) {
#ifdef _WIN32
if (WSAGetLastError() == WSAETIMEDOUT && socket.type != NET_SOCK_STREAM && socket.rcv_timeout_us > 0) return NET_EAGAIN;
#else
(void)socket;
#endif
return native_error();
}
bool message_flags_supported(int flags, int accepted) {
#ifdef _WIN32
accepted &= ~NET_MSG_DONTWAIT;
#endif
return (flags & ~accepted) == 0;
}
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;
}
#ifdef _WIN32
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;
}
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();
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;
}
int wait_for_local_address(int s, const Sock& socket, bool empty) {
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.nonblock) return NET_EAGAIN;
const auto deadline = socket.rcv_timeout_us > 0
? std::chrono::steady_clock::now() + std::chrono::microseconds(socket.rcv_timeout_us)
: 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
} // namespace
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) {
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;
constexpr short NativeWritable = POLLOUT;
#endif
std::vector<int> owners;
for (int index = 0; index < count; ++index) {
auto& entry = entries[index];
if (!natives[static_cast<std::size_t>(index)]) {
entry.revents = KernelSocketPoll::Unknown;
continue;
}
decltype(descriptors)::value_type descriptor{};
descriptor.fd = natives[static_cast<std::size_t>(index)]->value;
if (entry.events & KernelSocketPoll::Readable) descriptor.events |= NativeReadable;
if (entry.events & KernelSocketPoll::Urgent) descriptor.events |= NativeUrgent;
if (entry.events & KernelSocketPoll::Writable) descriptor.events |= NativeWritable;
descriptors.push_back(descriptor);
owners.push_back(index);
}
if (descriptors.empty()) return 0;
#ifdef _WIN32
const int result = WSAPoll(descriptors.data(), static_cast<ULONG>(descriptors.size()), timeoutMilliseconds);
#else
const int result = ::poll(descriptors.data(), descriptors.size(), timeoutMilliseconds);
#endif
if (result < 0) return -native_error();
int ready = 0;
for (std::size_t index = 0; index < descriptors.size(); ++index) {
const short native = descriptors[index].revents;
short revents = 0;
if (native & NativeReadable) revents |= KernelSocketPoll::Readable;
if (native & NativeUrgent) revents |= KernelSocketPoll::Urgent;
if (native & NativeWritable) revents |= KernelSocketPoll::Writable;
if (native & (POLLERR | POLLNVAL)) revents |= KernelSocketPoll::Error;
if (native & POLLHUP) revents |= KernelSocketPoll::HangUp;
entries[owners[index]].revents = revents;
if (revents != 0) ++ready;
}
return ready;
}
const bool g_socketPollerRegistered = (KernelSetSocketPoller_nid_no_patch(&PollSockets), true);
extern "C" int APS5_VABI sceNetSocketClose(int s);
bool CloseSocketForKernel(int descriptor, int* error) {
{
std::lock_guard lk(g_mutex);
if (g_socks.count(descriptor) == 0) return false;
}
*error = sceNetSocketClose(descriptor) == 0 ? 0 : *errno_slot();
return true;
}
const bool g_socketCloserRegistered = (KernelSetSocketCloser_nid_no_patch(&CloseSocketForKernel), true);
extern "C" int APS5_VABI sceNetSetsockopt(int s, int level, int optname, const void* optval, uint32_t optlen);
bool SetSocketOptionForKernel(int descriptor, int level, int option, const void* value, std::uint32_t length, int* error) {
{
std::lock_guard lk(g_mutex);
if (g_socks.count(descriptor) == 0) return false;
}
if (level == NET_SOL_SOCKET && (option == NET_SO_RCVTIMEO || option == NET_SO_SNDTIMEO)) {
*error = set_kernel_timeout(descriptor, option, value, length);
if (*error != 0) set_errno(*error);
return true;
}
*error = sceNetSetsockopt(descriptor, level, option, value, length) == 0 ? 0 : *errno_slot();
return true;
}
const bool g_socketOptionSetterRegistered = (KernelSetSocketOptionSetter_nid_no_patch(&SetSocketOptionForKernel), true);
constexpr int GuestFcntlGetStatus = 3;
constexpr int GuestFcntlSetStatus = 4;
constexpr int GuestReadWrite = 2;
constexpr int GuestNonblocking = 4;
constexpr int GuestStatusFlagsMask = 7;
bool ControlSocketStatusForKernel(int descriptor, int command, int flags, int* result, int* error) {
bool nonblock = false;
{
std::lock_guard lk(g_mutex);
const auto it = g_socks.find(descriptor);
if (it == g_socks.end()) return false;
nonblock = it->second.nonblock;
}
*result = 0;
*error = 0;
if (command == GuestFcntlGetStatus) {
*result = GuestReadWrite | (nonblock ? GuestNonblocking : 0);
return true;
}
if (command != GuestFcntlSetStatus) {
*error = NET_EINVAL;
return true;
}
if ((flags & ~GuestStatusFlagsMask) != 0) {
*error = NET_EOPNOTSUPP;
return true;
}
const int enabled = (flags & GuestNonblocking) != 0 ? 1 : 0;
if (sceNetSetsockopt(descriptor, NET_SOL_SOCKET, NET_SO_NBIO, &enabled, sizeof(enabled)) != 0) *error = *errno_slot();
return true;
}
const bool g_socketStatusControlRegistered = (KernelSetSocketStatusControl_nid_no_patch(&ControlSocketStatusForKernel), true);
bool FindSocketNativeForKernel(int descriptor, std::shared_ptr<void>* owner, std::uintptr_t* native) {
std::lock_guard lk(g_mutex);
const auto it = g_socks.find(descriptor);
if (it == g_socks.end() || !it->second.native) return false;
*native = static_cast<std::uintptr_t>(it->second.native->value);
*owner = it->second.native;
return true;
}
const bool g_socketNativeLookupRegistered = (KernelSetSocketNativeLookup_nid_no_patch(&FindSocketNativeForKernel), true);
int APS5_VABI sceNetInit_nid_postfix(void) {
std::lock_guard lk(g_mutex);
g_net_inited = true;
return 0;
}
int APS5_VABI sceNetTerm(void) {
std::lock_guard lk(g_mutex);
g_net_inited = false;
return 0;
}
int APS5_VABI sceNetPoolCreate(const char* name, int size, int flags) {
(void)name;
(void)flags;
if (size <= 0) {
return fail(NET_EINVAL);
}
std::lock_guard lk(g_mutex);
const int id = g_next_pool++;
g_pools.emplace(id, static_cast<std::size_t>(size));
return id;
}
int APS5_VABI sceNetPoolDestroy(int memid) {
std::lock_guard lk(g_mutex);
return g_pools.erase(memid) != 0 ? 0 : fail(NET_EBADF);
}
int APS5_VABI sceNetSocket(const char* name, int family, int type, int protocol) {
(void)name;
if (family != NET_AF_INET && family != NET_AF_INET6) {
return fail(NET_EAFNOSUPPORT);
}
if (type != NET_SOCK_STREAM && type != NET_SOCK_DGRAM && type != NET_SOCK_RAW) {
return fail(NET_EPROTONOSUPPORT);
}
if (!initialize_sockets()) return fail(5);
const NativeSocket native = ::socket(family == NET_AF_INET ? AF_INET : AF_INET6, type, protocol);
if (native == INVALID_NATIVE_SOCKET) return fail(native_error());
const int ipv6_only = 1;
if (family == NET_AF_INET6 &&
::setsockopt(native, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&ipv6_only), sizeof(ipv6_only)) != 0) {
const int error = native_error();
close_socket(native);
return fail(error);
}
std::shared_ptr<NativeSocketHandle> handle;
try {
handle = std::make_shared<NativeSocketHandle>(native);
} catch (const std::bad_alloc&) {
close_socket(native);
return fail(12);
}
const int fd = KernelReserveSocketNumber_nid_no_patch(static_cast<std::uintptr_t>(handle->value));
if (fd < 0) return fail(-fd);
std::lock_guard lk(g_mutex);
Sock s;
s.family = family;
s.type = type;
s.native = std::move(handle);
g_socks[fd] = s;
return fd;
}
int APS5_VABI sceNetSocketClose(int s) {
std::shared_ptr<NativeSocketHandle> native;
{
std::lock_guard lk(g_mutex);
const auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
native = it->second.native;
g_socks.erase(it);
}
KernelReleaseSocketNumber_nid_no_patch(s);
if (native) {
#ifdef _WIN32
::shutdown(native->value, SD_BOTH);
#else
::shutdown(native->value, SHUT_RDWR);
#endif
}
g_cv.NotifyAll();
return 0;
}
int APS5_VABI sceNetSocketAbort(int s, int flags) {
(void)flags;
std::shared_ptr<NativeSocketHandle> native;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
it->second.aborted = true;
native = it->second.native;
}
#ifdef _WIN32
if (native) ::shutdown(native->value, SD_BOTH);
#else
if (native) ::shutdown(native->value, SHUT_RDWR);
#endif
g_cv.NotifyAll();
return 0;
}
int APS5_VABI sceNetBind_nid_postfix(int s, const void* addr, uint32_t addrlen) {
Sock socket;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
socket = it->second;
if (it->second.bound) return fail(NET_EINVAL);
}
sockaddr_storage native{};
NativeLength native_length = 0;
if (!guest_to_native_address(addr, addrlen, native, native_length)) return fail(NET_EINVAL);
if (native.ss_family != (socket.family == NET_AF_INET ? AF_INET : AF_INET6)) return fail(NET_EAFNOSUPPORT);
if (::bind(socket.native->value, reinterpret_cast<const sockaddr*>(&native), native_length) != 0)
return fail(native_error());
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it != g_socks.end()) it->second.bound = true;
g_cv.NotifyAll();
return 0;
}
int APS5_VABI sceNetListen(int s, int backlog) {
Sock socket;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
socket = it->second;
}
if (socket.type != NET_SOCK_STREAM) return fail(NET_EOPNOTSUPP);
if (::listen(socket.native->value, backlog) != 0) return fail(native_error());
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it != g_socks.end()) {
it->second.bound = true;
it->second.listening = true;
}
return 0;
}
int APS5_VABI sceNetAccept(int s, void* addr, uint32_t* addrlen) {
Sock listener;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
listener = it->second;
}
if (!listener.listening) return fail(NET_EINVAL);
if (addr && !addrlen) return fail(NET_EINVAL);
sockaddr_storage peer{};
NativeLength peer_length = sizeof(peer);
const NativeSocket accepted = ::accept(listener.native->value,
addr ? reinterpret_cast<sockaddr*>(&peer) : nullptr, addr ? &peer_length : nullptr);
if (accepted == INVALID_NATIVE_SOCKET) return fail(native_error());
std::shared_ptr<NativeSocketHandle> handle;
try {
handle = std::make_shared<NativeSocketHandle>(accepted);
} catch (const std::bad_alloc&) {
close_socket(accepted);
return fail(12);
}
Sock connection;
connection.family = listener.family;
connection.type = NET_SOCK_STREAM;
connection.native = std::move(handle);
const int descriptor = KernelReserveSocketNumber_nid_no_patch(static_cast<std::uintptr_t>(connection.native->value));
if (descriptor < 0) return fail(-descriptor);
{
std::lock_guard lk(g_mutex);
g_socks.emplace(descriptor, connection);
}
if (addr && !native_to_guest_address(peer, addr, addrlen)) {
sceNetSocketClose(descriptor);
return fail(NET_EAFNOSUPPORT);
}
return descriptor;
}
static std::uint16_t& native_port(sockaddr_storage& address) {
return address.ss_family == AF_INET ? reinterpret_cast<sockaddr_in&>(address).sin_port : reinterpret_cast<sockaddr_in6&>(address).sin6_port;
}
static int disconnect_datagram(const Sock& socket) {
const auto value = socket.native->value;
sockaddr_storage peer{};
NativeLength peer_length = sizeof(peer);
if (::getpeername(value, reinterpret_cast<sockaddr*>(&peer), &peer_length) != 0) return 0;
sockaddr_storage local{};
NativeLength local_length = sizeof(local);
if (::getsockname(value, reinterpret_cast<sockaddr*>(&local), &local_length) != 0) return fail(native_error());
#ifdef _WIN32
sockaddr_storage unspecified{};
unspecified.ss_family = local.ss_family;
if (::connect(value, reinterpret_cast<const sockaddr*>(&unspecified), local_length) != 0) return fail(native_error());
#else
sockaddr unspecified{};
unspecified.sa_family = AF_UNSPEC;
if (::connect(value, &unspecified, sizeof(unspecified)) != 0) return fail(native_error());
#endif
sockaddr_storage current{};
NativeLength current_length = sizeof(current);
if (::getsockname(value, reinterpret_cast<sockaddr*>(¤t), ¤t_length) != 0) return fail(native_error());
if (native_port(current) != 0) return 0;
sockaddr_storage wildcard{};
wildcard.ss_family = local.ss_family;
native_port(wildcard) = native_port(local);
if (::bind(value, reinterpret_cast<const sockaddr*>(&wildcard), local_length) != 0) return fail(native_error());
return 0;
}
#ifdef _WIN32
extern "C" void RefuseClosedLoopbackAtOnce_nid_no_patch(SOCKET socket, const sockaddr* address);
#endif
int APS5_VABI sceNetConnect(int s, const void* addr, uint32_t addrlen) {
Sock socket;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
it->second.reported_error = 0;
socket = it->second;
}
if (socket.type == NET_SOCK_DGRAM && addr && addrlen >= 2 && static_cast<const std::uint8_t*>(addr)[1] == 0) {
if (const int error = disconnect_datagram(socket)) return error;
return fail(NET_EAFNOSUPPORT);
}
sockaddr_storage native{};
NativeLength native_length = 0;
if (!guest_to_native_address(addr, addrlen, native, native_length)) return fail(NET_EINVAL);
#ifdef _WIN32
if (socket.type == NET_SOCK_STREAM) RefuseClosedLoopbackAtOnce_nid_no_patch(socket.native->value, reinterpret_cast<const sockaddr*>(&native));
#endif
if (native.ss_family != (socket.family == NET_AF_INET ? AF_INET : AF_INET6)) return fail(NET_EAFNOSUPPORT);
if (::connect(socket.native->value, reinterpret_cast<const sockaddr*>(&native), native_length) == 0) {
#ifdef _WIN32
note_local_address(s, socket);
#endif
return 0;
}
#ifdef _WIN32
if (WSAGetLastError() == WSAEWOULDBLOCK) return fail(NET_EINPROGRESS);
#endif
return fail(native_error());
}
int64_t APS5_VABI sceNetRecv(int s, void* buf, size_t len, int flags) {
if (!message_flags_supported(flags, NET_MSG_PEEK | NET_MSG_DONTWAIT)) return fail(NET_EOPNOTSUPP);
if (!buf && len) return fail(NET_EINVAL);
if (len > INT_MAX) return fail(NET_EMSGSIZE);
Sock socket;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
socket = it->second;
}
#ifdef _WIN32
if (const int wait = wait_for_local_address(s, socket, len == 0)) return wait == RECEIVE_NOTHING ? 0 : fail(wait);
#endif
const GuestArena::HostWrite destination(len == 0 ? nullptr : buf, len);
if (!destination.Open()) return fail(NET_EFAULT);
const int native_flags = native_message_flags(flags);
const int result = ::recv(socket.native->value, static_cast<char*>(buf), static_cast<int>(len), native_flags);
#ifdef _WIN32
if (result < 0 && socket.type == NET_SOCK_DGRAM && WSAGetLastError() == WSAEMSGSIZE) return static_cast<int64_t>(len);
#endif
return result >= 0 ? result : fail(receive_error(socket));
}
int64_t APS5_VABI sceNetRecvfrom(int s, void* buf, size_t len, int flags, void* from, uint32_t* fromlen) {
if (!message_flags_supported(flags, NET_MSG_PEEK | NET_MSG_DONTWAIT)) return fail(NET_EOPNOTSUPP);
if (!buf && len) return fail(NET_EINVAL);
if (len > INT_MAX) return fail(NET_EMSGSIZE);
if (from && !fromlen) return fail(NET_EINVAL);
Sock socket;
{
std::lock_guard lk(g_mutex);
auto it = g_socks.find(s);
if (it == g_socks.end()) return fail(NET_EBADF);
socket = it->second;
}
#ifdef _WIN32
if (const int wait = wait_for_local_address(s, socket, len == 0)) {
if (wait != RECEIVE_NOTHING) return fail(wait);
if (from) *fromlen = 0;
return 0;
}
#endif
const GuestArena::HostWrite destination(len == 0 ? nullptr : buf, len);
if (!destination.Open()) return fail(NET_EFAULT);
sockaddr_storage peer{};
NativeLength peer_length = sizeof(peer);