From 1c7152db3ac254a5f8739419c82be42c1319532d Mon Sep 17 00:00:00 2001 From: AdamN Date: Fri, 1 Aug 2014 01:55:42 +0700 Subject: [PATCH] Adding Branch opcode to the MAKE_MIPS Temp revert old version to fix conflict; Implementing built-in PRO Adhoc Server; Add back sceUsbGps Implementing more Adhoc functions, and some bug fix (i don't remember them anymore) --- Core/Core.vcxproj | 2 + Core/Core.vcxproj.filters | 6 + Core/HLE/FunctionWrappers.h | 14 +- Core/HLE/proAdhoc.cpp | 1898 +++++++++++++------ Core/HLE/proAdhoc.h | 722 +++++++- Core/HLE/proAdhocServer.cpp | 1628 ++++++++++++++++ Core/HLE/proAdhocServer.h | 385 ++++ Core/HLE/sceKernelThread.cpp | 2 +- Core/HLE/sceNet.cpp | 142 +- Core/HLE/sceNet.h | 73 + Core/HLE/sceNetAdhoc.cpp | 3385 ++++++++++++++++++++++++++++------ Core/MIPS/MIPSCodeUtils.h | 1 + 12 files changed, 7038 insertions(+), 1220 deletions(-) create mode 100644 Core/HLE/proAdhocServer.cpp create mode 100644 Core/HLE/proAdhocServer.h diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index d136a4e845..497118a561 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -208,6 +208,7 @@ + @@ -445,6 +446,7 @@ + diff --git a/Core/Core.vcxproj.filters b/Core/Core.vcxproj.filters index 80e646b8ff..6348b1c1f5 100644 --- a/Core/Core.vcxproj.filters +++ b/Core/Core.vcxproj.filters @@ -508,6 +508,9 @@ HLE\Libraries + + HLE\Libraries + Ext\udis86 @@ -976,6 +979,9 @@ HLE\Libraries + + HLE\Libraries + Ext\udis86 diff --git a/Core/HLE/FunctionWrappers.h b/Core/HLE/FunctionWrappers.h index 7d2b3cecbf..39599d408f 100644 --- a/Core/HLE/FunctionWrappers.h +++ b/Core/HLE/FunctionWrappers.h @@ -142,7 +142,8 @@ template void WrapI_IIIIIIU() { // Hm, do so many params get passed in registers? template void WrapI_IIIIIIIIU() { - u32 retval = func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4), PARAM(5), PARAM(6), PARAM(7), PARAM(8)); + u32 param8 = *(u32*)Memory::GetPointer(currentMIPS->r[29]); //Fixed 9th parameter, thanks to Kingcom + u32 retval = func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4), PARAM(5), PARAM(6), PARAM(7), param8); RETURN(retval); } @@ -520,6 +521,12 @@ template void WrapI_CIIUII() { RETURN(retval); } +template void WrapI_CIIIUUI() { + int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1), PARAM(2), + PARAM(3), PARAM(4), PARAM(5), PARAM(6)); + RETURN(retval); +} + template void WrapI_CIUUU() { int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); @@ -792,3 +799,8 @@ template void WrapI_ICU u32 retval = func(PARAM(0), Memory::GetCharPointer(PARAM(1)), PARAM(2), Memory::GetPointer(PARAM(3)), PARAM(4), PARAM(5), PARAM(6)); RETURN(retval); } + +template void WrapI_VUI(){ + u32 retval = func(Memory::GetPointer(PARAM(0)), PARAM(1), PARAM(2)); + RETURN(retval); +} diff --git a/Core/HLE/proAdhoc.cpp b/Core/HLE/proAdhoc.cpp index 33886b6b41..d3bb420c08 100644 --- a/Core/HLE/proAdhoc.cpp +++ b/Core/HLE/proAdhoc.cpp @@ -1,8 +1,32 @@ -// TODO: Add license +// 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/. + + +// proAdhoc + +// This is a direct port of Coldbird's code from http://code.google.com/p/aemu/ +// All credit goes to him! -#include #include #include "util/text/parsers.h" +#include "Core/Core.h" +#include "Core/HLE/sceKernelInterrupt.h" +#include "Core/HLE/sceKernelThread.h" +#include "Core/HLE/sceKernelMemory.h" #include "proAdhoc.h" uint32_t fakePoolSize = 0; @@ -11,33 +35,42 @@ int one = 1; bool friendFinderRunning = false; SceNetAdhocctlPeerInfo * friends = NULL; SceNetAdhocctlScanInfo * networks = NULL; -int eventHandlerUpdate = -1; +SceNetAdhocctlScanInfo * newnetworks = NULL; +int eventAdhocctlHandlerUpdate = -1; +int eventMatchingHandlerUpdate = -1; int threadStatus = ADHOCCTL_STATE_DISCONNECTED; +bool IsAdhocctlInCB = false; +int actionAfterMatchingMipsCall; + +// Broadcast MAC +uint8_t broadcastMAC[ETHER_ADDR_LEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; + int metasocket; SceNetAdhocctlParameter parameter; +SceNetAdhocctlAdhocId product_code; std::thread friendFinderThread; recursive_mutex peerlock; SceNetAdhocPdpStat * pdp[255]; SceNetAdhocPtpStat * ptp[255]; int isLocalMAC(const SceNetEtherAddr * addr) { - SceNetEtherAddr saddr; - getLocalMac(&saddr); + SceNetEtherAddr saddr; + getLocalMac(&saddr); - // Compare MAC Addresses - int match = memcmp((const void *)addr, (const void *)&saddr, ETHER_ADDR_LEN); + // Compare MAC Addresses + int match = memcmp((const void *)addr, (const void *)&saddr, ETHER_ADDR_LEN); - // Return Result - return (match == 0); + // Return Result + return (match == 0); } int isPDPPortInUse(uint16_t port) { - // Iterate Elements - int i = 0; for(; i < 255; i++) if(pdp[i] != NULL && pdp[i]->lport == port) return 1; + // Iterate Elements + int i = 0; for (; i < 255; i++) if (pdp[i] != NULL && pdp[i]->lport == port) return 1; - // Unused Port - return 0; + // Unused Port + return 0; } int isPTPPortInUse(uint16_t port) { @@ -48,23 +81,10 @@ int isPTPPortInUse(uint16_t port) { return 0; } -SceNetAdhocMatchingMemberInternal* findMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { +SceNetAdhocMatchingMemberInternal* addMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { if (context == NULL || mac == NULL) return NULL; - - SceNetAdhocMatchingMemberInternal * peer = context->peerlist; - while (peer != NULL) { - if (IsMatch(peer->mac, *mac)) - return peer; - peer = peer->next; - } - - return NULL; -} - -void addMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { - if (context == NULL || mac == NULL) return; - SceNetAdhocMatchingMemberInternal * peer = findMember(context, mac); + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, mac); // Member is not added yet if (peer == NULL) { peer = (SceNetAdhocMatchingMemberInternal *)malloc(sizeof(SceNetAdhocMatchingMemberInternal)); @@ -75,138 +95,121 @@ void addMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { context->peerlist = peer; } } -} - -void deleteMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { - if (context == NULL || mac == NULL) return; - - // Previous Peer Reference - SceNetAdhocMatchingMemberInternal * prev = NULL; - - // Peer Pointer - SceNetAdhocMatchingMemberInternal * peer = context->peerlist; - - // Iterate Peers - for (; peer != NULL; peer = peer->next) { - // Found Peer - if (IsMatch(context->mac, *mac)) { - // Multithreading Lock - //context->peerlock.lock(); - - // Unlink Left (Beginning) - if (prev == NULL) context->peerlist = peer->next; - - // Unlink Left (Other) - else prev->next = peer->next; - - // Multithreading Unlock - //context->peerlock.unlock(); - - // Free Memory - free(peer); - - // Stop Search - break; - } - - // Set Previous Reference - prev = peer; - } - -} - -void deleteAllMembers(SceNetAdhocMatchingContext * context) { - if (context == NULL) return; - - SceNetAdhocMatchingMemberInternal * peer = context->peerlist; - while (peer != NULL) { - context->peerlist = peer->next; - free(peer); - peer = context->peerlist; - } + return peer; } void addFriend(SceNetAdhocctlConnectPacketS2C * packet) { - if (packet == NULL) return; + if (packet == NULL) return; - // Allocate Structure - SceNetAdhocctlPeerInfo * peer = (SceNetAdhocctlPeerInfo *)malloc(sizeof(SceNetAdhocctlPeerInfo)); - // Allocated Structure - if(peer != NULL) { - // Clear Memory - memset(peer, 0, sizeof(SceNetAdhocctlPeerInfo)); + // Multithreading Lock + peerlock.lock(); - // Link to existing Peers - peer->next = friends; + SceNetAdhocctlPeerInfo * peer = findFriend(&packet->mac); + // Already existed + if (peer != NULL) { + peer->nickname = packet->name; + peer->mac_addr = packet->mac; + peer->ip_addr = packet->ip; + // Update TimeStamp + peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); + } + else + { + // Allocate Structure + peer = (SceNetAdhocctlPeerInfo *)malloc(sizeof(SceNetAdhocctlPeerInfo)); + // Allocated Structure + if (peer != NULL) { + // Clear Memory + memset(peer, 0, sizeof(SceNetAdhocctlPeerInfo)); - // Save Nickname - peer->nickname = packet->name; + // Save Nickname + peer->nickname = packet->name; - // Save MAC Address - peer->mac_addr = packet->mac; + // Save MAC Address + peer->mac_addr = packet->mac; - // Save IP Address - peer->ip_addr = packet->ip; + // Save IP Address + peer->ip_addr = packet->ip; - // Multithreading Lock - peerlock.lock(); + // TimeStamp + peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); - // Link into Peerlist - friends = peer; + // Link to existing Peers + peer->next = friends; - // Multithreading Unlock - peerlock.unlock(); - } + // Link into Peerlist + friends = peer; + } + } + + // Multithreading Unlock + peerlock.unlock(); +} + +SceNetAdhocctlPeerInfo * findFriend(SceNetEtherAddr * MAC) { + if (MAC == NULL) return NULL; + + // Friends Reference + SceNetAdhocctlPeerInfo * peer = friends; + + // Iterate Friends + for (; peer != NULL; peer = peer->next) { + if (IsMatch(peer->mac_addr, *MAC)) break; + } + + // Return found friend + return peer; } void changeBlockingMode(int fd, int nonblocking) { - unsigned long on = 1; - unsigned long off = 0; + unsigned long on = 1; + unsigned long off = 0; #ifdef _MSC_VER - if(nonblocking){ - // Change to Non-Blocking Mode - ioctlsocket(fd,FIONBIO,&on); - }else { - // Change to Blocking Mode - ioctlsocket(fd, FIONBIO, &off); - } + if (nonblocking){ + // Change to Non-Blocking Mode + ioctlsocket(fd, FIONBIO, &on); + } + else { + // Change to Blocking Mode + ioctlsocket(fd, FIONBIO, &off); + } #else - if(nonblocking == 1) fcntl(fd, F_SETFL, O_NONBLOCK); - else { - // Get Flags - int flags = fcntl(fd, F_GETFL); - // Remove Non-Blocking Flag - fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); - } + if(nonblocking == 1) fcntl(fd, F_SETFL, O_NONBLOCK); + else { + // Get Flags + int flags = fcntl(fd, F_GETFL); + // Remove Non-Blocking Flag + fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); + } #endif } int countAvailableNetworks(void) { - // Network Count - int count = 0; - - // Group Reference - SceNetAdhocctlScanInfo * group = networks; - - // Count Groups - for(; group != NULL; group = group->next) count++; - - // Return Network Count - return count; -} - -SceNetAdhocctlScanInfo * findGroup(SceNetEtherAddr * MAC) { - if (MAC == NULL) return NULL; + // Network Count + int count = 0; // Group Reference SceNetAdhocctlScanInfo * group = networks; // Count Groups + for (; group != NULL; group = group->next) count++; + + // Return Network Count + return count; +} + +SceNetAdhocctlScanInfo * findGroup(SceNetEtherAddr * MAC) { + if (MAC == NULL) return NULL; + + // Groups Reference + SceNetAdhocctlScanInfo * group = networks; + + // Iterate Groups for (; group != NULL; group = group->next) { if (IsMatch(group->bssid.mac_addr, *MAC)) break; } - // Return Network Count + // Return found group return group; } @@ -222,408 +225,1070 @@ void freeGroupsRecursive(SceNetAdhocctlScanInfo * node) { } void deleteAllPDP(void) { - // Iterate Element - int i = 0; for(; i < 255; i++) { - // Active Socket - if(pdp[i] != NULL) { - // Close Socket - closesocket(pdp[i]->id); + // Iterate Element + int i = 0; for (; i < 255; i++) { + // Active Socket + if (pdp[i] != NULL) { + // Close Socket + closesocket(pdp[i]->id); - // Free Memory - free(pdp[i]); + // Free Memory + free(pdp[i]); - // Delete Reference - pdp[i] = NULL; - } - } + // Delete Reference + pdp[i] = NULL; + } + } } void deleteAllPTP(void) { - // Iterate Element - int i = 0; for(; i < 255; i++) { - // Active Socket - if(ptp[i] != NULL) { - // Close Socket - closesocket(ptp[i]->id); + // Iterate Element + int i = 0; for (; i < 255; i++) { + // Active Socket + if (ptp[i] != NULL) { + // Close Socket + closesocket(ptp[i]->id); - // Free Memory - free(ptp[i]); + // Free Memory + free(ptp[i]); - // Delete Reference - ptp[i] = NULL; - } - } + // Delete Reference + ptp[i] = NULL; + } + } } void deleteFriendByIP(uint32_t ip) { - // Previous Peer Reference - SceNetAdhocctlPeerInfo * prev = NULL; + // Previous Peer Reference + SceNetAdhocctlPeerInfo * prev = NULL; - // Peer Pointer - SceNetAdhocctlPeerInfo * peer = friends; + // Peer Pointer + SceNetAdhocctlPeerInfo * peer = friends; - // Iterate Peers - for(; peer != NULL; peer = peer->next) { - // Found Peer - if(peer->ip_addr == ip) { - // Multithreading Lock - peerlock.lock(); + // Iterate Peers + for (; peer != NULL; peer = peer->next) { + // Found Peer + if (peer->ip_addr == ip) { + // Instead of removing it from the list we'll make it timeout since most Matching games are moving group and may still need the peer data + peer->last_recv = 0; - // Unlink Left (Beginning) - if(prev == NULL)friends = peer->next; + // Multithreading Lock + /*peerlock.lock(); - // Unlink Left (Other) - else prev->next = peer->next; + // Unlink Left (Beginning) + if(prev == NULL)friends = peer->next; - // Multithreading Unlock - peerlock.unlock(); + // Unlink Left (Other) + else prev->next = peer->next; - // Free Memory - free(peer); + // Multithreading Unlock + peerlock.unlock(); - // Stop Search - break; - } + // Free Memory + free(peer); + peer = NULL;*/ - // Set Previous Reference - prev = peer; - } + // Stop Search + break; + } + + // Set Previous Reference + prev = peer; + } } int findFreeMatchingID(void) { - // Minimum Matching ID - int min = 1; + // Minimum Matching ID + int min = 1; - // Maximum Matching ID - int max = 0; + // Maximum Matching ID + int max = 0; - // Find highest Matching ID - SceNetAdhocMatchingContext * item = contexts; for(; item != NULL; item = item->next) { - // New Maximum - if(max < item->id) max = item->id; - } + // Find highest Matching ID + SceNetAdhocMatchingContext * item = contexts; for (; item != NULL; item = item->next) { + // New Maximum + if (max < item->id) max = item->id; + } - // Find unoccupied ID - int i = min; for(; i < max; i++) { - // Found unoccupied ID - if(findMatchingContext(i) == NULL) return i; - } + // Find unoccupied ID + int i = min; for (; i < max; i++) { + // Found unoccupied ID + if (findMatchingContext(i) == NULL) return i; + } - // Append at virtual end - return max + 1; + // Append at virtual end + return max + 1; } SceNetAdhocMatchingContext * findMatchingContext(int id) { - // Iterate Matching Context List - SceNetAdhocMatchingContext * item = contexts; for(; item != NULL; item = item->next) { // Found Matching ID - if(item->id == id) return item; - } + // Iterate Matching Context List + SceNetAdhocMatchingContext * item = contexts; for (; item != NULL; item = item->next) { // Found Matching ID + if (item->id == id) return item; + } - // Context not found - return NULL; + // Context not found + return NULL; +} + +/** +* Find Outgoing Request Target Peer +* @param context Matching Context Pointer +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findOutgoingRequest(SceNetAdhocMatchingContext * context) +{ + // Iterate Peer List for Matching Target + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Found Peer in List + if (peer->state == PSP_ADHOC_MATCHING_PEER_OUTGOING_REQUEST) return peer; + } + + // Peer not found + return NULL; +} + +/** +* Remove unneeded Peer Data after being accepted to a match +* @param context Matching Context Pointer +*/ +void postAcceptCleanPeerList(SceNetAdhocMatchingContext * context) +{ + // Acquire Peer Lock + peerlock.lock(); + + // Iterate Peer List + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; + while (peer != NULL) + { + // Save next Peer just in case we have to delete this one + SceNetAdhocMatchingMemberInternal * next = peer->next; + + // Unneeded Peer + if (peer->state != PSP_ADHOC_MATCHING_PEER_CHILD && peer->state != PSP_ADHOC_MATCHING_PEER_P2P && peer->state != PSP_ADHOC_MATCHING_PEER_PARENT) deletePeer(context, peer); + + // Move to Next Peer + peer = next; + } + + // Free Peer Lock + peerlock.unlock(); +} + +/** +* Add Sibling-Data that was sent with Accept-Datagram +* @param context Matching Context Pointer +* @param siblingcount Number of Siblings +* @param siblings Sibling MAC Array +*/ +void postAcceptAddSiblings(SceNetAdhocMatchingContext * context, int siblingcount, SceNetEtherAddr * siblings) +{ + // Cast Sibling MAC Array to uint8_t + // PSP CPU has a problem with non-4-byte aligned Pointer Access. + // As the buffer of "siblings" isn't properly aligned I don't want to risk a crash. + uint8_t * siblings_u8 = (uint8_t *)siblings; + + // Iterate Siblings + int i = 0; for (; i < siblingcount; i++) + { + // Allocate Memory + SceNetAdhocMatchingMemberInternal * sibling = (SceNetAdhocMatchingMemberInternal *)malloc(sizeof(SceNetAdhocMatchingMemberInternal)); + + // Allocated Memory + if (sibling != NULL) + { + // Clear Memory + memset(sibling, 0, sizeof(SceNetAdhocMatchingMemberInternal)); + + // Save MAC Address + memcpy(&sibling->mac, siblings_u8 + sizeof(SceNetEtherAddr) * i, sizeof(SceNetEtherAddr)); + + // Set Peer State + sibling->state = PSP_ADHOC_MATCHING_PEER_CHILD; + + // Initialize Ping Timer + sibling->lastping = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; + + // Link Peer, should check whether it's already added before + sibling->next = context->peerlist; + context->peerlist = sibling; + + // Spawn Established Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_ESTABLISHED, &sibling->mac, 0, NULL); + + INFO_LOG(SCENET, "Accepting Peer %02X:%02X:%02X:%02X:%02X:%02X", sibling->mac.data[0], sibling->mac.data[1], sibling->mac.data[2], sibling->mac.data[3], sibling->mac.data[4], sibling->mac.data[5]); + } + } +} + +/** +* Count Children Peers (for Parent) +* @param context Matching Context Pointer +* @return Number of Children +*/ +s32_le countChildren(SceNetAdhocMatchingContext * context) +{ + // Children Counter + s32_le count = 0; + + // Iterate Peer List for Matching Target + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Increase Children Counter + if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) count++; + } + + // Return Children Count + return count; +} + +/** +* Find Peer in Context by MAC +* @param context Matching Context Pointer +* @param mac Peer MAC Address +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findPeer(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) +{ + // Iterate Peer List for Matching Target + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Found Peer in List + if (memcmp(&peer->mac, mac, sizeof(SceNetEtherAddr)) == 0) + { + // Return Peer Pointer + return peer; + } + } + + // Peer not found + return NULL; +} + +/** +* Find Parent Peer +* @param context Matching Context Pointer +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findParent(SceNetAdhocMatchingContext * context) +{ + // Iterate Peer List for Matching Target + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Found Peer in List + if (peer->state == PSP_ADHOC_MATCHING_PEER_PARENT) return peer; + } + + // Peer not found + return NULL; +} + +/** +* Find P2P Buddy Peer +* @param context Matching Context Pointer +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findP2P(SceNetAdhocMatchingContext * context) +{ + // Iterate Peer List for Matching Target + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; + for (; peer != NULL; peer = peer->next) + { + // Found Peer in List + if (peer->state == PSP_ADHOC_MATCHING_PEER_P2P) return peer; + } + + // Peer not found + return NULL; +} + +/** +* Delete Peer from List +* @param context Matching Context Pointer +* @param peer Internal Peer Reference +*/ +void deletePeer(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer) +{ + // Valid Arguments + if (context != NULL && peer != NULL) + { + peerlock.lock(); + + // Previous Peer Reference + SceNetAdhocMatchingMemberInternal * previous = NULL; + + // Iterate Peer List + SceNetAdhocMatchingMemberInternal * item = context->peerlist; + for (; item != NULL; item = item->next) + { + // Found Peer Match + if (item == peer) break; + + // Set Previous Peer + previous = item; + } + + if (item != NULL) { + // Middle Item + if (previous != NULL) previous->next = item->next; + + // Beginning Item + else context->peerlist = item->next; + + INFO_LOG(SCENET, "Removing Peer %02X:%02X:%02X:%02X:%02X:%02X", peer->mac.data[0], peer->mac.data[1], peer->mac.data[2], peer->mac.data[3], peer->mac.data[4], peer->mac.data[5]); + } + + // Free Peer Memory + free(peer); + peer = NULL; + + peerlock.unlock(); + } +} + +/** +* Safely Link Thread Message to Event Thread Stack +* @param context Matching Context Pointer +* @param message Thread Message Pointer +*/ +void linkEVMessage(SceNetAdhocMatchingContext * context, ThreadMessage * message) +{ + // Lock Access + context->eventlock->lock(); + + // Link Message + message->next = context->event_stack; + context->event_stack = message; + + // Unlock Access + context->eventlock->unlock(); +} + +/** +* Safely Link Thread Message to IO Thread Stack +* @param context Matching Context Pointer +* @param message Thread Message Pointer +*/ +void linkIOMessage(SceNetAdhocMatchingContext * context, ThreadMessage * message) +{ + // Lock Access + context->inputlock->lock(); + + // Link Message + message->next = context->input_stack; + context->input_stack = message; + + // Unlock Access + context->inputlock->unlock(); +} + +/** +* Send Generic Thread Message +* @param context Matching Context Pointer +* @param stack ADHOC_MATCHING_EVENT_STACK or ADHOC_MATCHING_INPUT_STACK +* @param mac Target MAC +* @param opcode Message Opcode +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendGenericMessage(SceNetAdhocMatchingContext * context, int stack, SceNetEtherAddr * mac, int opcode, int optlen, const void * opt) +{ + // Calculate Required Memory Size + uint32_t size = sizeof(ThreadMessage) + optlen; + + // Allocate Memory + uint8_t * memory = (uint8_t *)malloc(size); + + // Allocated Memory + if (memory != NULL) + { + // Clear Memory + memset(memory, 0, size); + + // Cast Header + ThreadMessage * header = (ThreadMessage *)memory; + + // Set Message Opcode + header->opcode = opcode; + + // Set Peer MAC Address + header->mac = *mac; + + // Set Optional Data Length + header->optlen = optlen; + + // Set Optional Data + memcpy(memory + sizeof(ThreadMessage), opt, optlen); + + // Link Thread Message + if (stack == PSP_ADHOC_MATCHING_EVENT_STACK) linkEVMessage(context, header); + + // Link Thread Message to Input Stack + else linkIOMessage(context, header); + + // Exit Function + return; + } + + peerlock.lock(); + // Out of Memory Emergency Delete + deletePeer(context, findPeer(context, mac)); + peerlock.unlock(); +} + +/** +* Send Accept Message from P2P -> P2P or Parent -> Children +* @param context Matching Context Pointer +* @param peer Target Peer +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendAcceptMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int optlen, const void * opt) +{ + // Send Accept Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_ACCEPT, optlen, opt); +} + +/** +* Send Join Request from P2P -> P2P or Children -> Parent +* @param context Matching Context Pointer +* @param peer Target Peer +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendJoinRequest(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int optlen, const void * opt) +{ + // Send Join Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_JOIN, optlen, opt); +} + +/** +* Send Cancel Message to Peer (has various effects) +* @param context Matching Context Pointer +* @param peer Target Peer +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendCancelMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int optlen, const void * opt) +{ + // Send Cancel Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_CANCEL, optlen, opt); +} + +/** +* Send Bulk Data to Peer +* @param context Matching Context Pointer +* @param peer Target Peer +* @param datalen Data Length +* @param data Data +*/ +void sendBulkData(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int datalen, const void * data) +{ + // Send Bulk Data Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_BULK, datalen, data); +} + +/** +* Abort Bulk Data Transfer (if in progress) +* @param context Matching Context Pointer +* @param peer Target Peer +*/ +void abortBulkTransfer(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer) +{ + // Send Bulk Data Abort Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_BULK_ABORT, 0, NULL); +} + +/** +* Notify all established Peers about new Kid in the Neighborhood +* @param context Matching Context Pointer +* @param peer New Kid +*/ +void sendBirthMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer) +{ + // Send Birth Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_BIRTH, 0, NULL); +} + +/** +* Notify all established Peers about abandoned Child +* @param context Matching Context Pointer +* @param peer Abandoned Child +*/ +void sendDeathMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer) +{ + // Send Death Message + sendGenericMessage(context, PSP_ADHOC_MATCHING_INPUT_STACK, &peer->mac, PSP_ADHOC_MATCHING_PACKET_DEATH, 0, NULL); +} + +/** +* Return Number of Connected Peers +* @param context Matching Context Pointer +* @return Number of Connected Peers +*/ +uint32_t countConnectedPeers(SceNetAdhocMatchingContext * context) +{ + // Peer Count + uint32_t count = 0; + + // Parent Mode + if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT) + { + // Number of Children + 1 Parent (Self) + count = countChildren(context) + 1; + } + + // Child Mode + else if (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD) + { + // Default to 1 Child (Self) + count = 1; + + // Connected to Parent + if (findParent(context) != NULL) + { + // Add Number of Siblings + 1 Parents + count += countChildren(context) + 1; + } + } + + // P2P Mode + else + { + // Default to 1 P2P Client (Self) + count = 1; + + // Connected to another P2P Client + if (findP2P(context) != NULL) + { + // Add P2P Brother + count++; + } + } + + // Return Peer Count + return count; +} + +/** +* Spawn Local Event for Event Thread +* @param context Matching Context Pointer +* @param event Event ID +* @param mac Event Source MAC +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void spawnLocalEvent(SceNetAdhocMatchingContext * context, int event, SceNetEtherAddr * mac, int optlen, void * opt) +{ + // Spawn Local Event + sendGenericMessage(context, PSP_ADHOC_MATCHING_EVENT_STACK, mac, event, optlen, opt); +} + +/** +* Handle Timeouts in Matching Context +* @param context Matchi]ng Context Pointer +*/ +void handleTimeout(SceNetAdhocMatchingContext * context) +{ + peerlock.lock(); + // Iterate Peer List + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; while (peer != NULL) + { + // Get Next Pointer (to avoid crash on memory freeing) + SceNetAdhocMatchingMemberInternal * next = peer->next; + + u64_le now = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0 + // Timeout! + if ((now - peer->lastping) >= context->timeout) + { + // Spawn Timeout Event + if ((context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_PARENT)) || + (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) || + (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && peer->state == PSP_ADHOC_MATCHING_PEER_P2P)) + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_TIMEOUT, &peer->mac, 0, NULL); + + INFO_LOG(SCENET, "TimedOut Peer %02X:%02X:%02X:%02X:%02X:%02X (%dms)", peer->mac.data[0], peer->mac.data[1], peer->mac.data[2], peer->mac.data[3], peer->mac.data[4], peer->mac.data[5], (context->timeout/1000)); + + // Delete Peer from List + deletePeer(context, peer); + } + + // Move Pointer + peer = next; + } + peerlock.unlock(); +} + +/** +* Recursive Stack Cleaner +* @param node Current Thread Message Node +*/ +void clearStackRecursive(ThreadMessage * node) +{ + // Not End of List + if (node != NULL) clearStackRecursive(node->next); + + // Free Last Existing Node of List (NULL is handled in _free) + free(node); +} + +/** +* Clear Thread Stack +* @param context Matching Context Pointer +* @param stack ADHOC_MATCHING_EVENT_STACK or ADHOC_MATCHING_INPUT_STACK +*/ +void clearStack(SceNetAdhocMatchingContext * context, int stack) +{ + if (context == NULL) return; + + // Clear Event Stack + if (stack == PSP_ADHOC_MATCHING_EVENT_STACK) + { + context->eventlock->lock(); + // Free Memory Recursively + clearStackRecursive(context->event_stack); + + // Destroy Reference + context->event_stack = NULL; + + context->eventlock->unlock(); + } + + // Clear IO Stack + else + { + context->inputlock->lock(); + // Free Memory Recursively + clearStackRecursive(context->input_stack); + + // Destroy Reference + context->input_stack = NULL; + + context->inputlock->unlock(); + } +} + +/** +* Clear Peer List +* @param context Matching Context Pointer +*/ +void clearPeerList(SceNetAdhocMatchingContext * context) +{ + // Acquire Peer Lock + peerlock.lock(); + + // Iterate Peer List + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; + while (peer != NULL) + { + // Grab Next Pointer + context->peerlist = peer->next; //SceNetAdhocMatchingMemberInternal * next = peer->next; + + // Delete Peer + free(peer); //deletePeer(context, peer); + + // Move Pointer + peer = context->peerlist; //peer = next; + } + + // Free Peer Lock + peerlock.unlock(); +} + +bool IsMatchingInCallback(SceNetAdhocMatchingContext * context) { + bool inCB = false; + if (context == NULL) return inCB; + context->eventlock->lock(); //peerlock.lock(); + inCB = (/*context != NULL &&*/ context->IsMatchingInCB); + context->eventlock->unlock(); //peerlock.unlock(); + return inCB; +} + +void AfterMatchingMipsCall::run(MipsCall &call) { + if (context == NULL) return; + DEBUG_LOG(SCENET, "Entering AfterMatchingMipsCall::run [ID=%i][Event=%d] [cbId: %u]", context->id, EventID, call.cbId); + //u32 v0 = currentMIPS->r[MIPS_REG_V0]; + if (__IsInInterrupt()) ERROR_LOG(SCENET, "AfterMatchingMipsCall::run [ID=%i][Event=%d] is Returning Inside an Interrupt!", context->id, EventID); + //while (__IsInInterrupt()) sleep_ms(1); // Must not sleep inside callback handler + context->eventlock->lock(); //peerlock.lock(); + //SceNetAdhocMatchingContext * context = findMatchingContext(ID); + //if (context != NULL) + { + context->IsMatchingInCB = false; + } + context->eventlock->unlock(); //peerlock.unlock(); + //call.setReturnValue(v0); + DEBUG_LOG(SCENET, "Leaving AfterMatchingMipsCall::run [ID=%i][Event=%d] [retV0: %08x]", context->id, EventID, currentMIPS->r[MIPS_REG_V0]); +} + +void AfterMatchingMipsCall::SetContextID(u32 ContextID, u32 eventId) { + EventID = eventId; + peerlock.lock(); + context = findMatchingContext(ContextID); + peerlock.unlock(); +} + +// Make sure MIPS calls have been fully executed before the next notifyAdhocctlHandlers +void notifyAdhocctlHandlers(int flag, int error) { + CoreTiming::ScheduleEvent_Threadsafe_Immediate(eventAdhocctlHandlerUpdate, join32(flag, error)); + //CoreTiming::ScheduleEvent_Threadsafe(usToCycles(1), eventAdhocctlHandlerUpdate, join32(flag, error)); + //__KernelCheckCallbacks(); + //while (__KernelCurHasReadyCallbacks() || __KernelInCallback()) sleep_ms(1); + // TODO: We should use after action instead of guessing the time like this + sleep_ms(20); // Ugly workaround to give time for the mips callback to fully executed, usually only need <16ms +} + +// Matching callback is void function: typedef void(*SceNetAdhocMatchingHandler)(int id, int event, SceNetEtherAddr * peer, int optlen, void * opt); +// Important! The MIPS call need to be fully executed before the next MIPS call invoked, as the game (ie. DBZ Tag Team) may need to prepare something for the next callback event to use +// Note: Must not lock peerlock within this function to prevent race-condition with other thread whos owning peerlock and trying to lock context->eventlock owned by this thread +void notifyMatchingHandler(SceNetAdhocMatchingContext * context, ThreadMessage * msg, void * opt, u32 &bufAddr, u32 &bufLen, u32_le * args) { + //u32_le args[5] = { 0, 0, 0, 0, 0 }; + if ((s32)bufLen < (msg->optlen + 8)) { + bufLen = msg->optlen + 8; + if (Memory::IsValidAddress(bufAddr)) userMemory.Free(bufAddr); + bufAddr = userMemory.Alloc(bufLen); + INFO_LOG(SCENET, "MatchingHandler: Alloc(%i -> %i) = %08x", msg->optlen + 8, bufLen, bufAddr); + } + u8 * optPtr = Memory::GetPointer(bufAddr); + memcpy(optPtr, &msg->mac, sizeof(msg->mac)); + if (msg->optlen > 0) memcpy(optPtr + 8, opt, msg->optlen); + args[0] = context->id; + args[1] = msg->opcode; + args[2] = bufAddr; // PSP_GetScratchpadMemoryBase() + 0x6000; + args[3] = msg->optlen; + args[4] = args[2] + 8; + args[5] = context->handler.entryPoint; //not part of callback argument, just borrowing a space to store callback address so i don't need to search the context first later + + context->IsMatchingInCB = true; + // ScheduleEvent_Threadsafe_Immediate seems to get mixed up with interrupt (returning from mipscall inside an interrupt) and getting invalid address before returning from interrupt + CoreTiming::ScheduleEvent_Threadsafe_Immediate(eventMatchingHandlerUpdate, (u64)args); + //CoreTiming::ScheduleEvent_Threadsafe(usToCycles(1), eventMatchingHandlerUpdate, (u64)args); // I don't like guessing the time like this, if only there is a way to prevent callback from returning inside an interrupt + + /*AfterMatchingMipsCall *after = (AfterMatchingMipsCall *)__KernelCreateAction(actionAfterMatchingMipsCall); // Does Action need to resides in the same address space with the thread that runs callback handlers? + after->SetID(context->id); + __KernelDirectMipsCall(context->handler.entryPoint, after, args, 5, true);*/ + //__KernelCheckCallbacks(); + // Make sure MIPS call have been fully executed before the next notifyMatchingHandler + int count = 0; + while (/*(after != NULL) &&*/ IsMatchingInCallback(context) && (count < 250)) { + sleep_ms(1); + count++; + } + if (count >= 250) ERROR_LOG(SCENET, "MatchingHandler: Callback Failed to Return within %dms!", count); + //sleep_ms(20); // Wait a little more (for context switching may be?) to prevent DBZ Tag Team from getting connection lost, but this will cause lags on Lord of Arcana } void freeFriendsRecursive(SceNetAdhocctlPeerInfo * node) { - // End of List - if(node == NULL) return; + // End of List + if (node == NULL) return; - // Increase Recursion Depth - freeFriendsRecursive(node->next); + // Increase Recursion Depth + freeFriendsRecursive(node->next); - // Free Memory - free(node); + // Free Memory + free(node); } int friendFinder(){ - // Receive Buffer - int rxpos = 0; - uint8_t rx[1024]; + // Receive Buffer + int rxpos = 0; + uint8_t rx[1024]; - // Chat Packet - SceNetAdhocctlChatPacketC2S chat; - chat.base.opcode = OPCODE_CHAT; + // Chat Packet + SceNetAdhocctlChatPacketC2S chat; + chat.base.opcode = OPCODE_CHAT; - // Last Ping Time - uint64_t lastping = 0; + // Last Ping Time + uint64_t lastping = 0; - // Last Time Reception got updated - uint64_t lastreceptionupdate = 0; - - uint64_t now; + // Last Time Reception got updated + uint64_t lastreceptionupdate = 0; - // Log Startup - INFO_LOG(SCENET, "FriendFinder: Begin of Friend Finder Thread"); + uint64_t now; - // Finder Loop - while(friendFinderRunning) { - // Acquire Network Lock - //_acquireNetworkLock(); + // Log Startup + INFO_LOG(SCENET, "FriendFinder: Begin of Friend Finder Thread"); - // Ping Server - now = real_time_now()*1000.0; - if(now - lastping >= 100) { - // Update Ping Time - lastping = now; + // Finder Loop + while (friendFinderRunning) { + // Acquire Network Lock + //_acquireNetworkLock(); - // Prepare Packet - uint8_t opcode = OPCODE_PING; + // Ping Server + now = real_time_now()*1000000.0; // should be in microseconds, but it seems real_time_now() returns in seconds + if (now - lastping >= PSP_ADHOCCTL_PING_TIMEOUT) { //100 // We need to use lower interval to prevent getting timeout at Pro Adhoc Server through internet + // original code : ((sceKernelGetSystemTimeWide() - lastping) >= ADHOCCTL_PING_TIMEOUT) + // Update Ping Time + lastping = now; - // Send Ping to Server, may failed with socket error 10054/10053 if someone else with the same IP already connected to AdHoc Server (the server might need to be modified to differentiate MAC instead of IP) - int iResult = send(metasocket, (const char *)&opcode, 1,0); - /*if (iResult == SOCKET_ERROR) { - ERROR_LOG(SCENET, "FriendFinder: Socket Error (%i) when sending OPCODE_PING", errno); - //friendFinderRunning = false; - }*/ - } + // Prepare Packet + uint8_t opcode = OPCODE_PING; - // Send Chat Messages - //while(popFromOutbox(chat.message)) - //{ - // // Send Chat to Server - // sceNetInetSend(metasocket, (const char *)&chat, sizeof(chat), 0); - //} + // Send Ping to Server, may failed with socket error 10054/10053 if someone else with the same IP already connected to AdHoc Server (the server might need to be modified to differentiate MAC instead of IP) + int iResult = send(metasocket, (const char *)&opcode, 1, 0); + /*if (iResult == SOCKET_ERROR) { + ERROR_LOG(SCENET, "FriendFinder: Socket Error (%i) when sending OPCODE_PING", errno); + //friendFinderRunning = false; + }*/ + } - // Wait for Incoming Data - int received = recv(metasocket, (char *)(rx + rxpos), sizeof(rx) - rxpos,0); + // Send Chat Messages + //while(popFromOutbox(chat.message)) + //{ + // // Send Chat to Server + // sceNetInetSend(metasocket, (const char *)&chat, sizeof(chat), 0); + //} - // Free Network Lock - //_freeNetworkLock(); + // Wait for Incoming Data + int received = recv(metasocket, (char *)(rx + rxpos), sizeof(rx) - rxpos, 0); - // Received Data - if(received > 0) { - // Fix Position - rxpos += received; + // Free Network Lock + //_freeNetworkLock(); - // Log Incoming Traffic - //printf("Received %d Bytes of Data from Server\n", received); - INFO_LOG(SCENET, "Received %d Bytes of Data from Adhoc Server", received); - } + // Received Data + if (received > 0) { + // Fix Position + rxpos += received; - // Handle Packets - if(rxpos > 0) { - // BSSID Packet - if(rx[0] == OPCODE_CONNECT_BSSID) { - INFO_LOG(SCENET, "FriendFinder: Incoming OPCODE_CONNECT_BSSID"); - // Enough Data available - if(rxpos >= (int)sizeof(SceNetAdhocctlConnectBSSIDPacketS2C)) { - // Cast Packet - SceNetAdhocctlConnectBSSIDPacketS2C * packet = (SceNetAdhocctlConnectBSSIDPacketS2C *)rx; - // Update BSSID - parameter.bssid.mac_addr = packet->mac; - // Change State - threadStatus = ADHOCCTL_STATE_CONNECTED; - // Notify Event Handlers - CoreTiming::ScheduleEvent_Threadsafe_Immediate(eventHandlerUpdate, join32(ADHOCCTL_EVENT_CONNECT, 0)); + // Log Incoming Traffic + //printf("Received %d Bytes of Data from Server\n", received); + INFO_LOG(SCENET, "Received %d Bytes of Data from Adhoc Server", received); + } - // Move RX Buffer - memmove(rx, rx + sizeof(SceNetAdhocctlConnectBSSIDPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlConnectBSSIDPacketS2C)); + // Handle Packets + if (rxpos > 0) { + // BSSID Packet + if (rx[0] == OPCODE_CONNECT_BSSID) { + INFO_LOG(SCENET, "FriendFinder: Incoming OPCODE_CONNECT_BSSID"); + // Enough Data available + if (rxpos >= (int)sizeof(SceNetAdhocctlConnectBSSIDPacketS2C)) { + // Cast Packet + SceNetAdhocctlConnectBSSIDPacketS2C * packet = (SceNetAdhocctlConnectBSSIDPacketS2C *)rx; + // Update BSSID + parameter.bssid.mac_addr = packet->mac; + // Change State + threadStatus = ADHOCCTL_STATE_CONNECTED; + // Notify Event Handlers + notifyAdhocctlHandlers(ADHOCCTL_EVENT_CONNECT, 0); - // Fix RX Buffer Length - rxpos -= sizeof(SceNetAdhocctlConnectBSSIDPacketS2C); - } - } + // Move RX Buffer + memmove(rx, rx + sizeof(SceNetAdhocctlConnectBSSIDPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlConnectBSSIDPacketS2C)); - // Chat Packet - else if(rx[0] == OPCODE_CHAT) { - INFO_LOG(SCENET, "FriendFinder: Incoming OPCODE_CHAT"); - // Enough Data available - if(rxpos >= (int)sizeof(SceNetAdhocctlChatPacketS2C)) { - // Cast Packet - SceNetAdhocctlChatPacketS2C * packet = (SceNetAdhocctlChatPacketS2C *)rx; + // Fix RX Buffer Length + rxpos -= sizeof(SceNetAdhocctlConnectBSSIDPacketS2C); + } + } - // Fix for Idiots that try to troll the "ME" Nametag - if(strcasecmp((char *)packet->name.data, "ME") == 0) strcpy((char *)packet->name.data, "NOT ME"); + // Chat Packet + else if (rx[0] == OPCODE_CHAT) { + INFO_LOG(SCENET, "FriendFinder: Incoming OPCODE_CHAT"); + // Enough Data available + if (rxpos >= (int)sizeof(SceNetAdhocctlChatPacketS2C)) { + // Cast Packet + SceNetAdhocctlChatPacketS2C * packet = (SceNetAdhocctlChatPacketS2C *)rx; - // Add Incoming Chat to HUD - //printf("Receive chat message %s", packet->base.message); - DEBUG_LOG(SCENET, "Received chat message %s", packet->base.message); + // Fix for Idiots that try to troll the "ME" Nametag + if (strcasecmp((char *)packet->name.data, "ME") == 0) strcpy((char *)packet->name.data, "NOT ME"); - // Move RX Buffer - memmove(rx, rx + sizeof(SceNetAdhocctlChatPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlChatPacketS2C)); + // Add Incoming Chat to HUD + //printf("Receive chat message %s", packet->base.message); + DEBUG_LOG(SCENET, "Received chat message %s", packet->base.message); - // Fix RX Buffer Length - rxpos -= sizeof(SceNetAdhocctlChatPacketS2C); - } - } + // Move RX Buffer + memmove(rx, rx + sizeof(SceNetAdhocctlChatPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlChatPacketS2C)); - // Connect Packet - else if(rx[0] == OPCODE_CONNECT) { - DEBUG_LOG(SCENET, "FriendFinder: OPCODE_CONNECT"); - // Enough Data available - if(rxpos >= (int)sizeof(SceNetAdhocctlConnectPacketS2C)) { - // Log Incoming Peer - INFO_LOG(SCENET,"Incoming Peer Data..."); + // Fix RX Buffer Length + rxpos -= sizeof(SceNetAdhocctlChatPacketS2C); + } + } - // Cast Packet - SceNetAdhocctlConnectPacketS2C * packet = (SceNetAdhocctlConnectPacketS2C *)rx; + // Connect Packet + else if (rx[0] == OPCODE_CONNECT) { + DEBUG_LOG(SCENET, "FriendFinder: OPCODE_CONNECT"); + // Enough Data available + if (rxpos >= (int)sizeof(SceNetAdhocctlConnectPacketS2C)) { + // Log Incoming Peer + INFO_LOG(SCENET, "Incoming Peer Data..."); - // Add User - addFriend(packet); + // Cast Packet + SceNetAdhocctlConnectPacketS2C * packet = (SceNetAdhocctlConnectPacketS2C *)rx; - // Update HUD User Count + // Add User + addFriend(packet); + + // Update HUD User Count #ifdef LOCALHOST_AS_PEER - setUserCount(getActivePeerCount()); + setUserCount(getActivePeerCount()); #else - // setUserCount(getActivePeerCount()+1); + // setUserCount(getActivePeerCount()+1); #endif - // Move RX Buffer - memmove(rx, rx + sizeof(SceNetAdhocctlConnectPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlConnectPacketS2C)); + // Move RX Buffer + memmove(rx, rx + sizeof(SceNetAdhocctlConnectPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlConnectPacketS2C)); - // Fix RX Buffer Length - rxpos -= sizeof(SceNetAdhocctlConnectPacketS2C); - } - } + // Fix RX Buffer Length + rxpos -= sizeof(SceNetAdhocctlConnectPacketS2C); + } + } - // Disconnect Packet - else if(rx[0] == OPCODE_DISCONNECT) { - DEBUG_LOG(SCENET, "FriendFinder: OPCODE_DISCONNECT"); - // Enough Data available - if(rxpos >= (int)sizeof(SceNetAdhocctlDisconnectPacketS2C)) { - // Log Incoming Peer Delete Request - INFO_LOG(SCENET,"FriendFinder: Incoming Peer Data Delete Request..."); + // Disconnect Packet + else if (rx[0] == OPCODE_DISCONNECT) { + DEBUG_LOG(SCENET, "FriendFinder: OPCODE_DISCONNECT"); + // Enough Data available + if (rxpos >= (int)sizeof(SceNetAdhocctlDisconnectPacketS2C)) { + // Log Incoming Peer Delete Request + INFO_LOG(SCENET, "FriendFinder: Incoming Peer Data Delete Request..."); - // Cast Packet - SceNetAdhocctlDisconnectPacketS2C * packet = (SceNetAdhocctlDisconnectPacketS2C *)rx; + // Cast Packet + SceNetAdhocctlDisconnectPacketS2C * packet = (SceNetAdhocctlDisconnectPacketS2C *)rx; - // Delete User by IP, should delete by MAC since IP can be shared (behind NAT) isn't? - deleteFriendByIP(packet->ip); + // Delete User by IP, should delete by MAC since IP can be shared (behind NAT) isn't? + deleteFriendByIP(packet->ip); - // Update HUD User Count + // Update HUD User Count #ifdef LOCALHOST_AS_PEER - setUserCount(_getActivePeerCount()); + setUserCount(_getActivePeerCount()); #else - //setUserCount(_getActivePeerCount()+1); + //setUserCount(_getActivePeerCount()+1); #endif - // Move RX Buffer - memmove(rx, rx + sizeof(SceNetAdhocctlDisconnectPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlDisconnectPacketS2C)); + // Move RX Buffer + memmove(rx, rx + sizeof(SceNetAdhocctlDisconnectPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlDisconnectPacketS2C)); - // Fix RX Buffer Length - rxpos -= sizeof(SceNetAdhocctlDisconnectPacketS2C); - } - } + // Fix RX Buffer Length + rxpos -= sizeof(SceNetAdhocctlDisconnectPacketS2C); + } + } - // Scan Packet - else if(rx[0] == OPCODE_SCAN) { - DEBUG_LOG(SCENET, "FriendFinder: OPCODE_SCAN"); - // Enough Data available - if(rxpos >= (int)sizeof(SceNetAdhocctlScanPacketS2C)) { - // Log Incoming Network Information - INFO_LOG(SCENET,"Incoming Group Information..."); - // Cast Packet - SceNetAdhocctlScanPacketS2C * packet = (SceNetAdhocctlScanPacketS2C *)rx; + // Scan Packet + else if (rx[0] == OPCODE_SCAN) { + DEBUG_LOG(SCENET, "FriendFinder: OPCODE_SCAN"); + // Enough Data available + if (rxpos >= (int)sizeof(SceNetAdhocctlScanPacketS2C)) { + // Log Incoming Network Information + INFO_LOG(SCENET, "Incoming Group Information..."); + // Cast Packet + SceNetAdhocctlScanPacketS2C * packet = (SceNetAdhocctlScanPacketS2C *)rx; - // Multithreading Lock - peerlock.lock(); + // Multithreading Lock + peerlock.lock(); - // It seems AdHoc Server always sent the full group list, so we should reset group list during Scan initialization + // Should only add non-existing group (or replace an existing group) to prevent Ford Street Racing from showing a strange game session list + /*SceNetAdhocctlScanInfo * group = findGroup(&packet->mac); - // Should only add non-existing group (or replace an existing group) to prevent Ford Street Racing from showing a strange game session list - /*SceNetAdhocctlScanInfo * group = findGroup(&packet->mac); + if (group != NULL) { + // Copy Group Name + group->group_name = packet->group; - if (group != NULL) { - // Copy Group Name - group->group_name = packet->group; + // Set Group Host + group->bssid.mac_addr = packet->mac; + } + else*/ + { + // Allocate Structure Data + SceNetAdhocctlScanInfo * group = (SceNetAdhocctlScanInfo *)malloc(sizeof(SceNetAdhocctlScanInfo)); - // Set Group Host - group->bssid.mac_addr = packet->mac; - } - else*/ { - // Allocate Structure Data - SceNetAdhocctlScanInfo * group = (SceNetAdhocctlScanInfo *)malloc(sizeof(SceNetAdhocctlScanInfo)); + // Allocated Structure Data + if (group != NULL) + { + // Clear Memory, should this be done only when allocating new group? + memset(group, 0, sizeof(SceNetAdhocctlScanInfo)); - // Allocated Structure Data - if (group != NULL) - { - // Clear Memory, should this be done only when allocating new group? - memset(group, 0, sizeof(SceNetAdhocctlScanInfo)); + // Link to existing Groups + group->next = newnetworks; - // Link to existing Groups - group->next = networks; + // Copy Group Name + group->group_name = packet->group; - // Copy Group Name - group->group_name = packet->group; + // Set Group Host + group->bssid.mac_addr = packet->mac; - // Set Group Host - group->bssid.mac_addr = packet->mac; + // Link into Group List + newnetworks = group; + } + } - // Link into Group List - networks = group; - } - } + // Multithreading Unlock + peerlock.unlock(); - // Multithreading Unlock - peerlock.unlock(); + // Move RX Buffer + memmove(rx, rx + sizeof(SceNetAdhocctlScanPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlScanPacketS2C)); - // Move RX Buffer - memmove(rx, rx + sizeof(SceNetAdhocctlScanPacketS2C), sizeof(rx) - sizeof(SceNetAdhocctlScanPacketS2C)); + // Fix RX Buffer Length + rxpos -= sizeof(SceNetAdhocctlScanPacketS2C); + } + } - // Fix RX Buffer Length - rxpos -= sizeof(SceNetAdhocctlScanPacketS2C); - } - } + // Scan Complete Packet + else if (rx[0] == OPCODE_SCAN_COMPLETE) { + DEBUG_LOG(SCENET, "FriendFinder: OPCODE_SCAN_COMPLETE"); + // Log Scan Completion + INFO_LOG(SCENET, "FriendFinder: Incoming Scan complete response..."); - // Scan Complete Packet - else if(rx[0] == OPCODE_SCAN_COMPLETE) { - DEBUG_LOG(SCENET, "FriendFinder: OPCODE_SCAN_COMPLETE"); - // Log Scan Completion - INFO_LOG(SCENET,"FriendFinder: Incoming Scan complete response..."); + // Reset current networks to prevent leaving host to be listed again + peerlock.lock(); + freeGroupsRecursive(networks); + networks = newnetworks; + newnetworks = NULL; + peerlock.unlock(); - // Change State - threadStatus = ADHOCCTL_STATE_DISCONNECTED; + // Change State + threadStatus = ADHOCCTL_STATE_DISCONNECTED; - // Notify Event Handlers - CoreTiming::ScheduleEvent_Threadsafe_Immediate(eventHandlerUpdate,join32(ADHOCCTL_EVENT_SCAN, 0)); - //int i = 0; for(; i < ADHOCCTL_MAX_HANDLER; i++) - //{ - // // Active Handler - // if(_event_handler[i] != NULL) _event_handler[i](ADHOCCTL_EVENT_SCAN, 0, _event_args[i]); - //} + // Notify Event Handlers + notifyAdhocctlHandlers(ADHOCCTL_EVENT_SCAN, 0); + //int i = 0; for(; i < ADHOCCTL_MAX_HANDLER; i++) + //{ + // // Active Handler + // if(_event_handler[i] != NULL) _event_handler[i](ADHOCCTL_EVENT_SCAN, 0, _event_args[i]); + //} - // Move RX Buffer - memmove(rx, rx + 1, sizeof(rx) - 1); + // Move RX Buffer + memmove(rx, rx + 1, sizeof(rx) - 1); - // Fix RX Buffer Length - rxpos -= 1; - } - } - // Original value was 10 ms, I think 100 is just fine - sleep_ms(100); - } + // Fix RX Buffer Length + rxpos -= 1; + } + } + // Original value was 10 ms, I think 100 is just fine + sleep_ms(1); // Using 1ms for faster response just like AdhocServer - // Groups/Networks should be deallocated isn't? + // Don't do anything if it's paused, otherwise the log will be flooded + while (Core_IsStepping() && friendFinderRunning) sleep_ms(1); + } - // Prevent the games from having trouble to reInitiate Adhoc (the next NetInit -> PdpCreate after NetTerm) - threadStatus = ADHOCCTL_STATE_DISCONNECTED; + // Groups/Networks should be deallocated isn't? - // Log Shutdown - INFO_LOG(SCENET, "FriendFinder: End of Friend Finder Thread"); + // Prevent the games from having trouble to reInitiate Adhoc (the next NetInit -> PdpCreate after NetTerm) + threadStatus = ADHOCCTL_STATE_DISCONNECTED; - // Return Success - return 0; + // Log Shutdown + INFO_LOG(SCENET, "FriendFinder: End of Friend Finder Thread"); + + // Return Success + return 0; } int getActivePeerCount(void) { - // Counter - int count = 0; + // Counter + int count = 0; - // #ifdef LOCALHOST_AS_PEER - // // Increase for Localhost - // count++; - // #endif + // #ifdef LOCALHOST_AS_PEER + // // Increase for Localhost + // count++; + // #endif - // Peer Reference - SceNetAdhocctlPeerInfo * peer = friends; + // Peer Reference + SceNetAdhocctlPeerInfo * peer = friends; - // Iterate Peers - for(; peer != NULL; peer = peer->next) { - // Increase Counter - count++; - } + // Iterate Peers + for (; peer != NULL; peer = peer->next) { + // Increase Counter + count++; + } - // Return Result - return count; + // Return Result + return count; } int getLocalIp(sockaddr_in * SocketAddress){ @@ -670,39 +1335,94 @@ uint16_t getLocalPort(int sock) { localAddr.sin_port = 0; socklen_t addrLen = sizeof(localAddr); getsockname(sock, (struct sockaddr*)&localAddr, &addrLen); - return localAddr.sin_port; + return ntohs(localAddr.sin_port); +} + +int getSockBufferSize(int sock, int opt) { // opt = SO_RCVBUF/SO_SNDBUF + int n = 16384; + socklen_t m = sizeof(n); + getsockopt(sock, SOL_SOCKET, opt, (char *)&n, &m); // in linux the value is twice of the value being set using setsockopt + return (n/2); +} + +int setSockBufferSize(int sock, int opt, int size) { // opt = SO_RCVBUF/SO_SNDBUF + int n = size; // 8192; //16384 + return setsockopt(sock, SOL_SOCKET, opt, (char *)&n, sizeof(n)); +} + +/** +* Return the Number of Players with the chosen Nickname in the Local Users current Network +* @param nickname To-be-searched Nickname +* @return Number of matching Players +*/ +int getNicknameCount(const char * nickname) +{ + // Counter + int count = 0; + + // Local Nickname Matches + if (strcmp((char *)parameter.nickname.data, nickname) == 0) count++; + + // Peer Reference + SceNetAdhocctlPeerInfo * peer = friends; + + // Iterate Peers + for (; peer != NULL; peer = peer->next) + { + // Match found + if (strcmp((char *)peer->nickname.data, nickname) == 0) count++; + } + + // Return Result + return count; +} + +/** +* PDP Socket Counter +* @return Number of internal PDP Sockets +*/ +int getPDPSocketCount(void) +{ + // Socket Counter + int counter = 0; + + // Count Sockets + int i = 0; for (; i < 255; i++) if (pdp[i] != NULL) counter++; + + // Return Socket Count + return counter; } int getPTPSocketCount(void) { - // Socket Counter - int counter = 0; + // Socket Counter + int counter = 0; - // Count Sockets - int i = 0; for(; i < 255; i++) if(ptp[i] != NULL) counter++; + // Count Sockets + int i = 0; for (; i < 255; i++) if (ptp[i] != NULL) counter++; - // Return Socket Count - return counter; + // Return Socket Count + return counter; } int initNetwork(SceNetAdhocctlAdhocId *adhoc_id){ - int iResult = 0; -#ifdef _MSC_VER - WSADATA data; - iResult = WSAStartup(MAKEWORD(2,2),&data); // Might be better to call WSAStartup/WSACleanup from sceNetInit/sceNetTerm isn't? since it's the first/last network function being used - if(iResult != NOERROR){ - ERROR_LOG(SCENET, "WSA failed"); - return iResult; - } -#endif - metasocket = (int)INVALID_SOCKET; - metasocket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP); - if(metasocket == INVALID_SOCKET){ - ERROR_LOG(SCENET,"Invalid socket"); - return -1; - } - struct sockaddr_in server_addr; - server_addr.sin_family = AF_INET; - server_addr.sin_port = htons(27312); // Maybe read this from config too + int iResult = 0; +/*#ifdef _MSC_VER + WSADATA data; + iResult = WSAStartup(MAKEWORD(2,2),&data); // Might be better to call WSAStartup/WSACleanup from sceNetInit/sceNetTerm isn't? since it's the first/last network function being used, even better to put it in __NetInit/__NetShutdown as it's only called once + if(iResult != NOERROR){ + ERROR_LOG(SCENET, "WSA failed"); + return iResult; + } +#endif*/ + metasocket = (int)INVALID_SOCKET; + metasocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (metasocket == INVALID_SOCKET){ + ERROR_LOG(SCENET, "Invalid socket"); + return -1; + } + struct sockaddr_in server_addr; + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(SERVER_PORT); //27312 // Maybe read this from config too // Resolve dns addrinfo * resultAddr; @@ -712,7 +1432,7 @@ int initNetwork(SceNetAdhocctlAdhocId *adhoc_id){ iResult = getaddrinfo(g_Config.proAdhocServer.c_str(),0,NULL,&resultAddr); if (iResult != 0) { - ERROR_LOG(SCENET, "DNS error (%s)\n", g_Config.proAdhocServer.c_str()); + ERROR_LOG(SCENET, "DNS Error (%s)\n", g_Config.proAdhocServer.c_str()); return iResult; } for (ptr = resultAddr; ptr != NULL; ptr = ptr->ai_next) { @@ -722,6 +1442,12 @@ int initNetwork(SceNetAdhocctlAdhocId *adhoc_id){ break; } } + + memset(¶meter, 0, sizeof(parameter)); + strcpy((char *)¶meter.nickname.data, g_Config.sNickName.c_str()); + parameter.channel = 1; // Fake Channel 1 + getLocalMac(¶meter.bssid.mac_addr); + server_addr.sin_addr = serverIp; iResult = connect(metasocket,(sockaddr *)&server_addr,sizeof(server_addr)); if (iResult == SOCKET_ERROR) { @@ -729,128 +1455,214 @@ int initNetwork(SceNetAdhocctlAdhocId *adhoc_id){ ERROR_LOG(SCENET, "Socket error (%i) when connecting to %s/%u.%u.%u.%u:%u", errno, g_Config.proAdhocServer.c_str(), sip[0], sip[1], sip[2], sip[3], ntohs(server_addr.sin_port)); return iResult; } - memset(¶meter,0,sizeof(parameter)); - strcpy((char *)¶meter.nickname.data, g_Config.sNickName.c_str()); - parameter.channel = 1; // Fake Channel 1 - // Prepare Login Packet - getLocalMac(¶meter.bssid.mac_addr); - SceNetAdhocctlLoginPacketC2S packet; - packet.base.opcode = OPCODE_LOGIN; - SceNetEtherAddr addres; - getLocalMac(&addres); - packet.mac = addres; - strcpy((char *)packet.name.data, g_Config.sNickName.c_str()); - memcpy(packet.game.data, adhoc_id->data, ADHOCCTL_ADHOCID_LEN); - int sent = send(metasocket, (char*)&packet, sizeof(packet), 0); - changeBlockingMode(metasocket,1); // Change to non-blocking - if(sent > 0){ - return 0; - }else{ - return -1; - } + + // Prepare Login Packet + SceNetAdhocctlLoginPacketC2S packet; + packet.base.opcode = OPCODE_LOGIN; + SceNetEtherAddr addres; + getLocalMac(&addres); + packet.mac = addres; + strcpy((char *)packet.name.data, g_Config.sNickName.c_str()); + memcpy(packet.game.data, adhoc_id->data, ADHOCCTL_ADHOCID_LEN); + int sent = send(metasocket, (char*)&packet, sizeof(packet), 0); + changeBlockingMode(metasocket, 1); // Change to non-blocking + if (sent > 0){ + return 0; + } + else{ + return -1; + } } bool isBroadcastMAC(const SceNetEtherAddr * addr) { - return memcmp(addr->data, "\xFF\xFF\xFF\xFF\xFF\xFF", ETHER_ADDR_LEN) == 0; + // Broadcast MAC + if (memcmp(addr->data, "\xFF\xFF\xFF\xFF\xFF\xFF", ETHER_ADDR_LEN) == 0) return true; + // Normal MAC + return false; } bool resolveIP(uint32_t ip, SceNetEtherAddr * mac) { - sockaddr_in addr; - getLocalIp(&addr); - uint32 localIp = addr.sin_addr.s_addr; + sockaddr_in addr; + getLocalIp(&addr); + uint32 localIp = addr.sin_addr.s_addr; - if (ip == localIp) { - getLocalMac(mac); - return true; - } + if (ip == localIp){ + getLocalMac(mac); + return true; + } - // Multithreading Lock - peerlock.lock(); + // Multithreading Lock + peerlock.lock(); - // Iterate Peers - for (SceNetAdhocctlPeerInfo* peer = friends; peer != NULL; peer = peer->next) { - // Found Matching Peer - if (peer->ip_addr == ip) { - // Copy Data - *mac = peer->mac_addr; + // Peer Reference + SceNetAdhocctlPeerInfo * peer = friends; - // Multithreading Unlock - peerlock.unlock(); + // Iterate Peers + for (; peer != NULL; peer = peer->next) { + // Found Matching Peer + if (peer->ip_addr == ip) { + // Copy Data + *mac = peer->mac_addr; - // Return Success - return true; - } - } + // Multithreading Unlock + peerlock.unlock(); - // Multithreading Unlock - peerlock.unlock(); + // Return Success + return true; + } + } - // Peer not found - return false; + // Multithreading Unlock + peerlock.unlock(); + + // Peer not found + return false; } bool resolveMAC(SceNetEtherAddr * mac, uint32_t * ip) { - // Get Local MAC Address - SceNetEtherAddr localMac; - getLocalMac(&localMac); - // Local MAC Requested - if (memcmp(&localMac, mac, sizeof(SceNetEtherAddr)) == 0) { - // Get Local IP Address - sockaddr_in sockAddr; - getLocalIp(&sockAddr); - *ip = sockAddr.sin_addr.s_addr; - return true; - } + // Get Local MAC Address + SceNetEtherAddr localMac; + getLocalMac(&localMac); + // Local MAC Requested + if (memcmp(&localMac, mac, sizeof(SceNetEtherAddr)) == 0) { + // Get Local IP Address + sockaddr_in sockAddr; + getLocalIp(&sockAddr); + *ip = sockAddr.sin_addr.s_addr; + return true; // return succes + } - // Multithreading Lock - peerlock.lock(); + // Multithreading Lock + peerlock.lock(); - // Iterate Peers - for (SceNetAdhocctlPeerInfo * peer = friends; peer != NULL; peer = peer->next) { - // Found Matching Peer - if (memcmp(&peer->mac_addr, mac, sizeof(SceNetEtherAddr)) == 0) { - // Copy Data - *ip = peer->ip_addr; + // Peer Reference + SceNetAdhocctlPeerInfo * peer = friends; - // Multithreading Unlock - peerlock.unlock(); + // Iterate Peers + for (; peer != NULL; peer = peer->next) { + // Found Matching Peer + if (memcmp(&peer->mac_addr, mac, sizeof(SceNetEtherAddr)) == 0) { + // Copy Data + *ip = peer->ip_addr; - return true; - } - } + // Multithreading Unlock + peerlock.unlock(); - // Multithreading Unlock - peerlock.unlock(); + // Return Success + return true; + } + } - // Peer not found - return false; + // Multithreading Unlock + peerlock.unlock(); + + // Peer not found + return false; } bool validNetworkName(const SceNetAdhocctlGroupName * group_name) { - // Name given - if (group_name != NULL) { - for (int i = 0; i < ADHOCCTL_GROUPNAME_LEN; i++) { - // End of Name - if (group_name->data[i] == 0) - break; + // Result + int valid = true; - // Invalid name - if (!::isalnum(group_name->data[i])) - return false; - } - } + // Name given + if (group_name != NULL) { + // Iterate Name Characters + int i = 0; for (; i < ADHOCCTL_GROUPNAME_LEN && valid; i++) { + // End of Name + if (group_name->data[i] == 0) break; - return true; + // Not a digit + if (group_name->data[i] < '0' || group_name->data[i] > '9') { + // Not 'A' to 'Z' + if (group_name->data[i] < 'A' || group_name->data[i] > 'Z') { + // Not 'a' to 'z' + if (group_name->data[i] < 'a' || group_name->data[i] > 'z') { + // Invalid Name + valid = false; + } + } + } + } + } + // Return Result + return valid; } u64 join32(u32 num1, u32 num2){ - return (u64)num2 << 32 | num1; + return (u64)num2 << 32 | num1; } void split64(u64 num, int buff[]){ - int num1 = (int)(num&firstMask); - int num2 = (int)((num&secondMask)>>32); - buff[0] = num1; - buff[1] = num2; + int num1 = (int)(num&firstMask); + int num2 = (int)((num&secondMask) >> 32); + buff[0] = num1; + buff[1] = num2; } + +char* getMatchingEventStr(int code, char* buf) { + if (buf == NULL) return NULL; + switch (code) { + case PSP_ADHOC_MATCHING_EVENT_HELLO: + buf = "HELLO"; break; + case PSP_ADHOC_MATCHING_EVENT_REQUEST: + buf = "JOIN"; break; + case PSP_ADHOC_MATCHING_EVENT_LEAVE: + buf = "LEAVE"; break; + case PSP_ADHOC_MATCHING_EVENT_DENY: + buf = "REJECT"; break; + case PSP_ADHOC_MATCHING_EVENT_CANCEL: + buf = "CANCEL"; break; + case PSP_ADHOC_MATCHING_EVENT_ACCEPT: + buf = "ACCEPT"; break; + case PSP_ADHOC_MATCHING_EVENT_ESTABLISHED: + buf = "ESTABLISHED"; break; + case PSP_ADHOC_MATCHING_EVENT_TIMEOUT: + buf = "TIMEOUT"; break; + case PSP_ADHOC_MATCHING_EVENT_ERROR: + buf = "ERROR"; break; + case PSP_ADHOC_MATCHING_EVENT_BYE: + buf = "DISCONNECT"; break; + case PSP_ADHOC_MATCHING_EVENT_DATA: + buf = "DATA"; break; + case PSP_ADHOC_MATCHING_EVENT_DATA_ACK: + buf = "DATA_ACK"; break; + case PSP_ADHOC_MATCHING_EVENT_DATA_TIMEOUT: + buf = "DATA_TIMEOUT"; break; + case PSP_ADHOC_MATCHING_EVENT_INTERNAL_PING: + buf = "INTERNAL_PING"; break; + default: + buf = "UNKNOWN"; + } + return buf; +} + +char* getMatchingOpcodeStr(int code, char* buf) { + if (buf == NULL) return NULL; + switch (code) { + case PSP_ADHOC_MATCHING_PACKET_PING: + buf = "PING"; break; + case PSP_ADHOC_MATCHING_PACKET_HELLO: + buf = "HELLO"; break; + case PSP_ADHOC_MATCHING_PACKET_JOIN: + buf = "JOIN"; break; + case PSP_ADHOC_MATCHING_PACKET_ACCEPT: + buf = "ACCEPT"; break; + case PSP_ADHOC_MATCHING_PACKET_CANCEL: + buf = "CANCEL"; break; + case PSP_ADHOC_MATCHING_PACKET_BULK: + buf = "BULK"; break; + case PSP_ADHOC_MATCHING_PACKET_BULK_ABORT: + buf = "BULK_ABORT"; break; + case PSP_ADHOC_MATCHING_PACKET_BIRTH: + buf = "BIRTH"; break; + case PSP_ADHOC_MATCHING_PACKET_DEATH: + buf = "DEATH"; break; + case PSP_ADHOC_MATCHING_PACKET_BYE: + buf = "BYE"; break; + default: + buf = "UNKNOWN"; + } + return buf; +} + diff --git a/Core/HLE/proAdhoc.h b/Core/HLE/proAdhoc.h index 5757f89074..ca17493dfd 100644 --- a/Core/HLE/proAdhoc.h +++ b/Core/HLE/proAdhoc.h @@ -1,14 +1,34 @@ +// 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/. + #pragma once #include "base/timeutil.h" #include "base/mutex.h" #include "thread/thread.h" #include "net/resolve.h" +#include "Common/ChunkFile.h" #include "Core/Config.h" #include "Core/CoreTiming.h" +#include "Core/MemMap.h" #include "Core/HLE/HLE.h" #include "Core/HLE/sceNetAdhoc.h" +#include "Core/HLE/sceKernelThread.h" #include "Core/HLE/sceKernel.h" #include "Core/HLE/sceKernelMutex.h" #include "Core/HLE/sceUtility.h" @@ -22,8 +42,10 @@ typedef int socklen_t; #elif defined(_MSC_VER) #include #else +#include #include #include +#include #include #include #include @@ -33,13 +55,21 @@ typedef int socklen_t; #ifdef _MSC_VER #define PACK #undef errno +#undef ECONNABORTED +#undef ECONNRESET +#undef ENOTCONN #undef EAGAIN #undef EINPROGRESS #undef EISCONN +#undef EALREADY #define errno WSAGetLastError() +#define ECONNABORTED WSAECONNABORTED +#define ECONNRESET WSAECONNRESET +#define ENOTCONN WSAENOTCONN #define EAGAIN WSAEWOULDBLOCK #define EINPROGRESS WSAEWOULDBLOCK #define EISCONN WSAEISCONN +#define EALREADY WSAEALREADY inline bool connectInProgress(int errcode){ return (errcode == WSAEWOULDBLOCK || errcode == WSAEINVAL || errcode == WSAEALREADY); } #else #define INVALID_SOCKET -1 @@ -49,8 +79,25 @@ inline bool connectInProgress(int errcode){ return (errcode == WSAEWOULDBLOCK || inline bool connectInProgress(int errcode){ return (errcode == EINPROGRESS); } #endif +#ifndef POLL_ERR +#define POLL_ERR 0x008 /* Error condition. */ +#endif +#ifndef POLLERR +#define POLLERR POLL_ERR +#endif + +#ifndef POLL_PRI +#define POLL_PRI 0x002 /* There is urgent data to read. */ +#endif +#ifndef POLLPRI +#define POLLPRI POLL_PRI +#endif + #define IsMatch(buf1, buf2) (memcmp(&buf1, &buf2, sizeof(buf1)) == 0) +// Server Listening Port +#define SERVER_PORT 27312 + // psp strutcs and definitions #define ADHOCCTL_MODE_ADHOC 0 #define ADHOCCTL_MODE_GAMEMODE 1 @@ -78,10 +125,50 @@ inline bool connectInProgress(int errcode){ return (errcode == EINPROGRESS); } #define UTILITY_NETCONF_STATUS_FINISHED 3 #define UTILITY_NETCONF_STATUS_SHUTDOWN 4 +// Event Flags +#define ADHOC_EV_SEND 0x0001 +#define ADHOC_EV_RECV 0x0002 +#define ADHOC_EV_CONNECT 0x0004 +#define ADHOC_EV_ACCEPT 0x0008 +#define ADHOC_EV_FLUSH 0x0010 +#define ADHOC_EV_INVALID 0x0100 +#define ADHOC_EV_DELETE 0x0200 +#define ADHOC_EV_ALERT 0x0400 +#define ADHOC_EV_DISCONNECT 0x0800 + // PTP Connection States -#define PTP_STATE_CLOSED 0 -#define PTP_STATE_LISTEN 1 -#define PTP_STATE_ESTABLISHED 4 +#define ADHOC_PTP_STATE_CLOSED 0 +#define ADHOC_PTP_STATE_LISTEN 1 +#define ADHOC_PTP_STATE_SYN_SENT 2 +#define ADHOC_PTP_STATE_SYN_RCVD 3 +#define ADHOC_PTP_STATE_ESTABLISHED 4 + +// Nonblocking Flag for Adhoc socket API +#define ADHOC_F_NONBLOCK 0x0001 +// Alert Flags +#define ADHOC_F_ALERTSEND 0x0010 +#define ADHOC_F_ALERTRECV 0x0020 +#define ADHOC_F_ALERTPOLL 0x0040 +#define ADHOC_F_ALERTCONNECT 0x0080 +#define ADHOC_F_ALERTACCEPT 0x0100 +#define ADHOC_F_ALERTFLUSH 0x0200 +#define ADHOC_F_ALERTALL (ADHOC_F_ALERTSEND | ADHOC_F_ALERTRECV | ADHOC_F_ALERTPOLL | ADHOC_F_ALERTCONNECT | ADHOC_F_ALERTACCEPT | ADHOC_F_ALERTFLUSH) + +/* PDP Maximum Fragment Size */ +#define PSP_ADHOC_PDP_MFS 1444 + +/* PDP Maximum Transfer Unit */ +#define PSP_ADHOC_PDP_MTU 65523 + +/* PTP Maximum Segment Size */ +#define PSP_ADHOC_PTP_MSS 1444 + +/* GameMode Optional Data */ +#define ADHOC_GAMEMODE_F_UPDATE 0x00000001 + +// Timeouts +#define PSP_ADHOCCTL_RECV_TIMEOUT 100000 +#define PSP_ADHOCCTL_PING_TIMEOUT 2000000 #ifdef _MSC_VER #pragma pack(push, 1) @@ -92,6 +179,15 @@ typedef struct SceNetEtherAddr { uint8_t data[ETHER_ADDR_LEN]; } PACK SceNetEtherAddr; +// Broadcast MAC +extern uint8_t broadcastMAC[ETHER_ADDR_LEN]; + +// Malloc Pool Information +typedef struct SceNetMallocStat { + s32_le pool; // Pointer to the pool? + s32_le maximum; // Maximum size of the pool? + s32_le free; // How much memory is free +} PACK SceNetMallocStat; // Adhoc Virtual Network Name #define ADHOCCTL_GROUPNAME_LEN 8 @@ -144,7 +240,7 @@ typedef struct SceNetAdhocctlPeerInfo { SceNetEtherAddr mac_addr; u32_le ip_addr; uint8_t padding[2]; - u64_le last_recv; + u64_le last_recv; // Need to use the same method with sceKernelGetSystemTimeWide (ie. CoreTiming::GetGlobalTimeUsScaled) to prevent timing issue (ie. in game timeout) } PACK SceNetAdhocctlPeerInfo; // Peer Information with u32 pointers @@ -152,9 +248,9 @@ typedef struct SceNetAdhocctlPeerInfoEmu { u32_le next; // Changed the pointer to u32 SceNetAdhocctlNickname nickname; SceNetEtherAddr mac_addr; - u32_le ip_addr; - u32 padding; // Changed the pointer to u32 - u64_le last_recv; + u32_le ip_addr; //jpcsp wrote 6bytes of 0x11 for this & padding + u16 padding; // Changed the padding to u16 + u64_le last_recv; // Need to use the same method with sceKernelGetSystemTimeWide (ie. CoreTiming::GetGlobalTimeUsScaled) to prevent timing issue (ie. in game timeout) } PACK SceNetAdhocctlPeerInfoEmu; // Member Information @@ -177,6 +273,52 @@ typedef struct SceNetAdhocctlGameModeInfo { s32_le num; SceNetEtherAddr member[ADHOCCTL_GAMEMODE_MAX_MEMBERS]; } PACK SceNetAdhocctlGameModeInfo; + +// Socket Polling Event Listener +typedef struct SceNetAdhocPollSd{ + s32_le id; + s32_le events; + s32_le revents; +} PACK SceNetAdhocPollSd; + +// PDP Socket Status +typedef struct SceNetAdhocPdpStat{ + u32_le next; // struct SceNetAdhocPdpStat * next; + s32_le id; + SceNetEtherAddr laddr; + u16_le lport; + u32_le rcv_sb_cc; +} PACK SceNetAdhocPdpStat; + +// PTP Socket Status +typedef struct SceNetAdhocPtpStat { + u32_le next; // Changed the pointer to u32 + s32_le id; + SceNetEtherAddr laddr; + SceNetEtherAddr paddr; + u16_le lport; + u16_le pport; + s32_le snd_sb_cc; + s32_le rcv_sb_cc; + s32_le state; +} PACK SceNetAdhocPtpStat; + +// Gamemode Optional Peer Buffer Data +typedef struct SceNetAdhocGameModeOptData { + u32_le size; + u32_le flag; + u64_le last_recv; // Need to use the same method with sceKernelGetSystemTimeWide (ie. CoreTiming::GetGlobalTimeUsScaled) to prevent timing issue (ie. in game timeout) +} PACK SceNetAdhocGameModeOptData; + +// Gamemode Buffer Status +typedef struct SceNetAdhocGameModeBufferStat { + struct SceNetAdhocGameModeBufferStat * next; //should be u32_le ? + s32_le id; + void * ptr; //should be u32_le ? + u32_le size; + u32_le master; + SceNetAdhocGameModeOptData opt; +} PACK SceNetAdhocGameModeBufferStat; #ifdef _MSC_VER #pragma pack(pop) #endif @@ -184,57 +326,10 @@ typedef struct SceNetAdhocctlGameModeInfo { // Adhoc ID (Game Product Key) #define ADHOCCTL_ADHOCID_LEN 9 typedef struct SceNetAdhocctlAdhocId { - s32_le type; - uint8_t data[ADHOCCTL_ADHOCID_LEN]; - uint8_t padding[3]; -} SceNetAdhocctlAdhocId; - -// Socket Polling Event Listener -struct SceNetAdhocPollSd { - s32_le id; - s32_le events; - s32_le revents; -}; - -// PDP Socket Status -struct SceNetAdhocPdpStat { - struct SceNetAdhocPdpStat * next; - s32_le id; - SceNetEtherAddr laddr; - u16_le lport; - u32_le rcv_sb_cc; -}; - -// PTP Socket Status -struct SceNetAdhocPtpStat { - u32_le next; // Changed the pointer to u32 - s32_le id; - SceNetEtherAddr laddr; - SceNetEtherAddr paddr; - u16_le lport; - u16_le pport; - u32_le snd_sb_cc; - u32_le rcv_sb_cc; - s32_le state; -}; - -// Gamemode Optional Peer Buffer Data -struct SceNetAdhocGameModeOptData { - u32_le size; - u32_le flag; - u64_le last_recv; -}; - -// Gamemode Buffer Status -struct SceNetAdhocGameModeBufferStat { - struct SceNetAdhocGameModeBufferStat * next; - s32_le id; - void * ptr; - u32_le size; - u32_le master; - SceNetAdhocGameModeOptData opt; -}; - + s32_le type; + uint8_t data[ADHOCCTL_ADHOCID_LEN]; + uint8_t padding[3]; +} SceNetAdhocctlAdhocId; // should this be packed? // Internal Matching Peer Information typedef struct SceNetAdhocMatchingMemberInternal { @@ -251,23 +346,28 @@ typedef struct SceNetAdhocMatchingMemberInternal { s32_le sending; // Last Heartbeat - u64_le lastping; + u64_le lastping; // May need to use the same method with sceKernelGetSystemTimeWide (ie. CoreTiming::GetGlobalTimeUsScaled) to prevent timing issue (ie. in game timeout) } SceNetAdhocMatchingMemberInternal; // Matching handler struct SceNetAdhocMatchingHandlerArgs { s32_le id; - s32_le event; - SceNetEtherAddr * peer; + s32_le opcode; // event; + SceNetEtherAddr mac; // peer //u32_le macaddr; s32_le optlen; - void * opt; + void * opt; //u32_le optaddr }; struct SceNetAdhocMatchingHandler { u32_le entryPoint; }; +struct AdhocctlHandler { + u32 entryPoint; + u32 argument; +}; + // Thread Message Stack Item typedef struct ThreadMessage { // Next Thread Message @@ -288,7 +388,7 @@ typedef struct ThreadMessage { // Context Information typedef struct SceNetAdhocMatchingContext { // Next Context - struct SceNetAdhocMatchingContext * next; + struct SceNetAdhocMatchingContext *next; // Externally Visible ID s32_le id; @@ -306,19 +406,21 @@ typedef struct SceNetAdhocMatchingContext { SceNetEtherAddr mac; // Peer List for Connectees - SceNetAdhocMatchingMemberInternal * peerlist; // SceNetAdhocMatchingMemberInfo[Emu] + SceNetAdhocMatchingMemberInternal *peerlist; // SceNetAdhocMatchingMemberInfo[Emu] // Local PDP Port u16_le port; // Local PDP Socket s32_le socket; + // Socket Lock + recursive_mutex *socketlock; // Receive Buffer Length s32_le rxbuflen; // Receive Buffer - uint8_t * rxbuf; + uint8_t *rxbuf; // Hello Broadcast Interval (Microseconds) u32_le hello_int; @@ -338,35 +440,228 @@ typedef struct SceNetAdhocMatchingContext { // Event Handler SceNetAdhocMatchingHandler handler; - // Socket Connectivity - //bool connected; + // Event Handler Args + u32_le handlerArgs[6]; // actual arguments only 5, the 6th one is just for borrowing a space to store the callback address to use later + //SceNetAdhocMatchingHandlerArgs handlerArgs; // Hello Data Length - u32_le hellolen; + s32_le hellolen; // Hello Data Address u32_le helloAddr; // Hello Data - void * hello; + uint8_t *hello; + + // Timeout + u64_le timeout; + + // Helper Thread (fake PSP Thread) needed to execute callback + //HLEHelperThread *matchingThread; + //SceUID matching_thid; // Event Caller Thread - s32_le event_thid; + std::thread eventThread; // s32_le event_thid; + bool eventRunning = false; + bool IsMatchingInCB = false; // IO Handler Thread - s32_le input_thid; + std::thread inputThread; // s32_le input_thid; + bool inputRunning = false; // Event Caller Thread Message Stack - s32_le event_stack_lock; - ThreadMessage * event_stack; + recursive_mutex *eventlock; // s32_le event_stack_lock; + ThreadMessage *event_stack; // IO Handler Thread Message Stack - s32_le input_stack_lock; - ThreadMessage * input_stack; + recursive_mutex *inputlock; // s32_le input_stack_lock; + ThreadMessage *input_stack; + + // Socket Connectivity + //bool connected = false; + //bool InConnection = false; + //u32_le handlerid = -1; + //int eventMatchingHandlerUpdate = -1; } SceNetAdhocMatchingContext; // End of psp definitions +enum { + ERROR_NET_ADHOC_INVALID_SOCKET_ID = 0x80410701, + ERROR_NET_ADHOC_INVALID_ADDR = 0x80410702, + ERROR_NET_ADHOC_INVALID_PORT = 0x80410703, + ERROR_NET_ADHOC_INVALID_DATALEN = 0x80410705, + ERROR_NET_ADHOC_NOT_ENOUGH_SPACE = 0x80400706, + ERROR_NET_ADHOC_SOCKET_DELETED = 0x80410707, + ERROR_NET_ADHOC_SOCKET_ALERTED = 0x80410708, + ERROR_NET_ADHOC_WOULD_BLOCK = 0x80410709, //ERROR_NET_ADHOC_NO_DATA_AVAILABLE + ERROR_NET_ADHOC_PORT_IN_USE = 0x8041070a, + ERROR_NET_ADHOC_NOT_CONNECTED = 0x8041070B, + ERROR_NET_ADHOC_DISCONNECTED = 0x8041070c, + ERROR_NET_ADHOC_NOT_OPENED = 0x8040070D, + ERROR_NET_ADHOC_NOT_LISTENED = 0x8040070E, + ERROR_NET_ADHOC_SOCKET_ID_NOT_AVAIL = 0x8041070F, + ERROR_NET_ADHOC_PORT_NOT_AVAIL = 0x80410710, + ERROR_NET_ADHOC_INVALID_ARG = 0x80410711, + ERROR_NET_ADHOC_NOT_INITIALIZED = 0x80410712, + ERROR_NET_ADHOC_ALREADY_INITIALIZED = 0x80410713, + ERROR_NET_ADHOC_BUSY = 0x80410714, + ERROR_NET_ADHOC_TIMEOUT = 0x80410715, + ERROR_NET_ADHOC_NO_ENTRY = 0x80410716, + ERROR_NET_ADHOC_EXCEPTION_EVENT = 0x80410717, + ERROR_NET_ADHOC_CONNECTION_REFUSED = 0x80410718, + ERROR_NET_ADHOC_THREAD_ABORTED = 0x80410719, + ERROR_NET_ADHOC_ALREADY_CREATED = 0x8041071A, + ERROR_NET_ADHOC_NOT_IN_GAMEMODE = 0x8041071B, + ERROR_NET_ADHOC_NOT_CREATED = 0x8041071C, + + ERROR_NET_ADHOC_MATCHING_INVALID_MODE = 0x80410801, + ERROR_NET_ADHOC_MATCHING_INVALID_MAXNUM = 0x80410803, + ERROR_NET_ADHOC_MATCHING_RXBUF_TOO_SHORT = 0x80410804, + ERROR_NET_ADHOC_MATCHING_INVALID_OPTLEN = 0x80410805, + ERROR_NET_ADHOC_MATCHING_INVALID_ARG = 0x80410806, + ERROR_NET_ADHOC_MATCHING_INVALID_ID = 0x80410807, + ERROR_NET_ADHOC_MATCHING_ID_NOT_AVAIL = 0x80410808, + ERROR_NET_ADHOC_MATCHING_NO_SPACE = 0x80410809, + ERROR_NET_ADHOC_MATCHING_IS_RUNNING = 0x8041080A, + ERROR_NET_ADHOC_MATCHING_NOT_RUNNING = 0x8041080B, + ERROR_NET_ADHOC_MATCHING_UNKNOWN_TARGET = 0x8041080C, + ERROR_NET_ADHOC_MATCHING_TARGET_NOT_READY = 0x8041080D, + ERROR_NET_ADHOC_MATCHING_EXCEED_MAXNUM = 0x8041080E, + ERROR_NET_ADHOC_MATCHING_REQUEST_IN_PROGRESS = 0x8041080F, + ERROR_NET_ADHOC_MATCHING_ALREADY_ESTABLISHED = 0x80410810, + ERROR_NET_ADHOC_MATCHING_BUSY = 0x80410811, + ERROR_NET_ADHOC_MATCHING_ALREADY_INITIALIZED = 0x80410812, + ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED = 0x80410813, + ERROR_NET_ADHOC_MATCHING_PORT_IN_USE = 0x80410814, + ERROR_NET_ADHOC_MATCHING_STACKSIZE_TOO_SHORT = 0x80410815, + ERROR_NET_ADHOC_MATCHING_INVALID_DATALEN = 0x80410816, + ERROR_NET_ADHOC_MATCHING_NOT_ESTABLISHED = 0x80410817, + ERROR_NET_ADHOC_MATCHING_DATA_BUSY = 0x80410818, + + ERROR_NET_ADHOCCTL_WLAN_SWITCH_OFF = 0x80410b03, + ERROR_NET_ADHOCCTL_INVALID_ARG = 0x80410B04, + ERROR_NET_ADHOCCTL_ID_NOT_FOUND = 0x80410B06, + ERROR_NET_ADHOCCTL_ALREADY_INITIALIZED = 0x80410b07, + ERROR_NET_ADHOCCTL_NOT_INITIALIZED = 0x80410b08, + ERROR_NET_ADHOCCTL_DISCONNECTED = 0x80410b09, + ERROR_NET_ADHOCCTL_NOT_ENTER_GAMEMODE = 0x80410B0C, + ERROR_NET_ADHOCCTL_CHANNEL_NOT_AVAILABLE = 0x80410B0D, + ERROR_NET_ADHOCCTL_BUSY = 0x80410b10, + ERROR_NET_ADHOCCTL_TOO_MANY_HANDLERS = 0x80410b12, + ERROR_NET_ADHOCCTL_STACKSIZE_TOO_SHORT = 0x80410B13, + + ERROR_NET_WLAN_INVALID_ARG = 0x80410D13, + + ERROR_NET_NO_SPACE = 0x80410001 +}; + +const size_t MAX_ADHOCCTL_HANDLERS = 32; //4 +const size_t MAX_MATCHING_HANDLERS = 32; //4 + +enum { + /** + * Matching events used in pspAdhocMatchingCallback + */ + /** Hello event. optdata contains data if optlen > 0. */ + PSP_ADHOC_MATCHING_EVENT_HELLO = 1, + /** Join request. optdata contains data if optlen > 0. */ + PSP_ADHOC_MATCHING_EVENT_JOIN = 2, + /** Target left matching. */ + PSP_ADHOC_MATCHING_EVENT_LEFT = 3, + /** Join request rejected. */ + PSP_ADHOC_MATCHING_EVENT_REJECT = 4, + /** Join request cancelled. */ + PSP_ADHOC_MATCHING_EVENT_CANCEL = 5, + /** Join request accepted. optdata contains data if optlen > 0. */ + PSP_ADHOC_MATCHING_EVENT_ACCEPT = 6, + /** Matching is complete. */ + PSP_ADHOC_MATCHING_EVENT_COMPLETE = 7, + /** Ping timeout event. */ + PSP_ADHOC_MATCHING_EVENT_TIMEOUT = 8, + /** Error event. */ + PSP_ADHOC_MATCHING_EVENT_ERROR = 9, + /** Peer disconnect event. */ + PSP_ADHOC_MATCHING_EVENT_DISCONNECT = 10, + /** Data received event. optdata contains data if optlen > 0. */ + PSP_ADHOC_MATCHING_EVENT_DATA = 11, + /** Data acknowledged event. */ + PSP_ADHOC_MATCHING_EVENT_DATA_CONFIRM = 12, + /** Data timeout event. */ + PSP_ADHOC_MATCHING_EVENT_DATA_TIMEOUT = 13, + + /** Internal ping message. */ + PSP_ADHOC_MATCHING_EVENT_INTERNAL_PING = 100, + + /** + * Matching modes used in sceNetAdhocMatchingCreate + */ + /** Host */ + PSP_ADHOC_MATCHING_MODE_HOST = 1, + /** Client */ + PSP_ADHOC_MATCHING_MODE_CLIENT = 2, + /** Peer to peer */ + PSP_ADHOC_MATCHING_MODE_PTP = 3, +}; + +enum { + PSP_ADHOC_POLL_READY_TO_SEND = 1, // POLLIN ? + PSP_ADHOC_POLL_DATA_AVAILABLE = 2, // POLLPRI ? + PSP_ADHOC_POLL_CAN_CONNECT = 4, // POLLOUT ? + PSP_ADHOC_POLL_CAN_ACCEPT = 8, // POLLERR ? +}; + +// Matching modes +#define PSP_ADHOC_MATCHING_MODE_PARENT 1 +#define PSP_ADHOC_MATCHING_MODE_CHILD 2 +#define PSP_ADHOC_MATCHING_MODE_P2P 3 + +// Matching Events +#define PSP_ADHOC_MATCHING_EVENT_HELLO 1 +#define PSP_ADHOC_MATCHING_EVENT_REQUEST 2 +#define PSP_ADHOC_MATCHING_EVENT_LEAVE 3 +#define PSP_ADHOC_MATCHING_EVENT_DENY 4 +#define PSP_ADHOC_MATCHING_EVENT_CANCEL 5 +#define PSP_ADHOC_MATCHING_EVENT_ACCEPT 6 +#define PSP_ADHOC_MATCHING_EVENT_ESTABLISHED 7 +#define PSP_ADHOC_MATCHING_EVENT_TIMEOUT 8 +#define PSP_ADHOC_MATCHING_EVENT_ERROR 9 +#define PSP_ADHOC_MATCHING_EVENT_BYE 10 +#define PSP_ADHOC_MATCHING_EVENT_DATA 11 +#define PSP_ADHOC_MATCHING_EVENT_DATA_ACK 12 +#define PSP_ADHOC_MATCHING_EVENT_DATA_TIMEOUT 13 + +// Peer Status +// Offer only seen in P2P and PARENT mode after hello +// Parent only seen in CHILD mode after connection accept +// Child only seen in PARENT and CHILD mode after connection accept +// P2P only seen in P2P mode after connection accept +// Requester only seen in P2P and PARENT mode after connection request +#define PSP_ADHOC_MATCHING_PEER_OFFER 1 +#define PSP_ADHOC_MATCHING_PEER_PARENT 2 +#define PSP_ADHOC_MATCHING_PEER_CHILD 3 +#define PSP_ADHOC_MATCHING_PEER_P2P 4 +#define PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST 5 +#define PSP_ADHOC_MATCHING_PEER_OUTGOING_REQUEST 6 +#define PSP_ADHOC_MATCHING_PEER_CANCEL_IN_PROGRESS 7 + +// Stack Targets +#define PSP_ADHOC_MATCHING_INPUT_STACK 1 +#define PSP_ADHOC_MATCHING_EVENT_STACK 2 + +// Packet Opcodes +#define PSP_ADHOC_MATCHING_PACKET_PING 0 +#define PSP_ADHOC_MATCHING_PACKET_HELLO 1 +#define PSP_ADHOC_MATCHING_PACKET_JOIN 2 +#define PSP_ADHOC_MATCHING_PACKET_ACCEPT 3 +#define PSP_ADHOC_MATCHING_PACKET_CANCEL 4 +#define PSP_ADHOC_MATCHING_PACKET_BULK 5 +#define PSP_ADHOC_MATCHING_PACKET_BULK_ABORT 6 +#define PSP_ADHOC_MATCHING_PACKET_BIRTH 7 +#define PSP_ADHOC_MATCHING_PACKET_DEATH 8 +#define PSP_ADHOC_MATCHING_PACKET_BYE 9 + +// Pro Adhoc Server Packets Opcodes #define OPCODE_PING 0 #define OPCODE_LOGIN 1 #define OPCODE_CONNECT 2 @@ -445,17 +740,60 @@ typedef struct { SceNetAdhocctlChatPacketC2S base; SceNetAdhocctlNickname name; } PACK SceNetAdhocctlChatPacketS2C; + +// P2P Packet +typedef struct { + SceNetEtherAddr fromMAC; + SceNetEtherAddr toMAC; + u32_le dataPtr; //void * data +} PACK SceNetAdhocMatchingPacketBase; + +// P2P Accept Packet +typedef struct { + SceNetAdhocctlPacketBase base; //opcode + u32_le dataLen; + u32_le numMACs; //number of peers + u32_le dataPtr; //void * data + /*u32_le*/PSPPointer MACsPtr; //peers //SceNetEtherAddr * MACs +} PACK SceNetAdhocMatchingPacketAccept; + #ifdef _MSC_VER #pragma pack(pop) #endif +class AfterMatchingMipsCall : public Action { +public: + AfterMatchingMipsCall() {} + static Action *Create() { return new AfterMatchingMipsCall(); } + void DoState(PointerWrap &p) { + auto s = p.Section("AfterMatchingMipsCall", 1, 2); + if (!s) + return; + + p.Do(EventID); + //context = NULL; + } + void run(MipsCall &call); + void SetContextID(u32 ContextID, u32 eventId); + void SetContext(SceNetAdhocMatchingContext *Context, u32 eventId) { context = Context; EventID = eventId; } + +private: + u32 EventID; + SceNetAdhocMatchingContext *context; +}; + +extern int actionAfterMatchingMipsCall; +extern bool IsAdhocctlInCB; + // Aux vars extern int metasocket; extern SceNetAdhocctlParameter parameter; +extern SceNetAdhocctlAdhocId product_code; extern std::thread friendFinderThread; extern recursive_mutex peerlock; extern SceNetAdhocPdpStat * pdp[255]; extern SceNetAdhocPtpStat * ptp[255]; +extern std::map adhocctlHandlers; extern uint32_t fakePoolSize; extern SceNetAdhocMatchingContext * contexts; @@ -463,10 +801,14 @@ extern int one; extern bool friendFinderRunning; extern SceNetAdhocctlPeerInfo * friends; extern SceNetAdhocctlScanInfo * networks; -extern int eventHandlerUpdate; +extern int eventAdhocctlHandlerUpdate; +extern int eventMatchingHandlerUpdate; extern int threadStatus; // End of Aux vars +// Check if Matching callback is running +bool IsMatchingInCallback(SceNetAdhocMatchingContext * context); + /** * Local MAC Check * @param saddr To-be-checked MAC Address @@ -491,10 +833,10 @@ int isPTPPortInUse(uint16_t port); /* * Matching Members */ -SceNetAdhocMatchingMemberInternal* findMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); -void addMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); -void deleteMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); -void deleteAllMembers(SceNetAdhocMatchingContext * context); +//SceNetAdhocMatchingMemberInternal* findMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); // findPeer +SceNetAdhocMatchingMemberInternal* addMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); +//void deleteMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); // deletePeer +//void deleteAllMembers(SceNetAdhocMatchingContext * context); // clearPeerList /** @@ -503,6 +845,11 @@ void deleteAllMembers(SceNetAdhocMatchingContext * context); */ void addFriend(SceNetAdhocctlConnectPacketS2C * packet); +/* + * Find a Peer/Friend by MAC address + */ +SceNetAdhocctlPeerInfo * findFriend(SceNetEtherAddr * MAC); + /** * Changes the Blocking Mode of the socket * @param fd File Descriptor of the socket @@ -542,19 +889,6 @@ void deleteAllPTP(void); */ void deleteFriendByIP(uint32_t ip); -/** - * Find Free Matching ID - * @return First unoccupied Matching ID - */ -int findFreeMatchingID(void); - -/** - * Find Internal Matching Context for Matching ID - * @param id Matching ID - * @return Matching Context Pointer or... NULL - */ -SceNetAdhocMatchingContext * findMatchingContext(int id); - /** * Recursive Memory Freeing-Helper for Friend-Structures * @param node Current Node in List @@ -569,6 +903,178 @@ void freeFriendsRecursive(SceNetAdhocctlPeerInfo * node); */ int friendFinder(); +/** +* Find Free Matching ID +* @return First unoccupied Matching ID +*/ +int findFreeMatchingID(void); + +/** +* Find Internal Matching Context for Matching ID +* @param id Matching ID +* @return Matching Context Pointer or... NULL +*/ +SceNetAdhocMatchingContext * findMatchingContext(int id); + +/* +* Notify Matching Event Handler +*/ +void notifyMatchingHandler(SceNetAdhocMatchingContext * context, ThreadMessage * msg, void * opt, u32 &bufAddr, u32 &bufLen, u32_le * args); +// Notifiy Adhocctl Handlers +void notifyAdhocctlHandlers(int flag, int error); + +/* + * Packet Handler + */ +void postAcceptCleanPeerList(SceNetAdhocMatchingContext * context); +void postAcceptAddSiblings(SceNetAdhocMatchingContext * context, int siblingcount, SceNetEtherAddr * siblings); + +/* + * Timeout Handler + */ +void handleTimeout(SceNetAdhocMatchingContext * context); + +/** +* Clear Thread Stack +* @param context Matching Context Pointer +* @param stack ADHOC_MATCHING_EVENT_STACK or ADHOC_MATCHING_INPUT_STACK +*/ +void clearStack(SceNetAdhocMatchingContext * context, int stack); + +/** +* Clear Peer List +* @param context Matching Context Pointer +*/ +void clearPeerList(SceNetAdhocMatchingContext * context); + +/** +* Find Outgoing Request Target Peer +* @param context Matching Context Pointer +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findOutgoingRequest(SceNetAdhocMatchingContext * context); + +/** +* Send Accept Message from P2P -> P2P or Parent -> Children +* @param context Matching Context Pointer +* @param peer Target Peer +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendAcceptMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int optlen, const void * opt); + +/** +* Send Join Request from P2P -> P2P or Children -> Parent +* @param context Matching Context Pointer +* @param peer Target Peer +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendJoinRequest(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int optlen, const void * opt); + +/** +* Send Cancel Message to Peer (has various effects) +* @param context Matching Context Pointer +* @param peer Target Peer +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendCancelMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int optlen, const void * opt); + +/** +* Send Bulk Data to Peer +* @param context Matching Context Pointer +* @param peer Target Peer +* @param datalen Data Length +* @param data Data +*/ +void sendBulkData(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer, int datalen, const void * data); + +/** +* Abort Bulk Data Transfer (if in progress) +* @param context Matching Context Pointer +* @param peer Target Peer +*/ +void abortBulkTransfer(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer); + +/** +* Notify all established Peers about new Kid in the Neighborhood +* @param context Matching Context Pointer +* @param peer New Kid +*/ +void sendBirthMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer); + +/** +* Notify all established Peers about abandoned Child +* @param context Matching Context Pointer +* @param peer Abandoned Child +*/ +void sendDeathMessage(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer); + +/** +* Count Children Peers (for Parent) +* @param context Matching Context Pointer +* @return Number of Children +*/ +s32_le countChildren(SceNetAdhocMatchingContext * context); + +/** +* Delete Peer from List +* @param context Matching Context Pointer +* @param peer Internal Peer Reference +*/ +void deletePeer(SceNetAdhocMatchingContext * context, SceNetAdhocMatchingMemberInternal * peer); + +/** +* Find Peer in Context by MAC +* @param context Matching Context Pointer +* @param mac Peer MAC Address +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findPeer(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac); + +/** +* Find Parent Peer +* @param context Matching Context Pointer +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findParent(SceNetAdhocMatchingContext * context); + +/** +* Find P2P Buddy Peer +* @param context Matching Context Pointer +* @return Internal Peer Reference or... NULL +*/ +SceNetAdhocMatchingMemberInternal * findP2P(SceNetAdhocMatchingContext * context); + +/** +* Return Number of Connected Peers +* @param context Matching Context Pointer +* @return Number of Connected Peers +*/ +uint32_t countConnectedPeers(SceNetAdhocMatchingContext * context); + +/** +* Spawn Local Event for Event Thread +* @param context Matching Context Pointer +* @param event Event ID +* @param mac Event Source MAC +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void spawnLocalEvent(SceNetAdhocMatchingContext * context, int event, SceNetEtherAddr * mac, int optlen, void * opt); + +/* + * Matching Event Thread (Send Ping and Hello Data) Part of AdhocMatching + */ +//int matchingEvent(int matchingId); +//int matchingEventThread(int matchingId); //(uint32_t args, void * argp) + +/* +* Matching Input Thread (process Members) Part of AdhocMatching +*/ +//int matchingInputThread(int matchingId); //(uint32_t args, void * argp) + /** * Return Number of active Peers in the same Network as the Local Player * @return Number of active Peers @@ -582,6 +1088,24 @@ int getActivePeerCount(void); int getLocalIp(sockaddr_in * SocketAddress); uint32_t getLocalIp(int sock); +/* + * Get Socket Buffer Size (opt = SO_RCVBUF/SO_SNDBUF) + */ +int getSockBufferSize(int sock, int opt); + +/* +* Set Socket Buffer Size (opt = SO_RCVBUF/SO_SNDBUF) +*/ +int setSockBufferSize(int sock, int opt, int size); + +/** +* Return the Number of Players with the chosen Nickname in the Local Users current Network +* @param nickname To-be-searched Nickname +* @return Number of matching Players +*/ +int getNicknameCount(const char * nickname); + + /** * Joins two 32 bits number into a 64 bit one * @param num1: first number @@ -610,6 +1134,12 @@ void getLocalMac(SceNetEtherAddr * addr); */ uint16_t getLocalPort(int sock); +/** +* PDP Socket Counter +* @return Number of internal PDP Sockets +*/ +int getPDPSocketCount(void); + /** * PTP Socket Counter * @return Number of internal PTP Sockets @@ -653,3 +1183,9 @@ bool resolveMAC(SceNetEtherAddr * mac, uint32_t * ip); * @return true if valid, false otherwise. */ bool validNetworkName(const SceNetAdhocctlGroupName * groupname); + +// Convert Matching Event Code to String +char* getMatchingEventStr(int code, char* buf); + +// Convert Matching Opcode ID to String +char* getMatchingOpcodeStr(int code, char* buf); diff --git a/Core/HLE/proAdhocServer.cpp b/Core/HLE/proAdhocServer.cpp new file mode 100644 index 0000000000..2e46cb75d9 --- /dev/null +++ b/Core/HLE/proAdhocServer.cpp @@ -0,0 +1,1628 @@ +// Copyright (c) 2014- 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/. + + +// proAdhocServer + +// This is a direct port of Coldbird's code from http://code.google.com/p/aemu/ +// All credit goes to him! + +#include +#include +#include +#include + +#if !defined(__APPLE__) +#include +#endif + +#include +// Net stuff +#ifdef _XBOX +#include +typedef int socklen_t; +#elif defined(_MSC_VER) +#include +#else +#include +#include +#endif + +#include +#include +//#include +#include "Core/Core.h" +#include "Core/HLE/proAdhocServer.h" + + +// User Count +uint32_t _db_user_count = 0; + +// User Database +SceNetAdhocctlUserNode * _db_user = NULL; + +// Game Database +SceNetAdhocctlGameNode * _db_game = NULL; + +// Server Status +//int _status = 0; +bool adhocServerRunning = false; +std::thread adhocServerThread; + +// I'm too lazy to copy the whole list here, we should read these from database.db +std::vector crosslinks = { { "ULES01408", "ULUS10511" }, { "NPJH50263", "ULUS10511" } }; +std::vector productids = { { "ULUS10511", "Ace Combat X2 - Joint Assault" }, { "NPUH10023", "Armored Core 3 Portable" } }; + + +// Function Prototypes +const char * strcpyxml(char * out, const char * in, uint32_t size); + +// Function Prototypes +void interrupt(int sig); +void enable_address_reuse(int fd); +void change_blocking_mode(int fd, int nonblocking); +int create_listen_socket(uint16_t port); +int server_loop(int server); + + +/** + * Login User into Database (Stream) + * @param fd Socket + * @param ip IP Address (Network Order) + */ +void login_user_stream(int fd, uint32_t ip) +{ + // Enough Space available + if(_db_user_count < SERVER_USER_MAXIMUM) + { + // Check IP Duplication + SceNetAdhocctlUserNode * u = _db_user; + while(u != NULL && u->resolver.ip != ip) u = u->next; + + if (u != NULL) { // IP Already existed + uint8_t * ip4 = (uint8_t *)&u->resolver.ip; + INFO_LOG(SCENET, "AdhocServer: Already Existing IP: %u.%u.%u.%u\n", ip4[0], ip4[1], ip4[2], ip4[3]); + } + + // Unique IP Address + else //if(u == NULL) + { + // Allocate User Node Memory + SceNetAdhocctlUserNode * user = (SceNetAdhocctlUserNode *)malloc(sizeof(SceNetAdhocctlUserNode)); + + // Allocated User Node Memory + if(user != NULL) + { + // Clear Memory + memset(user, 0, sizeof(SceNetAdhocctlUserNode)); + + // Save Socket + user->stream = fd; + + // Save IP + user->resolver.ip = ip; + + // Link into User List + user->next = _db_user; + if(_db_user != NULL) _db_user->prev = user; + _db_user = user; + + // Initialize Death Clock + user->last_recv = time(NULL); + + // Notify User + uint8_t * ipa = (uint8_t *)&user->resolver.ip; + INFO_LOG(SCENET, "AdhocServer: New Connection from %u.%u.%u.%u", ipa[0], ipa[1], ipa[2], ipa[3]); + + // Fix User Counter + _db_user_count++; + + // Update Status Log + update_status(); + + // Exit Function + return; + } + } + } + + // Duplicate IP, Allocation Error or not enough space - Close Stream + closesocket(fd); +} + +/** + * Login User into Database (Login Data) + * @param user User Node + * @param data Login Packet + */ +void login_user_data(SceNetAdhocctlUserNode * user, SceNetAdhocctlLoginPacketC2S * data) +{ + // Product Code Check + int valid_product_code = 1; + + // Iterate Characters + int i = 0; for(; i < PRODUCT_CODE_LENGTH && valid_product_code == 1; i++) + { + // Valid Characters + if(!((data->game.data[i] >= 'A' && data->game.data[i] <= 'Z') || (data->game.data[i] >= '0' && data->game.data[i] <= '9'))) valid_product_code = 0; + } + + // Valid Packet Data + if(valid_product_code == 1 && memcmp(&data->mac, "\xFF\xFF\xFF\xFF\xFF\xFF", sizeof(data->mac)) != 0 && memcmp(&data->mac, "\x00\x00\x00\x00\x00\x00", sizeof(data->mac)) != 0 && data->name.data[0] != 0) + { + // Game Product Override + game_product_override(&data->game); + + // Find existing Game + SceNetAdhocctlGameNode * game = _db_game; + while(game != NULL && strncmp(game->game.data, data->game.data, PRODUCT_CODE_LENGTH) != 0) game = game->next; + + // Game not found + if(game == NULL) + { + // Allocate Game Node Memory + game = (SceNetAdhocctlGameNode *)malloc(sizeof(SceNetAdhocctlGameNode)); + + // Allocated Game Node Memory + if(game != NULL) + { + // Clear Memory + memset(game, 0, sizeof(SceNetAdhocctlGameNode)); + + // Save Game Product ID + game->game = data->game; + + // Link into Game List + game->next = _db_game; + if(_db_game != NULL) _db_game->prev = game; + _db_game = game; + } + } + + // Game now available + if(game != NULL) + { + // Save MAC + user->resolver.mac = data->mac; + + // Save Nickname + user->resolver.name = data->name; + + // Increase Player Count in Game Node + game->playercount++; + + // Link Game to Player + user->game = game; + + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, game->game.data, PRODUCT_CODE_LENGTH); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) started playing %s", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr); + + // Update Status Log + update_status(); + + // Leave Function + return; + } + } + + // Invalid Packet Data + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + INFO_LOG(SCENET, "AdhocServer: Invalid Login Packet Contents from %u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]); + } + + // Logout User - Out of Memory or Invalid Arguments + logout_user(user); +} + +/** + * Logout User from Database + * @param user User Node + */ +void logout_user(SceNetAdhocctlUserNode * user) +{ + // Disconnect from Group + if(user->group != NULL) disconnect_user(user); + + // Unlink Leftside (Beginning) + if(user->prev == NULL) _db_user = user->next; + + // Unlink Leftside (Other) + else user->prev->next = user->next; + + // Unlink Rightside + if(user->next != NULL) user->next->prev = user->prev; + + // Close Stream + closesocket(user->stream); + + // Playing User + if(user->game != NULL) + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) stopped playing %s", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr); + + // Fix Game Player Count + user->game->playercount--; + + // Empty Game Node + if(user->game->playercount == 0) + { + // Unlink Leftside (Beginning) + if(user->game->prev == NULL) _db_game = user->game->next; + + // Unlink Leftside (Other) + else user->game->prev->next = user->game->next; + + // Unlink Rightside + if(user->game->next != NULL) user->game->next->prev = user->game->prev; + + // Free Game Node Memory + free(user->game); + } + } + + // Unidentified User + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + INFO_LOG(SCENET, "AdhocServer: Dropped Connection to %u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]); + } + + // Free Memory + free(user); + + // Fix User Counter + _db_user_count--; + + // Update Status Log + update_status(); +} + +/** + * Free Database Memory + */ +void free_database(void) +{ + // There are users playing + if(_db_user_count > 0) + { + // Send Shutdown Notice + spread_message(NULL, SERVER_SHUTDOWN_MESSAGE); + } + + // Iterate Users for Deletion + SceNetAdhocctlUserNode * user = _db_user; + while(user != NULL) + { + // Next User (for safe delete) + SceNetAdhocctlUserNode * next = user->next; + + // Logout User + logout_user(user); + + // Move Pointer + user = next; + } +} + +/** + * Connect User to Game Group + * @param user User Node + * @param group Group Name + */ +void connect_user(SceNetAdhocctlUserNode * user, SceNetAdhocctlGroupName * group) +{ + // Group Name Check + int valid_group_name = 1; + { + // Iterate Characters + int i = 0; for(; i < ADHOCCTL_GROUPNAME_LEN && valid_group_name == 1; i++) + { + // End of Name + if(group->data[i] == 0) break; + + // A - Z + if(group->data[i] >= 'A' && group->data[i] <= 'Z') continue; + + // a - z + if(group->data[i] >= 'a' && group->data[i] <= 'z') continue; + + // 0 - 9 + if(group->data[i] >= '0' && group->data[i] <= '9') continue; + + // Invalid Symbol + valid_group_name = 0; + } + } + + // Valid Group Name + if(valid_group_name == 1) + { + // User is disconnected + if(user->group == NULL) + { + // Find Group in Game Node + SceNetAdhocctlGroupNode * g = user->game->group; + while(g != NULL && strncmp((char *)g->group.data, (char *)group->data, ADHOCCTL_GROUPNAME_LEN) != 0) g = g->next; + + // BSSID Packet + SceNetAdhocctlConnectBSSIDPacketS2C bssid; + + // Set BSSID Opcode + bssid.base.opcode = OPCODE_CONNECT_BSSID; + + // Set Default BSSID + bssid.mac = user->resolver.mac; + + // No Group found + if(g == NULL) + { + // Allocate Group Memory + g = (SceNetAdhocctlGroupNode *)malloc(sizeof(SceNetAdhocctlGroupNode)); + + // Allocated Group Memory + if(g != NULL) + { + // Clear Memory + memset(g, 0, sizeof(SceNetAdhocctlGroupNode)); + + // Link Game Node + g->game = user->game; + + // Link Group Node + g->next = g->game->group; + if(g->game->group != NULL) g->game->group->prev = g; + g->game->group = g; + + // Copy Group Name + g->group = *group; + + // Increase Group Counter for Game + g->game->groupcount++; + } + } + + // Group now available + if(g != NULL) + { + // Iterate remaining Group Players + SceNetAdhocctlUserNode * peer = g->player; + while(peer != NULL) + { + // Connect Packet + SceNetAdhocctlConnectPacketS2C packet; + + // Clear Memory + // memset(&packet, 0, sizeof(packet)); + + // Set Connect Opcode + packet.base.opcode = OPCODE_CONNECT; + + // Set Player Name + packet.name = user->resolver.name; + + // Set Player MAC + packet.mac = user->resolver.mac; + + // Set Player IP + packet.ip = user->resolver.ip; + + // Send Data + send(peer->stream, (const char*)&packet, sizeof(packet), 0); + + // Set Player Name + packet.name = peer->resolver.name; + + // Set Player MAC + packet.mac = peer->resolver.mac; + + // Set Player IP + packet.ip = peer->resolver.ip; + + // Send Data + send(user->stream, (const char*)&packet, sizeof(packet), 0); + + // Set BSSID + if(peer->group_next == NULL) bssid.mac = peer->resolver.mac; + + // Move Pointer + peer = peer->group_next; + } + + // Link User to Group + user->group_next = g->player; + if(g->player != NULL) g->player->group_prev = user; + g->player = user; + + // Link Group to User + user->group = g; + + // Increase Player Count + g->playercount++; + + // Send Network BSSID to User + send(user->stream, (const char*)&bssid, sizeof(bssid), 0); + + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + char safegroupstr[9]; + memset(safegroupstr, 0, sizeof(safegroupstr)); + strncpy(safegroupstr, (char *)user->group->group.data, ADHOCCTL_GROUPNAME_LEN); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) joined %s group %s", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr, safegroupstr); + + // Update Status Log + update_status(); + + // Exit Function + return; + } + } + + // Already connected to another group + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + char safegroupstr[9]; + memset(safegroupstr, 0, sizeof(safegroupstr)); + strncpy(safegroupstr, (char *)group->data, ADHOCCTL_GROUPNAME_LEN); + char safegroupstr2[9]; + memset(safegroupstr2, 0, sizeof(safegroupstr2)); + strncpy(safegroupstr2, (char *)user->group->group.data, ADHOCCTL_GROUPNAME_LEN); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) attempted to join %s group %s without disconnecting from %s first", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr, safegroupstr, safegroupstr2); + } + } + + // Invalid Group Name + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + char safegroupstr[9]; + memset(safegroupstr, 0, sizeof(safegroupstr)); + strncpy(safegroupstr, (char *)group->data, ADHOCCTL_GROUPNAME_LEN); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) attempted to join invalid %s group %s", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr, safegroupstr); + } + + // Invalid State, Out of Memory or Invalid Group Name + logout_user(user); +} + +/** + * Disconnect User from Game Group + * @param user User Node + */ +void disconnect_user(SceNetAdhocctlUserNode * user) +{ + // User is connected + if(user->group != NULL) + { + // Unlink Leftside (Beginning) + if(user->group_prev == NULL) user->group->player = user->group_next; + + // Unlink Leftside (Other) + else user->group_prev->group_next = user->group_next; + + // Unlink Rightside + if(user->group_next != NULL) user->group_next->group_prev = user->group_prev; + + // Fix Player Count + user->group->playercount--; + + // Iterate remaining Group Players + SceNetAdhocctlUserNode * peer = user->group->player; + while(peer != NULL) + { + // Disconnect Packet + SceNetAdhocctlDisconnectPacketS2C packet; + + // Clear Memory + // memset(&packet, 0, sizeof(packet)); + + // Set Disconnect Opcode + packet.base.opcode = OPCODE_DISCONNECT; + + // Set User IP + packet.ip = user->resolver.ip; + + // Send Data + send(peer->stream, (const char*)&packet, sizeof(packet), 0); + + // Move Pointer + peer = peer->group_next; + } + + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + char safegroupstr[9]; + memset(safegroupstr, 0, sizeof(safegroupstr)); + strncpy(safegroupstr, (char *)user->group->group.data, ADHOCCTL_GROUPNAME_LEN); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) left %s group %s", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr, safegroupstr); + + // Empty Group + if(user->group->playercount == 0) + { + // Unlink Leftside (Beginning) + if(user->group->prev == NULL) user->group->game->group = user->group->next; + + // Unlink Leftside (Other) + else user->group->prev->next = user->group->next; + + // Unlink Rightside + if(user->group->next != NULL) user->group->next->prev = user->group->prev; + + // Free Group Memory + free(user->group); + + // Decrease Group Counter in Game Node + user->game->groupcount--; + } + + // Unlink from Group + user->group = NULL; + user->group_next = NULL; + user->group_prev = NULL; + + // Update Status Log + update_status(); + + // Exit Function + return; + } + + // Not in a game group + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) attempted to leave %s group without joining one first", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr); + } + + // Delete User + logout_user(user); +} + +/** + * Send Game Group List + * @param user User Node + */ +void send_scan_results(SceNetAdhocctlUserNode * user) +{ + // User is disconnected + if(user->group == NULL) + { + // Iterate Groups + SceNetAdhocctlGroupNode * group = user->game->group; + for(; group != NULL; group = group->next) + { + // Scan Result Packet + SceNetAdhocctlScanPacketS2C packet; + + // Clear Memory + // memset(&packet, 0, sizeof(packet)); + + // Set Opcode + packet.base.opcode = OPCODE_SCAN; + + // Set Group Name + packet.group = group->group; + + // Iterate Players in Network Group + SceNetAdhocctlUserNode * peer = group->player; + for(; peer != NULL; peer = peer->group_next) + { + // Found Network Founder + if(peer->group_next == NULL) + { + // Set Group Host MAC + packet.mac = peer->resolver.mac; + } + } + + // Send Group Packet + send(user->stream, (const char*)&packet, sizeof(packet), 0); + } + + // Notify Player of End of Scan + uint8_t opcode = OPCODE_SCAN_COMPLETE; + send(user->stream, (const char*)&opcode, 1, 0); + + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) requested information on %d %s groups", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], user->game->groupcount, safegamestr); + + // Exit Function + return; + } + + // User in a game group + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + char safegroupstr[9]; + memset(safegroupstr, 0, sizeof(safegroupstr)); + strncpy(safegroupstr, (char *)user->group->group.data, ADHOCCTL_GROUPNAME_LEN); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) attempted to scan for %s groups without disconnecting from %s first", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr, safegroupstr); + } + + // Delete User + logout_user(user); +} + +/** + * Spread Chat Message in P2P Network + * @param user Sender User Node + * @param message Chat Message + */ +void spread_message(SceNetAdhocctlUserNode * user, char * message) +{ + // Global Notice + if(user == NULL) + { + // Iterate Players + for(user = _db_user; user != NULL; user = user->next) + { + // Player has access to chat + if(user->group != NULL) + { + // Chat Packet + SceNetAdhocctlChatPacketS2C packet; + + // Clear Memory + memset(&packet, 0, sizeof(packet)); + + // Set Chat Opcode + packet.base.base.opcode = OPCODE_CHAT; + + // Set Chat Message + strcpy(packet.base.message, message); + + // Send Data + send(user->stream, (const char*)&packet, sizeof(packet), 0); + } + } + + // Prevent NULL Error + return; + } + + // User is connected + else if(user->group != NULL) + { + // Broadcast Range Counter + uint32_t counter = 0; + + // Iterate Group Players + SceNetAdhocctlUserNode * peer = user->group->player; + while(peer != NULL) + { + // Skip Self + if(peer == user) + { + // Move Pointer + peer = peer->group_next; + + // Continue Loop + continue; + } + + // Chat Packet + SceNetAdhocctlChatPacketS2C packet; + + // Set Chat Opcode + packet.base.base.opcode = OPCODE_CHAT; + + // Set Chat Message + strcpy(packet.base.message, message); + + // Set Sender Nickname + packet.name = user->resolver.name; + + // Send Data + send(peer->stream, (const char*)&packet, sizeof(packet), 0); + + // Move Pointer + peer = peer->group_next; + + // Increase Broadcast Range Counter + counter++; + } + + // Message Sent + if(counter > 0) + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + char safegroupstr[9]; + memset(safegroupstr, 0, sizeof(safegroupstr)); + strncpy(safegroupstr, (char *)user->group->group.data, ADHOCCTL_GROUPNAME_LEN); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) sent \"%s\" to %d players in %s group %s", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], message, counter, safegamestr, safegroupstr); + } + + // Exit Function + return; + } + + // User not in a game group + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + char safegamestr[10]; + memset(safegamestr, 0, sizeof(safegamestr)); + strncpy(safegamestr, user->game->game.data, PRODUCT_CODE_LENGTH); + INFO_LOG(SCENET, "AdhocServer: %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u) attempted to send a text message without joining a %s group first", (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3], safegamestr); + } + + // Delete User + logout_user(user); +} + +/** + * Get User State + * @param user User Node + */ +int get_user_state(SceNetAdhocctlUserNode * user) +{ + // Timeout Status + if((time(NULL) - user->last_recv) >= SERVER_USER_TIMEOUT) return USER_STATE_TIMED_OUT; + + // Waiting Status + if(user->game == NULL) return USER_STATE_WAITING; + + // Logged-In Status + return USER_STATE_LOGGED_IN; +} + +/** + * Clear RX Buffer + * @param user User Node + * @param clear Number of Bytes to clear (-1 for all) + */ +void clear_user_rxbuf(SceNetAdhocctlUserNode * user, int clear) +{ + // Fix Clear Length + if(clear == -1 || clear > (int)user->rxpos) clear = user->rxpos; + + // Move Buffer + memmove(user->rx, user->rx + clear, sizeof(user->rx) - clear); + + // Fix RX Buffer Pointer + user->rxpos -= clear; +} + +/** + * Patch Game Product Code + * @param product To-be-patched Product Code + * @param from If the Product Code matches this... + * @param to ... then change it to this one. + */ +void game_product_relink(SceNetAdhocctlProductCode * product, char * from, char * to) +{ + // Relink Region Code + if(strncmp(product->data, from, PRODUCT_CODE_LENGTH) == 0) strncpy(product->data, to, PRODUCT_CODE_LENGTH); +} + +/** + * Game Product Override (used for mixing multi-region games) + * @param product IN: Source Product OUT: Override Product + */ +void game_product_override(SceNetAdhocctlProductCode * product) +{ + // Safe Product Code + char productid[PRODUCT_CODE_LENGTH + 1]; + + // Prepare Safe Product Code + strncpy(productid, product->data, PRODUCT_CODE_LENGTH); + productid[PRODUCT_CODE_LENGTH] = 0; + + // Database Handle + //sqlite3 * db = NULL; + + // Open Database + //if(sqlite3_open(SERVER_DATABASE, &db) == SQLITE_OK) + { + // Crosslinked Flag + int crosslinked = 0; + + // Exists Flag + int exists = 0; + + // SQL Statements + /*const char * sql = "SELECT id_to FROM crosslinks WHERE id_from=?;"; + const char * sql2 = "SELECT * FROM productids WHERE id=?;"; + const char * sql3 = "INSERT INTO productids(id, name) VALUES(?, ?);"; + + // Prepared SQL Statement + sqlite3_stmt * statement = NULL; + + // Prepare SQL Statement + if(sqlite3_prepare_v2(db, sql, strlen(sql) + 1, &statement, NULL) == SQLITE_OK) + { + // Bind SQL Statement Data + if(sqlite3_bind_text(statement, 1, productid, strlen(productid), SQLITE_STATIC) == SQLITE_OK) + { + // Found Matching Row + if(sqlite3_step(statement) == SQLITE_ROW) + { + // Grab Crosslink ID + const char * crosslink = (const char *)sqlite3_column_text(statement, 0); + + // Crosslink Product Code + strncpy(product->data, crosslink, PRODUCT_CODE_LENGTH); + + // Log Crosslink + INFO_LOG(SCENET, "Crosslinked %s to %s", productid, crosslink); + + // Set Crosslinked Flag + crosslinked = 1; + } + } + + // Destroy Prepared SQL Statement + sqlite3_finalize(statement); + }*/ + for (std::vector::iterator it = crosslinks.begin(); it != crosslinks.end(); it++) { + if (IsMatch(it->id_from, productid)) { + // Grab Crosslink ID + char crosslink[PRODUCT_CODE_LENGTH + 1]; + strncpy(crosslink, it->id_to, PRODUCT_CODE_LENGTH); + crosslink[PRODUCT_CODE_LENGTH] = 0; // null terminated + + // Crosslink Product Code + strncpy(product->data, it->id_to, PRODUCT_CODE_LENGTH); + + // Log Crosslink + INFO_LOG(SCENET, "AdhocServer: Crosslinked %s to %s", productid, crosslink); + + // Set Crosslinked Flag + crosslinked = 1; + break; + } + } + + // Not Crosslinked + if(!crosslinked) + { + // Prepare SQL Statement + /*if(sqlite3_prepare_v2(db, sql2, strlen(sql2) + 1, &statement, NULL) == SQLITE_OK) + { + // Bind SQL Statement Data + if(sqlite3_bind_text(statement, 1, productid, strlen(productid), SQLITE_STATIC) == SQLITE_OK) + { + // Found Matching Row + if(sqlite3_step(statement) == SQLITE_ROW) + { + // Set Exists Flag + exists = 1; + } + } + + // Destroy Prepare SQL Statement + sqlite3_finalize(statement); + }*/ + for (std::vector::iterator it = productids.begin(); it != productids.end(); it++) { + if (IsMatch(it->id, productid)) { + // Set Exists Flag + exists = 1; + break; + } + } + + // Game doesn't exist in Database + if(!exists) + { + // Prepare SQL Statement + /*if(sqlite3_prepare_v2(db, sql3, strlen(sql3) + 1, &statement, NULL) == SQLITE_OK) + { + // Bind SQL Statement Data + if(sqlite3_bind_text(statement, 1, productid, strlen(productid), SQLITE_STATIC) == SQLITE_OK && sqlite3_bind_text(statement, 2, productid, strlen(productid), SQLITE_STATIC) == SQLITE_OK) + { + // Save Product ID to Database + if(sqlite3_step(statement) == SQLITE_DONE) + { + // Log Addition + INFO_LOG(SCENET, "Added Unknown Product ID %s to Database", productid); + } + } + + // Destroy Prepare SQL Statement + sqlite3_finalize(statement); + }*/ + db_productid unkproduct; + strncpy(unkproduct.id, productid, sizeof(unkproduct.id)); + strncpy(unkproduct.name, productid, sizeof(productid)); + productids.push_back(unkproduct); //productids[productids.size()] = unkproduct; + // Log Addition + INFO_LOG(SCENET, "AdhocServer: Added Unknown Product ID %s to Database", productid); + } + } + + // Close Database + //sqlite3_close(db); + } +} + +/** + * Update Status Logfile + */ +void update_status(void) +{ + // Open Logfile + FILE * log = fopen(SERVER_STATUS_XMLOUT, "w"); + + // Opened Logfile + if(log != NULL) + { + // Write XML Header + fprintf(log, "\n"); + + // Write XSL Processor Information + fprintf(log, "\n"); + + // Output Root Tag + User Count + fprintf(log, "\n", _db_user_count); + + // Database Handle + //sqlite3 * db = NULL; + + // Open Database + //if(sqlite3_open(SERVER_DATABASE, &db) == SQLITE_OK) + { + // Iterate Games + SceNetAdhocctlGameNode * game = _db_game; for(; game != NULL; game = game->next) + { + // Safe Product ID + char productid[PRODUCT_CODE_LENGTH + 1]; + strncpy(productid, game->game.data, PRODUCT_CODE_LENGTH); + productid[PRODUCT_CODE_LENGTH] = 0; + + // Display Name + char displayname[128]; + memset(displayname, 0, sizeof(displayname)); + + // SQL Statement + //const char * sql = "SELECT name FROM productids WHERE id=?;"; + + // Prepared SQL Statement + //sqlite3_stmt * statement = NULL; + + // Prepare SQL Statement + /*if(sqlite3_prepare_v2(db, sql, strlen(sql) + 1, &statement, NULL) == SQLITE_OK) + { + // Bind SQL Statement Data + if(sqlite3_bind_text(statement, 1, productid, strlen(productid), SQLITE_STATIC) == SQLITE_OK) + { + // Found Matching Row + if(sqlite3_step(statement) == SQLITE_ROW) + { + // Fetch Game Name from Database + const char * gamename = (const char *)sqlite3_column_text(statement, 0); + + // Copy Game Name + strcpyxml(displayname, gamename, sizeof(displayname)); + } + + // Game not in Database + else + { + // Use Product Code as Name + strcpyxml(displayname, productid, sizeof(displayname)); + } + } + + // Destroy Prepared SQL Statement + sqlite3_finalize(statement); + }*/ + //db_productid *foundid = NULL; + bool found = false; + for (std::vector::iterator it = productids.begin(); it != productids.end(); it++) { + if (IsMatch(it->id, productid)) { + // Copy Game Name + strcpyxml(displayname, it->name, sizeof(displayname)); + found = true; + break; + } + } + + if (!found) { + // Use Product Code as Name + strcpyxml(displayname, productid, sizeof(displayname)); + } + + // Output Game Tag + Game Name + fprintf(log, "\t\n", displayname, game->playercount); + + // Activate User Count + uint32_t activecount = 0; + + // Iterate Game Groups + SceNetAdhocctlGroupNode * group = game->group; for(; group != NULL; group = group->next) + { + // Safe Group Name + char groupname[ADHOCCTL_GROUPNAME_LEN + 1]; + strncpy(groupname, (const char *)group->group.data, ADHOCCTL_GROUPNAME_LEN); + groupname[ADHOCCTL_GROUPNAME_LEN] = 0; + + // Output Group Tag + Group Name + User Count + fprintf(log, "\t\t\n", strcpyxml(displayname, groupname, sizeof(displayname)), group->playercount); + + // Iterate Users + SceNetAdhocctlUserNode * user = group->player; for(; user != NULL; user = user->group_next) + { + // Output User Tag + Username + fprintf(log, "\t\t\t%s\n", strcpyxml(displayname, (const char *)user->resolver.name.data, sizeof(displayname))); + } + + // Output Closing Group Tag + fprintf(log, "\t\t\n"); + + // Increase Active Game User Count + activecount += group->playercount; + } + + // Output Idle Game Group + if(game->playercount > activecount) + { + // Output Group Tag + Group Name + Idle User Count + fprintf(log, "\t\t\n", game->playercount - activecount); + } + + // Output Closing Game Tag + fprintf(log, "\t\n"); + } + + // Close Database + //sqlite3_close(db); + } + + // Output Closing Root Tag + fprintf(log, ""); + + // Close Logfile + fclose(log); + } +} + +/** + * Escape XML Sequences to avoid malformed XML files. + * @param out Out Buffer + * @param in In Buffer + * @param size Size of Out Buffer + * @return Reference to Out Buffer + */ +const char * strcpyxml(char * out, const char * in, uint32_t size) +{ + // Valid Arguments + if(out != NULL && in != NULL && size > 0) + { + // Clear Memory + memset(out, 0, size); + + // Written Size Pointer + uint32_t written = 0; + + // Iterate In-Buffer Symbols + uint32_t i = 0; for(; i < strlen(in); i++) + { + // " Symbol + if(in[i] == '"') + { + // Enough Space in Out-Buffer (6B for ") + if((size - written) > 6) + { + // Write Escaped Sequence + strcpy(out + written, """); + + // Move Pointer + written += 6; + } + + // Truncate required + else break; + } + + // < Symbol + else if(in[i] == '<') + { + // Enough Space in Out-Buffer (4B for <) + if((size - written) > 4) + { + // Write Escaped Sequence + strcpy(out + written, "<"); + + // Move Pointer + written += 4; + } + + // Truncate required + else break; + } + + // > Symbol + else if(in[i] == '>') + { + // Enough Space in Out-Buffer (4B for >) + if((size - written) > 4) + { + // Write Escaped Sequence + strcpy(out + written, ">"); + + // Move Pointer + written += 4; + } + + // Truncate required + else break; + } + + // & Symbol + else if(in[i] == '&') + { + // Enough Space in Out-Buffer (5B for &) + if((size - written) > 5) + { + // Write Escaped Sequence + strcpy(out + written, "&"); + + // Move Pointer + written += 5; + } + + // Truncate required + else break; + } + + // Normal Character + else + { + // Enough Space in Out-Buffer (1B) + if((size - written) > 1) + { + // Write Character + out[written++] = in[i]; + } + } + } + + // Return Reference + return out; + } + + // Invalid Arguments + return NULL; +} + +/** + * Server Entry Point + * @param argc Number of Arguments + * @param argv Arguments + * @return OS Error Code + */ +int proAdhocServerThread(int port) // (int argc, char * argv[]) +{ + // Result + int result = 0; + + INFO_LOG(SCENET, "AdhocServer: Begin of AdhocServer Thread"); + + // Create Signal Receiver for CTRL + C + //signal(SIGINT, interrupt); + + // Create Signal Receiver for kill / killall + //signal(SIGTERM, interrupt); + + // Create Listening Socket + int server = create_listen_socket(port); //SERVER_PORT + + // Created Listening Socket + if(server != -1) + { + // Notify User + INFO_LOG(SCENET, "AdhocServer: Listening for Connections on TCP Port %u", port); //SERVER_PORT + + // Enter Server Loop + result = server_loop(server); + + // Notify User + INFO_LOG(SCENET, "AdhocServer: Shutdown complete"); + } + + //_status = 0; + adhocServerRunning = false; + + INFO_LOG(SCENET, "AdhocServer: End of AdhocServer Thread"); + + // Return Result + return result; +} + +/** + * Server Shutdown Request Handler + * @param sig Captured Signal + */ +void interrupt(int sig) +{ + // Notify User + INFO_LOG(SCENET, "AdhocServer: Shutting down... please wait"); + + // Trigger Shutdown + //_status = 0; + adhocServerRunning = false; +} + +/** + * Enable Address Reuse on Socket + * @param fd Socket + */ +void enable_address_reuse(int fd) +{ + // Enable Value + int on = 1; + + // Enable Port Reuse + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)); +} + +/** + * Change Socket Blocking Mode + * @param fd Socket + * @param nonblocking 1 for Nonblocking, 0 for Blocking + */ +void change_blocking_mode(int fd, int nonblocking) +{ + unsigned long on = 1; + unsigned long off = 0; +#ifdef _MSC_VER + if (nonblocking){ + // Change to Non-Blocking Mode + ioctlsocket(fd, FIONBIO, &on); + } + else { + // Change to Blocking Mode + ioctlsocket(fd, FIONBIO, &off); + } +#else + // Change to Non-Blocking Mode + if(nonblocking) fcntl(fd, F_SETFL, O_NONBLOCK); + + // Change to Blocking Mode + else + { + // Get Flags + int flags = fcntl(fd, F_GETFL); + + // Remove Non-Blocking Flag + fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); + } +#endif +} + +/** + * Create Port-Bound Listening Socket + * @param port TCP Port + * @return Socket Descriptor + */ +int create_listen_socket(uint16_t port) +{ + // Create Socket + int fd = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + + // Created Socket + if(fd != -1) + { + // Enable Address Reuse + enable_address_reuse(fd); // Shouldn't Reuse the port for built-in AdhocServer to prevent conflict with Dedicated AdhocServer + + // Make Socket Nonblocking + change_blocking_mode(fd, 1); + + // Prepare Local Address Information + struct sockaddr_in local; + memset(&local, 0, sizeof(local)); + local.sin_family = AF_INET; + local.sin_addr.s_addr = INADDR_ANY; + local.sin_port = htons(port); + + // Bind Local Address to Socket + int bindresult = bind(fd, (struct sockaddr *)&local, sizeof(local)); + + // Bound Local Address to Socket + if(bindresult != -1) + { + // Switch Socket into Listening Mode + listen(fd, SERVER_LISTEN_BACKLOG); + + // Return Socket + return fd; + } + + // Notify User + else INFO_LOG(SCENET, "AdhocServer: Bind returned %i (Socket error %d)", bindresult, errno); + + // Close Socket + closesocket(fd); + } + + // Notify User + else INFO_LOG(SCENET, "AdhocServer: Socket returned %i (Socket error %d)", fd, errno); + + // Return Error + return -1; +} + +/** + * Server Main Loop + * @param server Server Listening Socket + * @return OS Error Code + */ +int server_loop(int server) +{ + // Set Running Status + //_status = 1; + adhocServerRunning = true; + + // Create Empty Status Logfile + update_status(); + + // Handling Loop + while (adhocServerRunning) //(_status == 1) + { + // Login Block + { + // Login Result + int loginresult = 0; + + // Login Processing Loop + do + { + // Prepare Address Structure + struct sockaddr_in addr; + socklen_t addrlen = sizeof(addr); + memset(&addr, 0, sizeof(addr)); + + // Accept Login Requests + // loginresult = accept4(server, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK); + + // Alternative Accept Approach (some Linux Kernel don't support the accept4 Syscall... wtf?) + loginresult = accept(server, (struct sockaddr *)&addr, &addrlen); + if(loginresult != -1) + { + // Switch Socket into Non-Blocking Mode + change_blocking_mode(loginresult, 1); + } + + // Login User (Stream) + if (loginresult != -1) { + u32_le sip = addr.sin_addr.s_addr; + if (sip == 0x0100007f) { //127.0.0.1 should be replaced with LAN/WAN IP whenever available + char str[100]; + gethostname(str, 100); + u8 *pip = (u8*)&sip; + if (gethostbyname(str)->h_addrtype == AF_INET && gethostbyname(str)->h_addr_list[0] != NULL) pip = (u8*)gethostbyname(str)->h_addr_list[0]; + sip = *(u32_le*)pip; + WARN_LOG(SCENET, "AdhocServer: Replacing IP %s with %u.%u.%u.%u", inet_ntoa(addr.sin_addr), pip[0], pip[1], pip[2], pip[3]); + } + login_user_stream(loginresult, sip); + } + } while(loginresult != -1); + } + + // Receive Data from Users + SceNetAdhocctlUserNode * user = _db_user; + while(user != NULL) + { + // Next User (for safe delete) + SceNetAdhocctlUserNode * next = user->next; + + // Receive Data from User + int recvresult = recv(user->stream, (char*)user->rx + user->rxpos, sizeof(user->rx) - user->rxpos, 0); + + // Connection Closed or Timed Out + if(recvresult == 0 || (recvresult == -1 && errno != EAGAIN && errno != EWOULDBLOCK) || get_user_state(user) == USER_STATE_TIMED_OUT) + { + // Logout User + logout_user(user); + } + + // Received Data (or leftovers in RX-Buffer) + else if(recvresult > 0 || user->rxpos > 0) + { + // New Incoming Data + if(recvresult > 0) + { + // Move RX Pointer + user->rxpos += recvresult; + + // Update Death Clock + user->last_recv = time(NULL); + } + + // Waiting for Login Packet + if(get_user_state(user) == USER_STATE_WAITING) + { + // Valid Opcode + if(user->rx[0] == OPCODE_LOGIN) + { + // Enough Data available + if(user->rxpos >= sizeof(SceNetAdhocctlLoginPacketC2S)) + { + // Clone Packet + SceNetAdhocctlLoginPacketC2S packet = *(SceNetAdhocctlLoginPacketC2S *)user->rx; + + // Remove Packet from RX Buffer + clear_user_rxbuf(user, sizeof(SceNetAdhocctlLoginPacketC2S)); + + // Login User (Data) + login_user_data(user, &packet); + } + } + + // Invalid Opcode + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + INFO_LOG(SCENET, "AdhocServer: Invalid Opcode 0x%02X in Waiting State from %u.%u.%u.%u", user->rx[0], ip[0], ip[1], ip[2], ip[3]); + + // Logout User + logout_user(user); + } + } + + // Logged-In User + else if(get_user_state(user) == USER_STATE_LOGGED_IN) + { + // Ping Packet + if(user->rx[0] == OPCODE_PING) + { + // Delete Packet from RX Buffer + clear_user_rxbuf(user, 1); + } + + // Group Connect Packet + else if(user->rx[0] == OPCODE_CONNECT) + { + // Enough Data available + if(user->rxpos >= sizeof(SceNetAdhocctlConnectPacketC2S)) + { + // Cast Packet + SceNetAdhocctlConnectPacketC2S * packet = (SceNetAdhocctlConnectPacketC2S *)user->rx; + + // Clone Group Name + SceNetAdhocctlGroupName group = packet->group; + + // Remove Packet from RX Buffer + clear_user_rxbuf(user, sizeof(SceNetAdhocctlConnectPacketC2S)); + + // Change Game Group + connect_user(user, &group); + } + } + + // Group Disconnect Packet + else if(user->rx[0] == OPCODE_DISCONNECT) + { + // Remove Packet from RX Buffer + clear_user_rxbuf(user, 1); + + // Leave Game Group + disconnect_user(user); + } + + // Network Scan Packet + else if(user->rx[0] == OPCODE_SCAN) + { + // Remove Packet from RX Buffer + clear_user_rxbuf(user, 1); + + // Send Network List + send_scan_results(user); + } + + // Chat Text Packet + else if(user->rx[0] == OPCODE_CHAT) + { + // Enough Data available + if(user->rxpos >= sizeof(SceNetAdhocctlChatPacketC2S)) + { + // Cast Packet + SceNetAdhocctlChatPacketC2S * packet = (SceNetAdhocctlChatPacketC2S *)user->rx; + + // Clone Buffer for Message + char message[64]; + memset(message, 0, sizeof(message)); + strncpy(message, packet->message, sizeof(message) - 1); + + // Remove Packet from RX Buffer + clear_user_rxbuf(user, sizeof(SceNetAdhocctlChatPacketC2S)); + + // Spread Chat Message + spread_message(user, message); + } + } + + // Invalid Opcode + else + { + // Notify User + uint8_t * ip = (uint8_t *)&user->resolver.ip; + INFO_LOG(SCENET, "AdhocServer: Invalid Opcode 0x%02X in Logged-In State from %s (MAC: %02X:%02X:%02X:%02X:%02X:%02X - IP: %u.%u.%u.%u)", user->rx[0], (char *)user->resolver.name.data, user->resolver.mac.data[0], user->resolver.mac.data[1], user->resolver.mac.data[2], user->resolver.mac.data[3], user->resolver.mac.data[4], user->resolver.mac.data[5], ip[0], ip[1], ip[2], ip[3]); + + // Logout User + logout_user(user); + } + } + } + + // Move Pointer + user = next; + } + + // Prevent needless CPU Overload (1ms Sleep) + sleep_ms(1); + + // Don't do anything if it's paused, otherwise the log will be flooded + while (adhocServerRunning && Core_IsStepping()) sleep_ms(1); + } + + // Free User Database Memory + free_database(); + + // Close Server Socket + closesocket(server); + + // Return Success + return 0; +} diff --git a/Core/HLE/proAdhocServer.h b/Core/HLE/proAdhocServer.h new file mode 100644 index 0000000000..972865cf6a --- /dev/null +++ b/Core/HLE/proAdhocServer.h @@ -0,0 +1,385 @@ +// Copyright (c) 2014- 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/. + + +// proAdhocServer + +// This is a direct port of Coldbird's code from http://code.google.com/p/aemu/ +// All credit goes to him! + +#ifndef _PROADHOCSERVER_H_ +#define _PROADHOCSERVER_H_ + +#include +#include +#include "proAdhoc.h" + +/*#ifdef _MSC_VER +#define PACK +#undef errno +#define errno WSAGetLastError() +#else +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define closesocket close +#define PACK __attribute__((packed)) +#endif*/ + +// Server Listening Port +//#define SERVER_PORT 27312 + +// Listener Connection Backlog (aka. Max Concurrent Logins) +#define SERVER_LISTEN_BACKLOG 128 + +// Server User Maximum +#define SERVER_USER_MAXIMUM 1024 + +// Server User Timeout (in seconds) +#define SERVER_USER_TIMEOUT 15 + +// Server SQLite3 Database +#define SERVER_DATABASE "database.db" + +// Server Status Logfile +#define SERVER_STATUS_XMLOUT "www/status.xml" + +// Server Shutdown Message +#define SERVER_SHUTDOWN_MESSAGE "PROMETHEUS HUB IS SHUTTING DOWN!" + +typedef struct db_crosslink{ + char id_from[PRODUCT_CODE_LENGTH + 1]; //SceNetAdhocctlProductCode id_from; + char id_to[PRODUCT_CODE_LENGTH + 1]; //SceNetAdhocctlProductCode id_to; +} db_crosslink; + +typedef struct db_productid { + char id[PRODUCT_CODE_LENGTH + 1]; //SceNetAdhocctlProductCode id; + char name[ADHOCCTL_NICKNAME_LEN]; //Title name +} db_productid; + +/* PSPSTRUCTS */ + +// Ethernet Address (MAC) +/*#define ETHER_ADDR_LEN 6 +typedef struct SceNetEtherAddr { + uint8_t data[ETHER_ADDR_LEN]; +} SceNetEtherAddr; + +// Adhoc Virtual Network Name (1234ABCD) +#define ADHOCCTL_GROUPNAME_LEN 8 +typedef struct SceNetAdhocctlGroupName { + uint8_t data[ADHOCCTL_GROUPNAME_LEN]; +} SceNetAdhocctlGroupName; + +// Player Nickname +#define ADHOCCTL_NICKNAME_LEN 128 +typedef struct SceNetAdhocctlNickname { + uint8_t data[ADHOCCTL_NICKNAME_LEN]; +} SceNetAdhocctlNickname;*/ + +/* PACKETS */ + +/*#define OPCODE_PING 0 +#define OPCODE_LOGIN 1 +#define OPCODE_CONNECT 2 +#define OPCODE_DISCONNECT 3 +#define OPCODE_SCAN 4 +#define OPCODE_SCAN_COMPLETE 5 +#define OPCODE_CONNECT_BSSID 6 +#define OPCODE_CHAT 7 + +// PSP Product Code +#define PRODUCT_CODE_LENGTH 9 +typedef struct +{ + // Game Product Code (ex. ULUS12345) + char data[PRODUCT_CODE_LENGTH]; +} PACK SceNetAdhocctlProductCode; // __attribute__((packed)) + +// Basic Packet +typedef struct +{ + uint8_t opcode; +} PACK SceNetAdhocctlPacketBase; + +// C2S Login Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + SceNetEtherAddr mac; + SceNetAdhocctlNickname name; + SceNetAdhocctlProductCode game; +} PACK SceNetAdhocctlLoginPacketC2S; + +// C2S Connect Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + SceNetAdhocctlGroupName group; +} PACK SceNetAdhocctlConnectPacketC2S; + +// C2S Chat Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + char message[64]; +} PACK SceNetAdhocctlChatPacketC2S; + +// S2C Connect Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + SceNetAdhocctlNickname name; + SceNetEtherAddr mac; + uint32_t ip; +} PACK SceNetAdhocctlConnectPacketS2C; + +// S2C Disconnect Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + uint32_t ip; +} PACK SceNetAdhocctlDisconnectPacketS2C; + +// S2C Scan Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + SceNetAdhocctlGroupName group; + SceNetEtherAddr mac; +} PACK SceNetAdhocctlScanPacketS2C; + +// S2C Connect BSSID Packet +typedef struct +{ + SceNetAdhocctlPacketBase base; + SceNetEtherAddr mac; +} PACK SceNetAdhocctlConnectBSSIDPacketS2C; + +// S2C Chat Packet +typedef struct +{ + SceNetAdhocctlChatPacketC2S base; + SceNetAdhocctlNickname name; +} PACK SceNetAdhocctlChatPacketS2C;*/ + +/* USER */ + +// User States +#define USER_STATE_WAITING 0 +#define USER_STATE_LOGGED_IN 1 +#define USER_STATE_TIMED_OUT 2 + +// PSP Resolver Information +typedef struct +{ + // PSP MAC Address + SceNetEtherAddr mac; + + // PSP Hotspot IP Address + uint32_t ip; + + // PSP Player Name + SceNetAdhocctlNickname name; +} SceNetAdhocctlResolverInfo; + +// Type Prototypes +typedef struct SceNetAdhocctlGameNode SceNetAdhocctlGameNode; +typedef struct SceNetAdhocctlGroupNode SceNetAdhocctlGroupNode; + +// Double-Linked User List +typedef struct SceNetAdhocctlUserNode { + // Next Element + struct SceNetAdhocctlUserNode * next; + + // Previous Element + struct SceNetAdhocctlUserNode * prev; + + // Next Element (Group) + struct SceNetAdhocctlUserNode * group_next; + + // Previous Element + struct SceNetAdhocctlUserNode * group_prev; + + // Resolver Information + SceNetAdhocctlResolverInfo resolver; + + // Game Link + SceNetAdhocctlGameNode * game; + + // Group Link + SceNetAdhocctlGroupNode * group; + + // TCP Socket + int stream; + + // Last Ping Update + time_t last_recv; + + // RX Buffer + uint8_t rx[1024]; + uint32_t rxpos; +} SceNetAdhocctlUserNode; + +// Double-Linked Game List +struct SceNetAdhocctlGameNode { + // Next Element + struct SceNetAdhocctlGameNode * next; + + // Previous Element + struct SceNetAdhocctlGameNode * prev; + + // PSP Game Product Code + SceNetAdhocctlProductCode game; + + // Number of Players + uint32_t playercount; + + // Number of Groups + uint32_t groupcount; + + // Double-Linked Group List + SceNetAdhocctlGroupNode * group; +}; + +// Double-Linked Group List +struct SceNetAdhocctlGroupNode { + // Next Element + struct SceNetAdhocctlGroupNode * next; + + // Previous Element + struct SceNetAdhocctlGroupNode * prev; + + // Game Link + SceNetAdhocctlGameNode * game; + + // PSP Adhoc Group Name + SceNetAdhocctlGroupName group; + + // Number of Players + uint32_t playercount; + + // Double-Linked Player List + SceNetAdhocctlUserNode * player; +}; + +// User Count +extern uint32_t _db_user_count; + +// User Database +extern SceNetAdhocctlUserNode * _db_user; + +// Game Database +extern SceNetAdhocctlGameNode * _db_game; + +/** + * Login User into Database (Stream) + * @param fd Socket + * @param ip IP Address (Network Order) + */ +void login_user_stream(int fd, uint32_t ip); + +/** + * Login User into Database (Login Data) + * @param user User Node + * @param data Login Packet + */ +void login_user_data(SceNetAdhocctlUserNode * user, SceNetAdhocctlLoginPacketC2S * data); + +/** + * Logout User from Database + * @param user User Node + */ +void logout_user(SceNetAdhocctlUserNode * user); + +/** + * Free Database Memory + */ +void free_database(void); + +/** + * Connect User to Game Group + * @param user User Node + * @param group Group Name + */ +void connect_user(SceNetAdhocctlUserNode * user, SceNetAdhocctlGroupName * group); + +/** + * Disconnect User from Game Group + * @param user User Node + */ +void disconnect_user(SceNetAdhocctlUserNode * user); + +/** + * Send Game Group List + * @param user User Node + */ +void send_scan_results(SceNetAdhocctlUserNode * user); + +/** + * Spread Chat Message in P2P Network + * @param user Sender User Node + * @param message Chat Message + */ +void spread_message(SceNetAdhocctlUserNode * user, char * message); + +/** + * Get User State + * @param user User Node + */ +int get_user_state(SceNetAdhocctlUserNode * user); + +/** + * Clear RX Buffer + * @param user User Node + * @param clear Number of Bytes to clear (-1 for all) + */ +void clear_user_rxbuf(SceNetAdhocctlUserNode * user, int clear); + +/** + * Patch Game Product Code + * @param product To-be-patched Product Code + * @param from If the Product Code matches this... + * @param to ... then change it to this one. + */ +void game_product_relink(SceNetAdhocctlProductCode * product, char * from, char * to); + +/** + * Game Product Override (used for mixing multi-region games) + * @param product IN: Source Product OUT: Override Product + */ +void game_product_override(SceNetAdhocctlProductCode * product); + +/* STATUS */ + +/** + * Update Status Logfile + */ +void update_status(void); + +/** +* Server Entry Point +* @param argc Number of Arguments +* @param argv Arguments +* @return OS Error Code +*/ +int proAdhocServerThread(int port); // (int argc, char * argv[]) + +//extern int _status; +extern bool adhocServerRunning; +extern std::thread adhocServerThread; + +#endif diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index d03bb4d837..cca8e9718d 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -3313,7 +3313,7 @@ static bool __CanExecuteCallbackNow(Thread *thread) { return g_inCbCount == 0; } -static void __KernelCallAddress(Thread *thread, u32 entryPoint, Action *afterAction, const u32 args[], int numargs, bool reschedAfter, SceUID cbId) +void __KernelCallAddress(Thread *thread, u32 entryPoint, Action *afterAction, const u32 args[], int numargs, bool reschedAfter, SceUID cbId) { hleSkipDeadbeef(); _dbg_assert_msg_(SCEKERNEL, numargs <= 6, "MipsCalls can only take 6 args."); diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index 7c2037c5b2..10cf403350 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -15,6 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + #include "net/resolve.h" #include "util/text/parsers.h" @@ -31,51 +32,16 @@ #include "sceNet.h" #include "sceUtility.h" +#include "Core/HLE/proAdhoc.h" #include "Core/HLE/sceNetAdhoc.h" +#include "Core/HLE/sceNet.h" static bool netInited; static bool netInetInited; static bool netApctlInited; -// TODO: Determine how many handlers we can actually have -const size_t MAX_APCTL_HANDLERS = 32; - -enum { - ERROR_NET_BUFFER_TOO_SMALL = 0x80400706, - - ERROR_NET_INET_ALREADY_INITIALIZED = 0x80410201, - - ERROR_NET_RESOLVER_BAD_ID = 0x80410408, - ERROR_NET_RESOLVER_ALREADY_STOPPED = 0x8041040a, - ERROR_NET_RESOLVER_INVALID_HOST = 0x80410414, - - ERROR_NET_APCTL_ALREADY_INITIALIZED = 0x80410a01, - ERROR_NET_ADHOCCTL_TOO_MANY_HANDLERS = 0x80410b12, -}; - -enum { - PSP_NET_APCTL_EVENT_DISCONNECT_REQUEST = 5, -}; - -struct ProductStruct { - s32_le unknown; // Unknown, set to 0 - char product[9]; // Game ID (Example: ULUS10000) -}; - -struct SceNetMallocStat { - s32_le pool; // Pointer to the pool? - s32_le maximum; // Maximum size of the pool? - s32_le free; // How much memory is free -}; - static struct SceNetMallocStat netMallocStat; - -struct ApctlHandler { - u32 entryPoint; - u32 argument; -}; - static std::map apctlHandlers; static void __ResetInitNetLib() { @@ -87,11 +53,23 @@ static void __ResetInitNetLib() { } void __NetInit() { + //net::Init(); +#ifdef _MSC_VER + WSADATA data; + int iResult = WSAStartup(MAKEWORD(2, 2), &data); // Might be better to call WSAStartup/WSACleanup from sceNetInit/sceNetTerm isn't? since it's the first/last network function being used, even better to put it in __NetInit/__NetShutdown as it's only called once + if (iResult != NOERROR){ + ERROR_LOG(SCENET, "WSA Failed"); + } +#endif __ResetInitNetLib(); } void __NetShutdown() { __ResetInitNetLib(); + //net::Shutdown(); +#ifdef _MSC_VER + WSACleanup(); // Might be better to call WSAStartup/WSACleanup from sceNetInit/sceNetTerm isn't? since it's the first/last network function being used, even better to put it in __NetInit/__NetShutdown as it's only called once +#endif } @@ -129,6 +107,7 @@ static u32 sceNetTerm() { WARN_LOG(SCENET, "UNTESTED sceNetTerm()"); netInited = false; + return 0; } @@ -137,12 +116,12 @@ static u32 sceNetInit(u32 poolSize, u32 calloutPri, u32 calloutStack, u32 netini // May need to Terminate old one first since the game (ie. GTA:VCS) might not called sceNetTerm before the next sceNetInit and behave strangely if (netInited) sceNetTerm(); - ERROR_LOG(SCENET, "UNIMPL sceNetInit(poolsize=%d, calloutpri=%i, calloutstack=%d, netintrpri=%i, netintrstack=%d) at %08x", poolSize, calloutPri, calloutStack, netinitPri, netinitStack, currentMIPS->pc); + ERROR_LOG(SCENET, "UNTESTED sceNetInit(poolsize=%d, calloutpri=%i, calloutstack=%d, netintrpri=%i, netintrstack=%d) at %08x", poolSize, calloutPri, calloutStack, netinitPri, netinitStack, currentMIPS->pc); netInited = true; netMallocStat.maximum = poolSize; netMallocStat.free = poolSize; netMallocStat.pool = 0; - + return 0; } @@ -168,7 +147,7 @@ static u32 sceWlanDevIsPowerOn() { } static u32 sceWlanGetSwitchState() { - DEBUG_LOG(SCENET, "UNTESTED sceWlanGetSwitchState()"); + VERBOSE_LOG(SCENET, "sceWlanGetSwitchState()"); return g_Config.bEnableWlan ? 1 : 0; } @@ -253,8 +232,7 @@ static int sceNetGetMallocStat(u32 statPtr) { static int sceNetInetInit() { ERROR_LOG(SCENET, "UNIMPL sceNetInetInit()"); - if (netInetInited) - return ERROR_NET_INET_ALREADY_INITIALIZED; + if (netInetInited) return ERROR_NET_INET_ALREADY_INITIALIZED; netInetInited = true; return 0; @@ -313,9 +291,9 @@ static u32 sceNetApctlAddHandler(u32 handlerPtr, u32 handlerArg) { apctlHandlers[retval] = handler; WARN_LOG(SCENET, "UNTESTED sceNetApctlAddHandler(%x, %x): added handler %d", handlerPtr, handlerArg, retval); } - else + else { ERROR_LOG(SCENET, "UNTESTED sceNetApctlAddHandler(%x, %x): Same handler already exists", handlerPtr, handlerArg); - + } // The id to return is the number of handlers currently registered return retval; @@ -326,9 +304,9 @@ static int sceNetApctlDelHandler(u32 handlerID) { apctlHandlers.erase(handlerID); WARN_LOG(SCENET, "UNTESTED sceNetapctlDelHandler(%d): deleted handler %d", handlerID, handlerID); } - else + else { ERROR_LOG(SCENET, "UNTESTED sceNetapctlDelHandler(%d): asked to delete invalid handler %d", handlerID, handlerID); - + } return 0; } @@ -337,6 +315,61 @@ static int sceNetInetInetAton(const char *hostname, u32 addrPtr) { return -1; } +static int sceNetInetPoll(void *fds, u32 nfds, int timeout) { // timeout in miliseconds + DEBUG_LOG(SCENET, "UNTESTED sceNetInetPoll(%p, %d, %i) at %08x", fds, nfds, timeout, currentMIPS->pc); + int retval = -1; + SceNetInetPollfd *fdarray = (SceNetInetPollfd *)fds; // SceNetInetPollfd/pollfd, sceNetInetPoll() have similarity to BSD poll() but pollfd have different size on 64bit +//#ifdef _MSC_VER + //WSAPoll only available for Vista or newer, so we'll use an alternative way for XP since Windows doesn't have poll function like *NIX + if (nfds > FD_SETSIZE) return -1; + fd_set readfds, writefds, exceptfds; + FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); + for (int i = 0; i < (s32)nfds; i++) { + if (fdarray[i].events & (INET_POLLRDNORM)) FD_SET(fdarray[i].fd, &readfds); // (POLLRDNORM | POLLIN) + if (fdarray[i].events & (INET_POLLWRNORM)) FD_SET(fdarray[i].fd, &writefds); // (POLLWRNORM | POLLOUT) + //if (fdarray[i].events & (ADHOC_EV_ALERT)) // (POLLRDBAND | POLLPRI) // POLLERR + FD_SET(fdarray[i].fd, &exceptfds); + fdarray[i].revents = 0; + } + timeval tmout; + tmout.tv_sec = timeout / 1000; // seconds + tmout.tv_usec = (timeout % 1000) * 1000; // microseconds + retval = select(nfds, &readfds, &writefds, &exceptfds, &tmout); + if (retval < 0) return -1; + retval = 0; + for (int i = 0; i < (s32)nfds; i++) { + if (FD_ISSET(fdarray[i].fd, &readfds)) fdarray[i].revents |= INET_POLLRDNORM; //POLLIN + if (FD_ISSET(fdarray[i].fd, &writefds)) fdarray[i].revents |= INET_POLLWRNORM; //POLLOUT + fdarray[i].revents &= fdarray[i].events; + if (FD_ISSET(fdarray[i].fd, &exceptfds)) fdarray[i].revents |= ADHOC_EV_ALERT; // POLLPRI; // POLLERR; // can be raised on revents regardless of events bitmask? + if (fdarray[i].revents) retval++; + } +//#else + /* + // Doesn't work properly yet + pollfd *fdtmp = (pollfd *)malloc(sizeof(pollfd) * nfds); + // Note: sizeof(pollfd) = 16bytes in 64bit and 8bytes in 32bit, while sizeof(SceNetInetPollfd) is always 8bytes + for (int i = 0; i < (s32)nfds; i++) { + fdtmp[i].fd = fdarray[i].fd; + fdtmp[i].events = 0; + if (fdarray[i].events & INET_POLLRDNORM) fdtmp[i].events |= (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI); + if (fdarray[i].events & INET_POLLWRNORM) fdtmp[i].events |= (POLLOUT | POLLWRNORM | POLLWRBAND); + fdtmp[i].revents = 0; + fdarray[i].revents = 0; + } + retval = poll(fdtmp, (nfds_t)nfds, timeout); //retval = WSAPoll(fdarray, nfds, timeout); + for (int i = 0; i < (s32)nfds; i++) { + if (fdtmp[i].revents & (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) fdarray[i].revents |= INET_POLLRDNORM; + if (fdtmp[i].revents & (POLLOUT | POLLWRNORM | POLLWRBAND)) fdarray[i].revents |= INET_POLLWRNORM; + fdarray[i].revents &= fdarray[i].events; + if (fdtmp[i].revents & POLLERR) fdarray[i].revents |= POLLERR; //INET_POLLERR // can be raised on revents regardless of events bitmask? + } + free(fdtmp); + */ +//#endif + return retval; +} + static int sceNetInetRecv(int socket, u32 bufPtr, u32 bufLen, u32 flags) { ERROR_LOG(SCENET, "UNIMPL sceNetInetRecv(%i, %08x, %i, %08x)", socket, bufPtr, bufLen, flags); return -1; @@ -348,8 +381,19 @@ static int sceNetInetSend(int socket, u32 bufPtr, u32 bufLen, u32 flags) { } static int sceNetInetGetErrno() { - ERROR_LOG(SCENET, "UNIMPL sceNetInetGetErrno()"); - return -1; + ERROR_LOG(SCENET, "UNTESTED sceNetInetGetErrno()"); + int error = errno; + switch (error) { + case ETIMEDOUT: + return INET_ETIMEDOUT; + case EISCONN: + return INET_EISCONN; + case EINPROGRESS: + return INET_EINPROGRESS; + //case EAGAIN: + // return INET_EAGAIN; + } + return error; //-1; } static int sceNetInetSocket(int domain, int type, int protocol) { @@ -417,7 +461,7 @@ const HLEFunction sceNetInet[] = { {0x805502DD, 0, "sceNetInetCloseWithRST"}, {0xd10a1a7a, 0, "sceNetInetListen"}, {0xdb094e1b, 0, "sceNetInetAccept"}, - {0xfaabb1dd, 0, "sceNetInetPoll"}, + {0xfaabb1dd, WrapI_VUI, "sceNetInetPoll" }, {0x5be8d595, 0, "sceNetInetSelect"}, {0x8d7284ea, 0, "sceNetInetClose"}, {0xcda85c99, WrapI_IUUU, "sceNetInetRecv"}, diff --git a/Core/HLE/sceNet.h b/Core/HLE/sceNet.h index 48ca49f296..f077a1eaa6 100644 --- a/Core/HLE/sceNet.h +++ b/Core/HLE/sceNet.h @@ -17,6 +17,77 @@ #pragma once +#include "Core/HLE/proAdhoc.h" + +// Option Names +#define PSP_SO_REUSEPORT 0x0200 +#define PSP_SO_NBIO 0x1009 + +// Infrastructure Errno Numbers +#define INET_EAGAIN 0x0B +#define INET_ETIMEDOUT 0x74 +#define INET_EINPROGRESS 0x77 +#define INET_EISCONN 0x7F + +// On-Demand Nonblocking Flag +#define INET_MSG_DONTWAIT 0x80 + +// Event Flags +#define INET_POLLRDNORM 0x0040 +#define INET_POLLWRNORM 0x0004 + +// TODO: Determine how many handlers we can actually have +const size_t MAX_APCTL_HANDLERS = 32; + +enum { + ERROR_NET_BUFFER_TOO_SMALL = 0x80400706, + + ERROR_NET_INET_ALREADY_INITIALIZED = 0x80410201, + + ERROR_NET_RESOLVER_BAD_ID = 0x80410408, + ERROR_NET_RESOLVER_ALREADY_STOPPED = 0x8041040a, + ERROR_NET_RESOLVER_INVALID_HOST = 0x80410414, + + ERROR_NET_APCTL_ALREADY_INITIALIZED = 0x80410a01, +}; + +enum { + PSP_NET_APCTL_EVENT_DISCONNECT_REQUEST = 5, +}; + +// Sockaddr +typedef struct SceNetInetSockaddr { + uint8_t sa_len; + uint8_t sa_family; + uint8_t sa_data[14]; +} SceNetInetSockaddr; + +// Sockaddr_in +typedef struct SceNetInetSockaddrIn { + uint8_t sin_len; + uint8_t sin_family; + u16_le sin_port; //uint16_t + u32_le sin_addr; //uint32_t + uint8_t sin_zero[8]; +} SceNetInetSockaddrIn; + +// Polling Event Field +typedef struct SceNetInetPollfd { //similar format to pollfd in 32bit (pollfd in 64bit have different size) + s32_le fd; + s16_le events; + s16_le revents; +} SceNetInetPollfd; + +struct ProductStruct { + s32_le unknown; // Unknown, set to 0 // Product Type ? + char product[PRODUCT_CODE_LENGTH]; // Game ID (Example: ULUS10000) +}; + +struct ApctlHandler { + u32 entryPoint; + u32 argument; +}; + class PointerWrap; void Register_sceNet(); @@ -25,3 +96,5 @@ void Register_sceWlanDrv(); void __NetInit(); void __NetShutdown(); void __NetDoState(PointerWrap &p); + +int sceNetInetPoll(void *fds, u32 nfds, int timeout); \ No newline at end of file diff --git a/Core/HLE/sceNetAdhoc.cpp b/Core/HLE/sceNetAdhoc.cpp index 40a0bb9fd3..30f7d0e6f0 100644 --- a/Core/HLE/sceNetAdhoc.cpp +++ b/Core/HLE/sceNetAdhoc.cpp @@ -20,161 +20,63 @@ // 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/MemMap.h" #include "Common/ChunkFile.h" +#include "Core/MIPS/MIPSCodeUtils.h" + +#include "Core/HLE/HLEHelperThread.h" #include "Core/HLE/FunctionWrappers.h" #include "Core/HLE/sceKernelThread.h" #include "Core/HLE/sceNetAdhoc.h" +#include "Core/HLE/sceKernel.h" +#include "Core/HLE/sceKernelMemory.h" +#include "Core/HLE/sceKernelModule.h" +#include "Core/HLE/sceKernelInterrupt.h" #include "Core/HLE/proAdhoc.h" -#include "Core/MemMap.h" - -enum { - ERROR_NET_ADHOC_INVALID_SOCKET_ID = 0x80410701, - ERROR_NET_ADHOC_INVALID_ADDR = 0x80410702, - ERROR_NET_ADHOC_INVALID_ARG = 0x80410B04, - ERROR_NET_ADHOC_NO_DATA_AVAILABLE = 0x80410709, - ERROR_NET_ADHOC_PORT_IN_USE = 0x8041070a, - ERROR_NET_ADHOC_NOT_INITIALIZED = 0x80410712, - ERROR_NET_ADHOC_ALREADY_INITIALIZED = 0x80410713, - ERROR_NET_ADHOC_DISCONNECTED = 0x8041070c, - ERROR_NET_ADHOC_TIMEOUT = 0x80410715, - ERROR_NET_ADHOC_NO_ENTRY = 0x80410716, - ERROR_NET_ADHOC_CONNECTION_REFUSED = 0x80410718, - ERROR_NET_ADHOC_INVALID_MATCHING_ID = 0x80410807, - ERROR_NET_ADHOC_MATCHING_ALREADY_INITIALIZED = 0x80410812, - ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED = 0x80410813, - ERROR_NET_ADHOC_WOULD_BLOCK = 0x80410709, - ERROR_NET_ADHOC_INVALID_DATALEN = 0x80410705, - ERROR_NET_ADHOC_INVALID_PORT = 0x80410703, - ERROR_NET_ADHOC_NOT_LISTENED = 0x8040070E, - ERROR_NET_ADHOC_NOT_OPENED = 0x8040070D, - ERROR_NET_ADHOC_SOCKET_ID_NOT_AVAIL = 0x8041070F, - ERROR_NET_ADHOC_NOT_CONNECTED = 0x8041070B, - - ERROR_NET_ADHOCCTL_INVALID_ARG = 0x80410B04, - ERROR_NET_ADHOCCTL_WLAN_SWITCH_OFF = 0x80410b03, - ERROR_NET_ADHOCCTL_ALREADY_INITIALIZED = 0x80410b07, - ERROR_NET_ADHOCCTL_NOT_INITIALIZED = 0x80410b08, - ERROR_NET_ADHOCCTL_DISCONNECTED = 0x80410b09, - ERROR_NET_ADHOCCTL_BUSY = 0x80410b10, - ERROR_NET_ADHOCCTL_TOO_MANY_HANDLERS = 0x80410b12, - - ERROR_NET_ADHOC_MATCHING_INVALID_MODE = 0x80410801, - ERROR_NET_ADHOC_MATCHING_INVALID_MAXNUM = 0x80410803, - ERROR_NET_ADHOC_MATCHING_RXBUF_TOO_SHORT = 0x80410804, - ERROR_NET_ADHOC_MATCHING_INVALID_OPTLEN = 0x80410805, - ERROR_NET_ADHOC_MATCHING_INVALID_ARG = 0x80410806, - ERROR_NET_ADHOC_MATCHING_INVALID_ID = 0x80410807, - ERROR_NET_ADHOC_MATCHING_ID_NOT_AVAIL = 0x80410808, - ERROR_NET_ADHOC_MATCHING_NO_SPACE = 0x80410809, - ERROR_NET_ADHOC_MATCHING_IS_RUNNING = 0x8041080A, - ERROR_NET_ADHOC_MATCHING_NOT_RUNNING = 0x8041080B, - ERROR_NET_ADHOC_MATCHING_UNKNOWN_TARGET = 0x8041080C, - ERROR_NET_ADHOC_MATCHING_TARGET_NOT_READY = 0x8041080D, - ERROR_NET_ADHOC_MATCHING_EXCEED_MAXNUM = 0x8041080E, - ERROR_NET_ADHOC_MATCHING_REQUEST_IN_PROGRESS = 0x8041080F, - ERROR_NET_ADHOC_MATCHING_ALREADY_ESTABLISHED = 0x80410810, - ERROR_NET_ADHOC_MATCHING_BUSY = 0x80410811, - ERROR_NET_ADHOC_MATCHING_PORT_IN_USE = 0x80410814, - ERROR_NET_ADHOC_MATCHING_STACKSIZE_TOO_SHORT = 0x80410815, - ERROR_NET_ADHOC_MATCHING_INVALID_DATALEN = 0x80410816, - ERROR_NET_ADHOC_MATCHING_NOT_ESTABLISHED = 0x80410817, - ERROR_NET_ADHOC_MATCHING_DATA_BUSY = 0x80410818, - - ERROR_NET_NO_SPACE = 0x80410001 -}; - -enum { - PSP_ADHOC_POLL_READY_TO_SEND = 1, - PSP_ADHOC_POLL_DATA_AVAILABLE = 2, - PSP_ADHOC_POLL_CAN_CONNECT = 4, - PSP_ADHOC_POLL_CAN_ACCEPT = 8, -}; - -enum { -/** -* Matching events used in pspAdhocMatchingCallback -*/ - /** Hello event. optdata contains data if optlen > 0. */ - PSP_ADHOC_MATCHING_EVENT_HELLO = 1, - /** Join request. optdata contains data if optlen > 0. */ - PSP_ADHOC_MATCHING_EVENT_JOIN = 2, - /** Target left matching. */ - PSP_ADHOC_MATCHING_EVENT_LEFT = 3, - /** Join request rejected. */ - PSP_ADHOC_MATCHING_EVENT_REJECT = 4, - /** Join request cancelled. */ - PSP_ADHOC_MATCHING_EVENT_CANCEL = 5, - /** Join request accepted. optdata contains data if optlen > 0. */ - PSP_ADHOC_MATCHING_EVENT_ACCEPT = 6, - /** Matching is complete. */ - PSP_ADHOC_MATCHING_EVENT_COMPLETE = 7, - /** Ping timeout event. */ - PSP_ADHOC_MATCHING_EVENT_TIMEOUT = 8, - /** Error event. */ - PSP_ADHOC_MATCHING_EVENT_ERROR = 9, - /** Peer disconnect event. */ - PSP_ADHOC_MATCHING_EVENT_DISCONNECT = 10, - /** Data received event. optdata contains data if optlen > 0. */ - PSP_ADHOC_MATCHING_EVENT_DATA = 11, - /** Data acknowledged event. */ - PSP_ADHOC_MATCHING_EVENT_DATA_CONFIRM = 12, - /** Data timeout event. */ - PSP_ADHOC_MATCHING_EVENT_DATA_TIMEOUT = 13, - - /** Internal ping message. */ - PSP_ADHOC_MATCHING_EVENT_INTERNAL_PING = 100, - - /** - * Matching modes used in sceNetAdhocMatchingCreate - */ - /** Host */ - PSP_ADHOC_MATCHING_MODE_HOST = 1, - /** Client */ - PSP_ADHOC_MATCHING_MODE_CLIENT = 2, - /** Peer to peer */ - PSP_ADHOC_MATCHING_MODE_PTP = 3, -}; - -const size_t MAX_ADHOCCTL_HANDLERS = 32; +#include "Core/HLE/sceNet.h" +#include "Core/HLE/proAdhocServer.h" // shared in sceNetAdhoc.h since it need to be used from sceNet.cpp also -/*static*/ bool netAdhocInited; -/*static*/ bool netAdhocctlInited; +bool netAdhocInited; +bool netAdhocctlInited; static bool netAdhocMatchingInited; +int netAdhocMatchingStarted = 0; -struct AdhocctlHandler { - u32 entryPoint; - u32 argument; -}; +SceUID threadAdhocID; +Thread *threadAdhoc; +u32 dummyThreadHackAddr; -static std::map adhocctlHandlers; - -void __NetAdhocInit() { - friendFinderRunning = false; - eventHandlerUpdate = -1; - netAdhocInited = false; - netAdhocctlInited = false; - netAdhocMatchingInited = false; - adhocctlHandlers.clear(); -} +std::map adhocctlHandlers; +int matchingEventThread(int matchingId); +int matchingInputThread(int matchingId); int sceNetAdhocTerm(); int sceNetAdhocctlTerm(); int sceNetAdhocMatchingTerm(); int sceNetAdhocMatchingSetHelloOpt(int matchingId, int optLenAddr, u32 optDataAddr); +static u32_le dummyThreadCode[4]; /* = { + MIPS_MAKE_ADDIU(MIPS_REG_A0, MIPS_REG_ZERO, 1000), + MIPS_MAKE_SYSCALL("ThreadManForUser", "sceKernelDelayThread"), + MIPS_MAKE_B(-3), + MIPS_MAKE_NOP(), + //MIPS_MAKE_BREAK(0), +};*/ + void __NetAdhocShutdown() { // Checks to avoid confusing logspam - if (netAdhocInited) { - sceNetAdhocTerm(); + if (netAdhocMatchingInited) { + sceNetAdhocMatchingTerm(); } if (netAdhocctlInited) { sceNetAdhocctlTerm(); } - if (netAdhocMatchingInited) { - sceNetAdhocMatchingTerm(); + if (netAdhocInited) { + sceNetAdhocTerm(); } + kernelMemory.Free(dummyThreadHackAddr); } void __NetAdhocDoState(PointerWrap &p) { @@ -186,19 +88,42 @@ void __NetAdhocDoState(PointerWrap &p) { p.Do(netAdhocctlInited); p.Do(netAdhocMatchingInited); p.Do(adhocctlHandlers); + + //p.Do(actionAfterMatchingMipsCall); // This could cause incompatibility with old savestate right? + //__KernelRestoreActionType(actionAfterMatchingMipsCall, AfterMatchingMipsCall::Create); + + //u32 blockSize = sizeof(dummyThreadCode); + //dummyThreadHackAddr = kernelMemory.Alloc(blockSize, false, "dummythreadhack"); + Memory::Memcpy(dummyThreadHackAddr, dummyThreadCode, sizeof(dummyThreadCode)); } static void __UpdateAdhocctlHandlers(int flag, int error) { - u32 args[3] = { 0, 0, 0 }; + u32_le args[3] = { 0, 0, 0 }; args[0] = flag; args[1] = error; + //__KernelSwitchToThread(threadIdleID[1], "switch to Adhocctl"); for (std::map::iterator it = adhocctlHandlers.begin(); it != adhocctlHandlers.end(); ++it) { args[2] = it->second.argument; - __KernelDirectMipsCall(it->second.entryPoint, NULL, args, 3, true); + //__KernelDirectMipsCall(it->second.entryPoint, NULL, args, 3, true); + __KernelCallAddress(threadAdhoc, it->second.entryPoint, NULL, args, 3, true, 0); } } +// TODO: MipsCall needs to be called from it's own PSP Thread instead of from any random PSP Thread +void __UpdateMatchingHandler(u64 ArgsPtr) { + u32_le *args = (u32_le *)ArgsPtr; + AfterMatchingMipsCall *after = (AfterMatchingMipsCall *)__KernelCreateAction(actionAfterMatchingMipsCall); + after->SetContextID(args[0], args[1]); + //u32 error; + //Thread *t = kernelObjects.Get(threadAdhocID, error); + //__KernelSwitchToThread(threadIdleID[1], "switch to AdhocMatching"); // __KernelSwitchContext(threadIdleID[1], "switch to AdhocMatching"); + __KernelCallAddress(threadAdhoc, args[5], after, args, 5, true, 0); + //__KernelDirectMipsCall(args[5], after, args, 5, true); + // Make sure MIPS call have been fully executed before the next callback invoked + //while (/*(after != NULL) &&*/ IsMatchingInCallback(context)) sleep_ms(1); //Must not sleep inside callback handler otherwise Metal Slug XX will gets ThreadQueueList Empty popup +} + static int getBlockingFlag(int id) { #ifdef _MSC_VER return 0; @@ -208,13 +133,56 @@ static int getBlockingFlag(int id) { #endif } -static void __handlerUpdateCallback(u64 userdata, int cycleslate) { +static void __handlerAdhocctlUpdateCallback(u64 userdata, int cycleslate) { + //SceUID cur = __KernelGetCurThread(); + // TODO: Since we only have access to __KernelDirectMipsCall we need to switch the thread context first to make sure the mipscall executed on the right thread + // Since __KernelSwitchToThread will flood the log with errors when current thread is already non-idle thread so we'll try to use any "fake" psp thread, BUT we need to backup ALL registers before the mipscall to prevent registers corruption after returning from mipscall + if ((__IsInInterrupt() || !__KernelIsDispatchEnabled() || __KernelInCallback()) /*||*/) + // ((cur != threadAdhocID && cur != threadIdleID[0] && cur != threadIdleID[1]) /*&& !__KernelSwitchToThread(threadAdhocID, "switch to AdhocThread")*/)) + { + // // Can't do anything now, inside an interrupt. Let's wait until later. + CoreTiming::ScheduleEvent(100, eventAdhocctlHandlerUpdate, userdata); + return; + } int buff[2]; split64(userdata,buff); __UpdateAdhocctlHandlers(buff[0], buff[1]); } -static u32 sceNetAdhocInit() { +static void __handlerMatchingUpdateCallback(u64 userdata, int cycleslate) { + //SceUID cur = __KernelGetCurThread(); + // TODO: Since we only have access to __KernelDirectMipsCall we need to switch the thread context first to make sure the mipscall executed on the right thread + // Since __KernelSwitchToThread will flood the log with errors when current thread is already non-idle thread so we'll try to use any "fake" psp thread, BUT we need to backup ALL registers before the mipscall to prevent registers corruption after returning from mipscall + if ((__IsInInterrupt() || !__KernelIsDispatchEnabled() || __KernelInCallback()) /*||*/) + // ((cur != threadAdhocID && cur != threadIdleID[0] && cur != threadIdleID[1]) /*&& !__KernelSwitchToThread(threadAdhocID, "switch to AdhocThread")*/)) + { + // Can't do anything now, inside an interrupt. Let's wait until later. + CoreTiming::ScheduleEvent(100, eventMatchingHandlerUpdate, userdata); + return; + } + __UpdateMatchingHandler(userdata); +} + +void __NetAdhocInit() { + friendFinderRunning = false; + netAdhocInited = false; + netAdhocctlInited = false; + netAdhocMatchingInited = false; + adhocctlHandlers.clear(); + dummyThreadCode[0] = MIPS_MAKE_ADDIU(MIPS_REG_A0, MIPS_REG_ZERO, 1000); + dummyThreadCode[1] = MIPS_MAKE_SYSCALL("ThreadManForUser", "sceKernelDelayThread"); + dummyThreadCode[2] = MIPS_MAKE_B(-3); + dummyThreadCode[3] = MIPS_MAKE_NOP(); + //dummyThreadCode[4] = MIPS_MAKE_BREAK(0); + u32 blockSize = sizeof(dummyThreadCode); + dummyThreadHackAddr = kernelMemory.Alloc(blockSize, false, "dummythreadhack"); + Memory::Memcpy(dummyThreadHackAddr, dummyThreadCode, sizeof(dummyThreadCode)); // This area will be cleared again after loading an old savestate :( + actionAfterMatchingMipsCall = __KernelRegisterActionType(AfterMatchingMipsCall::Create); + eventAdhocctlHandlerUpdate = CoreTiming::RegisterEvent("AdhocctlHandlerUpdateEvent", __handlerAdhocctlUpdateCallback); + eventMatchingHandlerUpdate = CoreTiming::RegisterEvent("MatchingHandlerUpdateEvent", __handlerMatchingUpdateCallback); +} + +u32 sceNetAdhocInit() { // Library uninitialized INFO_LOG(SCENET, "sceNetAdhocInit() at %08x", currentMIPS->pc); if (!netAdhocInited) { @@ -225,6 +193,23 @@ static u32 sceNetAdhocInit() { // Library initialized netAdhocInited = true; + // 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 + #define PSP_THREAD_ATTR_KERNEL 0x00001000 // PSP_THREAD_ATTR_KERNEL is located in sceKernelThread.cpp instead of sceKernelThread.h :( + //threadAdhocID = __KernelCreateThreadInternal("AdhocThread", __KernelGetCurThreadModuleId(), dummyThreadHackAddr, 0x30, 4096, PSP_THREAD_ATTR_KERNEL); + threadAdhoc = __KernelCreateThread(threadAdhocID, __KernelGetCurThreadModuleId(), "AdhocThread", dummyThreadHackAddr, 0x10, 8192, PSP_THREAD_ATTR_KERNEL); // We don't have access to __KernelCreateThread function that use Thread class from sceKernelThread.h :( + if (threadAdhocID > 0) { + __KernelStartThread(threadAdhocID, 0, 0); + } + + // Create built-in AdhocServer Thread + // TODO: It might be better to have it's own config (ie. g_Config.bEnableAdhocServer) + if (g_Config.bEnableWlan) { + //_status = 1; + adhocServerRunning = true; + adhocServerThread = std::thread(proAdhocServerThread, SERVER_PORT); + } + // Return Success return 0; } @@ -234,25 +219,23 @@ static u32 sceNetAdhocInit() { 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; - } else if (!g_Config.bEnableWlan) { + /*if (!g_Config.bEnableWlan) { // Pretend success but don't actually start the friendfinder thread and stuff. // Dunno if this is the way to go... netAdhocctlInited = true; - return 0; - } else if (initNetwork((SceNetAdhocctlAdhocId *)Memory::GetPointer(productAddr)) == 0) { - netAdhocctlInited = true; - eventHandlerUpdate = CoreTiming::RegisterEvent("HandlerUpdateEvent", __handlerUpdateCallback); + return 0; //Faking success to prevent GTA:VCS stuck in Host/Join screen + }*/ + + if (netAdhocctlInited) return ERROR_NET_ADHOCCTL_ALREADY_INITIALIZED; + + if (initNetwork((SceNetAdhocctlAdhocId *)Memory::GetPointer(productAddr)) != 0) WARN_LOG(SCENET, "sceNetAdhocctlInit: Faking success"); + + if (!friendFinderRunning) { friendFinderRunning = true; friendFinderThread = std::thread(friendFinder); - } else { - //WARN_LOG(SCENET, "sceNetAdhocctlInit: Failed to initialize"); - //return -1; // ERROR_NET_ADHOCCTL_NOT_INITIALIZED; //returning success while initNetwork failed to connect to ProServer may cause some games (ie. GTA:VCS) to behave strangely/stuck, but if not success some games (ie. Ford Street Racing) will also stuck - WARN_LOG(SCENET, "sceNetAdhocctlInit: Faking success"); - //return 0; // Generic error, but just return success to make games conform. } - netAdhocctlInited = true; //needed for cleanup during ctlTerm even when it failed to connect to Adhoc Server (since it's being faked as success) + + netAdhocctlInited = true; //needed for cleanup during AdhocctlTerm even when it failed to connect to Adhoc Server (since it's being faked as success) return 0; } @@ -285,7 +268,7 @@ static int sceNetAdhocctlGetState(u32 ptrToStatus) { */ // When choosing AdHoc menu in Wipeout Pulse sometimes it's saying that "WLAN is turned off" on game screen and getting "kUnityCommandCode_MediaDisconnected" error in the Log Console when calling sceNetAdhocPdpCreate, probably it needed to wait something from the thread before calling this (ie. need to receives 7 bytes from adhoc server 1st?) static int sceNetAdhocPdpCreate(const char *mac, u32 port, int bufferSize, u32 unknown) { - INFO_LOG(SCENET, "sceNetAdhocPdpCreate(%p, %u, %u, %u) at %08x", mac, port, bufferSize, unknown, currentMIPS->pc); + INFO_LOG(SCENET, "sceNetAdhocPdpCreate(%s, %u, %u, %u) at %08x", mac, port, bufferSize, unknown, currentMIPS->pc); if (!g_Config.bEnableWlan) { return -1; } @@ -308,13 +291,19 @@ static int sceNetAdhocPdpCreate(const char *mac, u32 port, int bufferSize, u32 u int usocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Valid Socket produced if (usocket != INVALID_SOCKET) { - // Enable Port Re-use - //setsockopt(usocket, SOL_SOCKET, SO_REUSEADDR, &_one, sizeof(_one)); NO idea if we need this + // Change socket buffer size when necessary + if (getSockBufferSize(usocket, SO_SNDBUF) < bufferSize) setSockBufferSize(usocket, SO_SNDBUF, bufferSize); + if (getSockBufferSize(usocket, SO_RCVBUF) < bufferSize) setSockBufferSize(usocket, SO_RCVBUF, bufferSize); + + // Enable Port Re-use, this will allow binding to an already used port, but only one of them can read the data (shared receive buffer?) + int one = 1; + setsockopt(usocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one)); // NO idea if we need this // Binding Information for local Port sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; + //if (port < 7) addr.sin_port = htons(port + 1341); else // <= 443 addr.sin_port = htons(port); // This not safe in any way... // The port might be under 1024 (ie. GTA:VCS use port 1, Ford Street Racing use port 0 (UNUSED_PORT), etc) and already used by other application/host OS, should we add 1024 to the port whenever it tried to use an already used port? @@ -342,7 +331,7 @@ static int sceNetAdhocPdpCreate(const char *mac, u32 port, int bufferSize, u32 u // Fill in Data internal->id = usocket; internal->laddr = *saddr; - internal->lport = ntohs(getLocalPort(usocket)); // port; //should use the port given to the socket (in case it's UNUSED_PORT port) isn't? + internal->lport = getLocalPort(usocket); //should use the port given to the socket (in case it's UNUSED_PORT port) isn't? internal->rcv_sb_cc = bufferSize; // Link Socket to Translator ID @@ -350,15 +339,6 @@ static int sceNetAdhocPdpCreate(const char *mac, u32 port, int bufferSize, u32 u // Forward Port on Router //sceNetPortOpen("UDP", sport); // I need to figure out how to use this in windows/linux - - // Wait for Status to be connected to prevent Wipeout Pulse from showing "WLAN is turned off" - if ((i == 0) && friendFinderRunning) { - int cnt = 0; - while ((threadStatus != ADHOCCTL_STATE_CONNECTED) && (cnt < 5000)) { - sleep_ms(1); - cnt++; - } - } // Success return i + 1; @@ -402,7 +382,7 @@ static int sceNetAdhocPdpCreate(const char *mac, u32 port, int bufferSize, u32 u * @return 0 on success or... ADHOCCTL_NOT_INITIALIZED, ADHOCCTL_INVALID_ARG */ static int sceNetAdhocctlGetParameter(u32 paramAddr) { - DEBUG_LOG(SCENET, "sceNetAdhocctlGetParameter(%u)",paramAddr); + DEBUG_LOG(SCENET, "sceNetAdhocctlGetParameter(%08x)",paramAddr); if (!g_Config.bEnableWlan) { return ERROR_NET_ADHOCCTL_DISCONNECTED; } @@ -437,12 +417,14 @@ static int sceNetAdhocctlGetParameter(u32 paramAddr) { * @return 0 on success or... ADHOC_INVALID_ARG, ADHOC_NOT_INITIALIZED, ADHOC_INVALID_SOCKET_ID, ADHOC_SOCKET_DELETED, ADHOC_INVALID_ADDR, ADHOC_INVALID_PORT, ADHOC_INVALID_DATALEN, ADHOC_SOCKET_ALERTED, ADHOC_TIMEOUT, ADHOC_THREAD_ABORTED, ADHOC_WOULD_BLOCK, NET_NO_SPACE, NET_INTERNAL */ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int len, int timeout, int flag) { - DEBUG_LOG(SCENET, "sceNetAdhocPdpSend(%i, %p, %i, %p, %i, %i, %i)", id, mac, port, data, len, timeout, flag); + DEBUG_LOG(SCENET, "sceNetAdhocPdpSend(%i, %s, %i, %p, %i, %i, %i)", id, mac, port, data, len, timeout, flag); if (!g_Config.bEnableWlan) { return -1; } SceNetEtherAddr * daddr = (SceNetEtherAddr *)mac; uint16 dport = (uint16)port; + + //if (dport < 7) dport += 1341; // Really should flatten this with early outs, all this indentation is making me dizzy. @@ -485,7 +467,7 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int int sent = sendto(socket->id, (const char *)data, len, 0, (sockaddr *)&target, sizeof(target)); int error = errno; if (sent == SOCKET_ERROR) { - ERROR_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpSend [size=%i]", error, len); + DEBUG_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpSend[%i:%u->%u] (size=%i)", error, id, getLocalPort(socket->id), ntohs(target.sin_port), len); } changeBlockingMode(socket->id, 0); @@ -495,7 +477,7 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int uint8_t * sip = (uint8_t *)&target.sin_addr.s_addr; // Sent Data if (sent == len) { - DEBUG_LOG(SCENET, "sceNetAdhocPdpSend[%i:%u]: Sent %u bytes to %u.%u.%u.%u:%u", socket->id, ntohs(getLocalPort(socket->id)), sent, sip[0], sip[1], sip[2], sip[3], ntohs(target.sin_port)); + DEBUG_LOG(SCENET, "sceNetAdhocPdpSend[%i:%u]: Sent %u bytes to %u.%u.%u.%u:%u\n", id, getLocalPort(socket->id), sent, sip[0], sip[1], sip[2], sip[3], ntohs(target.sin_port)); // Success return 0; @@ -534,6 +516,9 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int // Iterate Peers SceNetAdhocctlPeerInfo * peer = friends; for (; peer != NULL; peer = peer->next) { + // Skip timed out friends + if (peer->last_recv == 0) continue; + // Fill in Target Structure sockaddr_in target; target.sin_family = AF_INET; @@ -545,12 +530,12 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int int sent = sendto(socket->id, (const char *)data, len, 0, (sockaddr *)&target, sizeof(target)); int error = errno; if (sent == SOCKET_ERROR) { - ERROR_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpSend[%i](BC) [size=%i]", error, socket->id, len); + DEBUG_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpSend[%i:%u->%u](BC) [size=%i]", error, id, getLocalPort(socket->id), ntohs(target.sin_port), len); } changeBlockingMode(socket->id, 0); if (sent >= 0) { uint8_t * sip = (uint8_t *)&target.sin_addr.s_addr; - DEBUG_LOG(SCENET, "sceNetAdhocPdpSend[%i:%u](BC): Sent %u bytes to %u.%u.%u.%u:%u", socket->id, ntohs(getLocalPort(socket->id)), sent, sip[0], sip[1], sip[2], sip[3], ntohs(target.sin_port)); + DEBUG_LOG(SCENET, "sceNetAdhocPdpSend[%i:%u](BC): Sent %u bytes to %u.%u.%u.%u:%u\n", id, getLocalPort(socket->id), sent, sip[0], sip[1], sip[2], sip[3], ntohs(target.sin_port)); } } @@ -656,18 +641,18 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void * //_acquireNetworkLock(); // Receive Data - changeBlockingMode(socket->id,flag); + changeBlockingMode(socket->id, flag); int received = recvfrom(socket->id, (char *)buf, *len,0,(sockaddr *)&sin, &sinlen); int error = errno; if (received == SOCKET_ERROR) { - DEBUG_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpRecv [size=%i]", error, *len); + VERBOSE_LOG(SCENET, "Socket Error (%i) on sceNetAdhocPdpRecv [size=%i]", error, *len); } changeBlockingMode(socket->id, 0); // Received Data if (received >= 0) { uint8_t * sip = (uint8_t *)&sin.sin_addr.s_addr; - DEBUG_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Received %u bytes from %u.%u.%u.%u:%u", socket->id, ntohs(getLocalPort(socket->id)), received, sip[0], sip[1], sip[2], sip[3], ntohs(sin.sin_port)); + DEBUG_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Received %u bytes from %u.%u.%u.%u:%u\n", id, getLocalPort(socket->id), received, sip[0], sip[1], sip[2], sip[3], ntohs(sin.sin_port)); // Peer MAC SceNetEtherAddr mac; @@ -687,13 +672,13 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void * // Return Success return 0; } - INFO_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Unknown Peer %u.%u.%u.%u:%u", socket->id, ntohs(getLocalPort(socket->id)), sip[0], sip[1], sip[2], sip[3], ntohs(sin.sin_port)); + WARN_LOG(SCENET, "sceNetAdhocPdpRecv[%i:%u]: Received %i bytes from Unknown Peer %u.%u.%u.%u:%u [%02X:%02X:%02X:%02X:%02X:%02X]", id, getLocalPort(socket->id), received, sip[0], sip[1], sip[2], sip[3], ntohs(sin.sin_port), mac.data[0], mac.data[1], mac.data[2], mac.data[3], mac.data[4], mac.data[5]); // Free Network Lock //_freeNetworkLock(); //Receiving data from unknown peer, ignore it ? - return ERROR_NET_ADHOC_NO_DATA_AVAILABLE; + //return ERROR_NET_ADHOC_WOULD_BLOCK; //ERROR_NET_ADHOC_NO_DATA_AVAILABLE } // Free Network Lock @@ -721,15 +706,112 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void * return ERROR_NET_ADHOC_NOT_INITIALIZED; } -// Assuming < 0 for failure, homebrew SDK doesn't have much to say about this one.. -static int sceNetAdhocSetSocketAlert(int id, int flag) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocSetSocketAlert(%d, %d)", id, flag); - return -1; +// Flags seems to be bitmasks of ADHOC_F_ALERT... +int sceNetAdhocSetSocketAlert(int id, int flag) { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocSetSocketAlert(%d, %08x)", id, flag); + + return 0; //Dummy Result } -static int sceNetAdhocPollSocket(u32 socketStructAddr, int count, int timeout, int nonblock) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocPollSocket(%08x, %i, %i, %i)", socketStructAddr, count, timeout, nonblock); - return -1; +int sceNetAdhocPollSocket(u32 socketStructAddr, int count, int timeout, int nonblock) { // timeout in microseconds + DEBUG_LOG(SCENET, "UNTESTED sceNetAdhocPollSocket(%08x, %i, %i, %i) at %08x", socketStructAddr, count, timeout, nonblock, currentMIPS->pc); + + // Library is initialized + if (netAdhocInited) + { + SceNetAdhocPollSd * sds = NULL; + if (Memory::IsValidAddress(socketStructAddr)) sds = (SceNetAdhocPollSd *)Memory::GetPointer(socketStructAddr); + + // Valid Arguments + if (sds != NULL && count > 0) + { + // Socket Check + int i = 0; for (; i < count; i++) + { + // Invalid Socket + if (sds[i].id < 1 || sds[i].id > 255 || (pdp[sds[i].id - 1] == NULL && ptp[sds[i].id - 1] == NULL)) return ERROR_NET_ADHOC_INVALID_SOCKET_ID; + } + + // Nonblocking Mode + if (nonblock) timeout = 0; + + // Prevent Nonblocking Mode + else + if (timeout == 0) timeout = 1; + + int affectedsockets = 0; + if (count > FD_SETSIZE) count = FD_SETSIZE; // return affectedsockets; + + // Acquire Network Lock + //acquireNetworkLock(); + + // Poll Sockets + //int affectedsockets = sceNetInetPoll(isds, count, timeout); + + //WSAPoll only available for Vista or newer, so we'll use an alternative way for XP since Windows doesn't have poll function like *NIX + fd_set readfds, writefds, exceptfds; + int fd; + FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); + for (int i = 0; i < count; i++) { + sds[i].revents = 0; + // Fill in Socket ID + if (pdp[sds[i].id - 1] != NULL) { + fd = pdp[sds[i].id - 1]->id; + } + else { + fd = ptp[sds[i].id - 1]->id; + if (ptp[sds[i].id - 1]->state == ADHOC_PTP_STATE_LISTEN) sds[i].revents |= ADHOC_EV_ACCEPT; + else + if (ptp[sds[i].id - 1]->state == ADHOC_PTP_STATE_CLOSED) sds[i].revents |= ADHOC_EV_CONNECT; + } + if (sds[i].events & ADHOC_EV_RECV) FD_SET(fd, &readfds); + if (sds[i].events & ADHOC_EV_SEND) FD_SET(fd, &writefds); + //if (sds[i].events & ADHOC_EV_ALERT) + FD_SET(fd, &exceptfds); + } + timeval tmout; + tmout.tv_sec = timeout / 1000000; // seconds + tmout.tv_usec = (timeout % 1000000); // microseconds + affectedsockets = select(count, &readfds, &writefds, &exceptfds, &tmout); + if (affectedsockets > 0) { + affectedsockets = 0; + for (int i = 0; i < count; i++) { + if (pdp[sds[i].id - 1] != NULL) { + fd = pdp[sds[i].id - 1]->id; + } + else { + fd = ptp[sds[i].id - 1]->id; + } + if (FD_ISSET(fd, &readfds)) sds[i].revents |= ADHOC_EV_RECV; + if (FD_ISSET(fd, &writefds)) sds[i].revents |= ADHOC_EV_SEND; + sds[i].revents &= sds[i].events; + if (FD_ISSET(fd, &exceptfds)) sds[i].revents |= ADHOC_EV_ALERT; // can be raised on revents regardless of events bitmask? + if (sds[i].revents) affectedsockets++; + } + } + // Free Network Lock + //freeNetworkLock(); + + // Blocking Mode (Nonblocking Mode returns 0, even on Success) + if (!nonblock) + { + // Success + if (affectedsockets >= 0) return affectedsockets; // (affectedsockets > 0) + + // Timeout + return ERROR_NET_ADHOC_TIMEOUT; + } + + // No Events generated + return 0; + } + + // Invalid Argument + return ERROR_NET_ADHOC_INVALID_ARG; + } + + // Library is uninitialized + return ERROR_NET_ADHOC_NOT_INITIALIZED; } /** @@ -785,8 +867,29 @@ static int sceNetAdhocPdpDelete(int id, int unknown) { } static int sceNetAdhocctlGetAdhocId(u32 productStructAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetAdhocId(%x)", productStructAddr); - return 0; + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetAdhocId(%08x)", productStructAddr); + + // Library initialized + if (netAdhocctlInited) + { + // Valid Arguments + if (Memory::IsValidAddress(productStructAddr)) + { + SceNetAdhocctlAdhocId * adhoc_id = (SceNetAdhocctlAdhocId *)Memory::GetPointer(productStructAddr); + // Copy Product ID + *adhoc_id = product_code; + //Memory::WriteStruct(productStructAddr, &product_code); + + // Return Success + return 0; + } + + // Invalid Arguments + return ERROR_NET_ADHOCCTL_INVALID_ARG; + } + + // Library uninitialized + return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; } static int sceNetAdhocctlScan() { @@ -798,24 +901,16 @@ static int sceNetAdhocctlScan() { if (threadStatus == ADHOCCTL_STATE_DISCONNECTED) { threadStatus = ADHOCCTL_STATE_SCANNING; - // Multithreading Lock - peerlock.lock(); - - // It seems AdHoc Server always sent the full group list, so we should reset current networks to prevent leaving host to be listed again - freeGroupsRecursive(networks); - networks = NULL; - - // Multithreading Unlock - peerlock.unlock(); - // Prepare Scan Request Packet uint8_t opcode = OPCODE_SCAN; // Send Scan Request Packet, may failed with socket error 10054/10053 if someone else with the same IP already connected to AdHoc Server (the server might need to be modified to differentiate MAC instead of IP) int iResult = send(metasocket, (char *)&opcode, 1, 0); if (iResult == SOCKET_ERROR) { - ERROR_LOG(SCENET, "Socket error (%i) when sending", errno); + int error = errno; + ERROR_LOG(SCENET, "Socket error (%i) when sending", error); threadStatus = ADHOCCTL_STATE_DISCONNECTED; + //if (error == ECONNABORTED || error == ECONNRESET || error == ENOTCONN) return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; // A case where it need to reconnect to AdhocServer return ERROR_NET_ADHOCCTL_DISCONNECTED; // ERROR_NET_ADHOCCTL_BUSY } @@ -840,20 +935,21 @@ static int sceNetAdhocctlScan() { return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; } -static int sceNetAdhocctlGetScanInfo(u32 size, u32 bufAddr) { - INFO_LOG(SCENET, "sceNetAdhocctlGetScanInfo([%08x]=%i, %08x)", size, Memory::Read_U32(size), bufAddr); +static int sceNetAdhocctlGetScanInfo(u32 sizeAddr, u32 bufAddr) { + s32_le *buflen = NULL; + if (Memory::IsValidAddress(sizeAddr)) buflen = (s32_le *)Memory::GetPointer(sizeAddr); + SceNetAdhocctlScanInfoEmu *buf = NULL; + if (Memory::IsValidAddress(bufAddr)) buf = (SceNetAdhocctlScanInfoEmu *)Memory::GetPointer(bufAddr); + + INFO_LOG(SCENET, "sceNetAdhocctlGetScanInfo([%08x]=%i, %08x)", sizeAddr, buflen ? *buflen : -1, bufAddr); if (!g_Config.bEnableWlan) { return 0; } - int * buflen = (int *)Memory::GetPointer(size); - SceNetAdhocctlScanInfoEmu * buf = NULL; - if (Memory::IsValidAddress(bufAddr)) { - buf = (SceNetAdhocctlScanInfoEmu *)Memory::GetPointer(bufAddr); - } + // Library initialized if (netAdhocctlInited) { - - if (!Memory::IsValidAddress(size)) return ERROR_NET_ADHOCCTL_INVALID_ARG; + // Minimum Argument + if (buflen == NULL) return ERROR_NET_ADHOCCTL_INVALID_ARG; // Minimum Argument Requirements if (buflen != NULL) { @@ -972,7 +1068,7 @@ static u32 sceNetAdhocctlAddHandler(u32 handlerPtr, u32 handlerArg) { static u32 sceNetAdhocctlDisconnect() { // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? - INFO_LOG(SCENET, "sceNetAdhocctlDisconnect() at %08x", currentMIPS->pc); + INFO_LOG(SCENET, "sceNetAdhocctlDisconnect() at %08x [group=%s]", currentMIPS->pc, parameter.group_name.data); /* if (!g_Config.bEnableWlan) { return 0; @@ -1008,26 +1104,27 @@ static u32 sceNetAdhocctlDisconnect() { //_freeNetworkLock(); // Multithreading Lock - peerlock.lock(); + //peerlock.lock(); // Clear Peer List - freeFriendsRecursive(friends); + //freeFriendsRecursive(friends); // Delete Peer Reference - friends = NULL; + //friends = NULL; // Clear Group List - freeGroupsRecursive(networks); + //freeGroupsRecursive(networks); // Delete Group Reference - networks = NULL; + //networks = NULL; // Multithreading Unlock - peerlock.unlock(); + //peerlock.unlock(); } // Notify Event Handlers (even if we weren't connected, not doing this will freeze games like God Eater, which expect this behaviour) - __UpdateAdhocctlHandlers(ADHOCCTL_EVENT_DISCONNECT,0); + //__UpdateAdhocctlHandlers(ADHOCCTL_EVENT_DISCONNECT,0); + CoreTiming::ScheduleEvent_Threadsafe_Immediate(eventAdhocctlHandlerUpdate, join32(ADHOCCTL_EVENT_DISCONNECT, 0)); // Return Success, some games might ignore returned value and always treat it as success, otherwise repeatedly calling this function return 0; @@ -1051,12 +1148,8 @@ static u32 sceNetAdhocctlDelHandler(u32 handlerID) { int sceNetAdhocctlTerm() { // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? INFO_LOG(SCENET, "sceNetAdhocctlTerm()"); - /* - if (!g_Config.bEnableWlan) { - netAdhocctlInited = false; - return 0; - } - */ + + if (netAdhocMatchingInited) sceNetAdhocMatchingTerm(); if (netAdhocctlInited) { netAdhocctlInited = false; @@ -1069,17 +1162,74 @@ int sceNetAdhocctlTerm() { // Free stuff here closesocket(metasocket); metasocket = (int)INVALID_SOCKET; -#ifdef _MSC_VER - WSACleanup(); // Might be better to call WSAStartup/WSACleanup from sceNetInit/sceNetTerm isn't? since it's the first/last network function being used -#endif +/*#ifdef _MSC_VER + WSACleanup(); // Might be better to call WSAStartup/WSACleanup from sceNetInit/sceNetTerm isn't? since it's the first/last network function being used, even better to put it in __NetInit/__NetShutdown as it's only called once +#endif*/ } return 0; } static int sceNetAdhocctlGetNameByAddr(const char *mac, u32 nameAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetNameByAddr(%s, %08x)", mac, nameAddr); - return -1; + DEBUG_LOG(SCENET, "UNTESTED sceNetAdhocctlGetNameByAddr(%s, %08x)", mac, nameAddr); + + // Library initialized + if (netAdhocctlInited) + { + // Valid Arguments + if (mac != NULL && nameAddr != NULL) + { + SceNetAdhocctlNickname * nickname = NULL; + if (Memory::IsValidAddress(nameAddr)) nickname = (SceNetAdhocctlNickname *)Memory::GetPointer(nameAddr); + // Get Local MAC Address + SceNetEtherAddr localmac; getLocalMac(&localmac); + + // Local MAC Matches + if (memcmp(&localmac, mac, sizeof(SceNetEtherAddr)) == 0) + { + // Write Data + *nickname = parameter.nickname; + + // Return Success + return 0; + } + + // Multithreading Lock + peerlock.lock(); + + // Peer Reference + SceNetAdhocctlPeerInfo * peer = friends; + + // Iterate Peers + for (; peer != NULL; peer = peer->next) + { + // Match found + if (memcmp(&peer->mac_addr, mac, sizeof(SceNetEtherAddr)) == 0) + { + // Write Data + *nickname = peer->nickname; + + // Multithreading Unlock + peerlock.unlock(); + + // Return Success + return 0; + } + } + + // Multithreading Unlock + peerlock.unlock(); + + // Player not found + return ERROR_NET_ADHOC_NO_ENTRY; + } + + // Invalid Arguments + return ERROR_NET_ADHOCCTL_INVALID_ARG; + } + + // Library uninitialized + return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; } static int sceNetAdhocctlJoin(u32 scanInfoAddr) { @@ -1089,65 +1239,92 @@ static int sceNetAdhocctlJoin(u32 scanInfoAddr) { } // Library initialized - if (netAdhocctlInited) { + if (netAdhocctlInited) + { + // Valid Argument + if (Memory::IsValidAddress(scanInfoAddr)) + { + SceNetAdhocctlScanInfoEmu * sinfo = (SceNetAdhocctlScanInfoEmu *)Memory::GetPointer(scanInfoAddr); + //while (true) sleep_ms(1); - if (!Memory::IsValidAddress(scanInfoAddr)) return ERROR_NET_ADHOCCTL_INVALID_ARG; - - // Disconnected State - if (threadStatus == ADHOCCTL_STATE_DISCONNECTED) { - - SceNetAdhocctlScanInfo * sinfo = (SceNetAdhocctlScanInfo*)Memory::GetPointer(scanInfoAddr); - - // Prepare Connect Packet - SceNetAdhocctlConnectPacketC2S packet; - - // Clear Packet Memory - memset(&packet, 0, sizeof(packet)); - - // Set Packet Opcode - packet.base.opcode = OPCODE_CONNECT; - - // Set Target Group - if (sinfo != NULL) - packet.group = sinfo->group_name; - - // Acquire Network Lock - - // Send Packet - int iResult = send(metasocket, (const char *)&packet, sizeof(packet), 0); - if (iResult == SOCKET_ERROR) { - ERROR_LOG(SCENET, "Socket error (%i) when sending", errno); - return ERROR_NET_ADHOCCTL_DISCONNECTED; // ERROR_NET_ADHOCCTL_BUSY; - } - - // Free Network Lock - - // Set HUD Connection Status - //setConnectionStatus(1); - - // Wait for Status to be connected to prevent Ford Street Racing from Failed to create game session - if (friendFinderRunning) { - int cnt = 0; - while ((threadStatus != ADHOCCTL_STATE_CONNECTED) && (cnt < 5000)) { - sleep_ms(1); - cnt++; - } - } - - // Return Success - return 0; + // We can ignore minor connection process differences here + return sceNetAdhocctlCreate((const char*)&sinfo->group_name); } - // Connected State - return ERROR_NET_ADHOCCTL_BUSY; // ERROR_NET_ADHOCCTL_BUSY may trigger the game (ie. Ford Street Racing) to call sceNetAdhocctlDisconnect + // Invalid Argument + return ERROR_NET_ADHOCCTL_INVALID_ARG; } + // Uninitialized Library return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; } -static int sceNetAdhocctlGetPeerInfo(const char *mac, int size, u32 peerInfoAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetPeerInfo(%s, %i, %08x)", mac, size, peerInfoAddr); - return -1; +int sceNetAdhocctlGetPeerInfo(const char *mac, int size, u32 peerInfoAddr) { + VERBOSE_LOG(SCENET, "sceNetAdhocctlGetPeerInfo(%s, %i, %08x) at %08x", mac, size, peerInfoAddr, currentMIPS->pc); + if (!g_Config.bEnableWlan) { + return -1; + } + + SceNetEtherAddr * maddr = (SceNetEtherAddr *)mac; + SceNetAdhocctlPeerInfoEmu * buf = NULL; + if (Memory::IsValidAddress(peerInfoAddr)) { + buf = (SceNetAdhocctlPeerInfoEmu *)Memory::GetPointer(peerInfoAddr); + } + // Library initialized + if (netAdhocctlInited) { + if ((size < sizeof(SceNetAdhocctlPeerInfoEmu)) || (buf == NULL)) return ERROR_NET_ADHOCCTL_INVALID_ARG; + + int retval = ERROR_NET_ADHOCCTL_INVALID_ARG; // -1; + + // Local MAC + if (isLocalMAC(maddr)) { + sockaddr_in addr; + SceNetAdhocctlNickname nickname; + + getLocalIp(&addr); + strcpy((char*)nickname.data, g_Config.sNickName.c_str()); + //buf->next = 0; + buf->nickname = nickname; + buf->nickname.data[ADHOCCTL_NICKNAME_LEN - 1] = 0; // last char need to be null-terminated char + buf->mac_addr = *maddr; + buf->ip_addr = addr.sin_addr.s_addr; // 0x11111111; + //buf->padding = 0x1111; //0; + buf->last_recv = CoreTiming::GetGlobalTimeUsScaled(); + + // Success + retval = 0; + } + // Find Peer by MAC + else + { + // Multithreading Lock + peerlock.lock(); + + SceNetAdhocctlPeerInfo * peer = findFriend(maddr); + if (peer != NULL) { + // Fake Receive Time + if (peer->last_recv != 0) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); + + //buf->next = 0; + buf->nickname = peer->nickname; + buf->nickname.data[ADHOCCTL_NICKNAME_LEN - 1] = 0; // last char need to be null-terminated char + buf->mac_addr = *maddr; + buf->ip_addr = peer->ip_addr; // 0x11111111; + //buf->padding = /*0;*/ 0x1111; + buf->last_recv = peer->last_recv; //CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; //(uint64_t)time(NULL); //This timestamp is important issue on Dissidia 012 + + // Success + retval = 0; + } + + // Multithreading Unlock + peerlock.unlock(); + } + return retval; + } + + // Library uninitialized + return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; } /** @@ -1192,7 +1369,12 @@ int sceNetAdhocctlCreate(const char *groupName) { int iResult = send(metasocket, (const char *)&packet, sizeof(packet), 0); if (iResult == SOCKET_ERROR) { ERROR_LOG(SCENET, "Socket error (%i) when sending", errno); - return ERROR_NET_ADHOCCTL_DISCONNECTED; // ERROR_NET_ADHOCCTL_BUSY; + //return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; // ERROR_NET_ADHOCCTL_DISCONNECTED; // ERROR_NET_ADHOCCTL_BUSY; + //Faking success, to prevent Full Auto 2 from freezing while Initializing Network + threadStatus = ADHOCCTL_STATE_CONNECTED; + // Notify Event Handlers, Needed for the Nickname to be shown on the screen when success is faked + // Might be better not to notify the game when faking success (failed to connect to adhoc server), at least the player will know that it failed to connect + //__UpdateAdhocctlHandlers(ADHOCCTL_EVENT_CONNECT, 0); //CoreTiming::ScheduleEvent_Threadsafe_Immediate(eventAdhocctlHandlerUpdate, join32(ADHOCCTL_EVENT_CONNECT, 0)); } // Free Network Lock @@ -1228,9 +1410,9 @@ static int sceNetAdhocctlConnect(u32 ptrToGroupName) { if (Memory::IsValidAddress(ptrToGroupName)) { INFO_LOG(SCENET, "sceNetAdhocctlConnect(groupName=%s) at %08x", Memory::GetCharPointer(ptrToGroupName), currentMIPS->pc); return sceNetAdhocctlCreate(Memory::GetCharPointer(ptrToGroupName)); - } else { - return ERROR_NET_ADHOC_INVALID_ADDR; // shouldn't this be ERROR_NET_ADHOC_INVALID_ARG ? - } + } + + return ERROR_NET_ADHOC_INVALID_ARG; // ERROR_NET_ADHOC_INVALID_ADDR; } static int sceNetAdhocctlCreateEnterGameMode(const char *groupName, int unknown, int playerNum, u32 macsAddr, int timeout, int unknown2) { @@ -1243,18 +1425,38 @@ static int sceNetAdhocctlJoinEnterGameMode(const char *groupName, const char *ma return -1; } +/** +* Create and Join a GameMode Network as Host (with Minimum Peer Check) +* @param group_name Virtual Network Name +* @param game_type Network Type (1A, 1B, 2A) +* @param min_members Minimum Number of Peers +* @param num_members Total Number of Peers (including Host) +* @param members MAC Address List of Peers (own MAC at Index 0) +* @param timeout Timeout Value (in Microseconds) +* @param flag Unused Bitflags +* @return 0 on success or... ADHOCCTL_NOT_INITIALIZED, ADHOCCTL_INVALID_ARG, ADHOCCTL_BUSY, ADHOCCTL_CHANNEL_NOT_AVAILABLE +*/ +int sceNetAdhocctlCreateEnterGameModeMin(const char *group_name, int game_type, int min_members, int num_members, u32 membersAddr, u32 timeout, int flag) +{ + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlCreateEnterGameModeMin(%s, %i, %i, %i, %08x, %d, %i) at %08x", group_name, game_type, min_members, num_members, membersAddr, timeout, flag, currentMIPS->pc); + // We don't really need the Minimum User Check + return sceNetAdhocctlCreateEnterGameMode(group_name, game_type, num_members, membersAddr, timeout, flag); +} + int sceNetAdhocTerm() { INFO_LOG(SCENET, "sceNetAdhocTerm()"); // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup all the sockets right? - /* - if (!g_Config.bEnableWlan) { - netAdhocInited = false; - return 0; - } - */ + + if (netAdhocctlInited) sceNetAdhocctlTerm(); // Library is initialized if (netAdhocInited) { + // Delete fake PSP Thread + if (threadAdhocID != 0) { + __KernelStopThread(threadAdhocID, SCE_KERNEL_ERROR_THREAD_TERMINATED, "AdhocThread stopped"); + __KernelDeleteThread(threadAdhocID, SCE_KERNEL_ERROR_THREAD_TERMINATED, "AdhocThread deleted"); + } + // Delete PDP Sockets deleteAllPDP(); @@ -1262,11 +1464,19 @@ int sceNetAdhocTerm() { deleteAllPTP(); // Delete Gamemode Buffer - //_deleteAllGMB(); + //deleteAllGMB(); // Terminate Internet Library //sceNetInetTerm(); + //Kill AdhocServer Thread + if (adhocServerRunning) { + adhocServerRunning = false; + if (adhocServerThread.joinable()) { + adhocServerThread.join(); + } + } + // Unload Internet Modules (Just keep it in memory... unloading crashes?!) // if (_manage_modules != 0) sceUtilityUnloadModule(PSP_MODULE_NET_INET); // Library shutdown @@ -1278,9 +1488,77 @@ int sceNetAdhocTerm() { } } -static int sceNetAdhocGetPdpStat(int structSize, u32 structAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocGetPdpStat(%i, %08x)", structSize, structAddr); - return 0; +static int sceNetAdhocGetPdpStat(u32 structSize, u32 structAddr) { + VERBOSE_LOG(SCENET, "UNTESTED sceNetAdhocGetPdpStat(%08x, %08x) at %08x", structSize, structAddr, currentMIPS->pc); + + // Library is initialized + if (netAdhocInited) + { + s32_le *buflen = NULL; + if (Memory::IsValidAddress(structSize)) buflen = (s32_le *)Memory::GetPointer(structSize); + SceNetAdhocPdpStat *buf = NULL; + if (Memory::IsValidAddress(structAddr)) buf = (SceNetAdhocPdpStat *)Memory::GetPointer(structAddr); + + // Length Returner Mode + if (buflen != NULL && buf == NULL) + { + // Return Required Size + *buflen = sizeof(SceNetAdhocPdpStat) * getPDPSocketCount(); + + // Success + return 0; + } + + // Status Returner Mode + else if (buflen != NULL && buf != NULL) + { + // Socket Count + int socketcount = getPDPSocketCount(); + + // Figure out how many Sockets we will return + int count = *buflen / sizeof(SceNetAdhocPdpStat); + if (count > socketcount) count = socketcount; + + // Copy Counter + int i = 0; + + // Iterate Translation Table + int j = 0; for (; j < 255 && i < count; j++) + { + // Valid Socket Entry + if (pdp[j] != NULL) + { + // Copy Socket Data from Internal Memory + buf[i] = *pdp[j]; + + // Fix Client View Socket ID + buf[i].id = j + 1; + + // Write End of List Reference + buf[i].next = 0; + + // Link Previous Element + if (i > 0) + buf[i - 1].next = structAddr + ((i - 1) * sizeof(SceNetAdhocPdpStat)) + sizeof(SceNetAdhocPdpStat); //buf[i - 1].next = &buf[i]; + + // Increment Counter + i++; + } + } + + // Update Buffer Length + *buflen = i * sizeof(SceNetAdhocPdpStat); + + // Success + return 0; + } + + // Invalid Arguments + return ERROR_NET_ADHOC_INVALID_ARG; + } + + // Library is uninitialized + return ERROR_NET_ADHOC_NOT_INITIALIZED; } @@ -1292,17 +1570,17 @@ static int sceNetAdhocGetPdpStat(int structSize, u32 structAddr) { */ static int sceNetAdhocGetPtpStat(u32 structSize, u32 structAddr) { // Spams a lot - VERBOSE_LOG(SCENET,"sceNetAdhocGetPtpStat(%u,%u)",structSize,structAddr); + VERBOSE_LOG(SCENET,"sceNetAdhocGetPtpStat(%08x, %08x) at %08x",structSize,structAddr,currentMIPS->pc); - if (!g_Config.bEnableWlan) { - return 0; - } + s32_le *buflen = NULL; + if (Memory::IsValidAddress(structSize)) buflen = (s32_le *)Memory::GetPointer(structSize); + SceNetAdhocPtpStat *buf = NULL; + if (Memory::IsValidAddress(structAddr)) buf = (SceNetAdhocPtpStat *)Memory::GetPointer(structAddr); - int * buflen = (int *)Memory::GetPointer(structSize); // Library is initialized if (netAdhocInited) { // Length Returner Mode - if (buflen != NULL && !Memory::IsValidAddress(structAddr)) { + if (buflen != NULL && buf == NULL) { // Return Required Size *buflen = sizeof(SceNetAdhocPtpStat) * getPTPSocketCount(); @@ -1311,10 +1589,9 @@ static int sceNetAdhocGetPtpStat(u32 structSize, u32 structAddr) { } // Status Returner Mode - else if (buflen != NULL && Memory::IsValidAddress(structAddr)) { + else if (buflen != NULL && buf != NULL) { // Socket Count int socketcount = getPTPSocketCount(); - SceNetAdhocPtpStat * buf = (SceNetAdhocPtpStat *)Memory::GetPointer(structAddr); // Figure out how many Sockets we will return int count = *buflen / sizeof(SceNetAdhocPtpStat); @@ -1338,7 +1615,7 @@ static int sceNetAdhocGetPtpStat(u32 structSize, u32 structAddr) { // Link previous Element to this one if (i > 0) - buf[i-1].next = structAddr + (i*sizeof(SceNetAdhocPtpStat)) + sizeof(SceNetAdhocPtpStat); + buf[i - 1].next = structAddr + ((i - 1) * sizeof(SceNetAdhocPtpStat)) + sizeof(SceNetAdhocPtpStat); // Increment Counter i++; @@ -1374,7 +1651,7 @@ static int sceNetAdhocGetPtpStat(u32 structSize, u32 structAddr) { * @return Socket ID > 0 on success or... ADHOC_NOT_INITIALIZED, ADHOC_INVALID_ARG, ADHOC_INVALID_ADDR, ADHOC_INVALID_PORT */ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac, int dport, int bufsize, int rexmt_int, int rexmt_cnt, int unknown) { - DEBUG_LOG(SCENET, "sceNetAdhocPtpOpen(%s,%d,%s,%d,%d,%d,%d,%d)", srcmac, sport, dstmac,dport,bufsize, rexmt_int, rexmt_cnt, unknown); + INFO_LOG(SCENET, "sceNetAdhocPtpOpen(%s,%d,%s,%d,%d,%d,%d,%d)", srcmac, sport, dstmac,dport,bufsize, rexmt_int, rexmt_cnt, unknown); if (!g_Config.bEnableWlan) { return 0; } @@ -1402,6 +1679,10 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac, // Valid Socket produced if (tcpsocket > 0) { + // Change socket buffer size when necessary + if (getSockBufferSize(tcpsocket, SO_SNDBUF) < bufsize) setSockBufferSize(tcpsocket, SO_SNDBUF, bufsize); + if (getSockBufferSize(tcpsocket, SO_RCVBUF) < bufsize) setSockBufferSize(tcpsocket, SO_RCVBUF, bufsize); + // Enable Port Re-use setsockopt(tcpsocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one)); @@ -1500,7 +1781,8 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int if (Memory::IsValidAddress(peerPortPtr)) { port = (uint16_t *)Memory::GetPointer(peerPortPtr); } - DEBUG_LOG(SCENET, "sceNetAdhocPtpAccept(%d,%08x,[%08x]=%u,%d,%u)", id, peerMacAddrPtr, peerPortPtr, port ? *port : -1, timeout, flag); + + DEBUG_LOG(SCENET, "sceNetAdhocPtpAccept(%d,%08x,[%08x]=%u,%d,%u) at %08x", id, peerMacAddrPtr, peerPortPtr, port ? *port : -1, timeout, flag, currentMIPS->pc); if (!g_Config.bEnableWlan) { return 0; } @@ -1513,9 +1795,9 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int SceNetAdhocPtpStat * socket = ptp[id - 1]; // Listener Socket - if (socket->state == PTP_STATE_LISTEN) { + if (socket->state == ADHOC_PTP_STATE_LISTEN) { // Valid Arguments - if (addr != NULL && port != NULL) { + if (addr != NULL /*&& port != NULL*/) { //GTA:VCS seems to use 0 for the portPtr // Address Information sockaddr_in peeraddr; memset(&peeraddr, 0, sizeof(peeraddr)); @@ -1539,10 +1821,10 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int // Blocking Behaviour if (!flag && newsocket == -1) { // Get Start Time - uint32_t starttime = (uint32_t)(real_time_now()*1000.0); + uint32_t starttime = (uint32_t)(real_time_now()*1000000.0); // Retry until Timeout hits - while ((timeout == 0 ||((uint32_t)(real_time_now()*1000.0) - starttime) < (uint32_t)timeout) && newsocket == -1) { + while ((timeout == 0 ||((uint32_t)(real_time_now()*1000000.0) - starttime) < (uint32_t)timeout) && newsocket == -1) { // Accept Connection newsocket = accept(socket->id, (sockaddr *)&peeraddr, &peeraddrlen); @@ -1550,6 +1832,11 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int sleep_ms(1); } } + + if (newsocket == SOCKET_ERROR) { + int error = errno; + DEBUG_LOG(SCENET, "sceNetAdhocPtpAccept[%i]: Socket Error (%i)", id, error); + } // Restore Blocking Behaviour if (nbio == 0) { @@ -1559,6 +1846,8 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int // Accepted New Connection if (newsocket > 0) { + // Do we need to Change socket buffer size to match the listener buffer size? + // Enable Port Re-use setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one)); @@ -1584,6 +1873,12 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int // Copy Socket Descriptor to Structure internal->id = newsocket; + + // Set Buffer Size + if (getSockBufferSize(newsocket, SO_RCVBUF) < socket->rcv_sb_cc) setSockBufferSize(newsocket, SO_RCVBUF, socket->rcv_sb_cc); + if (getSockBufferSize(newsocket, SO_SNDBUF) < socket->snd_sb_cc) setSockBufferSize(newsocket, SO_SNDBUF, socket->snd_sb_cc); + internal->rcv_sb_cc = socket->rcv_sb_cc; + internal->snd_sb_cc = socket->snd_sb_cc; // Copy Local Address Data to Structure getLocalMac(&internal->laddr); @@ -1594,17 +1889,20 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int internal->pport = ntohs(peeraddr.sin_port); // Set Connected State - internal->state = PTP_STATE_ESTABLISHED; + internal->state = ADHOC_PTP_STATE_ESTABLISHED; // Return Peer Address Information *addr = internal->paddr; - *port = internal->pport; + if (port != NULL) *port = internal->pport; // Link PTP Socket ptp[i] = internal; // Add Port Forward to Router // sceNetPortOpen("TCP", internal->lport); + + uint8_t * pip = (uint8_t *)&peeraddr.sin_addr.s_addr; + INFO_LOG(SCENET, "sceNetAdhocPtpAccept[%i->%i:%u]: Established (%u.%u.%u.%u:%u)", id, i+1, internal->lport, pip[0], pip[1], pip[2], pip[3], internal->pport); // Return Socket return i + 1; @@ -1618,6 +1916,8 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int // Close Socket closesocket(newsocket); + + ERROR_LOG(SCENET, "sceNetAdhocPtpAccept[%i]: Failed (Socket Closed)", id); } // Action would block @@ -1652,7 +1952,7 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int * @return 0 on success or... ADHOC_NOT_INITIALIZED, ADHOC_INVALID_ARG, ADHOC_INVALID_SOCKET_ID, ADHOC_SOCKET_DELETED, ADHOC_CONNECTION_REFUSED, ADHOC_SOCKET_ALERTED, ADHOC_WOULD_BLOCK, ADHOC_TIMEOUT, ADHOC_NOT_OPENED, ADHOC_THREAD_ABORTED, NET_INTERNAL */ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { - DEBUG_LOG(SCENET, "sceNetAdhocPtpConnect(%i, %i, %08x)", id, timeout, flag); + INFO_LOG(SCENET, "sceNetAdhocPtpConnect(%i, %i, %08x) at %08x", id, timeout, flag, currentMIPS->pc); if (!g_Config.bEnableWlan) { return 0; } @@ -1691,6 +1991,10 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { // Grab Error Code int errorcode = errno; + + if (connectresult == SOCKET_ERROR) { + ERROR_LOG(SCENET, "sceNetAdhocPtpConnect[%i]: Socket Error (%i)", id, errorcode); + } // Restore Blocking Behaviour if (nbio == 0) { @@ -1699,9 +2003,9 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { } // Instant Connection (Lucky!) - if (connectresult == 0 || (connectresult == -1 && errorcode == EISCONN)) { + if (connectresult == 0 || (connectresult == -1 && (errorcode == EISCONN /*|| errorcode == EALREADY)*/))) { // Set Connected State - socket->state = PTP_STATE_ESTABLISHED; + socket->state = ADHOC_PTP_STATE_ESTABLISHED; // Success return 0; @@ -1715,14 +2019,14 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { // Blocking Mode else { // Grab Connection Start Time - uint32_t starttime = (uint32_t)(real_time_now()*1000.0); + uint32_t starttime = (uint32_t)(real_time_now()*1000000.0); // Peer Information (for Connection-Polling) sockaddr_in peer; memset(&peer, 0, sizeof(peer)); socklen_t peerlen = sizeof(peer); // Wait for Connection - while ((timeout == 0 || ( (uint32_t)(real_time_now()*1000.0) - starttime) < (uint32_t)timeout) && getpeername(socket->id, (sockaddr *)&peer, &peerlen) != 0) { + while ((timeout == 0 || ( (uint32_t)(real_time_now()*1000000.0) - starttime) < (uint32_t)timeout) && getpeername(socket->id, (sockaddr *)&peer, &peerlen) != 0) { // Wait 1ms sleep_ms(1); } @@ -1730,7 +2034,10 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { // Connected in Time if (sin.sin_addr.s_addr == peer.sin_addr.s_addr/* && sin.sin_port == peer.sin_port*/) { // Set Connected State - socket->state = PTP_STATE_ESTABLISHED; + socket->state = ADHOC_PTP_STATE_ESTABLISHED; + + uint8_t * pip = (uint8_t *)&peer.sin_addr.s_addr; + INFO_LOG(SCENET, "sceNetAdhocPtpConnect[%i:%u]: Established (%u.%u.%u.%u:%u)", id, socket->lport, pip[0], pip[1], pip[2], pip[3], socket->pport); // Success return 0; @@ -1766,7 +2073,7 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) { * @return 0 on success or... ADHOC_NOT_INITIALIZED, ADHOC_INVALID_ARG, ADHOC_INVALID_SOCKET_ID, ADHOC_SOCKET_DELETED */ static int sceNetAdhocPtpClose(int id, int unknown) { - DEBUG_LOG(SCENET,"sceNetAdhocPtpClose(%d,%d)",id,unknown); + INFO_LOG(SCENET,"sceNetAdhocPtpClose(%d,%d) at %08x",id,unknown,currentMIPS->pc); if (!g_Config.bEnableWlan) { return 0; } @@ -1814,7 +2121,7 @@ static int sceNetAdhocPtpClose(int id, int unknown) { * @return Socket ID > 0 on success or... ADHOC_NOT_INITIALIZED, ADHOC_INVALID_ARG, ADHOC_INVALID_ADDR, ADHOC_INVALID_PORT, ADHOC_SOCKET_ID_NOT_AVAIL, ADHOC_PORT_NOT_AVAIL, ADHOC_PORT_IN_USE, NET_NO_SPACE */ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int rexmt_int, int rexmt_cnt, int backlog, int unk) { - DEBUG_LOG(SCENET, "sceNetAdhocPtpListen(%p,%d,%d,%d,%d,%d,%d)",srcmac,sport,bufsize,rexmt_int,rexmt_cnt,backlog,unk); + INFO_LOG(SCENET, "sceNetAdhocPtpListen(%s,%d,%d,%d,%d,%d,%d)",srcmac,sport,bufsize,rexmt_int,rexmt_cnt,backlog,unk); if (!g_Config.bEnableWlan) { return 0; } @@ -1844,6 +2151,10 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int // Valid Socket produced if (tcpsocket > 0) { + // Change socket buffer size when necessary + if (getSockBufferSize(tcpsocket, SO_SNDBUF) < bufsize) setSockBufferSize(tcpsocket, SO_SNDBUF, bufsize); + if (getSockBufferSize(tcpsocket, SO_RCVBUF) < bufsize) setSockBufferSize(tcpsocket, SO_RCVBUF, bufsize); + // Enable Port Re-use setsockopt(tcpsocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one)); @@ -1853,10 +2164,11 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(sport); + int iResult = 0; // Bound Socket to local Port - if (bind(tcpsocket, (sockaddr *)&addr, sizeof(addr)) == 0) { + if ((iResult = bind(tcpsocket, (sockaddr *)&addr, sizeof(addr))) == 0) { // Switch into Listening Mode - if (listen(tcpsocket, backlog) == 0) { + if ((iResult = listen(tcpsocket, backlog)) == 0) { // Allocate Memory SceNetAdhocPtpStat * internal = (SceNetAdhocPtpStat *)malloc(sizeof(SceNetAdhocPtpStat)); @@ -1878,7 +2190,7 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int internal->lport = sport; // Flag Socket as Listener - internal->state = PTP_STATE_LISTEN; + internal->state = ADHOC_PTP_STATE_LISTEN; // Set Buffer Size internal->rcv_sb_cc = bufsize; @@ -1899,8 +2211,16 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int } } + if (iResult == SOCKET_ERROR) { + int error = errno; + ERROR_LOG(SCENET, "sceNetAdhocPtpListen[%i]: Socket Error (%i)", sport, error); + } + // Close Socket closesocket(tcpsocket); + + // Port not available (exclusively in use?) + return ERROR_NET_ADHOC_PORT_NOT_AVAIL; } // Socket not available @@ -1933,7 +2253,7 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int * @return 0 on success or... ADHOC_NOT_INITIALIZED, ADHOC_INVALID_ARG, ADHOC_INVALID_SOCKET_ID, ADHOC_SOCKET_DELETED, ADHOC_SOCKET_ALERTED, ADHOC_WOULD_BLOCK, ADHOC_TIMEOUT, ADHOC_NOT_CONNECTED, ADHOC_THREAD_ABORTED, ADHOC_INVALID_DATALEN, ADHOC_DISCONNECTED, NET_INTERNAL, NET_NO_SPACE */ static int sceNetAdhocPtpSend(int id, u32 dataAddr, u32 dataSizeAddr, int timeout, int flag) { - DEBUG_LOG(SCENET, "sceNetAdhocPtpSend(%d,%08x,%08x,%d,%d)", id, dataAddr, dataSizeAddr, timeout, flag); + DEBUG_LOG(SCENET, "sceNetAdhocPtpSend(%d,%08x,%08x,%d,%d) at %08x", id, dataAddr, dataSizeAddr, timeout, flag, currentMIPS->pc); if (!g_Config.bEnableWlan) { return 0; } @@ -1947,7 +2267,7 @@ static int sceNetAdhocPtpSend(int id, u32 dataAddr, u32 dataSizeAddr, int timeou SceNetAdhocPtpStat * socket = ptp[id - 1]; // Connected Socket - if (socket->state == PTP_STATE_ESTABLISHED) { + if (socket->state == ADHOC_PTP_STATE_ESTABLISHED) { // Valid Arguments if (data != NULL && len != NULL && *len > 0) { // Schedule Timeout Removal @@ -1972,6 +2292,9 @@ static int sceNetAdhocPtpSend(int id, u32 dataAddr, u32 dataSizeAddr, int timeou if (sent > 0) { // Save Length *len = sent; + + uint8_t * smac = (uint8_t *)&socket->paddr; + INFO_LOG(SCENET, "sceNetAdhocPtpSend[%i:%u]: Sent %u bytes to %02X:%02X:%02X:%02X:%02X:%02X:%u", id, socket->lport, sent, smac[0], smac[1], smac[2], smac[3], smac[4], smac[5], socket->pport); // Return Success return 0; @@ -1987,7 +2310,7 @@ static int sceNetAdhocPtpSend(int id, u32 dataAddr, u32 dataSizeAddr, int timeou } // Change Socket State - socket->state = PTP_STATE_CLOSED; + socket->state = ADHOC_PTP_STATE_CLOSED; // Disconnected return ERROR_NET_ADHOC_DISCONNECTED; @@ -2029,7 +2352,7 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou // Library is initialized if (netAdhocInited) { // Valid Socket - if (id > 0 && id <= 255 && ptp[id - 1] != NULL && ptp[id - 1]->state == PTP_STATE_ESTABLISHED) { + if (id > 0 && id <= 255 && ptp[id - 1] != NULL && ptp[id - 1]->state == ADHOC_PTP_STATE_ESTABLISHED) { // Cast Socket SceNetAdhocPtpStat * socket = ptp[id - 1]; @@ -2057,6 +2380,9 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou if (received > 0) { // Save Length *len = received; + + uint8_t * smac = (uint8_t *)&socket->paddr; + INFO_LOG(SCENET, "sceNetAdhocPtpRecv[%i:%u]: Received %u bytes from %02X:%02X:%02X:%02X:%02X:%02X:%u", id, socket->lport, received, smac[0], smac[1], smac[2], smac[3], smac[4], smac[5], socket->pport); // Return Success return 0; @@ -2072,7 +2398,7 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou } // Change Socket State - socket->state = PTP_STATE_CLOSED; + socket->state = ADHOC_PTP_STATE_CLOSED; // Disconnected return ERROR_NET_ADHOC_DISCONNECTED; @@ -2098,7 +2424,7 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou * @return 0 on success or... ADHOC_NOT_INITIALIZED, ADHOC_INVALID_ARG, ADHOC_INVALID_SOCKET_ID, ADHOC_SOCKET_DELETED, ADHOC_SOCKET_ALERTED, ADHOC_WOULD_BLOCK, ADHOC_TIMEOUT, ADHOC_THREAD_ABORTED, ADHOC_DISCONNECTED, ADHOC_NOT_CONNECTED, NET_INTERNAL */ static int sceNetAdhocPtpFlush(int id, int timeout, int nonblock) { - DEBUG_LOG(SCENET,"sceNetAdhocPtpFlush(%d,%d,%d)", id, timeout, nonblock); + DEBUG_LOG(SCENET,"sceNetAdhocPtpFlush(%d,%d,%d) at %08x", id, timeout, nonblock, currentMIPS->pc); if (!g_Config.bEnableWlan) { return 0; } @@ -2148,51 +2474,169 @@ static int sceNetAdhocGameModeDeleteReplica(int id) { return -1; } -static int sceNetAdhocGetSocketAlert() { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocGetSocketAlert()"); +int sceNetAdhocGetSocketAlert(int id, u32 flagPtr) { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocGetSocketAlert(%i, %08x)", id, flagPtr); + + // Dummy Value + if (Memory::IsValidAddress(flagPtr)) { + s32_le * flag = (s32_le*)Memory::GetPointer(flagPtr); + *flag = 0; + } + + // Dummy Result return 0; } -static int sceNetAdhocMatchingInit(u32 memsize) { - INFO_LOG(SCENET, "sceNetAdhocMatchingInit(%d) at %08x", memsize, currentMIPS->pc); - // Uninitialized Library - if (!netAdhocMatchingInited) { - // Save Fake Pool Size - fakePoolSize = memsize; +int sceNetAdhocMatchingStop(int matchingId) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingStop(%i) at %08x", matchingId, currentMIPS->pc); + //if (!g_Config.bEnableWlan) + // return -1; - // Initialize Library - netAdhocMatchingInited = true; + SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); + + if (item != NULL) { + item->inputRunning = false; + if (item->inputThread.joinable()) { + item->inputThread.join(); + } + + item->eventRunning = false; + if (item->eventThread.joinable()) { + item->eventThread.join(); + } + + // Stop fake PSP Thread + //__KernelStopThread(item->matching_thid, SCE_KERNEL_ERROR_THREAD_TERMINATED, "AdhocMatching stopped"); + //item->matchingThread->Terminate(); + + // Multithreading Lock + peerlock.lock(); + + // Remove your own MAC, or All memebers, or don't remove at all or we should do this on MatchingDelete ? + clearPeerList(item); //deleteAllMembers(item); + + item->running = 0; + netAdhocMatchingStarted--; + + // Multithreading Unlock + peerlock.unlock(); - // Return Success - return 0; - } else { - return ERROR_NET_ADHOC_MATCHING_ALREADY_INITIALIZED; } + + return 0; +} + +int sceNetAdhocMatchingDelete(int matchingId) { + // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? + + // Previous Context Reference + SceNetAdhocMatchingContext * prev = NULL; + + // Multithreading Lock + peerlock.lock(); //contextlock.lock(); + + // Context Pointer + SceNetAdhocMatchingContext * item = contexts; + + // Iterate contexts + for (; item != NULL; item = item->next) { + // Found matching ID + if (item->id == matchingId) { + // Unlink Left (Beginning) + if (prev == NULL) contexts = item->next; + + // Unlink Left (Other) + else prev->next = item->next; + + // Stop it first if it's still running + if (item->running) { + sceNetAdhocMatchingStop(matchingId); + } + // Delete the Fake PSP Thread + //__KernelDeleteThread(item->matching_thid, SCE_KERNEL_ERROR_THREAD_TERMINATED, "AdhocMatching deleted"); + //delete item->matchingThread; + // Make sure nobody locking/using the socket + item->socketlock->lock(); + // Delete the socket + sceNetAdhocPdpDelete(item->socket, 0); // item->connected = (sceNetAdhocPdpDelete(item->socket, 0) < 0); + item->socketlock->unlock(); + // Free allocated memories + free(item->hello); + free(item->rxbuf); + clearPeerList(item); //deleteAllMembers(item); + // Destroy locks + item->eventlock->lock(); // Make sure it's not locked when being deleted + item->eventlock->unlock(); + delete item->eventlock; + item->inputlock->lock(); // Make sure it's not locked when being deleted + item->inputlock->unlock(); + delete item->inputlock; + item->socketlock->lock(); // Make sure it's not locked when being deleted + item->socketlock->unlock(); + delete item->socketlock; + // Free item context memory + free(item); + item = NULL; + + // Stop Search + break; + } + + // Set Previous Reference + prev = item; + } + + // Multithreading Unlock + peerlock.unlock(); //contextlock.unlock(); + + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingDelete(%i) at %08x", matchingId, currentMIPS->pc); + return 0; +} + +int sceNetAdhocMatchingInit(u32 memsize) { + WARN_LOG(SCENET, "sceNetAdhocMatchingInit(%d) at %08x", memsize, currentMIPS->pc); + + // Uninitialized Library + if (netAdhocMatchingInited) return ERROR_NET_ADHOC_MATCHING_ALREADY_INITIALIZED; + + // Save Fake Pool Size + fakePoolSize = memsize; + + // Initialize Library + netAdhocMatchingInited = true; + + // Return Success + return 0; } int sceNetAdhocMatchingTerm() { // Should we cleanup all created matching contexts first? just in case there are games that doesn't delete them before calling this - /* if (netAdhocMatchingInited) { - // Should we also delete all PDP? since creating a matching context will also create a PDP socket - + // Delete all Matching contexts + SceNetAdhocMatchingContext * next = NULL; + SceNetAdhocMatchingContext * context = contexts; + while (context != NULL) { + next = context->next; + if (context->running) sceNetAdhocMatchingStop(context->id); + sceNetAdhocMatchingDelete(context->id); + context = next; + } } - */ - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingTerm()"); + + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingTerm()"); netAdhocMatchingInited = false; return 0; } - // Presumably returns a "matchingId". static int sceNetAdhocMatchingCreate(int mode, int maxnum, int port, int rxbuflen, int hello_int, int keepalive_int, int init_count, int rexmt_int, u32 callbackAddr) { - INFO_LOG(SCENET, "sceNetAdhocMatchingCreate(mode=%i, maxnum=%i, port=%i, rxbuflen=%i, hello=%i, keepalive=%i, initcount=%i, rexmt=%i, callbackAddr=%08x) at %08x", mode, maxnum, port, rxbuflen, hello_int, keepalive_int, init_count, rexmt_int, callbackAddr, currentMIPS->pc); + WARN_LOG(SCENET, "sceNetAdhocMatchingCreate(mode=%i, maxnum=%i, port=%i, rxbuflen=%i, hello=%i, keepalive=%i, initcount=%i, rexmt=%i, callbackAddr=%08x) at %08x", mode, maxnum, port, rxbuflen, hello_int, keepalive_int, init_count, rexmt_int, callbackAddr, currentMIPS->pc); if (!g_Config.bEnableWlan) { return -1; } - + SceNetAdhocMatchingHandler handler; handler.entryPoint = callbackAddr; @@ -2239,20 +2683,33 @@ static int sceNetAdhocMatchingCreate(int mode, int maxnum, int port, int rxbufle context->port = port; context->socket = socket; context->rxbuflen = rxbuflen; - context->hello_int = hello_int; - context->keepalive_int = 500000; - //context->keepalive_int = keepalive_int; context->resendcounter = init_count; - context->keepalivecounter = 100; - //context->keepalivecounter = init_count; - context->resend_int = rexmt_int; + context->resend_int = rexmt_int; // used as ack timeout on lost packet (ie. not receiving anything after sending)? + context->hello_int = hello_int; // client might set this to 0 + if (keepalive_int < 1) context->keepalive_int = PSP_ADHOCCTL_PING_TIMEOUT; else context->keepalive_int = keepalive_int; // client might set this to 0 + context->keepalivecounter = init_count; // used to multiply keepalive_int as timeout + context->timeout = (keepalive_int * init_count); + if (context->timeout < 5000000) context->timeout = 5000000; // For internet play we need higher timeout than what the game wanted context->handler = handler; // Fill in Selfpeer context->mac = localmac; + // Create locks + context->socketlock = new recursive_mutex; + context->eventlock = new recursive_mutex; + context->inputlock = new recursive_mutex; + + // Create fake thread + //#define PSP_THREAD_ATTR_KERNEL 0x00001000 // PSP_THREAD_ATTR_KERNEL is located in sceKernelThread.cpp instead of sceKernelThread.h :( + //context->matching_thid = __KernelCreateThreadInternal("AdhocMatching", 0, idleThreadHackAddr, 0x7f, 4096, PSP_THREAD_ATTR_KERNEL); + //context->matchingThread = new HLEHelperThread("AdhocMatching", "AdhocMatchingMod", "AdhocMatchingFunc", 0x7f, 4096); //8192 + // Multithreading Lock peerlock.lock(); //contextlock.lock(); + + // Add Callback Handler + context->handler.entryPoint = callbackAddr; // Link Context //context->connected = true; @@ -2298,131 +2755,330 @@ static int sceNetAdhocMatchingCreate(int mode, int maxnum, int port, int rxbufle // TODO: Should we execute the callback used to create the Matching Id if it's a valid address? static int sceNetAdhocMatchingStart(int matchingId, int evthPri, int evthStack, int inthPri, int inthStack, int optLen, u32 optDataAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingStart(%i, %i, %i, %i, %i, %i, %08x) at %08x", matchingId, evthPri, evthStack, inthPri, inthStack, optLen, optDataAddr, currentMIPS->pc); + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingStart(%i, %i, %i, %i, %i, %i, %08x) at %08x", matchingId, evthPri, evthStack, inthPri, inthStack, optLen, optDataAddr, currentMIPS->pc); if (!g_Config.bEnableWlan) return -1; + // Multithreading Lock + peerlock.lock(); + SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); + if (item != NULL) { - sceNetAdhocMatchingSetHelloOpt(matchingId, optLen, optDataAddr); + //sceNetAdhocMatchingSetHelloOpt(matchingId, optLen, optDataAddr); //SetHelloOpt only works when context is running if ((optLen > 0) && Memory::IsValidAddress(optDataAddr)) { // Allocate the memory and copy the content if (item->hello != NULL) free(item->hello); - item->hello = malloc(optLen); - if (item->hello != NULL) + item->hello = (uint8_t *)malloc(optLen); + if (item->hello != NULL) { Memory::Memcpy(item->hello, optDataAddr, optLen); + item->hellolen = optLen; + item->helloAddr = optDataAddr; + } + //else return ERROR_NET_ADHOC_MATCHING_NO_SPACE; //Faking success to prevent GTA:VCS from stuck unable to choose host/join menu } - //else return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; // ERROR_NET_ADHOC_MATCHING_INVALID_OPTLEN; // Returning Not Success will cause GTA:VC unable to host/join + //else return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; // ERROR_NET_ADHOC_MATCHING_INVALID_OPTLEN; // Returning Not Success will cause GTA:VC stuck unable to choose host/join menu - //Add your own MAC as a member (ony if it's empty?) - addMember(item, &item->mac); - - //TODO: Create a new thread - // Easier to implement if using an existing thread (friendFinder) instead of creating a new one ^_^ - - //sceKernelCreateThread - /*eventHandlerUpdate = CoreTiming::RegisterEvent("HandlerUpdateEvent", __handlerUpdateCallback); - memberFinderRunning = true; - memberFinderThread = std::thread(memberFinder);*/ - } - - return 0; -} - -static int sceNetAdhocMatchingStop(int matchingId) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingStop(%i)", matchingId); - if (!g_Config.bEnableWlan) - return -1; - - SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); - if (item != NULL) { - /*memberFinderRunning = false; - if (memberFinderThread.joinable()) { - friendFinderThread.join(); + //Add your own MAC as a member (only if it's empty?) + /*SceNetAdhocMatchingMemberInternal * peer = addMember(item, &item->mac); + switch (item->mode) { + case PSP_ADHOC_MATCHING_MODE_PARENT: + peer->state = PSP_ADHOC_MATCHING_PEER_OFFER; + break; + case PSP_ADHOC_MATCHING_MODE_CHILD: + peer->state = PSP_ADHOC_MATCHING_PEER_CHILD; + break; + case PSP_ADHOC_MATCHING_MODE_P2P: + peer->state = PSP_ADHOC_MATCHING_PEER_P2P; }*/ - // Remove your own MAC, or All memebers, or don't remove at all or we should do this on MatchingDelete ? - //deleteAllMembers(item); - } + // Start the Fake PSP Thread + //__KernelStartThread(item->matching_thid, 0, 0); + //item->matchingThread->Start(0, 0); - return 0; -} - -static int sceNetAdhocMatchingDelete(int matchingId) { - // WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right? - /* - if (!g_Config.bEnableWlan) - return -1; - */ - - // Previous Context Reference - SceNetAdhocMatchingContext * prev = NULL; - - // Context Pointer - SceNetAdhocMatchingContext * item = contexts; - - // Iterate contexts - for (; item != NULL; item = item->next) { - // Found matching ID - if (item->id == matchingId) { - // Multithreading Lock - peerlock.lock(); //contextlock.lock(); - - // Unlink Left (Beginning) - if (prev == NULL) contexts = item->next; - - // Unlink Left (Other) - else prev->next = item->next; - - // Multithreading Unlock - peerlock.unlock(); //contextlock.unlock(); - - // Delete the socket - sceNetAdhocPdpDelete(item->socket, 0); // item->connected = (sceNetAdhocPdpDelete(item->socket, 0) < 0); - // Free allocated memories - free(item->hello); - free(item->rxbuf); - deleteAllMembers(item); - // Free item context memory - free(item); - - // Stop Search - break; + //Create the threads + if (!item->eventRunning) { + item->eventRunning = true; + item->eventThread = std::thread(matchingEventThread, matchingId); + } + if (!item->inputRunning) { + item->inputRunning = true; + item->inputThread = std::thread(matchingInputThread, matchingId); } - // Set Previous Reference - prev = item; + item->running = 1; + netAdhocMatchingStarted++; } + //else return ERROR_NET_ADHOC_MATCHING_INVALID_ID; //Faking success to prevent GTA:VCS from stuck unable to choose host/join menu - WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingDelete(%i) at %08x", matchingId, currentMIPS->pc); + // Multithreading Unlock + peerlock.unlock(); + return 0; } static int sceNetAdhocMatchingSelectTarget(int matchingId, const char *macAddress, int optLen, u32 optDataPtr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingSelectTarget(%i, %s, %i, %08x)", matchingId, macAddress, optLen, optDataPtr); + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingSelectTarget(%i, %s, %i, %08x) at %08x", matchingId, macAddress, optLen, optDataPtr, currentMIPS->pc); if (!g_Config.bEnableWlan) return -1; - return 0; + + // Initialized Library + if (netAdhocMatchingInited) + { + // Valid Arguments + if (macAddress != NULL) + { + SceNetEtherAddr * target = (SceNetEtherAddr *)macAddress; + + // Find Matching Context for ID + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + + // Found Matching Context + if (context != NULL) + { + // Running Context + if (context->running) + { + // Search Result + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, (SceNetEtherAddr *)target); + + // Found Peer in List + if (peer != NULL) + { + // Valid Optional Data Length + if ((optLen == 0 && optDataPtr == NULL) || (optLen > 0 && optDataPtr != NULL)) + { + void * opt = NULL; + if (Memory::IsValidAddress(optDataPtr)) opt = Memory::GetPointer(optDataPtr); + // Host Mode + if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT) + { + // Already Connected + if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) return ERROR_NET_ADHOC_MATCHING_ALREADY_ESTABLISHED; + + // Not enough space + if (countChildren(context) == (context->maxpeers - 1)) return ERROR_NET_ADHOC_MATCHING_EXCEED_MAXNUM; + + // Requesting Peer + if (peer->state == PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST) + { + // Accept Peer in Group + peer->state = PSP_ADHOC_MATCHING_PEER_CHILD; + + // Sending order may need to be reversed since Stack appends to the front, so the order will be switched around. + + // Tell Children about new Sibling + sendBirthMessage(context, peer); + + // Send Accept Confirmation to Peer + sendAcceptMessage(context, peer, optLen, opt); + + // Return Success + return 0; + } + } + + // Client Mode + else if (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD) + { + // Already connected + if (findParent(context) != NULL) return ERROR_NET_ADHOC_MATCHING_ALREADY_ESTABLISHED; + + // Outgoing Request in Progress + if (findOutgoingRequest(context) != NULL) return ERROR_NET_ADHOC_MATCHING_REQUEST_IN_PROGRESS; + + // Valid Offer + if (peer->state == PSP_ADHOC_MATCHING_PEER_OFFER) + { + // Switch into Join Request Mode + peer->state = PSP_ADHOC_MATCHING_PEER_OUTGOING_REQUEST; + + // Send Join Request to Peer + sendJoinRequest(context, peer, optLen, opt); + + // Return Success + return 0; + } + } + + // P2P Mode + else + { + // Already connected + if (findP2P(context) != NULL) return ERROR_NET_ADHOC_MATCHING_ALREADY_ESTABLISHED; + + // Outgoing Request in Progress + if (findOutgoingRequest(context) != NULL) return ERROR_NET_ADHOC_MATCHING_REQUEST_IN_PROGRESS; + + // Join Request Mode + if (peer->state == PSP_ADHOC_MATCHING_PEER_OFFER) + { + // Switch into Join Request Mode + peer->state = PSP_ADHOC_MATCHING_PEER_OUTGOING_REQUEST; + + // Send Join Request to Peer + sendJoinRequest(context, peer, optLen, opt); + + // Return Success + return 0; + } + + // Requesting Peer + else if (peer->state == PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST) + { + // Accept Peer in Group + peer->state = PSP_ADHOC_MATCHING_PEER_P2P; + + // Send Accept Confirmation to Peer + sendAcceptMessage(context, peer, optLen, opt); + + // Return Success + return 0; + } + } + + // How did this happen?! It shouldn't! + return ERROR_NET_ADHOC_MATCHING_TARGET_NOT_READY; + } + + // Invalid Optional Data Length + return ERROR_NET_ADHOC_MATCHING_INVALID_OPTLEN; + } + + // Peer not found + return ERROR_NET_ADHOC_MATCHING_UNKNOWN_TARGET; + } + + // Idle Context + return ERROR_NET_ADHOC_MATCHING_NOT_RUNNING; + } + + // Invalid Matching ID + return ERROR_NET_ADHOC_MATCHING_INVALID_ID; + } + + // Invalid Arguments + return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + } + + // Uninitialized Library + return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; } -static int sceNetAdhocMatchingCancelTargetWithOpt(int matchingId, const char *macAddress, int optLen, u32 optDataPtr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingCancelTargetWithOpt(%i, %s, %i, %08x)", matchingId, macAddress, optLen, optDataPtr); +int sceNetAdhocMatchingCancelTargetWithOpt(int matchingId, const char *macAddress, int optLen, u32 optDataPtr) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingCancelTargetWithOpt(%i, %s, %i, %08x) at %08x", matchingId, macAddress, optLen, optDataPtr, currentMIPS->pc); if (!g_Config.bEnableWlan) return -1; - return 0; + + // Initialized Library + if (netAdhocMatchingInited) + { + SceNetEtherAddr * target = (SceNetEtherAddr *)macAddress; + void * opt = NULL; + if (Memory::IsValidAddress(optDataPtr)) opt = Memory::GetPointer(optDataPtr); + + // Valid Arguments + if (target != NULL && ((optLen == 0 && opt == NULL) || (optLen > 0 && opt != NULL))) + { + // Find Matching Context + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + + // Found Matching Context + if (context != NULL) + { + // Running Context + if (context->running) + { + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, (SceNetEtherAddr *)target); + + // Found Peer + if (peer != NULL) + { + // Valid Peer Mode + if ((context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && (peer->state == PSP_ADHOC_MATCHING_PEER_PARENT || peer->state == PSP_ADHOC_MATCHING_PEER_OUTGOING_REQUEST)) || + (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST)) || + (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && (peer->state == PSP_ADHOC_MATCHING_PEER_P2P || peer->state == PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST))) + { + // Notify other Children of Death + if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && peer->state == PSP_ADHOC_MATCHING_PEER_CHILD && countConnectedPeers(context) > 1) + { + // Send Death Message + sendDeathMessage(context, peer); + } + + // Mark Peer as Canceled + peer->state = PSP_ADHOC_MATCHING_PEER_CANCEL_IN_PROGRESS; + + // Send Cancel Event to Peer + sendCancelMessage(context, peer, optLen, opt); + + // Delete Peer from List + // Can't delete here, Threads still need this data. + // deletePeer(context, peer); + + // Return Success + return 0; + } + } + + // Peer not found + //return ERROR_NET_ADHOC_MATCHING_UNKNOWN_TARGET; + // Faking success to prevent the game (ie. Soul Calibur) to repeatedly calling this function when the other player is disconnected + return 0; + } + + // Context not running + return ERROR_NET_ADHOC_MATCHING_NOT_RUNNING; + } + + // Invalid Matching ID + return ERROR_NET_ADHOC_MATCHING_INVALID_ID; + } + + // Invalid Arguments + return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + } + + // Uninitialized Library + return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; } -static int sceNetAdhocMatchingCancelTarget(int matchingId, const char *macAddress) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingCancelTarget(%i, %s)", matchingId, macAddress); +int sceNetAdhocMatchingCancelTarget(int matchingId, const char *macAddress) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingCancelTarget(%i, %s)", matchingId, macAddress); if (!g_Config.bEnableWlan) return -1; - return 0; + return sceNetAdhocMatchingCancelTargetWithOpt(matchingId, macAddress, 0, NULL); } -static int sceNetAdhocMatchingGetHelloOpt(int matchingId, u32 optLenAddr, u32 optDataAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingGetHelloOpt(%i, %08x, %08x)", matchingId, optLenAddr, optDataAddr); +int sceNetAdhocMatchingGetHelloOpt(int matchingId, u32 optLenAddr, u32 optDataAddr) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingGetHelloOpt(%i, %08x, %08x)", matchingId, optLenAddr, optDataAddr); if (!g_Config.bEnableWlan) return -1; + + if (!Memory::IsValidAddress(optLenAddr)) return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + + s32_le * optlen = (s32_le *)optLenAddr; + + // Multithreading Lock + peerlock.lock(); + + SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); + + if (item != NULL) { + // Get OptData + *optlen = item->hellolen; + if ((*optlen > 0) && Memory::IsValidAddress(optDataAddr)) { + uint8_t * optdata = Memory::GetPointer(optDataAddr); + memcpy(optdata, item->hello, *optlen); + } + //else return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + } + //else return ERROR_NET_ADHOC_MATCHING_INVALID_ID; + + // Multithreading Unlock + peerlock.unlock(); + return 0; } @@ -2431,32 +3087,81 @@ int sceNetAdhocMatchingSetHelloOpt(int matchingId, int optLenAddr, u32 optDataAd if (!g_Config.bEnableWlan) return -1; - //if (!Memory::IsValidAddress(optDataAddr)) return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + if (!netAdhocMatchingInited) return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; - SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); - if (item != NULL) { - // Set OptData - int oldLen = item->hellolen; - item->hellolen = optLenAddr; //optLenAddr doesn't seems to be an address to the actual len - item->helloAddr = optDataAddr; + // Multithreading Lock + peerlock.lock(); - if (optLenAddr <= 0 || !Memory::IsValidAddress(optDataAddr)) { - if (item->hello != NULL) { - free(item->hello); - item->hello = NULL; + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + + // Multithreading Unlock + peerlock.unlock(); + + // Found Context + if (context != NULL) + { + // Valid Matching Modes + if (context->mode != PSP_ADHOC_MATCHING_MODE_CHILD) + { + // Running Context + if (context->running) + { + // Valid Optional Data Length + if ((optLenAddr == 0 && optDataAddr == NULL) || (optLenAddr > 0 && optDataAddr != NULL)) + { + // Grab Existing Hello Data + void * hello = context->hello; + + // Free Previous Hello Data, or Reuse it + //free(hello); + + // Allocation Required + if (optLenAddr > 0) + { + // Allocate Memory + if (optLenAddr > context->hellolen) { + hello = realloc(hello, optLenAddr); + } + + // Out of Memory + if (hello == NULL) { + context->hellolen = 0; + return ERROR_NET_ADHOC_MATCHING_NO_SPACE; + } + + // Clone Hello Data + //memcpy(hello, opt, optLenAddr); + Memory::Memcpy(hello, optDataAddr, optLenAddr); + + // Set Hello Data + context->hello = (uint8_t*)hello; + context->hellolen = optLenAddr; + context->helloAddr = optDataAddr; + } + else + { + // Delete Hello Data + context->hellolen = 0; + context->helloAddr = 0; + //free(context->hello); // Doesn't need to free it since it will be reused later + //context->hello = NULL; + } + + // Return Success + return 0; + } + + // Invalid Optional Data Length + return ERROR_NET_ADHOC_MATCHING_INVALID_OPTLEN; } + + // Context not running + return ERROR_NET_ADHOC_MATCHING_NOT_RUNNING; } - else { - if (optLenAddr > oldLen) { - free(item->hello); - item->hello = malloc(optLenAddr); - } - Memory::Memcpy(item->hello, optDataAddr, optLenAddr); - } + + // Invalid Matching Mode (Child) + return ERROR_NET_ADHOC_MATCHING_INVALID_MODE; } - //else return ERROR_NET_ADHOC_MATCHING_INVALID_ID; - - //sceNetAdhocctlScan(); return 0; } @@ -2466,88 +3171,325 @@ static int sceNetAdhocMatchingGetMembers(int matchingId, u32 sizeAddr, u32 buf) if (!g_Config.bEnableWlan) return -1; + if (!netAdhocMatchingInited) return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; + // Minimum Argument if (!Memory::IsValidAddress(sizeAddr)) return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; - SceNetAdhocMatchingContext * item = findMatchingContext(matchingId); - if (item != NULL) { - int * buflen = (int *)Memory::GetPointer(sizeAddr); - SceNetAdhocMatchingMemberInfoEmu * buf2 = NULL; - if (Memory::IsValidAddress(buf)) { - buf2 = (SceNetAdhocMatchingMemberInfoEmu *)Memory::GetPointer(buf); - } + // Multithreading Lock + peerlock.lock(); + // Find Matching Context + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + // Multithreading Unlock + peerlock.unlock(); - // Multithreading Lock - peerlock.lock(); + // Found Context + if (context != NULL) + { + // Running Context + if (context->running) + { + // Length Buffer available + if (sizeAddr != NULL) + { + int * buflen = (int *)Memory::GetPointer(sizeAddr); + SceNetAdhocMatchingMemberInfoEmu * buf2 = NULL; + if (Memory::IsValidAddress(buf)) { + buf2 = (SceNetAdhocMatchingMemberInfoEmu *)Memory::GetPointer(buf); + } - // Iterate Members - //SceNetAdhocMatchingMemberInternal * peer = item->peerlist; + // Number of Connected Peers + uint32_t peercount = countConnectedPeers(context); - //Using friend list instead, since it's easier to implement ^_^ - SceNetAdhocctlPeerInfo * peer = friends; + // Calculate Connected Peer Bytesize + int available = sizeof(SceNetAdhocMatchingMemberInfoEmu) * peercount; - int count = 0; - if (!Memory::IsValidAddress(buf)) { // Returning needed buf size instead - count++; - for (; peer != NULL; peer = peer->next) count++; - } - else { - buf2[count].mac_addr = item->mac; //add your own MAC - buf2[count].padding[0] = 0; // does padding need to be 0 ? - buf2[count++].padding[1] = 0; - for (; peer != NULL; peer = peer->next) { - buf2[count].mac_addr = peer->mac_addr; - buf2[count].padding[0] = 0; - buf2[count].padding[1] = 0; - count++; + // Length Returner Mode + if (buf == NULL) + { + // Get Connected Peer Count + *buflen = available; + } + + // Normal Mode + else + { + // Fix Negative Length + if ((*buflen) < 0) *buflen = 0; + + // Fix Oversize Request + if ((*buflen) > available) *buflen = available; + + // Clear Memory + memset(buf2, 0, *buflen); + + // Calculate Requested Peer Count + int requestedpeers = (*buflen) / sizeof(SceNetAdhocMatchingMemberInfoEmu); + + // Filled Request Counter + int filledpeers = 0; + + // Add Self-Peer + if (requestedpeers > 0) + { + // Add Local MAC + buf2[filledpeers++].mac_addr = context->mac; + + // Room for more than local peer + if (requestedpeers > 1) + { + // P2P Mode + if (context->mode == PSP_ADHOC_MATCHING_MODE_P2P) + { + // Find P2P Brother + SceNetAdhocMatchingMemberInternal * p2p = findP2P(context); + + // P2P Brother found + if (p2p != NULL) + { + // Add P2P Brother MAC + buf2[filledpeers++].mac_addr = p2p->mac; + } + } + + // Parent or Child Mode + else + { + // Iterate Peer List + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL && filledpeers < requestedpeers; peer = peer->next) + { + // Parent Mode + if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT) + { + // Interested in Children (Michael Jackson Style) + if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) + { + // Add Child MAC + buf2[filledpeers++].mac_addr = peer->mac; + } + } + + // Children Mode + else + { + // Interested in Parent & Siblings + if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_PARENT) + { + // Add Peer MAC + buf2[filledpeers++].mac_addr = peer->mac; + } + } + } + } + + } + + // Link Result List + int i = 0; + for (; i < filledpeers - 1; i++) + { + // Link Next Element + //buf2[i].next = &buf2[i + 1]; + buf2[i].next = buf + (sizeof(SceNetAdhocMatchingMemberInfoEmu)*i) + sizeof(SceNetAdhocMatchingMemberInfoEmu); + } + // Fix Last Element + if (filledpeers > 0) buf2[filledpeers - 1].next = 0; + } + + // Fix Buffer Size + *buflen = sizeof(SceNetAdhocMatchingMemberInfoEmu) * filledpeers; + } + + // Return Success + return 0; } - // Link List - int i = 0; - for (; i < count - 1; i++) { - // Link Network - buf2[i].next = buf + (sizeof(SceNetAdhocMatchingMemberInfoEmu)*i) + sizeof(SceNetAdhocMatchingMemberInfoEmu); - } - // Fix Last Element - if (count > 0) buf2[count - 1].next = 0; + + // Invalid Arguments + return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; } - // Fix Size - *buflen = count * sizeof(SceNetAdhocMatchingMemberInfoEmu); //includes your own MAC - - // Multithreading Unlock - peerlock.unlock(); + // Context not running + return ERROR_NET_ADHOC_MATCHING_NOT_RUNNING; } - //else return ERROR_NET_ADHOC_MATCHING_INVALID_ID; - return 0; + // Invalid Matching ID + return ERROR_NET_ADHOC_MATCHING_INVALID_ID; } -static int sceNetAdhocMatchingSendData(int matchingId, const char *mac, int dataLen, u32 dataAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingSendData(%i, %s, %i, %08x)", matchingId, mac, dataLen, dataAddr); +int sceNetAdhocMatchingSendData(int matchingId, const char *mac, int dataLen, u32 dataAddr) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingSendData(%i, %s, %i, %08x)", matchingId, mac, dataLen, dataAddr); if (!g_Config.bEnableWlan) return -1; - return 0; + + // Initialized Library + if (netAdhocMatchingInited) + { + // Valid Arguments + if (mac != NULL) + { + // Find Matching Context + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + + // Found Context + if (context != NULL) + { + // Running Context + if (context->running) + { + // Find Target Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, (SceNetEtherAddr *)mac); + + // Found Peer + if (peer != NULL) + { + void * data = NULL; + if (Memory::IsValidAddress(dataAddr)) data = Memory::GetPointer(dataAddr); + + // Valid Data Length + if (dataLen > 0 && data != NULL) + { + // Valid Peer Connection State + if (peer->state == PSP_ADHOC_MATCHING_PEER_PARENT || peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_P2P) + { + // Send in Progress + if (peer->sending) return ERROR_NET_ADHOC_MATCHING_DATA_BUSY; + + // Mark Peer as Sending + peer->sending = 1; + + // Send Data to Peer + sendBulkData(context, peer, dataLen, data); + + // Return Success + return 0; + } + + // Not connected / accepted + return ERROR_NET_ADHOC_MATCHING_NOT_ESTABLISHED; + } + + // Invalid Data Length + return ERROR_NET_ADHOC_MATCHING_INVALID_DATALEN; + } + + // Peer not found + return ERROR_NET_ADHOC_MATCHING_UNKNOWN_TARGET; + } + + // Context not running + return ERROR_NET_ADHOC_MATCHING_NOT_RUNNING; + } + + // Invalid Matching ID + return ERROR_NET_ADHOC_MATCHING_INVALID_ID; + } + + // Invalid Arguments + return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + } + + // Uninitialized Library + return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; } -static int sceNetAdhocMatchingAbortSendData(int matchingId, const char *mac) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingAbortSendData(%i, %s)", matchingId, mac); +int sceNetAdhocMatchingAbortSendData(int matchingId, const char *mac) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingAbortSendData(%i, %s)", matchingId, mac); if (!g_Config.bEnableWlan) return -1; - return 0; + + // Initialized Library + if (netAdhocMatchingInited) + { + // Valid Arguments + if (mac != NULL) + { + // Find Matching Context + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + + // Found Context + if (context != NULL) + { + // Running Context + if (context->running) + { + // Find Target Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, (SceNetEtherAddr *)mac); + + // Found Peer + if (peer != NULL) + { + // Peer is sending + if (peer->sending) + { + // Set Peer as Bulk Idle + peer->sending = 0; + + // Stop Bulk Data Sending (if in progress) + abortBulkTransfer(context, peer); + } + + // Return Success + return 0; + } + + // Peer not found + return ERROR_NET_ADHOC_MATCHING_UNKNOWN_TARGET; + } + + // Context not running + return ERROR_NET_ADHOC_MATCHING_NOT_RUNNING; + } + + // Invalid Matching ID + return ERROR_NET_ADHOC_MATCHING_INVALID_ID; + } + + // Invalid Arguments + return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + } + + // Uninitialized Library + return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; } static int sceNetAdhocMatchingGetPoolMaxAlloc() { ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingGetPoolMaxAlloc()"); if (!g_Config.bEnableWlan) return -1; - return 0; + + // Lazy way out - hardcoded return value + return (50 * 1024); } -static int sceNetAdhocMatchingGetPoolStat() { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocMatchingGetPoolStat()"); +int sceNetAdhocMatchingGetPoolStat(u32 poolstatPtr) { + WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingGetPoolStat(%08x)", poolstatPtr); if (!g_Config.bEnableWlan) return -1; - return 0; + + // Initialized Library + if (netAdhocMatchingInited) + { + SceNetMallocStat * poolstat = NULL; + if (Memory::IsValidAddress(poolstatPtr)) poolstat = (SceNetMallocStat *)Memory::GetPointer(poolstatPtr); + + // Valid Argument + if (poolstat != NULL) + { + // Fill Poolstat with Fake Data + poolstat->pool = fakePoolSize; + poolstat->maximum = fakePoolSize / 8 * 6; + poolstat->free = fakePoolSize / 8 * 7; + + // Return Success + return 0; + } + + // Invalid Argument + return ERROR_NET_ADHOC_MATCHING_INVALID_ARG; + } + + // Uninitialized Library + return ERROR_NET_ADHOC_MATCHING_NOT_INITIALIZED; } const HLEFunction sceNetAdhoc[] = { @@ -2558,7 +3500,7 @@ const HLEFunction sceNetAdhoc[] = { {0xabed3790, WrapI_ICUVIII, "sceNetAdhocPdpSend"}, {0xdfe53e03, WrapI_IVVVVUI, "sceNetAdhocPdpRecv"}, {0x7f27bb5e, WrapI_II, "sceNetAdhocPdpDelete"}, - {0xc7c1fc57, WrapI_IU, "sceNetAdhocGetPdpStat"}, + {0xc7c1fc57, WrapI_UU, "sceNetAdhocGetPdpStat"}, {0x157e6225, WrapI_II, "sceNetAdhocPtpClose"}, {0x4da4c788, WrapI_IUUII, "sceNetAdhocPtpSend"}, {0x877f6d66, WrapI_CICIIIII, "sceNetAdhocPtpOpen"}, @@ -2575,7 +3517,7 @@ const HLEFunction sceNetAdhoc[] = { {0x0b2228e9, WrapI_I, "sceNetAdhocGameModeDeleteReplica"}, {0x7F75C338, WrapI_UI, "sceNetAdhocGameModeCreateMaster"}, {0x73bfd52d, WrapI_II, "sceNetAdhocSetSocketAlert"}, - {0x4d2ce199, WrapI_V, "sceNetAdhocGetSocketAlert"}, + {0x4d2ce199, WrapI_IU, "sceNetAdhocGetSocketAlert"}, {0x7a662d6b, WrapI_UIII, "sceNetAdhocPollSocket"}, }; @@ -2595,12 +3537,12 @@ const HLEFunction sceNetAdhocMatching[] = { {0xf79472d7, WrapI_ICIU, "sceNetAdhocMatchingSendData"}, {0xec19337d, WrapI_IC, "sceNetAdhocMatchingAbortSendData"}, {0x40F8F435, WrapI_V, "sceNetAdhocMatchingGetPoolMaxAlloc"}, - {0x9c5cfb7d, WrapI_V, "sceNetAdhocMatchingGetPoolStat"}, + {0x9c5cfb7d, WrapI_U, "sceNetAdhocMatchingGetPoolStat"}, }; static int sceNetAdhocctlExitGameMode() { ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlExitGameMode()"); - return -1; + return 0; } static int sceNetAdhocctlGetGameModeInfo(u32 infoAddr) { @@ -2608,18 +3550,17 @@ static int sceNetAdhocctlGetGameModeInfo(u32 infoAddr) { return -1; } - static int sceNetAdhocctlGetPeerList(u32 sizeAddr, u32 bufAddr) { - INFO_LOG(SCENET, "sceNetAdhocctlGetPeerList(%08x, %08x) at %08x", sizeAddr, bufAddr, currentMIPS->pc); + s32_le *buflen = NULL; + if (Memory::IsValidAddress(sizeAddr)) buflen = (s32_le *)Memory::GetPointer(sizeAddr); + SceNetAdhocctlPeerInfoEmu *buf = NULL; + if (Memory::IsValidAddress(bufAddr)) buf = (SceNetAdhocctlPeerInfoEmu *)Memory::GetPointer(bufAddr); + + DEBUG_LOG(SCENET, "sceNetAdhocctlGetPeerList([%08x]=%i, %08x) at %08x", sizeAddr, buflen ? *buflen : -1, bufAddr, currentMIPS->pc); if (!g_Config.bEnableWlan) { return -1; } - int * buflen = (int *)Memory::GetPointer(sizeAddr); - SceNetAdhocctlPeerInfoEmu * buf = NULL; - if (Memory::IsValidAddress(bufAddr)) { - buf = (SceNetAdhocctlPeerInfoEmu *)Memory::GetPointer(bufAddr); - } // Initialized Library if (netAdhocctlInited) { // Minimum Arguments @@ -2649,7 +3590,7 @@ static int sceNetAdhocctlGetPeerList(u32 sizeAddr, u32 bufAddr) { // Iterate Peers for (; peer != NULL && discovered < requestcount; peer = peer->next) { // Fake Receive Time - peer->last_recv = (uint64_t)time(NULL); + if (peer->last_recv != 0) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); // Copy Peer Info buf[discovered].nickname = peer->nickname; @@ -2663,15 +3604,14 @@ static int sceNetAdhocctlGetPeerList(u32 sizeAddr, u32 bufAddr) { // Link List int i = 0; for (; i < discovered - 1; i++) { // Link Network - buf[i].next = bufAddr+(sizeof(SceNetAdhocctlPeerInfoEmu)*i)+ - sizeof(SceNetAdhocctlPeerInfoEmu); + buf[i].next = bufAddr+(sizeof(SceNetAdhocctlPeerInfoEmu)*i) + sizeof(SceNetAdhocctlPeerInfoEmu); } // Fix Last Element if (discovered > 0) buf[discovered - 1].next = 0; } // Fix Size - *buflen = discovered * sizeof(SceNetAdhocctlPeerInfo); + *buflen = discovered * sizeof(SceNetAdhocctlPeerInfoEmu); } // Multithreading Unlock @@ -2690,8 +3630,106 @@ static int sceNetAdhocctlGetPeerList(u32 sizeAddr, u32 bufAddr) { } static int sceNetAdhocctlGetAddrByName(const char *nickName, u32 sizeAddr, u32 bufAddr) { - ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetPeerList(%s, %08x, %08x)", nickName, sizeAddr, bufAddr); - return -1; + s32_le *buflen = NULL; //int32_t + if (Memory::IsValidAddress(sizeAddr)) buflen = (s32_le *)Memory::GetPointer(sizeAddr); + + WARN_LOG(SCENET, "UNTESTED sceNetAdhocctlGetPeerList(%s, [%08x]=%i, %08x)", nickName, sizeAddr, buflen ? *buflen : -1, bufAddr); + + // Library initialized + if (netAdhocctlInited) + { + // Valid Arguments + if (nickName != NULL && buflen != NULL) + { + SceNetAdhocctlPeerInfoEmu *buf = NULL; + if (Memory::IsValidAddress(bufAddr)) buf = (SceNetAdhocctlPeerInfoEmu *)Memory::GetPointer(bufAddr); + + // Multithreading Lock + peerlock.lock(); + + // Length Calculation Mode + if (buf == NULL) *buflen = getNicknameCount(nickName) * sizeof(SceNetAdhocctlPeerInfoEmu); + + // Normal Information Mode + else + { + // Clear Memory + memset(buf, 0, *buflen); + + // Discovered Player Count + int discovered = 0; + + // Calculate Requested Elements + int requestcount = *buflen / sizeof(SceNetAdhocctlPeerInfoEmu); + + // Minimum Space available + if (requestcount > 0) + { + // Local Nickname Matches + if (strcmp((char *)parameter.nickname.data, nickName) == 0) + { + // Get Local IP Address + sockaddr_in addr; + + getLocalIp(&addr); + //buf->next = 0; + buf[discovered].nickname = parameter.nickname; + buf[discovered].nickname.data[ADHOCCTL_NICKNAME_LEN - 1] = 0; // last char need to be null-terminated char + getLocalMac(&buf[discovered].mac_addr); + buf[discovered].ip_addr = addr.sin_addr.s_addr; // 0x11111111; + //buf->padding = 0x1111; //0; + buf[discovered++].last_recv = CoreTiming::GetGlobalTimeUsScaled(); + } + + // Peer Reference + SceNetAdhocctlPeerInfo * peer = friends; + + // Iterate Peers + for (; peer != NULL && discovered < requestcount; peer = peer->next) + { + // Match found + if (strcmp((char *)peer->nickname.data, nickName) == 0) + { + // Fake Receive Time + if (peer->last_recv != 0) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled(); //sceKernelGetSystemTimeWide(); + + // Copy Peer Info + buf[discovered].nickname = peer->nickname; + buf[discovered].nickname.data[ADHOCCTL_NICKNAME_LEN - 1] = 0; // last char need to be null-terminated char + buf[discovered].mac_addr = peer->mac_addr; + buf[discovered].ip_addr = peer->ip_addr; + buf[discovered++].last_recv = peer->last_recv; + } + } + + // Link List + int i = 0; for (; i < discovered - 1; i++) + { + // Link Network + buf[i].next = bufAddr + (sizeof(SceNetAdhocctlPeerInfoEmu)*i) + sizeof(SceNetAdhocctlPeerInfoEmu); + } + + // Fix Last Element + if (discovered > 0) buf[discovered - 1].next = 0; + } + + // Fix Buffer Size + *buflen = discovered * sizeof(SceNetAdhocctlPeerInfoEmu); + } + + // Multithreading Unlock + peerlock.unlock(); + + // Return Success + return 0; + } + + // Invalid Arguments + return ERROR_NET_ADHOCCTL_INVALID_ARG; + } + + // Library uninitialized + return ERROR_NET_ADHOCCTL_NOT_INITIALIZED; } const HLEFunction sceNetAdhocctl[] = { @@ -2716,16 +3754,47 @@ const HLEFunction sceNetAdhocctl[] = { {0x362cbe8f, WrapI_U, "sceNetAdhocctlGetAdhocId"}, {0x5a014ce0, WrapI_U, "sceNetAdhocctlGetGameModeInfo"}, {0x99560abe, WrapI_CUU, "sceNetAdhocctlGetAddrByName"}, - {0xb0b80e80, 0, "sceNetAdhocctlCreateEnterGameModeMin"}, // ?? + {0xb0b80e80, WrapI_CIIIUUI, "sceNetAdhocctlCreateEnterGameModeMin" }, // ?? }; +int sceNetAdhocDiscoverInitStart() { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocDiscoverInitStart()"); + return 0; +} + +int sceNetAdhocDiscoverStop() { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocDiscoverStop()"); + return 0; +} + +int sceNetAdhocDiscoverTerm() { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocDiscoverTerm()"); + return 0; +} + +int sceNetAdhocDiscoverUpdate() { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocDiscoverUpdate()"); + return 0; +} + +int sceNetAdhocDiscoverGetStatus() { + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocDiscoverGetStatus()"); + return 0; +} + +int sceNetAdhocDiscoverRequestSuspend(void) +{ + ERROR_LOG(SCENET, "UNIMPL sceNetAdhocDiscoverRequestSuspend()"); + return 0; +} + const HLEFunction sceNetAdhocDiscover[] = { - {0x941B3877, 0, "sceNetAdhocDiscoverInitStart"}, - {0x52DE1B97, 0, "sceNetAdhocDiscoverUpdate"}, - {0x944DDBC6, 0, "sceNetAdhocDiscoverGetStatus"}, - {0xA2246614, 0, "sceNetAdhocDiscoverTerm"}, - {0xF7D13214, 0, "sceNetAdhocDiscoverStop"}, - {0xA423A21B, 0, "sceNetAdhocDiscoverRequestSuspend"}, + {0x941B3877, WrapI_V, "sceNetAdhocDiscoverInitStart" }, + {0x52DE1B97, WrapI_V, "sceNetAdhocDiscoverUpdate" }, + {0x944DDBC6, WrapI_V, "sceNetAdhocDiscoverGetStatus" }, + {0xA2246614, WrapI_V, "sceNetAdhocDiscoverTerm" }, + {0xF7D13214, WrapI_V, "sceNetAdhocDiscoverStop" }, + {0xA423A21B, WrapI_V, "sceNetAdhocDiscoverRequestSuspend" }, }; void Register_sceNetAdhoc() { @@ -2734,3 +3803,1253 @@ void Register_sceNetAdhoc() { RegisterModule("sceNetAdhocDiscover", ARRAY_SIZE(sceNetAdhocDiscover), sceNetAdhocDiscover); RegisterModule("sceNetAdhocctl", ARRAY_SIZE(sceNetAdhocctl), sceNetAdhocctl); } + +/** +* Broadcast Ping Message to other Matching Users +* @param context Matching Context Pointer +*/ +void broadcastPingMessage(SceNetAdhocMatchingContext * context) +{ + // Ping Opcode + uint8_t ping = PSP_ADHOC_MATCHING_PACKET_PING; + + // Send Broadcast + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)(SceNetEtherAddr *)broadcastMAC, context->port, &ping, sizeof(ping), 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); +} + +/** +* Broadcast Hello Message to other Matching Users +* @param context Matching Context Pointer +*/ +void broadcastHelloMessage(SceNetAdhocMatchingContext * context) +{ + static uint8_t * hello = NULL; + static int32_t len = -5; + + // Allocate Hello Message Buffer, reuse when necessary + if ((int32_t)context->hellolen > len) { + hello = (uint8_t *)realloc(hello, 5 + context->hellolen); + len = context->hellolen; + } + + // Allocated Hello Message Buffer + if (hello != NULL) + { + // Hello Opcode + hello[0] = PSP_ADHOC_MATCHING_PACKET_HELLO; + + // Hello Data Length (have to memcpy this to avoid cpu alignment crash) + memcpy(hello + 1, &context->hellolen, sizeof(context->hellolen)); + + // Copy Hello Data + if (context->hellolen > 0) memcpy(hello + 5, context->hello, context->hellolen); + + // Send Broadcast + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)(SceNetEtherAddr *)broadcastMAC, context->port, hello, 5 + context->hellolen, 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Free Memory, not needed since it may be reused again later + //free(hello); + } +} + +/** +* Send Accept Packet to Player +* @param context Matching Context Pointer +* @param mac Target Player MAC +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendAcceptPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac, int optlen, void * opt) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, mac); + + // Found Peer + if (peer != NULL && (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_P2P)) + { + // Required Sibling Buffer + uint32_t siblingbuflen = 0; + + // Parent Mode + if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT) siblingbuflen = sizeof(SceNetEtherAddr) * (countConnectedPeers(context) - 2); + + // Sibling Count + int siblingcount = siblingbuflen / sizeof(SceNetEtherAddr); + + // Allocate Accept Message Buffer + uint8_t * accept = (uint8_t *)malloc(9 + optlen + siblingbuflen); + + // Allocated Accept Message Buffer + if (accept != NULL) + { + // Accept Opcode + accept[0] = PSP_ADHOC_MATCHING_PACKET_ACCEPT; + + // Optional Data Length + memcpy(accept + 1, &optlen, sizeof(optlen)); + + // Sibling Count + memcpy(accept + 5, &siblingcount, sizeof(siblingcount)); + + // Copy Optional Data + if (optlen > 0) memcpy(accept + 9, opt, optlen); + + // Parent Mode Extra Data required + if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && siblingcount > 0) + { + // Create MAC Array Pointer + uint8_t * siblingmacs = (uint8_t *)(accept + 9 + optlen); + + // MAC Writing Pointer + int i = 0; + + // Iterate Peer List + SceNetAdhocMatchingMemberInternal * item = context->peerlist; for (; item != NULL; item = item->next) + { + // Ignore Target + if (item == peer) continue; + + // Copy Child MAC + if (item->state == PSP_ADHOC_MATCHING_PEER_CHILD) + { + // Clone MAC the stupid memcpy way to shut up PSP CPU + memcpy(siblingmacs + sizeof(SceNetEtherAddr) * i++, &item->mac, sizeof(SceNetEtherAddr)); + } + } + } + + // Send Data + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)mac, context->port, accept, 9 + optlen + siblingbuflen, 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Free Memory + free(accept); + + // Spawn Local Established Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_ESTABLISHED, mac, 0, NULL); + } + } +} + +/** +* Send Join Packet to Player +* @param context Matching Context Pointer +* @param mac Target Player MAC +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendJoinPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac, int optlen, void * opt) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, mac); + + // Valid Peer + if (peer != NULL && peer->state == PSP_ADHOC_MATCHING_PEER_OUTGOING_REQUEST) + { + // Allocate Join Message Buffer + uint8_t * join = (uint8_t *)malloc(5 + optlen); + + // Allocated Join Message Buffer + if (join != NULL) + { + // Join Opcode + join[0] = PSP_ADHOC_MATCHING_PACKET_JOIN; + + // Optional Data Length + memcpy(join + 1, &optlen, sizeof(optlen)); + + // Copy Optional Data + if (optlen > 0) memcpy(join + 5, opt, optlen); + + // Send Data + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)mac, context->port, join, 5 + optlen, 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Free Memory + free(join); + } + } +} + +/** +* Send Cancel Packet to Player +* @param context Matching Context Pointer +* @param mac Target Player MAC +* @param optlen Optional Data Length +* @param opt Optional Data +*/ +void sendCancelPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac, int optlen, void * opt) +{ + // Allocate Cancel Message Buffer + uint8_t * cancel = (uint8_t *)malloc(5 + optlen); + + // Allocated Cancel Message Buffer + if (cancel != NULL) + { + // Cancel Opcode + cancel[0] = PSP_ADHOC_MATCHING_PACKET_CANCEL; + + // Optional Data Length + memcpy(cancel + 1, &optlen, sizeof(optlen)); + + // Copy Optional Data + if (optlen > 0) memcpy(cancel + 5, opt, optlen); + + // Send Data + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)mac, context->port, cancel, 5 + optlen, 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Free Memory + free(cancel); + } + + peerlock.lock(); + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, mac); + + // Found Peer + if (peer != NULL) + { + // Child Mode Fallback - Delete All + if (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD) + { + // Delete Peer List + clearPeerList(context); + } + + // Delete Peer + else deletePeer(context, peer); + } + peerlock.unlock(); +} + +/** +* Send Bulk Data Packet to Player +* @param context Matching Context Pointer +* @param mac Target Player MAC +* @param datalen Data Length +* @param data Data +*/ +void sendBulkDataPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac, int datalen, void * data) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, mac); + + // Valid Peer (rest is already checked in send.c) + if (peer != NULL) + { + // Don't send if it's aborted + //if (peer->sending == 0) return; + + // Allocate Send Message Buffer + uint8_t * send = (uint8_t *)malloc(5 + datalen); + + // Allocated Send Message Buffer + if (send != NULL) + { + // Send Opcode + send[0] = PSP_ADHOC_MATCHING_PACKET_BULK; + + // Data Length + memcpy(send + 1, &datalen, sizeof(datalen)); + + // Copy Data + memcpy(send + 5, data, datalen); + + // Send Data + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)mac, context->port, send, 5 + datalen, 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Free Memory + free(send); + + // Remove Busy Bit from Peer + peer->sending = 0; + + // Spawn Data Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_DATA_ACK, mac, 0, NULL); + } + } +} + +/** +* Tell Established Peers of new Child +* @param context Matching Context Pointer +* @param mac New Child's MAC +*/ +void sendBirthPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) +{ + // Find Newborn Child + SceNetAdhocMatchingMemberInternal * newborn = findPeer(context, mac); + + // Found Newborn Child + if (newborn != NULL) + { + // Packet Buffer + uint8_t packet[7]; + + // Set Opcode + packet[0] = PSP_ADHOC_MATCHING_PACKET_BIRTH; + + // Set Newborn MAC + memcpy(packet + 1, mac, sizeof(SceNetEtherAddr)); + + // Iterate Peers + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Skip Newborn Child + if (peer == newborn) continue; + + // Send only to children + if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) + { + // Send Packet + context->socketlock->lock(); + int sent = sceNetAdhocPdpSend(context->socket, (const char*)&peer->mac, context->port, packet, sizeof(packet), 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Log Send Success + if (sent >= 0) + INFO_LOG(SCENET, "InputLoop: Sending BIRTH to %02X:%02X:%02X:%02X:%02X:%02X", peer->mac.data[0], peer->mac.data[1], peer->mac.data[2], peer->mac.data[3], peer->mac.data[4], peer->mac.data[5]); + else + WARN_LOG(SCENET, "InputLoop: Failed to Send BIRTH to %02X:%02X:%02X:%02X:%02X:%02X", peer->mac.data[0], peer->mac.data[1], peer->mac.data[2], peer->mac.data[3], peer->mac.data[4], peer->mac.data[5]); + } + } + } +} + +/** +* Tell Established Peers of abandoned Child +* @param context Matching Context Pointer +* @param mac Dead Child's MAC +*/ +void sendDeathPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) +{ + // Find abandoned Child + SceNetAdhocMatchingMemberInternal * deadkid = findPeer(context, mac); + + // Found abandoned Child + if (deadkid != NULL) + { + // Packet Buffer + uint8_t packet[7]; + + // Set Opcode + packet[0] = PSP_ADHOC_MATCHING_PACKET_DEATH; + + // Set abandoned Child MAC + memcpy(packet + 1, mac, sizeof(SceNetEtherAddr)); + + // Iterate Peers + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Skip dead Child + if (peer == deadkid) continue; + + // Send only to children + if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) + { + // Send Packet + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)&peer->mac, context->port, packet, sizeof(packet), 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + } + } + } +} + +/** +* Tell Established Peers that we're shutting the Networking Layer down +* @param context Matching Context Pointer +*/ +void sendByePacket(SceNetAdhocMatchingContext * context) +{ + // Iterate Peers + SceNetAdhocMatchingMemberInternal * peer = context->peerlist; for (; peer != NULL; peer = peer->next) + { + // Peer of Interest + if (peer->state == PSP_ADHOC_MATCHING_PEER_PARENT || peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_P2P) + { + // Bye Opcode + uint8_t opcode = PSP_ADHOC_MATCHING_PACKET_BYE; + + // Send Bye Packet + context->socketlock->lock(); + sceNetAdhocPdpSend(context->socket, (const char*)&peer->mac, context->port, &opcode, sizeof(opcode), 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + } + } +} + +/** +* Handle Ping Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +*/ +void actOnPingPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // Found Peer + if (peer != NULL) + { + // Update Receive Timer + peer->lastping = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; + } +} + +/** +* Handle Hello Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnHelloPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, int32_t length) +{ + // Interested in Hello Data + if ((context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && findParent(context) == NULL) || (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && findP2P(context) == NULL)) + { + // Complete Packet Header available + if (length >= 5) + { + // Extract Optional Data Length + int optlen = 0; memcpy(&optlen, context->rxbuf + 1, sizeof(optlen)); + + // Complete Valid Packet available + if (optlen >= 0 && length >= (5 + optlen)) + { + // Set Default Null Data + void * opt = NULL; + + // Extract Optional Data Pointer + if (optlen > 0) opt = context->rxbuf + 5; + + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // Peer not found + if (peer == NULL) + { + // Allocate Memory + peer = (SceNetAdhocMatchingMemberInternal *)malloc(sizeof(SceNetAdhocMatchingMemberInternal)); + + // Allocated Memory + if (peer != NULL) + { + // Clear Memory + memset(peer, 0, sizeof(SceNetAdhocMatchingMemberInternal)); + + // Copy Sender MAC + peer->mac = *sendermac; + + // Set Peer State + peer->state = PSP_ADHOC_MATCHING_PEER_OFFER; + + // Initialize Ping Timer + peer->lastping = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; + + // Link Peer into List + peer->next = context->peerlist; + context->peerlist = peer; + } + } + + // Peer available now + if (peer != NULL) + { + // Spawn Hello Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_HELLO, sendermac, optlen, opt); + } + } + } + } +} + +/** +* Handle Join Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnJoinPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, int32_t length) +{ + // Not a child mode context + if (context->mode != PSP_ADHOC_MATCHING_MODE_CHILD) + { + // We still got a unoccupied slot in our room (Parent / P2P) + if ((context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && countChildren(context) < (context->maxpeers - 1)) || (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && findP2P(context) == NULL)) + { + // Complete Packet Header available + if (length >= 5) + { + // Extract Optional Data Length + int optlen = 0; memcpy(&optlen, context->rxbuf + 1, sizeof(optlen)); + + // Complete Valid Packet available + if (optlen >= 0 && length >= (5 + optlen)) + { + // Set Default Null Data + void * opt = NULL; + + // Extract Optional Data Pointer + if (optlen > 0) opt = context->rxbuf + 5; + + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // If we got the peer in the table already and are a parent, there is nothing left to be done. + // This is because the only way a parent can know of a child is via a join request... + // If we thus know of a possible child, then we already had a previous join request thus no need for double tapping. + if (peer != NULL && context->mode == PSP_ADHOC_MATCHING_MODE_PARENT) return; + + // New Peer + if (peer == NULL) + { + // Allocate Memory + peer = (SceNetAdhocMatchingMemberInternal *)malloc(sizeof(SceNetAdhocMatchingMemberInternal)); + + // Allocated Memory + if (peer != NULL) + { + // Clear Memory + memset(peer, 0, sizeof(SceNetAdhocMatchingMemberInternal)); + + // Copy Sender MAC + peer->mac = *sendermac; + + // Set Peer State + peer->state = PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST; + + // Initialize Ping Timer + peer->lastping = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; + + // Link Peer into List + peer->next = context->peerlist; + context->peerlist = peer; + + // Spawn Request Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_REQUEST, sendermac, optlen, opt); + + // Return Success + return; + } + } + + // Existing Peer (this case is only reachable for P2P mode) + else + { + // Set Peer State + peer->state = PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST; + + // Spawn Request Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_REQUEST, sendermac, optlen, opt); + + // Return Success + return; + } + } + } + } + INFO_LOG(SCENET, "Join Event(2) Rejected"); + // Auto-Reject Player + sendCancelPacket(context, sendermac, 0, NULL); + } +} + +/** +* Handle Accept Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnAcceptPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, uint32_t length) +{ + // Not a parent context + if (context->mode != PSP_ADHOC_MATCHING_MODE_PARENT) + { + // Don't have a master yet + if ((context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && findParent(context) == NULL) || (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && findP2P(context) == NULL)) + { + // Complete Packet Header available + if (length >= 9) + { + // Extract Optional Data Length + int optlen = 0; memcpy(&optlen, context->rxbuf + 1, sizeof(optlen)); + + // Extract Sibling Count + int siblingcount = 0; memcpy(&siblingcount, context->rxbuf + 5, sizeof(siblingcount)); + + // Complete Valid Packet available + if (optlen >= 0 && length >= (9 + optlen + sizeof(SceNetEtherAddr) * siblingcount)) + { + // Set Default Null Data + void * opt = NULL; + + // Extract Optional Data Pointer + if (optlen > 0) opt = context->rxbuf + 9; + + // Sibling MAC Array Null Data + SceNetEtherAddr * siblings = NULL; + + // Extract Optional Sibling MAC Array + if (siblingcount > 0) siblings = (SceNetEtherAddr *)(context->rxbuf + 9 + optlen); + + // Find Outgoing Request + SceNetAdhocMatchingMemberInternal * request = findOutgoingRequest(context); + + // We are waiting for a answer to our request... + if (request != NULL) + { + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // It's the answer we wanted! + if (request == peer) + { + // Change Peer State + peer->state = (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD) ? (PSP_ADHOC_MATCHING_PEER_PARENT) : (PSP_ADHOC_MATCHING_PEER_P2P); + + // Remove Unneeded Peer Information + postAcceptCleanPeerList(context); + + // Add Sibling Peers + if (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD) postAcceptAddSiblings(context, siblingcount, siblings); + + // IMPORTANT! The Event Order here is ok! + // Internally the Event Stack appends to the front, so the order will be switched around. + + // Spawn Established Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_ESTABLISHED, sendermac, 0, NULL); + + // Spawn Accept Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_ACCEPT, sendermac, optlen, opt); + } + } + } + } + } + } +} + +/** +* Handle Cancel Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnCancelPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, int32_t length) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // Get Parent + SceNetAdhocMatchingMemberInternal * parent = findParent(context); + + // Get Outgoing Join Request + SceNetAdhocMatchingMemberInternal * request = findOutgoingRequest(context); + + // Get P2P Partner + SceNetAdhocMatchingMemberInternal * p2p = findP2P(context); + + // Interest Condition fulfilled + if (peer != NULL) + { + // Complete Packet Header available + if (length >= 5) + { + // Extract Optional Data Length + int optlen = 0; memcpy(&optlen, context->rxbuf + 1, sizeof(optlen)); + + // Complete Valid Packet available + if (optlen >= 0 && length >= (5 + optlen)) + { + // Set Default Null Data + void * opt = NULL; + + // Extract Optional Data Pointer + if (optlen > 0) opt = context->rxbuf + 5; + + // Child Mode + if (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD) + { + // Join Request denied + if (request == peer) + { + // Spawn Deny Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_DENY, sendermac, optlen, opt); + + // Delete Peer from List + deletePeer(context, peer); + } + + // Kicked from Room + else if (parent == peer) + { + // Iterate Peers + SceNetAdhocMatchingMemberInternal * item = context->peerlist; for (; item != NULL; item = item->next) + { + // Established Peer + if (item->state == PSP_ADHOC_MATCHING_PEER_CHILD || item->state == PSP_ADHOC_MATCHING_PEER_PARENT) + { + // Spawn Leave / Kick Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_LEAVE, &item->mac, optlen, opt); + } + } + + // Delete Peer from List + clearPeerList(context); + } + } + + // Parent Mode + else if (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT) + { + // Cancel Join Request + if (peer->state == PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST) + { + // Spawn Request Cancel Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_CANCEL, sendermac, optlen, opt); + + // Delete Peer from List + deletePeer(context, peer); + } + + // Leave Room + else if (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) + { + // Spawn Leave / Kick Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_LEAVE, sendermac, optlen, opt); + + // Delete Peer from List + deletePeer(context, peer); + } + } + + // P2P Mode + else + { + // Join Request denied + if (request == peer) + { + // Spawn Deny Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_DENY, sendermac, optlen, opt); + + // Delete Peer from List + deletePeer(context, peer); + } + + // Kicked from Room + else if (p2p == peer) + { + // Spawn Leave / Kick Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_LEAVE, sendermac, optlen, opt); + + // Delete Peer from List + deletePeer(context, peer); + } + + // Cancel Join Request + else if (peer->state == PSP_ADHOC_MATCHING_PEER_INCOMING_REQUEST) + { + // Spawn Request Cancel Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_CANCEL, sendermac, optlen, opt); + + // Delete Peer from List + deletePeer(context, peer); + } + } + } + } + } +} + +/** +* Handle Bulk Data Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnBulkDataPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, int32_t length) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // Established Peer + if (peer != NULL && ( + (context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) || + (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && (peer->state == PSP_ADHOC_MATCHING_PEER_CHILD || peer->state == PSP_ADHOC_MATCHING_PEER_PARENT)) || + (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && peer->state == PSP_ADHOC_MATCHING_PEER_P2P))) + { + // Complete Packet Header available + if (length > 5) + { + // Extract Data Length + int datalen = 0; memcpy(&datalen, context->rxbuf + 1, sizeof(datalen)); + + // Complete Valid Packet available + if (datalen > 0 && length >= (5 + datalen)) + { + // Extract Data + void * data = context->rxbuf + 5; + + // Spawn Data Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_DATA, sendermac, datalen, data); + } + } + } +} + +/** +* Handle Birth Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnBirthPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, uint32_t length) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // Valid Circumstances + if (peer != NULL && context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && peer == findParent(context)) + { + // Complete Packet available + if (length >= (1 + sizeof(SceNetEtherAddr))) + { + // Extract Child MAC + SceNetEtherAddr mac; + memcpy(&mac, context->rxbuf + 1, sizeof(SceNetEtherAddr)); + + // Allocate Memory (If this fails... we are fucked.) + SceNetAdhocMatchingMemberInternal * sibling = (SceNetAdhocMatchingMemberInternal *)malloc(sizeof(SceNetAdhocMatchingMemberInternal)); + + // Allocated Memory + if (sibling != NULL) + { + // Clear Memory + memset(sibling, 0, sizeof(SceNetAdhocMatchingMemberInternal)); + + // Save MAC Address + sibling->mac = mac; + + // Set Peer State + sibling->state = PSP_ADHOC_MATCHING_PEER_CHILD; + + // Initialize Ping Timer + peer->lastping = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; + + peerlock.lock(); + + // Link Peer + sibling->next = context->peerlist; + context->peerlist = sibling; + + peerlock.unlock(); + + // Spawn Established Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_ESTABLISHED, &sibling->mac, 0, NULL); + } + } + } +} + +/** +* Handle Death Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +* @param length Packet Length +*/ +void actOnDeathPacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac, uint32_t length) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // Valid Circumstances + if (peer != NULL && context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && peer == findParent(context)) + { + // Complete Packet available + if (length >= (1 + sizeof(SceNetEtherAddr))) + { + // Extract Child MAC + SceNetEtherAddr mac; + memcpy(&mac, context->rxbuf + 1, sizeof(SceNetEtherAddr)); + + // Find Peer + SceNetAdhocMatchingMemberInternal * deadkid = findPeer(context, &mac); + + // Valid Sibling + if (deadkid->state == PSP_ADHOC_MATCHING_PEER_CHILD) + { + // Spawn Leave Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_LEAVE, &mac, 0, NULL); + + // Delete Peer + deletePeer(context, deadkid); + } + } + } +} + +/** +* Handle Bye Packet +* @param context Matching Context Pointer +* @param sendermac Packet Sender MAC +*/ +void actOnByePacket(SceNetAdhocMatchingContext * context, SceNetEtherAddr * sendermac) +{ + // Find Peer + SceNetAdhocMatchingMemberInternal * peer = findPeer(context, sendermac); + + // We know this guy + if (peer != NULL) + { + // P2P or Child Bye + if ((context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) || + (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && peer->state == PSP_ADHOC_MATCHING_PEER_CHILD) || + (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && peer->state == PSP_ADHOC_MATCHING_PEER_P2P)) + { + // Spawn Leave / Kick Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_BYE, sendermac, 0, NULL); + + // Delete Peer + deletePeer(context, peer); + } + + // Parent Bye + else if (context->mode == PSP_ADHOC_MATCHING_MODE_CHILD && peer->state == PSP_ADHOC_MATCHING_PEER_PARENT) + { + // Iterate Peers + SceNetAdhocMatchingMemberInternal * item = context->peerlist; for (; item != NULL; item = item->next) + { + // Established Peer + if (item->state == PSP_ADHOC_MATCHING_PEER_CHILD || item->state == PSP_ADHOC_MATCHING_PEER_PARENT) + { + // Spawn Leave / Kick Event + spawnLocalEvent(context, PSP_ADHOC_MATCHING_EVENT_BYE, &item->mac, 0, NULL); + } + } + + // Delete Peer from List + clearPeerList(context); + } + } +} + + +/** +* Matching Event Dispatcher Thread +* @param args sizeof(SceNetAdhocMatchingContext *) +* @param argp SceNetAdhocMatchingContext * +* @return Exit Point is never reached... +*/ +int matchingEventThread(int matchingId) +{ + u32 bufLen = 0; + u32 bufAddr = 0; + + // Multithreading Lock + peerlock.lock(); + // Cast Context + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + // Multithreading Unlock + peerlock.unlock(); + + // Log Startup + INFO_LOG(SCENET, "EventLoop: Begin of EventLoop[%i] Thread", matchingId); + + // Run while needed... + if (context != NULL) { + //static u32_le args[5] = { 0, 0, 0, 0, 0 }; // Need to be global/static so it can be accessed from a different thread + u32_le * args = context->handlerArgs; + + while (context->eventRunning) // (context->eventThread.get_id() != NULL) + { + // Messages on Stack ready for processing + if (context->event_stack != NULL) + { + // Claim Stack + context->eventlock->lock(); + + // Iterate Message List + ThreadMessage * msg = context->event_stack; for (; msg != NULL; msg = msg->next) + { + // Default Optional Data + void * opt = NULL; + + // Grab Optional Data + if (msg->optlen > 0) opt = ((u8 *)msg) + sizeof(ThreadMessage); //&msg[1] + + // Log Matching Events + if (msg->opcode >= 0) { + char buf[16]; + INFO_LOG(SCENET, "EventLoop[%d]: Matching Event [%d=%s] OptSize=%d", matchingId, msg->opcode, getMatchingEventStr(msg->opcode, buf), msg->optlen); + } + + context->eventlock->unlock(); // Unlock to prevent race-condition with other threads due to recursive lock + // Call Event Handler + //context->handler(context->id, msg->opcode, &msg->mac, msg->optlen, opt); + // Notify Event Handlers + notifyMatchingHandler(context, msg, opt, bufAddr, bufLen, args); + context->eventlock->lock(); // Lock again + } + + // Clear Event Message Stack + clearStack(context, PSP_ADHOC_MATCHING_EVENT_STACK); + + // Free Stack + context->eventlock->unlock(); + } + + // Share CPU Time + sleep_ms(1); //10 //sceKernelDelayThread(10000); + + // Don't do anything if it's paused, otherwise the log will be flooded + while (Core_IsStepping() && context->eventRunning) sleep_ms(1); + } + + // Process Last Messages + if (context->event_stack != NULL) + { + // Claim Stack + context->eventlock->lock(); + + // Iterate Message List + ThreadMessage * msg = context->event_stack; for (; msg != NULL; msg = msg->next) + { + // Default Optional Data + void * opt = NULL; + + // Grab Optional Data + if (msg->optlen > 0) opt = ((u8 *)msg) + sizeof(ThreadMessage); //&msg[1] + + INFO_LOG(SCENET, "EventLoop[%d]: Matching Event [EVENT=%d]\n", matchingId, msg->opcode); + + context->eventlock->unlock(); + // Original Call Event Handler + //context->handler(context->id, msg->opcode, &msg->mac, msg->optlen, opt); + // Notify Event Handlers + notifyMatchingHandler(context, msg, opt, bufAddr, bufLen, args); + context->eventlock->lock(); + } + + // Clear Event Message Stack + clearStack(context, PSP_ADHOC_MATCHING_EVENT_STACK); + + // Free Stack + context->eventlock->unlock(); + } + + // Delete Pointer Reference (and notify caller about finished cleanup) + //context->eventThread = NULL; + } + + // Log Shutdown + INFO_LOG(SCENET, "EventLoop: End of EventLoop[%i] Thread", matchingId); + + // Free memory + if (Memory::IsValidAddress(bufAddr)) userMemory.Free(bufAddr); + + // Return Zero to shut up Compiler (never reached anyway) + return 0; +} + +/** +* Matching IO Handler Thread +* @param args sizeof(SceNetAdhocMatchingContext *) +* @param argp SceNetAdhocMatchingContext * +* @return Exit Point is never reached... +*/ +int matchingInputThread(int matchingId) +{ + // Multithreading Lock + peerlock.lock(); + // Cast Context + SceNetAdhocMatchingContext * context = findMatchingContext(matchingId); + // Multithreading Unlock + peerlock.unlock(); + + // Last Ping + u64_le lastping = 0; + + // Last Hello + u64_le lasthello = 0; + + u64_le now; + + // Log Startup + INFO_LOG(SCENET, "InputLoop: Begin of InputLoop[%i] Thread", matchingId); + + // Run while needed... + if (context != NULL) { + while (context->inputRunning) + { + now = CoreTiming::GetGlobalTimeUsScaled(); //real_time_now()*1000000.0; + + // Hello Message Sending Context with unoccupied Slots + if ((context->mode == PSP_ADHOC_MATCHING_MODE_PARENT && (countChildren(context) < (context->maxpeers - 1))) || (context->mode == PSP_ADHOC_MATCHING_MODE_P2P && findP2P(context) == NULL)) + { + // Hello Message Broadcast necessary because of Hello Interval + if (context->hello_int > 0) + if ((now - lasthello) >= context->hello_int) + { + // Broadcast Hello Message + broadcastHelloMessage(context); + + // Update Hello Timer + lasthello = now; + } + } + + // Ping Required + if (context->keepalive_int > 0) + if ((now - lastping) >= context->keepalive_int) + { + // Broadcast Ping Message + broadcastPingMessage(context); + + // Update Ping Timer + lastping = now; + } + + // Messages on Stack ready for processing + if (context->input_stack != NULL) + { + // Claim Stack + context->inputlock->lock(); + + // Iterate Message List + ThreadMessage * msg = context->input_stack; + for (; msg != NULL; msg = msg->next) + { + // Default Optional Data + void * opt = NULL; + + // Grab Optional Data + if (msg->optlen > 0) opt = ((u8 *)msg) + sizeof(ThreadMessage); + + context->inputlock->unlock(); // Unlock to prevent race condition when locking peerlock + + // Send Accept Packet + if (msg->opcode == PSP_ADHOC_MATCHING_PACKET_ACCEPT) sendAcceptPacket(context, &msg->mac, msg->optlen, opt); + + // Send Join Packet + else if (msg->opcode == PSP_ADHOC_MATCHING_PACKET_JOIN) sendJoinPacket(context, &msg->mac, msg->optlen, opt); + + // Send Cancel Packet + else if (msg->opcode == PSP_ADHOC_MATCHING_PACKET_CANCEL) sendCancelPacket(context, &msg->mac, msg->optlen, opt); + + // Send Bulk Data Packet + else if (msg->opcode == PSP_ADHOC_MATCHING_PACKET_BULK) sendBulkDataPacket(context, &msg->mac, msg->optlen, opt); + + // Send Birth Packet + else if (msg->opcode == PSP_ADHOC_MATCHING_PACKET_BIRTH) sendBirthPacket(context, &msg->mac); + + // Cancel Bulk Data Transfer (does nothing as of now as we fire and forget anyway) // Do we need to check DeathPacket and BytePacket here? + // else if(msg->opcode == PSP_ADHOC_MATCHING_PACKET_BULK_ABORT) blabla; + + context->inputlock->lock(); // Lock again + } + + // Clear IO Message Stack + clearStack(context, PSP_ADHOC_MATCHING_INPUT_STACK); + + // Free Stack + context->inputlock->unlock(); + } + + // Receive PDP Datagram + SceNetEtherAddr sendermac; + uint16_t senderport; + int rxbuflen = context->rxbuflen; + context->socketlock->lock(); + int recvresult = sceNetAdhocPdpRecv(context->socket, &sendermac, &senderport, context->rxbuf, &rxbuflen, 0, ADHOC_F_NONBLOCK); + context->socketlock->unlock(); + + // Received Data from a Sender that interests us + if (recvresult == 0 && rxbuflen > 0 && context->port == senderport) + { + // Log Receive Success + if (context->rxbuf[0] > 1) { + char buf[16]; + INFO_LOG(SCENET, "InputLoop[%d]: Received %d Bytes (Opcode[%d]=%s)", matchingId, rxbuflen, context->rxbuf[0], getMatchingOpcodeStr(context->rxbuf[0], buf)); + } + + // Update Peer Timestamp + peerlock.lock(); + SceNetAdhocctlPeerInfo * peer = findFriend(&sendermac); + if (peer != NULL) { + now = CoreTiming::GetGlobalTimeUsScaled(); + u64_le delta = now - peer->last_recv; + DEBUG_LOG(SCENET, "Timestamp Delta: %llu (%llu - %llu)", delta, now, peer->last_recv); + if (/*context->rxbuf[0] > 0 &&*/ peer->last_recv != 0) peer->last_recv = now; // - context->keepalive_int; // May need to deduce by ping interval to prevent Dissidia 012 unable to see other players (ie. disappearing issue) + } + peerlock.unlock(); + + // Ping Packet + if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_PING) actOnPingPacket(context, &sendermac); + + // Hello Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_HELLO) actOnHelloPacket(context, &sendermac, rxbuflen); + + // Join Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_JOIN) actOnJoinPacket(context, &sendermac, rxbuflen); + + // Accept Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_ACCEPT) actOnAcceptPacket(context, &sendermac, rxbuflen); + + // Cancel Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_CANCEL) actOnCancelPacket(context, &sendermac, rxbuflen); + + // Bulk Data Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_BULK) actOnBulkDataPacket(context, &sendermac, rxbuflen); + + // Birth Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_BIRTH) actOnBirthPacket(context, &sendermac, rxbuflen); + + // Death Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_DEATH) actOnDeathPacket(context, &sendermac, rxbuflen); + + // Bye Packet + else if (context->rxbuf[0] == PSP_ADHOC_MATCHING_PACKET_BYE) actOnByePacket(context, &sendermac); + + // Ignore Incoming Trash Data + } + + // Handle Peer Timeouts + handleTimeout(context); + + // Share CPU Time + sleep_ms(1); //10 //sceKernelDelayThread(10000); + + // Don't do anything if it's paused, otherwise the log will be flooded + while (Core_IsStepping() && context->inputRunning) sleep_ms(1); + } + + // Send Bye Messages + sendByePacket(context); + + // Free Peer List Buffer + clearPeerList(context); //deleteAllMembers(context); + + // Delete Pointer Reference (and notify caller about finished cleanup) + //context->inputThread = NULL; + } + + // Log Shutdown + INFO_LOG(SCENET, "InputLoop: End of InputLoop[%i] Thread", matchingId); + + // Terminate Thread + //sceKernelExitDeleteThread(0); + + // Return Zero to shut up Compiler (never reached anyway) + return 0; +} diff --git a/Core/MIPS/MIPSCodeUtils.h b/Core/MIPS/MIPSCodeUtils.h index 3df69ad397..e315226a9f 100644 --- a/Core/MIPS/MIPSCodeUtils.h +++ b/Core/MIPS/MIPSCodeUtils.h @@ -23,6 +23,7 @@ // Invalid branch target address #define INVALIDTARGET 0xFFFFFFFF +#define MIPS_MAKE_B(offs) (0x10000000 | ((offs) & 0xFFFF)) #define MIPS_MAKE_J(addr) (0x08000000 | ((addr)>>2)) #define MIPS_MAKE_JAL(addr) (0x0C000000 | ((addr)>>2)) #define MIPS_MAKE_JR_RA() (0x03e00008)