-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathsceNetAdhoc.cpp
7873 lines (6559 loc) · 301 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 <WinSock2.h>
#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 "Common/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/Config.h"
#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 "Common/Data/Text/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;
#define DISCOVER_DURATION_US 2000000 // 2 seconds is probably the normal time it takes for PSP to connect to a group (ie. similar to NetconfigDialog time)
u64 netAdhocDiscoverStartTime = 0;
s32 netAdhocDiscoverStatus = NET_ADHOC_DISCOVER_STATUS_NONE;
bool netAdhocDiscoverIsStopping = false;
SceNetAdhocDiscoverParam* netAdhocDiscoverParam = nullptr;
u32 netAdhocDiscoverBufAddr = 0;
bool netAdhocGameModeEntered = false;
int netAdhocEnterGameModeTimeout = 15000000; // 15 sec as default timeout, to wait for all players to join
bool netAdhocMatchingInited;
int netAdhocMatchingStarted = 0;
int adhocDefaultTimeout = 5000000; //2000000 usec // For some unknown reason, sometimes it tooks more than 2 seconds for Adhocctl Init to connect to AdhocServer on localhost (normally only 10 ms), and sometimes it tooks more than 1 seconds for built-in AdhocServer to be ready (normally only 1 ms)
int adhocDefaultDelay = 10000; //10000
int adhocExtraDelay = 20000; //20000
int adhocEventPollDelay = 100000; //100000; // Same timings with PSP_ADHOCCTL_RECV_TIMEOUT ?
int adhocMatchingEventDelay = 30000; //30000
int adhocEventDelay = 2000000; //2000000 on real PSP ?
u32 defaultLastRecvDelta = 10000; //10000 usec worked well for games published by Falcom (ie. Ys vs Sora Kiseki, Vantage Master Portable)
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 adhocctlStateEvent = -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);
void sendBulkDataPacket(SceNetAdhocMatchingContext* context, SceNetEtherAddr* mac, int datalen, void* data);
int AcceptPtpSocket(int ptpId, int newsocket, sockaddr_in& peeraddr, SceNetEtherAddr* addr, u16_le* port);
int PollAdhocSocket(SceNetAdhocPollSd* sds, int count, int timeout, int nonblock);
int FlushPtpSocket(int socketId);
int RecreatePtpSocket(int ptpId);
int NetAdhocGameMode_DeleteMaster();
int NetAdhocctl_ExitGameMode();
int NetAdhocPtp_Connect(int id, int timeout, int flag, bool allowForcedConnect = true);
static int sceNetAdhocPdpCreate(const char* mac, int port, int bufferSize, u32 flag);
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
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 && masterGameModeArea.data;
}
static void __GameModeNotify(u64 userdata, int cyclesLate) {
SceUID threadID = userdata >> 32;
u32 error;
if (IsGameModeActive()) {
// Need to make sure all replicas have been created before we start syncing data
if (replicaGameModeAreas.size() == (gameModeMacs.size() - 1)) {
// Socket's buffer size should fit the largest size from master/replicas, so we waited until Master & all Replicas to be created first before creating the socket, since there are games (ie. Fading Shadows) that use different buffer size for Master and Replica.
if (gameModeSocket < 0 && !isZeroMAC(&masterGameModeArea.mac)) {
u8* buf = (u8*)realloc(gameModeBuffer, gameModeBuffSize);
if (buf)
gameModeBuffer = buf;
if ((gameModeSocket = sceNetAdhocPdpCreate((const char*)&masterGameModeArea.mac, ADHOC_GAMEMODE_PORT, gameModeBuffSize, 0)) < 0) {
ERROR_LOG(SCENET, "GameMode: Failed to create socket (Error %08x)", gameModeSocket);
__KernelResumeThreadFromWait(threadID, gameModeSocket);
return;
}
else
INFO_LOG(SCENET, "GameMode: Synchronizer (%d, %d) has started", gameModeSocket, gameModeBuffSize);
}
if (gameModeSocket < 0) {
// ReSchedule
CoreTiming::ScheduleEvent(usToCycles(GAMEMODE_UPDATE_INTERVAL) - cyclesLate, gameModeNotifyEvent, userdata);
return;
}
auto sock = adhocSockets[gameModeSocket - 1];
if (!sock) {
WARN_LOG(SCENET, "GameMode: Socket (%d) got deleted", gameModeSocket);
u32 waitVal = __KernelGetWaitValue(threadID, error);
if (error == 0) {
__KernelResumeThreadFromWait(threadID, waitVal);
}
return;
}
// Send Master data
if (masterGameModeArea.dataUpdated) {
int sentcount = 0;
for (auto& gma : replicaGameModeAreas) {
if (!gma.dataSent && IsSocketReady(sock->data.pdp.id, false, true) > 0) {
u16_le port = ADHOC_GAMEMODE_PORT;
auto it = gameModePeerPorts.find(gma.mac);
if (it != gameModePeerPorts.end())
port = it->second;
int sent = sceNetAdhocPdpSend(gameModeSocket, (const char*)&gma.mac, port, masterGameModeArea.data, masterGameModeArea.size, 0, ADHOC_F_NONBLOCK);
if (sent != ERROR_NET_ADHOC_WOULD_BLOCK) {
gma.dataSent = 1;
DEBUG_LOG(SCENET, "GameMode: Master data Sent %d bytes to Area #%d [%s]", masterGameModeArea.size, gma.id, mac2str(&gma.mac).c_str());
sentcount++;
}
}
else if (gma.dataSent) sentcount++;
}
if (sentcount == replicaGameModeAreas.size())
masterGameModeArea.dataUpdated = 0;
}
// Need to sync (send + recv) all players initial data (data from CreateMaster) after Master + All Replicas are created, and before the first UpdateMaster / UpdateReplica is called for Star Wars The Force Unleashed to show the correct players color on minimap (also prevent Starting issue on other GameMode games)
else {
SceUID waitID = __KernelGetWaitID(threadID, WAITTYPE_NET, error);
if (error == 0 && waitID == GAMEMODE_WAITID) {
// Resume thread after all replicas data have been received
int recvd = 0;
for (auto& gma : replicaGameModeAreas) {
// Either replicas new data has been received or that player has been disconnected
if (gma.dataUpdated || gma.updateTimestamp == 0) {
recvd++;
// Since we're able to receive data, now we're certain that remote player is listening and ready to receive data, so we send initial data one more time in case they're not listening yet on previous attempt (ie. Pocket Pool)
if (gma.dataUpdated) {
u16_le port = ADHOC_GAMEMODE_PORT;
auto it = gameModePeerPorts.find(gma.mac);
if (it != gameModePeerPorts.end())
port = it->second;
sceNetAdhocPdpSend(gameModeSocket, (const char*)&gma.mac, port, masterGameModeArea.data, masterGameModeArea.size, 0, ADHOC_F_NONBLOCK);
}
}
}
// Resume blocked thread
u64 now = CoreTiming::GetGlobalTimeUsScaled();
if (recvd == replicaGameModeAreas.size()) {
u32 waitVal = __KernelGetWaitValue(threadID, error);
if (error == 0) {
DEBUG_LOG(SCENET, "GameMode: Resuming Thread %d after Master data Synced (Result = %08x)", threadID, waitVal);
__KernelResumeThreadFromWait(threadID, waitVal);
}
else
ERROR_LOG(SCENET, "GameMode: Error (%08x) on WaitValue %d ThreadID %d", error, waitVal, threadID);
}
// Attempt to Re-Send initial Master data (in case previous packets were lost)
else if (static_cast<s64>(now - masterGameModeArea.updateTimestamp) > GAMEMODE_SYNC_TIMEOUT) {
DEBUG_LOG(SCENET, "GameMode: Attempt to Re-Send Master data after Sync Timeout (%d us)", GAMEMODE_SYNC_TIMEOUT);
// Reset Sent marker on players who haven't replied yet (except disconnected players)
for (auto& gma : replicaGameModeAreas)
if (!gma.dataUpdated && gma.updateTimestamp != 0)
gma.dataSent = 0;
masterGameModeArea.updateTimestamp = now;
masterGameModeArea.dataUpdated = 1;
}
}
}
// Recv new Replica data when available
if (IsSocketReady(sock->data.pdp.id, true, false) > 0) {
SceNetEtherAddr sendermac;
s32_le senderport = ADHOC_GAMEMODE_PORT;
s32_le bufsz = gameModeBuffSize;
int ret = sceNetAdhocPdpRecv(gameModeSocket, &sendermac, &senderport, gameModeBuffer, &bufsz, 0, ADHOC_F_NONBLOCK);
if (ret >= 0 && bufsz > 0) {
// Shows a warning if the sender/source port is different than what it supposed to be.
if (senderport != ADHOC_GAMEMODE_PORT && senderport != gameModePeerPorts[sendermac]) {
char name[9] = {};
auto n = GetI18NCategory("Networking");
peerlock.lock();
SceNetAdhocctlPeerInfo* peer = findFriend(&sendermac);
if (peer != NULL)
truncate_cpy(name, sizeof(name), (const char*)peer->nickname.data);
WARN_LOG(SCENET, "GameMode: Unknown Source Port from [%s][%s:%u -> %u] (Result=%i, Size=%i)", name, mac2str(&sendermac).c_str(), senderport, ADHOC_GAMEMODE_PORT, ret, bufsz);
host->NotifyUserMessage(std::string(n->T("GM: Data from Unknown Port")) + std::string(" [") + std::string(name) + std::string("]:") + std::to_string(senderport) + std::string(" -> ") + std::to_string(ADHOC_GAMEMODE_PORT) + std::string(" (") + std::to_string(portOffset) + std::string(")"), 2.0, 0x0080ff);
peerlock.unlock();
}
// Keeping track of the source port for further communication, in case it was re-mapped by router or ISP for some reason.
gameModePeerPorts[sendermac] = senderport;
for (auto& gma : replicaGameModeAreas) {
if (IsMatch(gma.mac, sendermac)) {
DEBUG_LOG(SCENET, "GameMode: Replica data Received %d bytes for Area #%d [%s]", bufsz, gma.id, 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, %d) has ended", gameModeSocket, gameModeBuffSize);
u32 waitVal = __KernelGetWaitValue(threadID, error);
if (error == 0) {
DEBUG_LOG(SCENET, "GameMode: Resuming Thread %d after Master Deleted (Result = %08x)", threadID, waitVal);
__KernelResumeThreadFromWait(threadID, waitVal);
}
}
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) {
WARN_LOG(SCENET, "sceNetAdhocctl Socket WaitID(%i) on Thread(%i) already woken up? (error: %08x)", uid, threadID, error);
return;
}
// Socket not found?! Should never happen! But if it ever happened (ie. loaded from SaveState where adhocctlRequests got cleared) return BUSY and let the game try again.
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;
// Don't send any packets not in these cases (by setting the len to 0)
switch (req.opcode)
{
case OPCODE_CONNECT:
len = sizeof(packet);
break;
case OPCODE_SCAN:
case OPCODE_DISCONNECT:
len = 1;
break;
}
if (g_Config.bEnableWlan) {
// Send Packet if it wasn't succesfully sent before
int ret = 0;
int sockerr = 0;
if (len > 0) {
ret = SOCKET_ERROR;
sockerr = EAGAIN;
// Don't send anything yet if connection to Adhoc Server is still in progress
if (!isAdhocctlNeedLogin && IsSocketReady((int)metasocket, false, true) > 0) {
ret = send((int)metasocket, (const char*)&packet, len, MSG_NOSIGNAL);
sockerr = errno;
// Successfully Sent or Connection has been closed or Connection failure occurred
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);
}
}
}
// Retry until successfully sent. Login packet sent after successfully connected to Adhoc Server (indicated by networkInited), so we're not sending Login again here
if ((req.opcode == OPCODE_LOGIN && !networkInited) || (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK))) {
u64 now = (u64)(time_now_d() * 1000000.0);
if (now - adhocctlStartTime <= static_cast<u64>(adhocDefaultTimeout) + 500) {
// Try again in another 0.5ms until timedout.
CoreTiming::ScheduleEvent(usToCycles(500) - cyclesLate, adhocctlNotifyEvent, userdata);
return;
}
else if (req.opcode != OPCODE_LOGIN)
result = ERROR_NET_ADHOCCTL_BUSY;
}
}
else
result = ERROR_NET_ADHOCCTL_WLAN_SWITCH_OFF;
u32 waitVal = __KernelGetWaitValue(threadID, error);
__KernelResumeThreadFromWait(threadID, result);
DEBUG_LOG(SCENET, "Returning (WaitID: %d, error: %08x) Result (%08x) of sceNetAdhocctl - Opcode: %d, State: %d", waitID, error, (int)result, waitVal, adhocctlState);
// We are done with this request
adhocctlRequests.erase(uid);
}
static void __AdhocctlState(u64 userdata, int cyclesLate) {
SceUID threadID = userdata >> 32;
int uid = (int)(userdata & 0xFFFFFFFF);
int event = uid - 1;
s64 result = 0;
u32 error = 0;
SceUID waitID = __KernelGetWaitID(threadID, WAITTYPE_NET, error);
if (waitID == 0 || error != 0) {
WARN_LOG(SCENET, "sceNetAdhocctl State WaitID(%i) on Thread(%i) already woken up? (error: %08x)", uid, threadID, error);
return;
}
u32 waitVal = __KernelGetWaitValue(threadID, error);
if (error == 0) {
adhocctlState = waitVal;
// FIXME: It seems Adhocctl is still busy within the Adhocctl Handler function (ie. during callbacks),
// so we should probably set isAdhocctlBusy to false after mispscall are fully executed (ie. in afterAction).
// But since Adhocctl Handler is optional, there might be cases where there are no handler thus no callback/mipcall being triggered,
// so we should probably need to set isAdhocctlBusy to false here too as a workaround (or may be there is internal handler by default?)
if (adhocctlHandlers.empty())
isAdhocctlBusy = false;
}
__KernelResumeThreadFromWait(threadID, result);
DEBUG_LOG(SCENET, "Returning (WaitID: %d, error: %08x) Result (%08x) of sceNetAdhocctl - Event: %d, State: %d", waitID, error, (int)result, event, adhocctlState);
}
// Used to simulate blocking on metasocket when send OP code to AdhocServer
int WaitBlockingAdhocctlSocket(AdhocctlRequest request, int usec, const char* reason) {
int uid = (metasocket <= 0) ? 1 : (int)metasocket;
if (adhocctlRequests.find(uid) != adhocctlRequests.end()) {
WARN_LOG(SCENET, "sceNetAdhocctl - WaitID[%d] already existed, Socket is busy!", uid);
return ERROR_NET_ADHOCCTL_BUSY;
}
u64 param = ((u64)__KernelGetCurThread()) << 32 | uid;
adhocctlStartTime = (u64)(time_now_d() * 1000000.0);
adhocctlRequests[uid] = request;
CoreTiming::ScheduleEvent(usToCycles(usec), adhocctlNotifyEvent, param);
__KernelWaitCurThread(WAITTYPE_NET, uid, request.opcode, 0, false, reason);
// Always returning a success when waiting for callback, since error code returned via callback?
return 0;
}
// Used to change Adhocctl State after a delay and before executing callback mipscall (since we don't have beforeAction)
int ScheduleAdhocctlState(int event, int newState, int usec, const char* reason) {
int uid = event + 1;
u64 param = ((u64)__KernelGetCurThread()) << 32 | uid;
CoreTiming::ScheduleEvent(usToCycles(usec), adhocctlStateEvent, param);
__KernelWaitCurThread(WAITTYPE_NET, uid, newState, 0, false, reason);
return 0;
}
int StartGameModeScheduler() {
INFO_LOG(SCENET, "Initiating GameMode Scheduler");
if (CoreTiming::IsScheduled(gameModeNotifyEvent)) {
WARN_LOG(SCENET, "GameMode Scheduler is already running!");
return -1;
}
u64 param = ((u64)__KernelGetCurThread()) << 32;
CoreTiming::ScheduleEvent(usToCycles(GAMEMODE_INIT_DELAY), gameModeNotifyEvent, param);
return 0;
}
int DoBlockingPdpRecv(AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& pdpsocket = sock->data.pdp;
if (sock->flags & ADHOC_F_ALERTRECV) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTRECV;
return 0;
}
int ret;
int sockerr;
SceNetEtherAddr mac;
struct sockaddr_in sin;
socklen_t sinlen;
sinlen = sizeof(sin);
memset(&sin, 0, sinlen);
// On Windows: MSG_TRUNC are not supported on recvfrom (socket error WSAEOPNOTSUPP), so we use dummy buffer as an alternative
ret = recvfrom(pdpsocket.id, dummyPeekBuf64k, dummyPeekBuf64kSize, MSG_PEEK | MSG_NOSIGNAL, (struct sockaddr*)&sin, &sinlen);
sockerr = errno;
// Discard packets from IP that can't be translated into MAC address to prevent confusing the game, since the sender MAC won't be updated and may contains invalid/undefined value.
// TODO: In order to discard packets from unresolvable IP (can't be translated into player's MAC) properly, we'll need to manage the socket buffer ourself,
// by reading the whole available data, separates each datagram and discard unresolvable one, so we can calculate the correct number of available data to recv on GetPdpStat too.
// We may also need to implement encryption (or a simple checksum will do) in order to validate the packet to findout whether it came from PPSSPP or a different App that may be sending/broadcasting data to the same port being used by a game
// (in case the IP was resolvable but came from a different App, which will need to be discarded too)
if (ret != SOCKET_ERROR && !resolveIP(sin.sin_addr.s_addr, &mac)) {
// Remove the packet from socket buffer
sinlen = sizeof(sin);
memset(&sin, 0, sinlen);
recvfrom(pdpsocket.id, dummyPeekBuf64k, dummyPeekBuf64kSize, MSG_NOSIGNAL, (struct sockaddr*)&sin, &sinlen);
// Try again later, until timeout reached
u64 now = (u64)(time_now_d() * 1000000.0);
if (req.timeout != 0 && now - req.startTime > req.timeout) {
result = ERROR_NET_ADHOC_TIMEOUT;
DEBUG_LOG(SCENET, "sceNetAdhocPdpRecv[%i]: Discard Timeout", req.id);
return 0;
}
else
return -1;
}
// At this point we assumed that the packet is a valid PPSSPP packet
if (ret > 0 && *req.length > 0)
memcpy(req.buffer, dummyPeekBuf64k, std::min(ret, *req.length));
// Note: UDP must not be received partially, otherwise leftover data in socket's buffer will be discarded
if (ret >= 0 && ret <= *req.length) {
sinlen = sizeof(sin);
memset(&sin, 0, sinlen);
ret = recvfrom(pdpsocket.id, (char*)req.buffer, std::max(0, *req.length), MSG_NOSIGNAL, (struct 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
*req.length = 0;
if (ret >= 0) {
DEBUG_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Received %u bytes from %s:%u\n", req.id, getLocalPort(pdpsocket.id), ret, ip2str(sin.sin_addr).c_str(), ntohs(sin.sin_port));
// 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(pdpsocket.id), ret, ip2str(sin.sin_addr).c_str(), 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) {
u64 now = (u64)(time_now_d() * 1000000.0);
if (req.timeout == 0 || now - req.startTime <= req.timeout) {
// Try again later
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
// Returning required buffer size when available data in recv buffer is larger than provided buffer size
else if (ret > *req.length) {
WARN_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Peeked %u/%u bytes from %s:%u\n", req.id, getLocalPort(pdpsocket.id), ret, *req.length, ip2str(sin.sin_addr).c_str(), ntohs(sin.sin_port));
*req.length = ret;
// Find Peer MAC
if (resolveIP(sin.sin_addr.s_addr, &mac)) {
// Provide Sender Information
*req.remoteMAC = mac;
*req.remotePort = ntohs(sin.sin_port) - portOffset;
// FIXME: Do we need to update last recv timestamp? eventhough data hasn't been retrieved yet (ie. peeked)
peerlock.lock();
auto peer = findFriend(&mac);
if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled();
peerlock.unlock();
}
result = ERROR_NET_ADHOC_NOT_ENOUGH_SPACE;
}
// FIXME: Blocking operation with infinite timeout(0) should never get a TIMEOUT error, right? May be we should return INVALID_ARG instead if it was infinite timeout (0)?
else
result = ERROR_NET_ADHOC_TIMEOUT; // 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(AdhocSocketRequest& req, s64& result, AdhocSendTargets& targetPeers) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& pdpsocket = sock->data.pdp;
if (sock->flags & ADHOC_F_ALERTSEND) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTSEND;
return 0;
}
result = 0;
bool retry = false;
for (auto peer = targetPeers.peers.begin(); peer != targetPeers.peers.end(); ) {
// Fill in Target Structure
struct sockaddr_in target {};
target.sin_family = AF_INET;
target.sin_addr.s_addr = peer->ip;
target.sin_port = htons(peer->port + peer->portOffset);
int ret = sendto(pdpsocket.id, (const char*)req.buffer, targetPeers.length, MSG_NOSIGNAL, (struct sockaddr*)&target, sizeof(target));
int sockerr = errno;
if (ret >= 0) {
DEBUG_LOG(SCENET, "sceNetAdhocPdpSend[%i:%u](B): Sent %u bytes to %s:%u\n", req.id, getLocalPort(pdpsocket.id), ret, ip2str(target.sin_addr).c_str(), 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)) {
u64 now = (u64)(time_now_d() * 1000000.0);
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, req.id, getLocalPort(pdpsocket.id), ntohs(target.sin_port), targetPeers.length);
}
if (retry)
return -1;
return 0;
}
int DoBlockingPtpSend(AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& ptpsocket = sock->data.ptp;
if (sock->flags & ADHOC_F_ALERTSEND) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTSEND;
return 0;
}
// Send Data
int ret = send(ptpsocket.id, (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);
// Set to Established on successful Send when an attempt to Connect was initiated
if (ptpsocket.state == ADHOC_PTP_STATE_SYN_SENT)
ptpsocket.state = ADHOC_PTP_STATE_ESTABLISHED;
// Return Success
result = 0;
}
else if (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK || (ptpsocket.state == ADHOC_PTP_STATE_SYN_SENT && (sockerr == ENOTCONN || connectInProgress(sockerr))))) {
u64 now = (u64)(time_now_d() * 1000000.0);
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;
}
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPtpSend[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPtpRecv(AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& ptpsocket = sock->data.ptp;
if (sock->flags & ADHOC_F_ALERTRECV) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTRECV;
return 0;
}
int ret = recv(ptpsocket.id, (char*)req.buffer, std::max(0, *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();
// Set to Established on successful Recv when an attempt to Connect was initiated
if (ptpsocket.state == ADHOC_PTP_STATE_SYN_SENT)
ptpsocket.state = ADHOC_PTP_STATE_ESTABLISHED;
result = 0;
}
else if (ret == SOCKET_ERROR && (sockerr == EAGAIN || sockerr == EWOULDBLOCK || (ptpsocket.state == ADHOC_PTP_STATE_SYN_SENT && (sockerr == ENOTCONN || connectInProgress(sockerr))))) {
u64 now = (u64)(time_now_d() * 1000000.0);
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(AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& ptpsocket = sock->data.ptp;
if (sock->flags & ADHOC_F_ALERTACCEPT) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTACCEPT;
return 0;
}
struct 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(ptpsocket.id, true, false, &sockerr);
if (ret > 0) {
// Accept Connection
ret = accept(ptpsocket.id, (struct 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))) {
u64 now = (u64)(time_now_d() * 1000000.0);
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(AdhocSocketRequest& req, s64& result, AdhocSendTargets& targetPeer) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& ptpsocket = sock->data.ptp;
if (sock->flags & ADHOC_F_ALERTCONNECT) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTCONNECT;
return 0;
}
int sockerr, ret;
// Try to connect again if the first attempt failed due to remote side was not listening yet (ie. ECONNREFUSED or ETIMEDOUT)
if (sock->attemptCount < 1) {
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = targetPeer.peers[0].ip;
sin.sin_port = htons(ptpsocket.pport + targetPeer.peers[0].portOffset);
// Try to Connect
int ret = connect(ptpsocket.id, (struct sockaddr*)&sin, sizeof(sin));
int sockerr = errno;
if (connectInProgress(sockerr)) {
sock->data.ptp.state = ADHOC_PTP_STATE_SYN_SENT;
sock->attemptCount = 1;
}
// On Windows you can call connect again using the same socket after ECONNREFUSED/ETIMEDOUT/ENETUNREACH error, but on non-Windows you'll need to recreate the socket first
else {
if (RecreatePtpSocket(req.id) < 0) {
WARN_LOG(SCENET, "sceNetAdhocPtpConnect[%i:%u]: Failed to Recreate Socket", req.id, ptpsocket.lport);
}
}
}
// Check if the connection has completed (assuming "connect" has been called before)
ret = IsSocketReady(ptpsocket.id, false, true, &sockerr);
// Connection is ready
if (ret > 0) {
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
socklen_t sinlen = sizeof(sin);
ret = getpeername(ptpsocket.id, (struct sockaddr*)&sin, &sinlen);
if (ret == SOCKET_ERROR) {
WARN_LOG(SCENET, "sceNetAdhocPtpConnect[%i:%u]: getpeername error %i", req.id, ptpsocket.lport, errno);
}
// Set Connected State
ptpsocket.state = ADHOC_PTP_STATE_ESTABLISHED;
INFO_LOG(SCENET, "sceNetAdhocPtpConnect[%i:%u]: Established (%s:%u)", req.id, ptpsocket.lport, ip2str(sin.sin_addr).c_str(), ptpsocket.pport);
// Success
result = 0;
}
// Timeout
else if (ret == 0) {
u64 now = (u64)(time_now_d() * 1000000.0);
if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else {
// Handle Workaround that force the first Connect to be blocking for issue related to lobby or high latency networks
if (sock->nonblocking)
result = ERROR_NET_ADHOC_WOULD_BLOCK;
else
result = ERROR_NET_ADHOC_TIMEOUT; // FIXME: PSP never returned ERROR_NET_ADHOC_TIMEOUT on PtpConnect? or only returned ERROR_NET_ADHOC_TIMEOUT when the host is too busy? Seems to be returning ERROR_NET_ADHOC_CONNECTION_REFUSED on timedout instead (if the other side in not listening yet, which is similar to BSD).
}
}
// Select was interrupted or contains invalid args?
else
result = ERROR_NET_ADHOC_EXCEPTION_EVENT; // ERROR_NET_ADHOC_INVALID_ARG;
if (ret == SOCKET_ERROR)
DEBUG_LOG(SCENET, "sceNetAdhocPtpConnect[%i]: Socket Error (%i)", req.id, sockerr);
return 0;
}
int DoBlockingPtpFlush(AdhocSocketRequest& req, s64& result) {
auto sock = adhocSockets[req.id - 1];
if (!sock) {
result = ERROR_NET_ADHOC_SOCKET_DELETED;
return 0;
}
auto& ptpsocket = sock->data.ptp;
if (sock->flags & ADHOC_F_ALERTFLUSH) {
result = ERROR_NET_ADHOC_SOCKET_ALERTED;
sock->alerted_flags |= ADHOC_F_ALERTFLUSH;
return 0;
}
// Try Sending Empty Data
int sockerr = FlushPtpSocket(ptpsocket.id);
result = 0;
if (sockerr == EAGAIN || sockerr == EWOULDBLOCK) {
u64 now = (u64)(time_now_d() * 1000000.0);
if (req.timeout == 0 || now - req.startTime <= req.timeout) {
return -1;
}
else
result = ERROR_NET_ADHOC_TIMEOUT;
}
if (sockerr != 0) {
DEBUG_LOG(SCENET, "sceNetAdhocPtpFlush[%i]: Socket Error (%i)", req.id, sockerr);
}
return 0;
}
int DoBlockingAdhocPollSocket(AdhocSocketRequest& req, s64& result) {
SceNetAdhocPollSd* sds = (SceNetAdhocPollSd*)req.buffer;
int ret = PollAdhocSocket(sds, req.id, 0, 0);
if (ret <= 0) {
u64 now = (u64)(time_now_d() * 1000000.0);
// POSIX poll using negative timeout for indefinitely blocking, not sure about PSP's AdhocPollSocket tho since most of PSP's sceNet API using 0 for indefinitely blocking.
if (static_cast<int>(req.timeout) <= 0 || now - req.startTime <= req.timeout) {
return -1;
}
else if (ret < 0)
ret = ERROR_NET_ADHOC_EXCEPTION_EVENT;
// FIXME: Does AdhocPollSocket can return any error code other than ERROR_NET_ADHOC_EXCEPTION_EVENT?
//else
// ret = ERROR_NET_ADHOC_TIMEOUT;
}
result = ret;
if (ret > 0) {
for (int i = 0; i < req.id; i++) {
if (sds[i].id > 0 && sds[i].id <= MAX_SOCKET && adhocSockets[sds[i].id - 1] != NULL) {
auto sock = adhocSockets[sds[i].id - 1];
if (sock->type == SOCK_PTP)
VERBOSE_LOG(SCENET, "Poll PTP Socket Id: %d (%d), events: %08x, revents: %08x - state: %d", sds[i].id, sock->data.ptp.id, sds[i].events, sds[i].revents, sock->data.ptp.state);
else
VERBOSE_LOG(SCENET, "Poll PDP Socket Id: %d (%d), events: %08x, revents: %08x", sds[i].id, sock->data.pdp.id, sds[i].events, sds[i].revents);
}
}
}
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) {
WARN_LOG(SCENET, "sceNetAdhoc Socket WaitID(%i) on Thread(%i) already woken up? (error: %08x)", uid, threadID, error);
return;
}
// Socket not found?! Should never happened! But if it ever happened (ie. loaded from SaveState where adhocSocketRequests got cleared) return TIMEOUT and let the game try again.
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(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(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(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: