Browse Source

Closes #182 -- dpogue/kill_utils

Conflicts:
	Sources/Plasma/Apps/plClient/winmain.cpp
Adam Johnson 13 years ago
parent
commit
8d36a0d028
  1. 35
      Sources/Plasma/Apps/plClient/winmain.cpp
  2. 36
      Sources/Plasma/Apps/plClientPatcher/UruPlayer.cpp
  3. 26
      Sources/Plasma/Apps/plUruLauncher/Main.cpp
  4. 6
      Sources/Plasma/Apps/plUruLauncher/SelfPatcher.cpp
  5. 183
      Sources/Plasma/CoreLib/hsStlUtils.h
  6. 28
      Sources/Plasma/CoreLib/hsUtils.h
  7. 28
      Sources/Plasma/FeatureLib/pfConsoleCore/pfConsoleCommandsCore.cpp
  8. 7
      Sources/Plasma/FeatureLib/pfCsrSrv/pfCsrSrv.cpp
  9. 6
      Sources/Plasma/FeatureLib/pfGameMgr/Intern.h
  10. 54
      Sources/Plasma/FeatureLib/pfGameMgr/pfGameMgr.cpp
  11. 12
      Sources/Plasma/FeatureLib/pfGameMgr/pfGameMgr.h
  12. 1
      Sources/Plasma/NucleusLib/CMakeLists.txt
  13. 22
      Sources/Plasma/NucleusLib/pnAsyncCore/Private/pnAcIo.h
  14. 2
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNt.cpp
  15. 6
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNtInt.h
  16. 54
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNtSocket.cpp
  17. 1
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNtThread.cpp
  18. 6
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/W9x/pnAceW9xInt.h
  19. 6
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/W9x/pnAceW9xSocket.cpp
  20. 50
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Win32/pnAceW32Dns.cpp
  21. 8
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/pnAceInt.h
  22. 6
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/pnAceIo.cpp
  23. 3
      Sources/Plasma/NucleusLib/pnAsyncCoreExe/pnAceTimer.cpp
  24. 2
      Sources/Plasma/NucleusLib/pnEncryption/CMakeLists.txt
  25. 57
      Sources/Plasma/NucleusLib/pnEncryption/plBigNum.cpp
  26. 95
      Sources/Plasma/NucleusLib/pnEncryption/plBigNum.h
  27. 1
      Sources/Plasma/NucleusLib/pnEncryption/plChallengeHash.cpp
  28. 64
      Sources/Plasma/NucleusLib/pnNetBase/pnNbSrvs.cpp
  29. 28
      Sources/Plasma/NucleusLib/pnNetBase/pnNbSrvs.h
  30. 18
      Sources/Plasma/NucleusLib/pnNetCli/Intern.h
  31. 1
      Sources/Plasma/NucleusLib/pnNetCli/Pch.h
  32. 79
      Sources/Plasma/NucleusLib/pnNetCli/pnNcChannel.cpp
  33. 20
      Sources/Plasma/NucleusLib/pnNetCli/pnNcCli.cpp
  34. 54
      Sources/Plasma/NucleusLib/pnNetCli/pnNcEncrypt.cpp
  35. 15
      Sources/Plasma/NucleusLib/pnNetCli/pnNetCli.h
  36. 52
      Sources/Plasma/NucleusLib/pnNetCommon/plNetAddress.cpp
  37. 146
      Sources/Plasma/NucleusLib/pnNetCommon/plNetAddress.h
  38. 16
      Sources/Plasma/NucleusLib/pnNetCommon/pnNetCommon.cpp
  39. 7
      Sources/Plasma/NucleusLib/pnNetCommon/pnNetCommon.h
  40. 21
      Sources/Plasma/NucleusLib/pnNetDiag/CMakeLists.txt
  41. 143
      Sources/Plasma/NucleusLib/pnNetDiag/Intern.h
  42. 68
      Sources/Plasma/NucleusLib/pnNetDiag/Pch.h
  43. 194
      Sources/Plasma/NucleusLib/pnNetDiag/pnNdDns.cpp
  44. 262
      Sources/Plasma/NucleusLib/pnNetDiag/pnNdIcmp.cpp
  45. 858
      Sources/Plasma/NucleusLib/pnNetDiag/pnNdTcp.cpp
  46. 167
      Sources/Plasma/NucleusLib/pnNetDiag/pnNetDiag.cpp
  47. 145
      Sources/Plasma/NucleusLib/pnNetDiag/pnNetDiag.h
  48. 177
      Sources/Plasma/NucleusLib/pnNetDiag/pnNetSys.cpp
  49. 18
      Sources/Plasma/NucleusLib/pnNetProtocol/Private/Protocols/Cli2Auth/pnNpCli2Auth.h
  50. 6
      Sources/Plasma/NucleusLib/pnNetProtocol/Private/Protocols/Srv2Mcp/pnNpSrv2Mcp.h
  51. 1
      Sources/Plasma/NucleusLib/pnSimpleNet/CMakeLists.txt
  52. 54
      Sources/Plasma/NucleusLib/pnSimpleNet/Pch.h
  53. 275
      Sources/Plasma/NucleusLib/pnSimpleNet/pnSimpleNet.cpp
  54. 3
      Sources/Plasma/NucleusLib/pnSimpleNet/pnSimpleNet.h
  55. 13
      Sources/Plasma/NucleusLib/pnUUID/pnUUID.h
  56. 18
      Sources/Plasma/NucleusLib/pnUtils/CMakeLists.txt
  57. 387
      Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Addr.cpp
  58. 56
      Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Dll.cpp
  59. 166
      Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Misc.cpp
  60. 58
      Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Sync.cpp
  61. 95
      Sources/Plasma/NucleusLib/pnUtils/pnUtAddr.cpp
  62. 170
      Sources/Plasma/NucleusLib/pnUtils/pnUtAddr.h
  63. 7
      Sources/Plasma/NucleusLib/pnUtils/pnUtAllIncludes.h
  64. 109
      Sources/Plasma/NucleusLib/pnUtils/pnUtArray.h
  65. 182
      Sources/Plasma/NucleusLib/pnUtils/pnUtBase64.cpp
  66. 85
      Sources/Plasma/NucleusLib/pnUtils/pnUtBase64.h
  67. 48
      Sources/Plasma/NucleusLib/pnUtils/pnUtCmd.cpp
  68. 10
      Sources/Plasma/NucleusLib/pnUtils/pnUtCmd.h
  69. 45
      Sources/Plasma/NucleusLib/pnUtils/pnUtHash.h
  70. 63
      Sources/Plasma/NucleusLib/pnUtils/pnUtMath.cpp
  71. 102
      Sources/Plasma/NucleusLib/pnUtils/pnUtMath.h
  72. 81
      Sources/Plasma/NucleusLib/pnUtils/pnUtMisc.h
  73. 48
      Sources/Plasma/NucleusLib/pnUtils/pnUtPriQ.h
  74. 184
      Sources/Plasma/NucleusLib/pnUtils/pnUtRand.cpp
  75. 67
      Sources/Plasma/NucleusLib/pnUtils/pnUtRand.h
  76. 46
      Sources/Plasma/NucleusLib/pnUtils/pnUtSort.h
  77. 163
      Sources/Plasma/NucleusLib/pnUtils/pnUtSpareList.cpp
  78. 148
      Sources/Plasma/NucleusLib/pnUtils/pnUtSpareList.h
  79. 57
      Sources/Plasma/NucleusLib/pnUtils/pnUtSync.h
  80. 82
      Sources/Plasma/NucleusLib/pnUtils/pnUtTls.cpp
  81. 72
      Sources/Plasma/NucleusLib/pnUtils/pnUtTls.h
  82. 1
      Sources/Plasma/NucleusLib/pnUtilsExe/CMakeLists.txt
  83. 110
      Sources/Plasma/NucleusLib/pnUtilsExe/Private/pnUteTls.cpp
  84. 72
      Sources/Plasma/PubUtilLib/plNetClient/plNetLinkingMgr.cpp
  85. 31
      Sources/Plasma/PubUtilLib/plNetClientComm/plNetClientComm.cpp
  86. 1
      Sources/Plasma/PubUtilLib/plNetGameLib/Pch.h
  87. 51
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglAuth.cpp
  88. 7
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglAuth.h
  89. 23
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglCsr.cpp
  90. 4
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglCsr.h
  91. 32
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglFile.cpp
  92. 4
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglFile.h
  93. 13
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGame.cpp
  94. 2
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGame.h
  95. 27
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGateKeeper.cpp
  96. 4
      Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGateKeeper.h

35
Sources/Plasma/Apps/plClient/winmain.cpp

