Merge pull request #13183 from hrydgard/upnp-fixes-ANR2ME

UPnP and miscellaneous fixes, extracted from #13132 by ANR2ME
This commit is contained in:
Henrik Rydgård authored and GitHub committed 2020-07-23 01:35:35 +02:00
commit 9f88a8835d
12 files changed
+328 -222

No files matched your search

+3 -1
View File
@@ -957,8 +957,10 @@ static ConfigSetting networkSettings[] = {
ConfigSetting("EnableAdhocServer", &g_Config.bEnableAdhocServer, false, true, true),
ConfigSetting("proAdhocServer", &g_Config.proAdhocServer, "myneighborsushicat.com", true, true),
ConfigSetting("PortOffset", &g_Config.iPortOffset, 0, true, true),
ConfigSetting("EnableUPnP", &g_Config.bEnableUPnP, false, true, true),
ConfigSetting("MinTimeout", &g_Config.iMinTimeout, 1, true, true),
ConfigSetting("TCPNoDelay", &g_Config.bTCPNoDelay, false, true, true),
ConfigSetting("EnableUPnP", &g_Config.bEnableUPnP, false, true, true),
ConfigSetting("UPnPUseOriginalPort", &g_Config.bUPnPUseOriginalPort, true, true, true),
ConfigSetting("EnableNetworkChat", &g_Config.bEnableNetworkChat, false, true, true),
ConfigSetting("ChatButtonPosition",&g_Config.iChatButtonPosition,BOTTOM_LEFT,true,true),
+2
View File
@@ -411,7 +411,9 @@ public:
std::string proAdhocServer;
bool bEnableWlan;
bool bEnableAdhocServer;
bool bTCPNoDelay;
bool bEnableUPnP;
bool bUPnPUseOriginalPort;
int iPortOffset;
int iMinTimeout;
int iWlanAdhocChannel;
+33 -14
View File
@@ -73,6 +73,7 @@ std::string message = "";
bool chatScreenVisible = false;
bool updateChatScreen = false;
int newChat = 0;
bool isOriPort = false;
bool isLocalServer = false;
sockaddr LocalhostIP;
sockaddr LocalIP;
@@ -82,11 +83,7 @@ bool isLocalMAC(const SceNetEtherAddr * addr) {
SceNetEtherAddr saddr;
getLocalMac(&saddr);
// Compare MAC Addresses
int match = memcmp((const void *)addr, (const void *)&saddr, ETHER_ADDR_LEN);
// Return Result
return (match == 0);
return (memcmp((const void*)addr, (const void*)&saddr, ETHER_ADDR_LEN) == 0);
}
bool isPDPPortInUse(uint16_t port) {
@@ -163,7 +160,7 @@ void addFriend(SceNetAdhocctlConnectPacketS2C * packet) {
if (peer != NULL) {
char tmpmac[18];
u32 tmpip = packet->ip;
WARN_LOG(SCENET, "Friend Peer Already Existed! Updating [%s][%s][%s]", packet->name.data, mac2str(&packet->mac, tmpmac), inet_ntoa(*(struct in_addr*)&tmpip)); //inet_ntoa(*(in_addr*)&packet->ip)
WARN_LOG(SCENET, "Friend Peer Already Existed! Updating [%s][%s][%s]", mac2str(&packet->mac, tmpmac), inet_ntoa(*(struct in_addr*)&tmpip), packet->name.data); //inet_ntoa(*(in_addr*)&packet->ip)
peer->nickname = packet->name;
peer->mac_addr = packet->mac;
peer->ip_addr = packet->ip;
@@ -1010,7 +1007,7 @@ void AfterMatchingMipsCall::run(MipsCall &call) {
u32 v0 = currentMIPS->r[MIPS_REG_V0];
if (__IsInInterrupt()) ERROR_LOG(SCENET, "AfterMatchingMipsCall::run [ID=%i][Event=%d] is Returning Inside an Interrupt!", contextID, EventID);
if (Memory::IsValidAddress(bufAddr)) userMemory.Free(bufAddr);
SetMatchingInCallback(context, false);
//SetMatchingInCallback(context, false);
DEBUG_LOG(SCENET, "AfterMatchingMipsCall::run [ID=%i][Event=%d] [cbId: %u][retV0: %08x]", contextID, EventID, call.cbId, v0);
//call.setReturnValue(v0);
}
@@ -1303,13 +1300,11 @@ int friendFinder(){
// Cast Packet
SceNetAdhocctlConnectPacketS2C * packet = (SceNetAdhocctlConnectPacketS2C *)rx;
DEBUG_LOG(SCENET, "FriendFinder: OPCODE_CONNECT");
// Fix strings with null-terminated
packet->name.data[ADHOCCTL_NICKNAME_LEN - 1] = 0;
// Log Incoming Peer
INFO_LOG(SCENET, "Incoming Peer Data...");
INFO_LOG(SCENET, "FriendFinder: Incoming OPCODE_CONNECT [%s][%s][%s]", mac2str(&packet->mac), inet_ntoa(*(in_addr*)&packet->ip), packet->name.data);
// Add User
addFriend(packet);
@@ -1604,6 +1599,33 @@ uint32_t getLocalIp(int sock) {
return localAddr.sin_addr.s_addr;
}
static std::vector<std::pair<uint32_t, uint32_t>> InitPrivateIPRanges() {
struct sockaddr_in saNet, saMask;
std::vector<std::pair<uint32_t, uint32_t>> ip_ranges;
if (1 == inet_pton(AF_INET, "192.168.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.255.0.0", &(saMask.sin_addr)))
ip_ranges.push_back({saNet.sin_addr.s_addr, saMask.sin_addr.s_addr});
if (1 == inet_pton(AF_INET, "172.16.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.240.0.0", &(saMask.sin_addr)))
ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr });
if (1 == inet_pton(AF_INET, "10.0.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.0.0.0", &(saMask.sin_addr)))
ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr });
if (1 == inet_pton(AF_INET, "127.0.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.0.0.0", &(saMask.sin_addr)))
ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr });
if (1 == inet_pton(AF_INET, "169.254.0.0", &(saNet.sin_addr)) && 1 == inet_pton(AF_INET, "255.255.0.0", &(saMask.sin_addr)))
ip_ranges.push_back({ saNet.sin_addr.s_addr, saMask.sin_addr.s_addr });
return ip_ranges;
}
bool isPrivateIP(uint32_t ip) {
static const std::vector<std::pair<uint32_t, uint32_t>> ip_ranges = InitPrivateIPRanges();
for (auto ipRange : ip_ranges) {
if ((ip & ipRange.second) == (ipRange.first & ipRange.second)) // We can just use ipRange.first directly if it's already correctly formatted
return true;
}
return false;
}
void getLocalMac(SceNetEtherAddr * addr){
// Read MAC Address from config
uint8_t mac[ETHER_ADDR_LEN] = {0};
@@ -1859,10 +1881,7 @@ int initNetwork(SceNetAdhocctlAdhocId *adhoc_id){
}
bool isBroadcastMAC(const SceNetEtherAddr * addr) {
// Broadcast MAC
if (memcmp(addr->data, "\xFF\xFF\xFF\xFF\xFF\xFF", ETHER_ADDR_LEN) == 0) return true;
// Normal MAC
return false;
return (memcmp(addr->data, "\xFF\xFF\xFF\xFF\xFF\xFF", ETHER_ADDR_LEN) == 0);
}
bool resolveIP(uint32_t ip, SceNetEtherAddr * mac) {
+10 -2
View File
@@ -479,12 +479,14 @@ typedef struct SceNetAdhocMatchingContext {
SceUID matching_thid;
// Event Caller Thread
std::thread eventThread; // s32_le event_thid;
std::thread eventThread;
//s32_le event_thid;
bool eventRunning = false;
bool IsMatchingInCB = false;
// IO Handler Thread
std::thread inputThread; // s32_le input_thid;
std::thread inputThread;
//s32_le input_thid;
bool inputRunning = false;
// Event Caller Thread Message Stack
@@ -844,6 +846,7 @@ extern SceNetAdhocPtpStat * ptp[255];
extern uint16_t portOffset;
extern uint32_t minSocketTimeoutUS;
extern bool isOriPort;
extern bool isLocalServer;
extern sockaddr LocalhostIP; // Used to differentiate localhost IP on multiple-instance
extern sockaddr LocalIP; // IP of Network Adapter used to connect to Adhoc Server (LAN/WAN)
@@ -1159,6 +1162,11 @@ int getActivePeerCount(const bool excludeTimedout = true);
int getLocalIp(sockaddr_in * SocketAddress);
uint32_t getLocalIp(int sock);
/*
* Check if an IP (big-endian/network order) is Private or Public IP
*/
bool isPrivateIP(uint32_t ip);
/*
* Get UDP Socket Max Message Size
*/
+2 -2
View File
@@ -1685,13 +1685,13 @@ int proAdhocServerThread(int port) // (int argc, char * argv[])
INFO_LOG(SCENET, "AdhocServer: Listening for Connections on TCP Port %u", port); //SERVER_PORT
// Port forward
g_PortManager.Add(port, IP_PROTOCOL_TCP);
g_PortManager.Add(IP_PROTOCOL_TCP, port);
// Enter Server Loop
result = server_loop(server);
// Remove Port mapping
g_PortManager.Remove(port, IP_PROTOCOL_TCP);
g_PortManager.Remove(IP_PROTOCOL_TCP, port);
// Notify User
INFO_LOG(SCENET, "AdhocServer: Shutdown complete");
+25 -21
View File
@@ -118,6 +118,7 @@ static void __ResetInitNetLib() {
void __NetInit() {
// Windows: Assuming WSAStartup already called beforehand
portOffset = g_Config.iPortOffset;
isOriPort = g_Config.bEnableUPnP && g_Config.bUPnPUseOriginalPort;
minSocketTimeoutUS = g_Config.iMinTimeout * 1000UL;
InitLocalhostIP();
@@ -129,28 +130,24 @@ void __NetInit() {
// Only initialize when UPnP is enabled since it takes a few seconds to detect UPnP device (may affect people who don't have UPnP device)
if (g_Config.bEnableUPnP) {
g_PortManager.Init();
// TODO: May be we should initialize & cleanup somewhere else than here for PortManager to be used as general purpose for whatever port forwarding PPSSPP needed
g_PortManager.Initialize();
}
__ResetInitNetLib();
}
void __NetShutdown() {
// Checks to avoid confusing logspam
if (netAdhocctlInited) sceNetAdhocctlTerm();
if (netAdhocInited) sceNetAdhocTerm();
if (netApctlInited) sceNetApctlTerm();
if (netInetInited) sceNetInetTerm();
if (netInited) sceNetTerm();
// Network Cleanup
Net_Term();
__ResetInitNetLib();
if (g_Config.bEnableUPnP) {
// Since PortManager supposed to be general purpose for whatever port forwarding PPSSPP needed, may be we shouldn't clear & restore ports in here? it will be cleared and restored by PortManager's destructor when exiting PPSSPP anyway
if (g_PortManager.GetInitState() == UPNP_INITSTATE_DONE) {
g_PortManager.Clear();
g_PortManager.Restore();
g_PortManager.Deinit();
g_PortManager.Terminate();
}
}
@@ -219,13 +216,14 @@ static inline void FreeUser(u32 &addr) {
addr = 0;
}
static u32 sceNetTerm() {
u32 Net_Term() {
// May also need to Terminate netAdhocctl and netAdhoc to free some resources & threads, since the game (ie. GTA:VCS, Wipeout Pulse, etc) might not called them before calling sceNetTerm and causing them to behave strangely on the next sceNetInit & sceNetAdhocInit
if (netAdhocctlInited) sceNetAdhocctlTerm();
if (netAdhocInited) sceNetAdhocTerm();
NetAdhocctl_Term();
NetAdhoc_Term();
if (netApctlInited) sceNetApctlTerm();
if (netInetInited) sceNetInetTerm();
// TODO: Not implemented yet
//sceNetApctl_Term();
//NetInet_Term();
// Library is initialized
if (netInited) {
@@ -246,15 +244,21 @@ static u32 sceNetTerm() {
// Library shutdown
}
WARN_LOG(SCENET, "sceNetTerm()");
netInited = false;
FreeUser(netPoolAddr);
FreeUser(netThread1Addr);
FreeUser(netThread2Addr);
netInited = false;
return 0;
}
static u32 sceNetTerm() {
WARN_LOG(SCENET, "sceNetTerm()");
int retval = Net_Term();
// Give time to make sure everything are cleaned up
hleDelayResult(0, "give time to init/cleanup", adhocEventDelayMS * 1000);
return 0;
hleDelayResult(retval, "give time to init/cleanup", adhocEventDelayMS * 1000);
return retval;
}
/*
@@ -270,7 +274,7 @@ static int sceNetInit(u32 poolSize, u32 calloutPri, u32 calloutStack, u32 netini
// TODO: The correct behavior is actually to allocate more and leak the other threads/pool.
// But we reset here for historic reasons (GTA:VCS potentially triggers this.)
if (netInited)
sceNetTerm(); // This cleanup attempt might not worked when SaveState were loaded in the middle of multiplayer game and re-entering multiplayer, thus causing memory leaks & wasting binded ports. May be we shouldn't save/load "Inited" vars on SaveState?
Net_Term(); // This cleanup attempt might not worked when SaveState were loaded in the middle of multiplayer game and re-entering multiplayer, thus causing memory leaks & wasting binded ports. May be we shouldn't save/load "Inited" vars on SaveState?
if (poolSize == 0) {
return hleLogError(SCENET, SCE_KERNEL_ERROR_ILLEGAL_MEMSIZE, "invalid pool size");
+2
View File
@@ -109,6 +109,8 @@ void __NetInit();
void __NetShutdown();
void __NetDoState(PointerWrap &p);
u32 Net_Term();
int sceNetInetPoll(void *fds, u32 nfds, int timeout);
int sceNetInetTerm();
int sceNetApctlTerm();
+191 -136
View File
@@ -377,7 +377,7 @@ static int sceNetAdhocPdpCreate(const char *mac, int port, int bufferSize, u32 u
// Fill in Data
internal->id = usocket;
internal->laddr = *saddr;
internal->lport = port; //getLocalPort(usocket) - portOffset; //should use the port given to the socket (in case it's UNUSED_PORT port) isn't?
internal->lport = port; //getLocalPort(usocket) - portOffset;
internal->rcv_sb_cc = bufferSize;
// Link Socket to Translator ID
@@ -385,7 +385,7 @@ static int sceNetAdhocPdpCreate(const char *mac, int port, int bufferSize, u32 u
// Forward Port on Router
//sceNetPortOpen("UDP", port);
g_PortManager.Add(port + portOffset, IP_PROTOCOL_UDP);
g_PortManager.Add(IP_PROTOCOL_UDP, isOriPort ? port : port + portOffset, port + portOffset);
// Success
return i + 1;
@@ -519,6 +519,9 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int
// Get Peer IP
if (resolveMAC((SceNetEtherAddr *)daddr, (uint32_t *)&target.sin_addr.s_addr)) {
// Some games (ie. PSP2) might try to talk to it's self, not sure if they talked through WAN or LAN when using public Adhoc Server tho
target.sin_port = htons(dport + ((isOriPort && !isPrivateIP(target.sin_addr.s_addr)) ? 0 : portOffset));
// Acquire Network Lock
//_acquireNetworkLock();
@@ -582,13 +585,14 @@ static int sceNetAdhocPdpSend(int id, const char *mac, u32 port, void *data, int
SceNetAdhocctlPeerInfo * peer = friends;
for (; peer != NULL; peer = peer->next) {
// Does Skipping sending to timed out friends could cause desync when players moving group at the time MP game started?
//if (peer->last_recv == 0) continue;
if (peer->last_recv == 0)
continue;
// Fill in Target Structure
sockaddr_in target;
target.sin_family = AF_INET;
target.sin_addr.s_addr = peer->ip_addr;
target.sin_port = htons(dport + portOffset);
target.sin_port = htons(dport + ((isOriPort && !isPrivateIP(peer->ip_addr)) ? 0 : portOffset));
int sent = sendto(socket->id, (const char *)data, len, 0, (sockaddr *)&target, sizeof(target));
int error = errno;
@@ -733,10 +737,10 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void *
*sport = ntohs(sin.sin_port) - portOffset;
// Update last recv timestamp, may cause disconnection not detected properly tho
/*peerlock.lock();
peerlock.lock();
auto peer = findFriend(&mac);
if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled();
peerlock.unlock();*/
peerlock.unlock();
}
// Free Network Lock
@@ -749,9 +753,9 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void *
if (flag == 0) {
// Simulate blocking behaviour with non-blocking socket
uint32_t starttime = (uint32_t)(real_time_now() * 1000.0);
uint32_t starttime = (uint32_t)(real_time_now() * 1000000.0);
// Wait for Connection. On Windows: recvfrom on UDP can get error WSAECONNRESET when previous sendto's destination is unreachable (or destination port is not bound), may need to disable SIO_UDP_CONNRESET
while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && (connectInProgress(error) || error == ECONNRESET)) {
while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && (connectInProgress(error) || error == ECONNRESET)) {
received = recvfrom(socket->id, (char*)buf, *len, 0, (sockaddr*)&sin, &sinlen);
error = errno;
// Wait 1ms
@@ -782,10 +786,10 @@ static int sceNetAdhocPdpRecv(int id, void *addr, void * port, void *buf, void *
*len = received; // Kurok homebrew seems to use the new value of len than returned value as data length
// Update last recv timestamp, may cause disconnection not detected properly tho
/*peerlock.lock();
peerlock.lock();
auto peer = findFriend(&mac);
if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled();
peerlock.unlock();*/
peerlock.unlock();
// Free Network Lock
//_freeNetworkLock();
@@ -951,27 +955,13 @@ int sceNetAdhocPollSocket(u32 socketStructAddr, int count, int timeout, int nonb
return ERROR_NET_ADHOC_NOT_INITIALIZED;
}
/**
* Adhoc Emulator PDP Socket Delete
* @param id Socket File Descriptor
* @param flag Bitflags (Unused)
* @return 0 on success or... ADHOC_INVALID_ARG, ADHOC_NOT_INITIALIZED, ADHOC_INVALID_SOCKET_ID
*/
static int sceNetAdhocPdpDelete(int id, int unknown) {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
INFO_LOG(SCENET, "sceNetAdhocPdpDelete(%d, %d) at %08x", id, unknown, currentMIPS->pc);
/*
if (!g_Config.bEnableWlan) {
return 0;
}
*/
int NetAdhocPdp_Delete(int id, int unknown) {
// Library is initialized
if (netAdhocInited) {
// Valid Arguments
if (id > 0 && id <= 255) {
// Cast Socket
SceNetAdhocPdpStat * sock = pdp[id - 1];
SceNetAdhocPdpStat* sock = pdp[id - 1];
// Valid Socket
if (sock != NULL) {
@@ -980,7 +970,7 @@ static int sceNetAdhocPdpDelete(int id, int unknown) {
// Remove Port Forward from Router
//sceNetPortClose("UDP", sock->lport);
//g_PortManager.Remove(sock->lport + portOffset, IP_PROTOCOL_UDP); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers
//g_PortManager.Remove(IP_PROTOCOL_UDP, isOriPort ? sock->lport : sock->lport + portOffset); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers
// Free Memory
free(sock);
@@ -1004,6 +994,24 @@ static int sceNetAdhocPdpDelete(int id, int unknown) {
return ERROR_NET_ADHOC_NOT_INITIALIZED;
}
/**
* Adhoc Emulator PDP Socket Delete
* @param id Socket File Descriptor
* @param flag Bitflags (Unused)
* @return 0 on success or... ADHOC_INVALID_ARG, ADHOC_NOT_INITIALIZED, ADHOC_INVALID_SOCKET_ID
*/
static int sceNetAdhocPdpDelete(int id, int unknown) {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
INFO_LOG(SCENET, "sceNetAdhocPdpDelete(%d, %d) at %08x", id, unknown, currentMIPS->pc);
/*
if (!g_Config.bEnableWlan) {
return 0;
}
*/
return NetAdhocPdp_Delete(id, unknown);
}
static int sceNetAdhocctlGetAdhocId(u32 productStructAddr) {
ERROR_LOG(SCENET, "UNIMPL sceNetAdhocctlGetAdhocId(%08x)", productStructAddr);
@@ -1227,12 +1235,7 @@ static u32 sceNetAdhocctlAddHandler(u32 handlerPtr, u32 handlerArg) {
return retval;
}
static u32 sceNetAdhocctlDisconnect() {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
char grpName[9] = { 0 };
memcpy(grpName, parameter.group_name.data, ADHOCCTL_GROUPNAME_LEN); // Copied to null-terminated var to prevent unexpected behaviour on Logs
INFO_LOG(SCENET, "sceNetAdhocctlDisconnect() at %08x [group=%s]", currentMIPS->pc, grpName);
u32 NetAdhocctl_Disconnect() {
// Library initialized
if (netAdhocctlInited) {
// Connected State (Adhoc Mode)
@@ -1250,7 +1253,7 @@ static u32 sceNetAdhocctlDisconnect() {
//_acquireNetworkLock();
// Send Disconnect Request Packet
int iResult = send(metasocket, (const char *)&opcode, 1, 0);
int iResult = send(metasocket, (const char*)&opcode, 1, 0);
if (iResult == SOCKET_ERROR) {
ERROR_LOG(SCENET, "Socket error (%i) when sending", errno);
}
@@ -1280,9 +1283,9 @@ static u32 sceNetAdhocctlDisconnect() {
// Multithreading 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)
notifyAdhocctlHandlers(ADHOCCTL_EVENT_DISCONNECT, 0);
notifyAdhocctlHandlers(ADHOCCTL_EVENT_DISCONNECT, 0);
hleCheckCurrentCallbacks();
// Return Success, some games might ignore returned value and always treat it as success, otherwise repeatedly calling this function
@@ -1293,6 +1296,15 @@ static u32 sceNetAdhocctlDisconnect() {
return 0; //ERROR_NET_ADHOC_NOT_INITIALIZED; // Wipeout Pulse will repeatedly calling this function if returned value is ERROR_NET_ADHOC_NOT_INITIALIZED
}
static u32 sceNetAdhocctlDisconnect() {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
char grpName[9] = { 0 };
memcpy(grpName, parameter.group_name.data, ADHOCCTL_GROUPNAME_LEN); // Copied to null-terminated var to prevent unexpected behaviour on Logs
INFO_LOG(SCENET, "sceNetAdhocctlDisconnect() at %08x [group=%s]", currentMIPS->pc, grpName);
return NetAdhocctl_Disconnect();
}
static u32 sceNetAdhocctlDelHandler(u32 handlerID) {
if (adhocctlHandlers.find(handlerID) != adhocctlHandlers.end()) {
adhocctlHandlers.erase(handlerID);
@@ -1304,14 +1316,11 @@ static u32 sceNetAdhocctlDelHandler(u32 handlerID) {
return 0;
}
int sceNetAdhocctlTerm() {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
INFO_LOG(SCENET, "sceNetAdhocctlTerm()");
//if (netAdhocMatchingInited) sceNetAdhocMatchingTerm();
int NetAdhocctl_Term() {
if (netAdhocctlInited) {
if (threadStatus != ADHOCCTL_STATE_DISCONNECTED) sceNetAdhocctlDisconnect();
if (threadStatus != ADHOCCTL_STATE_DISCONNECTED)
NetAdhocctl_Disconnect();
if (networkInited) {
// Terminate Adhoc Threads
friendFinderRunning = false;
@@ -1342,6 +1351,15 @@ int sceNetAdhocctlTerm() {
return 0;
}
int sceNetAdhocctlTerm() {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
INFO_LOG(SCENET, "sceNetAdhocctlTerm()");
//if (netAdhocMatchingInited) NetAdhocMatching_Term();
return NetAdhocctl_Term();
}
static int sceNetAdhocctlGetNameByAddr(const char *mac, u32 nameAddr) {
char tmpmac[18];
DEBUG_LOG(SCENET, "UNTESTED sceNetAdhocctlGetNameByAddr(%s, %08x)", mac2str((SceNetEtherAddr*)mac, tmpmac), nameAddr);
@@ -1350,10 +1368,9 @@ static int sceNetAdhocctlGetNameByAddr(const char *mac, u32 nameAddr) {
if (netAdhocctlInited)
{
// Valid Arguments
if (mac != NULL && nameAddr != 0)
if (mac != NULL && Memory::IsValidAddress(nameAddr))
{
SceNetAdhocctlNickname * nickname = NULL;
if (Memory::IsValidAddress(nameAddr)) nickname = (SceNetAdhocctlNickname *)Memory::GetPointer(nameAddr);
SceNetAdhocctlNickname * nickname = (SceNetAdhocctlNickname *)Memory::GetPointer(nameAddr);
// Get Local MAC Address
SceNetEtherAddr localmac;
getLocalMac(&localmac);
@@ -1666,12 +1683,12 @@ int sceNetAdhocctlCreateEnterGameModeMin(const char *group_name, int game_type,
return sceNetAdhocctlCreateEnterGameMode(group_name, game_type, num_members, membersAddr, timeout, flag); //0;
}
int sceNetAdhocTerm() {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup all the sockets right?
int NetAdhoc_Term() {
// Since Adhocctl & AdhocMatching uses Sockets & Threads we should terminate them also to release their resources
if (netAdhocMatchingInited) sceNetAdhocMatchingTerm();
if (netAdhocctlInited) sceNetAdhocctlTerm();
if (netAdhocMatchingInited)
NetAdhocMatching_Term();
if (netAdhocctlInited)
NetAdhocctl_Term();
// Library is initialized
if (netAdhocInited) {
@@ -1690,14 +1707,23 @@ int sceNetAdhocTerm() {
// Unload Internet Modules (Just keep it in memory... unloading crashes?!)
// if (_manage_modules != 0) sceUtilityUnloadModule(PSP_MODULE_NET_INET);
// Library shutdown
netAdhocInited = false;
return hleLogSuccessInfoI(SCENET, 0);
} else {
//return hleLogSuccessInfoI(SCENET, 0);
}
/*else {
// TODO: Reportedly returns SCE_KERNEL_ERROR_LWMUTEX_NOT_FOUND in some cases?
// Only seen returning 0 in tests.
return hleLogWarning(SCENET, 0, "already uninitialized");
}
}*/
return 0;
}
int sceNetAdhocTerm() {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup all the sockets right?
return hleLogSuccessInfoI(SCENET, NetAdhoc_Term());
}
static int sceNetAdhocGetPdpStat(u32 structSize, u32 structAddr) {
@@ -1870,6 +1896,7 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac,
}
SceNetEtherAddr* saddr = (SceNetEtherAddr*)srcmac;
SceNetEtherAddr* daddr = (SceNetEtherAddr*)dstmac;
bool isClient = false;
// Library is initialized
if (netAdhocInited) {
// Some games (ie. DBZ Shin Budokai 2) might be getting the saddr/srcmac content from SaveState and causing problems if current MAC is different :( So we try to fix it here
@@ -1880,6 +1907,7 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac,
if (saddr != NULL && isLocalMAC(saddr) && daddr != NULL && !isBroadcastMAC(daddr)) {
// Random Port required
if (sport == 0) {
isClient = true;
// Find unused Port
// while (sport == 0 || _IsPTPPortInUse(sport)) {
// // Generate Port Number
@@ -1912,7 +1940,7 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac,
setSockTimeout(tcpsocket, SO_SNDTIMEO, rexmt_int);
// Disable Nagle Algo to send immediately. Or may be we shouldn't disable Nagle since there is PtpFlush function?
//setSockNoDelay(tcpsocket, 1);
if (g_Config.bTCPNoDelay) setSockNoDelay(tcpsocket, 1);
// Binding Information for local Port
sockaddr_in addr;
@@ -1963,7 +1991,8 @@ static int sceNetAdhocPtpOpen(const char *srcmac, int sport, const char *dstmac,
// Add Port Forward to Router. We may not even need to forward this local port, since PtpOpen usually have port 0 (any port) as source port and followed by PtpConnect (which mean acting as Client), right?
//sceNetPortOpen("TCP", sport);
//g_PortManager.Add(sport + portOffset, IP_PROTOCOL_TCP);
if (!isClient)
g_PortManager.Add(IP_PROTOCOL_TCP, isOriPort ? sport : sport + portOffset, sport + portOffset);
// Return PTP Socket Pointer
return i + 1;
@@ -2067,10 +2096,10 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int
// Blocking Behaviour
if (!flag && newsocket == SOCKET_ERROR) {
// 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 == SOCKET_ERROR) && connectInProgress(error)) {
while ((timeout == 0 || ((uint32_t)(real_time_now()*1000000.0) - starttime) < (uint32_t)timeout) && (newsocket == SOCKET_ERROR) && connectInProgress(error)) {
// Accept Connection
newsocket = accept(socket->id, (sockaddr *)&peeraddr, &peeraddrlen);
error = errno;
@@ -2101,7 +2130,7 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int
setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(one));
// Disable Nagle Algo to send immediately. Or may be we shouldn't disable Nagle since there is PtpFlush function?
//setSockNoDelay(newsocket, 1);
if (g_Config.bTCPNoDelay) setSockNoDelay(newsocket, 1);
// Grab Local Address
if (getsockname(newsocket, (sockaddr *)&local, &locallen) == 0) {
@@ -2153,7 +2182,7 @@ static int sceNetAdhocPtpAccept(int id, u32 peerMacAddrPtr, u32 peerPortPtr, int
// Add Port Forward to Router. Or may be doesn't need to be forwarded since local port already accessible from outside if others were able to connect & get accepted at this point, right?
//sceNetPortOpen("TCP", internal->lport);
//g_PortManager.Add(internal->lport + portOffset, IP_PROTOCOL_TCP);
//g_PortManager.Add(IP_PROTOCOL_TCP, internal->lport + portOffset);
INFO_LOG(SCENET, "sceNetAdhocPtpAccept[%i->%i:%u]: Established (%s:%u)", id, i+1, internal->lport, inet_ntoa(peeraddr.sin_addr), internal->pport);
@@ -2234,6 +2263,9 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) {
// Grab Peer IP
if (resolveMAC(&socket->paddr, (uint32_t *)&sin.sin_addr.s_addr)) {
// Some games (ie. PSP2) might try to talk to it's self, not sure if they talked through WAN or LAN when using public Adhoc Server tho
sin.sin_port = htons(socket->pport + ((isOriPort && !isPrivateIP(sin.sin_addr.s_addr)) ? 0 : portOffset));
// Grab Nonblocking Flag
uint32_t nbio = getBlockingFlag(socket->id);
@@ -2245,7 +2277,7 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) {
}*/
// Connect Socket to Peer (Nonblocking)
// Fixme: The First Non-blocking POSIX connect will always returns EAGAIN/EWOULDBLOCK because it returns without waiting for ACK, But GvG Next Plus is treating non-blocking connect just like blocking connect, May be on a real PSP the first non-blocking sceNetAdhocPtpConnect can be successfull?
// NOTE: Based on what i read at stackoverflow, The First Non-blocking POSIX connect will always returns EAGAIN/EWOULDBLOCK because it returns without waiting for ACK/handshake, But GvG Next Plus is treating non-blocking PtpConnect just like blocking connect, May be on a real PSP the first non-blocking sceNetAdhocPtpConnect can be successfull?
int connectresult = connect(socket->id, (sockaddr *)&sin, sizeof(sin));
// Grab Error Code
@@ -2282,14 +2314,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);
}
@@ -2329,6 +2361,39 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) {
return ERROR_NET_ADHOC_NOT_INITIALIZED;
}
int NetAdhocPtp_Close(int id, int unknown) {
// Library is initialized
if (netAdhocInited) {
// Valid Arguments & Atleast one Socket
if (id > 0 && id <= 255 && ptp[id - 1] != NULL) {
// Cast Socket
SceNetAdhocPtpStat* socket = ptp[id - 1];
// Close Connection
closesocket(socket->id);
// Remove Port Forward from Router
//sceNetPortClose("TCP", socket->lport);
//g_PortManager.Remove(IP_PROTOCOL_TCP, isOriPort ? socket->lport : socket->lport + portOffset); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers
// Free Memory
free(socket);
// Free Reference
ptp[id - 1] = NULL;
// Success
return 0;
}
// Invalid Argument
return ERROR_NET_ADHOC_INVALID_SOCKET_ID;
}
// Library is uninitialized
return ERROR_NET_ADHOC_NOT_INITIALIZED;
}
/**
* Adhoc Emulator PTP Socket Closer
* @param id Socket File Descriptor
@@ -2337,39 +2402,11 @@ static int sceNetAdhocPtpConnect(int id, int timeout, int flag) {
*/
static int sceNetAdhocPtpClose(int id, int unknown) {
INFO_LOG(SCENET,"sceNetAdhocPtpClose(%d,%d) at %08x",id,unknown,currentMIPS->pc);
if (!g_Config.bEnableWlan) {
/*if (!g_Config.bEnableWlan) {
return 0;
}
// Library is initialized
if (netAdhocInited) {
// Valid Arguments & Atleast one Socket
if (id > 0 && id <= 255 && ptp[id - 1] != NULL) {
// Cast Socket
SceNetAdhocPtpStat * socket = ptp[id - 1];
// Close Connection
closesocket(socket->id);
// Remove Port Forward from Router
//sceNetPortClose("TCP", socket->lport);
//g_PortManager.Remove(socket->lport + portOffset, IP_PROTOCOL_TCP); // Let's not remove mapping in real-time as it could cause lags/disconnection when joining a room with slow routers
// Free Memory
free(socket);
// Free Reference
ptp[id - 1] = NULL;
// Success
return 0;
}
// Invalid Argument
return ERROR_NET_ADHOC_INVALID_SOCKET_ID;
}
}*/
// Library is uninitialized
return ERROR_NET_ADHOC_NOT_INITIALIZED;
return NetAdhocPtp_Close(id, unknown);
}
@@ -2435,7 +2472,7 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int
setSockTimeout(tcpsocket, SO_RCVTIMEO, rexmt_int);
// Disable Nagle Algo to send immediately. Or may be we shouldn't disable Nagle since there is PtpFlush function?
//setSockNoDelay(tcpsocket, 1);
if (g_Config.bTCPNoDelay) setSockNoDelay(tcpsocket, 1);
// Binding Information for local Port
sockaddr_in addr;
@@ -2488,7 +2525,7 @@ static int sceNetAdhocPtpListen(const char *srcmac, int sport, int bufsize, int
// Add Port Forward to Router
//sceNetPortOpen("TCP", sport);
g_PortManager.Add(sport + portOffset, IP_PROTOCOL_TCP);
g_PortManager.Add(IP_PROTOCOL_TCP, isOriPort ? sport : sport + portOffset, sport + portOffset);
// Return PTP Socket Pointer
return i + 1;
@@ -2672,9 +2709,9 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou
if (flag == 0) {
// Simulate blocking behaviour with non-blocking socket
uint32_t starttime = (uint32_t)(real_time_now() * 1000.0);
uint32_t starttime = (uint32_t)(real_time_now() * 1000000.0);
// Wait for Connection
while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && connectInProgress(error)) {
while ((timeout == 0 || ((uint32_t)(real_time_now() * 1000000.0) - starttime) < (uint32_t)timeout) && (received == SOCKET_ERROR) && connectInProgress(error)) {
received = recv(socket->id, (char*)buf, *len, 0);
error = errno;
// Wait 1ms
@@ -2696,10 +2733,10 @@ static int sceNetAdhocPtpRecv(int id, u32 dataAddr, u32 dataSizeAddr, int timeou
*len = received;
// Update last recv timestamp, may cause disconnection not detected properly tho
/*peerlock.lock();
peerlock.lock();
auto peer = findFriend(&socket->paddr);
if (peer != NULL) peer->last_recv = CoreTiming::GetGlobalTimeUsScaled();
peerlock.unlock();*/
peerlock.unlock();
char tmpmac[18];
DEBUG_LOG(SCENET, "sceNetAdhocPtpRecv[%i:%u]: Received %u bytes from %s:%u", id, socket->lport, received, mac2str(&socket->paddr, tmpmac), socket->pport);
@@ -2833,10 +2870,8 @@ int sceNetAdhocGetSocketAlert(int id, u32 flagPtr) {
return 0;
}
int sceNetAdhocMatchingStop(int matchingId) {
WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingStop(%i) at %08x", matchingId, currentMIPS->pc);
SceNetAdhocMatchingContext * item = findMatchingContext(matchingId);
int NetAdhocMatching_Stop(int matchingId) {
SceNetAdhocMatchingContext* item = findMatchingContext(matchingId);
if (item != NULL) {
item->inputRunning = false;
@@ -2878,17 +2913,21 @@ int sceNetAdhocMatchingStop(int matchingId) {
return 0;
}
int sceNetAdhocMatchingDelete(int matchingId) {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
int sceNetAdhocMatchingStop(int matchingId) {
WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingStop(%i) at %08x", matchingId, currentMIPS->pc);
return NetAdhocMatching_Stop(matchingId);
}
int NetAdhocMatching_Delete(int matchingId) {
// Previous Context Reference
SceNetAdhocMatchingContext * prev = NULL;
SceNetAdhocMatchingContext* prev = NULL;
// Multithreading Lock
peerlock.lock(); //contextlock.lock();
// Context Pointer
SceNetAdhocMatchingContext * item = contexts;
SceNetAdhocMatchingContext* item = contexts;
// Iterate contexts
for (; item != NULL; item = item->next) {
@@ -2902,7 +2941,7 @@ int sceNetAdhocMatchingDelete(int matchingId) {
// Stop it first if it's still running
if (item->running) {
sceNetAdhocMatchingStop(matchingId);
NetAdhocMatching_Stop(matchingId);
}
// Delete the Fake PSP Thread
//__KernelDeleteThread(item->matching_thid, SCE_KERNEL_ERROR_THREAD_TERMINATED, "AdhocMatching deleted");
@@ -2910,7 +2949,7 @@ int sceNetAdhocMatchingDelete(int matchingId) {
// Make sure nobody locking/using the socket
item->socketlock->lock();
// Delete the socket
sceNetAdhocPdpDelete(item->socket, 0); // item->connected = (sceNetAdhocPdpDelete(item->socket, 0) < 0);
NetAdhocPdp_Delete(item->socket, 0); // item->connected = (sceNetAdhocPdpDelete(item->socket, 0) < 0);
item->socketlock->unlock();
// Free allocated memories
free(item->hello);
@@ -2919,10 +2958,10 @@ int sceNetAdhocMatchingDelete(int matchingId) {
// Destroy locks
item->eventlock->lock(); // Make sure it's not locked when being deleted
item->eventlock->unlock();
delete item->eventlock;
delete item->eventlock;
item->inputlock->lock(); // Make sure it's not locked when being deleted
item->inputlock->unlock();
delete item->inputlock;
delete item->inputlock;
item->socketlock->lock(); // Make sure it's not locked when being deleted
item->socketlock->unlock();
delete item->socketlock;
@@ -2941,6 +2980,14 @@ int sceNetAdhocMatchingDelete(int matchingId) {
// Multithreading Unlock
peerlock.unlock(); //contextlock.unlock();
return 0;
}
int sceNetAdhocMatchingDelete(int matchingId) {
// WLAN might be disabled in the middle of successfull multiplayer, but we still need to cleanup right?
NetAdhocMatching_Delete(matchingId);
WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingDelete(%i) at %08x", matchingId, currentMIPS->pc);
// Give a little time to make sure everything are cleaned up before the following AdhocMatchingCreate, Not too long tho, otherwise Naruto Ultimate Ninja Heroes 3 will have an issue
@@ -2965,21 +3012,27 @@ int sceNetAdhocMatchingInit(u32 memsize) {
return 0;
}
int sceNetAdhocMatchingTerm() {
WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingTerm()");
// Should we cleanup all created matching contexts first? just in case there are games that doesn't delete them before calling this
int NetAdhocMatching_Term() {
if (netAdhocMatchingInited) {
// Delete all Matching contexts
SceNetAdhocMatchingContext* next = NULL;
SceNetAdhocMatchingContext * context = contexts;
SceNetAdhocMatchingContext* context = contexts;
while (context != NULL) {
next = context->next;
//if (context->running) sceNetAdhocMatchingStop(context->id);
sceNetAdhocMatchingDelete(context->id);
//if (context->running) NetAdhocMatching_Stop(context->id);
NetAdhocMatching_Delete(context->id);
context = next;
}
contexts = NULL;
}
return 0;
}
int sceNetAdhocMatchingTerm() {
WARN_LOG(SCENET, "UNTESTED sceNetAdhocMatchingTerm()");
// Should we cleanup all created matching contexts first? just in case there are games that doesn't delete them before calling this
NetAdhocMatching_Term();
netAdhocMatchingInited = false;
return 0;
@@ -3156,13 +3209,13 @@ static int sceNetAdhocMatchingStart(int matchingId, int evthPri, int evthStack,
peer->state = PSP_ADHOC_MATCHING_PEER_P2P;
}*/
// Create & Start the Fake PSP Thread
// Create & Start the Fake PSP Thread ("matching_ev%d" and "matching_io%d")
std::string thrname = std::string("MatchingThr") + std::to_string(matchingId);
item->matching_thid = __KernelCreateThread(thrname.c_str(), __KernelGetCurThreadModuleId(), matchingThreadHackAddr, evthPri, evthStack, PSP_THREAD_ATTR_USER, 0, false);
//item->matchingThread = new HLEHelperThread(thrname, "sceNetAdhocMatching", "AdhocMatchingFunc", inthPri, inthStack);
item->matching_thid = sceKernelCreateThread(thrname.c_str(), matchingThreadHackAddr, evthPri, evthStack, 0, 0);
//item->matchingThread = new HLEHelperThread(thrname.c_str(), "sceNetAdhocMatching", "__NetMatchingCallbacks", inthPri, inthStack);
if (item->matching_thid > 0) {
__KernelStartThread(item->matching_thid, 0, 0);
//item->matchingThread->Start(0, 0);
sceKernelStartThread(item->matching_thid, 0, 0); //sceKernelStartThread(context->event_thid, sizeof(context), &context);
//item->matchingThread->Start(matchingId, 0);
}
//Create the threads
@@ -3976,7 +4029,7 @@ int sceNetAdhocMatchingGetPoolStat(u32 poolstatPtr) {
void __NetTriggerCallbacks()
{
std::lock_guard<std::recursive_mutex> adhocGuard(adhocEvtMtx);
int delayus = 1000;
int delayus = 10000;
auto params = adhocctlEvents.begin();
if (params != adhocctlEvents.end())
@@ -3994,14 +4047,15 @@ void __NetTriggerCallbacks()
args[2] = it->second.argument;
AfterAdhocMipsCall* after = (AfterAdhocMipsCall*)__KernelCreateAction(actionAfterAdhocMipsCall);
after->SetData(it->first, flags, args[2]);
SetAdhocctlInCallback(true);
__KernelDirectMipsCall(it->second.entryPoint, after, args, 3, true);
//SetAdhocctlInCallback(true);
//__KernelDirectMipsCall(it->second.entryPoint, after, args, 3, true);
hleEnqueueCall(it->second.entryPoint, 3, args, after);
}
adhocctlEvents.pop_front();
if (flags == ADHOCCTL_EVENT_CONNECT)
delayus = (adhocEventDelayMS + 2*adhocExtraPollDelayMS) * 1000;
delayus = (adhocEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; // May affects Dissidia 012 and GTA VCS
else
delayus = (adhocEventPollDelayMS + 2*adhocExtraPollDelayMS) * 1000; //Added an extra delay to prevent I/O Timing method from causing disconnection
delayus = (adhocEventPollDelayMS + 2*adhocExtraPollDelayMS) * 1000; // Added an extra delay to prevent I/O Timing method from causing disconnection
}
}
@@ -4009,10 +4063,10 @@ void __NetTriggerCallbacks()
hleDelayResult(0, "Prevent Adhocctl thread from blocking", delayus);
}
void __NetMatchingCallbacks()
void __NetMatchingCallbacks() //(int matchingId)
{
std::lock_guard<std::recursive_mutex> adhocGuard(adhocEvtMtx);
int delayus = 1000;
int delayus = 10000;
auto params = matchingEvents.begin();
if (params != matchingEvents.end())
@@ -4026,9 +4080,10 @@ void __NetMatchingCallbacks()
AfterMatchingMipsCall* after = (AfterMatchingMipsCall*)__KernelCreateAction(actionAfterMatchingMipsCall);
after->SetData(args[0], args[1], args[2]);
//SetMatchingInCallback(context, true);
__KernelDirectMipsCall(args[5], after, args, 5, true);
//__KernelDirectMipsCall(args[5], after, args, 5, true);
hleEnqueueCall(args[5], 5, args, after);
matchingEvents.pop_front();
delayus = (adhocMatchingEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; //Added an extra delay to prevent I/O Timing method from causing disconnection
delayus = (adhocMatchingEventDelayMS + 2*adhocExtraPollDelayMS) * 1000; // Added an extra delay to prevent I/O Timing method from causing disconnection
}
}
@@ -4122,7 +4177,7 @@ static int sceNetAdhocctlGetPeerList(u32 sizeAddr, u32 bufAddr) {
// Multithreading Lock
peerlock.lock();
bool excludeTimedout = false; //true;
bool excludeTimedout = true;
// Length Calculation Mode
if (buf == NULL) {
int activePeers = getActivePeerCount(excludeTimedout);
@@ -5404,7 +5459,7 @@ int matchingEventThread(int matchingId)
}
// Share CPU Time
sleep_ms(1); //10 //sceKernelDelayThread(10000);
sleep_ms(10); //1 //sceKernelDelayThread(10000);
// Don't do anything if it's paused, otherwise the log will be flooded
while (Core_IsStepping() && coreState != CORE_POWERDOWN && contexts != NULL && context->eventRunning) sleep_ms(1);
@@ -5635,7 +5690,7 @@ int matchingInputThread(int matchingId) // TODO: The MatchingInput thread is usi
handleTimeout(context);
}
// Share CPU Time
sleep_ms(1); //10 //sceKernelDelayThread(10000);
sleep_ms(10); //1 //sceKernelDelayThread(10000);
// Don't do anything if it's paused, otherwise the log will be flooded
while (Core_IsStepping() && coreState != CORE_POWERDOWN && contexts != NULL && context->inputRunning) sleep_ms(1);
+3 -2
View File
@@ -53,5 +53,6 @@ extern int adhocEventDelayMS; // This will affect the duration of "Connecting...
extern std::recursive_mutex adhocEvtMtx;
extern int IsAdhocctlInCB;
int sceNetAdhocctlTerm();
int sceNetAdhocTerm();
int NetAdhocMatching_Term();
int NetAdhocctl_Term();
int NetAdhoc_Term();
+42 -33
View File
@@ -30,9 +30,10 @@
#include <Core/System.h>
#include <Core/Host.h>
#include <Core/ELF/ParamSFO.h>
#include "Core/HLE/proAdhoc.h" // This import is only used to get product id that was used to connect to adhoc server
#include "Core/Util/PortManager.h"
#include <Common/Log.h>
#include "i18n/i18n.h"
#include "net/resolve.h"
PortManager g_PortManager;
@@ -43,15 +44,20 @@ PortManager::PortManager():
m_InitState(UPNP_INITSTATE_NONE),
m_LocalPort(UPNP_LOCAL_PORT_ANY),
m_leaseDuration("43200") {
// Since WSAStartup can be used multiple times it should be safe to do this right?
net::Init();
}
PortManager::~PortManager() {
// FIXME: On Windows it seems using any UPnP functions in this destructor that gets triggered when exiting PPSSPP will resulting to UPNPCOMMAND_HTTP_ERROR due to early WSACleanup (miniupnpc was getting WSANOTINITIALISED internally)
Clear();
Restore();
Deinit();
Terminate();
net::Shutdown();
}
void PortManager::Deinit() {
void PortManager::Terminate() {
INFO_LOG(SCENET, "PortManager::Terminate()");
if (urls) {
FreeUPNPUrls(urls);
free(urls);
@@ -67,24 +73,24 @@ void PortManager::Deinit() {
m_defaultDesc.clear();
m_leaseDuration.clear();
m_LocalPort = UPNP_LOCAL_PORT_ANY;
m_InitState = UPNP_INITSTATE_DONE;
m_InitState = UPNP_INITSTATE_NONE;
}
bool PortManager::Init(const unsigned int timeout) {
bool PortManager::Initialize(const unsigned int timeout) {
// Windows: Assuming WSAStartup already called beforehand
struct UPNPDev* devlist;
struct UPNPDev* dev;
char* descXML;
int descXMLsize = 0;
int descXMLstatus = 0;
int localport = m_LocalPort; // UPNP_LOCAL_PORT_ANY (0), or UPNP_LOCAL_PORT_SAME (1) as an alias for 1900 for backwards compatability?
int localport = m_LocalPort; // UPNP_LOCAL_PORT_ANY (0), or UPNP_LOCAL_PORT_SAME (1) as an alias for 1900 (for backwards compatability?)
int ipv6 = 0; // 0 = IPv4, 1 = IPv6
unsigned char ttl = 2; // defaulting to 2
int error = 0;
INFO_LOG(SCENET, "PortManager::Init(%d)", timeout);
INFO_LOG(SCENET, "PortManager::Initialize(%d)", timeout);
if (!g_Config.bEnableUPnP) {
ERROR_LOG(SCENET, "PortManager::Init - UPnP is Disabled on Networking Settings");
ERROR_LOG(SCENET, "PortManager::Initialize - UPnP is Disabled on Networking Settings");
return false;
}
@@ -95,12 +101,11 @@ bool PortManager::Init(const unsigned int timeout) {
WARN_LOG(SCENET, "PortManager - Initialization already in progress");
return false;
}
// We should redetect UPnP just in case the player switched to a different network in the middle
/*case UPNP_INITSTATE_DONE: {
// Should we redetect UPnP? just in case the player switched to a different network in the middle
case UPNP_INITSTATE_DONE: {
WARN_LOG(SCENET, "PortManager - Already Initialized");
return false;
return true;
}
*/
default:
break;
}
@@ -151,14 +156,9 @@ bool PortManager::Init(const unsigned int timeout) {
INFO_LOG(SCENET, "PortManager - Connection Type: %s", connectionType);
}
// Using Game ID & Player Name as default description for mapping (prioritizing the ID sent by the game to Adhoc server)
char productid[10] = { 0 };
memcpy(productid, product_code.data, sizeof(product_code.data));
std::string gameID = std::string(productid);
if (productid[0] == '\0') {
gameID = g_paramSFO.GetDiscID();
}
m_defaultDesc = "PPSSPP:" + gameID + ":" + g_Config.sNickName;
// Using Game ID & Player Name as default description for mapping
std::string gameID = g_paramSFO.GetDiscID();
m_defaultDesc = "PPSSPP:" + gameID + ":" + g_Config.sNickName; // Some routers may automatically prefixed it with "UPnP:"
freeUPNPDevlist(devlist);
@@ -179,17 +179,21 @@ int PortManager::GetInitState() {
return m_InitState;
}
bool PortManager::Add(unsigned short port, const char* protocol) {
bool PortManager::Add(const char* protocol, unsigned short port, unsigned short intport) {
char port_str[16];
char intport_str[16];
int r;
INFO_LOG(SCENET, "PortManager::Add(%d, %s)", port, protocol);
if (intport == 0)
intport = port;
INFO_LOG(SCENET, "PortManager::Add(%s, %d, %d)", protocol, port, intport);
if (urls == NULL || urls->controlURL == NULL || urls->controlURL[0] == '\0')
{
if (g_Config.bEnableUPnP) WARN_LOG(SCENET, "PortManager::Add - the init was not done !");
return false;
}
sprintf(port_str, "%d", port);
sprintf(intport_str, "%d", intport);
// Only add new port map if it's not previously created by PPSSPP for current IP
auto el_it = std::find_if(m_portList.begin(), m_portList.end(),
[port_str, protocol](const std::pair<std::string, std::string> &el) { return el.first == port_str && el.second == protocol; });
@@ -201,11 +205,11 @@ bool PortManager::Add(unsigned short port, const char* protocol) {
r = UPNP_DeletePortMapping(urls->controlURL, datas->first.servicetype, port_str, protocol, NULL);
}
r = UPNP_AddPortMapping(urls->controlURL, datas->first.servicetype,
port_str, port_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str());
port_str, intport_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str());
if (r == 725 && m_leaseDuration != "0") {
m_leaseDuration = "0";
r = UPNP_AddPortMapping(urls->controlURL, datas->first.servicetype,
port_str, port_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str());
port_str, intport_str, m_lanip.c_str(), m_defaultDesc.c_str(), protocol, NULL, m_leaseDuration.c_str());
}
if (r != 0)
{
@@ -213,7 +217,7 @@ bool PortManager::Add(unsigned short port, const char* protocol) {
if (r == UPNPCOMMAND_HTTP_ERROR) {
auto n = GetI18NCategory("Networking");
host->NotifyUserMessage(n->T("UPnP need to be reinitialized"), 6.0f, 0x0000ff);
Deinit(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts
Terminate(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts
return false;
}
}
@@ -224,10 +228,10 @@ bool PortManager::Add(unsigned short port, const char* protocol) {
return true;
}
bool PortManager::Remove(unsigned short port, const char* protocol) {
bool PortManager::Remove(const char* protocol, unsigned short port) {
char port_str[16];
INFO_LOG(SCENET, "PortManager::Remove(%d, %s)", port, protocol);
INFO_LOG(SCENET, "PortManager::Remove(%s, %d)", protocol, port);
if (urls == NULL || urls->controlURL == NULL || urls->controlURL[0] == '\0')
{
if (g_Config.bEnableUPnP) WARN_LOG(SCENET, "PortManager::Remove - the init was not done !");
@@ -241,7 +245,7 @@ bool PortManager::Remove(unsigned short port, const char* protocol) {
if (r == UPNPCOMMAND_HTTP_ERROR) {
auto n = GetI18NCategory("Networking");
host->NotifyUserMessage(n->T("UPnP need to be reinitialized"), 6.0f, 0x0000ff);
Deinit(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts
Terminate(); // Most of the time errors occurred because the router is no longer reachable (ie. changed networks) so we should invalidate the state to prevent further lags due to timeouts
return false;
}
}
@@ -317,8 +321,9 @@ bool PortManager::Clear() {
do {
snprintf(index, 6, "%d", i);
rHost[0] = '\0'; enabled[0] = '\0';
duration[0] = '\0'; desc[0] = '\0';
duration[0] = '\0'; desc[0] = '\0'; protocol[0] = '\0';
extPort[0] = '\0'; intPort[0] = '\0'; intAddr[0] = '\0';
// May gets UPNPCOMMAND_HTTP_ERROR when called while exiting PPSSPP (ie. used in destructor)
r = UPNP_GetGenericPortMappingEntry(urls->controlURL,
datas->first.servicetype,
index,
@@ -326,7 +331,7 @@ bool PortManager::Clear() {
protocol, desc, enabled,
rHost, duration);
// Only removes port mappings created by PPSSPP for current LAN IP
if (r == 0 && intAddr == m_lanip && std::strncmp(desc, "PPSSPP", 6) == 0) {
if (r == 0 && intAddr == m_lanip && std::string(desc).find("PPSSPP:") != std::string::npos) {
int r2 = UPNP_DeletePortMapping(urls->controlURL, datas->first.servicetype, extPort, protocol, rHost);
if (r2 != 0)
{
@@ -372,7 +377,7 @@ bool PortManager::RefreshPortList() {
do {
snprintf(index, 6, "%d", i);
rHost[0] = '\0'; enabled[0] = '\0';
duration[0] = '\0'; desc[0] = '\0';
duration[0] = '\0'; desc[0] = '\0'; protocol[0] = '\0';
extPort[0] = '\0'; intPort[0] = '\0'; intAddr[0] = '\0';
r = UPNP_GetGenericPortMappingEntry(urls->controlURL,
datas->first.servicetype,
@@ -381,13 +386,17 @@ bool PortManager::RefreshPortList() {
protocol, desc, enabled,
rHost, duration);
if (r == 0) {
std::string desc_str = std::string(desc);
// Some router might prefix the description with "UPnP:" so we may need to truncate it to prevent it from getting multiple prefix when restored later
if (desc_str.find("UPnP:") == 0)
desc_str = desc_str.substr(5);
// Only include port mappings created by PPSSPP for current LAN IP
if (intAddr == m_lanip && std::strncmp(desc, "PPSSPP", 6) == 0) {
if (intAddr == m_lanip && desc_str.find("PPSSPP:") != std::string::npos) {
m_portList.push_back({ extPort, protocol });
}
// Port mappings belong to others that might be taken by PPSSPP later
else {
m_otherPortList.push_back({ false, protocol, extPort, intPort, intAddr, rHost, desc, duration, enabled });
m_otherPortList.push_back({ false, protocol, extPort, intPort, intAddr, rHost, desc_str, duration, enabled });
}
}
i++;
+8 -8
View File
@@ -61,27 +61,27 @@ public:
// Initialize UPnP
// timeout: milliseconds to wait for a router to respond (default = 2000 ms)
bool Init(const unsigned int timeout = 2000);
bool Initialize(const unsigned int timeout = 2000);
// Uninitialize/Reset the state
void Deinit();
void Terminate();
// Get UPnP Initialization status
int GetInitState();
// Add a port & protocol (TCP, UDP or vendor-defined) to map for forwarding
bool Add(unsigned short port, const char* protocol);
// Add a port & protocol (TCP, UDP or vendor-defined) to map for forwarding (intport = 0 : same as [external] port)
bool Add(const char* protocol, unsigned short port, unsigned short intport = 0);
// Remove a port mapping
bool Remove(unsigned short port, const char* protocol);
// Remove a port mapping (external port)
bool Remove(const char* protocol, unsigned short port);
// Removes any lingering mapped ports from previous crashes
// Removes any lingering mapped ports created by PPSSPP (including from previous crashes)
bool Clear();
// Restore ports mapped by others that were taken by PPSSPP, better used after Clear()
bool Restore();
// Get port list mapped by PPSSPP for current LAN IP & others
// Retrieves port lists mapped by PPSSPP for current LAN IP & other's applications
bool RefreshPortList();
protected:
+7 -3
View File
@@ -690,7 +690,6 @@ void GameSettingsScreen::CreateViews() {
networkingSettings->Add(new ChoiceWithValueDisplay(&g_Config.proAdhocServer, n->T("Change proAdhocServer Address"), (const char *)nullptr))->OnClick.Handle(this, &GameSettingsScreen::OnChangeproAdhocServerAddress);
networkingSettings->Add(new CheckBox(&g_Config.bEnableAdhocServer, n->T("Enable built-in PRO Adhoc Server", "Enable built-in PRO Adhoc Server")));
networkingSettings->Add(new CheckBox(&g_Config.bEnableUPnP, n->T("Enable UPnP", "Enable UPnP (need a few seconds to detect)")));
networkingSettings->Add(new ChoiceWithValueDisplay(&g_Config.sMACAddress, n->T("Change Mac Address"), (const char *)nullptr))->OnClick.Handle(this, &GameSettingsScreen::OnChangeMacAddress);
static const char* wlanChannels[] = { "Auto", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" };
auto wlanChannelChoice = networkingSettings->Add(new PopupMultiChoice(&g_Config.iWlanAdhocChannel, gr->T("WLAN Channel"), wlanChannels, 0, ARRAY_SIZE(wlanChannels), gr->GetName(), screenManager()));
@@ -698,8 +697,13 @@ void GameSettingsScreen::CreateViews() {
wlanChannelChoice->HideChoice(i+2);
wlanChannelChoice->HideChoice(i+7);
}
networkingSettings->Add(new PopupSliderChoice(&g_Config.iPortOffset, 0, 60000, n->T("Port offset", "Port offset(0 = PSP compatibility)"), 100, screenManager()));
networkingSettings->Add(new PopupSliderChoice(&g_Config.iMinTimeout, 1, 15000, n->T("Minimum Timeout", "Minimum Timeout (override low latency communication in milliseconds)"), 100, screenManager()));
networkingSettings->Add(new PopupSliderChoice(&g_Config.iPortOffset, 0, 60000, n->T("Port offset", "Port offset (0 = PSP compatibility)"), 100, screenManager()));
networkingSettings->Add(new PopupSliderChoice(&g_Config.iMinTimeout, 1, 15000, n->T("Minimum Timeout", "Minimum Timeout (override low latency in ms)"), 100, screenManager()));
networkingSettings->Add(new CheckBox(&g_Config.bTCPNoDelay, n->T("TCP No Delay", "TCP No Delay (faster TCP)")));
networkingSettings->Add(new ItemHeader(n->T("UPnP")));
networkingSettings->Add(new CheckBox(&g_Config.bEnableUPnP, n->T("Enable UPnP", "Enable UPnP (need a few seconds to detect)")));
networkingSettings->Add(new CheckBox(&g_Config.bUPnPUseOriginalPort, n->T("UPnP use original port", "UPnP use original port (PSP compatibility)")))->SetEnabledPtr(&g_Config.bEnableUPnP);
networkingSettings->Add(new ItemHeader(n->T("Chat")));
networkingSettings->Add(new CheckBox(&g_Config.bEnableNetworkChat, n->T("Enable network chat", "Enable network chat")));