1
0

sprintf() begone! Replaced with StringUtils' Printf()

git-svn-id: http://mc-server.googlecode.com/svn/trunk@216 0a769ca7-a7f5-676a-18bf-c427514a06d6
This commit is contained in:
madmaxoft@gmail.com 2012-02-01 13:43:47 +00:00
parent d3614be2e0
commit 2568bad3cc
18 changed files with 429 additions and 292 deletions

View File

@ -38,11 +38,13 @@ using namespace std;
#endif #endif
#ifndef _WIN32 #ifndef _WIN32
#define sprintf_s(buffer, buffer_size, stringbuffer, ...) (sprintf(buffer, stringbuffer, __VA_ARGS__))
#define vsprintf_s(buffer, stringbuffer, ...) (vsprintf(buffer, stringbuffer, __VA_ARGS__))
#define sscanf_s(buffer, stringbuffer, ...) (sscanf(buffer, stringbuffer, __VA_ARGS__)) #define sscanf_s(buffer, stringbuffer, ...) (sscanf(buffer, stringbuffer, __VA_ARGS__))
#endif #endif
cIniFile::cIniFile( const string iniPath) cIniFile::cIniFile( const string iniPath)
{ {
Path( iniPath); Path( iniPath);
@ -115,6 +117,10 @@ bool cIniFile::ReadFile()
return false; return false;
} }
bool cIniFile::WriteFile() bool cIniFile::WriteFile()
{ {
unsigned commentID, keyID, valueID; unsigned commentID, keyID, valueID;
@ -148,6 +154,10 @@ bool cIniFile::WriteFile()
return true; return true;
} }
long cIniFile::FindKey( const string & keyname) const long cIniFile::FindKey( const string & keyname) const
{ {
for ( unsigned keyID = 0; keyID < names.size(); ++keyID) for ( unsigned keyID = 0; keyID < names.size(); ++keyID)
@ -156,6 +166,10 @@ long cIniFile::FindKey( const string & keyname) const
return noID; return noID;
} }
long cIniFile::FindValue( unsigned const keyID, const string & valuename) const long cIniFile::FindValue( unsigned const keyID, const string & valuename) const
{ {
if ( !keys.size() || keyID >= keys.size()) if ( !keys.size() || keyID >= keys.size())
@ -167,6 +181,10 @@ long cIniFile::FindValue( unsigned const keyID, const string & valuename) const
return noID; return noID;
} }
unsigned cIniFile::AddKeyName( const string & keyname) unsigned cIniFile::AddKeyName( const string & keyname)
{ {
names.resize( names.size() + 1, keyname); names.resize( names.size() + 1, keyname);
@ -174,6 +192,10 @@ unsigned cIniFile::AddKeyName( const string & keyname)
return names.size() - 1; return names.size() - 1;
} }
string cIniFile::KeyName( unsigned const keyID) const string cIniFile::KeyName( unsigned const keyID) const
{ {
if ( keyID < names.size()) if ( keyID < names.size())
@ -182,6 +204,10 @@ string cIniFile::KeyName( unsigned const keyID) const
return ""; return "";
} }
unsigned cIniFile::NumValues( unsigned const keyID) unsigned cIniFile::NumValues( unsigned const keyID)
{ {
if ( keyID < keys.size()) if ( keyID < keys.size())
@ -189,6 +215,10 @@ unsigned cIniFile::NumValues( unsigned const keyID)
return 0; return 0;
} }
unsigned cIniFile::NumValues( const string & keyname) unsigned cIniFile::NumValues( const string & keyname)
{ {
long keyID = FindKey( keyname); long keyID = FindKey( keyname);
@ -197,6 +227,10 @@ unsigned cIniFile::NumValues( const string & keyname)
return keys[keyID].names.size(); return keys[keyID].names.size();
} }
string cIniFile::ValueName( unsigned const keyID, unsigned const valueID) const string cIniFile::ValueName( unsigned const keyID, unsigned const valueID) const
{ {
if ( keyID < keys.size() && valueID < keys[keyID].names.size()) if ( keyID < keys.size() && valueID < keys[keyID].names.size())
@ -204,6 +238,10 @@ string cIniFile::ValueName( unsigned const keyID, unsigned const valueID) const
return ""; return "";
} }
string cIniFile::ValueName( const string & keyname, unsigned const valueID) const string cIniFile::ValueName( const string & keyname, unsigned const valueID) const
{ {
long keyID = FindKey( keyname); long keyID = FindKey( keyname);
@ -212,6 +250,10 @@ string cIniFile::ValueName( const string & keyname, unsigned const valueID) cons
return ValueName( keyID, valueID); return ValueName( keyID, valueID);
} }
bool cIniFile::SetValue( unsigned const keyID, unsigned const valueID, const string & value) bool cIniFile::SetValue( unsigned const keyID, unsigned const valueID, const string & value)
{ {
if ( keyID < keys.size() && valueID < keys[keyID].names.size()) if ( keyID < keys.size() && valueID < keys[keyID].names.size())
@ -220,6 +262,10 @@ bool cIniFile::SetValue( unsigned const keyID, unsigned const valueID, const str
return false; return false;
} }
bool cIniFile::SetValue( const string & keyname, const string & valuename, const string & value, bool const create) bool cIniFile::SetValue( const string & keyname, const string & valuename, const string & value, bool const create)
{ {
long keyID = FindKey( keyname); long keyID = FindKey( keyname);
@ -250,33 +296,48 @@ bool cIniFile::SetValue( const string & keyname, const string & valuename, const
return true; return true;
} }
bool cIniFile::SetValueI( const string & keyname, const string & valuename, int const value, bool const create) bool cIniFile::SetValueI( const string & keyname, const string & valuename, int const value, bool const create)
{ {
char svalue[MAX_VALUEDATA]; AString Data;
Printf(Data, "%d", value);
sprintf_s( svalue, MAX_VALUEDATA, "%d", value); return SetValue( keyname, valuename, Data, create);
return SetValue( keyname, valuename, svalue, create);
} }
bool cIniFile::SetValueF( const string & keyname, const string & valuename, double const value, bool const create) bool cIniFile::SetValueF( const string & keyname, const string & valuename, double const value, bool const create)
{ {
char svalue[MAX_VALUEDATA]; AString Data;
Printf(Data, "%f", value);
sprintf_s( svalue, MAX_VALUEDATA, "%f", value); return SetValue( keyname, valuename, Data, create);
return SetValue( keyname, valuename, svalue, create);
} }
bool cIniFile::SetValueV( const string & keyname, const string & valuename, char *format, ...) bool cIniFile::SetValueV( const string & keyname, const string & valuename, char *format, ...)
{ {
va_list args; va_list args;
char value[MAX_VALUEDATA];
va_start( args, format); va_start( args, format);
vsprintf_s( value, format, args);
AString Data;
AppendVPrintf(Data, format, args);
va_end( args); va_end( args);
return SetValue( keyname, valuename, value ); return SetValue( keyname, valuename, Data);
} }
string cIniFile::GetValue( unsigned const keyID, unsigned const valueID, const string & defValue) const string cIniFile::GetValue( unsigned const keyID, unsigned const valueID, const string & defValue) const
{ {
if ( keyID < keys.size() && valueID < keys[keyID].names.size()) if ( keyID < keys.size() && valueID < keys[keyID].names.size())
@ -284,6 +345,10 @@ string cIniFile::GetValue( unsigned const keyID, unsigned const valueID, const s
return defValue; return defValue;
} }
string cIniFile::GetValue( const string & keyname, const string & valuename, const string & defValue) const string cIniFile::GetValue( const string & keyname, const string & valuename, const string & defValue) const
{ {
long keyID = FindKey( keyname); long keyID = FindKey( keyname);
@ -297,22 +362,32 @@ string cIniFile::GetValue( const string & keyname, const string & valuename, con
return keys[keyID].values[valueID]; return keys[keyID].values[valueID];
} }
int cIniFile::GetValueI(const string & keyname, const string & valuename, int const defValue) const int cIniFile::GetValueI(const string & keyname, const string & valuename, int const defValue) const
{ {
char svalue[MAX_VALUEDATA]; AString Data;
Printf(Data, "%d", defValue);
sprintf_s( svalue, MAX_VALUEDATA, "%d", defValue); return atoi( GetValue( keyname, valuename, Data).c_str());
return atoi( GetValue( keyname, valuename, svalue).c_str());
} }
double cIniFile::GetValueF(const string & keyname, const string & valuename, double const defValue) const double cIniFile::GetValueF(const string & keyname, const string & valuename, double const defValue) const
{ {
char svalue[MAX_VALUEDATA]; AString Data;
Printf(Data, "%f", defValue);
sprintf_s( svalue, MAX_VALUEDATA, "%f", defValue); return atof( GetValue( keyname, valuename, Data).c_str());
return atof( GetValue( keyname, valuename, svalue).c_str());
} }
// 16 variables may be a bit of over kill, but hey, it's only code. // 16 variables may be a bit of over kill, but hey, it's only code.
unsigned cIniFile::GetValueV( const string & keyname, const string & valuename, char *format, unsigned cIniFile::GetValueV( const string & keyname, const string & valuename, char *format,
void *v1, void *v2, void *v3, void *v4, void *v1, void *v2, void *v3, void *v4,
@ -342,6 +417,10 @@ unsigned cIniFile::GetValueV( const string & keyname, const string & valuename,
return nVals; return nVals;
} }
bool cIniFile::DeleteValueByID( const unsigned keyID, const unsigned valueID ) bool cIniFile::DeleteValueByID( const unsigned keyID, const unsigned valueID )
{ {
if ( keyID < keys.size() && valueID < keys[keyID].names.size()) if ( keyID < keys.size() && valueID < keys[keyID].names.size())

View File

@ -12,23 +12,24 @@
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/* /*
!! MODIFIED BY FAKETRUTH !! !! MODIFIED BY FAKETRUTH and madmaxoft!!
*/ */
#ifndef CIniFile_H #ifndef CIniFile_H
#define CIniFile_H #define CIniFile_H
// C++ Includes
#include <string>
#include <vector>
// C Includes
#include <stdlib.h>
#define MAX_KEYNAME 128 #define MAX_KEYNAME 128
#define MAX_VALUENAME 128 #define MAX_VALUENAME 128
#define MAX_VALUEDATA 2048 #define MAX_VALUEDATA 2048
class cIniFile //tolua_export class cIniFile //tolua_export
{ //tolua_export { //tolua_export
private: private:
@ -114,10 +115,12 @@ public:
return ( GetValueI( keyname, valuename, int( defValue)) > 0); return ( GetValueI( keyname, valuename, int( defValue)) > 0);
} //tolua_export } //tolua_export
double GetValueF( const std::string & keyname, const std::string & valuename, const double defValue = 0.0) const; //tolua_export double GetValueF( const std::string & keyname, const std::string & valuename, const double defValue = 0.0) const; //tolua_export
// This is a variable length formatted GetValue routine. All these voids // This is a variable length formatted GetValue routine. All these voids
// are required because there is no vsscanf() like there is a vsprintf(). // are required because there is no vsscanf() like there is a vsprintf().
// Only a maximum of 8 variable can be read. // Only a maximum of 8 variable can be read.
unsigned GetValueV( const std::string & keyname, const std::string & valuename, char *format, // NOTE: do not use this function, instead get the string value and parse it yourself
OBSOLETE unsigned GetValueV( const std::string & keyname, const std::string & valuename, char *format,
void *v1 = 0, void *v2 = 0, void *v3 = 0, void *v4 = 0, void *v1 = 0, void *v2 = 0, void *v3 = 0, void *v4 = 0,
void *v5 = 0, void *v6 = 0, void *v7 = 0, void *v8 = 0, void *v5 = 0, void *v6 = 0, void *v7 = 0, void *v8 = 0,
void *v9 = 0, void *v10 = 0, void *v11 = 0, void *v12 = 0, void *v9 = 0, void *v10 = 0, void *v11 = 0, void *v12 = 0,

View File

@ -80,11 +80,12 @@
/// Evaluates to the number of elements in an array (compile-time!) /// Evaluates to the number of elements in an array (compile-time!)
#define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X))) #define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X)))
// sprintf_s is the preferred call in MSVC ("secure"); make it *nix-compatible: #ifdef _MSC_VER
#ifndef _WIN32 #define OBSOLETE __declspec(deprecated)
#define sprintf_s(dst, size, format, ...) sprintf(dst, format, __VA_ARGS__ ) #else
#define vsnprintf_s(buffer, buffer_size, maxcount, stringbuffer, ...) (vsnprintf(buffer, maxcount, stringbuffer, __VA_ARGS__)) // TODO: how do other compilers mark functions as obsolete, so that their usage results in a compile-time warning?
#endif // _WIN32 #define OBSOLETE
#endif

View File

@ -899,8 +899,8 @@ cBlockEntity* cChunk::GetBlockEntity( int a_X, int a_Y, int a_Z )
/// Loads the chunk from the old-format disk file, erases the file afterwards. Returns true if successful /// Loads the chunk from the old-format disk file, erases the file afterwards. Returns true if successful
bool cChunk::LoadFromDisk() bool cChunk::LoadFromDisk()
{ {
char SourceFile[128]; AString SourceFile;
sprintf_s(SourceFile, ARRAYCOUNT(SourceFile), "world/X%i_Y%i_Z%i.bin", m_PosX, m_PosY, m_PosZ ); Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", m_PosX, m_PosY, m_PosZ );
cFile f; cFile f;
if (!f.Open(SourceFile, cFile::fmRead)) if (!f.Open(SourceFile, cFile::fmRead))
@ -974,7 +974,7 @@ bool cChunk::LoadFromDisk()
f.Close(); f.Close();
// Delete old format file // Delete old format file
if (std::remove(SourceFile) != 0) if (std::remove(SourceFile.c_str()) != 0)
{ {
LOGERROR("Could not delete file %s", SourceFile ); LOGERROR("Could not delete file %s", SourceFile );
} }

View File

@ -105,8 +105,8 @@ bool cChunkLoader::SaveChunk( const cChunk & a_Chunk )
cChunk* cChunkLoader::LoadOldFormat( int a_X, int a_Y, int a_Z ) cChunk* cChunkLoader::LoadOldFormat( int a_X, int a_Y, int a_Z )
{ {
char SourceFile[128]; AString SourceFile;
sprintf_s(SourceFile, 128, "world/X%i_Y%i_Z%i.bin", a_X, a_Y, a_Z ); Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", a_X, a_Y, a_Z );
FILE* f = 0; FILE* f = 0;
#ifdef _WIN32 #ifdef _WIN32
@ -181,8 +181,8 @@ cChunk* cChunkLoader::LoadOldFormat( int a_X, int a_Y, int a_Z )
bool cChunkLoader::SaveOldFormat( const cChunk & a_Chunk ) bool cChunkLoader::SaveOldFormat( const cChunk & a_Chunk )
{ {
char SourceFile[128]; AString SourceFile;
sprintf_s(SourceFile, 128, "world/X%i_Y%i_Z%i.bin", a_Chunk.m_PosX, a_Chunk.m_PosY, a_Chunk.m_PosZ ); Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", a_Chunk.m_PosX, a_Chunk.m_PosY, a_Chunk.m_PosZ );
#ifdef _WIN32 #ifdef _WIN32
{ {
@ -310,8 +310,8 @@ cChunk* cChunkLoader::LoadFormat1( int a_X, int a_Y, int a_Z )
cChunkLoader::ChunkPack* cChunkLoader::LoadPak1( int PakX, int PakY, int PakZ ) cChunkLoader::ChunkPack* cChunkLoader::LoadPak1( int PakX, int PakY, int PakZ )
{ {
char SourceFile[128]; AString SourceFile;
sprintf_s(SourceFile, 128, "world/X%i_Y%i_Z%i.pak", PakX, PakY, PakZ ); Printf(SourceFile, "world/X%i_Y%i_Z%i.pak", PakX, PakY, PakZ );
FILE* f = 0; FILE* f = 0;
#ifdef _WIN32 #ifdef _WIN32

View File

@ -455,9 +455,8 @@ void cChunkMap::SaveLayer( cChunkLayer* a_Layer )
std::string WorldName = m_World->GetName(); std::string WorldName = m_World->GetName();
cMakeDir::MakeDir( WorldName.c_str() ); cMakeDir::MakeDir( WorldName.c_str() );
char SourceFile[128]; AString SourceFile;
Printf(SourceFile, "%s/X%i_Z%i.pak", WorldName.c_str(), a_Layer->m_X, a_Layer->m_Z );
sprintf_s(SourceFile, ARRAYCOUNT(SourceFile), ( WorldName + "/X%i_Z%i.pak").c_str(), a_Layer->m_X, a_Layer->m_Z );
cFile f; cFile f;
if (!f.Open(SourceFile, cFile::fmWrite)) if (!f.Open(SourceFile, cFile::fmWrite))
@ -538,9 +537,9 @@ void cChunkMap::SaveLayer( cChunkLayer* a_Layer )
cChunkMap::cChunkLayer* cChunkMap::LoadLayer(int a_LayerX, int a_LayerZ ) cChunkMap::cChunkLayer* cChunkMap::LoadLayer(int a_LayerX, int a_LayerZ )
{ {
std::string WorldName = m_World->GetName(); std::string WorldName = m_World->GetName();
char SourceFile[128];
sprintf_s(SourceFile, ARRAYCOUNT(SourceFile), (WorldName + "/X%i_Z%i.pak").c_str(), a_LayerX, a_LayerZ ); AString SourceFile;
Printf(SourceFile, "%s/X%i_Z%i.pak", WorldName.c_str(), a_LayerX, a_LayerZ);
cFile f(SourceFile, cFile::fmRead); cFile f(SourceFile, cFile::fmRead);
if (!f.IsOpen()) if (!f.IsOpen())

View File

@ -507,11 +507,15 @@ void cClientHandle::HandlePacket( cPacket* a_Packet )
case E_PING: // Somebody tries to retrieve information about the server case E_PING: // Somebody tries to retrieve information about the server
{ {
LOGINFO("Got ping"); LOGINFO("Got ping");
char NumPlayers[8], cMaxPlayers[8]; AString Reply;
sprintf_s(NumPlayers, 8, "%i", cRoot::Get()->GetWorld()->GetNumPlayers()); Printf(Reply, "%s%s%i%s%i",
sprintf_s(cMaxPlayers, 8, "%i", cRoot::Get()->GetWorld()->GetMaxPlayers()); cRoot::Get()->GetWorld()->GetDescription().c_str(),
std::string response = std::string(cRoot::Get()->GetWorld()->GetDescription() + cChatColor::Delimiter + NumPlayers + cChatColor::Delimiter + cMaxPlayers ); cChatColor::Delimiter.c_str(),
Kick( response.c_str() ); cRoot::Get()->GetWorld()->GetNumPlayers(),
cChatColor::Delimiter.c_str(),
cRoot::Get()->GetWorld()->GetMaxPlayers()
);
Kick(Reply.c_str());
} }
break; break;
case E_HANDSHAKE: case E_HANDSHAKE:
@ -1659,9 +1663,9 @@ void cClientHandle::ReceiveThread( void *lpParam )
LOG("Unknown packet: 0x%02x \'%c\' %i", (unsigned char)temp, (unsigned char)temp, (unsigned char)temp ); LOG("Unknown packet: 0x%02x \'%c\' %i", (unsigned char)temp, (unsigned char)temp, (unsigned char)temp );
char c_Str[128]; AString Reason;
sprintf_s( c_Str, 128, "[C->S] Unknown PacketID: 0x%02x", (unsigned char)temp ); Printf(Reason, "[C->S] Unknown PacketID: 0x%02x", (unsigned char)temp );
cPacket_Disconnect DC(c_Str); cPacket_Disconnect DC(Reason);
DC.Send( socket ); DC.Send( socket );
cSleep::MilliSleep( 1000 ); // Give packet some time to be received cSleep::MilliSleep( 1000 ); // Give packet some time to be received

View File

@ -34,9 +34,9 @@ cEvent::cEvent(void)
delete m_Event; delete m_Event;
m_bIsNamed = true; m_bIsNamed = true;
char c_Str[64]; AString EventName;
sprintf(c_Str, "cEvent%p", this); Printf(EventName, "cEvent%p", this);
m_Event = sem_open( c_Str, O_CREAT, 777, 0 ); m_Event = sem_open(EventName.c_str(), O_CREAT, 777, 0 );
if (m_Event == SEM_FAILED) if (m_Event == SEM_FAILED)
{ {
LOGERROR("cEvent: Cannot create event, errno = %i. Aborting server.", errno); LOGERROR("cEvent: Cannot create event, errno = %i. Aborting server.", errno);

View File

@ -28,7 +28,7 @@ cFile::cFile(void) :
/// Constructs and opens / creates the file specified, use IsOpen() to check for success /// Constructs and opens / creates the file specified, use IsOpen() to check for success
cFile::cFile(const char * iFileName, EMode iMode) : cFile::cFile(const AString & iFileName, EMode iMode) :
#ifdef USE_STDIO_FILE #ifdef USE_STDIO_FILE
m_File(NULL) m_File(NULL)
#else #else
@ -55,7 +55,7 @@ cFile::~cFile()
bool cFile::Open(const char * iFileName, EMode iMode) bool cFile::Open(const AString & iFileName, EMode iMode)
{ {
assert(!IsOpen()); // You should close the file before opening another one assert(!IsOpen()); // You should close the file before opening another one
@ -76,7 +76,7 @@ bool cFile::Open(const char * iFileName, EMode iMode)
return false; return false;
} }
} }
m_File = fopen(iFileName, Mode); m_File = fopen(iFileName.c_str(), Mode);
return (m_File != NULL); return (m_File != NULL);
} }

View File

@ -58,12 +58,12 @@ public:
cFile(void); cFile(void);
/// Constructs and opens / creates the file specified, use IsOpen() to check for success /// Constructs and opens / creates the file specified, use IsOpen() to check for success
cFile(const char * iFileName, EMode iMode); cFile(const AString & iFileName, EMode iMode);
/// Auto-closes the file, if open /// Auto-closes the file, if open
~cFile(); ~cFile();
bool Open(const char * iFileName, EMode iMode); bool Open(const AString & iFileName, EMode iMode);
void Close(void); void Close(void);
bool IsOpen(void) const; bool IsOpen(void) const;
bool IsEOF(void) const; bool IsEOF(void) const;

View File

@ -19,10 +19,18 @@ cHeartBeat::cHeartBeat()
Authenticate(); Authenticate();
} }
cHeartBeat::~cHeartBeat() cHeartBeat::~cHeartBeat()
{ {
} }
void cHeartBeat::ReceivedData( char a_Data[256], int a_Size ) void cHeartBeat::ReceivedData( char a_Data[256], int a_Size )
{ {
if( a_Size < 0 ) // Disconnected if( a_Size < 0 ) // Disconnected
@ -97,28 +105,40 @@ void cHeartBeat::ReceivedData( char a_Data[256], int a_Size )
} while( bLoop ); } while( bLoop );
} }
void cHeartBeat::SendUpdate() void cHeartBeat::SendUpdate()
{ {
CloseSocket(); CloseSocket();
if( Connect( "mc-server.org", 80 ) ) if( Connect( "mc-server.org", 80 ) )
{ {
int Port = cRoot::Get()->GetServer()->GetPort(); int Port = cRoot::Get()->GetServer()->GetPort();
char c_Port[16]; AString Msg;
sprintf_s( c_Port, 16, "%i", Port ); AString sPort;
Printf(sPort, "%i", Port);
std::string sPort = std::string( c_Port ); AString sChecksum = md5( m_ServerID + sPort );
std::string sChecksum = md5( m_ServerID + sPort ); Printf(Msg, "GET http://master.mc-server.org/?update=%s&checksum=%s&port=%d\n", m_ServerID, sChecksum , Port);
SendMessage( (std::string("GET http://master.mc-server.org/?update=") + m_ServerID + std::string("&checksum=") + sChecksum + std::string("&port=") + sPort + "\n").c_str() ); SendMessage(Msg.c_str());
} }
} }
void cHeartBeat::Authenticate() void cHeartBeat::Authenticate()
{ {
CloseSocket(); CloseSocket();
if( Connect( "mc-server.org", 80 ) ) if (Connect( "mc-server.org", 80))
{ {
m_State = 1; m_State = 1;
int RetVal = SendMessage( "GET http://master.mc-server.org/\r\n\r\n"); int RetVal = SendMessage( "GET http://master.mc-server.org/\r\n\r\n");
LOGINFO("Returned %i", RetVal ); LOGINFO("Returned %i", RetVal);
} }
} }

View File

@ -13,7 +13,7 @@
// When in MSVC, the debugger provides "thread naming" by catching special exceptions. Interface here: // When in MSVC, the debugger provides "thread naming" by catching special exceptions. Interface here:
#ifdef _MSC_VER #if defined(_MSC_VER) && defined(_DEBUG)
// //
// Usage: SetThreadName (-1, "MainThread"); // Usage: SetThreadName (-1, "MainThread");
// //
@ -41,7 +41,7 @@ static void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName)
{ {
} }
} }
#endif // _MSC_VER #endif // _MSC_VER && _DEBUG

View File

@ -6,6 +6,7 @@
#include <fstream> #include <fstream>
#include <ctime> #include <ctime>
#include <stdarg.h> #include <stdarg.h>
#include "cMakeDir.h"
@ -13,35 +14,31 @@
cLog* cLog::s_Log = NULL; cLog* cLog::s_Log = NULL;
cLog::cLog( const char* a_FileName ) cLog::cLog(const AString & a_FileName )
: m_File(NULL) : m_File(NULL)
{ {
s_Log = this; s_Log = this;
// create logs directory // create logs directory
#ifdef _WIN32 cMakeDir::MakeDir("logs");
{
SECURITY_ATTRIBUTES Attrib;
Attrib.nLength = sizeof(SECURITY_ATTRIBUTES);
Attrib.lpSecurityDescriptor = NULL;
Attrib.bInheritHandle = false;
::CreateDirectory("logs", &Attrib);
}
#else
{
mkdir("logs", S_IRWXU | S_IRWXG | S_IRWXO);
}
#endif
OpenLog( (std::string("logs/") + std::string(a_FileName)).c_str() ); OpenLog( (std::string("logs/") + a_FileName).c_str() );
} }
cLog::~cLog() cLog::~cLog()
{ {
CloseLog(); CloseLog();
s_Log = NULL; s_Log = NULL;
} }
cLog* cLog::GetInstance() cLog* cLog::GetInstance()
{ {
if(s_Log) if(s_Log)
@ -51,6 +48,10 @@ cLog* cLog::GetInstance()
return s_Log; return s_Log;
} }
void cLog::CloseLog() void cLog::CloseLog()
{ {
if( m_File ) if( m_File )
@ -58,6 +59,10 @@ void cLog::CloseLog()
m_File = 0; m_File = 0;
} }
void cLog::OpenLog( const char* a_FileName ) void cLog::OpenLog( const char* a_FileName )
{ {
if(m_File) fclose (m_File); if(m_File) fclose (m_File);
@ -68,6 +73,10 @@ void cLog::OpenLog( const char* a_FileName )
#endif #endif
} }
void cLog::ClearLog() void cLog::ClearLog()
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -81,43 +90,43 @@ void cLog::ClearLog()
m_File = 0; m_File = 0;
} }
void cLog::Log(const char* a_Format, va_list argList )
{
char c_Buffer[1024];
if( argList != 0 )
{
vsnprintf_s(c_Buffer, 1024, 1024, a_Format, argList );
} void cLog::Log(const char* a_Format, va_list argList)
else {
{ AString Message;
sprintf_s( c_Buffer, 1024, "%s", a_Format ); AppendVPrintf(Message, a_Format, argList);
}
time_t rawtime; time_t rawtime;
time ( &rawtime ); time ( &rawtime );
#ifdef _WIN32
struct tm timeinfo;
localtime_s( &timeinfo, &rawtime );
#else
struct tm* timeinfo; struct tm* timeinfo;
#ifdef _WIN32
struct tm timeinforeal;
timeinfo = &timeinforeal;
localtime_s(timeinfo, &rawtime );
#else
timeinfo = localtime( &rawtime ); timeinfo = localtime( &rawtime );
#endif #endif
char c_Buffer2[1024];
#ifdef _WIN32 AString Line;
sprintf_s(c_Buffer2, 1024, "[%02d:%02d:%02d] %s\n", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, c_Buffer); Printf(Line, "[%02d:%02d:%02d] %s\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, Message.c_str());
#else if (m_File)
sprintf(c_Buffer2, "[%02d:%02d:%02d] %s\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, c_Buffer); {
#endif fputs(Line.c_str(), m_File);
if(m_File){
fputs(c_Buffer2, m_File);
fflush(m_File); fflush(m_File);
} }
printf("%s", c_Buffer2 ); printf("%s", Line.c_str());
} }
void cLog::Log(const char* a_Format, ...) void cLog::Log(const char* a_Format, ...)
{ {
va_list argList; va_list argList;
@ -126,7 +135,15 @@ void cLog::Log(const char* a_Format, ...)
va_end(argList); va_end(argList);
} }
void cLog::SimpleLog(const char* a_String) void cLog::SimpleLog(const char* a_String)
{ {
Log("%s", a_String ); Log("%s", a_String );
} }

View File

@ -4,19 +4,21 @@
#include "FileDefine.h" #include "FileDefine.h"
#ifndef _WIN32 #ifndef _WIN32
#include <stdarg.h> #include <stdarg.h>
#endif #endif
class cLog { // tolua_export
class cLog
{ // tolua_export
private: private:
FILE* m_File; FILE * m_File;
static cLog* s_Log; static cLog * s_Log;
#ifdef _WIN32
typedef char* va_list;
#endif
public: public:
cLog( const char* a_FileName ); cLog(const AString & a_FileName);
~cLog(); ~cLog();
void Log(const char* a_Format, va_list argList ); void Log(const char* a_Format, va_list argList );
void Log(const char* a_Format, ...); void Log(const char* a_Format, ...);
@ -28,3 +30,7 @@ public:
static cLog* GetInstance(); static cLog* GetInstance();
}; };
//tolua_end //tolua_end

View File

@ -16,17 +16,25 @@ cMCLogger* cMCLogger::GetInstance()
return s_MCLogger; return s_MCLogger;
} }
cMCLogger::cMCLogger() cMCLogger::cMCLogger()
{ {
m_CriticalSection = new cCriticalSection(); m_CriticalSection = new cCriticalSection();
char c_Buffer[128]; AString FileName;
sprintf_s(c_Buffer, 128, "LOG_%d.txt", (int)time(0) ); Printf(FileName, "LOG_%d.txt", (int)time(0) );
m_Log = new cLog(c_Buffer); m_Log = new cLog(FileName);
m_Log->Log("--- Started Log ---"); m_Log->Log("--- Started Log ---");
s_MCLogger = this; s_MCLogger = this;
} }
cMCLogger::cMCLogger( char* a_File ) cMCLogger::cMCLogger( char* a_File )
{ {
m_CriticalSection = new cCriticalSection(); m_CriticalSection = new cCriticalSection();

View File

@ -784,8 +784,8 @@ bool cPlayer::LoadFromDisk()
if( itr->second ) LOGINFO("%s", itr->first.c_str() ); if( itr->second ) LOGINFO("%s", itr->first.c_str() );
} }
char SourceFile[128]; AString SourceFile;
sprintf_s(SourceFile, 128, "players/%s.json", m_pState->PlayerName.c_str() ); Printf(SourceFile, "players/%s.json", m_pState->PlayerName.c_str() );
cFile f; cFile f;
if (!f.Open(SourceFile, cFile::fmRead)) if (!f.Open(SourceFile, cFile::fmRead))
@ -796,8 +796,8 @@ bool cPlayer::LoadFromDisk()
// Get file size // Get file size
long FileSize = f.GetSize(); long FileSize = f.GetSize();
char * buffer = new char[FileSize]; std::auto_ptr<char> buffer(new char[FileSize]);
if (f.Read(buffer, FileSize) != FileSize ) if (f.Read(buffer.get(), FileSize) != FileSize)
{ {
LOGERROR("ERROR READING FROM FILE \"%s\"", SourceFile); LOGERROR("ERROR READING FROM FILE \"%s\"", SourceFile);
return false; return false;
@ -806,12 +806,12 @@ bool cPlayer::LoadFromDisk()
Json::Value root; Json::Value root;
Json::Reader reader; Json::Reader reader;
if( !reader.parse( buffer, root, false ) ) if (!reader.parse(buffer.get(), root, false))
{ {
LOGERROR("ERROR WHILE PARSING JSON FROM FILE %s", SourceFile); LOGERROR("ERROR WHILE PARSING JSON FROM FILE %s", SourceFile);
} }
delete [] buffer; buffer.reset();
Json::Value & JSON_PlayerPosition = root["position"]; Json::Value & JSON_PlayerPosition = root["position"];
if( JSON_PlayerPosition.size() == 3 ) if( JSON_PlayerPosition.size() == 3 )
@ -876,8 +876,8 @@ bool cPlayer::SaveToDisk()
Json::StyledWriter writer; Json::StyledWriter writer;
std::string JsonData = writer.write( root ); std::string JsonData = writer.write( root );
char SourceFile[128]; AString SourceFile;
sprintf_s(SourceFile, 128, "players/%s.json", m_pState->PlayerName.c_str() ); Printf(SourceFile, "players/%s.json", m_pState->PlayerName.c_str() );
cFile f; cFile f;
if (!f.Open(SourceFile, cFile::fmWrite)) if (!f.Open(SourceFile, cFile::fmWrite))

View File

@ -13,15 +13,15 @@ cSemaphore::cSemaphore( unsigned int a_MaxCount, unsigned int a_InitialCount /*
#ifndef _WIN32 #ifndef _WIN32
(void)a_MaxCount; (void)a_MaxCount;
m_Handle = new sem_t; m_Handle = new sem_t;
if( sem_init( (sem_t*)m_Handle, 0, 0 ) ) if (sem_init( (sem_t*)m_Handle, 0, 0))
{ {
LOG("WARNING cSemaphore: Could not create unnamed semaphore, fallback to named."); LOG("WARNING cSemaphore: Could not create unnamed semaphore, fallback to named.");
delete (sem_t*)m_Handle; // named semaphores return their own address delete (sem_t*)m_Handle; // named semaphores return their own address
m_bNamed = true; m_bNamed = true;
char c_Str[32]; AString Name;
sprintf( c_Str, "cSemaphore%p", this ); Printf(Name, "cSemaphore%p", this );
m_Handle = sem_open( c_Str, O_CREAT, 777, a_InitialCount ); m_Handle = sem_open(Name.c_str(), O_CREAT, 777, a_InitialCount);
if( m_Handle == SEM_FAILED ) if( m_Handle == SEM_FAILED )
{ {
LOG("ERROR: Could not create Semaphore. (%i)", errno ); LOG("ERROR: Could not create Semaphore. (%i)", errno );

View File

@ -224,18 +224,18 @@ void cWebAdmin::Request_Handler(webserver::http_request* r)
} }
else else
{ {
char MemUsage[32]; AString MemUsage;
sprintf( MemUsage, "%0.2f", ((double)resource_usage.ru_maxrss / 1024 / 1024) ); Printf(MemUsage, "%0.2f", ((double)resource_usage.ru_maxrss / 1024 / 1024) );
ReplaceString( Template, std::string("{MEM}"), MemUsage ); ReplaceString(Template, std::string("{MEM}"), MemUsage);
} }
#else #else
HANDLE hProcess = GetCurrentProcess(); HANDLE hProcess = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc; PROCESS_MEMORY_COUNTERS pmc;
if( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc) ) ) if( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc) ) )
{ {
char MemUsage[32]; AString MemUsage;
sprintf( MemUsage, "%0.2f", (pmc.WorkingSetSize / 1024.f / 1024.f) ); Printf(MemUsage, "%0.2f", (pmc.WorkingSetSize / 1024.f / 1024.f) );
ReplaceString( Template, std::string("{MEM}"), MemUsage ); ReplaceString( Template, "{MEM}", MemUsage );
} }
#endif #endif
// end mem usage // end mem usage