@ -121,7 +121,7 @@ bool gPendingActivate = false;
bool gPendingActivateFlag = false;
static bool s_loginDlgRunning = false;
static CEvent s_statusEvent(kEventManualReset);
static hsSemaphore s_statusEvent(0); // Start non-signalled
static UINT s_WmTaskbarList = RegisterWindowMessage("TaskbarButtonCreated");
FILE *errFP = nil;
@ -1129,7 +1129,7 @@ void StatusCallback(void *param)
{
HWND hwnd = (HWND)param;
char *statusUrl = hsWStringToString(GetServerStatusUrl());
const char *statusUrl = GetServerStatusUrl();
CURL *hCurl = curl_easy_init();
// For reporting errors
@ -1153,9 +1153,8 @@ void StatusCallback(void *param)
}
curl_easy_cleanup(hCurl);
delete [] statusUrl;
s_statusEvent.Signal();
s_statusEvent.Signal(); // Signal the semaphore
}
BOOL CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam )
@ -1211,7 +1210,7 @@ BOOL CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM
case WM_DESTROY:
{
s_loginDlgRunning = false;
s_statusEvent.Wait(kEventWaitForever);
s_statusEvent.Wait();
KillTimer(hwndDlg, AUTH_LOGIN_TIMER);
return TRUE;
}
@ -1283,8 +1282,8 @@ BOOL CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM
}
else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_URULOGIN_GAMETAPLINK)
{
const wchar_t *signupurl = GetServerSignupUrl();
ShellExecuteW(NULL, L"open", signupurl, NULL, NULL, SW_SHOWNORMAL);
const char* signupurl = GetServerSignupUrl();
ShellExecuteA(NULL, "open", signupurl, NULL, NULL, SW_SHOWNORMAL);
return TRUE;
}
@ -1490,25 +1489,27 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
wchar_t cmdLine[MAX_PATH];
const wchar_t ** addrs;
plStringStream cmdLine;
const char** addrs;
if (!eventExists) // if it is missing, assume patcher wasn't launched
{
StrCopy(cmdLine, s_patcherExeName, arrsize(cmdLine));
cmdLine << _TEMP_CONVERT_FROM_WCHAR_T(s_patcherExeName);
GetAuthSrvHostnames(&addrs);
if(wcslen(addrs[0]))
StrPrintf(cmdLine, arrsize(cmdLine), L"%ws /AuthSrv=%ws", cmdLine, addrs[0]);
if(strlen(addrs[0]))
cmdLine << plString::Format(" /AuthSrv=%s", addrs[0]);
GetFileSrvHostnames(&addrs);
if(wcslen(addrs[0]))
StrPrintf(cmdLine, arrsize(cmdLine), L"%ws /FileSrv=%ws", cmdLine, addrs[0]);
if(strlen(addrs[0]))
cmdLine << plString::Format(" /FileSrv=%s", addrs[0]);
GetGateKeeperSrvHostnames(&addrs);
if(wcslen(addrs[0]))
StrPrintf(cmdLine, arrsize(cmdLine), L"%ws /GateKeeperSrv=%ws", cmdLine, addrs[0]);
if(strlen(addrs[0]))
cmdLine << plString::Format(" /GateKeeperSrv=%s", addrs[0]);
if(!CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
if(!CreateProcessW(NULL, (LPWSTR)cmdLine.GetString().ToUtf16().GetData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
hsMessageBox("Failed to launch patcher", "Error", hsMessageBoxNormal);
}

36
Sources/Plasma/Apps/plClientPatcher/UruPlayer.cpp

@ -47,6 +47,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "Pch.h"
#include "plStatusLog/plStatusLog.h"
#include <queue>
#pragma hdrstop
@ -67,7 +68,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
struct ManifestFile
{
LINK(ManifestFile) link;
ManifestFile(const wchar_t clientName[], const wchar_t downloadName[], const wchar_t md5val[], int flags, plLauncherInfo *info)
{
StrCopy(filename, clientName, arrsize(filename));
@ -113,7 +113,7 @@ struct ManifestResult {
long * indicator;
plLauncherInfo * info;
CCritSect critsect;
hsMutex critsect;
ARRAY(unsigned) indices;
};
@ -142,13 +142,12 @@ static unsigned s_fileListRequests;
static bool s_patchComplete;
static PROCESS_INFORMATION s_pi;
static long s_numFiles;
static CCritSect s_critsect;
static char s_workingDir[MAX_PATH];
static bool s_patchError;
static long s_asyncCoreInitCount;
static long s_numConnectFailures;
static bool s_running;
static LISTDECL(ManifestFile, link) s_manifestQueue;
static std::queue<ManifestFile*> manifestQueue;
//static AsyncThreadTaskList * s_taskList;
// error strings
@ -347,10 +346,13 @@ void Shutdown(plLauncherInfo *info) {
//============================================================================
static void RequestNextManifestFile () {
bool success = true;
ManifestFile *nextfile = s_manifestQueue.Head();
if(!nextfile)
if (!manifestQueue.size())
return;
s_manifestQueue.Unlink(nextfile);
ManifestFile* nextfile = manifestQueue.front();
manifestQueue.pop();
char path[MAX_PATH];
wchar_t basePath[MAX_PATH];
StrPrintf(path, arrsize(path), "%s%S", s_workingDir, nextfile->filename);
@ -496,9 +498,9 @@ static void ProcessManifestEntry (void * param, ENetError error) {
);
uint32_t start = (uint32_t)(TimeGetTime() / kTimeIntervalsPerMs);
if(!MD5Check(path, p->mr->manifest[p->index].md5)) {
p->mr->critsect.Enter();
p->mr->critsect.Lock();
p->mr->indices.Add(p->index);
p->mr->critsect.Leave();
p->mr->critsect.Unlock();
AtomicAdd(&ProgressStream::totalBytes, p->mr->manifest[p->index].zipSize);
}
@ -614,14 +616,14 @@ static void ProcessManifest (void * param) {
PathRemoveFilename(basePath, basePath, arrsize(basePath));
PathCreateDirectory(basePath, kPathCreateDirFlagEntireTree);
ManifestFile * mf = new ManifestFile(
ManifestFile* mf = new ManifestFile(
manifest[index].clientName,
manifest[index].downloadName,
manifest[index].md5,
manifest[index].flags,
mr->info
);
if (i < kMaxManifestFileRequests) {
ProgressStream * stream;
stream = NEWZERO(ProgressStream);
@ -645,7 +647,7 @@ static void ProcessManifest (void * param) {
}
else {
// queue up this file download
s_manifestQueue.Link(mf);
manifestQueue.push(mf);
}
}
}
@ -838,7 +840,9 @@ static void FileSrvIpAddressCallback (
plLauncherInfo *info = (plLauncherInfo *) param;
// Start connecting to the server
NetCliFileStartConnect(&addr, 1, true);
const char* caddr = hsWStringToString(addr);
NetCliFileStartConnect(&caddr, 1, true);
delete[] caddr;
NetCliFileManifestRequest(ThinManifestCallback, info, s_thinmanifest, info->buildId);
@ -900,7 +904,7 @@ void UruPrepProc (void * param) {
s_patchComplete = false;
s_patchError = false;
const wchar_t ** addrs;
const char** addrs;
unsigned count;
count = GetGateKeeperSrvHostnames(&addrs);
@ -916,8 +920,10 @@ void UruPrepProc (void * param) {
AsyncSleep(10);
} while ((!s_patchComplete && !s_patchError && s_running) || s_perf[kPerfThreadTaskCount]);
while(ManifestFile *mf = s_manifestQueue.Head())
while (manifestQueue.size())
{
ManifestFile* mf = manifestQueue.front();
manifestQueue.pop();
delete mf;
}
// If s_patchError, we don't wait around for s_numFiles

26
Sources/Plasma/Apps/plUruLauncher/Main.cpp

@ -46,6 +46,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
***/
#include "Pch.h"
#include "hsThread.h"
#pragma hdrstop
@ -147,12 +148,12 @@ static HANDLE s_thread;
static HANDLE s_event;
static HINSTANCE s_hInstance;
static HWND s_dialog;
static CEvent s_dialogCreateEvent(kEventManualReset);
static CCritSect s_critsect;
static hsSemaphore s_dialogCreateEvent(0);
static hsMutex s_critsect;
static LISTDECL(WndEvent, link) s_eventQ;
static CEvent s_shutdownEvent(kEventManualReset);
static hsSemaphore s_shutdownEvent(0);
static wchar_t s_workingDir[MAX_PATH];
static CEvent s_statusEvent(kEventManualReset);
static hsSemaphore s_statusEvent(0);
static char s_curlError[CURL_ERROR_SIZE];
@ -196,9 +197,9 @@ static void Abort () {
//============================================================================
static void PostEvent (WndEvent *event) {
s_critsect.Enter();
s_critsect.Lock();
s_eventQ.Link(event);
s_critsect.Leave();
s_critsect.Unlock();
}
//============================================================================
@ -393,11 +394,11 @@ static void Recv_SetBytesRemaining (HWND hwnd, const SetBytesRemainingEvent &eve
static void DispatchEvents (HWND hwnd) {
LISTDECL(WndEvent, link) eventQ;
s_critsect.Enter();
s_critsect.Lock();
{
eventQ.Link(&s_eventQ);
}
s_critsect.Leave();
s_critsect.Unlock();
#define DISPATCH(a) case kEvent##a: Recv_##a(hwnd, *(const a##Event *) event); break
while (WndEvent *event = eventQ.Head()) {
@ -608,7 +609,7 @@ static size_t CurlCallback(void *buffer, size_t size, size_t nmemb, void *)
//============================================================================
static void StatusCallback(void *)
{
char *serverUrl = hsWStringToString(GetServerStatusUrl());
const char *serverUrl = GetServerStatusUrl();
CURL * hCurl = curl_easy_init();
curl_easy_setopt(hCurl, CURLOPT_ERRORBUFFER, s_curlError);
@ -630,7 +631,6 @@ static void StatusCallback(void *)
}
curl_easy_cleanup(hCurl);
delete [] serverUrl;
s_statusEvent.Signal();
}
@ -810,7 +810,7 @@ int __stdcall WinMain (
s_launcherInfo.buildId = cmdParser.GetInt(kArgBuildId);
// Wait for the dialog to be created
s_dialogCreateEvent.Wait(kEventWaitForever);
s_dialogCreateEvent.Wait();
_beginthread(StatusCallback, 0, nil); // get status
}
@ -950,10 +950,10 @@ int __stdcall WinMain (
}
ShutdownAsyncCore();
s_statusEvent.Wait(kEventWaitForever);
s_statusEvent.Wait();
PostMessage(s_dialog, WM_QUIT, 0, 0); // tell our window to shutdown
s_shutdownEvent.Wait(kEventWaitForever); // wait for our window to shutdown
s_shutdownEvent.Wait(); // wait for our window to shutdown
SetConsoleCtrlHandler(CtrlHandler, FALSE);

6
Sources/Plasma/Apps/plUruLauncher/SelfPatcher.cpp

@ -226,7 +226,9 @@ static void FileSrvIpAddressCallback (
}
// Start connecting to the server
NetCliFileStartConnect(&addr, 1, true);
const char* caddr = hsWStringToString(addr);
NetCliFileStartConnect(&caddr, 1, true);
delete[] caddr;
PathGetProgramDirectory(s_newPatcherFile, arrsize(s_newPatcherFile));
GetTempFileNameW(s_newPatcherFile, kPatcherExeFilename, 0, s_newPatcherFile);
@ -245,7 +247,7 @@ static bool SelfPatcherProc (bool * abort, plLauncherInfo *info) {
NetClientInitialize();
NetClientSetErrorHandler(NetErrorHandler);
const wchar_t ** addrs;
const char** addrs;
unsigned count;
count = GetGateKeeperSrvHostnames(&addrs);

183
Sources/Plasma/CoreLib/hsStlUtils.h

@ -53,184 +53,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include <set>
/*****************************************************************************
*
* derived stl classes that use our heap manager
*
***/
// TEMPLATE CLASS cyallocator
template<class _Ty>
class cyallocator
: public std::allocator<_Ty>
{ // generic cyallocator for objects of class _Ty
public:
typedef std::allocator<_Ty> _Mybase;
typedef typename _Mybase::value_type value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef const value_type* const_pointer;
typedef const value_type& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
template<class _Other>
struct rebind
{ // convert an cyallocator<_Ty> to an cyallocator <_Other>
typedef cyallocator<_Other> other;
};
pointer address(reference _Val) const
{ // return address of mutable _Val
return (&_Val);
}
const_pointer address(const_reference _Val) const
{ // return address of nonmutable _Val
return (&_Val);
}
cyallocator()
{ // construct default cyallocator (do nothing)
}
cyallocator(const cyallocator<_Ty>&)
{ // construct by copying (do nothing)
}
template<class _Other>
cyallocator(const cyallocator<_Other>&)
{ // construct from a related cyallocator (do nothing)
}
template<class _Other>
cyallocator<_Ty>& operator=(const cyallocator<_Other>&)
{ // assign from a related cyallocator (do nothing)
return (*this);
}
void deallocate(pointer _Ptr, size_type)
{ // deallocate object at _Ptr, ignore size
free(_Ptr);
}
pointer allocate(size_type _Count)
{ // allocate array of _Count elements
return (pointer)malloc(_Count * sizeof(_Ty));
}
pointer allocate(size_type _Count, const void*)
{ // allocate array of _Count elements, ignore hint
return (allocate(_Count));
}
void construct(pointer _Ptr, const _Ty& _Val)
{ // construct object at _Ptr with value _Val
std::_Construct(_Ptr, _Val);
}
void destroy(pointer _Ptr)
{ // destroy object at _Ptr
std::_Destroy(_Ptr);
}
size_t max_size() const
{ // estimate maximum array size
size_t _Count = (size_t)(-1) / sizeof (_Ty);
return (0 < _Count ? _Count : 1);
}
};
// cyallocator TEMPLATE OPERATORS
template<class _Ty,
class _Other> inline
bool operator==(const cyallocator<_Ty>&, const cyallocator<_Other>&)
{ // test for cyallocator equality (always true)
return (true);
}
template<class _Ty,
class _Other> inline
bool operator!=(const cyallocator<_Ty>&, const cyallocator<_Other>&)
{ // test for cyallocator inequality (always false)
return (false);
}
#ifndef _CRTIMP2
#define _CRTIMP2
#endif
// CLASS cyallocator<void>
template<> class _CRTIMP2 cyallocator<void>
{ // generic cyallocator for type void
public:
typedef void _Ty;
typedef _Ty* pointer;
typedef const _Ty* const_pointer;
typedef _Ty value_type;
template<class _Other>
struct rebind
{ // convert an cyallocator<void> to an cyallocator <_Other>
typedef cyallocator<_Other> other;
};
cyallocator()
{ // construct default cyallocator (do nothing)
}
cyallocator(const cyallocator<_Ty>&)
{ // construct by copying (do nothing)
}
template<class _Other>
cyallocator(const cyallocator<_Other>&)
{ // construct from related cyallocator (do nothing)
}
template<class _Other>
cyallocator<_Ty>& operator=(const cyallocator<_Other>&)
{ // assign from a related cyallocator (do nothing)
return (*this);
}
};
/*****************************************************************************
*
* Drop-in replacements for stl classes. Uses our allocator instead of the default one.
*
***/
typedef std::basic_string<char, std::char_traits<char>, cyallocator<char> > cystring;
typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, cyallocator<wchar_t> > cywstring;
// cyistring and cyiwstring declared later in this file
// TEMPLATE CLASS cyvector
template<class _Ty>
class cyvector : public std::vector<_Ty, cyallocator<_Ty> > {
};
// TEMPLATE CLASS cymap
template<class _Kty, class _Ty, class _Pr=std::less<_Kty> >
class cymap : public std::map<_Kty, _Ty, _Pr, cyallocator<std::pair<_Kty, _Ty > > > {
};
// TEMPLATE CLASS cylist
template<class _Ty>
class cylist : public std::list<_Ty, cyallocator<_Ty> > {
};
// TEMPLATE CLASS cyset
template<class _Kty, class _Pr = std::less<_Kty> >
class cyset : public std::set<_Kty, _Pr, cyallocator< _Kty > > {
};
/*****************************************************************************
*
* stl extensions
@ -347,11 +169,6 @@ struct wstricmp_char_traits : public std::char_traits< wchar_t >
typedef std::basic_string<char, stricmp_char_traits> istring;
typedef std::basic_string<wchar_t, wstricmp_char_traits> iwstring;
// cyallocator version of istring
typedef std::basic_string<char, stricmp_char_traits, cyallocator<char> > cyistring;
typedef std::basic_string<wchar_t, wstricmp_char_traits, cyallocator<wchar_t> > cyiwstring;
// std::string trim
std::string & trimleft(std::string & s, const char * charset=" \t\n\r");
std::wstring & trimleft(std::wstring & s, const wchar_t * charset=L" \t\n\r");

28
Sources/Plasma/CoreLib/hsUtils.h

@ -250,3 +250,31 @@ void DebugMsg(const char fmt[], ...);
#else
#define DEFAULT_FATAL(var) default: FATAL("No valid case for switch variable '" #var "'"); break;
#endif
/*****************************************************************************
*
* Atomic Operations
*
***/
// *value += increment; return original value of *value; thread safe
inline long AtomicAdd(long* value, long increment) {
#ifdef HS_BUILD_FOR_WIN32
return InterlockedExchangeAdd(value, increment);
#elif HS_BUILD_FOR_UNIX
return __sync_fetch_and_add(value, increment);
#else
#error "No Atomic Set support on this architecture"
#endif
}
// *value = value; return original value of *value; thread safe
inline long AtomicSet(long* value, long set) {
#ifdef HS_BUILD_FOR_WIN32
return InterlockedExchange(value, set);
#elif HS_BUILD_FOR_UNIX
return __sync_lock_test_and_set(value, set);
#else
#error "No Atomic Set support on this architecture"
#endif
}

28
Sources/Plasma/FeatureLib/pfConsoleCore/pfConsoleCommandsCore.cpp

@ -89,9 +89,7 @@ PF_CONSOLE_CMD(
"string url",
"Set the server's status URL"
) {
wchar_t *wurl = hsStringToWString((const char *)params[0]);
SetServerStatusUrl(wurl);
delete [] wurl;
SetServerStatusUrl(params[0]);
}
//============================================================================
@ -101,9 +99,7 @@ PF_CONSOLE_CMD(
"string url",
"Set the server's new user sign-up URL"
) {
wchar_t *wurl = hsStringToWString((const char *)params[0]);
SetServerSignupUrl(wurl);
delete [] wurl;
SetServerSignupUrl(params[0]);
}
//============================================================================
@ -113,9 +109,7 @@ PF_CONSOLE_CMD(
"string name",
"Set the displayable server name"
) {
wchar_t *wname = hsStringToWString((const char *)params[0]);
SetServerDisplayName(wname);
delete [] wname;
SetServerDisplayName(params[0]);
}
@ -130,9 +124,7 @@ PF_CONSOLE_CMD(
"string address",
"Set the File Server address"
) {
wchar_t *wHost = hsStringToWString((const char *)params[0]);
SetFileSrvHostname(wHost);
delete [] wHost;
SetFileSrvHostname(params[0]);
}
@ -147,9 +139,7 @@ PF_CONSOLE_CMD(
"string address",
"Set the Auth Server address"
) {
wchar_t *wHost = hsStringToWString((const char *)params[0]);
SetAuthSrvHostname(wHost);
delete [] wHost;
SetAuthSrvHostname(params[0]);
}
//============================================================================
@ -200,9 +190,7 @@ PF_CONSOLE_CMD(
"string address",
"Set the Csr Server address"
) {
wchar_t *wHost = hsStringToWString((const char *)params[0]);
SetCsrSrvHostname(wHost);
delete [] wHost;
SetCsrSrvHostname(params[0]);
}
//============================================================================
@ -294,9 +282,7 @@ PF_CONSOLE_CMD(
"string address",
"Set the GateKeeper Server address"
) {
wchar_t *wHost = hsStringToWString((const char *)params[0]);
SetGateKeeperSrvHostname(wHost);
delete [] wHost;
SetGateKeeperSrvHostname(params[0]);
}
//============================================================================

7
Sources/Plasma/FeatureLib/pfCsrSrv/pfCsrSrv.cpp

@ -113,11 +113,10 @@ static bool QueryAccept (
void * ,
unsigned channel,
SimpleNetConn * ,
const NetAddress & addr
const plNetAddress& addr
) {
wchar_t str[64];
NetAddressToString(addr, str, arrsize(str), kNetAddressFormatAll);
LogMsg(kLogPerf, L"pfCsrSrv: Accepted connection from %s", str);
plString str = addr.AsString();
LogMsg(kLogPerf, L"pfCsrSrv: Accepted connection from %s", str.c_str());
return channel == kSimpleNetChannelCsr;
}

6
Sources/Plasma/FeatureLib/pfGameMgr/Intern.h

@ -64,9 +64,9 @@ typedef pfGameCli * (*FGameCliFactory)(
);
struct GameTypeReg {
FGameCliFactory create;
Uuid typeId;
const wchar_t * name;
FGameCliFactory create;
plUUID typeId;
const wchar_t* name;
};
void GameMgrRegisterGameType (const GameTypeReg & reg);

54
Sources/Plasma/FeatureLib/pfGameMgr/pfGameMgr.cpp

@ -58,10 +58,9 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
//============================================================================
// pfGameCli factory
//============================================================================
struct Factory : THashKeyVal<Uuid> {
HASHLINK(Factory) link;
const GameTypeReg & reg;
struct Factory
{
const GameTypeReg& reg;
Factory (const GameTypeReg & reg);
Factory& operator= (const Factory &); // not impl
@ -113,7 +112,7 @@ struct JoinTransState {
//============================================================================
struct IGameMgr {
pfGameCli * CreateGameCli (const Uuid & gameTypeId, unsigned gameId, plKey receiver);
pfGameCli * CreateGameCli (const plUUID& gameTypeId, unsigned gameId, plKey receiver);
void Recv (GameMsgHeader * msg);
void RecvGameInstance (const Srv2Cli_GameMgr_GameInstance & msg, void * param);
@ -132,7 +131,7 @@ struct IGameMgr {
static HASHTABLEDECL(TransState, THashKeyVal<unsigned>, link) s_trans;
static HASHTABLEDECL(IGameCli, THashKeyVal<unsigned>, link) s_games;
static HASHTABLEDECL(Factory, THashKeyVal<Uuid>, link) s_factories;
static std::map<plUUID, Factory*> s_factories;
static long s_transId;
static ARRAYOBJ(plKey) s_receivers;
@ -145,10 +144,14 @@ static ARRAYOBJ(plKey) s_receivers;
***/
//============================================================================
static void ShutdownFactories () {
while (Factory * factory = s_factories.Head())
static void ShutdownFactories()
{
std::map<plUUID, Factory*>::iterator it;
for (it = s_factories.begin(); it != s_factories.end(); ++it) {
Factory* factory = it->second;
delete factory;
}
s_factories.clear();
}
//============================================================================
@ -175,14 +178,15 @@ static inline unsigned INextTransId () {
***/
//============================================================================
pfGameCli * IGameMgr::CreateGameCli (const Uuid & gameTypeId, unsigned gameId, plKey receiver) {
if (Factory * factory = s_factories.Find(gameTypeId)) {
pfGameCli * gameCli = factory->reg.create(gameId, receiver);
gameCli->internal->factory = factory;
pfGameCli* IGameMgr::CreateGameCli(const plUUID& gameTypeId, unsigned gameId, plKey receiver)
{
std::map<plUUID, Factory*>::iterator it;
if ((it = s_factories.find(gameTypeId)) != s_factories.end()) {
pfGameCli* gameCli = it->second->reg.create(gameId, receiver);
gameCli->internal->factory = it->second;
return gameCli;
}
return nil;
}
@ -351,10 +355,12 @@ pfGameCli * pfGameMgr::GetGameCli (unsigned gameId) const {
}
//============================================================================
const wchar_t * pfGameMgr::GetGameNameByTypeId (const Uuid & gameTypeId) const {
if (Factory * factory = s_factories.Find(gameTypeId))
return factory->reg.name;
const wchar_t* pfGameMgr::GetGameNameByTypeId(const plUUID& gameTypeId) const
{
std::map<plUUID, Factory*>::iterator it;
if ((it = s_factories.find(gameTypeId)) != s_factories.end()) {
return it->second->reg.name;
}
return nil;
}
@ -489,9 +495,9 @@ unsigned pfGameCli::GetGameId () const {
}
//============================================================================
const Uuid & pfGameCli::GetGameTypeId () const {
const plUUID& pfGameCli::GetGameTypeId () const {
return internal->factory->GetValue();
return internal->factory->reg.typeId;
}
//============================================================================
@ -615,11 +621,9 @@ void IGameCli::RecvOwnerChange (const Srv2Cli_Game_OwnerChange & msg, void * par
***/
//============================================================================
Factory::Factory (const GameTypeReg & reg)
: reg(reg)
, THashKeyVal<Uuid>(reg.typeId)
Factory::Factory(const GameTypeReg& reg) : reg(reg)
{
s_factories.Add(this);
s_factories[reg.typeId] = this;
}

12
Sources/Plasma/FeatureLib/pfGameMgr/pfGameMgr.h

@ -156,7 +156,7 @@ public:
// Return interface to the specified game
pfGameCli * GetGameCli (unsigned gameId) const;
// Get the name of a game by its typeid
const wchar_t * GetGameNameByTypeId (const Uuid & gameTypeId) const;
const wchar_t* GetGameNameByTypeId (const plUUID& gameTypeId) const;
//========================================================================
//========================================================================
@ -226,11 +226,11 @@ public:
//========================================================================
// Game client properties
//-----------------------
unsigned GetGameId () const;
const Uuid & GetGameTypeId () const;
const wchar_t * GetName () const;
plKey GetReceiver () const;
unsigned GetPlayerCount () const;
unsigned GetGameId () const;
const plUUID& GetGameTypeId () const;
const wchar_t* GetName () const;
plKey GetReceiver () const;
unsigned GetPlayerCount () const;
//========================================================================
//========================================================================

1
Sources/Plasma/NucleusLib/CMakeLists.txt

@ -17,7 +17,6 @@ add_subdirectory(pnModifier)
add_subdirectory(pnNetBase)
add_subdirectory(pnNetCli)
add_subdirectory(pnNetCommon)
add_subdirectory(pnNetDiag)
add_subdirectory(pnNetProtocol)
add_subdirectory(pnProduct)
add_subdirectory(pnSceneObject)

22
Sources/Plasma/NucleusLib/pnAsyncCore/Private/pnAcIo.h

@ -50,6 +50,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNASYNCCORE_PRIVATE_PNACIO_H
#include "pnNetCommon/plNetAddress.h"
/****************************************************************************
*
@ -103,8 +105,8 @@ struct AsyncNotifySocket {
};
struct AsyncNotifySocketConnect : AsyncNotifySocket {
NetAddress localAddr;
NetAddress remoteAddr;
plNetAddress localAddr;
plNetAddress remoteAddr;
unsigned connType;
};
@ -113,7 +115,7 @@ struct AsyncNotifySocketListen : AsyncNotifySocketConnect {
unsigned buildType;
unsigned branchId;
Uuid productId;
NetAddress addr;
plNetAddress addr;
uint8_t * buffer;
unsigned bytes;
unsigned bytesProcessed;
@ -213,7 +215,7 @@ FAsyncNotifySocketProc AsyncSocketFindNotifyProc (
void AsyncSocketConnect (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param = nil,
const void * sendData = nil,
@ -275,11 +277,11 @@ void AsyncSocketSetBacklogAlloc (
// for connections with hard-coded behavior, set the notifyProc here (e.g. for use
// protocols like SNMP on port 25)
unsigned AsyncSocketStartListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc = nil
);
void AsyncSocketStopListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc = nil
);
@ -297,15 +299,15 @@ void AsyncSocketEnableNagling (
typedef void (* FAsyncLookupProc) (
void * param,
const wchar_t name[],
const char name[],
unsigned addrCount,
const NetAddress addrs[]
const plNetAddress addrs[]
);
void AsyncAddressLookupName (
AsyncCancelId * cancelId,
FAsyncLookupProc lookupProc,
const wchar_t name[],
const char name[],
unsigned port,
void * param
);
@ -313,7 +315,7 @@ void AsyncAddressLookupName (
void AsyncAddressLookupAddr (
AsyncCancelId * cancelId,
FAsyncLookupProc lookupProc,
const NetAddress & address,
const plNetAddress& address,
void * param
);

2
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNt.cpp

@ -222,8 +222,6 @@ static void INtOpDispatch (
//===========================================================================
static unsigned THREADCALL NtWorkerThreadProc (AsyncThread * thread) {
ThreadDenyBlock();
unsigned sleepMs = INFINITE;
while (s_running) {

6
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNtInt.h

@ -191,7 +191,7 @@ void NtWaitForShutdown ();
void NtSleep (unsigned sleepMs);
void NtSocketConnect (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param,
const void * sendData,
@ -228,11 +228,11 @@ void NtSocketSetBacklogAlloc (
unsigned bufferSize
);
unsigned NtSocketStartListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
);
void NtSocketStopListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
);
void NtSocketEnableNagling (

54
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNtSocket.cpp

@ -77,7 +77,7 @@ static const unsigned kMinBacklogBytes = 4 * 1024;
struct NtListener {
LINK(NtListener) nextPort;
SOCKET hSocket;
NetAddress addr;
plNetAddress addr;
FAsyncNotifySocketProc notifyProc;
int listenCount;
@ -91,7 +91,7 @@ struct NtOpConnAttempt : Operation {
AsyncCancelId cancelId;
bool canceled;
unsigned localPort;
NetAddress remoteAddr;
plNetAddress remoteAddr;
FAsyncNotifySocketProc notifyProc;
void * param;
SOCKET hSocket;
@ -113,7 +113,7 @@ struct NtOpSocketRead : Operation {
struct NtSock : NtObject {
LINK(NtSock) link;
NetAddress addr;
plNetAddress addr;
unsigned closeTimeMs;
unsigned connType;
FAsyncNotifySocketProc notifyProc;
@ -171,13 +171,13 @@ NtSock::~NtSock () {
//===========================================================================
// must be called inside s_listenCrit
static bool ListenPortIncrement (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc,
int count
) {
NtListener * listener;
for (listener = s_listenList.Head(); listener; listener = s_listenList.Next(listener)) {
if (!NetAddressEqual(listener->addr, listenAddr))
if (listener->addr != listenAddr)
continue;
if (listener->notifyProc != notifyProc)
continue;
@ -192,12 +192,11 @@ static bool ListenPortIncrement (
//===========================================================================
static void SocketGetAddresses (
NtSock * sock,
NetAddress * localAddr,
NetAddress * remoteAddr
plNetAddress* localAddr,
plNetAddress* remoteAddr
) {
// NetAddress may be bigger than sockaddr_in so start by zeroing the whole thing
memset(localAddr, 0, sizeof(*localAddr));
memset(remoteAddr, 0, sizeof(*remoteAddr));
localAddr->Clear();
remoteAddr->Clear();
// don't have to enter critsect or validate socket before referencing it
// because this routine is called before the user has a chance to close it
@ -470,7 +469,7 @@ static bool SocketInitConnect (
//===========================================================================
static void SocketInitListen (
NtSock * const sock,
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
for (;;) {
@ -509,7 +508,7 @@ static void SocketInitListen (
}
//===========================================================================
static SOCKET ListenSocket (NetAddress * listenAddr) {
static SOCKET ListenSocket(plNetAddress* listenAddr) {
// create a new socket to listen
SOCKET s;
if (INVALID_SOCKET == (s = socket(AF_INET, SOCK_STREAM, 0))) {
@ -540,19 +539,18 @@ static SOCKET ListenSocket (NetAddress * listenAddr) {
);
*/
NetAddressNode node = NetAddressGetNode(*listenAddr);
unsigned port = NetAddressGetPort(*listenAddr);
uint32_t node = listenAddr->GetHost();
uint16_t port = listenAddr->GetPort();
// bind socket to port
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons((uint16_t)port);
addr.sin_addr.S_un.S_addr = htonl(node);
addr.sin_port = htons(port);
addr.sin_addr.S_un.S_addr = node;
memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
if (bind(s, (sockaddr *) &addr, sizeof(addr))) {
wchar_t str[32];
NetAddressToString(*listenAddr, str, arrsize(str), kNetAddressFormatAll);
LogMsg(kLogError, "bind to addr %s failed (err %u)", str, WSAGetLastError());
plString str = listenAddr->AsString();
LogMsg(kLogError, "bind to addr %s failed (err %u)", str.c_str(), WSAGetLastError());
break;
}
@ -581,13 +579,13 @@ static SOCKET ListenSocket (NetAddress * listenAddr) {
}
// success!
NetAddressSetPort(port, listenAddr);
listenAddr->SetPort(port);
return s;
} while (false);
// failure!
closesocket(s);
NetAddressSetPort(0, listenAddr);
listenAddr->SetPort(0);
return INVALID_SOCKET;
}
@ -613,7 +611,7 @@ static void ListenPrepareListeners (fd_set * readfds) {
}
//===========================================================================
static SOCKET ConnectSocket (unsigned localPort, const NetAddress & addr) {
static SOCKET ConnectSocket (unsigned localPort, const plNetAddress& addr) {
SOCKET s;
if (INVALID_SOCKET == (s = socket(AF_INET, SOCK_STREAM, 0))) {
LogMsg(kLogError, "socket create failed");
@ -639,7 +637,7 @@ static SOCKET ConnectSocket (unsigned localPort, const NetAddress & addr) {
}
}
if (connect(s, (const sockaddr *) &addr, sizeof(addr))) {
if (connect(s, (const sockaddr *) &addr.GetAddressInfo(), sizeof(AddressType))) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
LogMsg(kLogError, "sockegt connect failed");
break;
@ -1127,12 +1125,12 @@ bool INtSocketOpCompleteQueuedSocketWrite (
//===========================================================================
unsigned NtSocketStartListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
s_listenCrit.Enter();
StartListenThread();
NetAddress addr = listenAddr;
plNetAddress addr = listenAddr;
for (;;) {
// if the port is already open then just increment the reference count
if (ListenPortIncrement(addr, notifyProc, 1))
@ -1152,7 +1150,7 @@ unsigned NtSocketStartListening (
}
s_listenCrit.Leave();
unsigned port = NetAddressGetPort(addr);
unsigned port = addr.GetPort();
if (port)
SetEvent(s_listenEvent);
@ -1161,7 +1159,7 @@ unsigned NtSocketStartListening (
//===========================================================================
void NtSocketStopListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
s_listenCrit.Enter();
@ -1172,7 +1170,7 @@ void NtSocketStopListening (
//===========================================================================
void NtSocketConnect (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param,
const void * sendData,

1
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Nt/pnAceNtThread.cpp

@ -61,7 +61,6 @@ namespace Nt {
//===========================================================================
void NtSleep (unsigned sleepMs) {
ThreadAssertCanBlock(__FILE__, __LINE__);
Sleep(sleepMs);
}

6
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/W9x/pnAceW9xInt.h

@ -88,7 +88,7 @@ bool W9xThreadWaitId (
);
void W9xSocketConnect (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param,
const void * sendData,
@ -126,11 +126,11 @@ void W9xSocketSetBacklogAlloc (
unsigned bufferSize
);
unsigned W9xSocketStartListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
);
void W9xSocketStopListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
);
void W9xSocketEnableNagling (

6
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/W9x/pnAceW9xSocket.cpp

@ -999,7 +999,7 @@ static LRESULT CALLBACK WndProc (
//===========================================================================
void W9xSocketConnect (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param,
const void * sendData,
@ -1148,7 +1148,7 @@ void W9xSocketDisconnect (
//===========================================================================
unsigned W9xSocketStartListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
return 0;
@ -1157,7 +1157,7 @@ unsigned W9xSocketStartListening (
//===========================================================================
void W9xSocketStopListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
}

50
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/Win32/pnAceW32Dns.cpp

@ -69,7 +69,7 @@ struct Lookup {
FAsyncLookupProc lookupProc;
unsigned port;
void * param;
wchar_t name[kMaxLookupName];
char name[kMaxLookupName];
char buffer[MAXGETHOSTSTRUCT];
};
@ -88,9 +88,6 @@ static unsigned s_nextLookupCancelId = 1;
//===========================================================================
static void LookupProcess (Lookup * lookup, unsigned error) {
unsigned count = 0;
NetAddress * addrs = nil;
if (error)
return;
@ -104,25 +101,18 @@ static void LookupProcess (Lookup * lookup, unsigned error) {
in_addr const * const * const inAddr = (in_addr **) host.h_addr_list;
// count the number of addresses
while (inAddr[count])
++count;
// allocate a buffer large enough to hold all the addresses
addrs = (NetAddress *)malloc(sizeof(*addrs) * count);
memset(addrs, 0, sizeof(*addrs) * count);
size_t count = arrsize(inAddr);
plNetAddress* addrs = new plNetAddress[count];
// fill in address data
const uint16_t port = htons((uint16_t) lookup->port);
for (unsigned i = 0; i < count; ++i) {
sockaddr_in * inetaddr = (sockaddr_in *) &addrs[i];
inetaddr->sin_family = AF_INET;
inetaddr->sin_addr = *inAddr[i];
inetaddr->sin_port = port;
for (size_t i = 0; i < count; ++i) {
addrs[i].SetHost(inAddr[i]->S_un.S_addr);
addrs[i].SetPort(lookup->port);
}
if (host.h_name && host.h_name[0])
StrToUnicode(lookup->name, host.h_name, arrsize(lookup->name));
strncpy(lookup->name, host.h_name, arrsize(lookup->name));
if (lookup->lookupProc)
lookup->lookupProc(lookup->param, lookup->name, count, addrs);
@ -134,7 +124,7 @@ static void LookupProcess (Lookup * lookup, unsigned error) {
delete lookup;
PerfSubCounter(kAsyncPerfNameLookupAttemptsCurr, 1);
free(addrs);
delete[] addrs;
}
//===========================================================================
@ -271,7 +261,7 @@ void DnsDestroy (unsigned exitThreadWaitMs) {
void AsyncAddressLookupName (
AsyncCancelId * cancelId, // out
FAsyncLookupProc lookupProc,
const wchar_t name[],
const char* name,
unsigned port,
void * param
) {
@ -282,9 +272,8 @@ void AsyncAddressLookupName (
PerfAddCounter(kAsyncPerfNameLookupAttemptsTotal, 1);
// Get name/port
char ansiName[kMaxLookupName];
StrToAnsi(ansiName, name, arrsize(ansiName));
if (char * portStr = StrChr(ansiName, ':')) {
char* ansiName = strdup(name);
if (char* portStr = StrChr(ansiName, ':')) {
if (unsigned newPort = StrToUnsigned(portStr + 1, nil, 10))
port = newPort;
*portStr = 0;
@ -295,7 +284,7 @@ void AsyncAddressLookupName (
lookup->lookupProc = lookupProc;
lookup->port = port;
lookup->param = param;
StrCopy(lookup->name, name, arrsize(lookup->name));
strncpy(lookup->name, name, arrsize(lookup->name));
s_critsect.Enter();
{
@ -312,7 +301,7 @@ void AsyncAddressLookupName (
lookup->cancelHandle = WSAAsyncGetHostByName(
s_lookupWindow,
WM_LOOKUP_FOUND_HOST,
ansiName,
name,
&lookup->buffer[0],
sizeof(lookup->buffer)
);
@ -327,7 +316,7 @@ void AsyncAddressLookupName (
void AsyncAddressLookupAddr (
AsyncCancelId * cancelId, // out
FAsyncLookupProc lookupProc,
const NetAddress & address,
const plNetAddress& address,
void * param
) {
ASSERT(lookupProc);
@ -340,13 +329,10 @@ void AsyncAddressLookupAddr (
lookup->lookupProc = lookupProc;
lookup->port = 1;
lookup->param = param;
NetAddressToString(
address,
lookup->name,
arrsize(lookup->name),
kNetAddressFormatNodeNumber
);
plString str = address.GetHostString();
strncpy(lookup->name, str.c_str(), arrsize(lookup->name));
s_critsect.Enter();
{
// Start the lookup thread if it wasn't started already

8
Sources/Plasma/NucleusLib/pnAsyncCoreExe/Private/pnAceInt.h

@ -50,6 +50,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNASYNCCOREEXE_PRIVATE_PNACEINT_H
#include "pnNetCommon/plNetAddress.h"
/*****************************************************************************
*
@ -106,7 +108,7 @@ typedef void (* FSleep) (unsigned sleepMs);
// Sockets
typedef void (* FAsyncSocketConnect) (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param,
const void * sendData,
@ -151,12 +153,12 @@ typedef void (* FAsyncSocketSetBacklogAlloc) (
);
typedef unsigned (* FAsyncSocketStartListening) (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
);
typedef void (* FAsyncSocketStopListening) (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
);

6
Sources/Plasma/NucleusLib/pnAsyncCoreExe/pnAceIo.cpp

@ -206,7 +206,7 @@ static unsigned GetConnHash (
//===========================================================================
void AsyncSocketConnect (
AsyncCancelId * cancelId,
const NetAddress & netAddr,
const plNetAddress& netAddr,
FAsyncNotifySocketProc notifyProc,
void * param,
const void * sendData,
@ -293,7 +293,7 @@ void AsyncSocketSetBacklogAlloc (
//===========================================================================
unsigned AsyncSocketStartListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
ASSERT(g_api.socketStartListening);
@ -302,7 +302,7 @@ unsigned AsyncSocketStartListening (
//===========================================================================
void AsyncSocketStopListening (
const NetAddress & listenAddr,
const plNetAddress& listenAddr,
FAsyncNotifySocketProc notifyProc
) {
ASSERT(g_api.socketStopListening);

3
Sources/Plasma/NucleusLib/pnAsyncCoreExe/pnAceTimer.cpp

@ -307,9 +307,6 @@ void AsyncTimerDelete (
// Wait until the timer procedure completes
if (timerProc) {
// ensure that I/O worker threads don't call this function with waitComplete=true
// to prevent a possible deadlock of a timer callback waiting for itself to complete
ThreadAssertCanBlock(__FILE__, __LINE__);
while (s_timerCurr == timerProc)
Sleep(1);

2
Sources/Plasma/NucleusLib/pnEncryption/CMakeLists.txt

@ -3,11 +3,13 @@ include_directories("../../NucleusLib")
include_directories(${OPENSSL_INCLUDE_DIR})
set(pnEncryption_SOURCES
plBigNum.cpp
plChallengeHash.cpp
plChecksum.cpp
)
set(pnEncryption_HEADERS
plBigNum.h
plChallengeHash.h
plChecksum.h
plRandom.h

57
Sources/Plasma/NucleusLib/pnUtils/pnUtBigNum.cpp → Sources/Plasma/NucleusLib/pnEncryption/plBigNum.cpp

@ -39,18 +39,12 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBigNum.cpp
*
***/
#include "pnUtBigNum.h"
#include "plBigNum.h"
#include <openssl/rand.h>
#include <algorithm>
static inline void byteswap(size_t size, unsigned char * data)
static inline void byteswap(size_t size, uint8_t* data)
{
for (size_t i = 0; i < (size / 2); ++i)
std::swap(data[i], data[size - i - 1]);
@ -58,32 +52,28 @@ static inline void byteswap(size_t size, unsigned char * data)
/****************************************************************************
*
* BigNum public methods
* plBigNum public methods
*
***/
//===========================================================================
BigNum::BigNum () : m_context(nil)
plBigNum::plBigNum () : m_context(nil)
{
BN_init(&m_number);
}
//===========================================================================
BigNum::BigNum (const BigNum & a) : m_context(nil)
plBigNum::plBigNum(const plBigNum& a) : m_context(nil)
{
BN_init(&m_number);
BN_copy(&m_number, &a.m_number);
}
//===========================================================================
BigNum::BigNum (unsigned a) : m_context(nil)
plBigNum::plBigNum(unsigned a) : m_context(nil)
{
BN_init(&m_number);
BN_set_word(&m_number, a);
}
//===========================================================================
BigNum::BigNum (unsigned bytes, const void * data, bool le) : m_context(nil)
plBigNum::plBigNum(unsigned bytes, const void* data, bool le) : m_context(nil)
{
BN_init(&m_number);
if (le)
@ -92,16 +82,15 @@ BigNum::BigNum (unsigned bytes, const void * data, bool le) : m_context(nil)
FromData_BE(bytes, data);
}
//===========================================================================
BigNum::~BigNum ()
plBigNum::~plBigNum ()
{
if (m_context)
BN_CTX_free(m_context);
BN_free(&m_number);
}
//===========================================================================
int BigNum::Compare (uint32_t a) const {
int plBigNum::Compare(uint32_t a) const
{
// -1 if (this < a)
// 0 if (this == a)
// 1 if (this > a)
@ -118,43 +107,39 @@ int BigNum::Compare (uint32_t a) const {
return 1;
}
//===========================================================================
void BigNum::FromData_LE (unsigned bytes, const void * data)
void plBigNum::FromData_LE(uint32_t bytes, const void* data)
{
unsigned char * buffer = new unsigned char[bytes];
uint8_t* buffer = new uint8_t[bytes];
memcpy(buffer, data, bytes);
byteswap(bytes, buffer);
BN_bin2bn(buffer, bytes, &m_number);
delete [] buffer;
delete[] buffer;
}
//===========================================================================
unsigned char * BigNum::GetData_BE (unsigned * bytes) const
uint8_t* plBigNum::GetData_BE(uint32_t* bytes) const
{
*bytes = BN_num_bytes(&m_number);
unsigned char * data = new unsigned char[*bytes];
uint8_t* data = new uint8_t[*bytes];
BN_bn2bin(&m_number, data);
return data;
}
//===========================================================================
unsigned char * BigNum::GetData_LE (unsigned * bytes) const
uint8_t* plBigNum::GetData_LE(uint32_t* bytes) const
{
*bytes = BN_num_bytes(&m_number);
unsigned char * data = new unsigned char[*bytes];
uint8_t* data = new uint8_t[*bytes];
BN_bn2bin(&m_number, data);
byteswap(*bytes, data);
return data;
}
//===========================================================================
void BigNum::Rand (unsigned bits, BigNum * seed)
void plBigNum::Rand(uint32_t bits, plBigNum* seed)
{
// this = random number with bits or fewer bits
unsigned seedbytes;
unsigned char * seedData = seed->GetData_BE(&seedbytes);
uint32_t seedbytes;
uint8_t* seedData = seed->GetData_BE(&seedbytes);
RAND_seed(seedData, seedbytes);
BN_rand(&m_number, bits, 0, 0);
delete [] seedData;
delete[] seedData;
}

95
Sources/Plasma/NucleusLib/pnUtils/pnUtBigNum.h → Sources/Plasma/NucleusLib/pnEncryption/plBigNum.h

@ -39,31 +39,26 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBigNum.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBIGNUM_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBIGNUM_H
#include "Pch.h"
#ifndef plBigNum_inc
#define plBigNum_inc
/*****************************************************************************
*
* BigNum class
* plBigNum class
*
***/
#include "HeadSpin.h"
#include <openssl/bn.h>
class BigNum {
class plBigNum
{
private:
BIGNUM m_number;
mutable BN_CTX * m_context;
mutable BN_CTX* m_context;
BN_CTX * GetContext () const
BN_CTX* GetContext() const
{
if (!m_context)
m_context = BN_CTX_new();
@ -71,13 +66,13 @@ private:
}
public:
BigNum ();
BigNum (const BigNum & a);
BigNum (unsigned a);
BigNum (unsigned bytess, const void * data, bool le=false);
~BigNum ();
plBigNum();
plBigNum(const plBigNum& a);
plBigNum(uint32_t a);
plBigNum(uint32_t bytess, const void* data, bool le=false);
~plBigNum();
BigNum & operator= (const BigNum & a)
plBigNum& operator=(const plBigNum& a)
{
BN_copy(&m_number, &a.m_number);
return *this;
@ -86,37 +81,39 @@ public:
// Constant parameters need not be distinct from the destination or from
// each other
void Add (const BigNum & a, uint32_t b)
void Add(const plBigNum& a, uint32_t b)
{
// this = a + b
BN_copy(&m_number, &a.m_number);
BN_add_word(&m_number, b);
}
void Add (const BigNum & a, const BigNum & b)
void Add(const plBigNum& a, const plBigNum& b)
{
// this = a + b
BN_add(&m_number, &a.m_number, &b.m_number);
}
int Compare (uint32_t a) const;
int Compare (const BigNum & a) const
int Compare(uint32_t a) const;
int Compare(const plBigNum& a) const
{
return BN_cmp(&m_number, &a.m_number);
}
bool isZero() const
{
return BN_is_zero(&m_number);
}
void Div (const BigNum & a, uint32_t b, uint32_t * remainder)
void Div(const plBigNum& a, uint32_t b, uint32_t* remainder)
{
// this = a / b, remainder = a % b
BN_copy(&m_number, &a.m_number);
*remainder = (uint32_t)BN_div_word(&m_number, b);
}
void Div (const BigNum & a, const BigNum & b, BigNum * remainder)
void Div(const plBigNum& a, const plBigNum& b, plBigNum* remainder)
{
// this = a / b, remainder = a % b
// either this or remainder may be nil
@ -124,55 +121,55 @@ public:
&a.m_number, &b.m_number, GetContext());
}
void FromData_BE (unsigned bytess, const void * data)
void FromData_BE(uint32_t bytess, const void* data)
{
BN_bin2bn((const unsigned char *)data, bytess, &m_number);
BN_bin2bn((const uint8_t*)data, bytess, &m_number);
}
void FromData_LE (unsigned bytess, const void * data);
void FromData_LE(uint32_t bytess, const void* data);
unsigned char * GetData_BE (unsigned * bytess) const;
unsigned char * GetData_LE (unsigned * bytess) const;
uint8_t* GetData_BE(uint32_t* bytess) const;
uint8_t* GetData_LE(uint32_t* bytess) const;
bool IsPrime () const
bool IsPrime() const
{
// Cyan's code uses 3 checks, so we'll follow suit.
// This provides an accurate answer to p < 0.015625
return BN_is_prime_fasttest(&m_number, 3, nil, GetContext(), nil, 1) > 0;
}
void Mod (const BigNum & a, const BigNum & b)
void Mod(const plBigNum& a, const plBigNum& b)
{
// this = a % b
BN_div(nil, &m_number, &a.m_number, &b.m_number, GetContext());
}
void Mul (const BigNum & a, uint32_t b)
void Mul(const plBigNum& a, uint32_t b)
{
// this = a * b
BN_copy(&m_number, &a.m_number);
BN_mul_word(&m_number, b);
}
void Mul (const BigNum & a, const BigNum & b)
void Mul(const plBigNum& a, const plBigNum& b)
{
// this = a * b
BN_mul(&m_number, &a.m_number, &b.m_number, GetContext());
}
void PowMod (uint32_t a, const BigNum & b, const BigNum & c)
void PowMod(uint32_t a, const plBigNum& b, const plBigNum& c)
{
// this = a ^ b % c
PowMod(BigNum(a), b, c);
PowMod(plBigNum(a), b, c);
}
void PowMod (const BigNum & a, const BigNum & b, const BigNum & c)
void PowMod(const plBigNum& a, const plBigNum& b, const plBigNum& c)
{
// this = a ^ b % c
BN_mod_exp(&m_number, &a.m_number, &b.m_number, &c.m_number, GetContext());
}
void Rand (const BigNum & a, BigNum * seed)
void Rand(const plBigNum& a, plBigNum* seed)
{
// this = random number less than a
int bits = BN_num_bits(&a.m_number);
@ -181,49 +178,49 @@ public:
while (Compare(a) >= 0);
}
void Rand (unsigned bits, BigNum * seed);
void Rand(uint32_t bits, plBigNum* seed);
void RandPrime (unsigned bits, BigNum * seed)
void RandPrime(uint32_t bits, plBigNum* seed)
{
BN_generate_prime(&m_number, bits, 1, nil, nil, nil, nil);
}
void Set (const BigNum & a)
void Set(const plBigNum& a)
{
BN_copy(&m_number, &a.m_number);
}
void Set (unsigned a)
void Set(uint32_t a)
{
BN_set_word(&m_number, a);
}
void SetOne () { Set(1); }
void SetZero () { Set(0); }
void SetOne() { Set(1); }
void SetZero() { Set(0); }
void Shl (const BigNum & a, unsigned b)
void Shl(const plBigNum& a, uint32_t b)
{
// this = a << b
BN_lshift(&m_number, &a.m_number, b);
}
void Shr (const BigNum & a, unsigned b)
void Shr(const plBigNum& a, uint32_t b)
{
// this = a >> b
BN_rshift(&m_number, &a.m_number, b);
}
void Sub (const BigNum & a, uint32_t b)
void Sub(const plBigNum& a, uint32_t b)
{
// this = a - b
BN_copy(&m_number, &a.m_number);
BN_sub_word(&m_number, b);
}
void Sub (const BigNum & a, const BigNum & b)
void Sub(const plBigNum& a, const plBigNum& b)
{
// this = a - b
BN_sub(&m_number, &a.m_number, &b.m_number);
}
};
#endif
#endif // plBigNum_inc

1
Sources/Plasma/NucleusLib/pnEncryption/plChallengeHash.cpp

@ -41,7 +41,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/
#include "plChallengeHash.h"
#include "pnUtils/pnUtils.h"
ShaDigest fSeed;

64
Sources/Plasma/NucleusLib/pnNetBase/pnNbSrvs.cpp

@ -53,26 +53,26 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*
***/
static wchar_t s_authAddrConsole[64] = {0};
static const wchar_t * s_authAddrs[] = {
static char s_authAddrConsole[64] = {0};
static const char* s_authAddrs[] = {
s_authAddrConsole
};
static wchar_t s_fileAddrConsole[64] = {0};
static const wchar_t * s_fileAddrs[] = {
static char s_fileAddrConsole[64] = {0};
static const char* s_fileAddrs[] = {
s_fileAddrConsole
};
static wchar_t s_csrAddrConsole[64] = {0};
static const wchar_t * s_csrAddrs[] = {
static char s_csrAddrConsole[64] = {0};
static const char* s_csrAddrs[] = {
s_csrAddrConsole
};
static wchar_t s_gateKeeperAddrConsole[64] = {0};
static const wchar_t * s_gateKeeperAddrs[] = {
static char s_gateKeeperAddrConsole[64] = {0};
static const char* s_gateKeeperAddrs[] = {
s_gateKeeperAddrConsole
};
@ -86,97 +86,97 @@ static const wchar_t * s_gateKeeperAddrs[] = {
//============================================================================
// Auth
//============================================================================
unsigned GetAuthSrvHostnames (const wchar_t *** addrs) {
unsigned GetAuthSrvHostnames (const char*** addrs) {
*addrs = s_authAddrs;
return arrsize(s_authAddrs);
}
//============================================================================
void SetAuthSrvHostname (const wchar_t addr[]) {
void SetAuthSrvHostname (const char addr[]) {
wcsncpy(s_authAddrConsole, addr, arrsize(s_authAddrConsole));
strncpy(s_authAddrConsole, addr, arrsize(s_authAddrConsole));
}
//============================================================================
// File
//============================================================================
unsigned GetFileSrvHostnames (const wchar_t *** addrs) {
unsigned GetFileSrvHostnames (const char*** addrs) {
*addrs = s_fileAddrs;
return arrsize(s_fileAddrs);
}
//============================================================================
void SetFileSrvHostname (const wchar_t addr[]) {
void SetFileSrvHostname (const char addr[]) {
wcsncpy(s_fileAddrConsole, addr, arrsize(s_fileAddrConsole));
strncpy(s_fileAddrConsole, addr, arrsize(s_fileAddrConsole));
}
//============================================================================
// Csr
//============================================================================
unsigned GetCsrSrvHostnames (const wchar_t *** addrs) {
unsigned GetCsrSrvHostnames (const char*** addrs) {
*addrs = s_csrAddrs;
return arrsize(s_csrAddrs);
}
//============================================================================
void SetCsrSrvHostname (const wchar_t addr[]) {
void SetCsrSrvHostname (const char addr[]) {
wcsncpy(s_csrAddrConsole, addr, arrsize(s_csrAddrConsole));
strncpy(s_csrAddrConsole, addr, arrsize(s_csrAddrConsole));
}
//============================================================================
// GateKeeper
//============================================================================
unsigned GetGateKeeperSrvHostnames (const wchar_t *** addrs) {
unsigned GetGateKeeperSrvHostnames (const char*** addrs) {
*addrs = s_gateKeeperAddrs;
return arrsize(s_gateKeeperAddrs);
}
//============================================================================
void SetGateKeeperSrvHostname (const wchar_t addr[]) {
wcsncpy(s_gateKeeperAddrConsole, addr, arrsize(s_gateKeeperAddrConsole));
void SetGateKeeperSrvHostname (const char addr[]) {
strncpy(s_gateKeeperAddrConsole, addr, arrsize(s_gateKeeperAddrConsole));
}
//============================================================================
// User-visible Server
//============================================================================
static wchar_t s_serverStatusUrl[256] = {0};
static wchar_t s_serverSignupUrl[256] = {0};
static wchar_t s_serverName[256] = {0};
static char s_serverStatusUrl[256] = {0};
static char s_serverSignupUrl[256] = {0};
static char s_serverName[256] = {0};
//============================================================================
const wchar_t *GetServerStatusUrl () {
const char* GetServerStatusUrl () {
return s_serverStatusUrl;
}
//============================================================================
void SetServerStatusUrl (const wchar_t url[]) {
wcsncpy(s_serverStatusUrl, url, arrsize(s_serverStatusUrl));
void SetServerStatusUrl (const char url[]) {
strncpy(s_serverStatusUrl, url, arrsize(s_serverStatusUrl));
}
//============================================================================
const wchar_t *GetServerSignupUrl () {
const char* GetServerSignupUrl () {
return s_serverSignupUrl;
}
//============================================================================
void SetServerSignupUrl (const wchar_t url[]) {
wcsncpy(s_serverSignupUrl, url, arrsize(s_serverSignupUrl));
void SetServerSignupUrl (const char url[]) {
strncpy(s_serverSignupUrl, url, arrsize(s_serverSignupUrl));
}
//============================================================================
const wchar_t *GetServerDisplayName () {
const char* GetServerDisplayName () {
return s_serverName;
}
//============================================================================
void SetServerDisplayName (const wchar_t name[]) {
wcsncpy(s_serverName, name, arrsize(s_serverName));
void SetServerDisplayName (const char name[]) {
strncpy(s_serverName, name, arrsize(s_serverName));
}

28
Sources/Plasma/NucleusLib/pnNetBase/pnNbSrvs.h

@ -84,25 +84,25 @@ enum ESrvType {
*
***/
unsigned GetAuthSrvHostnames (const wchar_t *** addrs); // returns addrCount
void SetAuthSrvHostname (const wchar_t addr[]);
unsigned GetAuthSrvHostnames (const char*** addrs); // returns addrCount
void SetAuthSrvHostname (const char addr[]);
unsigned GetFileSrvHostnames (const wchar_t *** addrs); // returns addrCount
void SetFileSrvHostname (const wchar_t addr[]);
unsigned GetFileSrvHostnames (const char*** addrs); // returns addrCount
void SetFileSrvHostname (const char addr[]);
unsigned GetCsrSrvHostnames (const wchar_t *** addrs); // returns addrCount
void SetCsrSrvHostname (const wchar_t addr[]);
unsigned GetCsrSrvHostnames (const char*** addrs); // returns addrCount
void SetCsrSrvHostname (const char addr[]);
unsigned GetGateKeeperSrvHostnames (const wchar_t *** addrs); // returns addrCount
void SetGateKeeperSrvHostname (const wchar_t addr[]);
unsigned GetGateKeeperSrvHostnames (const char*** addrs); // returns addrCount
void SetGateKeeperSrvHostname (const char addr[]);
const wchar_t *GetServerStatusUrl ();
void SetServerStatusUrl (const wchar_t url[]);
const char *GetServerStatusUrl ();
void SetServerStatusUrl (const char url[]);
const wchar_t *GetServerSignupUrl ();
void SetServerSignupUrl (const wchar_t url[]);
const char *GetServerSignupUrl ();
void SetServerSignupUrl (const char url[]);
const wchar_t *GetServerDisplayName ();
void SetServerDisplayName (const wchar_t name[]);
const char *GetServerDisplayName ();
void SetServerDisplayName (const char name[]);
#endif // pnNbSrvs_inc

18
Sources/Plasma/NucleusLib/pnNetCli/Intern.h

@ -80,8 +80,8 @@ const NetMsgInitSend * NetMsgChannelFindSendMessage (
void NetMsgChannelGetDhConstants (
const NetMsgChannel * channel,
unsigned * dh_g,
const BigNum ** dh_xa, // client: dh_x server: dh_a
const BigNum ** dh_n
const plBigNum** dh_xa, // client: dh_x server: dh_a
const plBigNum** dh_n
);
@ -92,18 +92,18 @@ void NetMsgChannelGetDhConstants (
***/
void NetMsgCryptClientStart (
NetMsgChannel * channel,
NetMsgChannel* channel,
unsigned seedBytes,
const uint8_t seedData[],
BigNum * clientSeed,
BigNum * serverSeed
const uint8_t seedData[],
plBigNum* clientSeed,
plBigNum* serverSeed
);
void NetMsgCryptServerConnect (
NetMsgChannel * channel,
NetMsgChannel* channel,
unsigned seedBytes,
const uint8_t seedData[],
BigNum * clientSeed
const uint8_t seedData[],
plBigNum* clientSeed
);

1
Sources/Plasma/NucleusLib/pnNetCli/Pch.h

@ -54,6 +54,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "pnUtils/pnUtils.h"
#include "pnNetBase/pnNetBase.h"
#include "pnAsyncCore/pnAsyncCore.h"
#include "pnEncryption/plBigNum.h"
#include "pnNetCli.h"
#include "Intern.h"

79
Sources/Plasma/NucleusLib/pnNetCli/pnNcChannel.cpp

@ -46,6 +46,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
***/
#include "Pch.h"
#include "hsThread.h"
#include <list>
#pragma hdrstop
@ -60,34 +62,33 @@ namespace pnNetCli {
struct ChannelCrit {
~ChannelCrit ();
ChannelCrit ();
inline void Enter () { m_critsect.Enter(); }
inline void Leave () { m_critsect.Leave(); }
inline void EnterSafe () { if (m_init) m_critsect.Enter(); }
inline void LeaveSafe () { if (m_init) m_critsect.Leave(); }
inline void Enter () { m_critsect.Lock(); }
inline void Leave () { m_critsect.Unlock(); }
inline void EnterSafe () { if (m_init) m_critsect.Lock(); }
inline void LeaveSafe () { if (m_init) m_critsect.Unlock(); }
private:
bool m_init;
CCritSect m_critsect;
hsMutex m_critsect;
};
struct NetMsgChannel : AtomicRef {
LINK(NetMsgChannel) m_link;
unsigned m_protocol;
uint32_t m_protocol;
bool m_server;
// Message definitions
unsigned m_largestRecv;
uint32_t m_largestRecv;
ARRAY(NetMsgInitSend) m_sendMsgs;
ARRAY(NetMsgInitRecv) m_recvMsgs;
// Diffie-Hellman constants
unsigned m_dh_g;
BigNum m_dh_xa; // client: dh_x server: dh_a
BigNum m_dh_n;
uint32_t m_dh_g;
plBigNum m_dh_xa; // client: dh_x server: dh_a
plBigNum m_dh_n;
};
static ChannelCrit s_channelCrit;
static LIST(NetMsgChannel) * s_channels;
static ChannelCrit s_channelCrit;
static std::list<NetMsgChannel*>* s_channels;
/****************************************************************************
@ -105,8 +106,9 @@ ChannelCrit::ChannelCrit () {
ChannelCrit::~ChannelCrit () {
EnterSafe();
if (s_channels) {
while (NetMsgChannel * const channel = s_channels->Head()) {
s_channels->Unlink(channel);
while (s_channels->size()) {
NetMsgChannel* const channel = s_channels->front();
s_channels->remove(channel);
channel->DecRef("ChannelLink");
}
@ -239,30 +241,29 @@ static void AddRecvMsgs_CS (
// copy the message handler
*dst = *src;
const unsigned bytes = ValidateMsg(dst->msg);
const uint32_t bytes = ValidateMsg(dst->msg);
channel->m_largestRecv = max(channel->m_largestRecv, bytes);
}
}
//===========================================================================
static NetMsgChannel * FindChannel_CS (unsigned protocol, bool server) {
static NetMsgChannel* FindChannel_CS (uint32_t protocol, bool server) {
if (!s_channels)
return nil;
NetMsgChannel * channel = s_channels->Head();
for (; channel; channel = s_channels->Next(channel)) {
if ((channel->m_protocol == protocol) && (channel->m_server == server))
break;
std::list<NetMsgChannel*>::iterator it = s_channels->begin();
for (; it != s_channels->end(); ++it) {
if (((*it)->m_protocol == protocol) && ((*it)->m_server == server))
return *it;
}
return channel;
return nil;
}
//===========================================================================
static NetMsgChannel * FindOrCreateChannel_CS (unsigned protocol, bool server) {
static NetMsgChannel* FindOrCreateChannel_CS (uint32_t protocol, bool server) {
if (!s_channels) {
s_channels = new LIST(NetMsgChannel);
s_channels->SetLinkOffset(offsetof(NetMsgChannel, m_link));
s_channels = new std::list<NetMsgChannel*>();
}
// find or create protocol
@ -273,7 +274,7 @@ static NetMsgChannel * FindOrCreateChannel_CS (unsigned protocol, bool server) {
channel->m_server = server;
channel->m_largestRecv = 0;
s_channels->Link(channel);
s_channels->push_back(channel);
channel->IncRef("ChannelLink");
}
@ -291,7 +292,7 @@ static NetMsgChannel * FindOrCreateChannel_CS (unsigned protocol, bool server) {
NetMsgChannel * NetMsgChannelLock (
unsigned protocol,
bool server,
unsigned * largestRecv
uint32_t * largestRecv
) {
NetMsgChannel * channel;
s_channelCrit.Enter();
@ -353,9 +354,9 @@ const NetMsgInitSend * NetMsgChannelFindSendMessage (
//============================================================================
void NetMsgChannelGetDhConstants (
const NetMsgChannel * channel,
unsigned * dh_g,
const BigNum ** dh_xa,
const BigNum ** dh_n
uint32_t * dh_g,
const plBigNum** dh_xa,
const plBigNum** dh_n
) {
if (dh_g) *dh_g = channel->m_dh_g;
if (dh_xa) *dh_xa = &channel->m_dh_xa;
@ -374,15 +375,15 @@ void NetMsgChannelGetDhConstants (
//===========================================================================
void NetMsgProtocolRegister (
unsigned protocol,
uint32_t protocol,
bool server,
const NetMsgInitSend sendMsgs[],
unsigned sendMsgCount,
uint32_t sendMsgCount,
const NetMsgInitRecv recvMsgs[],
unsigned recvMsgCount,
unsigned dh_g,
const BigNum & dh_xa, // client: dh_x server: dh_a
const BigNum & dh_n
uint32_t recvMsgCount,
uint32_t dh_g,
const plBigNum& dh_xa, // client: dh_x server: dh_a
const plBigNum& dh_n
) {
s_channelCrit.EnterSafe();
{
@ -406,10 +407,10 @@ void NetMsgProtocolRegister (
}
//===========================================================================
void NetMsgProtocolDestroy (unsigned protocol, bool server) {
void NetMsgProtocolDestroy (uint32_t protocol, bool server) {
s_channelCrit.EnterSafe();
if (NetMsgChannel * channel = FindChannel_CS(protocol, server)) {
s_channels->Unlink(channel);
if (NetMsgChannel* channel = FindChannel_CS(protocol, server)) {
s_channels->remove(channel);
channel->DecRef("ChannelLink");
}
s_channelCrit.LeaveSafe();

20
Sources/Plasma/NucleusLib/pnNetCli/pnNcCli.cpp

@ -58,7 +58,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
# define NCCLI_LOG LogMsg
#endif
#ifndef PLASMA_EXTERNAL_RELEASE
#if !defined(PLASMA_EXTERNAL_RELEASE) && defined(HS_BUILD_FOR_WIN32)
struct NetLogMessage_Header
{
@ -173,7 +173,7 @@ static void PutBufferOnWire (NetCli * cli, void * data, unsigned bytes) {
uint8_t * temp = NULL;
#ifndef PLASMA_EXTERNAL_RELEASE
#if !defined(PLASMA_EXTERNAL_RELEASE) && defined(HS_BUILD_FOR_WIN32)
// Write to the netlog
if (s_netlog) {
NetLogMessage_Header header;
@ -309,7 +309,7 @@ static void BufferedSendData (
else
{
// Value arrays are passed in by ptr
for (int i = 0; i < count; i++) {
for (size_t i = 0; i < count; i++) {
if (cmd->size == sizeof(uint8_t)) {
((uint8_t*)temp)[i] = ((uint8_t*)*msg)[i];
} else if (cmd->size == sizeof(uint16_t)) {
@ -449,7 +449,7 @@ static bool DispatchData (NetCli * cli, void * param) {
// byte-swap integers
// This is so screwed up >.<
for (int i = 0; i < count; i++) {
for (size_t i = 0; i < count; i++) {
if (cli->recvField->size == sizeof(uint16_t)) {
((uint16_t*)data)[i] = hsToLE16(((uint16_t*)data)[i]);
} else if (cli->recvField->size == sizeof(uint32_t)) {
@ -652,8 +652,8 @@ static void CreateSymmetricKey (
static void ClientConnect (NetCli * cli) {
// Initiate diffie-hellman for client
BigNum clientSeed;
BigNum serverSeed;
plBigNum clientSeed;
plBigNum serverSeed;
NetMsgCryptClientStart(
cli->channel,
sizeof(cli->seed),
@ -717,7 +717,7 @@ static bool ServerRecvConnect (
else {
// Compute client seed
uint8_t clientSeed[kNetMaxSymmetricSeedBytes];
BigNum clientSeedValue;
plBigNum clientSeedValue;
{
NetMsgCryptServerConnect(
cli->channel,
@ -761,7 +761,7 @@ static bool ClientRecvEncrypt (
return false;
// find out if we want encryption
const BigNum * DH_N;
const plBigNum* DH_N;
NetMsgChannelGetDhConstants(cli->channel, nil, nil, &DH_N);
bool encrypt = !DH_N->isZero();
@ -919,7 +919,7 @@ static NetCli * ConnCreate (
cli->mode = mode;
cli->SetValue(kNilGuid);
#ifndef PLASMA_EXTERNAL_RELEASE
#if !defined(PLASMA_EXTERNAL_RELEASE) && defined(HS_BUILD_FOR_WIN32)
// Network debug pipe
if (!s_netlog) {
InitializeCriticalSection(&s_pipeCritical);
@ -1124,7 +1124,7 @@ bool NetCliDispatch (
cli->input.Add(bytes, data);
bool result = DispatchData(cli, param);
#ifndef PLASMA_EXTERNAL_RELEASE
#if !defined(PLASMA_EXTERNAL_RELEASE) && defined(HS_BUILD_FOR_WIN32)
// Write to the netlog
if (s_netlog) {
NetLogMessage_Header header;

54
Sources/Plasma/NucleusLib/pnNetCli/pnNcEncrypt.cpp

@ -58,23 +58,23 @@ namespace pnNetCli {
// g and n are pregenerated and published
// (built into both client and server software)
BigNum g(4);
BigNum n; n.RandPrime(kKeyBits, &seed);
plBigNum g(4);
plBigNum n; n.RandPrime(kKeyBits, &seed);
// a and x are pregenerated; a is built into server software, and x is
// built into client software
BigNum a; a.Rand(kKeyBits, &seed);
BigNum x; x.PowMod(g, a, n);
plBigNum a; a.Rand(kKeyBits, &seed);
plBigNum x; x.PowMod(g, a, n);
// client chooses b and y on connect, and sends y to the server
BigNum b; b.Rand(kKeyBits, &seed);
BigNum y; y.PowMod(g, b, n);
plBigNum b; b.Rand(kKeyBits, &seed);
plBigNum y; y.PowMod(g, b, n);
// server computes key: k = y^a mod n
BigNum ka; ka.PowMod(y, a, n);
plBigNum ka; ka.PowMod(y, a, n);
// client computes key: k = x^b mod n
BigNum kb; kb.PowMod(x, b, n);
plBigNum kb; kb.PowMod(x, b, n);
***/
@ -90,14 +90,14 @@ COMPILER_ASSERT(IS_POW2(kNetDiffieHellmanKeyBits));
//============================================================================
// TODO: Cache computed keys
static void GetCachedServerKey (
NetMsgChannel * channel,
BigNum * ka,
const BigNum & dh_y
NetMsgChannel* channel,
plBigNum* ka,
const plBigNum& dh_y
) {
// Get diffie-hellman constants
unsigned DH_G;
const BigNum * DH_A;
const BigNum * DH_N;
unsigned DH_G;
const plBigNum* DH_A;
const plBigNum* DH_N;
NetMsgChannelGetDhConstants(channel, &DH_G, &DH_A, &DH_N);
hsAssert(!DH_N->isZero(), "DH_N must not be zero in encrypted mode");
@ -114,15 +114,15 @@ static void GetCachedServerKey (
//============================================================================
void NetMsgCryptClientStart (
NetMsgChannel * channel,
NetMsgChannel* channel,
unsigned seedBytes,
const uint8_t seedData[],
BigNum * clientSeed,
BigNum * serverSeed
const uint8_t seedData[],
plBigNum* clientSeed,
plBigNum* serverSeed
) {
unsigned DH_G;
const BigNum * DH_X;
const BigNum * DH_N;
const plBigNum* DH_X;
const plBigNum* DH_N;
NetMsgChannelGetDhConstants(channel, &DH_G, &DH_X, &DH_N);
if (DH_N->isZero()) { // no actual encryption, but the caller expects a seed
clientSeed->SetZero();
@ -130,9 +130,9 @@ void NetMsgCryptClientStart (
}
else {
// Client chooses b and y on connect
BigNum g(DH_G);
BigNum seed(seedBytes, seedData);
BigNum b; b.Rand(kNetDiffieHellmanKeyBits, &seed);
plBigNum g(DH_G);
plBigNum seed(seedBytes, seedData);
plBigNum b; b.Rand(kNetDiffieHellmanKeyBits, &seed);
// Client computes key: kb = x^b mod n
clientSeed->PowMod(*DH_X, b, *DH_N);
@ -144,13 +144,13 @@ void NetMsgCryptClientStart (
//============================================================================
void NetMsgCryptServerConnect (
NetMsgChannel * channel,
NetMsgChannel* channel,
unsigned seedBytes,
const uint8_t seedData[],
BigNum * clientSeed
const uint8_t seedData[],
plBigNum* clientSeed
) {
// Server computes client key: ka = y^a mod n
const BigNum dh_y(seedBytes, seedData);
const plBigNum dh_y(seedBytes, seedData);
GetCachedServerKey(channel, clientSeed, dh_y);
}

15
Sources/Plasma/NucleusLib/pnNetCli/pnNetCli.h

@ -48,6 +48,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETCLI_PNNETCLI_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETCLI_PNNETCLI_H
#include "pnEncryption/plBigNum.h"
/*****************************************************************************
*
@ -318,20 +319,20 @@ struct NetMsgInitRecv {
};
void NetMsgProtocolRegister (
unsigned protocol, // from pnNetBase/pnNbProtocol.h
uint32_t protocol, // from pnNetBase/pnNbProtocol.h
bool server,
const NetMsgInitSend sendMsgs[], // messages this program can send
unsigned sendMsgCount,
uint32_t sendMsgCount,
const NetMsgInitRecv recvMsgs[], // messages this program can receive
unsigned recvMsgCount,
uint32_t recvMsgCount,
// Diffie-Hellman keys
unsigned dh_g,
const BigNum & dh_xa, // client: dh_x server: dh_a
const BigNum & dh_n
uint32_t dh_g,
const plBigNum& dh_xa, // client: dh_x server: dh_a
const plBigNum& dh_n
);
void NetMsgProtocolDestroy (
unsigned protocol,
uint32_t protocol,
bool server
);

52
Sources/Plasma/NucleusLib/pnNetCommon/plNetAddress.cpp

@ -50,47 +50,41 @@ plNetAddress::plNetAddress()
Clear();
}
plNetAddress::plNetAddress(uint32_t addr, int port)
plNetAddress::plNetAddress(uint32_t addr, uint16_t port)
{
Clear();
SetHost(addr);
SetPort(port);
}
plNetAddress::plNetAddress(const char * addr, int port)
plNetAddress::plNetAddress(const char* addr, uint16_t port)
{
Clear();
SetHost(addr);
SetPort(port);
}
bool plNetAddress::SetAnyAddr()
{
{
fAddr.sin_family = AF_INET;
fAddr.sin_addr.s_addr = INADDR_ANY;
return true;
}
bool plNetAddress::SetAnyPort()
{
{
fAddr.sin_family = AF_INET;
fAddr.sin_port = htons(0);
return true;
}
bool plNetAddress::SetPort(int port)
{
bool plNetAddress::SetPort(uint16_t port)
{
fAddr.sin_family = AF_INET;
fAddr.sin_port = htons(port);
return true;
}
void plNetAddress::Clear()
{
memset(&fAddr,0,sizeof(fAddr));
@ -98,16 +92,14 @@ void plNetAddress::Clear()
fAddr.sin_addr.s_addr = INADDR_ANY;
}
int plNetAddress::GetPort() const
uint16_t plNetAddress::GetPort() const
{
return ntohs(fAddr.sin_port);
}
std::string plNetAddress::GetHostString() const
plString plNetAddress::GetHostString() const
{
return std::string(pnNetCommon::GetTextAddr(fAddr.sin_addr.s_addr));
return pnNetCommon::GetTextAddr(fAddr.sin_addr.s_addr);
}
uint32_t plNetAddress::GetHost() const
@ -115,37 +107,35 @@ uint32_t plNetAddress::GetHost() const
return fAddr.sin_addr.s_addr;
}
std::string plNetAddress::GetHostWithPort() const
plString plNetAddress::GetHostWithPort() const
{
static const int buf_len = 1024;
char buf[buf_len];
sprintf(buf,"%s:%d",pnNetCommon::GetTextAddr(fAddr.sin_addr.s_addr),GetPort());
return std::string(buf);
plStringStream ss;
ss << pnNetCommon::GetTextAddr(fAddr.sin_addr.s_addr) << ":" << GetPort();
return ss.GetString();
}
bool plNetAddress::SetHost(const char * hostname)
bool plNetAddress::SetHost(const char* hostname)
{
fAddr.sin_addr.s_addr = pnNetCommon::GetBinAddr(hostname);
fAddr.sin_family = AF_INET;
return true;
}
bool plNetAddress::SetHost(uint32_t addr)
bool plNetAddress::SetHost(uint32_t addr)
{
memcpy(&fAddr.sin_addr, &addr,sizeof(addr));
fAddr.sin_family = AF_INET;
return true;
}
std::string plNetAddress::AsString() const
plString plNetAddress::AsString() const
{
char buf[100] = "";
sprintf(buf,"IP:%s:%d",pnNetCommon::GetTextAddr(fAddr.sin_addr.s_addr),GetPort());
return std::string(buf);
}
plStringStream ss;
ss << "IP:" << pnNetCommon::GetTextAddr(fAddr.sin_addr.s_addr);
ss << ":" << GetPort();
return ss.GetString();
}
void plNetAddress::Read(hsStream * s)
{

146
Sources/Plasma/NucleusLib/pnNetCommon/plNetAddress.h

@ -44,6 +44,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef plNetAddress_h_inc
#define plNetAddress_h_inc
#include "HeadSpin.h"
#include "plString.h"
#include "hsStlUtils.h"
#include "hsStream.h"
@ -66,33 +68,155 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
typedef sockaddr_in AddressType;
/**
* A class representing a network address endpoint, as a pair of host address
* and port number.
*
* Internally, this class stores the network address using the sockaddr_in
* structure, but provides methods to transparently get and set the host
* address and port.
*/
class plNetAddress
{
// fAddr must be first field
AddressType fAddr;
public:
/**
* Initializes an empty network address.
* All the fields of the sockaddr will be zeroed.
*/
plNetAddress();
plNetAddress(uint32_t addr, int port);
plNetAddress(const char * addr, int port);
/**
* Initializes a new network address from the given IPv4 address and port
* number.
*
* @param addr The IPv4 address as a 32-bit network byte order integer.
* @param port The port number as a 16-bit host order integer.
*/
plNetAddress(uint32_t addr, uint16_t port);
/**
* Initializes a new network address from the given hostname and port
* number.
*
* @param addr The DNS hostname of the host.
* @param port The port number as a 16-bit host order integer.
*/
plNetAddress(const char* addr, uint16_t port);
virtual ~plNetAddress(){}
bool operator==(const plNetAddress& other) const {
return (GetHost() == other.GetHost()) && (GetPort() == other.GetPort());
}
bool operator!=(const plNetAddress& other) const {
return !(*this == other);
}
/**
* Clears the address and zeros out the sockaddr fields.
*/
void Clear();
/**
* Sets the address to INADDR_ANY for binding to any host.
*/
bool SetAnyAddr();
/**
* Sets the port number to 0 to allow binding to any port.
*/
bool SetAnyPort();
bool SetPort(int port);
bool SetHost(const char * hostname);
bool SetHost(uint32_t ip4addr);
int GetPort() const;
std::string GetHostString() const;
/**
* Gets the port number of the host.
*
* @return The host port number.
*/
uint16_t GetPort() const;
/**
* Sets the port number of the host.
*
* @param port The port number in host byte order.
*/
bool SetPort(uint16_t port);
/**
* Gets the IPv4 address of the host as a 32-bit integer in network byte
* order (big endian).
*
* @return The IPv4 host address.
*/
uint32_t GetHost() const;
std::string GetHostWithPort() const;
const AddressType & GetAddressInfo() const { return fAddr; }
AddressType & GetAddressInfo() { return fAddr; }
std::string AsString() const;
/**
* Sets the IPv4 address of the host from a DNS name.
*
* @param hostname The DNS name of the host.
*/
bool SetHost(const char* hostname);
/**
* Sets the IPv4 address of the host from an unsigned 32-bit integer in
* network byte order (big endian).
*
* @param ip4addr The host IPv4 address in network byte order.
*/
bool SetHost(uint32_t ip4addr);
/**
* Retrieves the internal address type.
*
* @return A constant sockaddr_in.
*/
const AddressType& GetAddressInfo() const { return fAddr; }
/**
* Retrieves the internal address type.
*
* @return A sockaddr_in.
*/
AddressType& GetAddressInfo() { return fAddr; }
/**
* Returns the IPv4 address of the host as a string in 4-octet dotted
* notation.
*
* @return A string of the IPv4 host address.
*/
plString GetHostString() const;
/**
* Return the IPv4 address and port number of the host as a string in
* 4-octet dotted notation with a colon separated port.
*
* @return A string of the IPv4 host address and port number.
*/
plString GetHostWithPort() const;
/**
* Returns a string representation of the host address and port number.
*
* @return A string representation of the address.
*/
plString AsString() const;
/**
* Reads and deserializes the address from a stream.
*
* @param stream The stream from which to read the address.
*/
void Read(hsStream * stream);
/**
* Serializes and writes the address to a stream.
*
* @param stream The stream to which to write the address.
*/
void Write(hsStream * stream);
};

16
Sources/Plasma/NucleusLib/pnNetCommon/pnNetCommon.cpp

@ -57,23 +57,23 @@ namespace pnNetCommon
#ifndef SERVER
// NOTE: On Win32, WSAStartup() must be called before GetTextAddr() will work.
const char * GetTextAddr(uint32_t binAddr)
plString GetTextAddr(uint32_t binAddr)
{
in_addr in;
memcpy(&in,&binAddr,sizeof(binAddr));
return inet_ntoa(in);
memcpy(&in, &binAddr, sizeof(binAddr));
return plString::Format("%s", inet_ntoa(in));
}
// NOTE: On Win32, WSAStartup() must be called before GetBinAddr() will work.
uint32_t GetBinAddr(const char * textAddr)
{
uint32_t addr = 0;
if (!textAddr)
return addr;
struct addrinfo * ai = NULL;
struct addrinfo* ai = NULL;
addr = inet_addr(textAddr);
if(addr == INADDR_NONE)
{
@ -82,7 +82,7 @@ uint32_t GetBinAddr(const char * textAddr)
memcpy(&addr,(void*)(&(((sockaddr_in*)(ai->ai_addr))->sin_addr)),sizeof(addr));
pnAddrInfo::Free(ai);
}
return addr;
}

7
Sources/Plasma/NucleusLib/pnNetCommon/pnNetCommon.h

@ -43,6 +43,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#define pnNetCommon_h_inc
#include "HeadSpin.h"
#include "plString.h"
#include "hsStlUtils.h"
#include "hsRefCnt.h"
#include "hsStream.h"
@ -81,9 +82,9 @@ namespace pnNetCommon
{
#ifndef SERVER
uint32_t GetBinAddr(const char * textAddr);
const char * GetTextAddr(uint32_t binAddr);
uint32_t GetBinAddr(const char* textAddr);
plString GetTextAddr(uint32_t binAddr);
#endif // SERVER
}

21
Sources/Plasma/NucleusLib/pnNetDiag/CMakeLists.txt

@ -1,21 +0,0 @@
include_directories("../../CoreLib")
include_directories("../../NucleusLib")
set(pnNetDiag_HEADERS
Intern.h
Pch.h
pnNetDiag.h
)
set(pnNetDiag_SOURCES
pnNdDns.cpp
pnNdIcmp.cpp
pnNdTcp.cpp
pnNetDiag.cpp
pnNetSys.cpp
)
add_library(pnNetDiag STATIC ${pnNetDiag_HEADERS} ${pnNetDiag_SOURCES})
source_group("Header Files" FILES ${pnNetDiag_HEADERS})
source_group("Source Files" FILES ${pnNetDiag_SOURCES})

143
Sources/Plasma/NucleusLib/pnNetDiag/Intern.h

@ -1,143 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/Intern.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_INTERN_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/Intern.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_INTERN_H
namespace ND {
extern HMODULE g_lib;
extern const wchar_t g_version[];
//============================================================================
enum {
kDiagSrvAuth,
kDiagSrvFile,
kNumDiagSrvs
};
//============================================================================
inline unsigned NetProtocolToSrv (ENetProtocol protocol) {
switch (protocol) {
case kNetProtocolCli2Auth: return kDiagSrvAuth;
case kNetProtocolCli2File: return kDiagSrvFile;
default: return kNumDiagSrvs;
}
}
//============================================================================
inline const wchar_t * SrvToString (unsigned srv) {
switch (srv) {
case kDiagSrvAuth: return L"Auth";
case kDiagSrvFile: return L"File";
DEFAULT_FATAL(srv);
}
}
} using namespace ND;
//============================================================================
struct NetDiag : AtomicRef {
bool destroyed;
CCritSect critsect;
wchar_t * hosts[kNumDiagSrvs];
unsigned nodes[kNumDiagSrvs];
~NetDiag ();
void Destroy ();
void SetHost (unsigned srv, const wchar_t host[]);
};
/*****************************************************************************
*
* SYS
*
***/
void SysStartup ();
void SysShutdown ();
/*****************************************************************************
*
* DNS
*
***/
void DnsStartup ();
void DnsShutdown ();
/*****************************************************************************
*
* ICMP
*
***/
void IcmpStartup ();
void IcmpShutdown ();
/*****************************************************************************
*
* TCP
*
***/
void TcpStartup ();
void TcpShutdown ();

68
Sources/Plasma/NucleusLib/pnNetDiag/Pch.h

@ -1,68 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/Pch.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_PCH_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/Pch.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_PCH_H
#include "pnUtils/pnUtils.h"
#include "pnNetBase/pnNetBase.h"
#include "pnAsyncCore/pnAsyncCore.h"
#include "pnProduct/pnProduct.h"
#include "pnNetCli/pnNetCli.h"
#define USES_PROTOCOL_CLI2AUTH
#define USES_PROTOCOL_CLI2FILE
#include "pnNetProtocol/pnNetProtocol.h"
#include "pnNetDiag.h"
#include "Intern.h"
#include <process.h>
#include <IPExport.h>
#include <IPTypes.h>

194
Sources/Plasma/NucleusLib/pnNetDiag/pnNdDns.cpp

@ -1,194 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/pnNdDns.cpp
*
***/
#include "Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Internal types
*
***/
struct DNSParam {
NetDiag * diag;
FNetDiagDumpProc dump;
FNetDiagTestCallback callback;
void * param;
ENetProtocol protocol;
unsigned srv;
};
/*****************************************************************************
*
* Internal functions
*
***/
//============================================================================
static void LookupCallback (
void * param,
const wchar_t name[],
unsigned addrCount,
const NetAddress addrs[]
) {
DNSParam * p = (DNSParam *)param;
if (addrCount) {
unsigned node = NetAddressGetNode(addrs[0]);
p->diag->critsect.Enter();
{
p->diag->nodes[p->srv] = node;
}
p->diag->critsect.Leave();
wchar_t nodeStr[64];
NetAddressNodeToString(p->diag->nodes[p->srv], nodeStr, arrsize(nodeStr));
p->dump(L"[DNS] Success. %s --> %s", name, nodeStr);
p->callback(
p->diag,
p->protocol,
kNetSuccess,
p->param
);
}
else {
p->diag->critsect.Enter();
{
// if the hostname still matches, then clear the node
if (p->diag->hosts[p->srv] && 0 == StrCmp(p->diag->hosts[p->srv], name))
p->diag->nodes[p->srv] = 0;
}
p->diag->critsect.Leave();
p->dump(L"[DNS] Failed to resolve hostname %s", name);
p->callback(
p->diag,
p->protocol,
kNetErrNameLookupFailed,
p->param
);
}
p->diag->DecRef("DNS");
delete p;
}
/*****************************************************************************
*
* Module functions
*
***/
//============================================================================
void DnsStartup () {
}
//============================================================================
void DnsShutdown () {
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void NetDiagDns (
NetDiag * diag,
ENetProtocol protocol,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
) {
ASSERT(diag);
ASSERT(dump);
ASSERT(callback);
unsigned srv = NetProtocolToSrv(protocol);
if (srv == kNumDiagSrvs) {
dump(L"[DNS] Unsupported protocol: %s", NetProtocolToString(protocol));
callback(diag, protocol, kNetErrNotSupported, param);
return;
}
wchar_t * host = nil;
diag->critsect.Enter();
{
if (diag->hosts[srv])
host = StrDup(diag->hosts[srv]);
}
diag->critsect.Leave();
if (!host) {
dump(L"[DNS] No hostname set for protocol: %s", NetProtocolToString(protocol));
callback(diag, protocol, kNetSuccess, param);
return;
}
diag->IncRef("DNS");
dump(L"[DNS] Looking up %s...", host);
DNSParam * dnsParam = NEWZERO(DNSParam);
dnsParam->diag = diag;
dnsParam->srv = srv;
dnsParam->protocol = protocol;
dnsParam->dump = dump;
dnsParam->callback = callback;
dnsParam->param = param;
AsyncCancelId cancelId;
AsyncAddressLookupName(
&cancelId,
LookupCallback,
host,
0,
dnsParam
);
free(host);
}

262
Sources/Plasma/NucleusLib/pnNetDiag/pnNdIcmp.cpp

@ -1,262 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/pnNdIcmp.cpp
*
***/
#include "Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local types
*
***/
typedef HANDLE (PASCAL FAR * FIcmpCreateFile) ();
typedef DWORD (PASCAL FAR * FIcmpSendEcho) (
HANDLE icmpHandle,
DWORD destinationAddress,
LPVOID requestData,
WORD requestSize,
PIP_OPTION_INFORMATION options,
LPVOID replyBuffer,
DWORD replySize,
DWORD timeoutMs
);
struct PingParam {
NetDiag * diag;
FNetDiagDumpProc dump;
FNetDiagTestCallback callback;
void * param;
ENetProtocol protocol;
unsigned srv;
};
/*****************************************************************************
*
* Local data
*
***/
static const unsigned kPingCount = 5;
static const unsigned kPayloadBytes = 32;
static FIcmpCreateFile IcmpCreateFile;
static FIcmpSendEcho IcmpSendEcho;
static uint8_t s_payload[kPayloadBytes];
/*****************************************************************************
*
* Local functions
*
***/
//============================================================================
static const wchar_t * IpStatusToString (ULONG status) {
switch (status) {
case IP_SUCCESS: return L"IP_SUCCESS";
case IP_BUF_TOO_SMALL: return L"IP_BUF_TOO_SMALL";
case IP_DEST_NET_UNREACHABLE: return L"IP_DEST_NET_UNREACHABLE";
case IP_DEST_HOST_UNREACHABLE: return L"IP_DEST_HOST_UNREACHABLE";
case IP_DEST_PROT_UNREACHABLE: return L"IP_DEST_PROT_UNREACHABLE";
case IP_DEST_PORT_UNREACHABLE: return L"IP_DEST_PORT_UNREACHABLE";
case IP_NO_RESOURCES: return L"IP_NO_RESOURCES";
case IP_BAD_OPTION: return L"IP_BAD_OPTION";
case IP_HW_ERROR: return L"IP_HW_ERROR";
case IP_PACKET_TOO_BIG: return L"IP_PACKET_TOO_BIG";
case IP_REQ_TIMED_OUT: return L"IP_REQ_TIMED_OUT";
case IP_BAD_REQ: return L"IP_BAD_REQ";
case IP_BAD_ROUTE: return L"IP_BAD_ROUTE";
case IP_TTL_EXPIRED_TRANSIT: return L"IP_TTL_EXPIRED_TRANSIT";
case IP_TTL_EXPIRED_REASSEM: return L"IP_TTL_EXPIRED_REASSEM";
case IP_PARAM_PROBLEM: return L"IP_PARAM_PROBLEM";
case IP_SOURCE_QUENCH: return L"IP_SOURCE_QUENCH";
case IP_OPTION_TOO_BIG: return L"IP_OPTION_TOO_BIG";
case IP_BAD_DESTINATION: return L"IP_BAD_DESTINATION";
default: return L"Unknown error";
}
}
//============================================================================
static void __cdecl PingThreadProc (void * param) {
PingParam * p = (PingParam *)param;
HANDLE icmp = IcmpCreateFile();
if (!icmp) {
p->dump(L"[ICMP] Failed to create ICMP handle");
p->callback(p->diag, p->protocol, kNetErrFileNotFound, p->param);
return;
}
char addr[64];
wchar_t waddr[64];
NetAddressNodeToString(p->diag->nodes[p->srv], waddr, arrsize(waddr));
StrToAnsi(addr, waddr, arrsize(addr));
ENetError result = kNetSuccess;
uint8_t reply[kPayloadBytes + sizeof(ICMP_ECHO_REPLY)];
for (unsigned i = 0; i < kPingCount; ++i) {
DWORD retval = IcmpSendEcho(
icmp,
inet_addr(addr),
s_payload,
sizeof(s_payload),
NULL,
reply,
sizeof(reply),
4000
);
PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)reply;
if (retval) {
p->dump(L"[ICMP] Reply from %s. ms=%u", waddr, pEchoReply->RoundTripTime);
}
else {
result = kNetErrConnectFailed;
p->dump(L"[ICMP] No reply from %s. %s", waddr, IpStatusToString(pEchoReply->Status));
}
}
p->callback(p->diag, p->protocol, result, p->param);
p->diag->DecRef("ICMP");
delete p;
}
/*****************************************************************************
*
* Module functions
*
***/
//============================================================================
void IcmpStartup () {
if (g_lib) {
IcmpCreateFile = (FIcmpCreateFile)GetProcAddress(g_lib, "IcmpCreateFile");
IcmpSendEcho = (FIcmpSendEcho)GetProcAddress(g_lib, "IcmpSendEcho");
}
memset(s_payload, (uint8_t)((uintptr_t)&s_payload >> 4), arrsize(s_payload));
}
//============================================================================
void IcmpShutdown () {
IcmpCreateFile = nil;
IcmpSendEcho = nil;
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void NetDiagIcmp (
NetDiag * diag,
ENetProtocol protocol,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
) {
ASSERT(diag);
ASSERT(dump);
ASSERT(callback);
if (!IcmpCreateFile || !IcmpSendEcho) {
dump(L"[ICMP] Failed to load IP helper API");
callback(diag, protocol, kNetErrNotSupported, param);
return;
}
unsigned srv = NetProtocolToSrv(protocol);
if (srv == kNumDiagSrvs) {
dump(L"[ICMP] Unsupported protocol: %s", NetProtocolToString(protocol));
callback(diag, protocol, kNetErrNotSupported, param);
return;
}
unsigned node = 0;
diag->critsect.Enter();
{
node = diag->nodes[srv];
}
diag->critsect.Leave();
if (!node) {
dump(L"[ICMP] No address set for protocol: %s", NetProtocolToString(protocol));
callback(diag, protocol, kNetSuccess, param);
return;
}
wchar_t nodeStr[64];
NetAddressNodeToString(node, nodeStr, arrsize(nodeStr));
dump(L"[ICMP] Pinging %s with %u bytes of data...", nodeStr, kPayloadBytes);
PingParam * pingParam = NEWZERO(PingParam);
pingParam->diag = diag;
pingParam->srv = srv;
pingParam->protocol = protocol;
pingParam->dump = dump;
pingParam->callback = callback;
pingParam->param = param;
diag->IncRef("ICMP");
_beginthread(PingThreadProc, 0, pingParam);
}

858
Sources/Plasma/NucleusLib/pnNetDiag/pnNdTcp.cpp

@ -1,858 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/pnNdTcp.cpp
*
***/
#include "Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local types
*
***/
struct AuthConn : AtomicRef {
NetDiag * diag;
FNetDiagDumpProc dump;
FNetDiagTestCallback callback;
void * param;
AsyncSocket sock;
AsyncCancelId cancelId;
NetCli * cli;
long pingsInRoute;
long pingsCompleted;
bool done;
ENetError error;
~AuthConn ();
};
struct AuthTrans : THashKeyVal<unsigned> {
HASHLINK(AuthTrans) link;
AuthConn * conn;
unsigned pingAtMs;
AuthTrans (AuthConn * conn);
~AuthTrans ();
};
struct FileConn : AtomicRef {
NetDiag * diag;
FNetDiagDumpProc dump;
FNetDiagTestCallback callback;
void * param;
AsyncSocket sock;
AsyncCancelId cancelId;
ARRAY(uint8_t) recvBuffer;
long pingsInRoute;
long pingsCompleted;
bool done;
ENetError error;
~FileConn ();
};
struct FileTrans : THashKeyVal<unsigned> {
HASHLINK(FileTrans) link;
FileConn * conn;
unsigned pingAtMs;
FileTrans (FileConn * conn);
~FileTrans ();
};
/*****************************************************************************
*
* Local data
*
***/
static const unsigned kPingTimeoutMs = 5000;
static const unsigned kTimeoutCheckMs = 100;
static const unsigned kMaxPings = 15;
static long s_authProtocolRegistered;
static unsigned s_transId;
static CCritSect s_critsect;
static bool s_shutdown;
static uint8_t s_payload[32];
static AsyncTimer * s_timer;
static HASHTABLEDECL(
AuthTrans,
THashKeyVal<unsigned>,
link
) s_authTrans;
static HASHTABLEDECL(
FileTrans,
THashKeyVal<unsigned>,
link
) s_fileTrans;
/*****************************************************************************
*
* Cli2Auth protocol
*
***/
//============================================================================
static bool Recv_PingReply (
const uint8_t msg[],
unsigned bytes,
void *
) {
const Auth2Cli_PingReply & reply = *(const Auth2Cli_PingReply *)msg;
AuthTrans * trans;
s_critsect.Enter();
{
if (bytes < sizeof(Auth2Cli_PingReply)) {
// beta6 compatibility
if (nil != (trans = s_authTrans.Tail()))
s_authTrans.Unlink(trans);
}
else if (nil != (trans = s_authTrans.Find(reply.transId)))
s_authTrans.Unlink(trans);
}
s_critsect.Leave();
if (trans) {
unsigned replyAtMs = TimeGetMs();
trans->conn->dump(L"[TCP] Reply from SrvAuth. ms=%u", replyAtMs - trans->pingAtMs);
delete trans;
return true;
}
else {
return false;
}
}
//============================================================================
#define MSG(s) kNetMsg_Cli2Auth_##s
static NetMsgInitSend s_send[] = {
{ MSG(PingRequest) },
};
#undef MSG
#define MSG(s) kNetMsg_Auth2Cli_##s, Recv_##s
static NetMsgInitRecv s_recv[] = {
{ MSG(PingReply) },
};
#undef MSG
/*****************************************************************************
*
* Local functions
*
***/
//============================================================================
static unsigned TimerCallback (void *) {
unsigned timeMs = TimeGetMs();
s_critsect.Enter();
{
ENetError error = kNetErrTimeout;
{for (AuthTrans * next, * curr = s_authTrans.Head(); curr; curr = next) {
next = s_authTrans.Next(curr);
unsigned diff = timeMs - curr->pingAtMs;
if (diff > kPingTimeoutMs) {
if (!curr->conn->error)
curr->conn->error = error;
curr->conn->dump(L"[TCP] No reply from SrvAuth: %u, %s (ms=%u)", error, NetErrorToString(error), diff);
delete curr;
}
}}
{for (FileTrans * next, * curr = s_fileTrans.Head(); curr; curr = next) {
next = s_fileTrans.Next(curr);
unsigned diff = timeMs - curr->pingAtMs;
if (diff > kPingTimeoutMs) {
if (!curr->conn->error)
curr->conn->error = error;
curr->conn->dump(L"[TCP] No reply from SrvFile: %u, %s (ms=%u)", error, NetErrorToString(error), diff);
delete curr;
}
}}
}
s_critsect.Leave();
return kTimeoutCheckMs;
}
//============================================================================
static void AuthPingProc (void * param) {
AuthConn * conn = (AuthConn *)param;
while (!conn->done && conn->pingsCompleted < kMaxPings) {
if (!conn->pingsInRoute) {
AuthTrans * trans = new AuthTrans(conn);
trans->pingAtMs = TimeGetMs();
s_critsect.Enter();
for (;;) {
if (conn->done) {
conn->pingsCompleted = kMaxPings;
delete trans;
break;
}
while (++s_transId == 0)
NULL_STMT;
trans->SetValue(s_transId);
s_authTrans.Add(trans);
const uintptr_t msg[] = {
kCli2Auth_PingRequest,
trans->pingAtMs,
trans->GetValue(),
sizeof(s_payload),
(uintptr_t) s_payload,
};
NetCliSend(conn->cli, msg, arrsize(msg));
NetCliFlush(conn->cli);
break;
}
s_critsect.Leave();
}
AsyncSleep(10);
}
s_critsect.Enter();
{
conn->done = true;
AsyncSocketDisconnect(conn->sock, true);
NetCliDelete(conn->cli, false);
conn->cli = nil;
}
s_critsect.Leave();
conn->DecRef("Pinging");
}
//============================================================================
static bool AuthConnEncrypt (ENetError error, void * param) {
AuthConn * conn = (AuthConn *)param;
if (IS_NET_SUCCESS(error)) {
conn->dump(L"[TCP] SrvAuth stream encrypted.");
conn->dump(L"[TCP] Pinging SrvAuth with 32 bytes of data...");
conn->IncRef("Pinging");
_beginthread(AuthPingProc, 0, conn);
}
else {
conn->dump(L"[TCP] SrvAuth stream encryption failed: %u, %s", error, NetErrorToString(error));
}
return IS_NET_SUCCESS(error);
}
//============================================================================
static void NotifyAuthConnSocketConnect (AuthConn * conn) {
conn->dump(L"[TCP] SrvAuth socket established, encrypting stream...");
conn->TransferRef("Connecting", "Connected");
conn->cli = NetCliConnectAccept(
conn->sock,
kNetProtocolCli2Auth,
false,
AuthConnEncrypt,
0,
nil,
conn
);
}
//============================================================================
static void NotifyAuthConnSocketConnectFailed (AuthConn * conn) {
conn->error = kNetErrConnectFailed;
conn->cancelId = 0;
conn->dump(L"[TCP] SrvAuth socket connection failed %u, %s", conn->error, NetErrorToString(conn->error));
conn->DecRef("Connecting");
}
//============================================================================
static void NotifyAuthConnSocketDisconnect (AuthConn * conn) {
if (!conn->done && !conn->error)
conn->error = kNetErrDisconnected;
conn->cancelId = 0;
conn->dump(L"[TCP] SrvAuth socket closed: %u, %s", conn->error, NetErrorToString(conn->error));
HASHTABLEDECL(
AuthTrans,
THashKeyVal<unsigned>,
link
) authTrans;
s_critsect.Enter();
{
conn->done = true;
while (AuthTrans * trans = s_authTrans.Head())
authTrans.Add(trans);
}
s_critsect.Leave();
while (AuthTrans * trans = authTrans.Head()) {
conn->dump(L"[TCP] No reply from SrvAuth: %u, %s", conn->error, NetErrorToString(conn->error));
delete trans;
}
conn->DecRef("Connected");
}
//============================================================================
static bool NotifyAuthConnSocketRead (AuthConn * conn, AsyncNotifySocketRead * read) {
NetCliDispatch(conn->cli, read->buffer, read->bytes, conn);
read->bytesProcessed += read->bytes;
return true;
}
//============================================================================
static bool AuthSocketNotifyCallback (
AsyncSocket sock,
EAsyncNotifySocket code,
AsyncNotifySocket * notify,
void ** userState
) {
bool result = true;
AuthConn * conn;
switch (code) {
case kNotifySocketConnectSuccess:
conn = (AuthConn *) notify->param;
*userState = conn;
conn->sock = sock;
conn->cancelId = 0;
NotifyAuthConnSocketConnect(conn);
break;
case kNotifySocketConnectFailed:
conn = (AuthConn *) notify->param;
NotifyAuthConnSocketConnectFailed(conn);
break;
case kNotifySocketDisconnect:
conn = (AuthConn *) *userState;
NotifyAuthConnSocketDisconnect(conn);
break;
case kNotifySocketRead:
conn = (AuthConn *) *userState;
result = NotifyAuthConnSocketRead(conn, (AsyncNotifySocketRead *) notify);
break;
}
return result;
}
//============================================================================
static bool Recv_File2Cli_ManifestReply (FileConn * conn, const File2Cli_ManifestReply & msg) {
FileTrans * trans;
s_critsect.Enter();
{
if (nil != (trans = s_fileTrans.Find(msg.transId)))
s_fileTrans.Unlink(trans);
}
s_critsect.Leave();
if (trans) {
unsigned replyAtMs = TimeGetMs();
trans->conn->dump(L"[TCP] Reply from SrvFile. ms=%u", replyAtMs - trans->pingAtMs);
delete trans;
return true;
}
else {
return false;
}
}
//============================================================================
static void FilePingProc (void * param) {
FileConn * conn = (FileConn *)param;
while (!conn->done && conn->pingsCompleted < kMaxPings) {
if (!conn->pingsInRoute) {
FileTrans * trans = new FileTrans(conn);
trans->pingAtMs = TimeGetMs();
s_critsect.Enter();
for (;;) {
if (conn->done) {
conn->pingsCompleted = kMaxPings;
delete trans;
break;
}
while (++s_transId == 0)
NULL_STMT;
trans->SetValue(s_transId);
s_fileTrans.Add(trans);
Cli2File_ManifestRequest msg;
StrCopy(msg.group, L"External", arrsize(msg.group));
msg.messageId = kCli2File_ManifestRequest;
msg.transId = trans->GetValue();
msg.messageBytes = sizeof(msg);
msg.buildId = 0;
AsyncSocketSend(conn->sock, &msg, sizeof(msg));
break;
}
s_critsect.Leave();
}
AsyncSleep(10);
}
s_critsect.Enter();
{
conn->done = true;
AsyncSocketDisconnect(conn->sock, true);
}
s_critsect.Leave();
conn->DecRef("Pinging");
}
//============================================================================
static void NotifyFileConnSocketConnect (FileConn * conn) {
conn->TransferRef("Connecting", "Connected");
conn->dump(L"[TCP] SrvFile socket established");
conn->dump(L"[TCP] Pinging SrvFile...");
conn->IncRef("Pinging");
_beginthread(FilePingProc, 0, conn);
}
//============================================================================
static void NotifyFileConnSocketConnectFailed (FileConn * conn) {
conn->error = kNetErrConnectFailed;
conn->cancelId = 0;
conn->dump(L"[TCP] SrvFile socket connection failed %u, %s", conn->error, NetErrorToString(conn->error));
conn->DecRef("Connecting");
}
//============================================================================
static void NotifyFileConnSocketDisconnect (FileConn * conn) {
if (!conn->done && !conn->error)
conn->error = kNetErrDisconnected;
conn->cancelId = 0;
conn->dump(L"[TCP] SrvFile socket closed: %u, %s", conn->error, NetErrorToString(conn->error));
HASHTABLEDECL(
FileTrans,
THashKeyVal<unsigned>,
link
) fileTrans;
s_critsect.Enter();
{
conn->done = true;
while (FileTrans * trans = s_fileTrans.Head())
fileTrans.Add(trans);
}
s_critsect.Leave();
while (FileTrans * trans = fileTrans.Head()) {
conn->dump(L"[TCP] No reply from SrvFile: %u, %s", conn->error, NetErrorToString(conn->error));
delete trans;
}
conn->DecRef("Connected");
}
//============================================================================
static bool NotifyFileConnSocketRead (FileConn * conn, AsyncNotifySocketRead * read) {
conn->recvBuffer.Add(read->buffer, read->bytes);
read->bytesProcessed += read->bytes;
for (;;) {
if (conn->recvBuffer.Count() < sizeof(uint32_t))
return true;
uint32_t msgSize = *(uint32_t *)conn->recvBuffer.Ptr();
if (conn->recvBuffer.Count() < msgSize)
return true;
const Cli2File_MsgHeader * msg = (const Cli2File_MsgHeader *) conn->recvBuffer.Ptr();
if (msg->messageId != kFile2Cli_ManifestReply) {
conn->dump(L"[TCP] SrvFile received unexpected message. id: %u", msg->messageId);
return false;
}
if (!Recv_File2Cli_ManifestReply(conn, *(const File2Cli_ManifestReply *)msg))
return false;
conn->recvBuffer.Move(0, msgSize, conn->recvBuffer.Count() - msgSize);
conn->recvBuffer.ShrinkBy(msgSize);
}
}
//============================================================================
static bool FileSocketNotifyCallback (
AsyncSocket sock,
EAsyncNotifySocket code,
AsyncNotifySocket * notify,
void ** userState
) {
bool result = true;
FileConn * conn;
switch (code) {
case kNotifySocketConnectSuccess:
conn = (FileConn *) notify->param;
*userState = conn;
conn->sock = sock;
conn->cancelId = 0;
NotifyFileConnSocketConnect(conn);
break;
case kNotifySocketConnectFailed:
conn = (FileConn *) notify->param;
NotifyFileConnSocketConnectFailed(conn);
break;
case kNotifySocketDisconnect:
conn = (FileConn *) *userState;
NotifyFileConnSocketDisconnect(conn);
break;
case kNotifySocketRead:
conn = (FileConn *) *userState;
result = NotifyFileConnSocketRead(conn, (AsyncNotifySocketRead *) notify);
break;
}
return result;
}
//============================================================================
static void StartAuthTcpTest (
NetDiag * diag,
const NetAddress & addr,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
) {
if (0 == AtomicSet(&s_authProtocolRegistered, 1)) {
memset(
s_payload,
(uint8_t)((uintptr_t)&s_payload >> 4),
sizeof(s_payload)
);
NetMsgProtocolRegister(
kNetProtocolCli2Auth,
false,
s_send, arrsize(s_send),
s_recv, arrsize(s_recv),
kAuthDhGValue,
BigNum(sizeof(kAuthDhXData), kAuthDhXData),
BigNum(sizeof(kAuthDhNData), kAuthDhNData)
);
}
wchar_t addrStr[128];
NetAddressToString(addr, addrStr, arrsize(addrStr), kNetAddressFormatAll);
dump(L"[TCP] Connecting to SrvAuth at %s...", addrStr);
diag->IncRef("TCP");
AuthConn * conn = NEWZERO(AuthConn);
conn->diag = diag;
conn->dump = dump;
conn->callback = callback;
conn->param = param;
conn->IncRef("Connecting");
Cli2Auth_Connect connect;
connect.hdr.connType = (uint8_t) kConnTypeCliToAuth;
connect.hdr.hdrBytes = sizeof(connect.hdr);
connect.hdr.buildId = BuildId();
connect.hdr.buildType = BUILD_TYPE_LIVE;
connect.hdr.branchId = BranchId();
connect.hdr.productId = ProductId();
connect.data.token = kNilGuid;
connect.data.dataBytes = sizeof(connect.data);
AsyncSocketConnect(
&conn->cancelId,
addr,
AuthSocketNotifyCallback,
conn,
&connect,
sizeof(connect),
0,
0
);
}
//============================================================================
static void StartFileTcpTest (
NetDiag * diag,
const NetAddress & addr,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
) {
wchar_t addrStr[128];
NetAddressToString(addr, addrStr, arrsize(addrStr), kNetAddressFormatAll);
dump(L"[TCP] Connecting to SrvFile at %s...", addrStr);
diag->IncRef("TCP");
FileConn * conn = NEWZERO(FileConn);
conn->diag = diag;
conn->dump = dump;
conn->callback = callback;
conn->param = param;
conn->IncRef("Connecting");
Cli2File_Connect connect;
connect.hdr.connType = kConnTypeCliToFile;
connect.hdr.hdrBytes = sizeof(connect.hdr);
connect.hdr.buildId = 0;
connect.hdr.buildType = BUILD_TYPE_LIVE;
connect.hdr.branchId = BranchId();
connect.hdr.productId = ProductId();
connect.data.buildId = BuildId();
connect.data.serverType = kSrvTypeNone;
connect.data.dataBytes = sizeof(connect.data);
AsyncSocketConnect(
&conn->cancelId,
addr,
FileSocketNotifyCallback,
conn,
&connect,
sizeof(connect),
0,
0
);
}
/*****************************************************************************
*
* AuthConn
*
***/
//============================================================================
AuthConn::~AuthConn () {
if (cli)
NetCliDelete(cli, false);
if (sock)
AsyncSocketDelete(sock);
callback(diag, kNetProtocolCli2Auth, error, param);
diag->DecRef("TCP");
}
/*****************************************************************************
*
* AuthTrans
*
***/
//============================================================================
AuthTrans::AuthTrans (AuthConn * conn)
: conn(conn)
{
conn->IncRef("Ping");
AtomicAdd(&conn->pingsInRoute, 1);
}
//============================================================================
AuthTrans::~AuthTrans () {
AtomicAdd(&conn->pingsCompleted, 1);
AtomicAdd(&conn->pingsInRoute, -1);
conn->DecRef("Ping");
}
/*****************************************************************************
*
* FileConn
*
***/
//============================================================================
FileConn::~FileConn () {
if (sock)
AsyncSocketDelete(sock);
callback(diag, kNetProtocolCli2File, error, param);
diag->DecRef("TCP");
}
/*****************************************************************************
*
* FileTrans
*
***/
//============================================================================
FileTrans::FileTrans (FileConn * conn)
: conn(conn)
{
conn->IncRef("Ping");
AtomicAdd(&conn->pingsInRoute, 1);
}
//============================================================================
FileTrans::~FileTrans () {
AtomicAdd(&conn->pingsCompleted, 1);
AtomicAdd(&conn->pingsInRoute, -1);
conn->DecRef("Ping");
}
/*****************************************************************************
*
* Module functions
*
***/
//============================================================================
void TcpStartup () {
s_shutdown = false;
AsyncTimerCreate(&s_timer, TimerCallback, 0, nil);
}
//============================================================================
void TcpShutdown () {
s_shutdown = true;
AsyncTimerDeleteCallback(s_timer, TimerCallback);
s_timer = nil;
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void NetDiagTcp (
NetDiag * diag,
ENetProtocol protocol,
unsigned port,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
) {
ASSERT(diag);
ASSERT(dump);
ASSERT(callback);
unsigned srv = NetProtocolToSrv(protocol);
if (srv == kNumDiagSrvs) {
dump(L"[TCP] Unsupported protocol: %s", NetProtocolToString(protocol));
callback(diag, protocol, kNetErrNotSupported, param);
return;
}
unsigned node;
NetAddress addr;
diag->critsect.Enter();
{
node = diag->nodes[srv];
}
diag->critsect.Leave();
if (!node) {
dump(L"[TCP] No address set for protocol: %s", NetProtocolToString(protocol));
callback(diag, protocol, kNetSuccess, param);
return;
}
NetAddressFromNode(node, port, &addr);
switch (protocol) {
case kNetProtocolCli2Auth:
StartAuthTcpTest(diag, addr, dump, callback, param);
break;
case kNetProtocolCli2File:
StartFileTcpTest(diag, addr, dump, callback, param);
break;
DEFAULT_FATAL(protocol);
}
}

167
Sources/Plasma/NucleusLib/pnNetDiag/pnNetDiag.cpp

@ -1,167 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/pnNetDiag.cpp
*
***/
#include "Pch.h"
#pragma hdrstop
namespace ND {
/*****************************************************************************
*
* Local data
*
***/
/*****************************************************************************
*
* Module data
*
***/
HMODULE g_lib;
//const wchar_t g_version[] = L"miasma";
//const wchar_t g_version[] = L"ectomorph";
const wchar_t g_version[] = L"solvent";
} // namespace ND
/*****************************************************************************
*
* NetDiag
*
***/
//============================================================================
NetDiag::~NetDiag () {
for (unsigned srv = 0; srv < kNumDiagSrvs; ++srv)
free(hosts[srv]);
}
//============================================================================
void NetDiag::SetHost (unsigned srv, const wchar_t host[]) {
critsect.Enter();
{
free(hosts[srv]);
if (host)
hosts[srv] = StrDup(host);
else
hosts[srv] = nil;
nodes[srv] = 0;
}
critsect.Leave();
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void NetDiagInitialize () {
g_lib = LoadLibrary("Iphlpapi.dll");
SysStartup();
DnsStartup();
IcmpStartup();
TcpStartup();
}
//============================================================================
void NetDiagDestroy () {
TcpShutdown();
IcmpShutdown();
DnsShutdown();
SysShutdown();
if (g_lib) {
FreeLibrary(g_lib);
g_lib = nil;
}
}
//============================================================================
NetDiag * NetDiagCreate () {
NetDiag * diag = NEWZERO(NetDiag);
diag->IncRef("Lifetime");
return diag;
}
//============================================================================
void NetDiagDelete (NetDiag * diag) {
ASSERT(!diag->destroyed);
diag->destroyed = true;
diag->DecRef("Lifetime");
}
//============================================================================
void NetDiagSetHost (
NetDiag * diag,
ENetProtocol protocol,
const wchar_t host[]
) {
ASSERT(diag);
unsigned srv = NetProtocolToSrv(protocol);
if (srv == kNumDiagSrvs)
return;
diag->SetHost(srv, host);
}

145
Sources/Plasma/NucleusLib/pnNetDiag/pnNetDiag.h

@ -1,145 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/pnNetDiag.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_PNNETDIAG_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_PNNETDIAG_H
#define PNNETDIAG_INCLUDED
#ifdef PLNETGAMELIB_INCLUDED
#error "pnNetDiag and plNetGameLib libraries may not be included in the same project because they invalidate each other's pnNetCli settings"
#endif
/*****************************************************************************
*
* Module
*
***/
void NetDiagInitialize ();
void NetDiagDestroy ();
/*****************************************************************************
*
* NetDiag
*
***/
struct NetDiag;
NetDiag * NetDiagCreate ();
void NetDiagDelete (NetDiag * diag);
void NetDiagSetHost (
NetDiag * diag,
ENetProtocol protocol,
const wchar_t name[]
);
typedef void ( __cdecl * FNetDiagDumpProc)(
const wchar_t fmt[],
...
);
typedef void (*FNetDiagTestCallback)(
NetDiag * diag,
ENetProtocol protocol,
ENetError result,
void * param
);
//============================================================================
// Test: SYS
// Gather system information
//============================================================================
void NetDiagSys (
NetDiag * diag,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
);
//============================================================================
// Test: DNS
// Lookup server address
//============================================================================
void NetDiagDns (
NetDiag * diag,
ENetProtocol protocol,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
);
//============================================================================
// Test: ICMP
// Send out 5 sequential ICMP ping packets to the server
//============================================================================
void NetDiagIcmp (
NetDiag * diag,
ENetProtocol protocol,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
);
//============================================================================
// Test: TCP
// Connect to server and measure bandwidth
//============================================================================
void NetDiagTcp (
NetDiag * diag,
ENetProtocol protocol,
unsigned port, // 0 --> use default client port
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
);
#endif // PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNNETDIAG_PNNETDIAG_H

177
Sources/Plasma/NucleusLib/pnNetDiag/pnNetSys.cpp

@ -1,177 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnNetDiag/pnNetSys.cpp
*
***/
#include "Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local types
*
***/
typedef DWORD (PASCAL FAR * FGetAdaptersInfo)(
PIP_ADAPTER_INFO pAdapterInfo,
PULONG pOutBufLen
);
/*****************************************************************************
*
* Local data
*
***/
static FGetAdaptersInfo getAdaptersInfo;
/*****************************************************************************
*
* Module functions
*
***/
//============================================================================
void SysStartup () {
if (g_lib) {
getAdaptersInfo = (FGetAdaptersInfo)GetProcAddress(g_lib, "GetAdaptersInfo");
}
}
//============================================================================
void SysShutdown () {
getAdaptersInfo = nil;
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void NetDiagSys (
NetDiag * diag,
FNetDiagDumpProc dump,
FNetDiagTestCallback callback,
void * param
) {
ASSERT(diag);
ASSERT(dump);
ASSERT(callback);
{ // Timestamp
wchar_t str[256];
uint64_t time = TimeGetTime();
TimePrettyPrint(time, arrsize(str), str);
dump(L"[SYS] Time: %s UTC", str);
}
{ // Command line
dump(L"[SYS] Cmdline: %s", AppGetCommandLine());
}
{ // Product
wchar_t product[128];
ProductString(product, arrsize(product));
dump(L"[SYS] Product: %s", product);
}
{ // pnNetDiag version
dump(L"[SYS] Cognomen: '%s'", g_version);
}
{ // OS
OSVERSIONINFOEX info;
info.dwOSVersionInfoSize = sizeof(info);
GetVersionEx((OSVERSIONINFO*)&info);
dump(L"[SYS] OS Version: %u.%u", info.dwMajorVersion, info.dwMinorVersion);
dump(L"[SYS] OS Patch: %u.%u (%S)", info.wServicePackMajor, info.wServicePackMinor, info.szCSDVersion);
}
{ // System
uint16_t cpuCaps;
uint32_t cpuVendor[3];
uint16_t cpuSignature;
CpuGetInfo(&cpuCaps, cpuVendor, &cpuSignature);
SYSTEM_INFO info;
GetSystemInfo(&info);
dump(L"[SYS] CPU Count: %u", info.dwNumberOfProcessors);
dump(L"[SYS] CPU Vendor: %.*S", sizeof(cpuVendor), cpuVendor);
}
{ // Adapters
if (!getAdaptersInfo) {
dump(L"[SYS] Failed to load IP helper API");
callback(diag, kNetProtocolNil, kNetErrNotSupported, param);
return;
}
ULONG ulOutBufLen = 0;
getAdaptersInfo(nil, &ulOutBufLen);
PIP_ADAPTER_INFO pInfo = (PIP_ADAPTER_INFO)malloc(ulOutBufLen);
PIP_ADAPTER_INFO pAdapter;
if (getAdaptersInfo(pInfo, &ulOutBufLen) == NO_ERROR) {
pAdapter = pInfo;
while (pAdapter) {
dump(L"[SYS] NIC: %S", pAdapter->Description);
pAdapter = pAdapter->Next;
}
callback(diag, kNetProtocolNil, kNetSuccess, param);
}
else {
dump(L"[SYS] Error getting adaper list");
callback(diag, kNetProtocolNil, kNetErrFileNotFound, param);
}
free(pInfo);
}
}

18
Sources/Plasma/NucleusLib/pnNetProtocol/Private/Protocols/Cli2Auth/pnNpCli2Auth.h

@ -677,8 +677,8 @@ struct Auth2Cli_AccountExistsReply {
// ServerAddr
extern const NetMsg kNetMsg_Auth2Cli_ServerAddr;
struct Auth2Cli_ServerAddr {
uint32_t messageId;
NetAddressNode srvAddr;
uint32_t messageId;
uint32_t srvAddr;
Uuid token;
};
@ -713,13 +713,13 @@ struct Auth2Cli_AcctLoginReply {
// AgeReply
extern const NetMsg kNetMsg_Auth2Cli_AgeReply;
struct Auth2Cli_AgeReply {
uint32_t messageId;
uint32_t transId;
ENetError result;
uint32_t ageMcpId;
Uuid ageInstId;
uint32_t ageVaultId;
NetAddressNode gameSrvNode;
uint32_t messageId;
uint32_t transId;
ENetError result;
uint32_t ageMcpId;
Uuid ageInstId;
uint32_t ageVaultId;
uint32_t gameSrvNode;
};
// AcctCreateReply

6
Sources/Plasma/NucleusLib/pnNetProtocol/Private/Protocols/Srv2Mcp/pnNpSrv2Mcp.h

@ -191,9 +191,9 @@ struct Srv2Mcp_KickPlayer : SrvMsgHeader {
***/
struct Mcp2Srv_AgeJoinReply : SrvMsgHeader {
uint32_t ageMcpId;
Uuid ageUuid;
NetAddressNode gameSrvNode;
uint32_t ageMcpId;
Uuid ageUuid;
uint32_t gameSrvNode;
};
struct Mcp2Srv_AgeSpawnRequest : SrvMsgHeader {

1
Sources/Plasma/NucleusLib/pnSimpleNet/CMakeLists.txt

@ -2,7 +2,6 @@ include_directories("../../CoreLib")
include_directories("../../NucleusLib")
set(pnSimpleNet_HEADERS
Pch.h
pnSimpleNet.h
)

54
Sources/Plasma/NucleusLib/pnSimpleNet/Pch.h

@ -1,54 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnSimpleNet/Pch.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNSIMPLENET_PCH_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnSimpleNet/Pch.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNSIMPLENET_PCH_H
#include "pnSimpleNet.h"

275
Sources/Plasma/NucleusLib/pnSimpleNet/pnSimpleNet.cpp

@ -45,9 +45,11 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*
***/
#include "Pch.h"
#pragma hdrstop
#include "pnSimpleNet.h"
#include "hsThread.h"
#include <list>
#include <map>
/*****************************************************************************
*
@ -56,35 +58,25 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
***/
struct SimpleNetConn : AtomicRef {
LINK(SimpleNetConn) link;
AsyncSocket sock;
AsyncCancelId cancelId;
unsigned channelId;
uint32_t channelId;
bool abandoned;
struct ConnectParam * connectParam;
SimpleNet_MsgHeader * oversizeMsg;
ARRAY(uint8_t) oversizeBuffer;
~SimpleNetConn () {
ASSERT(!link.IsLinked());
}
ARRAY(uint8_t) oversizeBuffer;
};
struct SimpleNetChannel : AtomicRef, THashKeyVal<unsigned> {
HASHLINK(SimpleNetChannel) link;
struct SimpleNetChannel : AtomicRef {
FSimpleNetOnMsg onMsg;
FSimpleNetOnError onError;
LISTDECL(SimpleNetConn, link) conns;
uint32_t channelId;
std::list<SimpleNetConn*> conns;
SimpleNetChannel (unsigned channel)
: THashKeyVal<unsigned>(channel)
{ }
SimpleNetChannel (uint32_t channel) : channelId(channel) { }
~SimpleNetChannel () {
ASSERT(!link.IsLinked());
ASSERT(!conns.Head());
ASSERT(!conns.size());
}
};
@ -92,7 +84,7 @@ struct ConnectParam {
SimpleNetChannel * channel;
FSimpleNetOnConnect callback;
void * param;
~ConnectParam () {
if (channel)
channel->DecRef();
@ -107,15 +99,10 @@ struct ConnectParam {
***/
static bool s_running;
static CCritSect s_critsect;
static hsMutex s_critsect;
static FSimpleNetQueryAccept s_queryAccept;
static void * s_queryAcceptParam;
static HASHTABLEDECL(
SimpleNetChannel,
THashKeyVal<unsigned>,
link
) s_channels;
static std::map<uint32_t, SimpleNetChannel*> s_channels;
/*****************************************************************************
@ -128,13 +115,13 @@ static HASHTABLEDECL(
static void NotifyConnSocketConnect (SimpleNetConn * conn) {
conn->TransferRef("Connecting", "Connected");
conn->connectParam->callback(
conn->connectParam->param,
conn,
kNetSuccess
);
delete conn->connectParam;
conn->connectParam = nil;
}
@ -142,18 +129,21 @@ static void NotifyConnSocketConnect (SimpleNetConn * conn) {
//============================================================================
static void NotifyConnSocketConnectFailed (SimpleNetConn * conn) {
s_critsect.Enter();
s_critsect.Lock();
{
conn->link.Unlink();
std::map<uint32_t, SimpleNetChannel*>::iterator it;
if ((it = s_channels.find(conn->channelId)) != s_channels.end()) {
it->second->conns.remove(conn);
}
}
s_critsect.Leave();
s_critsect.Unlock();
conn->connectParam->callback(
conn->connectParam->param,
nil,
kNetErrConnectFailed
);
delete conn->connectParam;
conn->connectParam = nil;
@ -165,38 +155,44 @@ static void NotifyConnSocketConnectFailed (SimpleNetConn * conn) {
static void NotifyConnSocketDisconnect (SimpleNetConn * conn) {
bool abandoned;
SimpleNetChannel * channel;
s_critsect.Enter();
SimpleNetChannel* channel = nil;
s_critsect.Lock();
{
abandoned = conn->abandoned;
if (nil != (channel = s_channels.Find(conn->channelId)))
std::map<uint32_t, SimpleNetChannel*>::iterator it;
if ((it = s_channels.find(conn->channelId)) != s_channels.end()) {
channel = it->second;
channel->IncRef();
conn->link.Unlink();
channel->conns.remove(conn);
}
}
s_critsect.Leave();
s_critsect.Unlock();
if (channel && !abandoned) {
channel->onError(conn, kNetErrDisconnected);
channel->DecRef();
}
conn->DecRef("Connected");
}
//============================================================================
static bool NotifyConnSocketRead (SimpleNetConn * conn, AsyncNotifySocketRead * read) {
SimpleNetChannel * channel;
s_critsect.Enter();
SimpleNetChannel* channel = nil;
s_critsect.Lock();
{
if (nil != (channel = s_channels.Find(conn->channelId)))
std::map<uint32_t, SimpleNetChannel*>::iterator it;
if ((it = s_channels.find(conn->channelId)) != s_channels.end()) {
channel = it->second;
channel->IncRef();
}
}
s_critsect.Leave();
s_critsect.Unlock();
if (!channel)
return false;
bool result = true;
const uint8_t * curr = read->buffer;
@ -208,19 +204,19 @@ static bool NotifyConnSocketRead (SimpleNetConn * conn, AsyncNotifySocketRead *
unsigned spaceLeft = conn->oversizeMsg->messageBytes - conn->oversizeBuffer.Count();
unsigned copyBytes = min(spaceLeft, term - curr);
conn->oversizeBuffer.Add(curr, copyBytes);
curr += copyBytes;
// Wait until we have received the entire message
if (copyBytes != spaceLeft)
break;
// Dispatch oversize msg
if (!channel->onMsg(conn, conn->oversizeMsg)) {
result = false;
break;
}
conn->oversizeBuffer.SetCount(0);
continue;
}
@ -231,23 +227,23 @@ static bool NotifyConnSocketRead (SimpleNetConn * conn, AsyncNotifySocketRead *
SimpleNet_MsgHeader * msg = (SimpleNet_MsgHeader *) read->buffer;
// Sanity check message size
// Sanity check message size
if (msg->messageBytes < sizeof(*msg)) {
result = false;
break;
}
// Handle oversized messages
if (msg->messageBytes > kAsyncSocketBufferSize) {
conn->oversizeBuffer.SetCount(msg->messageBytes);
conn->oversizeMsg = (SimpleNet_MsgHeader *) conn->oversizeBuffer.Ptr();
*conn->oversizeMsg = *msg;
*conn->oversizeMsg = *msg;
curr += sizeof(*msg);
continue;
}
// Wait until we have received the entire message
const uint8_t * msgTerm = (const uint8_t *) curr + msg->messageBytes;
if (msgTerm > term)
@ -263,7 +259,7 @@ static bool NotifyConnSocketRead (SimpleNetConn * conn, AsyncNotifySocketRead *
// Return count of bytes we processed
read->bytesProcessed = curr - read->buffer;
channel->DecRef();
return result;
}
@ -286,59 +282,62 @@ static bool AsyncNotifySocketProc (
const SimpleNet_ConnData & connect = *(const SimpleNet_ConnData *) listen->buffer;
listen->bytesProcessed += sizeof(connect);
SimpleNetChannel * channel;
s_critsect.Enter();
SimpleNetChannel* channel = nil;
s_critsect.Lock();
{
if (nil != (channel = s_channels.Find(connect.channelId)))
std::map<uint32_t, SimpleNetChannel*>::iterator it;
if ((it = s_channels.find(connect.channelId)) != s_channels.end()) {
channel = it->second;
channel->IncRef();
}
}
s_critsect.Leave();
s_critsect.Unlock();
if (!channel)
break;
conn = NEWZERO(SimpleNetConn);
conn->channelId = channel->GetValue();
conn->channelId = channel->channelId;
conn->IncRef("Lifetime");
conn->IncRef("Connected");
conn->sock = sock;
*userState = conn;
bool accepted = s_queryAccept(
s_queryAcceptParam,
channel->GetValue(),
channel->channelId,
conn,
listen->remoteAddr
);
if (!accepted) {
SimpleNetDisconnect(conn);
}
else {
s_critsect.Enter();
s_critsect.Lock();
{
channel->conns.Link(conn);
channel->conns.push_back(conn);
}
s_critsect.Leave();
s_critsect.Unlock();
}
channel->DecRef();
}
break;
case kNotifySocketConnectSuccess: {
conn = (SimpleNetConn *) notify->param;
*userState = conn;
bool abandoned;
s_critsect.Enter();
s_critsect.Lock();
{
conn->sock = sock;
conn->cancelId = 0;
abandoned = conn->abandoned;
}
s_critsect.Leave();
s_critsect.Unlock();
if (abandoned)
AsyncSocketDisconnect(sock, true);
else
@ -349,35 +348,38 @@ static bool AsyncNotifySocketProc (
case kNotifySocketConnectFailed:
conn = (SimpleNetConn *) notify->param;
NotifyConnSocketConnectFailed(conn);
break;
break;
case kNotifySocketDisconnect:
conn = (SimpleNetConn *) *userState;
NotifyConnSocketDisconnect(conn);
break;
break;
case kNotifySocketRead:
conn = (SimpleNetConn *) *userState;
result = NotifyConnSocketRead(conn, (AsyncNotifySocketRead *) notify);
break;
break;
default:
break;
}
return result;
}
//============================================================================
static void Connect (const NetAddress & addr, ConnectParam * cp) {
static void Connect(const plNetAddress& addr, ConnectParam * cp) {
SimpleNetConn * conn = NEWZERO(SimpleNetConn);
conn->channelId = cp->channel->GetValue();
conn->channelId = cp->channel->channelId;
conn->connectParam = cp;
conn->IncRef("Lifetime");
conn->IncRef("Connecting");
s_critsect.Enter();
s_critsect.Lock();
{
cp->channel->conns.Link(conn);
cp->channel->conns.push_back(conn);
SimpleNet_Connect connect;
connect.hdr.connType = kConnTypeSimpleNet;
connect.hdr.hdrBytes = sizeof(connect.hdr);
@ -385,8 +387,8 @@ static void Connect (const NetAddress & addr, ConnectParam * cp) {
connect.hdr.buildType = BUILD_TYPE_LIVE;
connect.hdr.branchId = BranchId();
connect.hdr.productId = ProductId();
connect.data.channelId = cp->channel->GetValue();
connect.data.channelId = cp->channel->channelId;
AsyncSocketConnect(
&conn->cancelId,
addr,
@ -395,12 +397,12 @@ static void Connect (const NetAddress & addr, ConnectParam * cp) {
&connect,
sizeof(connect)
);
conn = nil;
conn = nil;
cp = nil;
}
s_critsect.Leave();
s_critsect.Unlock();
delete conn;
delete cp;
}
@ -408,9 +410,9 @@ static void Connect (const NetAddress & addr, ConnectParam * cp) {
//============================================================================
static void AsyncLookupCallback (
void * param,
const wchar_t name[],
const char name[],
unsigned addrCount,
const NetAddress addrs[]
const plNetAddress addrs[]
) {
ConnectParam * cp = (ConnectParam *)param;
@ -447,8 +449,8 @@ void SimpleNetShutdown () {
s_running = false;
ASSERT(!s_channels.Head());
ASSERT(!s_channels.size());
AsyncSocketUnregisterNotifyProc(
kConnTypeSimpleNet,
AsyncNotifySocketProc
@ -460,7 +462,7 @@ void SimpleNetConnIncRef (SimpleNetConn * conn) {
ASSERT(s_running);
ASSERT(conn);
conn->IncRef();
}
@ -469,7 +471,7 @@ void SimpleNetConnDecRef (SimpleNetConn * conn) {
ASSERT(s_running);
ASSERT(conn);
conn->DecRef();
}
@ -481,12 +483,13 @@ bool SimpleNetStartListening (
ASSERT(s_running);
ASSERT(queryAccept);
ASSERT(!s_queryAccept);
s_queryAccept = queryAccept;
s_queryAcceptParam = param;
NetAddress addr;
NetAddressFromNode(0, kNetDefaultSimpleNetPort, &addr);
plNetAddress addr;
addr.SetPort(kNetDefaultSimpleNetPort);
addr.SetAnyAddr();
return (0 != AsyncSocketStartListening(addr, nil));
}
@ -495,8 +498,9 @@ void SimpleNetStopListening () {
ASSERT(s_running);
NetAddress addr;
NetAddressFromNode(0, kNetDefaultSimpleNetPort, &addr);
plNetAddress addr;
addr.SetPort(kNetDefaultSimpleNetPort);
addr.SetAnyAddr();
AsyncSocketStopListening(addr, nil);
s_queryAccept = nil;
@ -514,22 +518,22 @@ void SimpleNetCreateChannel (
SimpleNetChannel * channel = NEWZERO(SimpleNetChannel)(channelId);
channel->IncRef();
s_critsect.Enter();
s_critsect.Lock();
{
#ifdef HS_DEBUGGING
{
SimpleNetChannel * existing = s_channels.Find(channelId);
ASSERT(!existing);
std::map<uint32_t, SimpleNetChannel*>::iterator it = s_channels.find(channelId);
ASSERT(it == s_channels.end());
}
#endif
channel->onMsg = onMsg;
channel->onError = onError;
s_channels.Add(channel);
s_channels[channelId] = channel;
channel->IncRef();
}
s_critsect.Leave();
s_critsect.Unlock();
channel->DecRef();
}
@ -539,47 +543,57 @@ void SimpleNetDestroyChannel (unsigned channelId) {
ASSERT(s_running);
SimpleNetChannel * channel;
s_critsect.Enter();
s_critsect.Lock();
{
if (nil != (channel = s_channels.Find(channelId))) {
s_channels.Unlink(channel);
while (SimpleNetConn * conn = channel->conns.Head()) {
std::map<uint32_t, SimpleNetChannel*>::iterator it;
if ((it = s_channels.find(channelId)) != s_channels.end()) {
channel = it->second;
while (channel->conns.size()) {
SimpleNetConn* conn = channel->conns.front();
SimpleNetDisconnect(conn);
channel->conns.Unlink(conn);
channel->conns.pop_front();
}
s_channels.erase(it);
}
}
s_critsect.Leave();
s_critsect.Unlock();
if (channel)
channel->DecRef();
channel->DecRef();
}
//============================================================================
void SimpleNetStartConnecting (
unsigned channelId,
const wchar_t addr[],
const char addr[],
FSimpleNetOnConnect onConnect,
void * param
) {
ASSERT(s_running);
ASSERT(onConnect);
ConnectParam * cp = new ConnectParam;
cp->callback = onConnect;
cp->param = param;
s_critsect.Enter();
cp->channel = nil;
s_critsect.Lock();
{
if (nil != (cp->channel = s_channels.Find(channelId)))
std::map<uint32_t, SimpleNetChannel*>::iterator it;
if ((it = s_channels.find(channelId)) != s_channels.end()) {
cp->channel = it->second;
cp->channel->IncRef();
}
}
s_critsect.Leave();
s_critsect.Unlock();
ASSERT(cp->channel);
// Do we need to lookup the address?
const wchar_t * name = addr;
const char* name = addr;
while (unsigned ch = *name) {
++name;
if (!(isdigit(ch) || ch == L'.' || ch == L':')) {
@ -596,8 +610,7 @@ void SimpleNetStartConnecting (
}
}
if (!name[0]) {
NetAddress netAddr;
NetAddressFromString(&netAddr, addr, kNetDefaultSimpleNetPort);
plNetAddress netAddr(addr, kNetDefaultSimpleNetPort);
Connect(netAddr, cp);
}
}
@ -608,8 +621,8 @@ void SimpleNetDisconnect (
) {
ASSERT(s_running);
ASSERT(conn);
s_critsect.Enter();
s_critsect.Lock();
{
conn->abandoned = true;
if (conn->sock) {
@ -621,7 +634,7 @@ void SimpleNetDisconnect (
conn->cancelId = nil;
}
}
s_critsect.Leave();
s_critsect.Unlock();
conn->DecRef("Lifetime");
}
@ -635,11 +648,11 @@ void SimpleNetSend (
ASSERT(msg);
ASSERT(msg->messageBytes != (uint32_t)-1);
ASSERT(conn);
s_critsect.Enter();
s_critsect.Lock();
{
if (conn->sock)
AsyncSocketSend(conn->sock, msg, msg->messageBytes);
}
s_critsect.Leave();
s_critsect.Unlock();
}

3
Sources/Plasma/NucleusLib/pnSimpleNet/pnSimpleNet.h

@ -53,6 +53,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "pnProduct/pnProduct.h"
#include "pnNetBase/pnNetBase.h"
#include "pnAsyncCore/pnAsyncCore.h"
#include "pnNetCommon/plNetAddress.h"
/*****************************************************************************
*
@ -148,7 +149,7 @@ typedef bool (*FSimpleNetQueryAccept) ( // return true to accept incoming connec
void * param,
unsigned channel,
SimpleNetConn * conn,
const NetAddress & addr
const plNetAddress& addr
);
void SimpleNetCreateChannel (

13
Sources/Plasma/NucleusLib/pnUUID/pnUUID.h

@ -80,9 +80,16 @@ public:
void Read( hsStream * s );
void Write( hsStream * s );
operator plString ( void ) const { return AsString();}
bool operator==( const plUUID & other ) const { return IsEqualTo( &other ); }
bool operator!=( const plUUID & other ) const { return !IsEqualTo( &other ); }
int operator <( const plUUID & other ) const { return CompareTo( &other ); }
bool operator==(const plUUID& other) const {
return IsEqualTo(&other);
}
bool operator!=(const plUUID& other) const {
return !IsEqualTo(&other);
}
bool operator<(const plUUID& other) const {
return CompareTo(&other) == -1;
}
operator Uuid () const;
static plUUID Generate();

18
Sources/Plasma/NucleusLib/pnUtils/CMakeLists.txt

@ -5,44 +5,32 @@ set(pnUtils_HEADERS
Pch.h
pnUtils.h
pnUtCoreLib.h
pnUtAddr.h
pnUtAllIncludes.h
pnUtArray.h
pnUtBase64.h
pnUtBigNum.h
pnUtCmd.h
pnUtCrypt.h
pnUtHash.h
pnUtList.h
pnUtMath.h
pnUtMisc.h
pnUtPath.h
pnUtPragma.h
pnUtPriQ.h
pnUtRand.h
pnUtRef.h
pnUtSort.h
pnUtSpareList.h
pnUtStr.h
pnUtSync.h
pnUtTime.h
pnUtTls.h
pnUtUuid.h
)
set(pnUtils_SOURCES
pnUtAddr.cpp
pnUtArray.cpp
pnUtBase64.cpp
pnUtBigNum.cpp
pnUtCmd.cpp
pnUtCrypt.cpp
pnUtHash.cpp
pnUtList.cpp
pnUtMath.cpp
pnUtMisc.cpp
pnUtPath.cpp
pnUtRand.cpp
pnUtSpareList.cpp
pnUtStr.cpp
pnUtTime.cpp
pnUtUuid.cpp
@ -50,16 +38,12 @@ set(pnUtils_SOURCES
if(WIN32)
set(pnUtils_WIN32
Win32/pnUtW32Addr.cpp
Win32/pnUtW32Misc.cpp
Win32/pnUtW32Path.cpp
Win32/pnUtW32Str.cpp
Win32/pnUtW32Sync.cpp
Win32/pnUtW32Time.cpp
Win32/pnUtW32Uuid.cpp
pnUtCrypt.cpp
pnUtTls.cpp
)
else()
set(pnUtils_UNIX

387
Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Addr.cpp

@ -1,387 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Addr.cpp
*
***/
#include "../pnUtils.h"
/*****************************************************************************
*
* Private
*
***/
// hardcoded uint8_t ordering -- Intel only
#ifdef _M_IX86
const unsigned kHostClassALoopbackAddr = 0x7f000001; // 127.0.0.1
const unsigned kHostClassALoopbackMask = 0x00ffffff;
const unsigned kNetClassALoopbackAddr = 0x0100007f; // 127.0.0.1
const unsigned kNetClassALoopbackMask = 0xffffff00;
const unsigned kHostClassANatAddr = 0x000000a0; // 10.0.0.0 - 10.255.255.255
const unsigned kHostClassANatMask = 0x000000ff;
const unsigned kNetClassANatAddr = 0x0a000000; // 10.0.0.0 - 10.255.255.255
const unsigned kNetClassANatMask = 0xff000000;
const unsigned kHostClassBNetAddr = 0x000010ac; // 172.16.0.0 - 172.31.255.255
const unsigned kHostClassBNetMask = 0x0000f0ff;
const unsigned kNetClassBNetAddr = 0xac100000; // 172.16.0.0 - 172.31.255.255
const unsigned kNetClassBNetMask = 0xfff00000;
const unsigned kHostClassCNatAddr = 0x0000a8c0; // 192.168.0.0 - 192.168.255.255
const unsigned kHostClassCNatMask = 0x0000ffff;
const unsigned kNetClassCNatAddr = 0xc0a80000; // 192.168.0.0 - 192.168.255.255
const unsigned kNetClassCNatMask = 0xffff0000;
#else
#error "Must implement for this architecture"
#endif // ifdef _M_IX86
/*****************************************************************************
*
* Internal functions
*
***/
//===========================================================================
// Address sort order:
// (highest)
// externally visible address
// 10.0.0.0 - 10.255.255.255
// 172.16.0.0 - 172.31.255.255
// 192.168.0.0 - 192.168.255.255
// 127.0.0.0 - 127.0.0.255
// (lowest)
static int NetAddressNodeSortValueNetOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kNetClassALoopbackMask) == (kNetClassALoopbackAddr & kNetClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kNetClassCNatMask) == (kNetClassCNatAddr & kNetClassCNatMask))
return 3;
if ((addr & kNetClassBNetMask) == (kNetClassBNetAddr & kNetClassBNetMask))
return 2;
if ((addr & kNetClassANatMask) == (kNetClassANatAddr & kNetClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static int NetAddressNodeSortValueHostOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kHostClassALoopbackMask) == (kHostClassALoopbackAddr & kHostClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kHostClassCNatMask) == (kHostClassCNatAddr & kHostClassCNatMask))
return 3;
if ((addr & kHostClassBNetMask) == (kHostClassBNetAddr & kHostClassBNetMask))
return 2;
if ((addr & kHostClassANatMask) == (kHostClassANatAddr & kHostClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static NetAddressNode NodeFromString (const wchar_t * string[]) {
// skip leading whitespace
const wchar_t * str = *string;
while (iswspace(*str))
++str;
// This function handles partial ip addresses (61.33)
// as well as full dotted quads. The address can be
// terminated by whitespace or ':' as well as '\0'
uint8_t data[4];
* (uint32_t *) data = 0;
for (unsigned i = sizeof(data); i--; ) {
if (!iswdigit(*str))
return (unsigned)-1;
unsigned value = StrToUnsigned(str, &str, 10);
if (value >= 256)
return (unsigned)-1;
data[i] = (uint8_t) value;
if (!*str || (*str == ':') || iswspace(*str))
break;
static const wchar_t s_separator[] = L"\0...";
if (*str++ != s_separator[i])
return (unsigned)-1;
}
*string = str;
return * (NetAddressNode *) &data[0];
}
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
int d = i1.sin_addr.S_un.S_addr - i2.sin_addr.S_un.S_addr;
return d ? d : i1.sin_port - i2.sin_port;
}
//===========================================================================
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
return i1.sin_addr.S_un.S_addr == i2.sin_addr.S_un.S_addr;
}
//===========================================================================
unsigned NetAddressHash (const NetAddress & addr) {
// by using only the node number as the hash value, users can safely use
// hash value to find addresses by either using either "SameSystem" or "Equal"
const sockaddr_in & iAddr = * (const sockaddr_in *) &addr;
return iAddr.sin_addr.S_un.S_addr;
}
//===========================================================================
void NetAddressToString (
const NetAddress & addr,
wchar_t * str,
unsigned chars,
ENetAddressFormat format
) {
ASSERT(str);
static const wchar_t * s_fmts[] = {
L"%S", // kNetAddressFormatNodeNumber
L"%S:%u", // kNetAddressFormatAll
};
ASSERT(format < arrsize(s_fmts));
const sockaddr_in & inetaddr = * (const sockaddr_in *) &addr;
StrPrintf(
str,
chars,
s_fmts[format],
inet_ntoa(inetaddr.sin_addr),
ntohs(inetaddr.sin_port)
);
}
//===========================================================================
bool NetAddressFromString (NetAddress * addr, const wchar_t str[], unsigned defaultPort) {
ASSERT(addr);
ASSERT(str);
// NetAddress is bigger than sockaddr_in so start by zeroing the whole thing
memset(addr, 0, sizeof(*addr));
for (;;) {
NetAddressNode node = NodeFromString(&str);
if (node == (unsigned)-1)
break;
if (*str == L':')
defaultPort = StrToUnsigned(str + 1, nil, 10);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_port = htons((uint16_t) defaultPort);
inetaddr->sin_addr.S_un.S_addr = htonl(node);
// inetaddr->sin_zero already zeroed
return true;
}
// address already zeroed
return false;
}
//===========================================================================
unsigned NetAddressGetPort (
const NetAddress & addr
) {
return ntohs(((sockaddr_in *) &addr)->sin_port);
}
//===========================================================================
void NetAddressSetPort (
unsigned port,
NetAddress * addr
) {
((sockaddr_in *) addr)->sin_port = htons((uint16_t) port);
}
//============================================================================
NetAddressNode NetAddressGetNode (const NetAddress & addr) {
return ntohl(((const sockaddr_in *) &addr)->sin_addr.S_un.S_addr);
}
//===========================================================================
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
) {
memset(addr, 0, sizeof(*addr));
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_addr.S_un.S_addr = htonl(node);
inetaddr->sin_port = htons((uint16_t) port);
}
//===========================================================================
void NetAddressNodeToString (
NetAddressNode node,
wchar_t * str,
unsigned chars
) {
in_addr addr;
addr.S_un.S_addr = htonl(node);
StrPrintf(str, chars, L"%S", inet_ntoa(addr));
}
//===========================================================================
NetAddressNode NetAddressNodeFromString (
const wchar_t string[],
const wchar_t * endPtr[]
) {
if (!endPtr)
endPtr = &string;
*endPtr = string;
return NodeFromString(endPtr);
}
//===========================================================================
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
) {
NetAddressFromNode(
kHostClassALoopbackAddr,
port,
addr
);
}
//===========================================================================
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
) {
ASSERT(count);
ASSERT(addresses);
for (;;) {
// Get local computer name
char name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = arrsize(name);
if (!GetComputerName(name, &size))
StrCopy(name, "localhost", arrsize(name));
// Get IPv4 addresses for local system
const struct hostent * host = gethostbyname(name);
if (!host || !host->h_name)
break;
host = gethostbyname(host->h_name);
if (!host)
break;
if (host->h_length != sizeof(uint32_t))
break;
// Count total number of addresses
unsigned found = 0;
const uint32_t ** addr = (const uint32_t **) host->h_addr_list;
for (; *addr; ++addr)
++found;
if (!found)
break;
// Create a buffer to sort the addresses
NetAddressNode * dst;
if (found > count)
dst = (NetAddressNode*)_alloca(found * sizeof(NetAddressNode));
else
dst = addresses;
// Fill address buffer
const uint32_t * src = * (const uint32_t **) host->h_addr_list;
for (unsigned index = 0; index < found; ++index)
dst[index] = ntohl(src[index]);
// Sort addresses by priority
QSORT(
NetAddressNode,
dst,
found,
NetAddressNodeSortValueHostOrder(elem1) - NetAddressNodeSortValueHostOrder(elem2)
);
// Return the number of addresses the user actually requested
if (found > count) {
for (unsigned index = 0; index < count; ++index)
addresses[index] = dst[index];
return count;
}
return found;
}
// Initialize with a valid value
addresses[0] = kHostClassALoopbackAddr;
return 1;
}

56
Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Dll.cpp

@ -1,56 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Dll.cpp
*
***/
#include "../pnUtils.h"
/*****************************************************************************
*
* Private
*
***/

166
Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Misc.cpp

@ -47,13 +47,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "../pnUtils.h"
/*****************************************************************************
*
* Private
*
***/
static MEMORYSTATUSEX s_memstatus;
/*****************************************************************************
*
* Exports
@ -65,162 +58,3 @@ const wchar_t * AppGetCommandLine () {
return GetCommandLineW();
}
//============================================================================
void MachineGetName (wchar_t *computerName, unsigned int length) {
DWORD len = length;
GetComputerNameW(computerName, &len);
}
/*****************************************************************************
*
* System status
*
***/
//============================================================================
void MemoryGetStatus (MemoryStatus * status) {
MEMORYSTATUSEX mem;
mem.dwLength = sizeof(mem);
GlobalMemoryStatusEx(&mem);
const uint64_t BYTES_PER_MB = 1024 * 1024;
status->totalPhysMB = unsigned(mem.ullTotalPhys / BYTES_PER_MB);
status->availPhysMB = unsigned(mem.ullAvailPhys / BYTES_PER_MB);
status->totalPageFileMB = unsigned(mem.ullTotalPageFile / BYTES_PER_MB);
status->availPageFileMB = unsigned(mem.ullAvailPageFile / BYTES_PER_MB);
status->totalVirtualMB = unsigned(mem.ullTotalVirtual / BYTES_PER_MB);
status->availVirtualMB = unsigned(mem.ullAvailVirtual / BYTES_PER_MB);
status->memoryLoad = mem.dwMemoryLoad;
}
//============================================================================
void DiskGetStatus (ARRAY(DiskStatus) * disks) {
DWORD length = GetLogicalDriveStrings(0, NULL);
if (!length || length > 2048)
return;
wchar_t* buffer = (wchar_t*)malloc((length + 1) * sizeof(wchar_t));
wchar_t* origbuf = buffer;
if (!GetLogicalDriveStringsW(length, buffer))
{
free(buffer);
return;
}
for (; *buffer; buffer += StrLen(buffer) + 1) {
UINT driveType = GetDriveTypeW(buffer);
if (driveType != DRIVE_FIXED)
continue;
ULARGE_INTEGER freeBytes;
ULARGE_INTEGER totalBytes;
if (!GetDiskFreeSpaceExW(buffer, &freeBytes, &totalBytes, NULL))
continue;
DiskStatus status;
StrCopy(status.name, buffer, arrsize(status.name));
const uint64_t BYTES_PER_MB = 1024 * 1024;
status.totalSpaceMB = unsigned(totalBytes.QuadPart / BYTES_PER_MB);
status.freeSpaceMB = unsigned(freeBytes.QuadPart / BYTES_PER_MB);
disks->Add(status);
}
free(origbuf);
}
//============================================================================
// Loosely taken from MS's cpuid code sample
void CpuGetInfo (
uint16_t * cpuCaps,
uint32_t * cpuVendor,
uint16_t * cpuSignature
) {
uint32_t signature = 0;
uint32_t extended = 0;
uint32_t flags[2] = { 0, 0 };
cpuVendor[0] = 0;
#ifdef _MSC_VER
_asm {
// Detect if cpuid instruction is supported by attempting
// to change the ID bit of EFLAGS
pushfd
pop eax // get EFLAGS
mov ecx, eax // store copy of original EFLAGS
xor eax, 0x200000 // flip ID bit
push eax
popfd // replace EFLAGS
pushfd // get EFLAGS
pop eax
xor eax, ecx
je DONE
// Get processor id (GenuineIntel, AuthenticAMD, etc)
xor eax, eax
cpuid
mov edi, cpuVendor
mov [edi + 0], ebx
mov [edi + 4], edx
mov [edi + 8], ecx
// Check if capability flags are supported
cmp eax, 1
jl DONE
// Get processor capability flags and signature
mov eax, 1
cpuid
mov signature, eax
mov [flags + 0], edx
mov [flags + 4], ecx
// Check for extended capabilities
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jl DONE
// Get extended capabilities
mov eax, 0x80000001
cpuid
mov extended, edx
DONE:
}
#endif
// Decode capability flags
const static struct CpuCap {
uint16_t cpuFlag;
uint8_t field;
uint8_t bit;
} s_caps[] = {
// feature field bit
// ------- ----- ---
{ kCpuCapCmov, 0, 15 },
{ kCpuCapEst, 1, 7 },
{ kCpuCapHtt, 0, 28 },
{ kCpuCapMmx, 0, 23 },
{ kCpuCapPsn, 0, 18 },
{ kCpuCapSse, 0, 25 },
{ kCpuCapSse2, 0, 26 },
{ kCpuCapSse3, 1, 0 },
{ kCpuCapTsc, 0, 4 },
};
for (unsigned i = 0; i < arrsize(s_caps); ++i) {
const CpuCap & cap = s_caps[i];
if (flags[cap.field] & (1 << cap.bit))
*cpuCaps |= cap.cpuFlag;
}
// Copy signature
*cpuSignature = uint16_t(signature & 0xfff);
// If this is an AMD CPU, check for 3DNow support
const char * vendorAmd = "AuthenticAMD";
if (!memcmp(vendorAmd, cpuVendor, 12)) {
if (extended & (1 << 31))
*cpuCaps |= kCpuCap3dNow;
}
}

58
Sources/Plasma/NucleusLib/pnUtils/Win32/pnUtW32Sync.cpp

@ -314,61 +314,3 @@ void CLock::LeaveWrite () {
LeaveSpinLock(&m_spinLock);
}
/*****************************************************************************
*
* CEvent
*
***/
//============================================================================
CEvent::CEvent (
ECEventResetBehavior resetType,
bool initialSet
) {
m_handle = CreateEvent(
nil, // security attributes
(resetType == kEventManualReset) ? true : false,
initialSet,
nil // name
);
}
//============================================================================
CEvent::~CEvent () {
(void) CloseHandle(m_handle);
}
//============================================================================
void CEvent::Signal () {
SetEvent(m_handle);
}
//============================================================================
void CEvent::Reset () {
ResetEvent(m_handle);
}
//============================================================================
bool CEvent::Wait (unsigned waitMs) {
ThreadAssertCanBlock(__FILE__, __LINE__);
return WaitForSingleObject(m_handle, waitMs) == WAIT_OBJECT_0;
}
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
long AtomicAdd (long * value, long increment) {
return InterlockedExchangeAdd(value, increment);
}
//===========================================================================
long AtomicSet (long * value, long set) {
return InterlockedExchange(value, set);
}

95
Sources/Plasma/NucleusLib/pnUtils/pnUtAddr.cpp

@ -1,95 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.cpp
*
***/
#include "pnUtAddr.h"
/*****************************************************************************
*
* CNetAddressHash
*
***/
//============================================================================
CNetAddressHash::CNetAddressHash (
const NetAddress & addr
) : m_addr(addr)
, m_equals(nil)
{ }
//============================================================================
CNetAddressHash::CNetAddressHash (
const NetAddress & addr,
FNetAddressEqualityProc equals
) : m_addr(addr)
, m_equals(equals)
{ }
//============================================================================
bool CNetAddressHash::operator== (const CNetAddressHash & rhs) const {
ASSERT(m_equals);
return m_equals(m_addr, rhs.m_addr);
}
//============================================================================
unsigned CNetAddressHash::GetHash () const {
return NetAddressHash(m_addr);
}
//============================================================================
const NetAddress & CNetAddressHash::GetAddr () const {
return m_addr;
}
/*****************************************************************************
*
* Exported data
*
***/
NetAddress kNilNetAddress;

170
Sources/Plasma/NucleusLib/pnUtils/pnUtAddr.h

@ -1,170 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTADDR_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTADDR_H
#include "Pch.h"
/*****************************************************************************
*
* Types and constants
*
***/
struct NetAddress {
uint8_t data[24];
};
typedef unsigned NetAddressNode;
extern NetAddress kNilNetAddress;
typedef bool (*FNetAddressEqualityProc)(
const NetAddress & a1,
const NetAddress & a2
);
class CNetAddressHash {
NetAddress m_addr;
FNetAddressEqualityProc m_equals;
public:
CNetAddressHash (
const NetAddress & addr
);
CNetAddressHash (
const NetAddress & addr,
FNetAddressEqualityProc equals
// Useful values for 'equals':
// NetAddressEqual --> address node and port numbers match
// NetAddressSameSystem --> address node numbers match
);
void operator= (const CNetAddressHash & rhs) const; // not impl.
bool operator== (const CNetAddressHash & rhs) const;
unsigned GetHash () const;
const NetAddress & GetAddr () const;
};
/*****************************************************************************
*
* Functions
*
***/
enum ENetAddressFormat {
kNetAddressFormatNodeNumber,
kNetAddressFormatAll,
kNumNetAddressFormats
};
unsigned NetAddressHash (const NetAddress & addr);
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2);
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2);
inline bool NetAddressEqual (const NetAddress & a1, const NetAddress & a2) {
return NetAddressCompare(a1, a2) == 0;
}
void NetAddressToString (
const NetAddress & addr,
wchar_t * str,
unsigned chars,
ENetAddressFormat format
);
// 'str' must be in the form of a dotted IP address (IPv4 or IPv6)
// - names which require DNS lookup will cause the function to return false
bool NetAddressFromString (
NetAddress * addr,
const wchar_t str[],
unsigned defaultPort
);
unsigned NetAddressGetPort (
const NetAddress & addr
);
void NetAddressSetPort (
unsigned port,
NetAddress * addr
);
void NetAddressNodeToString (
NetAddressNode node,
wchar_t * str,
unsigned chars
);
NetAddressNode NetAddressNodeFromString (
const wchar_t string[],
const wchar_t * endPtr[]
);
NetAddressNode NetAddressGetNode (
const NetAddress & addr
);
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
);
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
);
// Returns number of addresses set, which is guaranteed to be non-zero.
// Furthermore, it sorts the addresses so that loopback and NAT addresses
// are at the end of the array, and "real" addresses are at the beginning.
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
);
#endif

7
Sources/Plasma/NucleusLib/pnUtils/pnUtAllIncludes.h

@ -51,9 +51,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "pnUtCoreLib.h" // must be first in list
#include "pnUtPragma.h"
#include "pnUtAddr.h"
#include "pnUtUuid.h"
#include "pnUtMath.h"
#include "pnUtSort.h"
#include "pnUtArray.h"
#include "pnUtList.h"
@ -61,16 +59,11 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "pnUtPriQ.h"
#include "pnUtSync.h"
#include "pnUtTime.h"
#include "pnUtTls.h"
#include "pnUtStr.h"
#include "pnUtRef.h"
#include "pnUtPath.h"
#include "pnUtBigNum.h"
#include "pnUtCmd.h"
#include "pnUtMisc.h"
#include "pnUtCrypt.h"
#include "pnUtSpareList.h"
#include "pnUtRand.h"
#include "pnUtBase64.h"
#endif // PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H

109
Sources/Plasma/NucleusLib/pnUtils/pnUtArray.h

@ -62,12 +62,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#define FARRAY(type) TFArray< type, TArrayCopyBits< type > >
#define FARRAYOBJ(type) TFArray< type, TArrayCopyObject< type > >
#define SORTARRAYFIELD(type, keyType, field) TSortArray< type, TArrayCopyBits< type >, keyType, offsetof(type, field)>
#define SORTARRAYFIELDOBJ(type, keyType, field) TSortArray< type, TArrayCopyObject< type >, keyType, offsetof(type, field)>
#define SORTARRAYTYPE(type) TSortArray< type, TArrayCopyBits< type >, type, 0>
#define SORTARRAYTYPEOBJ(type) TSortArray< type, TArrayCopyObject< type >, type, 0>
/****************************************************************************
*
* CBuffer
@ -978,107 +972,4 @@ template<class T, class C>
void TArray<T,C>::Trim () {
this->AdjustSize(this->m_count, this->m_count);
}
/****************************************************************************
*
* TSortArray
*
***/
template<class T, class C, class K, unsigned OFFSET>
class TSortArray : public TArray<T,C> {
private:
inline static K & SortKey (T & rec) { return *(K *)((uint8_t *)&rec + OFFSET); }
inline static const K & SortKey (const T & rec) { return *(const K *)((const uint8_t *)&rec + OFFSET); }
public:
inline bool Delete (K sortKey);
inline T * Find (K sortKey) { unsigned index; return Find(sortKey, &index); }
inline T * Find (K sortKey, unsigned * index);
inline const T * Find (K sortKey) const { unsigned index; return Find(sortKey, &index); }
inline const T * Find (K sortKey, unsigned * index) const;
inline T * Insert (K sortKey, unsigned index);
inline void Sort ();
};
//===========================================================================
template<class T, class C, class K, unsigned OFFSET>
bool TSortArray<T,C,K,OFFSET>::Delete (K sortKey) {
// Find the correct position for this key
unsigned index;
BSEARCH(T, this->Ptr(), this->Count(), (sortKey > SortKey(elem)), &index);
// Verify that an entry exists for this key
unsigned count = this->Count();
if ((index >= count) || (SortKey((*this)[index]) != sortKey))
return false;
// Delete the entry
this->DeleteOrdered(index);
return true;
}
//===========================================================================
template<class T, class C, class K, unsigned OFFSET>
T * TSortArray<T,C,K,OFFSET>::Find (K sortKey, unsigned * index) {
// Find the correct position for this key
BSEARCH(T, this->Ptr(), this->Count(), (sortKey > SortKey(elem)), index);
if (*index >= this->Count())
return nil;
// Check whether the key is at that position
T & elem = (*this)[*index];
return (SortKey(elem) == sortKey) ? &elem : nil;
}
//===========================================================================
template<class T, class C, class K, unsigned OFFSET>
const T * TSortArray<T,C,K,OFFSET>::Find (K sortKey, unsigned * index) const {
// Find the correct position for this key
BSEARCH(T, this->Ptr(), this->Count(), (sortKey > SortKey(elem)), index);
if (*index >= this->Count())
return nil;
// Check whether the key is at that position
const T & elem = (*this)[*index];
return (SortKey(elem) == sortKey) ? &elem : nil;
}
//===========================================================================
template<class T, class C, class K, unsigned OFFSET>
T * TSortArray<T,C,K,OFFSET>::Insert (K sortKey, unsigned index) {
// Insert a new entry at this position
unsigned count = this->Count();
this->SetCount(count + 1);
if (index < count)
this->Move(index + 1, index, count - index);
// Fill in the new entry
T & elem = (*this)[index];
SortKey(elem) = sortKey;
return &elem;
}
//===========================================================================
template<class T, class C, class K, unsigned OFFSET>
void TSortArray<T,C,K,OFFSET>::Sort () {
T * ptr = this->Ptr();
unsigned count = this->Count();
QSORT(
T,
ptr,
count,
SortKey(elem1) > SortKey(elem2)
);
}
#endif

182
Sources/Plasma/NucleusLib/pnUtils/pnUtBase64.cpp

@ -1,182 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.cpp
*
***/
#include "pnUtBase64.h"
/*****************************************************************************
*
* Private
*
***/
static const char kEncode64[] = {
// 0000000000111111111122222222223333333333444444444455555555556666
// 0123456789012345678901234567890123456789012345678901234567890123
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
};
// Note that the decode table contains one special entry:
// The '-' character (0x2d) maps to 63 just like '/' (0x2f)
// so that URLs will work with Base64Decode when we implement them.
#define kTerminator 127
#define xx kTerminator
static const char kDecode64[] = {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,62,xx,63,xx,63,
52,53,54,55,56,57,58,59,60,61,xx,xx,xx,xx,xx,xx,
xx, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25,xx,xx,xx,xx,xx,
xx,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
};
#undef xx
static const char kFillchar = '=';
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
unsigned Base64Encode (
unsigned srcChars,
const uint8_t srcData[],
unsigned dstChars,
char * dstData
) {
ASSERT(srcData);
ASSERT(dstChars >= Base64EncodeSize(srcChars));
ASSERT(dstData);
const char * dstBase = dstData;
const uint8_t * srcTerm = srcData + srcChars;
for (;;) switch (srcTerm - srcData) {
case 0:
*dstData++ = 0;
return dstData - dstBase;
case 1:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) ];
*dstData++ = kFillchar;
*dstData++ = kFillchar;
*dstData++ = 0;
return dstData - dstBase;
case 2:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) + ((srcData[1] >> 4) & 0x0f) ];
*dstData++ = kEncode64[ ((srcData[1] << 2) & 0x3c) ];
*dstData++ = kFillchar;
*dstData++ = 0;
return dstData - dstBase;
default:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) + ((srcData[1] >> 4) & 0x0f) ];
*dstData++ = kEncode64[ ((srcData[1] << 2) & 0x3c) + ((srcData[2] >> 6) & 0x03) ];
*dstData++ = kEncode64[ (srcData[2] & 0x3f) ];
srcData += 3;
break;
}
}
//============================================================================
unsigned Base64Decode (
unsigned srcChars,
const char srcData[],
unsigned dstChars,
uint8_t * dstData
) {
ASSERT(srcData);
ASSERT(dstChars >= Base64DecodeSize(srcChars, srcData));
ASSERT(dstData);
const uint8_t * dstBase = dstData;
const char * srcTerm = srcData + srcChars;
while (srcTerm - srcData >= 4) {
*dstData++ = (uint8_t) (
(kDecode64[srcData[0]] << 2 & 0xfc)
+(kDecode64[srcData[1]] >> 4 & 0x03)
);
if (kDecode64[srcData[2]] == kTerminator)
break;
*dstData++ = (uint8_t) (
(kDecode64[srcData[1]] << 4 & 0xf0)
+(kDecode64[srcData[2]] >> 2 & 0x0f)
);
if (kDecode64[srcData[3]] == kTerminator)
break;
*dstData++ = (uint8_t) (
(kDecode64[srcData[2]] << 6 & 0xc0)
+(kDecode64[srcData[3]])
);
srcData += 4;
}
return dstData - dstBase;
}

85
Sources/Plasma/NucleusLib/pnUtils/pnUtBase64.h

@ -1,85 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBASE64_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBASE64_H
#include "Pch.h"
/*****************************************************************************
*
* Base64 Codec API
*
***/
const unsigned kBase64EncodeBlock = 4;
const unsigned kBase64EncodeMultiple = 3;
inline unsigned Base64EncodeSize (unsigned srcChars) {
return (srcChars + kBase64EncodeMultiple - 1) / kBase64EncodeMultiple
* kBase64EncodeBlock;
}
unsigned Base64Encode (
unsigned srcChars,
const uint8_t srcData[],
unsigned dstChars,
char * dstData
);
inline unsigned Base64DecodeSize (unsigned srcChars, const char srcData[]) {
return srcChars * kBase64EncodeMultiple / kBase64EncodeBlock
- ((srcChars >= 1 && srcData[srcChars - 1] == '=') ? 1 : 0)
- ((srcChars >= 2 && srcData[srcChars - 2] == '=') ? 1 : 0);
}
unsigned Base64Decode (
unsigned srcChars,
const char srcData[],
unsigned dstChars,
uint8_t * dstData
);
#endif

48
Sources/Plasma/NucleusLib/pnUtils/pnUtCmd.cpp

@ -648,51 +648,3 @@ bool CCmdParser::Parse (const wchar_t cmdLine[]) {
return result;
}
/****************************************************************************
*
* CCmdParserSimple
*
***/
//===========================================================================
CCmdParserSimple::CCmdParserSimple (
unsigned requiredStringCount,
unsigned optionalStringCount,
const wchar_t flaggedBoolNames[] // double null terminated if used
) {
// Count the number of flagged arguments
unsigned flaggedBoolCount = 0;
const wchar_t * curr;
if (flaggedBoolNames)
for (curr = flaggedBoolNames; *curr; curr += StrLen(curr) + 1)
++flaggedBoolCount;
// Build the argument definition array
unsigned totalCount = requiredStringCount + optionalStringCount + flaggedBoolCount;
FARRAY(CmdArgDef) argDef(totalCount);
unsigned index = 0;
for (; index < requiredStringCount; ++index) {
argDef[index].flags = kCmdArgRequired | kCmdTypeString;
argDef[index].name = nil;
argDef[index].id = index + 1;
}
for (; index < requiredStringCount + optionalStringCount; ++index) {
argDef[index].flags = kCmdArgOptional | kCmdTypeString;
argDef[index].name = nil;
argDef[index].id = index + 1;
}
for (curr = flaggedBoolNames; index < totalCount; ++index) {
argDef[index].flags = kCmdArgFlagged | kCmdTypeBool;
argDef[index].name = curr;
argDef[index].id = 0;
curr += StrLen(curr) + 1;
}
// Initialize the parser
Initialize(argDef.Ptr(), argDef.Count());
}

10
Sources/Plasma/NucleusLib/pnUtils/pnUtCmd.h

@ -133,14 +133,4 @@ public:
bool Parse (const wchar_t cmdLine[] = nil);
};
class CCmdParserSimple : public CCmdParser {
public:
CCmdParserSimple (
unsigned requiredStringCount,
unsigned optionalStringCount,
const wchar_t flaggedBoolNames[] // double null terminated if used
);
};
#endif

45
Sources/Plasma/NucleusLib/pnUtils/pnUtHash.h

@ -51,7 +51,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "Pch.h"
#include "pnUtList.h"
#include "pnUtArray.h"
#include "pnUtMath.h"
#include "pnUtStr.h"
/****************************************************************************
@ -63,24 +62,12 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// Define a field inside an object that is used to link it into a hash table
#define HASHLINK(object) THashLink< object >
// Define a POINTER to a hash table, not a hash table
#define HASHTABLE(object,key) THashTable< object, key >
// Define a hash table:
// - starts with kSlotMinCount rows
// - can grow to kDefaultSlotMaxCount rows
// (hash table grows when a row contains more than kGrowOnListSize entries
#define HASHTABLEDECL(object,key,link) THashTableDecl< object, key, offsetof(object,link), 0 >
// Define a hash table in situations when a forward reference prevents use of HASHTABLEDECL
// - Size characteristics are identical to HASHTABLEDECL
#define HASHTABLEDYN(object,key) THashTableDyn< object, key >
// Define a hash table with:
// - starts with <size>
// - row table never grows
#define HASHTABLEDECLSIZE(object,key,link,size) THashTableDecl<object, key, offsetof(object,link), size >
#if defined(_MSC_VER)
#define forceinline __forceinline
@ -437,8 +424,14 @@ void TBaseHashTable<T>::SetLinkOffset (int linkOffset, unsigned maxSize) {
m_linkOffset = linkOffset;
m_fullList.SetLinkOffset(m_linkOffset + offsetof(THashLink<T>, m_linkToFull));
if (!m_slotMask)
SetSlotCount(max(kSlotMinCount, MathNextPow2(maxSize)));
if (!m_slotMask) {
// http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
uint32_t v = maxSize - 1;
v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16;
v++;
SetSlotCount(max(kSlotMinCount, v));
}
}
//===========================================================================
@ -590,28 +583,6 @@ THashTableDecl<T,K,linkOffset,maxSize>::THashTableDecl () {
}
/****************************************************************************
*
* THashTableDyn
*
***/
template<class T, class K>
class THashTableDyn : public THashTable<T,K> {
public:
void Initialize (int linkOffset, unsigned maxSize = 0);
};
//===========================================================================
template<class T, class K>
void THashTableDyn<T,K>::Initialize (int linkOffset, unsigned maxSize) {
this->SetLinkOffset(linkOffset, maxSize);
this->SetSlotMaxCount(maxSize);
}
/****************************************************************************
*
* THashKeyVal

63
Sources/Plasma/NucleusLib/pnUtils/pnUtMath.cpp

@ -1,63 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.cpp
*
***/
#include "pnUtMath.h"
/*****************************************************************************
*
* Exported bit manipulation functions
*
***/
//===========================================================================
unsigned MathHighBitPos (uint32_t val) {
ASSERT(val);
double f = (double)val;
return (*((uint32_t *)&f + 1) >> 20) - 1023;
}

102
Sources/Plasma/NucleusLib/pnUtils/pnUtMath.h

@ -1,102 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMATH_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMATH_H
#include "Pch.h"
/*****************************************************************************
*
* Bit manipulation functions
*
***/
unsigned MathHighBitPos (uint32_t val);
//===========================================================================
inline unsigned MathBitCount (uint32_t val) {
val = val - ((val >> 1) & 033333333333) - ((val >> 2) & 011111111111);
val = ((val + (val >> 3)) & 030707070707);
val = val + (val >> 6);
val = (val + (val >> 12) + (val >> 24)) & 077;
return val;
}
//===========================================================================
inline unsigned MathBitMaskCreate (unsigned count) {
ASSERT(count <= 8 * sizeof(unsigned));
return count ? ((2 << (count - 1)) - 1) : 0;
}
//===========================================================================
inline uint32_t MathHighBitValue (uint32_t val) {
return val ? 1 << MathHighBitPos(val) : 0;
}
//===========================================================================
inline bool MathIsPow2 (unsigned val) {
return !(val & (val - 1));
}
//===========================================================================
inline unsigned MathLowBitValue (unsigned val) {
return val & ~(val - 1);
}
//===========================================================================
inline unsigned MathNextMultiplePow2 (unsigned val, unsigned multiple) {
ASSERT(multiple);
ASSERT(MathIsPow2(multiple));
return (val + (multiple - 1)) & ~(multiple - 1);
}
//===========================================================================
inline uint32_t MathNextPow2 (uint32_t val) {
return MathIsPow2(val) ? val : 1 << (MathHighBitPos(val) + 1);
}
#endif

81
Sources/Plasma/NucleusLib/pnUtils/pnUtMisc.h

@ -51,16 +51,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "Pch.h"
#include "pnUtArray.h"
/*****************************************************************************
*
* Constants
*
***/
const wchar_t UNICODE_BOM = 0xfeff; // Unicode byte-order mark
const char UTF8_BOM[] = "\xef\xbb\xbf";
/*****************************************************************************
*
* Module instance functions
@ -80,14 +70,6 @@ void * ModuleGetInstance ();
const wchar_t * AppGetCommandLine ();
/*****************************************************************************
*
* System info functions
*
***/
void MachineGetName (wchar_t * computerName, unsigned length = 32);
/*****************************************************************************
*
* Misc types
@ -101,67 +83,4 @@ typedef void (CDECL * FStateDump)(
...
);
/*****************************************************************************
*
* Dll initialization
*
***/
#if HS_BUILD_FOR_WIN32
#define SRV_MODULE_PRE_INIT() \
extern BOOL WINAPI PreDllMain (HANDLE handle, DWORD reason, LPVOID); \
extern "C" BOOL (WINAPI *_pRawDllMain)(HANDLE, DWORD, LPVOID) = PreDllMain
#endif
/*****************************************************************************
*
* System status
*
***/
struct MemoryStatus {
unsigned totalPhysMB; // total physical memory
unsigned availPhysMB; // free physical memory
unsigned totalPageFileMB; // total page file size
unsigned availPageFileMB; // free page file size
unsigned totalVirtualMB; // total virtual address space for calling process
unsigned availVirtualMB; // available virtual address space for calling process
unsigned memoryLoad; // 0..100
};
void MemoryGetStatus (MemoryStatus * status);
struct DiskStatus {
wchar_t name[16];
unsigned totalSpaceMB;
unsigned freeSpaceMB;
};
void DiskGetStatus (ARRAY(DiskStatus) * disks);
void CpuGetInfo (
uint16_t * cpuCaps,
uint32_t * cpuVendor,
uint16_t * cpuSignature
);
// CPU capability flags
const unsigned kCpuCap3dNow = 1<<0;
const unsigned kCpuCapCmov = 1<<1; // conditional move
const unsigned kCpuCapEst = 1<<2; // enhanced speed step
const unsigned kCpuCapHtt = 1<<3; // hyperthreading
const unsigned kCpuCapMmx = 1<<4; // multimedia extensions
const unsigned kCpuCapPsn = 1<<5; // processor serial number
const unsigned kCpuCapSse = 1<<6; // streaming SIMD extensions
const unsigned kCpuCapSse2 = 1<<7;
const unsigned kCpuCapSse3 = 1<<8;
const unsigned kCpuCapTsc = 1<<9; // time stamp counter
// Macros for packing and unpacking CPU signature
#define CPU_SIGNATURE(family, model, stepping) ((stepping) | (model << 4) | (family << 8))
#define CPU_SIGNATURE_FAMILY(sig) ((sig >> 8) & 0xf)
#define CPU_SIGNATURE_MODEL(sig) ((sig >> 4) & 0xf)
#define CPU_SIGNATURE_STEPPING(sig) (sig & 0xf)
#endif

48
Sources/Plasma/NucleusLib/pnUtils/pnUtPriQ.h

@ -57,11 +57,9 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
***/
#define PRIORITY_TIME(class) TPriorityTime< class >
#define PRIORITY_NUMERIC(class,type) TPriorityNumeric< class,type >
#define PRIQ(class,priority) TPriorityQueue< class,priority >
#define PRIQDECL(class,priority,field) TPriorityQueueDecl< class,priority,offsetof(class,field) >
#define PRIQDYN(class,priority) TPriorityQueueDyn< class,priority >
/****************************************************************************
@ -351,19 +349,6 @@ public:
};
/****************************************************************************
*
* TPriorityQueueDyn
*
***/
template<class C, class P>
class TPriorityQueueDyn : public TPriorityQueue<C,P> {
public:
void Initialize (int linkOffset) { this->SetLinkOffset(linkOffset); }
};
/****************************************************************************
*
* class TBasePriority
@ -419,39 +404,6 @@ void TBasePriority<C,P>::Relink () {
queue->Enqueue(object);
}
/****************************************************************************
*
* class TPriorityNumeric
*
***/
template<class C,class T>
class TPriorityNumeric : public TBasePriority< C, TPriorityNumeric<C,T> > {
public:
TPriorityNumeric () : m_value(0) { }
TPriorityNumeric (T value) : m_value(value) { }
void Set (T value) {
if (value == m_value)
return;
m_value = value;
this->Relink();
}
T Get () const {
return m_value;
}
bool IsPriorityHigher (const TPriorityNumeric<C,T> & source) {
return m_value > source.m_value;
}
bool IsPriorityHigher (T value) const {
return m_value > value;
}
private:
T m_value;
};
/****************************************************************************
*
* class TPriorityTime

184
Sources/Plasma/NucleusLib/pnUtils/pnUtRand.cpp

@ -1,184 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.cpp
*
***/
#include "pnUtRand.h"
/*****************************************************************************
*
* Private
*
***/
class RandomContext {
uint32_t m_seed;
uint32_t m_value;
void UpdateValue ();
public:
RandomContext ();
void Reset ();
void SetSeed (unsigned seed);
float GetFloat ();
float GetFloat (float minVal, float maxVal);
unsigned GetUnsigned ();
unsigned GetUnsigned (unsigned minVal, unsigned maxVal);
};
/*****************************************************************************
*
* Private data
*
***/
static const uint32_t kDefaultRandomSeed = 0x075bd924;
static RandomContext s_random;
/*****************************************************************************
*
* RandomContext
*
***/
//============================================================================
RandomContext::RandomContext ()
: m_seed(kDefaultRandomSeed)
{
Reset();
}
//============================================================================
void RandomContext::UpdateValue () {
const uint32_t A = 0xbc8f;
const uint32_t Q = 0xadc8;
const uint32_t R = 0x0d47;
uint32_t div = m_value / Q;
m_value = A * (m_value - Q * div) - R * div;
if (m_value > kRandomMax)
m_value -= kRandomMax + 1;
if (!m_value)
m_value = kDefaultRandomSeed;
}
//============================================================================
void RandomContext::Reset () {
m_value = m_seed;
}
//============================================================================
void RandomContext::SetSeed (unsigned seed) {
// Never allow a seed of zero
m_seed = seed ? seed : kDefaultRandomSeed;
Reset();
}
//============================================================================
float RandomContext::GetFloat () {
UpdateValue();
return m_value * (1.0f / kRandomMax);
}
//============================================================================
float RandomContext::GetFloat (float minVal, float maxVal) {
float value = GetFloat();
return minVal + value * (maxVal - minVal);
}
//============================================================================
unsigned RandomContext::GetUnsigned () {
UpdateValue();
return (unsigned)m_value;
}
//============================================================================
unsigned RandomContext::GetUnsigned (unsigned minVal, unsigned maxVal) {
unsigned value = GetUnsigned();
return minVal + value % (maxVal - minVal + 1);
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void RandReset () {
s_random.Reset();
}
//============================================================================
void RandSetSeed (unsigned seed) {
s_random.SetSeed(seed);
}
//============================================================================
float RandFloat () {
return s_random.GetFloat();
}
//============================================================================
float RandFloat (float minVal, float maxVal) {
return s_random.GetFloat(minVal, maxVal);
}
//============================================================================
unsigned RandUnsigned () {
return s_random.GetUnsigned();
}
//============================================================================
unsigned RandUnsigned (unsigned minVal, unsigned maxVal) {
return s_random.GetUnsigned(minVal, maxVal);
}

67
Sources/Plasma/NucleusLib/pnUtils/pnUtRand.h

@ -1,67 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTRAND_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTRAND_H
#include "Pch.h"
/*****************************************************************************
*
* Psuedo-random number generator
*
***/
const uint32_t kRandomMax = 0x7fffffff;
void RandReset ();
void RandSetSeed (unsigned seed);
float RandFloat ();
float RandFloat (float minVal, float maxVal);
unsigned RandUnsigned ();
unsigned RandUnsigned (unsigned minVal, unsigned maxVal);
#endif

46
Sources/Plasma/NucleusLib/pnUtils/pnUtSort.h

@ -191,50 +191,4 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
} \
} \
}
/****************************************************************************
*
* BSEARCH
*
* This macro binary searches a sorted array to find an existing entry or
* the position where a new entry should be placed. It returns the index of
* the first entry for which the expression is false (zero or negative), or
* count if the expression is true (positive) for all entries.
*
* Typically the expression will return:
* > 0 if (sortKey > elem)
* <= 0 if (sortKey <= elem)
*
* The final parameter to the macro is the address of a variable which is
* filled with the resulting index.
*
***/
//===========================================================================
#define BSEARCH(T, ptr, count, expr, addrOfIndex) { \
\
const T * low = (ptr); \
const T * high = (ptr) + (count); /* first entry for which */ \
/* expr is false */ \
\
if (low != high) \
for (;;) { \
const T & elem = *(low + (high - low) / 2); \
int result = (expr); \
if (result > 0) { \
if (&elem == low) \
break; \
low = &elem; \
} \
else { \
high = &elem; \
if (&elem == low) \
break; \
} \
} \
\
*(addrOfIndex) = high - (ptr); \
\
}
#endif

163
Sources/Plasma/NucleusLib/pnUtils/pnUtSpareList.cpp

@ -1,163 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.cpp
*
***/
#include "pnUtSpareList.h"
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
CBaseSpareList::CBaseSpareList ()
: m_allocHead(nil),
m_spareHead(nil),
m_chunkSize(0)
{
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects = 0;
#endif
}
//===========================================================================
void * CBaseSpareList::Alloc (unsigned objectSize, const char typeName[]) {
// if there aren't any spare nodes available then make more
if (!m_spareHead)
GrowSpareList(objectSize, typeName);
// dequeue the head of the spare list
void * const object = m_spareHead;
m_spareHead = m_spareHead->spareNext;
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects++;
#endif
// initialize memory to a freaky value in debug mode
#ifdef HS_DEBUGGING
memset(object, (uint8_t) ((unsigned) object >> 4), objectSize);
#endif
return object;
}
//===========================================================================
void CBaseSpareList::Free (void * object, unsigned objectSize) {
// initialize memory to a freaky value in debug mode
#ifdef HS_DEBUGGING
memset(object, (uint8_t) ((unsigned) object >> 4), objectSize);
#endif
// link memory block onto head of spare list
((SpareNode *) object)->spareNext = m_spareHead;
m_spareHead = (SpareNode *) object;
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects--;
#endif
}
//===========================================================================
void CBaseSpareList::GrowSpareList (unsigned objectSize, const char typeName[]) {
// Grow the allocation by a substantial amount each time
// to reduce the time spent in memory managament
m_chunkSize *= 2;
const unsigned MIN_ALLOC = max(1, 256/objectSize);
const unsigned MAX_ALLOC = max(512, 32*1024/objectSize);
if (m_chunkSize < MIN_ALLOC)
m_chunkSize = MIN_ALLOC;
else if (m_chunkSize > MAX_ALLOC)
m_chunkSize = MAX_ALLOC;
// allocate a block of memory to hold a bunch
// of T-objects, but allocate them as "raw" memory
AllocNode * allocNode = (AllocNode *) malloc(
sizeof(AllocNode) + objectSize * m_chunkSize
);
// link allocation onto head of allocation list
allocNode->allocNext = m_allocHead;
m_allocHead = allocNode;
// chain newly created raw memory units together onto the spare list
SpareNode * spareCurr = (SpareNode *) (allocNode + 1);
SpareNode * spareEnd = (SpareNode *) ((uint8_t *) spareCurr + objectSize * m_chunkSize);
do {
spareCurr->spareNext = m_spareHead;
m_spareHead = spareCurr;
spareCurr = (SpareNode *) ((uint8_t *) spareCurr + objectSize);
} while (spareCurr < spareEnd);
}
//===========================================================================
void CBaseSpareList::CleanUp (const char typeName[]) {
// warn of resource leaks
#ifdef SPARELIST_TRACK_MEMORY
if (m_unfreedObjects) {
#ifdef CLIENT
{
char buffer[256];
snprintf(buffer, arrsize(buffer), "Memory leak: %s", typeName);
FATAL(buffer);
}
#else
{
DEBUG_MSG("Memory leak: %s", typeName);
}
#endif
}
#endif
// walk chain of AllocNodes and free each of them
while (m_allocHead) {
AllocNode * allocNext = m_allocHead->allocNext;
free(m_allocHead);
m_allocHead = allocNext;
}
m_spareHead = nil;
}

148
Sources/Plasma/NucleusLib/pnUtils/pnUtSpareList.h

@ -1,148 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSPARELIST_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSPARELIST_H
#include "Pch.h"
#include <typeinfo>
#ifdef HS_DEBUGGING
#define SPARELIST_TRACK_MEMORY
#endif
/****************************************************************************
*
* CBaseSpareList
*
***/
class CBaseSpareList {
public:
CBaseSpareList ();
protected:
struct SpareNode {
SpareNode * spareNext;
};
SpareNode * m_spareHead;
void * Alloc (unsigned objectSize, const char typeName[]);
void CleanUp (const char typeName[]);
void Free (void * object, unsigned objectSize);
private:
union AllocNode {
AllocNode * allocNext;
uint64_t align;
};
AllocNode * m_allocHead;
unsigned m_chunkSize;
#ifdef SPARELIST_TRACK_MEMORY
unsigned m_unfreedObjects;
#endif
void GrowSpareList (unsigned objectSize, const char typeName[]);
};
/****************************************************************************
*
* TSpareList
*
***/
template<class T>
class TSpareList : public CBaseSpareList {
private:
enum { OBJECT_SIZE = MAX(sizeof(T), sizeof(SpareNode)) };
public:
~TSpareList () { CleanUp(); }
void * Alloc ();
void CleanUp ();
void Delete (T * node);
void Free (T * node);
T * New ();
};
//===========================================================================
template<class T>
void * TSpareList<T>::Alloc () {
return CBaseSpareList::Alloc(OBJECT_SIZE, typeid(T).name());
}
//===========================================================================
template<class T>
void TSpareList<T>::CleanUp () {
CBaseSpareList::CleanUp(typeid(T).name());
}
//===========================================================================
template<class T>
void TSpareList<T>::Delete (T * node) {
node->~T();
CBaseSpareList::Free(node, OBJECT_SIZE);
}
//===========================================================================
template<class T>
void TSpareList<T>::Free (T * node) {
CBaseSpareList::Free(node, OBJECT_SIZE);
}
//===========================================================================
template<class T>
T * TSpareList<T>::New () {
return new(CBaseSpareList::Alloc(OBJECT_SIZE, typeid(T).name())) T;
}
#endif

57
Sources/Plasma/NucleusLib/pnUtils/pnUtSync.h

@ -50,26 +50,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "Pch.h"
/****************************************************************************
*
* Atomic operations
*
***/
// *value += increment; return original value of *value; thread safe
long AtomicAdd (long * value, long increment);
// *value = value; return original value of *value; thread safe
long AtomicSet (long * value, long set);
#define ATOMIC_ONCE(code) { \
static long s_count = 1; \
if (AtomicSet(&s_count, 0)) \
code; \
} //
/****************************************************************************
*
* CLock
@ -95,41 +75,4 @@ public:
void LeaveWrite ();
};
/*****************************************************************************
*
* CEvent
*
***/
#ifdef HS_BUILD_FOR_WIN32
typedef HANDLE EventHandle;
//#else
//# error "CEvent: Not implemented on this platform"
//#endif
const unsigned kEventWaitForever = (unsigned)-1;
enum ECEventResetBehavior {
kEventManualReset,
kEventAutoReset,
};
class CEvent {
EventHandle m_handle;
public:
CEvent (
ECEventResetBehavior resetType,
bool initialSet = false
);
~CEvent ();
void Signal ();
void Reset ();
bool Wait (unsigned waitMs);
const EventHandle & Handle () const { return m_handle; }
};
#endif // HS_BUILD_FOR_WIN32
#endif

82
Sources/Plasma/NucleusLib/pnUtils/pnUtTls.cpp

@ -1,82 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.cpp
*
***/
#include "pnUtTls.h"
/*****************************************************************************
*
* Exports
*
***/
#ifdef HS_BUILD_FOR_WIN32
//============================================================================
void ThreadLocalAlloc (unsigned * id) {
ASSERT(id);
*id = TlsAlloc();
}
//============================================================================
void ThreadLocalFree (unsigned id) {
(void)TlsFree(id);
}
//============================================================================
void * ThreadLocalGetValue (unsigned id) {
return TlsGetValue(id);
}
//============================================================================
void ThreadLocalSetValue (unsigned id, void * value) {
TlsSetValue(id, value);
}
#else
# error "TLS not implemented for this platform"
#endif

72
Sources/Plasma/NucleusLib/pnUtils/pnUtTls.h

@ -1,72 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTLS_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTLS_H
#include "Pch.h"
/*****************************************************************************
*
* Thread local storage functions
*
***/
const unsigned kTlsInvalidValue = (unsigned) -1;
void ThreadLocalAlloc (unsigned * id);
void ThreadLocalFree (unsigned id);
void * ThreadLocalGetValue (unsigned id);
void ThreadLocalSetValue (unsigned id, void * value);
// Thread capability functions - prevents deadlocks and performance
// bottlenecks by disallowing some threads certain operations.
void ThreadAllowBlock ();
void ThreadDenyBlock ();
void ThreadAssertCanBlock (const char file[], int line);
#endif

1
Sources/Plasma/NucleusLib/pnUtilsExe/CMakeLists.txt

@ -8,7 +8,6 @@ set(pnUtilsExe_HEADERS
set(pnUtilsExe_PRIVATE
Private/pnUteTime.cpp
Private/pnUteTls.cpp
)
if(WIN32)

110
Sources/Plasma/NucleusLib/pnUtilsExe/Private/pnUteTls.cpp

@ -1,110 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtilsExe/Private/pnUteTls.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
#if HS_BUILD_FOR_WIN32
/*****************************************************************************
*
* Private data
*
***/
static unsigned s_tlsNoBlock = kTlsInvalidValue;
/*****************************************************************************
*
* Local functions
*
***/
//============================================================================
static void ThreadCapsInitialize () {
ThreadLocalAlloc(&s_tlsNoBlock);
}
//============================================================================
static void ThreadCapsDestroy () {
if (s_tlsNoBlock != kTlsInvalidValue) {
ThreadLocalFree(s_tlsNoBlock);
s_tlsNoBlock = kTlsInvalidValue;
}
}
//============================================================================
AUTO_INIT_FUNC(InitThreadCaps) {
ThreadCapsInitialize();
atexit(ThreadCapsDestroy);
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void ThreadAllowBlock () {
ThreadLocalSetValue(s_tlsNoBlock, (void *) false);
}
//============================================================================
void ThreadDenyBlock () {
ThreadLocalSetValue(s_tlsNoBlock, (void *) true);
}
//============================================================================
void ThreadAssertCanBlock (const char file[], int line) {
if (ThreadLocalGetValue(s_tlsNoBlock))
ErrorAssert(line, file, "This thread may not block");
}
#endif

72
Sources/Plasma/PubUtilLib/plNetClient/plNetLinkingMgr.cpp

@ -44,6 +44,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "plNetCliAgeJoiner.h"
#include "plNetCliAgeLeaver.h"
#include <list>
#include "plNetTransport/plNetTransportMember.h" // OfferLinkToPlayer()
#include "plgDispatch.h"
@ -70,8 +72,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*
***/
struct NlmOpNode;
enum ENlmOp {
kNlmOpNoOp,
kNlmOpWaitOp,
@ -82,7 +82,6 @@ enum ENlmOp {
struct NlmOp {
ENlmOp opcode;
NlmOpNode * node;
NlmOp (const ENlmOp & op)
: opcode(op)
{ }
@ -114,12 +113,6 @@ struct NlmLeaveAgeOp : NlmOp {
{ }
};
struct NlmOpNode {
LINK(NlmOpNode) link;
NlmOp * op;
~NlmOpNode () { delete op; }
};
/*****************************************************************************
*
@ -129,7 +122,7 @@ struct NlmOpNode {
static plNCAgeJoiner * s_ageJoiner;
static plNCAgeLeaver * s_ageLeaver;
static LISTDECL(NlmOpNode, link) s_oplist;
static std::list<NlmOp*> s_opqueue;
/*****************************************************************************
@ -140,10 +133,11 @@ static LISTDECL(NlmOpNode, link) s_oplist;
//============================================================================
static void QueueOp (NlmOp * op, bool front = false) {
NlmOpNode * node = NEWZERO(NlmOpNode);
node->op = op;
op->node = node;
s_oplist.Link(node, front ? kListHead : kListTail);
if (front) {
s_opqueue.push_front(op);
} else {
s_opqueue.push_back(op);
}
}
@ -184,8 +178,10 @@ void plNetLinkingMgr::NCAgeJoinerCallback (
lm->SetEnabled(true);
// Pull our wait op off exec queue
if (NlmOpWaitOp * waitOp = (NlmOpWaitOp *) userState)
delete waitOp->node;
if (NlmOpWaitOp * waitOp = (NlmOpWaitOp *) userState) {
s_opqueue.remove(waitOp);
delete waitOp;
}
}
break;
@ -206,8 +202,10 @@ void plNetLinkingMgr::NCAgeLeaverCallback (
s_ageLeaver = nil;
// Pull our wait op off exec queue
if (NlmOpWaitOp * waitOp = (NlmOpWaitOp *) userState)
delete waitOp->node;
if (NlmOpWaitOp * waitOp = (NlmOpWaitOp *) userState) {
s_opqueue.remove(waitOp);
delete waitOp;
}
}
break;
@ -219,28 +217,27 @@ void plNetLinkingMgr::NCAgeLeaverCallback (
void plNetLinkingMgr::ExecNextOp () {
plNetLinkingMgr * lm = plNetLinkingMgr::GetInstance();
NlmOpNode * opNode = s_oplist.Head();
if (!opNode)
if (!s_opqueue.size())
return;
switch (opNode->op->opcode) {
case kNlmOpNoOp: {
}
break;
case kNlmOpWaitOp: {
}
return; // don't allow wait op to be unlinked/deleted from list
NlmOp* op = s_opqueue.front();
switch (op->opcode) {
case kNlmOpNoOp:
break;
case kNlmOpWaitOp:
return; // don't allow wait op to be unlinked/deleted from list
case kNlmOpJoinAgeOp: {
ASSERT(!s_ageJoiner);
ASSERT(!s_ageLeaver);
// Insert a wait operation into the exec queue
NlmOpWaitOp * waitOp = NEWZERO(NlmOpWaitOp);
QueueOp(waitOp, true);
NlmJoinAgeOp * joinAgeOp = (NlmJoinAgeOp *) opNode->op;
NlmJoinAgeOp * joinAgeOp = (NlmJoinAgeOp *)op;
NCAgeJoinerCreate(
&s_ageJoiner,
joinAgeOp->age,
@ -249,7 +246,7 @@ void plNetLinkingMgr::ExecNextOp () {
);
}
break;
case kNlmOpLeaveAgeOp: {
ASSERT(!s_ageJoiner);
ASSERT(!s_ageLeaver);
@ -261,7 +258,7 @@ void plNetLinkingMgr::ExecNextOp () {
lm->SetEnabled(false);
lm->fLinkedIn = false;
NlmLeaveAgeOp * leaveAgeOp = (NlmLeaveAgeOp *) opNode->op;
NlmLeaveAgeOp * leaveAgeOp = (NlmLeaveAgeOp *)op;
NCAgeLeaverCreate(
&s_ageLeaver,
leaveAgeOp->quitting,
@ -271,8 +268,9 @@ void plNetLinkingMgr::ExecNextOp () {
}
break;
}
delete opNode;
s_opqueue.remove(op);
delete op;
}

31
Sources/Plasma/PubUtilLib/plNetClientComm/plNetClientComm.cpp

@ -110,11 +110,11 @@ static bool s_loginComplete = false;
static bool s_hasAuthSrvIpAddress = false;
static bool s_hasFileSrvIpAddress = false;
static ENetError s_authResult = kNetErrAuthenticationFailed;
static wchar_t s_authSrvAddr[256];
static wchar_t s_fileSrvAddr[256];
static char s_authSrvAddr[256];
static char s_fileSrvAddr[256];
static wchar_t s_iniServerAddr[256];
static wchar_t s_iniFileServerAddr[256];
static char s_iniServerAddr[256];
static char s_iniFileServerAddr[256];
static wchar_t s_iniAccountUsername[kMaxAccountNameLength];
static ShaDigest s_namePassHash;
static wchar_t s_iniAuthToken[kMaxPublisherAuthKeyLength];
@ -591,23 +591,22 @@ static void INetCliAuthAgeRequestCallback (
unsigned ageMcpId,
unsigned ageVaultId,
const Uuid & ageInstId,
NetAddressNode gameAddr
plNetAddress gameAddr
) {
if (!IS_NET_ERROR(result) || result == kNetErrVaultNodeNotFound) {
s_age.ageInstId = ageInstId;
s_age.ageVaultId = ageVaultId;
wchar_t gameAddrStr[64];
wchar_t ageInstIdStr[64];
NetAddressNodeToString(gameAddr, gameAddrStr, arrsize(gameAddrStr));
plString gameAddrStr = gameAddr.GetHostString();
LogMsg(
kLogPerf,
L"Connecting to game server %s, ageInstId %s",
gameAddrStr,
gameAddrStr.c_str(),
GuidToString(ageInstId, ageInstIdStr, arrsize(ageInstIdStr))
);
NetCliGameDisconnect();
NetCliGameStartConnect(gameAddr);
NetCliGameStartConnect(gameAddr.GetHost());
NetCliGameJoinAgeRequest(
ageMcpId,
s_account.accountUuid,
@ -668,7 +667,7 @@ static void AuthSrvIpAddressCallback (
void * param,
const wchar_t addr[]
) {
StrCopy(s_authSrvAddr, addr, arrsize(s_authSrvAddr));
StrToAnsi(s_authSrvAddr, addr, arrsize(s_authSrvAddr));
s_hasAuthSrvIpAddress = true;
}
@ -678,7 +677,7 @@ static void FileSrvIpAddressCallback (
void * param,
const wchar_t addr[]
) {
StrCopy(s_fileSrvAddr, addr, arrsize(s_fileSrvAddr));
StrToAnsi(s_fileSrvAddr, addr, arrsize(s_fileSrvAddr));
s_hasFileSrvIpAddress = true;
}
@ -823,12 +822,12 @@ void NetCommUpdate () {
//============================================================================
void NetCommConnect () {
const wchar_t ** addrs;
const char** addrs;
unsigned count;
hsBool connectedToKeeper = false;
// if a console override was specified for a authserv, connect directly to the authserver rather than going through the gatekeeper
if((count = GetAuthSrvHostnames(&addrs)) && wcslen(addrs[0]))
if((count = GetAuthSrvHostnames(&addrs)) && strlen(addrs[0]))
{
NetCliAuthStartConnect(addrs, count);
}
@ -846,7 +845,7 @@ void NetCommConnect () {
AsyncSleep(10);
}
const wchar_t * authSrv[] = {
const char* authSrv[] = {
s_authSrvAddr
};
NetCliAuthStartConnect(authSrv, 1);
@ -855,7 +854,7 @@ void NetCommConnect () {
if (!gDataServerLocal) {
// if a console override was specified for a filesrv, connect directly to the fileserver rather than going through the gatekeeper
if((count = GetFileSrvHostnames(&addrs)) && wcslen(addrs[0]))
if((count = GetFileSrvHostnames(&addrs)) && strlen(addrs[0]))
{
NetCliFileStartConnect(addrs, count);
}
@ -875,7 +874,7 @@ void NetCommConnect () {
AsyncSleep(10);
}
const wchar_t * fileSrv[] = {
const char* fileSrv[] = {
s_fileSrvAddr
};
NetCliFileStartConnect(fileSrv, 1);

1
Sources/Plasma/PubUtilLib/plNetGameLib/Pch.h

@ -51,6 +51,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#define PLASMA20_SOURCES_PLASMA_PUBUTILLIB_PLNETGAMELIB_PCH_H
#include "pnUtils/pnUtils.h"
#include "pnEncryption/plBigNum.h"
#include "pnNetBase/pnNetBase.h"
#include "pnAsyncCore/pnAsyncCore.h"
#include "pnNetCli/pnNetCli.h"

51
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglAuth.cpp

@ -90,8 +90,8 @@ struct CliAuConn : AtomicRef {
LINK(CliAuConn) link;
AsyncSocket sock;
NetCli * cli;
wchar_t name[MAX_PATH];
NetAddress addr;
char name[MAX_PATH];
plNetAddress addr;
Uuid token;
unsigned seq;
unsigned serverChallenge;
@ -197,7 +197,7 @@ struct AgeRequestTrans : NetAuthTrans {
unsigned m_ageMcpId;
Uuid m_ageInstId;
unsigned m_ageVaultId;
NetAddressNode m_gameSrvNode;
uint32_t m_gameSrvNode;
AgeRequestTrans (
const wchar_t ageName[],
@ -1527,8 +1527,8 @@ static void Connect (
//============================================================================
static void Connect (
const wchar_t name[],
const NetAddress & addr
const char name[],
const plNetAddress& addr
) {
ASSERT(s_running);
@ -1536,7 +1536,7 @@ static void Connect (
conn->addr = addr;
conn->seq = ConnNextSequence();
conn->lastHeardTimeMs = GetNonZeroTimeMs(); // used in connect timeout, and ping timeout
StrCopy(conn->name, name, arrsize(conn->name));
strncpy(conn->name, name, arrsize(conn->name));
conn->IncRef("Lifetime");
conn->AutoReconnect();
@ -1545,9 +1545,9 @@ static void Connect (
//============================================================================
static void AsyncLookupCallback (
void * param,
const wchar_t name[],
const char name[],
unsigned addrCount,
const NetAddress addrs[]
const plNetAddress addrs[]
) {
if (!addrCount) {
ReportNetError(kNetProtocolCli2Auth, kNetErrNameLookupFailed);
@ -2194,18 +2194,11 @@ static bool Recv_ServerAddr (
{
if (s_active) {
s_active->token = msg.token;
NetAddressFromNode(
msg.srvAddr,
NetAddressGetPort(s_active->addr),
&s_active->addr
);
wchar_t addrStr[64];
NetAddressNodeToString(
msg.srvAddr,
addrStr,
arrsize(addrStr)
);
LogMsg(kLogPerf, L"SrvAuth addr: %s", addrStr);
s_active->addr.SetHost(msg.srvAddr);
plString logmsg = _TEMP_CONVERT_FROM_LITERAL("SrvAuth addr: ");
logmsg += s_active->addr.GetHostString();
LogMsg(kLogPerf, L"SrvAuth addr: %s", logmsg.c_str());
}
}
s_critsect.Leave();
@ -2760,13 +2753,16 @@ bool AgeRequestTrans::Send () {
//============================================================================
void AgeRequestTrans::Post () {
plNetAddress addr;
addr.SetHost(htonl(m_gameSrvNode));
m_callback(
m_result,
m_param,
m_ageMcpId,
m_ageVaultId,
m_ageInstId,
m_gameSrvNode
addr
);
}
@ -5032,8 +5028,8 @@ void AuthInitialize () {
s_send, arrsize(s_send),
s_recv, arrsize(s_recv),
kAuthDhGValue,
BigNum(sizeof(kAuthDhXData), kAuthDhXData),
BigNum(sizeof(kAuthDhNData), kAuthDhNData)
plBigNum(sizeof(kAuthDhXData), kAuthDhXData),
plBigNum(sizeof(kAuthDhNData), kAuthDhNData)
);
}
@ -5125,8 +5121,8 @@ void AuthPingEnable (bool enable) {
//============================================================================
void NetCliAuthStartConnect (
const wchar_t * authAddrList[],
unsigned authAddrCount
const char* authAddrList[],
uint32_t authAddrCount
) {
// TEMP: Only connect to one auth server until we fill out this module
// to choose the "best" auth connection.
@ -5134,7 +5130,7 @@ void NetCliAuthStartConnect (
for (unsigned i = 0; i < authAddrCount; ++i) {
// Do we need to lookup the address?
const wchar_t * name = authAddrList[i];
const char* name = authAddrList[i];
while (unsigned ch = *name) {
++name;
if (!(isdigit(ch) || ch == L'.' || ch == L':')) {
@ -5150,8 +5146,7 @@ void NetCliAuthStartConnect (
}
}
if (!name[0]) {
NetAddress addr;
NetAddressFromString(&addr, authAddrList[i], kNetDefaultClientPort);
plNetAddress addr(authAddrList[i], kNetDefaultClientPort);
Connect(authAddrList[i], addr);
}
}

7
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglAuth.h

@ -50,6 +50,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#endif
#define PLASMA20_SOURCES_PLASMA_PUBUTILLIB_PLNETGAMELIB_PRIVATE_PLNGLAUTH_H
#include "pnNetCommon/plNetAddress.h"
/*****************************************************************************
*
@ -61,8 +62,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// Connect
//============================================================================
void NetCliAuthStartConnect (
const wchar_t * authAddrList[],
unsigned authAddrCount
const char* authAddrList[],
uint32_t authAddrCount
);
bool NetCliAuthQueryConnected ();
void NetCliAuthAutoReconnectEnable (bool enable); // is enabled by default
@ -326,7 +327,7 @@ typedef void (*FNetCliAuthAgeRequestCallback)(
unsigned ageMcpId,
unsigned ageVaultId,
const Uuid & ageInstId,
NetAddressNode gameAddr
plNetAddress gameAddr
);
void NetCliAuthAgeRequest (
const wchar_t ageName[], // L"Teledahn"

23
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglCsr.cpp

@ -73,7 +73,7 @@ struct CliCsConn : AtomicRef {
AsyncSocket sock;
AsyncCancelId cancelId;
NetCli * cli;
NetAddress addr;
plNetAddress addr;
unsigned seq;
bool abandoned;
unsigned serverChallenge;
@ -369,7 +369,7 @@ static bool SocketNotifyCallback (
//============================================================================
static void Connect (
const NetAddress & addr,
const plNetAddress& addr,
ConnectParam * cp
) {
CliCsConn * conn = NEWZERO(CliCsConn);
@ -413,9 +413,9 @@ static void Connect (
//============================================================================
static void AsyncLookupCallback (
void * param,
const wchar_t name[],
const char name[],
unsigned addrCount,
const NetAddress addrs[]
const plNetAddress addrs[]
) {
if (!addrCount) {
ReportNetError(kNetProtocolCli2Auth, kNetErrNameLookupFailed);
@ -758,8 +758,8 @@ void CsrInitialize () {
s_send, arrsize(s_send),
s_recv, arrsize(s_recv),
kCsrDhGValue,
BigNum(sizeof(kCsrDhXData), kCsrDhXData),
BigNum(sizeof(kCsrDhNData), kCsrDhNData)
plBigNum(sizeof(kCsrDhXData), kCsrDhXData),
plBigNum(sizeof(kCsrDhNData), kCsrDhNData)
);
}
@ -830,8 +830,8 @@ unsigned CsrGetConnId () {
//============================================================================
void NetCliCsrStartConnect (
const wchar_t * addrList[],
unsigned addrCount,
const char* addrList[],
uint32_t addrCount,
FNetCliCsrConnectedCallback callback,
void * param
) {
@ -840,7 +840,7 @@ void NetCliCsrStartConnect (
for (unsigned i = 0; i < addrCount; ++i) {
// Do we need to lookup the address?
const wchar_t * name = addrList[i];
const char* name = addrList[i];
while (unsigned ch = *name) {
++name;
if (!(isdigit(ch) || ch == L'.' || ch == L':')) {
@ -860,9 +860,8 @@ void NetCliCsrStartConnect (
}
}
if (!name[0]) {
NetAddress addr;
NetAddressFromString(&addr, addrList[i], kNetDefaultClientPort);
plNetAddress addr(addrList[i], kNetDefaultClientPort);
ConnectParam * cp = new ConnectParam;
cp->callback = callback;
cp->param = param;

4
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglCsr.h

@ -62,8 +62,8 @@ typedef void (*FNetCliCsrConnectedCallback) (
unsigned latestBuildId
);
void NetCliCsrStartConnect (
const wchar_t * addrList[],
unsigned addrCount,
const char* addrList[],
uint32_t addrCount,
FNetCliCsrConnectedCallback callback = nil,
void * param = nil
);

32
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglFile.cpp

@ -64,8 +64,8 @@ struct CliFileConn : AtomicRef {
LINK(CliFileConn) link;
CLock sockLock; // to protect the socket pointer so we don't nuke it while using it
AsyncSocket sock;
wchar_t name[MAX_PATH];
NetAddress addr;
char name[MAX_PATH];
plNetAddress addr;
unsigned seq;
ARRAY(uint8_t) recvBuffer;
AsyncCancelId cancelId;
@ -539,13 +539,13 @@ static void Connect (CliFileConn * conn) {
//============================================================================
static void Connect (
const wchar_t name[],
const NetAddress & addr
const char name[],
const plNetAddress& addr
) {
ASSERT(s_running);
CliFileConn * conn = NEWZERO(CliFileConn);
StrCopy(conn->name, name, arrsize(conn->name));
strncpy(conn->name, name, arrsize(conn->name));
conn->addr = addr;
conn->buildId = s_connectBuildId;
conn->serverType = s_serverType;
@ -559,9 +559,9 @@ static void Connect (
//============================================================================
static void AsyncLookupCallback (
void * param,
const wchar_t name[],
const char name[],
unsigned addrCount,
const NetAddress addrs[]
const plNetAddress addrs[]
) {
if (!addrCount) {
ReportNetError(kNetProtocolCli2File, kNetErrNameLookupFailed);
@ -1334,8 +1334,8 @@ unsigned FileGetConnId () {
//============================================================================
void NetCliFileStartConnect (
const wchar_t * fileAddrList[],
unsigned fileAddrCount,
const char* fileAddrList[],
uint32_t fileAddrCount,
bool isPatcher /* = false */
) {
// TEMP: Only connect to one file server until we fill out this module
@ -1346,7 +1346,7 @@ void NetCliFileStartConnect (
for (unsigned i = 0; i < fileAddrCount; ++i) {
// Do we need to lookup the address?
const wchar_t * name = fileAddrList[i];
const char* name = fileAddrList[i];
while (unsigned ch = *name) {
++name;
if (!(isdigit(ch) || ch == L'.' || ch == L':')) {
@ -1362,8 +1362,7 @@ void NetCliFileStartConnect (
}
}
if (!name[0]) {
NetAddress addr;
NetAddressFromString(&addr, fileAddrList[i], kNetDefaultClientPort);
plNetAddress addr(fileAddrList[i], kNetDefaultClientPort);
Connect(fileAddrList[i], addr);
}
}
@ -1371,8 +1370,8 @@ void NetCliFileStartConnect (
//============================================================================
void NetCliFileStartConnectAsServer (
const wchar_t * fileAddrList[],
unsigned fileAddrCount,
const char* fileAddrList[],
uint32_t fileAddrCount,
unsigned serverType,
unsigned serverBuildId
) {
@ -1384,7 +1383,7 @@ void NetCliFileStartConnectAsServer (
for (unsigned i = 0; i < fileAddrCount; ++i) {
// Do we need to lookup the address?
const wchar_t * name = fileAddrList[i];
const char* name = fileAddrList[i];
while (unsigned ch = *name) {
++name;
if (!(isdigit(ch) || ch == L'.' || ch == L':')) {
@ -1400,8 +1399,7 @@ void NetCliFileStartConnectAsServer (
}
}
if (!name[0]) {
NetAddress addr;
NetAddressFromString(&addr, fileAddrList[i], kNetDefaultServerPort);
plNetAddress addr(fileAddrList[i], kNetDefaultServerPort);
Connect(fileAddrList[i], addr);
}
}

4
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglFile.h

@ -62,12 +62,12 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// Connect
//============================================================================
void NetCliFileStartConnect (
const wchar_t * fileAddrList[],
const char* fileAddrList[],
unsigned fileAddrCount,
bool isPatcher = false
);
void NetCliFileStartConnectAsServer (
const wchar_t * fileAddrList[],
const char* fileAddrList[],
unsigned fileAddrCount,
unsigned serverType,
unsigned serverBuildId

13
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGame.cpp

@ -62,7 +62,7 @@ struct CliGmConn : AtomicRef {
AsyncSocket sock;
AsyncCancelId cancelId;
NetCli * cli;
NetAddress addr;
plNetAddress addr;
unsigned seq;
bool abandoned;
@ -354,7 +354,7 @@ static bool SocketNotifyCallback (
//============================================================================
static void Connect (
const NetAddress & addr
const plNetAddress& addr
) {
CliGmConn * conn = NEWZERO(CliGmConn);
conn->addr = addr;
@ -711,8 +711,8 @@ void GameInitialize () {
s_send, arrsize(s_send),
s_recv, arrsize(s_recv),
kGameDhGValue,
BigNum(sizeof(kGameDhXData), kGameDhXData),
BigNum(sizeof(kGameDhNData), kGameDhNData)
plBigNum(sizeof(kGameDhXData), kGameDhXData),
plBigNum(sizeof(kGameDhNData), kGameDhNData)
);
}
@ -796,10 +796,9 @@ void GamePingEnable (bool enable) {
//============================================================================
void NetCliGameStartConnect (
const NetAddressNode & node
const uint32_t node
) {
NetAddress addr;
NetAddressFromNode(node, kNetDefaultClientPort, &addr);
plNetAddress addr(node, kNetDefaultClientPort);
Connect(addr);
}

2
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGame.h

@ -61,7 +61,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// Connect
//============================================================================
void NetCliGameStartConnect (
const NetAddressNode & node
const uint32_t node
);
//============================================================================

27
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGateKeeper.cpp

@ -89,8 +89,8 @@ struct CliGkConn : AtomicRef {
LINK(CliGkConn) link;
AsyncSocket sock;
NetCli * cli;
wchar_t name[MAX_PATH];
NetAddress addr;
char name[MAX_PATH];
plNetAddress addr;
Uuid token;
unsigned seq;
unsigned serverChallenge;
@ -463,8 +463,8 @@ static void Connect (
//============================================================================
static void Connect (
const wchar_t name[],
const NetAddress & addr
const char name[],
const plNetAddress& addr
) {
ASSERT(s_running);
@ -472,7 +472,7 @@ static void Connect (
conn->addr = addr;
conn->seq = ConnNextSequence();
conn->lastHeardTimeMs = GetNonZeroTimeMs(); // used in connect timeout, and ping timeout
StrCopy(conn->name, name, arrsize(conn->name));
strncpy(conn->name, name, arrsize(conn->name));
conn->IncRef("Lifetime");
conn->AutoReconnect();
@ -481,9 +481,9 @@ static void Connect (
//============================================================================
static void AsyncLookupCallback (
void * param,
const wchar_t name[],
const char name[],
unsigned addrCount,
const NetAddress addrs[]
const plNetAddress addrs[]
) {
if (!addrCount) {
ReportNetError(kNetProtocolCli2GateKeeper, kNetErrNameLookupFailed);
@ -984,8 +984,8 @@ void GateKeeperInitialize () {
s_send, arrsize(s_send),
s_recv, arrsize(s_recv),
kGateKeeperDhGValue,
BigNum(sizeof(kGateKeeperDhXData), kGateKeeperDhXData),
BigNum(sizeof(kGateKeeperDhNData), kGateKeeperDhNData)
plBigNum(sizeof(kGateKeeperDhXData), kGateKeeperDhXData),
plBigNum(sizeof(kGateKeeperDhNData), kGateKeeperDhNData)
);
}
@ -1053,14 +1053,14 @@ unsigned GateKeeperGetConnId () {
//============================================================================
void NetCliGateKeeperStartConnect (
const wchar_t * gateKeeperAddrList[],
unsigned gateKeeperAddrCount
const char* gateKeeperAddrList[],
uint32_t gateKeeperAddrCount
) {
gateKeeperAddrCount = min(gateKeeperAddrCount, 1);
for (unsigned i = 0; i < gateKeeperAddrCount; ++i) {
// Do we need to lookup the address?
const wchar_t * name = gateKeeperAddrList[i];
const char* name = gateKeeperAddrList[i];
while (unsigned ch = *name) {
++name;
if (!(isdigit(ch) || ch == L'.' || ch == L':')) {
@ -1076,8 +1076,7 @@ void NetCliGateKeeperStartConnect (
}
}
if (!name[0]) {
NetAddress addr;
NetAddressFromString(&addr, gateKeeperAddrList[i], kNetDefaultClientPort);
plNetAddress addr(gateKeeperAddrList[i], kNetDefaultClientPort);
Connect(gateKeeperAddrList[i], addr);
}
}

4
Sources/Plasma/PubUtilLib/plNetGameLib/Private/plNglGateKeeper.h

@ -62,8 +62,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// Connect
//============================================================================
void NetCliGateKeeperStartConnect (
const wchar_t * gateKeeperAddrList[],
unsigned gateKeeperAddrCount
const char* gateKeeperAddrList[],
uint32_t gateKeeperAddrCount
);
bool NetCliGateKeeperQueryConnected ();

Loading…
Cancel
Save