/
sceNetAdhoc.cpp
6865 lines (5660 loc) · 234 KB
/
sceNetAdhoc.cpp
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
// Copyright (c) 2013- PPSSPP Project.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0 or later versions.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#if defined(_WIN32)
#include "Common/CommonWindows.h"
#endif
#if !defined(_WIN32)
#include <netinet/tcp.h>
#endif
#ifndef MSG_NOSIGNAL
// Default value to 0x00 (do nothing) in systems where it's not supported.
#define MSG_NOSIGNAL 0x00
#endif
#include <mutex>
#include "thread/threadutil.h"
// sceNetAdhoc
// This is a direct port of Coldbird's code from http://code.google.com/p/aemu/
// All credit goes to him!
#include "Core/Core.h"
#include "Core/Host.h"
#include "Core/Reporting.h"
#include "Core/MemMapHelpers.h"
#include "Common/Serialize/Serializer.h"
#include "Common/Serialize/SerializeFuncs.h"
#include "Common/Serialize/SerializeMap.h"
#include "Common/TimeUtil.h"
#include "Core/MIPS/MIPSCodeUtils.h"
#include "Core/Util/PortManager.h"
#include "Core/HLE/HLEHelperThread.h"
#include "Core/HLE/FunctionWrappers.h"
#include "Core/HLE/sceKernelThread.h"
#include "Core/HLE/sceKernel.h"
#include "Core/HLE/sceKernelMemory.h"
#include "Core/HLE/sceKernelModule.h"
#include "Core/HLE/sceKernelInterrupt.h"
#include "Core/HLE/sceNetAdhoc.h"
#include "Core/HLE/sceNet.h"
#include "Core/HLE/proAdhocServer.h"
#include "Core/HLE/KernelWaitHelpers.h"
#include "i18n/i18n.h"
// shared in sceNetAdhoc.h since it need to be used from sceNet.cpp also
// TODO: Make accessor functions instead, and throw all this state in a struct.
bool netAdhocInited;
bool netAdhocctlInited;
bool networkInited = false;
bool netAdhocGameModeEntered;
bool netAdhocMatchingInited;
int netAdhocMatchingStarted = 0;
int adhocDefaultTimeout = 2000; //5000 ms
int adhocExtraPollDelayMS = 10; //10
int adhocEventPollDelayMS = 100; //100; Seems to be the same with PSP_ADHOCCTL_RECV_TIMEOUT
int adhocMatchingEventDelayMS = 30; //30
int adhocEventDelayMS = 300; //500; This will affect the duration of "Connecting..." dialog/message box in .Hack//Link and Naruto Ultimate Ninja Heroes 3
SceUID threadAdhocID;
std::recursive_mutex adhocEvtMtx;
std::deque<std::pair<u32, u32>> adhocctlEvents;
std::deque<MatchingArgs> matchingEvents;
std::map<int, AdhocctlHandler> adhocctlHandlers;
std::vector<SceUID> matchingThreads;
int IsAdhocctlInCB = 0;
int adhocctlNotifyEvent = -1;
int adhocSocketNotifyEvent = -1;
std::map<int, AdhocctlRequest> adhocctlRequests;
std::map<u64, AdhocSocketRequest> adhocSocketRequests;
std::map<u64, AdhocSendTargets> sendTargetPeers;
int gameModeNotifyEvent = -1;
u32 dummyThreadHackAddr = 0;
u32_le dummyThreadCode[3];
u32 matchingThreadHackAddr = 0;
u32_le matchingThreadCode[3];
int matchingEventThread(int matchingId);
int matchingInputThread(int matchingId);
int AcceptPtpSocket(int ptpId, int newsocket, sockaddr_in& peeraddr, SceNetEtherAddr* addr, u16_le* port);
int PollAdhocSocket(SceNetAdhocPollSd* sds, int count, int timeout);
int FlushPtpSocket(int socketId);
int NetAdhocctl_ExitGameMode();
static int sceNetAdhocPdpSend(int id, const char* mac, u32 port, void* data, int len, int timeout, int flag);
static int sceNetAdhocPdpRecv(int id, void* addr, void* port, void* buf, void* dataLength, u32 timeout, int flag);
void __NetAdhocShutdown() {
// Kill AdhocServer Thread
if (adhocServerRunning) {
adhocServerRunning = false;
if (adhocServerThread.joinable()) {
adhocServerThread.join();
}
}
// Checks to avoid confusing logspam
if (netAdhocMatchingInited) {
NetAdhocMatching_Term();
}
if (netAdhocctlInited) {
NetAdhocctl_Term();
}
if (netAdhocInited) {
NetAdhoc_Term();
}
if (dummyThreadHackAddr) {
kernelMemory.Free(dummyThreadHackAddr);
dummyThreadHackAddr = 0;
}
if (matchingThreadHackAddr) {
kernelMemory.Free(matchingThreadHackAddr);
matchingThreadHackAddr = 0;
}
}
bool IsGameModeActive() {
return netAdhocGameModeEntered && gameModeBuffer != nullptr && gameModeSocket > 0 && adhocSockets[gameModeSocket - 1] != nullptr;
}
static void __GameModeNotify(u64 userdata, int cyclesLate) {
SceUID threadID = userdata >> 32;
int uid = (int)(userdata & 0xFFFFFFFF);
// TODO: May be we should check for timeout too? since EnterGammeMode have timeout arg
if (IsGameModeActive()) {
auto sock = adhocSockets[gameModeSocket - 1];
// Send Master data
if (masterGameModeArea.dataUpdated) {
for (auto& gma : replicaGameModeAreas) {
if (IsGameModeActive() && IsSocketReady(sock->data.pdp.id, false, true) > 0) {
int sent = sceNetAdhocPdpSend(gameModeSocket, (const char*)&gma.mac, ADHOC_GAMEMODE_PORT, masterGameModeArea.data, masterGameModeArea.size, 0, ADHOC_F_NONBLOCK);
if (sent >= 0) {
masterGameModeArea.dataUpdated = 0;
DEBUG_LOG(SCENET, "GameMode Sent %d bytes to %s", masterGameModeArea.size, mac2str(&gma.mac).c_str());
}
}
}
}
// Recv new Replica data
while (IsGameModeActive() && IsSocketReady(sock->data.pdp.id, true, false) > 0) {
SceNetEtherAddr sendermac;
s32_le senderport = ADHOC_GAMEMODE_PORT;
s32_le bufsz = GAMEMODE_BUFFER_SIZE;
int ret = sceNetAdhocPdpRecv(gameModeSocket, &sendermac, &senderport, gameModeBuffer, &bufsz, 0, ADHOC_F_NONBLOCK);
if (ret >= 0 && bufsz > 0) {
for (auto& gma : replicaGameModeAreas) {
if (IsMatch(gma.mac, sendermac)) {
DEBUG_LOG(SCENET, "GameMode Received %d bytes of new Data for Area [%s]", bufsz, mac2str(&sendermac).c_str());
memcpy(gma.data, gameModeBuffer, std::min(gma.size, bufsz));
gma.dataUpdated = 1;
gma.updateTimestamp = CoreTiming::GetGlobalTimeUsScaled();
break;
}
}
}
}
// ReSchedule
CoreTiming::ScheduleEvent(usToCycles(GAMEMODE_UPDATE_INTERVAL) - cyclesLate, gameModeNotifyEvent, userdata);
return;
}
INFO_LOG(SCENET, "GameMode Scheduler (%d) has finished", uid);
}
static void __AdhocctlNotify(u64 userdata, int cyclesLate) {
SceUID threadID = userdata >> 32;
int uid = (int)(userdata & 0xFFFFFFFF);
s64 result = 0;
u32 error = 0;
SceUID waitID = __KernelGetWaitID(threadID, WAITTYPE_NET, error);
if (waitID == 0 || error != 0)
return;
// Socket not found?! Should never happened! but if it ever happen should we just exit here or need to wake the thread first?
if (adhocctlRequests.find(uid) == adhocctlRequests.end()) {
WARN_LOG(SCENET, "sceNetAdhocctl Socket WaitID(%i) not found!", uid);
//__KernelResumeThreadFromWait(threadID, ERROR_NET_ADHOCCTL_BUSY);
return;
}
AdhocctlRequest& req = adhocctlRequests[uid];
int len = 0;
SceNetAdhocctlConnectPacketC2S packet;
memset(&packet, 0, sizeof(packet));
packet.base.opcode = req.opcode;
packet.group = req.group;
switch (req.opcode)
{
case OPCODE_CONNECT:
len = sizeof(packet);
break;
case OPCODE_SCAN:
case OPCODE_DISCONNECT:
len = 1;
break;
}
// Send Packet if it wasn't succesfully sent before
if (len > 0) {
if (IsSocketReady(metasocket, false, true) > 0) {
int ret = send(metasocket, (const char*)&packet, len, MSG_NOSIGNAL);
int sockerr = errno;
if (ret > 0 || (ret == SOCKET_ERROR && sockerr != EAGAIN && sockerr != EWOULDBLOCK)) {
// Prevent from sending again
req.opcode = 0;
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocctl[%i]: Socket Error (%i)", uid, sockerr);
}
}
}
// Now we just need to wait for replies from adhoc server and the change of state
int waitVal = __KernelGetWaitValue(threadID, error);
if (adhocctlState != waitVal && error == 0) {
// Detecting Adhocctl Initialization using waitVal < 0
if (waitVal >= 0 || (waitVal < 0 && (g_Config.bEnableWlan && !networkInited))) {
u64 now = (u64)(real_time_now() * 1000.0);
if (now - adhocctlStartTime <= adhocDefaultTimeout) {
// Try again in another 0.5ms until state matched or timedout.
CoreTiming::ScheduleEvent(usToCycles(500) - cyclesLate, adhocctlNotifyEvent, userdata);
return;
}
else
result = 0; // ERROR_NET_ADHOCCTL_BUSY
}
else
result = 0; // Faking successfully connected to adhoc server
}
__KernelResumeThreadFromWait(threadID, result);
DEBUG_LOG(SCENET, "Returning (WaitID: %d, error: %d) Result (%08x) of sceNetAdhocctl - State: %d", waitID, error, (int)result, adhocctlState);
// We are done with this request
adhocctlRequests.erase(uid);
}
int WaitAdhocctlState(AdhocctlRequest request, int state, int usec, const char* reason) {
int uid = (state < 0) ? 1 : metasocket;
if (adhocctlRequests.find(uid) != adhocctlRequests.end()) {
WARN_LOG(SCENET, "sceNetAdhocctl - WaitID[%d] already existed, Socket is busy!", uid);
return ERROR_NET_ADHOCCTL_BUSY;
}
if (adhocctlNotifyEvent < 0)
adhocctlNotifyEvent = CoreTiming::RegisterEvent("__AdhocctlNotify", __AdhocctlNotify);
u64 param = ((u64)__KernelGetCurThread()) << 32 | uid;
adhocctlStartTime = (u64)(real_time_now() * 1000.0);
adhocctlRequests[uid] = request;
CoreTiming::ScheduleEvent(usToCycles(usec), adhocctlNotifyEvent, param);
__KernelWaitCurThread(WAITTYPE_NET, uid, state, 0, false, reason);
// faked success
return 0;
}
int StartGameModeScheduler() {
if (gameModeSocket < 0)
return -1;
if (gameModeNotifyEvent < 0)
gameModeNotifyEvent = CoreTiming::RegisterEvent("__GameModeNotify", __GameModeNotify);
INFO_LOG(SCENET, "GameMode Scheduler (%d) has started", gameModeSocket);
u64 param = ((u64)__KernelGetCurThread()) << 32 | gameModeSocket;
CoreTiming::ScheduleEvent(usToCycles(GAMEMODE_UPDATE_INTERVAL), gameModeNotifyEvent, param);
return 0;
}
int DoBlockingPdpRecv(int uid, AdhocSocketRequest& req, s64& result) {
sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
socklen_t sinlen = sizeof(sin);
int ret = recvfrom(uid, (char*)req.buffer, *req.length, MSG_PEEK | MSG_NOSIGNAL, (sockaddr*)&sin, &sinlen);
int sockerr = errno;
// Note: UDP must not be received partially, otherwise leftover data in socket's buffer will be discarded
if (ret >= 0 && ret <= *req.length) {
ret = recvfrom(uid, (char*)req.buffer, *req.length, MSG_NOSIGNAL, (sockaddr*)&sin, &sinlen);
// UDP can also receives 0 data, while on TCP receiving 0 data = connection gracefully closed, but not sure whether PDP can send/recv 0 data or not tho
if (ret > 0) {
DEBUG_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Received %u bytes from %s:%u\n", req.id, getLocalPort(uid), ret, inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
// Peer MAC
SceNetEtherAddr mac;
// Find Peer MAC
if (resolveIP(sin.sin_addr.s_addr, &mac)) {
// Provide Sender Information
*req.remoteMAC = mac;
*req.remotePort = ntohs(sin.sin_port) - portOffset;
// Save Length
*req.length = ret;
// Update last recv timestamp
peerlock.lock();
auto peer = findFriend(&mac);
if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled();
peerlock.unlock();
}
// Unknown Peer
else {
*req.length = ret;
*req.remotePort = ntohs(sin.sin_port) - portOffset;
WARN_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Received %i bytes from Unknown Peer %s:%u", req.id, getLocalPort(uid), ret, inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
}
}
result = 0;
}
// On Windows: recvfrom on UDP can get error WSAECONNRESET when previous sendto's destination is unreachable (or destination port is not bound yet), may need to disable SIO_UDP_CONNRESET error
else if (sockerr == EAGAIN || sockerr == EWOULDBLOCK || sockerr == ECONNRESET || sockerr == ETIMEDOUT) {
u64 now = (u64)(real_time_now() * 1000000.0);
auto sock = adhocSockets[req.id - 1];
if (sock->flags & ADHOC_F_ALERTRECV) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTRECV;
sock->alerted_flags |= ADHOC_F_ALERTRECV;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
// Try again later
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
else
result = ERROR_NET_ADHOC_INVALID_ARG; // ERROR_NET_ADHOC_DISCONNECTED
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPdpRecv[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPdpSend(int uid, AdhocSocketRequest& req, s64& result, AdhocSendTargets& targetPeers) {
auto sock = adhocSockets[req.id - 1];
auto& pdpsocket = sock->data.pdp;
result = 0;
bool retry = false;
for (auto peer = targetPeers.peers.begin(); peer != targetPeers.peers.end(); ) {
// Fill in Target Structure
sockaddr_in target;
target.sin_family = AF_INET;
target.sin_addr.s_addr = peer->ip;
target.sin_port = htons(peer->port + ((isOriPort && !isPrivateIP(peer->ip)) ? 0 : portOffset));
int ret = sendto(pdpsocket.id, (const char*)req.buffer, targetPeers.length, MSG_NOSIGNAL, (sockaddr*)&target, sizeof(target));
int sockerr = errno;
if (ret >= 0) {
DEBUG_LOG(SCENET, "sceNetAdhocPdpSend[%i:%u](B): Sent %u bytes to %s:%u\n", uid, getLocalPort(pdpsocket.id), ret, inet_ntoa(target.sin_addr), ntohs(target.sin_port));
// Remove successfully sent to peer to prevent sending the same data again during a retry
peer = targetPeers.peers.erase(peer);
}
else {
if (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK || sockerr == ETIMEDOUT)) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (sock->flags & ADHOC_F_ALERTSEND) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTSEND;
sock->alerted_flags |= ADHOC_F_ALERTSEND;
break;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
retry = true;
}
else
// FIXME: Does Broadcast always success? even with timeout/blocking?
result = ERROR_NET_ADHOC_TIMEOUT;
}
++peer;
}
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpSend[%i:%u->%u](B) [size=%i]", sockerr, uid, getLocalPort(pdpsocket.id), ntohs(target.sin_port), targetPeers.length);
}
if (retry)
return -1;
return 0;
}
int DoBlockingPtpSend(int uid, AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
auto& ptpsocket = sock->data.ptp;
// Send Data
int ret = send(uid, (const char*)req.buffer, *req.length, MSG_NOSIGNAL);
int sockerr = errno;
// Success
if (ret > 0) {
// Save Length
*req.length = ret;
DEBUG_LOG(SCENET, "sceNetAdhocPtpSend[%i:%u]: Sent %u bytes to %s:%u\n", req.id, ptpsocket.lport, ret, mac2str(&ptpsocket.paddr).c_str(), ptpsocket.pport);
// Return Success
result = 0;
}
else if (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK || sockerr == ETIMEDOUT)) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (sock->flags & ADHOC_F_ALERTSEND) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTSEND;
sock->alerted_flags |= ADHOC_F_ALERTSEND;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
// Change Socket State. // FIXME: Does Alerted Socket should be closed too?
ptpsocket.state = ADHOC_PTP_STATE_CLOSED;
// Disconnected
result = ERROR_NET_ADHOC_DISCONNECTED;
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPtpSend[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPtpRecv(int uid, AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
auto& ptpsocket = sock->data.ptp;
int ret = recv(uid, (char*)req.buffer, *req.length, MSG_NOSIGNAL);
int sockerr = errno;
// Received Data. POSIX: May received 0 bytes when the remote peer already closed the connection.
if (ret > 0) {
DEBUG_LOG(SCENET, "sceNetAdhocPtpRecv[%i:%u]: Received %u bytes from %s:%u\n", req.id, ptpsocket.lport, ret, mac2str(&ptpsocket.paddr).c_str(), ptpsocket.pport);
// Save Length
*req.length = ret;
// Update last recv timestamp
peerlock.lock();
auto peer = findFriend(&ptpsocket.paddr);
if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled();
peerlock.unlock();
result = 0;
}
else if (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK || sockerr == ETIMEDOUT)) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (sock->flags & ADHOC_F_ALERTRECV) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTRECV;
sock->alerted_flags |= ADHOC_F_ALERTRECV;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
else {
// Change Socket State. // FIXME: Does Alerted Socket should be closed too?
ptpsocket.state = ADHOC_PTP_STATE_CLOSED;
// Disconnected
result = ERROR_NET_ADHOC_DISCONNECTED; // ERROR_NET_ADHOC_INVALID_ARG
}
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPtpRecv[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPtpAccept(int uid, AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
auto& ptpsocket = sock->data.ptp;
sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
socklen_t sinlen = sizeof(sin);
int ret, sockerr;
// Check if listening socket is ready to accept
ret = IsSocketReady(uid, true, false, &sockerr);
if (ret > 0) {
// Accept Connection
ret = accept(uid, (sockaddr*)&sin, &sinlen);
sockerr = errno;
}
// Accepted New Connection
if (ret > 0) {
int newid = AcceptPtpSocket(req.id, ret, sin, req.remoteMAC, req.remotePort);
if (newid > 0)
result = newid;
}
else if (ret == 0 || (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK || sockerr == ETIMEDOUT))) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (sock->flags & ADHOC_F_ALERTACCEPT) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTACCEPT;
sock->alerted_flags |= ADHOC_F_ALERTACCEPT;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
else
result = ERROR_NET_ADHOC_INVALID_ARG; //ERROR_NET_ADHOC_TIMEOUT
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPtpAccept[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPtpConnect(int uid, AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
auto& ptpsocket = sock->data.ptp;
int sockerr;
// Wait for Connection (assuming "connect" has been called before)
int ret = IsSocketReady(uid, false, true, &sockerr);
// Connection is ready
if (ret > 0) {
sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
socklen_t sinlen = sizeof(sin);
getpeername(uid, (sockaddr*)&sin, &sinlen);
// Set Connected State
ptpsocket.state = ADHOC_PTP_STATE_ESTABLISHED;
INFO_LOG(SCENET, "sceNetAdhocPtpConnect[%i:%u]: Established (%s:%u)", req.id, ptpsocket.lport, inet_ntoa(sin.sin_addr), ptpsocket.pport);
// Success
result = 0;
}
// Timeout
else if (ret == 0) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (sock->flags & ADHOC_F_ALERTCONNECT) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTCONNECT;
sock->alerted_flags |= ADHOC_F_ALERTCONNECT;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
else
result = ERROR_NET_ADHOC_CONNECTION_REFUSED; // ERROR_NET_ADHOC_TIMEOUT;
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPtpConnect[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPtpFlush(int uid, AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
auto& ptpsocket = sock->data.ptp;
// Try Sending Empty Data
int sockerr = FlushPtpSocket(uid);
if (sockerr >= 0) {
result = 0;
return 0;
}
else if (sockerr == EAGAIN || sockerr == EWOULDBLOCK || sockerr == ETIMEDOUT) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (sock->flags & ADHOC_F_ALERTFLUSH) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
// FIXME: Should we clear the flag after alert signaled?
sock->flags &= ~ADHOC_F_ALERTFLUSH;
sock->alerted_flags |= ADHOC_F_ALERTFLUSH;
}
else if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
// Change Socket State. // FIXME: Does Alerted Socket should be closed too?
ptpsocket.state = ADHOC_PTP_STATE_CLOSED;
// Disconnected
result = ERROR_NET_ADHOC_DISCONNECTED;
return 0;
}
int DoBlockingAdhocPollSocket(int uid, AdhocSocketRequest& req, s64& result) {
SceNetAdhocPollSd* sds = (SceNetAdhocPollSd*)req.buffer;
int ret = PollAdhocSocket(sds, req.id, 0);
if (ret <= 0) {
u64 now = (u64)(real_time_now() * 1000000.0);
if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else if (ret == 0)
ret = ERROR_NET_ADHOC_TIMEOUT;
else
ret = ERROR_NET_ADHOC_EXCEPTION_EVENT;
if (ret == ERROR_NET_ADHOC_WOULD_BLOCK)
ret = ERROR_NET_ADHOC_TIMEOUT;
}
result = ret;
return 0;
}
static void __AdhocSocketNotify(u64 userdata, int cyclesLate) {
SceUID threadID = userdata >> 32;
int uid = (int)(userdata & 0xFFFFFFFF); // fd/socket id
s64 result = -1;
u32 error = 0;
int delayUS = 500;
SceUID waitID = __KernelGetWaitID(threadID, WAITTYPE_NET, error);
if (waitID == 0 || error != 0)
return;
// Socket not found?! Should never happened! but if it ever happen should we just exit here or need to wake the thread first?
if (adhocSocketRequests.find(userdata) == adhocSocketRequests.end()) {
WARN_LOG(SCENET, "sceNetAdhoc Socket WaitID(%i) on Thread(%i) not found!", uid, threadID);
//__KernelResumeThreadFromWait(threadID, ERROR_NET_ADHOC_TIMEOUT);
return;
}
AdhocSocketRequest req = adhocSocketRequests[userdata];
switch (req.type) {
case PDP_SEND:
if (sendTargetPeers.find(userdata) == sendTargetPeers.end()) {
// No destination peers?
result = 0;
break;
}
if (DoBlockingPdpSend(uid, req, result, sendTargetPeers[userdata])) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
sendTargetPeers.erase(userdata);
break;
case PDP_RECV:
if (DoBlockingPdpRecv(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
case PTP_SEND:
if (DoBlockingPtpSend(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
case PTP_RECV:
if (DoBlockingPtpRecv(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
case PTP_ACCEPT:
if (DoBlockingPtpAccept(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
case PTP_CONNECT:
if (DoBlockingPtpConnect(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
case PTP_FLUSH:
if (DoBlockingPtpFlush(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
case ADHOC_POLL_SOCKET:
if (DoBlockingAdhocPollSocket(uid, req, result)) {
// Try again in another 0.5ms until data available or timedout.
CoreTiming::ScheduleEvent(usToCycles(delayUS) - cyclesLate, adhocSocketNotifyEvent, userdata);
return;
}
break;
}
__KernelResumeThreadFromWait(threadID, result);
DEBUG_LOG(SCENET, "Returning (WaitID: %d, error: %d) Result (%08x) of sceNetAdhoc - SocketID: %d", waitID, error, (int)result, req.id);
// We are done with this socket
adhocSocketRequests.erase(userdata);
}
// input threadSocketId = ((u64)__KernelGetCurThread()) << 32 | socketId;
int WaitBlockingAdhocSocket(u64 threadSocketId, int type, int pspSocketId, void* buffer, s32_le* len, u32 timeoutUS, SceNetEtherAddr* remoteMAC, u16_le* remotePort, const char* reason) {
int uid = (int)(threadSocketId & 0xFFFFFFFF);
if (adhocSocketRequests.find(threadSocketId) != adhocSocketRequests.end()) {
WARN_LOG(SCENET, "sceNetAdhoc - WaitID[%d] already existed, Socket[%d] is busy!", uid, pspSocketId);
return ERROR_NET_ADHOC_BUSY;
}
if (adhocSocketNotifyEvent < 0)
adhocSocketNotifyEvent = CoreTiming::RegisterEvent("__AdhocSocketNotify", __AdhocSocketNotify);
//changeBlockingMode(socketId, 1);
u32 tmout = timeoutUS;
if (tmout > 0)
tmout = std::max(tmout, minSocketTimeoutUS);
u64 startTime = (u64)(real_time_now() * 1000000.0);
adhocSocketRequests[threadSocketId] = { type, pspSocketId, buffer, len, tmout, startTime, remoteMAC, remotePort };
// Some games (ie. Power Stone Collection) are using as small as 100 usec timeout
CoreTiming::ScheduleEvent(usToCycles(100), adhocSocketNotifyEvent, threadSocketId);
__KernelWaitCurThread(WAITTYPE_NET, uid, 0, 0, false, reason);
// Fallback return value
return ERROR_NET_ADHOC_TIMEOUT;
}
void netAdhocValidateLoopMemory() {
// Allocate Memory if it wasn't valid/allocated after loaded from old SaveState
if (!dummyThreadHackAddr || (dummyThreadHackAddr && strcmp("dummythreadhack", kernelMemory.GetBlockTag(dummyThreadHackAddr)) != 0)) {
u32 blockSize = sizeof(dummyThreadCode);
dummyThreadHackAddr = kernelMemory.Alloc(blockSize, false, "dummythreadhack");
if (dummyThreadHackAddr) Memory::Memcpy(dummyThreadHackAddr, dummyThreadCode, sizeof(dummyThreadCode));
}
if (!matchingThreadHackAddr || (matchingThreadHackAddr && strcmp("matchingThreadHack", kernelMemory.GetBlockTag(matchingThreadHackAddr)) != 0)) {
u32 blockSize = sizeof(matchingThreadCode);
matchingThreadHackAddr = kernelMemory.Alloc(blockSize, false, "matchingThreadHack");
if (matchingThreadHackAddr) Memory::Memcpy(matchingThreadHackAddr, matchingThreadCode, sizeof(matchingThreadCode));
}
}
void __NetAdhocDoState(PointerWrap &p) {
auto s = p.Section("sceNetAdhoc", 1, 6);
if (!s)
return;
auto cur_netAdhocInited = netAdhocInited;
auto cur_netAdhocctlInited = netAdhocctlInited;
auto cur_netAdhocMatchingInited = netAdhocMatchingInited;
Do(p, netAdhocInited);
Do(p, netAdhocctlInited);
Do(p, netAdhocMatchingInited);
Do(p, adhocctlHandlers);
if (s >= 2) {
Do(p, actionAfterMatchingMipsCall);
if (actionAfterMatchingMipsCall != -1) {
__KernelRestoreActionType(actionAfterMatchingMipsCall, AfterMatchingMipsCall::Create);
}
Do(p, dummyThreadHackAddr);
}
else {
actionAfterMatchingMipsCall = -1;
dummyThreadHackAddr = 0;
}
if (s >= 3) {
Do(p, actionAfterAdhocMipsCall);
if (actionAfterAdhocMipsCall != -1) {
__KernelRestoreActionType(actionAfterAdhocMipsCall, AfterAdhocMipsCall::Create);
}
Do(p, matchingThreadHackAddr);
}
else {
actionAfterAdhocMipsCall = -1;
matchingThreadHackAddr = 0;
}
if (s >= 4) {
Do(p, threadAdhocID);
Do(p, matchingThreads);
}
else {
threadAdhocID = 0;
for (auto& it : matchingThreads) {
it = 0;
}
}
if (s >= 5) {
Do(p, adhocConnectionType);
Do(p, adhocctlState);
Do(p, adhocctlNotifyEvent);
if (adhocctlNotifyEvent != -1) {
CoreTiming::RestoreRegisterEvent(adhocctlNotifyEvent, "__AdhocctlNotify", __AdhocctlNotify);
}
Do(p, adhocSocketNotifyEvent);
if (adhocSocketNotifyEvent != -1) {
CoreTiming::RestoreRegisterEvent(adhocSocketNotifyEvent, "__AdhocSocketNotify", __AdhocSocketNotify);
}
}
else {
adhocConnectionType = ADHOC_CONNECT;
adhocctlState = ADHOCCTL_STATE_DISCONNECTED;
adhocctlNotifyEvent = -1;
adhocSocketNotifyEvent = -1;
}
if (s >= 6) {
Do(p, gameModeNotifyEvent);
if (gameModeNotifyEvent != -1) {
CoreTiming::RestoreRegisterEvent(gameModeNotifyEvent, "__GameModeNotify", __GameModeNotify);
}
}
else {
gameModeNotifyEvent = -1;
}
if (p.mode == p.MODE_READ) {
// Discard leftover events
adhocctlEvents.clear();
matchingEvents.clear();
adhocctlRequests.clear();
adhocSocketRequests.clear();
sendTargetPeers.clear();
// Let's not change "Inited" value when Loading SaveState to prevent memory & port leaks
netAdhocMatchingInited = cur_netAdhocMatchingInited;
netAdhocctlInited = cur_netAdhocctlInited;
netAdhocInited = cur_netAdhocInited;
}
}
void __UpdateAdhocctlHandlers(u32 flag, u32 error) {
std::lock_guard<std::recursive_mutex> adhocGuard(adhocEvtMtx);
adhocctlEvents.push_back({ flag, error });
}
void __UpdateMatchingHandler(MatchingArgs ArgsPtr) {
std::lock_guard<std::recursive_mutex> adhocGuard(adhocEvtMtx);
matchingEvents.push_back(ArgsPtr);
}
u32_le __CreateHLELoop(u32_le *loopAddr, const char *sceFuncName, const char *hleFuncName, const char *tagName) {
if (loopAddr == NULL || sceFuncName == NULL || hleFuncName == NULL)
return 0;
loopAddr[0] = MIPS_MAKE_SYSCALL(sceFuncName, hleFuncName);
loopAddr[1] = MIPS_MAKE_B(-2);
loopAddr[2] = MIPS_MAKE_NOP();
u32 blockSize = sizeof(u32_le)*3;
u32_le dummyThreadHackAddr = kernelMemory.Alloc(blockSize, false, tagName); // blockSize will be rounded to 256 granularity
Memory::Memcpy(dummyThreadHackAddr, loopAddr, sizeof(u32_le) * 3); // This area will be cleared again after loading an old savestate :(
return dummyThreadHackAddr;
}
void __AdhocNotifInit() {
adhocctlNotifyEvent = CoreTiming::RegisterEvent("__AdhocctlNotify", __AdhocctlNotify);
adhocSocketNotifyEvent = CoreTiming::RegisterEvent("__AdhocSocketNotify", __AdhocSocketNotify);
gameModeNotifyEvent = CoreTiming::RegisterEvent("__GameModeNotify", __GameModeNotify);
adhocctlRequests.clear();
adhocSocketRequests.clear();
sendTargetPeers.clear();
}
void __NetAdhocInit() {
friendFinderRunning = false;
netAdhocInited = false;
netAdhocctlInited = false;
netAdhocMatchingInited = false;
adhocctlHandlers.clear();
__AdhocNotifInit();
__AdhocServerInit();
// Create built-in AdhocServer Thread
if (g_Config.bEnableWlan && g_Config.bEnableAdhocServer) {
adhocServerRunning = true;
adhocServerThread = std::thread(proAdhocServerThread, SERVER_PORT);
}
}
u32 sceNetAdhocInit() {
if (!netAdhocInited) {
// Library initialized
netAdhocInited = true;
// Return Success
return hleLogSuccessInfoI(SCENET, 0, "at %08x", currentMIPS->pc);
}
// Already initialized
return hleLogWarning(SCENET, ERROR_NET_ADHOC_ALREADY_INITIALIZED, "already initialized");
}
static u32 sceNetAdhocctlInit(int stackSize, int prio, u32 productAddr) {
INFO_LOG(SCENET, "sceNetAdhocctlInit(%i, %i, %08x) at %08x", stackSize, prio, productAddr, currentMIPS->pc);
if (netAdhocctlInited)
return ERROR_NET_ADHOCCTL_ALREADY_INITIALIZED;
if (Memory::IsValidAddress(productAddr)) {
Memory::ReadStruct(productAddr, &product_code);
}
adhocctlEvents.clear();
netAdhocctlInited = true; //needed for cleanup during AdhocctlTerm even when it failed to connect to Adhoc Server (since it's being faked as success)
// Create fake PSP Thread for callback
// TODO: Should use a separated threads for friendFinder, matchingEvent, and matchingInput and created on AdhocctlInit & AdhocMatchingStart instead of here
netAdhocValidateLoopMemory();
threadAdhocID = __KernelCreateThread("AdhocThread", __KernelGetCurThreadModuleId(), dummyThreadHackAddr, prio, stackSize, PSP_THREAD_ATTR_USER, 0, true);
if (threadAdhocID > 0) {
__KernelStartThread(threadAdhocID, 0, 0);
}
// TODO: Merging friendFinder (real) thread to AdhocThread (fake) thread on PSP side
if (!friendFinderRunning) {
friendFinderRunning = true;
friendFinderThread = std::thread(friendFinder);
}
// Need to make sure to be connected to adhoc server before returning to prevent GTA VCS failed to create/join a group and unable to see any game room
int us = adhocExtraPollDelayMS * 1000;
if (g_Config.bEnableWlan && !networkInited) {
AdhocctlRequest dummyreq = { OPCODE_LOGIN, {0} };
return WaitAdhocctlState(dummyreq, -1, us, "adhocctl init");
}
// Give a little time for friendFinder thread to be ready before the game use the next sceNet functions, should've checked for friendFinderRunning status instead of guessing the time?
else
hleDelayResult(0, "give some time", us);
return 0;
}
int NetAdhocctl_GetState() {
return adhocctlState;
}
int sceNetAdhocctlGetState(u32 ptrToStatus) {
// Library uninitialized